From 3865a186a7ee5b774f06df8c126afdc93ef76992 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Fri, 8 Jul 2022 22:25:15 -0500 Subject: [PATCH 001/322] Possessor and possessable additions (#619) * possessor-fixup and possessable additions * comment and docstring fixes * fix possessable initialization * split animation flags into it's own header remove unnecessary checks --- dCommon/dCommonVars.h | 1 - dCommon/eAninmationFlags.h | 44 ++++++++ dGame/Entity.cpp | 5 +- dGame/dComponents/PossessableComponent.cpp | 72 ++++++------- dGame/dComponents/PossessableComponent.h | 108 ++++++++++++++----- dGame/dComponents/PossessorComponent.h | 26 +++-- dGame/dComponents/RacingControlComponent.cpp | 1 + dScripts/SGCannon.cpp | 10 +- 8 files changed, 178 insertions(+), 89 deletions(-) create mode 100644 dCommon/eAninmationFlags.h diff --git a/dCommon/dCommonVars.h b/dCommon/dCommonVars.h index 4cbdb61c..e941413b 100644 --- a/dCommon/dCommonVars.h +++ b/dCommon/dCommonVars.h @@ -664,7 +664,6 @@ enum ePlayerFlags { NJ_WU_SHOW_DAILY_CHEST = 2099 }; - //======== FUNC =========== template diff --git a/dCommon/eAninmationFlags.h b/dCommon/eAninmationFlags.h new file mode 100644 index 00000000..09cfde22 --- /dev/null +++ b/dCommon/eAninmationFlags.h @@ -0,0 +1,44 @@ +#pragma once + +#ifndef __EANINMATIONFLAGS__H__ +#define __EANINMATIONFLAGS__H__ + +#include + +enum class eAnimationFlags : uint32_t { + IDLE_INVALID = 0, // made up, for internal use!!! + IDLE_BASIC, + IDLE_SWIM, + IDLE_CARRY, + IDLE_SWORD, + IDLE_HAMMER, + IDLE_SPEAR, + IDLE_PISTOL, + IDLE_BOW, + IDLE_COMBAT, + IDLE_JETPACK, + IDLE_HORSE, + IDLE_SG, + IDLE_ORGAN, + IDLE_SKATEBOARD, + IDLE_DAREDEVIL, + IDLE_SAMURAI, + IDLE_SUMMONER, + IDLE_BUCCANEER, + IDLE_MISC, + IDLE_NINJA, + IDLE_MISC1, + IDLE_MISC2, + IDLE_MISC3, + IDLE_MISC4, + IDLE_MISC5, + IDLE_MISC6, + IDLE_MISC7, + IDLE_MISC8, + IDLE_MISC9, + IDLE_MISC10, + IDLE_MISC11, + IDLE_MISC12 +}; + +#endif //!__EANINMATIONFLAGS__H__ \ No newline at end of file diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index bb7e0335..68277cd8 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -208,8 +208,9 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_ZONE_CONTROL, nullptr)); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_POSSESSABLE) > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_POSSESSABLE, new PossessableComponent(this))); + uint32_t possessableComponentId = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_POSSESSABLE); + if (possessableComponentId > 0) { + m_Components.insert(std::make_pair(COMPONENT_TYPE_POSSESSABLE, new PossessableComponent(this, possessableComponentId))); } if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MODULE_ASSEMBLY) > 0) { diff --git a/dGame/dComponents/PossessableComponent.cpp b/dGame/dComponents/PossessableComponent.cpp index d4fd0d62..1d721466 100644 --- a/dGame/dComponents/PossessableComponent.cpp +++ b/dGame/dComponents/PossessableComponent.cpp @@ -1,51 +1,43 @@ #include "PossessableComponent.h" - #include "PossessorComponent.h" #include "EntityManager.h" +#include "Item.h" -PossessableComponent::PossessableComponent(Entity* parent) : Component(parent) -{ - m_Possessor = LWOOBJID_EMPTY; +PossessableComponent::PossessableComponent(Entity* parent, uint32_t componentId) : Component(parent){ + m_Possessor = LWOOBJID_EMPTY; + + // Get the possession Type from the CDClient + auto query = CDClientDatabase::CreatePreppedStmt("SELECT possessionType, depossessOnHit FROM PossessableComponent WHERE id = ?;"); + + query.bind(1, static_cast(componentId)); + + auto result = query.execQuery(); + + // Should a result not exist for this default to attached visible + if (!result.eof()) { + m_PossessionType = static_cast(result.getIntField(0, 0)); + m_DepossessOnHit = static_cast(result.getIntField(1, 0)); + } else { + m_PossessionType = ePossessionType::ATTACHED_VISIBLE; + m_DepossessOnHit = false; + } + result.finalize(); } -PossessableComponent::~PossessableComponent() -{ - -} +void PossessableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { + outBitStream->Write(m_DirtyPossessable || bIsInitialUpdate); + if (m_DirtyPossessable || bIsInitialUpdate) { + m_DirtyPossessable = false; + outBitStream->Write(m_Possessor != LWOOBJID_EMPTY); + if (m_Possessor != LWOOBJID_EMPTY) outBitStream->Write(m_Possessor); -void PossessableComponent::SetPossessor(LWOOBJID value) -{ - m_Possessor = value; -} + outBitStream->Write(m_AnimationFlag != eAnimationFlags::IDLE_INVALID); + if(m_AnimationFlag != eAnimationFlags::IDLE_INVALID) outBitStream->Write(m_AnimationFlag); -LWOOBJID PossessableComponent::GetPossessor() const -{ - return m_Possessor; -} - -void PossessableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) -{ - outBitStream->Write(m_Possessor != LWOOBJID_EMPTY); - if (m_Possessor != LWOOBJID_EMPTY) - { - outBitStream->Write1(); - outBitStream->Write(m_Possessor); - outBitStream->Write0(); - outBitStream->Write0(); - } -} - -void PossessableComponent::Update(float deltaTime) -{ - + outBitStream->Write(m_ImmediatelyDepossess); + } } void PossessableComponent::OnUse(Entity* originator) { - PossessorComponent* possessorComponent; - if (originator->TryGetComponent(COMPONENT_TYPE_POSSESSOR, possessorComponent)) { - SetPossessor(originator->GetObjectID()); - possessorComponent->SetPossessable(m_Parent->GetObjectID()); - EntityManager::Instance()->SerializeEntity(m_Parent); - EntityManager::Instance()->SerializeEntity(originator); - } -} + // TODO: Implement this +} \ No newline at end of file diff --git a/dGame/dComponents/PossessableComponent.h b/dGame/dComponents/PossessableComponent.h index 744ebfc5..5eefaaf4 100644 --- a/dGame/dComponents/PossessableComponent.h +++ b/dGame/dComponents/PossessableComponent.h @@ -3,44 +3,96 @@ #include "BitStream.h" #include "Entity.h" #include "Component.h" +#include "Item.h" +#include "PossessorComponent.h" +#include "eAninmationFlags.h" /** * Represents an entity that can be controlled by some other entity, generally used by cars to indicate that some * player is controlling it. */ class PossessableComponent : public Component { -public: - static const uint32_t ComponentType = COMPONENT_TYPE_POSSESSABLE; - - PossessableComponent(Entity* parentEntity); - ~PossessableComponent() override; + public: + static const uint32_t ComponentType = COMPONENT_TYPE_POSSESSABLE; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void Update(float deltaTime) override; + PossessableComponent(Entity* parentEntity, uint32_t componentId); - /** - * Sets the possessor of this entity - * @param value the ID of the possessor to set - */ - void SetPossessor(LWOOBJID value); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Returns the possessor of this entity - * @return the possessor of this entitythe - */ - LWOOBJID GetPossessor() const; + /** + * Sets the possessor of this entity + * @param value the ID of the possessor to set + */ + void SetPossessor(LWOOBJID value) { m_Possessor = value; m_DirtyPossessable = true;}; - /** - * Handles an OnUsed event by some other entity, if said entity has a PossessorComponent it becomes the possessor - * of this entity - * @param originator the entity that caused the event to trigger - */ - void OnUse(Entity* originator) override; + /** + * Returns the possessor of this entity + * @return the possessor of this entity + */ + LWOOBJID GetPossessor() const { return m_Possessor; }; -private: + /** + * Sets the animation Flag of the possessable + * @param value the animation flag to set to + */ + void SetAnimationFlag(eAnimationFlags value) { m_AnimationFlag = value; m_DirtyPossessable = true;}; + + /** + * Returns the possession type of this entity + * @return the possession type of this entity + */ + ePossessionType GetPossessionType() const { return m_PossessionType; }; + + /** + * Returns if the entity should deposses on hit + * @return if the entity should deposses on hit + */ + bool GetDepossessOnHit() const { return m_DepossessOnHit; }; + + /** + * Forcibly depossess the entity + */ + void ForceDepossess() { m_ImmediatelyDepossess = true; m_DirtyPossessable = true;}; + + /** + * Handles an OnUsed event by some other entity, if said entity has a Possessor it becomes the possessor + * of this entity + * @param originator the entity that caused the event to trigger + */ + void OnUse(Entity* originator) override; + + private: + + /** + * @brief Whether the possessor is dirty + */ + bool m_DirtyPossessable = true; + + /** + * @brief The possessor of this entity, e.g. the entity that controls this entity + */ + LWOOBJID m_Possessor = LWOOBJID_EMPTY; + + /** + * @brief The type of possesstion to use on this entity + */ + ePossessionType m_PossessionType = ePossessionType::NO_POSSESSION; + + /** + * @brief Should the possessable be dismount on hit + */ + bool m_DepossessOnHit = false; + + /** + * @brief What animaiton flag to use + * + */ + eAnimationFlags m_AnimationFlag = eAnimationFlags::IDLE_INVALID; + + /** + * @brief Should this be immediately depossessed + * + */ + bool m_ImmediatelyDepossess = false; - /** - * The possessor of this entity, e.g. the entity that controls this entity - */ - LWOOBJID m_Possessor; }; diff --git a/dGame/dComponents/PossessorComponent.h b/dGame/dComponents/PossessorComponent.h index f3389274..f202b907 100644 --- a/dGame/dComponents/PossessorComponent.h +++ b/dGame/dComponents/PossessorComponent.h @@ -4,6 +4,14 @@ #include "Entity.h" #include "Component.h" +// possession types +enum class ePossessionType : uint8_t { + NO_POSSESSION = 0, + ATTACHED_VISIBLE, + NOT_ATTACHED_VISIBLE, + NOT_ATTACHED_NOT_VISIBLE, +}; + /** * Represents an entity that can posess other entities. Generally used by players to drive a car. */ @@ -22,34 +30,34 @@ class PossessorComponent : public Component { */ void SetPossessable(LWOOBJID value) { m_Possessable = value; m_DirtyPossesor = true; } - /** - * Sets the possesible type that's currently used, merely used by the shooting gallery if it's 0 - * @param value the possesible type to set - */ - void SetPossessableType(uint8_t value) { m_PossessableType = value; m_DirtyPossesor = true; } - /** * Returns the entity that this entity is currently posessing * @return the entity that this entity is currently posessing */ LWOOBJID GetPossessable() const { return m_Possessable; } + /** + * Sets the possesible type that's currently used, merely used by the shooting gallery if it's 0 + * @param value the possesible type to set + */ + void SetPossessableType(ePossessionType value) { m_PossessableType = value; m_DirtyPossesor = true; } + private: /** * The ID of the entity this entity is possessing (e.g. the ID of a car) */ - LWOOBJID m_Possessable; + LWOOBJID m_Possessable = LWOOBJID_EMPTY; /** * @brief possessable type * */ - uint8_t m_PossessableType; + ePossessionType m_PossessableType = ePossessionType::NO_POSSESSION; /** * @brief if the possessor is dirty * */ - bool m_DirtyPossesor; + bool m_DirtyPossesor = false; }; diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index d8794114..7bea03f6 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -212,6 +212,7 @@ void RacingControlComponent::LoadPlayerVehicle(Entity *player, if (possessorComponent != nullptr) { possessorComponent->SetPossessable(carEntity->GetObjectID()); + possessorComponent->SetPossessableType(ePossessionType::ATTACHED_VISIBLE); // for racing it's always Attached_Visible } // Set the player's current activity as racing. diff --git a/dScripts/SGCannon.cpp b/dScripts/SGCannon.cpp index b1f64b64..ab179226 100644 --- a/dScripts/SGCannon.cpp +++ b/dScripts/SGCannon.cpp @@ -95,14 +95,6 @@ void SGCannon::OnActivityStateChangeRequest(Entity *self, LWOOBJID senderID, int Game::logger->Log("SGCannon", "Shooting gallery component is null\n"); } - auto* possessorComponent = player->GetComponent(); - - /*if (possessorComponent != nullptr) { - possessorComponent->SetPossessable(self->GetObjectID()); - - EntityManager::Instance()->SerializeEntity(player); - }*/ - auto* characterComponent = player->GetComponent(); if (characterComponent != nullptr) { @@ -111,7 +103,7 @@ void SGCannon::OnActivityStateChangeRequest(Entity *self, LWOOBJID senderID, int auto possessor = player->GetComponent(); if(possessor) { possessor->SetPossessable(self->GetObjectID()); - possessor->SetPossessableType(0); + possessor->SetPossessableType(ePossessionType::NO_POSSESSION); } EntityManager::Instance()->SerializeEntity(player); From dddc33607b32e93341c61c723252471af8e18d6b Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Fri, 8 Jul 2022 22:25:44 -0500 Subject: [PATCH 002/322] remove unused code and callbacktimers in testmap (#620) --- dGame/dUtilities/SlashCommandHandler.cpp | 79 ++++++++---------------- 1 file changed, 27 insertions(+), 52 deletions(-) diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 8631f760..ae8e7969 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -1362,13 +1362,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (requestedPlayerToSetLevelOf != "") { ChatPackets::SendSystemMessage( - sysAddr, u"Set " + GeneralUtils::ASCIIToUTF16(requestedPlayerToSetLevelOf) + u"'s level to " + GeneralUtils::to_u16string(requestedLevel) + - u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + + sysAddr, u"Set " + GeneralUtils::ASCIIToUTF16(requestedPlayerToSetLevelOf) + u"'s level to " + GeneralUtils::to_u16string(requestedLevel) + + u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + u". Relog to see changes."); } else { ChatPackets::SendSystemMessage( - sysAddr, u"Set your level to " + GeneralUtils::to_u16string(requestedLevel) + - u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + + sysAddr, u"Set your level to " + GeneralUtils::to_u16string(requestedLevel) + + u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + u". Relog to see changes."); } return; @@ -1518,61 +1518,36 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit const auto objid = entity->GetObjectID(); - if (force || CheckIfAccessibleZone(reqZone)) { // to prevent tomfoolery - bool darwin = true; //Putting this on true, as I'm sick of having to wait 3-4 seconds on a transfer while trying to quickly moderate properties + if (force || CheckIfAccessibleZone(reqZone)) { // to prevent tomfoolery - Character* character = entity->GetCharacter(); - if (character) { - std::string lowerName = character->GetName(); - std::transform(lowerName.begin(), lowerName.end(), lowerName.begin(), ::tolower); - // feel free to add your name to the list - if (lowerName.find("max") != std::string::npos || lowerName.find("darwin") != std::string::npos || lowerName.find("gie") != std::string::npos) { - darwin = true; - } - } + ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, reqZone, cloneId, false, [objid](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { - if (!darwin) { - GameMessages::SendPlayAnimation(entity, u"lup-teleport"); - GameMessages::SendSetStunned(objid, PUSH, user->GetSystemAddress(), - LWOOBJID_EMPTY, true, true, true, true, true, true, true, true - ); - } - - ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, reqZone, cloneId, false, [objid, darwin](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { auto* entity = EntityManager::Instance()->GetEntity(objid); + if (!entity) return; - if (entity == nullptr) { - return; + const auto sysAddr = entity->GetSystemAddress(); + + ChatPackets::SendSystemMessage(sysAddr, u"Transfering map..."); + + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + if (entity->GetCharacter()) { + entity->GetCharacter()->SetZoneID(zoneID); + entity->GetCharacter()->SetZoneInstance(zoneInstance); + entity->GetCharacter()->SetZoneClone(zoneClone); + entity->GetComponent()->SetLastRocketConfig(u""); } - float transferTime = 3.32999992370605f; - if (darwin) transferTime = 0.0f; + entity->GetCharacter()->SaveXMLToDatabase(); - entity->AddCallbackTimer(transferTime, [=] { - const auto sysAddr = entity->GetSystemAddress(); - - ChatPackets::SendSystemMessage(sysAddr, u"Transfering map..."); - - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); - if (entity->GetCharacter()) { - entity->GetCharacter()->SetZoneID(zoneID); - entity->GetCharacter()->SetZoneInstance(zoneInstance); - entity->GetCharacter()->SetZoneClone(zoneClone); - entity->GetComponent()->SetLastRocketConfig(u""); - } - - entity->GetCharacter()->SaveXMLToDatabase(); - - WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); - }); - return; - }); - } else { - std::string msg = "ZoneID not found or allowed: "; - msg.append(args[0]); - ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(msg, msg.size())); - } - } + WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); + return; + }); + } else { + std::string msg = "ZoneID not found or allowed: "; + msg.append(args[0]); + ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(msg, msg.size())); + } + } if (chatCommand == "createprivate" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 3) { From 485de6173aa8f36173a82f7c56ce179269e82167 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 8 Jul 2022 23:07:52 -0700 Subject: [PATCH 003/322] Added caching for behavior parameter table (#621) * Added caching for table Added caching for table Add more caching Update MasterServer.cpp grds Update CDBehaviorParameterTable.cpp Update CDBehaviorParameterTable.h Update CDBehaviorTemplateTable.cpp Update Behavior.cpp Update Behavior.cpp change to map Remove redundant query * Remove include * change to enum * Update Behavior.cpp * Use already cached table * Update Behavior.cpp --- dDatabase/CDClientManager.cpp | 2 +- dDatabase/Tables/CDBehaviorParameterTable.cpp | 84 ++++++---------- dDatabase/Tables/CDBehaviorParameterTable.h | 11 ++- dDatabase/Tables/CDBehaviorTemplateTable.cpp | 15 ++- dDatabase/Tables/CDBehaviorTemplateTable.h | 6 +- dGame/dBehaviors/Behavior.cpp | 99 +++++++------------ dGame/dBehaviors/Behavior.h | 2 +- 7 files changed, 93 insertions(+), 126 deletions(-) diff --git a/dDatabase/CDClientManager.cpp b/dDatabase/CDClientManager.cpp index 7ad852bc..75ada1ea 100644 --- a/dDatabase/CDClientManager.cpp +++ b/dDatabase/CDClientManager.cpp @@ -8,7 +8,7 @@ void CDClientManager::Initialize(void) { tables.insert(std::make_pair("ActivityRewards", new CDActivityRewardsTable())); UNUSED(tables.insert(std::make_pair("Animations", new CDAnimationsTable()))); tables.insert(std::make_pair("BehaviorParameter", new CDBehaviorParameterTable())); - UNUSED(tables.insert(std::make_pair("BehaviorTemplate", new CDBehaviorTemplateTable()))); + tables.insert(std::make_pair("BehaviorTemplate", new CDBehaviorTemplateTable())); tables.insert(std::make_pair("ComponentsRegistry", new CDComponentsRegistryTable())); tables.insert(std::make_pair("CurrencyTable", new CDCurrencyTableTable())); tables.insert(std::make_pair("DestructibleComponent", new CDDestructibleComponentTable())); diff --git a/dDatabase/Tables/CDBehaviorParameterTable.cpp b/dDatabase/Tables/CDBehaviorParameterTable.cpp index 4991ac82..bbbdb2b6 100644 --- a/dDatabase/Tables/CDBehaviorParameterTable.cpp +++ b/dDatabase/Tables/CDBehaviorParameterTable.cpp @@ -3,33 +3,25 @@ //! Constructor CDBehaviorParameterTable::CDBehaviorParameterTable(void) { -#ifdef CDCLIENT_CACHE_ALL auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorParameter"); + size_t hash = 0; while (!tableData.eof()) { + hash = 0; CDBehaviorParameter entry; entry.behaviorID = tableData.getIntField(0, -1); entry.parameterID = tableData.getStringField(1, ""); entry.value = tableData.getFloatField(2, -1.0f); - //Check if we have an entry with this ID: - auto it = m_entries.find(entry.behaviorID); - if (it != m_entries.end()) { - it->second.insert(std::make_pair(entry.parameterID, entry.value)); - } - else { - //Otherwise, insert it: - m_entries.insert(std::make_pair(entry.behaviorID, std::map())); - auto jit = m_entries.find(entry.behaviorID); + GeneralUtils::hash_combine(hash, entry.behaviorID); + GeneralUtils::hash_combine(hash, entry.parameterID); - //Add our value as well: - jit->second.insert(std::make_pair(entry.parameterID, entry.value)); - } + auto it = m_Entries.find(entry.behaviorID); + m_ParametersList.insert(entry.parameterID); + m_Entries.insert(std::make_pair(hash, entry)); tableData.nextRow(); } - tableData.finalize(); -#endif } //! Destructor @@ -40,51 +32,33 @@ std::string CDBehaviorParameterTable::GetName(void) const { return "BehaviorParameter"; } -float CDBehaviorParameterTable::GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue) +CDBehaviorParameter CDBehaviorParameterTable::GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue) { + CDBehaviorParameter returnValue; + returnValue.behaviorID = 0; + returnValue.parameterID = ""; + returnValue.value = defaultValue; + size_t hash = 0; GeneralUtils::hash_combine(hash, behaviorID); GeneralUtils::hash_combine(hash, name); // Search for specific parameter const auto& it = m_Entries.find(hash); - if (it != m_Entries.end()) { - return it->second; - } - - // Check if this behavior has already been checked - const auto& itChecked = m_Entries.find(behaviorID); - if (itChecked != m_Entries.end()) { - return defaultValue; - } - -#ifndef CDCLIENT_CACHE_ALL - auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT parameterID, value FROM BehaviorParameter WHERE behaviorID = ?;"); - query.bind(1, (int) behaviorID); - - auto tableData = query.execQuery(); - - m_Entries.insert_or_assign(behaviorID, 0); - - while (!tableData.eof()) { - const std::string parameterID = tableData.getStringField(0, ""); - const float value = tableData.getFloatField(1, 0); - - size_t parameterHash = 0; - GeneralUtils::hash_combine(parameterHash, behaviorID); - GeneralUtils::hash_combine(parameterHash, parameterID); - - m_Entries.insert_or_assign(parameterHash, value); - - tableData.nextRow(); - } - - const auto& it2 = m_Entries.find(hash); - if (it2 != m_Entries.end()) { - return it2->second; - } -#endif - - return defaultValue; + return it != m_Entries.end() ? it->second : returnValue; +} + +std::map CDBehaviorParameterTable::GetParametersByBehaviorID(uint32_t behaviorID) { + size_t hash; + std::map returnInfo; + for (auto parameterCandidate : m_ParametersList) { + hash = 0; + GeneralUtils::hash_combine(hash, behaviorID); + GeneralUtils::hash_combine(hash, parameterCandidate); + auto infoCandidate = m_Entries.find(hash); + if (infoCandidate != m_Entries.end()) { + returnInfo.insert(std::make_pair(infoCandidate->second.parameterID, infoCandidate->second.value)); + } + } + return returnInfo; } diff --git a/dDatabase/Tables/CDBehaviorParameterTable.h b/dDatabase/Tables/CDBehaviorParameterTable.h index 3d14d66d..17605636 100644 --- a/dDatabase/Tables/CDBehaviorParameterTable.h +++ b/dDatabase/Tables/CDBehaviorParameterTable.h @@ -2,7 +2,8 @@ // Custom Classes #include "CDTable.h" -#include +#include +#include /*! \file CDBehaviorParameterTable.hpp @@ -19,8 +20,8 @@ struct CDBehaviorParameter { //! BehaviorParameter table class CDBehaviorParameterTable : public CDTable { private: - std::map m_Entries; - + std::unordered_map m_Entries; + std::unordered_set m_ParametersList; public: //! Constructor @@ -35,5 +36,7 @@ public: */ std::string GetName(void) const override; - float GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue = 0); + CDBehaviorParameter GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue = 0); + + std::map GetParametersByBehaviorID(uint32_t behaviorID); }; diff --git a/dDatabase/Tables/CDBehaviorTemplateTable.cpp b/dDatabase/Tables/CDBehaviorTemplateTable.cpp index f9830317..c79f4177 100644 --- a/dDatabase/Tables/CDBehaviorTemplateTable.cpp +++ b/dDatabase/Tables/CDBehaviorTemplateTable.cpp @@ -16,7 +16,7 @@ CDBehaviorTemplateTable::CDBehaviorTemplateTable(void) { // Reserve the size this->entries.reserve(size); - + // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorTemplate"); while (!tableData.eof()) { @@ -27,6 +27,7 @@ CDBehaviorTemplateTable::CDBehaviorTemplateTable(void) { entry.effectHandle = tableData.getStringField(3, ""); this->entries.push_back(entry); + this->entriesMappedByBehaviorID.insert(std::make_pair(entry.behaviorID, entry)); tableData.nextRow(); } @@ -55,3 +56,15 @@ std::vector CDBehaviorTemplateTable::Query(std::function CDBehaviorTemplateTable::GetEntries(void) const { return this->entries; } + +const CDBehaviorTemplate CDBehaviorTemplateTable::GetByBehaviorID(uint32_t behaviorID) { + auto entry = this->entriesMappedByBehaviorID.find(behaviorID); + if (entry == this->entriesMappedByBehaviorID.end()) { + CDBehaviorTemplate entryToReturn; + entryToReturn.behaviorID = 0; + entryToReturn.effectHandle = ""; + return entryToReturn; + } else { + return entry->second; + } +} diff --git a/dDatabase/Tables/CDBehaviorTemplateTable.h b/dDatabase/Tables/CDBehaviorTemplateTable.h index a63c2160..36424c12 100644 --- a/dDatabase/Tables/CDBehaviorTemplateTable.h +++ b/dDatabase/Tables/CDBehaviorTemplateTable.h @@ -2,6 +2,7 @@ // Custom Classes #include "CDTable.h" +#include /*! \file CDBehaviorTemplateTable.hpp @@ -21,7 +22,7 @@ struct CDBehaviorTemplate { class CDBehaviorTemplateTable : public CDTable { private: std::vector entries; - + std::unordered_map entriesMappedByBehaviorID; public: //! Constructor @@ -47,5 +48,6 @@ public: \return The entries */ std::vector GetEntries(void) const; - + + const CDBehaviorTemplate GetByBehaviorID(uint32_t behaviorID); }; diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index 7305ed2d..ac1ab7de 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -7,6 +7,7 @@ #include "dLogger.h" #include "BehaviorTemplates.h" #include "BehaviorBranchContext.h" +#include /* * Behavior includes @@ -69,7 +70,7 @@ #include "RenderComponent.h" #include "DestroyableComponent.h" -std::map Behavior::Cache = {}; +std::unordered_map Behavior::Cache = {}; CDBehaviorParameterTable* Behavior::BehaviorParameterTable = nullptr; Behavior* Behavior::GetBehavior(const uint32_t behaviorId) @@ -285,28 +286,22 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) } BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) { - auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT templateID FROM BehaviorTemplate WHERE behaviorID = ?;"); - query.bind(1, (int) behaviorId); + auto behaviorTemplateTable = CDClientManager::Instance()->GetTable("BehaviorTemplate"); - auto result = query.execQuery(); - - // Make sure we do not proceed if we are trying to load an invalid behavior - if (result.eof()) - { - if (behaviorId != 0) - { - Game::logger->Log("Behavior::GetBehaviorTemplate", "Failed to load behavior template with id (%i)!\n", behaviorId); + BehaviorTemplates templateID = BehaviorTemplates::BEHAVIOR_EMPTY; + // Find behavior template by its behavior id. Default to 0. + if (behaviorTemplateTable) { + auto templateEntry = behaviorTemplateTable->GetByBehaviorID(behaviorId); + if (templateEntry.behaviorID == behaviorId) { + templateID = static_cast(templateEntry.templateID); } - - return BehaviorTemplates::BEHAVIOR_EMPTY; } - const auto id = static_cast(result.getIntField(0)); + if (templateID == BehaviorTemplates::BEHAVIOR_EMPTY && behaviorId != 0) { + Game::logger->Log("Behavior", "Failed to load behavior template with id (%i)!\n", behaviorId); + } - result.finalize(); - - return id; + return templateID; } // For use with enemies, to display the correct damage animations on the players @@ -412,6 +407,17 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID Behavior::Behavior(const uint32_t behaviorId) { + auto behaviorTemplateTable = CDClientManager::Instance()->GetTable("BehaviorTemplate"); + + CDBehaviorTemplate templateInDatabase; + + if (behaviorTemplateTable) { + auto templateEntry = behaviorTemplateTable->GetByBehaviorID(behaviorId); + if (templateEntry.behaviorID == behaviorId) { + templateInDatabase = templateEntry; + } + } + this->m_behaviorId = behaviorId; // Add to cache @@ -423,14 +429,8 @@ Behavior::Behavior(const uint32_t behaviorId) this->m_templateId = BehaviorTemplates::BEHAVIOR_EMPTY; } - auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT templateID, effectID, effectHandle FROM BehaviorTemplate WHERE behaviorID = ?;"); - query.bind(1, (int) behaviorId); - - auto result = query.execQuery(); - // Make sure we do not proceed if we are trying to load an invalid behavior - if (result.eof()) + if (templateInDatabase.behaviorID == 0) { Game::logger->Log("Behavior", "Failed to load behavior with id (%i)!\n", behaviorId); @@ -441,34 +441,19 @@ Behavior::Behavior(const uint32_t behaviorId) return; } - this->m_templateId = static_cast(result.getIntField(0)); + this->m_templateId = static_cast(templateInDatabase.templateID); - this->m_effectId = result.getIntField(1); + this->m_effectId = templateInDatabase.effectID; - if (!result.fieldIsNull(2)) - { - const std::string effectHandle = result.getStringField(2); - if (effectHandle == "") - { - this->m_effectHandle = nullptr; - } - else - { - this->m_effectHandle = new std::string(effectHandle); - } - } - else - { - this->m_effectHandle = nullptr; - } - - result.finalize(); + this->m_effectHandle = templateInDatabase.effectHandle != "" ? new std::string(templateInDatabase.effectHandle) : nullptr; } float Behavior::GetFloat(const std::string& name, const float defaultValue) const { - return BehaviorParameterTable->GetEntry(this->m_behaviorId, name, defaultValue); + // Get the behavior parameter entry and return its value. + if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance()->GetTable("BehaviorParameter"); + return BehaviorParameterTable->GetEntry(this->m_behaviorId, name, defaultValue).value; } @@ -498,24 +483,14 @@ Behavior* Behavior::GetAction(float value) const std::map Behavior::GetParameterNames() const { - std::map parameters; - - auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT parameterID, value FROM BehaviorParameter WHERE behaviorID = ?;"); - query.bind(1, (int) this->m_behaviorId); - - auto tableData = query.execQuery(); - - while (!tableData.eof()) - { - parameters.insert_or_assign(tableData.getStringField(0, ""), tableData.getFloatField(1, 0)); - - tableData.nextRow(); + std::map templatesInDatabase; + // Find behavior template by its behavior id. + if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance()->GetTable("BehaviorParameter"); + if (BehaviorParameterTable) { + templatesInDatabase = BehaviorParameterTable->GetParametersByBehaviorID(this->m_behaviorId); } - tableData.finalize(); - - return parameters; + return templatesInDatabase; } void Behavior::Load() diff --git a/dGame/dBehaviors/Behavior.h b/dGame/dBehaviors/Behavior.h index e8700f48..34ba469b 100644 --- a/dGame/dBehaviors/Behavior.h +++ b/dGame/dBehaviors/Behavior.h @@ -19,7 +19,7 @@ public: /* * Static */ - static std::map Cache; + static std::unordered_map Cache; static CDBehaviorParameterTable* BehaviorParameterTable; static Behavior* GetBehavior(uint32_t behaviorId); From 66edf57b025196b31fc89906f3cc616f827ecb0f Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 9 Jul 2022 15:27:20 -0700 Subject: [PATCH 004/322] Wait for world to shutdown (#624) We need to wait for the message that the world has shutdown before shutting it down. --- dMasterServer/MasterServer.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index ac49b1a1..94e0d5b6 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -303,7 +303,6 @@ int main(int argc, char** argv) { if (affirmTimeout == 1000) { instance->Shutdown(); - instance->SetShutdownComplete(true); Game::im->RedirectPendingRequests(instance); } From 325dc5a5711fbd5bbff66024820fb392d9e0a599 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 9 Jul 2022 15:57:45 -0700 Subject: [PATCH 005/322] Revert "Wait for world to shutdown (#624)" (#626) This reverts commit 66edf57b025196b31fc89906f3cc616f827ecb0f. --- dMasterServer/MasterServer.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 94e0d5b6..ac49b1a1 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -303,6 +303,7 @@ int main(int argc, char** argv) { if (affirmTimeout == 1000) { instance->Shutdown(); + instance->SetShutdownComplete(true); Game::im->RedirectPendingRequests(instance); } From 06217ad5e30981a3e8b94093dca2c0bbc4d28b80 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 10 Jul 2022 17:59:07 -0700 Subject: [PATCH 006/322] Address friends list IDs and removal of friends (#628) * Add friends list migration * Change friends to use charID Update friends table to use charID and not LWOOBJID variant. * Fix remove friend Fix remove friend and make the query more readable at a glance. * Add and remove friends in the container Properly add and remove friends in the player container --- dChatServer/ChatPacketHandler.cpp | 145 +++++++++++--------- migrations/dlu/4_friends_list_objectids.sql | 1 + 2 files changed, 84 insertions(+), 62 deletions(-) create mode 100644 migrations/dlu/4_friends_list_objectids.sql diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index 899fd355..82f24ffa 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -21,10 +21,17 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { auto player = playerContainer.GetPlayerData(playerID); if (!player) return; - //Get our friends list from the Db: - auto stmt = Database::CreatePreppedStmt("SELECT * FROM friends WHERE player_id = ? OR friend_id = ?"); - stmt->setUInt64(1, playerID); - stmt->setUInt64(2, playerID); + //Get our friends list from the Db. Using a derived table since the friend of a player can be in either column. + auto stmt = Database::CreatePreppedStmt( + "SELECT fr.requested_player, best_friend, ci.name FROM " + "(SELECT CASE " + "WHEN player_id = ? THEN friend_id " + "WHEN friend_id = ? THEN player_id " + "END AS requested_player, best_friend FROM friends) AS fr " + "JOIN charinfo AS ci ON ci.id = fr.requested_player " + "WHERE fr.requested_player IS NOT NULL;"); + stmt->setUInt(1, static_cast(playerID)); + stmt->setUInt(2, static_cast(playerID)); std::vector friends; @@ -32,27 +39,16 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { while (res->next()) { FriendData fd; fd.isFTP = false; // not a thing in DLU - fd.friendID = res->getInt64(1); - if (fd.friendID == playerID) fd.friendID = res->getUInt64(2); + fd.friendID = res->getUInt(1); + GeneralUtils::SetBit(fd.friendID, static_cast(eObjectBits::OBJECT_BIT_PERSISTENT)); + GeneralUtils::SetBit(fd.friendID, static_cast(eObjectBits::OBJECT_BIT_CHARACTER)); - fd.isBestFriend = res->getInt(3) == 2; //0 = friends, 1 = requested, 2 = bffs - - //We need to find their name as well: - { - auto stmt = Database::CreatePreppedStmt("SELECT name FROM charinfo WHERE id=? limit 1"); - stmt->setInt(1, fd.friendID); - - auto res = stmt->executeQuery(); - while (res->next()) { - fd.friendName = res->getString(1); - } - - delete res; - delete stmt; - } + fd.isBestFriend = res->getInt(2) == 2; //0 = friends, 1 = requested, 2 = bffs + fd.friendName = res->getString(3); //Now check if they're online: auto fr = playerContainer.GetPlayerData(fd.friendID); + Game::logger->Log("ChatPacketHandler", "friend is %llu\n", fd.friendID); if (fr) { fd.isOnline = true; fd.zoneID = fr->zoneID; @@ -69,7 +65,9 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { } delete res; + res = nullptr; delete stmt; + stmt = nullptr; //Now, we need to send the friendlist to the server they came from: CBITSTREAM; @@ -100,8 +98,6 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { std::string playerName = PacketUtils::ReadString(0x14, packet, true); //There's another bool here to determine if it's a best friend request, but we're not handling it right now. - //PacketUtils::SavePacket("FriendRequest.bin", (char*)inStream.GetData(), inStream.GetNumberOfBytesUsed()); - //We need to check to see if the player is actually online or not: auto targetData = playerContainer.GetPlayerData(playerName); if (targetData) { @@ -118,23 +114,46 @@ void ChatPacketHandler::HandleFriendResponse(Packet* packet) { uint8_t responseCode = packet->data[0x14]; std::string friendName = PacketUtils::ReadString(0x15, packet, true); - Game::logger->Log("ChatPacketHandler", "Friend response code: %i\n", responseCode); - - if (responseCode != 0) return; //If we're not accepting the request, end here, do not insert to friends table. - - PacketUtils::SavePacket("HandleFriendResponse.bin", (char*)inStream.GetData(), inStream.GetNumberOfBytesUsed()); - //Now to try and find both of these: auto goonA = playerContainer.GetPlayerData(playerID); auto goonB = playerContainer.GetPlayerData(friendName); if (!goonA || !goonB) return; + if (responseCode != 0) return; //If we're not accepting the request, end here, do not insert to friends table. + + for (auto friendData : goonA->friends) { + if (friendData.friendID == goonB->playerID) return; + } + + for (auto friendData : goonB->friends) { + if (friendData.friendID == goonA->playerID) return; + } + + // Add the goons to their friends list + FriendData goonAData; + goonAData.zoneID = goonA->zoneID; + goonAData.friendID = goonA->playerID; + goonAData.friendName = goonA->playerName; + goonAData.isBestFriend = false; + goonAData.isFTP = false; + goonAData.isOnline = true; + goonB->friends.push_back(goonAData); + + FriendData goonBData; + goonBData.zoneID = goonB->zoneID; + goonBData.friendID = goonB->playerID; + goonBData.friendName = goonB->playerName; + goonBData.isBestFriend = false; + goonBData.isFTP = false; + goonBData.isOnline = true; + goonA->friends.push_back(goonBData); + SendFriendResponse(goonB, goonA, responseCode); SendFriendResponse(goonA, goonB, responseCode); //Do we need to send it to both? I think so so both get the updated friendlist but... idk. - auto stmt = Database::CreatePreppedStmt("INSERT INTO `friends`(`player_id`, `friend_id`, `best_friend`) VALUES (?,?,?)"); - stmt->setUInt64(1, goonA->playerID); - stmt->setUInt64(2, goonB->playerID); + auto stmt = Database::CreatePreppedStmt("INSERT IGNORE INTO `friends` (`player_id`, `friend_id`, `best_friend`) VALUES (?,?,?)"); + stmt->setUInt(1, static_cast(goonA->playerID)); + stmt->setUInt(2, static_cast(goonB->playerID)); stmt->setInt(3, 0); stmt->execute(); delete stmt; @@ -145,50 +164,61 @@ void ChatPacketHandler::HandleRemoveFriend(Packet* packet) { LWOOBJID playerID; inStream.Read(playerID); inStream.Read(playerID); - std::string friendName = PacketUtils::ReadString(16, packet, true); + std::string friendName = PacketUtils::ReadString(0x14, packet, true); //we'll have to query the db here to find the user, since you can delete them while they're offline. //First, we need to find their ID: - auto stmt = Database::CreatePreppedStmt("select id from charinfo where name=? limit 1;"); + auto stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE name=? LIMIT 1;"); stmt->setString(1, friendName.c_str()); LWOOBJID friendID = 0; auto res = stmt->executeQuery(); while (res->next()) { - friendID = res->getUInt64(1); + friendID = res->getUInt(1); } + // Convert friendID to LWOOBJID + GeneralUtils::SetBit(friendID, static_cast(eObjectBits::OBJECT_BIT_PERSISTENT)); + GeneralUtils::SetBit(friendID, static_cast(eObjectBits::OBJECT_BIT_CHARACTER)); + delete res; + res = nullptr; delete stmt; + stmt = nullptr; - //Set our bits to convert to the BIG BOY objectID. - friendID = GeneralUtils::ClearBit(friendID, OBJECT_BIT_CHARACTER); - friendID = GeneralUtils::ClearBit(friendID, OBJECT_BIT_PERSISTENT); - - //YEET: - auto deletestmt = Database::CreatePreppedStmt("DELETE FROM `friends` WHERE player_id=? AND friend_id=? LIMIT 1"); - deletestmt->setUInt64(1, playerID); - deletestmt->setUInt64(2, friendID); + auto deletestmt = Database::CreatePreppedStmt("DELETE FROM friends WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?) LIMIT 1;"); + deletestmt->setUInt(1, static_cast(playerID)); + deletestmt->setUInt(2, static_cast(friendID)); + deletestmt->setUInt(3, static_cast(friendID)); + deletestmt->setUInt(4, static_cast(playerID)); deletestmt->execute(); - delete deletestmt; - //because I'm lazy and they can be reversed: - { - auto deletestmt = Database::CreatePreppedStmt("DELETE FROM `friends` WHERE player_id=? AND friend_id=? LIMIT 1"); - deletestmt->setUInt64(1, friendID); - deletestmt->setUInt64(2, playerID); - deletestmt->execute(); - delete deletestmt; - } + delete deletestmt; + deletestmt = nullptr; //Now, we need to send an update to notify the sender (and possibly, receiver) that their friendship has been ended: auto goonA = playerContainer.GetPlayerData(playerID); if (goonA) { + // Remove the friend from our list of friends + for (auto friendData = goonA->friends.begin(); friendData != goonA->friends.end(); friendData++) { + if ((*friendData).friendID == friendID) { + goonA->friends.erase(friendData); + break; + } + } SendRemoveFriend(goonA, friendName, true); } - + auto goonB = playerContainer.GetPlayerData(friendID); if (!goonB) return; + // Do it again for other person + for (auto friendData = goonB->friends.begin(); friendData != goonB->friends.end(); friendData++) { + if ((*friendData).friendID == playerID) { + goonB->friends.erase(friendData); + break; + } + } + std::string goonAName = GeneralUtils::UTF16ToWTF8(playerContainer.GetName(playerID)); SendRemoveFriend(goonB, goonAName, true); } @@ -217,8 +247,6 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) Game::logger->Log("ChatPacketHandler", "Got a message from (%s) [%d]: %s\n", senderName.c_str(), channel, message.c_str()); - //PacketUtils::SavePacket("chat.bin", reinterpret_cast(packet->data), packet->length); - if (channel != 8) return; auto* team = playerContainer.GetTeam(playerID); @@ -454,8 +482,6 @@ void ChatPacketHandler::HandleTeamKick(Packet* packet) playerContainer.RemoveMember(team, kickedId, false, true, false); } - - //PacketUtils::SavePacket("kick.bin", reinterpret_cast(packet->data), packet->length); } void ChatPacketHandler::HandleTeamPromote(Packet* packet) @@ -481,8 +507,6 @@ void ChatPacketHandler::HandleTeamPromote(Packet* packet) playerContainer.PromoteMember(team, promoted->playerID); } - - //PacketUtils::SavePacket("promote.bin", reinterpret_cast(packet->data), packet->length); } void ChatPacketHandler::HandleTeamLootOption(Packet* packet) @@ -509,8 +533,6 @@ void ChatPacketHandler::HandleTeamLootOption(Packet* packet) playerContainer.UpdateTeamsOnWorld(team, false); } - - //PacketUtils::SavePacket("option.bin", reinterpret_cast(packet->data), packet->length); } void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) @@ -560,7 +582,6 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) const auto memberName = playerContainer.GetName(memberId); - //ChatPacketHandler::SendTeamAddPlayer(otherMember, false, false, false, data->playerID, leaderName, data->zoneID); if (otherMember != nullptr) { ChatPacketHandler::SendTeamSetOffWorldFlag(otherMember, data->playerID, data->zoneID); diff --git a/migrations/dlu/4_friends_list_objectids.sql b/migrations/dlu/4_friends_list_objectids.sql new file mode 100644 index 00000000..efb3a7ae --- /dev/null +++ b/migrations/dlu/4_friends_list_objectids.sql @@ -0,0 +1 @@ +UPDATE friends SET player_id = player_id % 0x100000000, friend_id = friend_id % 0x100000000; \ No newline at end of file From d642de9462127a10bd83885610adebd34f9c69ec Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Sun, 10 Jul 2022 20:40:26 +0100 Subject: [PATCH 007/322] Implement a migration runner --- CMakeLists.txt | 17 ++++- README.md | 2 +- dCommon/GeneralUtils.cpp | 50 +++++++++++++++ dCommon/GeneralUtils.h | 2 + dDatabase/Database.cpp | 45 +++++++------ dDatabase/Database.h | 11 +++- dDatabase/MigrationRunner.cpp | 78 +++++++++++++++++++++++ dDatabase/MigrationRunner.h | 19 ++++++ dMasterServer/MasterServer.cpp | 8 +++ migrations/cdserver/3_plunger_gun_fix.sql | 1 - migrations/dlu/2_reporter_id.sql | 2 +- 11 files changed, 208 insertions(+), 27 deletions(-) create mode 100644 dDatabase/MigrationRunner.cpp create mode 100644 dDatabase/MigrationRunner.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 6cf311d2..5373dfe4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,6 +2,8 @@ cmake_minimum_required(VERSION 3.14) project(Darkflame) include(CTest) +set (CMAKE_CXX_STANDARD 17) + # Read variables from file FILE(READ "${CMAKE_SOURCE_DIR}/CMakeVariables.txt" variables) @@ -88,8 +90,6 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DPROJECT_VERSION=${PROJECT_VERSION}") # Echo the version message(STATUS "Version: ${PROJECT_VERSION}") -set(CMAKE_CXX_STANDARD 17) - if(WIN32) add_compile_definitions(_CRT_SECURE_NO_WARNINGS) endif(WIN32) @@ -138,6 +138,19 @@ configure_file("${CMAKE_SOURCE_DIR}/vanity/INFO.md" "${CMAKE_BINARY_DIR}/vanity/ configure_file("${CMAKE_SOURCE_DIR}/vanity/TESTAMENT.md" "${CMAKE_BINARY_DIR}/vanity/TESTAMENT.md" COPYONLY) configure_file("${CMAKE_SOURCE_DIR}/vanity/NPC.xml" "${CMAKE_BINARY_DIR}/vanity/NPC.xml" COPYONLY) +# Move our migrations for MasterServer to run +file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/migrations/) +file(GLOB SQL_FILES ${CMAKE_SOURCE_DIR}/migrations/dlu/*.sql) +foreach (file ${SQL_FILES}) + get_filename_component(file ${file} NAME) + if (NOT EXISTS ${PROJECT_BINARY_DIR}/migrations/${file}) + configure_file( + ${CMAKE_SOURCE_DIR}/migrations/dlu/${file} ${PROJECT_BINARY_DIR}/migrations/${file} + COPYONLY + ) + endif() +endforeach() + # 3rdparty includes include_directories(${PROJECT_SOURCE_DIR}/thirdparty/raknet/Source/) if(APPLE) diff --git a/README.md b/README.md index 6b82e1b0..d029ed93 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,7 @@ Darkflame Universe utilizes a MySQL/MariaDB database for account and character i Initial setup can vary drastically based on which operating system or distribution you are running; there are instructions out there for most setups, follow those and come back here when you have a database up and running. * Create a database for Darkflame Universe to use -* Run each SQL file in the order at which they appear [here](migrations/dlu/) on the database +* Run the migrations by running `./MasterServer -m` to automatically run them ### Resources diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index b3461e8a..01306226 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -188,3 +188,53 @@ std::u16string GeneralUtils::ReadWString(RakNet::BitStream *inStream) { return string; } + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#include + +std::vector GeneralUtils::GetFileNamesFromFolder(const std::string& folder) +{ + std::vector names; + std::string search_path = folder + "/*.*"; + WIN32_FIND_DATA fd; + HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd); + if (hFind != INVALID_HANDLE_VALUE) { + do { + if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { + names.push_back(fd.cFileName); + } + } while (::FindNextFile(hFind, &fd)); + ::FindClose(hFind); + } + return names; +} +#else +#include +#include +#include +#include +#include +#include + +std::vector GeneralUtils::GetFileNamesFromFolder(const std::string& folder) { + std::vector names; + struct dirent* entry; + DIR* dir = opendir(folder.c_str()); + if (dir == NULL) { + return names; + } + + while ((entry = readdir(dir)) != NULL) { + std::string value(entry->d_name, strlen(entry->d_name)); + if (value == "." || value == "..") { + continue; + } + names.push_back(value); + } + + closedir(dir); + + return names; +} +#endif \ No newline at end of file diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index 58b9e962..4973201e 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -128,6 +128,8 @@ namespace GeneralUtils { std::vector SplitString(const std::string& str, char delimiter); + std::vector GetFileNamesFromFolder(const std::string& folder); + template T Parse(const char* value); diff --git a/dDatabase/Database.cpp b/dDatabase/Database.cpp index ef4faa52..26a45359 100644 --- a/dDatabase/Database.cpp +++ b/dDatabase/Database.cpp @@ -8,6 +8,8 @@ using namespace std; sql::Driver * Database::driver; sql::Connection * Database::con; +sql::Properties Database::props; +std::string Database::database; void Database::Connect(const string& host, const string& database, const string& username, const string& password) { @@ -25,14 +27,26 @@ void Database::Connect(const string& host, const string& database, const string& properties["user"] = szUsername; properties["password"] = szPassword; properties["autoReconnect"] = "true"; - con = driver->connect(properties); - con->setSchema(szDatabase); -} //Connect -void Database::Destroy(std::string source) { + Database::props = properties; + Database::database = database; + + Database::Connect(); +} + +void Database::Connect() { + con = driver->connect(Database::props); + con->setSchema(Database::database); +} + +void Database::Destroy(std::string source, bool log) { if (!con) return; - if (source != "") Game::logger->Log("Database", "Destroying MySQL connection from %s!\n", source.c_str()); - else Game::logger->Log("Database", "Destroying MySQL connection!\n"); + + if (log) { + if (source != "") Game::logger->Log("Database", "Destroying MySQL connection from %s!\n", source.c_str()); + else Game::logger->Log("Database", "Destroying MySQL connection!\n"); + } + con->close(); delete con; } //Destroy @@ -48,13 +62,7 @@ sql::PreparedStatement* Database::CreatePreppedStmt(const std::string& query) { sql::SQLString str(test, size); if (!con) { - //Connect to the MySQL Database - std::string mysql_host = Game::config->GetValue("mysql_host"); - std::string mysql_database = Game::config->GetValue("mysql_database"); - std::string mysql_username = Game::config->GetValue("mysql_username"); - std::string mysql_password = Game::config->GetValue("mysql_password"); - - Connect(mysql_host, mysql_database, mysql_username, mysql_password); + Connect(); Game::logger->Log("Database", "Trying to reconnect to MySQL\n"); } @@ -64,13 +72,7 @@ sql::PreparedStatement* Database::CreatePreppedStmt(const std::string& query) { con = nullptr; - //Connect to the MySQL Database - std::string mysql_host = Game::config->GetValue("mysql_host"); - std::string mysql_database = Game::config->GetValue("mysql_database"); - std::string mysql_username = Game::config->GetValue("mysql_username"); - std::string mysql_password = Game::config->GetValue("mysql_password"); - - Connect(mysql_host, mysql_database, mysql_username, mysql_password); + Connect(); Game::logger->Log("Database", "Trying to reconnect to MySQL from invalid or closed connection\n"); } @@ -79,3 +81,6 @@ sql::PreparedStatement* Database::CreatePreppedStmt(const std::string& query) { return stmt; } //CreatePreppedStmt +void Database::Commit() { + Database::con->commit(); +} \ No newline at end of file diff --git a/dDatabase/Database.h b/dDatabase/Database.h index e972b0ca..ece62a95 100644 --- a/dDatabase/Database.h +++ b/dDatabase/Database.h @@ -13,10 +13,17 @@ class Database { private: static sql::Driver *driver; static sql::Connection *con; - + static sql::Properties props; + static std::string database; public: static void Connect(const std::string& host, const std::string& database, const std::string& username, const std::string& password); - static void Destroy(std::string source=""); + static void Connect(); + static void Destroy(std::string source = "", bool log = true); + static sql::Statement* CreateStmt(); static sql::PreparedStatement* CreatePreppedStmt(const std::string& query); + static void Commit(); + + static std::string GetDatabase() { return database; } + static sql::Properties GetProperties() { return props; } }; diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp new file mode 100644 index 00000000..a058b85e --- /dev/null +++ b/dDatabase/MigrationRunner.cpp @@ -0,0 +1,78 @@ +#include "MigrationRunner.h" + +#include "GeneralUtils.h" + +#include +#include +#include + +void MigrationRunner::RunMigrations() { + auto stmt = Database::CreatePreppedStmt("CREATE TABLE IF NOT EXISTS migration_history (name TEXT NOT NULL, date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP());"); + stmt->executeQuery(); + delete stmt; + + sql::SQLString finalSQL = ""; + Migration checkMigration{}; + + for (const auto& entry : GeneralUtils::GetFileNamesFromFolder("./migrations/")) { + auto migration = LoadMigration(entry); + + if (migration.data.empty()) { + continue; + } + + checkMigration = migration; + + stmt = Database::CreatePreppedStmt("SELECT name FROM migration_history WHERE name = ?;"); + stmt->setString(1, migration.name); + auto res = stmt->executeQuery(); + bool doExit = res->next(); + delete res; + delete stmt; + if (doExit) continue; + + Game::logger->Log("MigrationRunner", "Running migration: " + migration.name + "\n"); + + finalSQL.append(migration.data); + finalSQL.append('\n'); + + stmt = Database::CreatePreppedStmt("INSERT INTO migration_history (name) VALUES (?);"); + stmt->setString(1, entry); + stmt->execute(); + delete stmt; + } + + if (!finalSQL.empty()) { + try { + auto simpleStatement = Database::CreateStmt(); + simpleStatement->execute(finalSQL); + delete simpleStatement; + } + catch (sql::SQLException e) { + Game::logger->Log("MigrationRunner", std::string("Encountered error running migration: ") + e.what() + "\n"); + } + } +} + +Migration MigrationRunner::LoadMigration(std::string path) { + Migration migration{}; + std::ifstream file("./migrations/" + path); + + if (file.is_open()) { + std::hash hash; + + std::string line; + std::string total = ""; + + while (std::getline(file, line)) { + total += line; + } + + file.close(); + + migration.name = path; + migration.data = total; + } + + return migration; +} diff --git a/dDatabase/MigrationRunner.h b/dDatabase/MigrationRunner.h new file mode 100644 index 00000000..343b252d --- /dev/null +++ b/dDatabase/MigrationRunner.h @@ -0,0 +1,19 @@ +#pragma once + +#include "Database.h" + +#include "dCommonVars.h" +#include "Game.h" +#include "dCommonVars.h" +#include "dLogger.h" + +struct Migration { + std::string data; + std::string name; +}; + +class MigrationRunner { +public: + static void RunMigrations(); + static Migration LoadMigration(std::string path); +}; \ No newline at end of file diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index ac49b1a1..1cfd7d4a 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -19,6 +19,7 @@ #include "CDClientDatabase.h" #include "CDClientManager.h" #include "Database.h" +#include "MigrationRunner.h" #include "Diagnostics.h" #include "dCommonVars.h" #include "dConfig.h" @@ -127,6 +128,13 @@ int main(int argc, char** argv) { return EXIT_FAILURE; } + if (argc > 1 && (strcmp(argv[1], "-m") == 0 || strcmp(argv[1], "--migrations") == 0)) { + MigrationRunner::RunMigrations(); + Game::logger->Log("MigrationRunner", "Finished running migrations\n"); + + return EXIT_SUCCESS; + } + //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/migrations/cdserver/3_plunger_gun_fix.sql b/migrations/cdserver/3_plunger_gun_fix.sql index 35654e8b..3d33592e 100644 --- a/migrations/cdserver/3_plunger_gun_fix.sql +++ b/migrations/cdserver/3_plunger_gun_fix.sql @@ -1,2 +1 @@ --- File added April 9th, 2022 UPDATE ItemComponent SET itemType = 5 where id = 7082; diff --git a/migrations/dlu/2_reporter_id.sql b/migrations/dlu/2_reporter_id.sql index 26103342..dc2a9a7e 100644 --- a/migrations/dlu/2_reporter_id.sql +++ b/migrations/dlu/2_reporter_id.sql @@ -1 +1 @@ -ALTER TABLE bug_reports ADD reporter_id INT NOT NULL DEFAULT 0; +ALTER TABLE bug_reports ADD (reporter_id) INT NOT NULL DEFAULT 0; From bfa1f57158f7b16f73f3cdf3702610fe5b7eff93 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Tue, 12 Jul 2022 03:06:54 +0100 Subject: [PATCH 008/322] Improve cpplinq checks On certain Windows header versions defining NOMINMAX doesn't work for some odd reason. --- thirdparty/cpplinq/cpplinq.hpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/thirdparty/cpplinq/cpplinq.hpp b/thirdparty/cpplinq/cpplinq.hpp index d25cde85..ae9169d9 100644 --- a/thirdparty/cpplinq/cpplinq.hpp +++ b/thirdparty/cpplinq/cpplinq.hpp @@ -14,6 +14,8 @@ #ifndef CPPLINQ__HEADER_GUARD # define CPPLINQ__HEADER_GUARD +#undef min +#undef max #define NOMINMAX // ---------------------------------------------------------------------------- From b7497a47e4c0aa6b3605f6b09706a7e06f62d428 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 11 Jul 2022 20:43:09 -0700 Subject: [PATCH 009/322] Lower memory usage of Behavior Parameter Table by 10MB (#627) * Added caching for table Added caching for table Add more caching Update MasterServer.cpp grds Update CDBehaviorParameterTable.cpp Update CDBehaviorParameterTable.h Update CDBehaviorTemplateTable.cpp Update Behavior.cpp Update Behavior.cpp change to map Remove redundant query * Remove include * change to enum * Update Behavior.cpp * Use already cached table * Update Behavior.cpp * Reduce memory usage Reduces the memory usage for the BehaviorParameter table by 10MB in memory. * Update CDBehaviorTemplateTable.cpp --- dDatabase/Tables/CDBehaviorParameterTable.cpp | 16 +++++++++++----- dDatabase/Tables/CDBehaviorParameterTable.h | 6 +++--- dDatabase/Tables/CDBehaviorTemplateTable.cpp | 11 +++++++++-- dDatabase/Tables/CDBehaviorTemplateTable.h | 10 ++++++---- dGame/dBehaviors/Behavior.cpp | 2 +- 5 files changed, 30 insertions(+), 15 deletions(-) diff --git a/dDatabase/Tables/CDBehaviorParameterTable.cpp b/dDatabase/Tables/CDBehaviorParameterTable.cpp index bbbdb2b6..05f39016 100644 --- a/dDatabase/Tables/CDBehaviorParameterTable.cpp +++ b/dDatabase/Tables/CDBehaviorParameterTable.cpp @@ -9,14 +9,20 @@ CDBehaviorParameterTable::CDBehaviorParameterTable(void) { hash = 0; CDBehaviorParameter entry; entry.behaviorID = tableData.getIntField(0, -1); - entry.parameterID = tableData.getStringField(1, ""); + auto candidateStringToAdd = std::string(tableData.getStringField(1, "")); + auto parameter = m_ParametersList.find(candidateStringToAdd); + if (parameter != m_ParametersList.end()) { + entry.parameterID = parameter; + } else { + entry.parameterID = m_ParametersList.insert(candidateStringToAdd).first; + } entry.value = tableData.getFloatField(2, -1.0f); GeneralUtils::hash_combine(hash, entry.behaviorID); - GeneralUtils::hash_combine(hash, entry.parameterID); + GeneralUtils::hash_combine(hash, *entry.parameterID); auto it = m_Entries.find(entry.behaviorID); - m_ParametersList.insert(entry.parameterID); + m_ParametersList.insert(*entry.parameterID); m_Entries.insert(std::make_pair(hash, entry)); tableData.nextRow(); @@ -36,7 +42,7 @@ CDBehaviorParameter CDBehaviorParameterTable::GetEntry(const uint32_t behaviorID { CDBehaviorParameter returnValue; returnValue.behaviorID = 0; - returnValue.parameterID = ""; + returnValue.parameterID = m_ParametersList.end(); returnValue.value = defaultValue; size_t hash = 0; @@ -57,7 +63,7 @@ std::map CDBehaviorParameterTable::GetParametersByBehaviorID GeneralUtils::hash_combine(hash, parameterCandidate); auto infoCandidate = m_Entries.find(hash); if (infoCandidate != m_Entries.end()) { - returnInfo.insert(std::make_pair(infoCandidate->second.parameterID, infoCandidate->second.value)); + returnInfo.insert(std::make_pair(*(infoCandidate->second.parameterID), infoCandidate->second.value)); } } return returnInfo; diff --git a/dDatabase/Tables/CDBehaviorParameterTable.h b/dDatabase/Tables/CDBehaviorParameterTable.h index 17605636..c45d287b 100644 --- a/dDatabase/Tables/CDBehaviorParameterTable.h +++ b/dDatabase/Tables/CDBehaviorParameterTable.h @@ -12,9 +12,9 @@ //! BehaviorParameter Entry Struct struct CDBehaviorParameter { - unsigned int behaviorID; //!< The Behavior ID - std::string parameterID; //!< The Parameter ID - float value; //!< The value of the behavior template + unsigned int behaviorID; //!< The Behavior ID + std::unordered_set::iterator parameterID; //!< The Parameter ID + float value; //!< The value of the behavior template }; //! BehaviorParameter table diff --git a/dDatabase/Tables/CDBehaviorTemplateTable.cpp b/dDatabase/Tables/CDBehaviorTemplateTable.cpp index c79f4177..b832400d 100644 --- a/dDatabase/Tables/CDBehaviorTemplateTable.cpp +++ b/dDatabase/Tables/CDBehaviorTemplateTable.cpp @@ -24,7 +24,13 @@ CDBehaviorTemplateTable::CDBehaviorTemplateTable(void) { entry.behaviorID = tableData.getIntField(0, -1); entry.templateID = tableData.getIntField(1, -1); entry.effectID = tableData.getIntField(2, -1); - entry.effectHandle = tableData.getStringField(3, ""); + auto candidateToAdd = tableData.getStringField(3, ""); + auto parameter = m_EffectHandles.find(candidateToAdd); + if (parameter != m_EffectHandles.end()) { + entry.effectHandle = parameter; + } else { + entry.effectHandle = m_EffectHandles.insert(candidateToAdd).first; + } this->entries.push_back(entry); this->entriesMappedByBehaviorID.insert(std::make_pair(entry.behaviorID, entry)); @@ -62,7 +68,8 @@ const CDBehaviorTemplate CDBehaviorTemplateTable::GetByBehaviorID(uint32_t behav if (entry == this->entriesMappedByBehaviorID.end()) { CDBehaviorTemplate entryToReturn; entryToReturn.behaviorID = 0; - entryToReturn.effectHandle = ""; + entryToReturn.effectHandle = m_EffectHandles.end(); + entryToReturn.effectID = 0; return entryToReturn; } else { return entry->second; diff --git a/dDatabase/Tables/CDBehaviorTemplateTable.h b/dDatabase/Tables/CDBehaviorTemplateTable.h index 36424c12..170da854 100644 --- a/dDatabase/Tables/CDBehaviorTemplateTable.h +++ b/dDatabase/Tables/CDBehaviorTemplateTable.h @@ -3,6 +3,7 @@ // Custom Classes #include "CDTable.h" #include +#include /*! \file CDBehaviorTemplateTable.hpp @@ -11,10 +12,10 @@ //! BehaviorTemplate Entry Struct struct CDBehaviorTemplate { - unsigned int behaviorID; //!< The Behavior ID - unsigned int templateID; //!< The Template ID (LOT) - unsigned int effectID; //!< The Effect ID attached - std::string effectHandle; //!< The effect handle + unsigned int behaviorID; //!< The Behavior ID + unsigned int templateID; //!< The Template ID (LOT) + unsigned int effectID; //!< The Effect ID attached + std::unordered_set::iterator effectHandle; //!< The effect handle }; @@ -23,6 +24,7 @@ class CDBehaviorTemplateTable : public CDTable { private: std::vector entries; std::unordered_map entriesMappedByBehaviorID; + std::unordered_set m_EffectHandles; public: //! Constructor diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index ac1ab7de..a2329f96 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -445,7 +445,7 @@ Behavior::Behavior(const uint32_t behaviorId) this->m_effectId = templateInDatabase.effectID; - this->m_effectHandle = templateInDatabase.effectHandle != "" ? new std::string(templateInDatabase.effectHandle) : nullptr; + this->m_effectHandle = *templateInDatabase.effectHandle != "" ? new std::string(*templateInDatabase.effectHandle) : nullptr; } From 24dbd3944da07590ac6b7508c403fdc5251609af Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 12 Jul 2022 20:36:06 -0700 Subject: [PATCH 010/322] Friends List Overhaul (#630) v103 * Add friends list migration * Change friends to use charID Update friends table to use charID and not LWOOBJID variant. * Fix remove friend Fix remove friend and make the query more readable at a glance. * Add and remove friends in the container Properly add and remove friends in the player container * add enums * Add best friends and basic GM support V1 * Add more features * not online / doesnt exist implementation Implements the not online and invalid character response codes * Address players not being removed Fix an issue where players would not be marked as offline in the friends list due to the message not being sent in all circumstances. Tested changes on 3 clients, switching characters, logging out from character select, switching characters, world transfer and my friends list looked as it was supposed to. * Implement proper friends system Remove debug logs Track count of best friends Add best friends list cap of 5 Add config option and best friend update Add a config option and implement the last missing best friend serialization Added comments and fixed remove best friend bug Added some comments and addressed an issue where removing best friends would not remove them from your internal count of friends. properties and logs fixes whoops, had an issue send reply if already BFFs Send the correct objectID I really need to rename these Fix white space goon * Replace queries with unique ptrs * remove user from player container on deletion Remove the user from the player container when they delete their character. --- CMakeVariables.txt | 2 +- dChatServer/ChatPacketHandler.cpp | 315 +++++++++++++----- dChatServer/ChatPacketHandler.h | 8 +- dChatServer/PlayerContainer.cpp | 2 +- dChatServer/PlayerContainer.h | 1 + dCommon/AddFriendResponseCode.h | 15 + dCommon/AddFriendResponseType.h | 24 ++ dGame/EntityManager.cpp | 2 +- dGame/UserManager.cpp | 14 +- .../dComponents/PropertyEntranceComponent.cpp | 24 +- dGame/dComponents/PropertyEntranceComponent.h | 2 +- dWorldServer/WorldServer.cpp | 17 +- resources/worldconfig.ini | 4 + 13 files changed, 321 insertions(+), 109 deletions(-) create mode 100644 dCommon/AddFriendResponseCode.h create mode 100644 dCommon/AddFriendResponseType.h diff --git a/CMakeVariables.txt b/CMakeVariables.txt index ed0cfce8..db89fef7 100644 --- a/CMakeVariables.txt +++ b/CMakeVariables.txt @@ -1,6 +1,6 @@ PROJECT_VERSION_MAJOR=1 PROJECT_VERSION_MINOR=0 -PROJECT_VERSION_PATCH=2 +PROJECT_VERSION_PATCH=3 # LICENSE LICENSE=AGPL-3.0 # The network version. diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index 82f24ffa..b84c3eef 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -8,6 +8,10 @@ #include "dServer.h" #include "GeneralUtils.h" #include "dLogger.h" +#include "AddFriendResponseCode.h" +#include "AddFriendResponseType.h" +#include "RakString.h" +#include "dConfig.h" extern PlayerContainer playerContainer; @@ -22,20 +26,20 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { if (!player) return; //Get our friends list from the Db. Using a derived table since the friend of a player can be in either column. - auto stmt = Database::CreatePreppedStmt( + std::unique_ptr stmt(Database::CreatePreppedStmt( "SELECT fr.requested_player, best_friend, ci.name FROM " "(SELECT CASE " "WHEN player_id = ? THEN friend_id " "WHEN friend_id = ? THEN player_id " "END AS requested_player, best_friend FROM friends) AS fr " "JOIN charinfo AS ci ON ci.id = fr.requested_player " - "WHERE fr.requested_player IS NOT NULL;"); + "WHERE fr.requested_player IS NOT NULL;")); stmt->setUInt(1, static_cast(playerID)); stmt->setUInt(2, static_cast(playerID)); std::vector friends; - auto res = stmt->executeQuery(); + std::unique_ptr res(stmt->executeQuery()); while (res->next()) { FriendData fd; fd.isFTP = false; // not a thing in DLU @@ -43,18 +47,19 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { GeneralUtils::SetBit(fd.friendID, static_cast(eObjectBits::OBJECT_BIT_PERSISTENT)); GeneralUtils::SetBit(fd.friendID, static_cast(eObjectBits::OBJECT_BIT_CHARACTER)); - fd.isBestFriend = res->getInt(2) == 2; //0 = friends, 1 = requested, 2 = bffs + fd.isBestFriend = res->getInt(2) == 3; //0 = friends, 1 = left_requested, 2 = right_requested, 3 = both_accepted - are now bffs + if (fd.isBestFriend) player->countOfBestFriends+=1; fd.friendName = res->getString(3); //Now check if they're online: auto fr = playerContainer.GetPlayerData(fd.friendID); - Game::logger->Log("ChatPacketHandler", "friend is %llu\n", fd.friendID); + if (fr) { fd.isOnline = true; fd.zoneID = fr->zoneID; //Since this friend is online, we need to update them on the fact that we've just logged in: - SendFriendUpdate(fr, player, 1); + SendFriendUpdate(fr, player, 1, fd.isBestFriend); } else { fd.isOnline = false; @@ -64,11 +69,6 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { friends.push_back(fd); } - delete res; - res = nullptr; - delete stmt; - stmt = nullptr; - //Now, we need to send the friendlist to the server they came from: CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); @@ -91,18 +91,150 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { } void ChatPacketHandler::HandleFriendRequest(Packet* packet) { + auto maxNumberOfBestFriendsAsString = Game::config->GetValue("max_number_of_best_friends"); + // If this config option doesn't exist, default to 5 which is what live used. + auto maxNumberOfBestFriends = maxNumberOfBestFriendsAsString != "" ? std::stoi(maxNumberOfBestFriendsAsString) : 5U; CINSTREAM; - LWOOBJID playerID; - inStream.Read(playerID); - inStream.Read(playerID); - std::string playerName = PacketUtils::ReadString(0x14, packet, true); - //There's another bool here to determine if it's a best friend request, but we're not handling it right now. + LWOOBJID requestorPlayerID; + inStream.Read(requestorPlayerID); + inStream.Read(requestorPlayerID); + uint32_t spacing{}; + inStream.Read(spacing); + std::string playerName = ""; + uint16_t character; + bool noMoreLettersInName = false; - //We need to check to see if the player is actually online or not: - auto targetData = playerContainer.GetPlayerData(playerName); - if (targetData) { - SendFriendRequest(targetData, playerContainer.GetPlayerData(playerID)); + for (uint32_t j = 0; j < 33; j++) { + inStream.Read(character); + if (character == '\0') noMoreLettersInName = true; + if (!noMoreLettersInName) playerName.push_back(static_cast(character)); } + + char isBestFriendRequest{}; + inStream.Read(isBestFriendRequest); + + auto requestor = playerContainer.GetPlayerData(requestorPlayerID); + std::unique_ptr requestee(playerContainer.GetPlayerData(playerName)); + + // Check if player is online first + if (isBestFriendRequest && !requestee) { + for (auto friendDataCandidate : requestor->friends) { + if (friendDataCandidate.friendName == playerName) { + requestee.reset(new PlayerData()); + // Setup the needed info since you can add a best friend offline. + requestee->playerID = friendDataCandidate.friendID; + requestee->playerName = RakNet::RakString(friendDataCandidate.friendName.c_str()); + requestee->zoneID = LWOZONEID(); + + FriendData requesteeFriendData{}; + requesteeFriendData.friendID = requestor->playerID; + requesteeFriendData.friendName = requestor->playerName; + requesteeFriendData.isFTP = false; + requesteeFriendData.isOnline = false; + requesteeFriendData.zoneID = requestor->zoneID; + requestee->friends.push_back(requesteeFriendData); + requestee->sysAddr = UNASSIGNED_SYSTEM_ADDRESS; + break; + } + } + } + + // If at this point we dont have a target, then they arent online and we cant send the request. + // Send the response code that corresponds to what the error is. + if (!requestee) { + std::unique_ptr nameQuery(Database::CreatePreppedStmt("SELECT name from charinfo where name = ?;")); + nameQuery->setString(1, playerName); + std::unique_ptr result(nameQuery->executeQuery()); + + requestee.reset(new PlayerData()); + requestee->playerName = RakNet::RakString(playerName.c_str()); + + SendFriendResponse(requestor, requestee.get(), result->next() ? AddFriendResponseType::NOTONLINE : AddFriendResponseType::INVALIDCHARACTER); + return; + } + + if (isBestFriendRequest) { + std::unique_ptr friendUpdate(Database::CreatePreppedStmt("SELECT * FROM friends WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?) LIMIT 1;")); + friendUpdate->setUInt(1, static_cast(requestorPlayerID)); + friendUpdate->setUInt(2, static_cast(requestee->playerID)); + friendUpdate->setUInt(3, static_cast(requestee->playerID)); + friendUpdate->setUInt(4, static_cast(requestorPlayerID)); + std::unique_ptr result(friendUpdate->executeQuery()); + + LWOOBJID queryPlayerID = LWOOBJID_EMPTY; + LWOOBJID queryFriendID = LWOOBJID_EMPTY; + uint8_t oldBestFriendStatus{}; + uint8_t bestFriendStatus{}; + + if (result->next()) { + // Get the IDs + queryPlayerID = result->getInt(1); + queryFriendID = result->getInt(2); + oldBestFriendStatus = result->getInt(3); + bestFriendStatus = oldBestFriendStatus; + + // Set the bits + GeneralUtils::SetBit(queryPlayerID, static_cast(eObjectBits::OBJECT_BIT_CHARACTER)); + GeneralUtils::SetBit(queryPlayerID, static_cast(eObjectBits::OBJECT_BIT_PERSISTENT)); + GeneralUtils::SetBit(queryFriendID, static_cast(eObjectBits::OBJECT_BIT_CHARACTER)); + GeneralUtils::SetBit(queryFriendID, static_cast(eObjectBits::OBJECT_BIT_PERSISTENT)); + + // Since this player can either be the friend of someone else or be friends with someone else + // their column in the database determines what bit gets set. When the value hits 3, they + // are now best friends with the other player. + if (queryPlayerID == requestorPlayerID) { + bestFriendStatus |= 1ULL << 0; + } else { + bestFriendStatus |= 1ULL << 1; + } + } + + // Only do updates if there was a change in the bff status. + if (oldBestFriendStatus != bestFriendStatus) { + if (requestee->countOfBestFriends >= maxNumberOfBestFriends || requestor->countOfBestFriends >= maxNumberOfBestFriends) { + if (requestee->countOfBestFriends >= maxNumberOfBestFriends) { + SendFriendResponse(requestor, requestee.get(), AddFriendResponseType::THEIRFRIENDLISTFULL, false); + } + if (requestor->countOfBestFriends >= maxNumberOfBestFriends) { + SendFriendResponse(requestor, requestee.get(), AddFriendResponseType::YOURFRIENDSLISTFULL, false); + } + } else { + // Then update the database with this new info. + std::unique_ptr updateQuery(Database::CreatePreppedStmt("UPDATE friends SET best_friend = ? WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?) LIMIT 1;")); + updateQuery->setUInt(1, bestFriendStatus); + updateQuery->setUInt(2, static_cast(requestorPlayerID)); + updateQuery->setUInt(3, static_cast(requestee->playerID)); + updateQuery->setUInt(4, static_cast(requestee->playerID)); + updateQuery->setUInt(5, static_cast(requestorPlayerID)); + updateQuery->executeUpdate(); + // Sent the best friend update here if the value is 3 + if (bestFriendStatus == 3U) { + requestee->countOfBestFriends+=1; + requestor->countOfBestFriends+=1; + if (requestee->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) SendFriendResponse(requestee.get(), requestor, AddFriendResponseType::ACCEPTED, false, true); + if (requestor->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) SendFriendResponse(requestor, requestee.get(), AddFriendResponseType::ACCEPTED, false, true); + for (auto& friendData : requestor->friends) { + if (friendData.friendID == requestee->playerID) { + friendData.isBestFriend = true; + } + } + for (auto& friendData : requestee->friends) { + if (friendData.friendID == requestor->playerID) { + friendData.isBestFriend = true; + } + } + } + } + } else { + if (requestor->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) SendFriendResponse(requestor, requestee.get(), AddFriendResponseType::WAITINGAPPROVAL, true, true); + } + } else { + // Do not send this if we are requesting to be a best friend. + SendFriendRequest(requestee.get(), requestor); + } + + // If the player is actually a player and not a ghost one defined above, release it from being deleted. + if (requestee->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) requestee.release(); } void ChatPacketHandler::HandleFriendResponse(Packet* packet) { @@ -110,53 +242,75 @@ void ChatPacketHandler::HandleFriendResponse(Packet* packet) { LWOOBJID playerID; inStream.Read(playerID); inStream.Read(playerID); - - uint8_t responseCode = packet->data[0x14]; + + AddFriendResponseCode clientResponseCode = static_cast(packet->data[0x14]); std::string friendName = PacketUtils::ReadString(0x15, packet, true); //Now to try and find both of these: - auto goonA = playerContainer.GetPlayerData(playerID); - auto goonB = playerContainer.GetPlayerData(friendName); - if (!goonA || !goonB) return; + auto requestor = playerContainer.GetPlayerData(playerID); + auto requestee = playerContainer.GetPlayerData(friendName); + if (!requestor || !requestee) return; - if (responseCode != 0) return; //If we're not accepting the request, end here, do not insert to friends table. - - for (auto friendData : goonA->friends) { - if (friendData.friendID == goonB->playerID) return; + AddFriendResponseType serverResponseCode{}; + uint8_t isAlreadyBestFriends = 0U; + // We need to convert this response code to one we can actually send back to the client. + switch (clientResponseCode) { + case AddFriendResponseCode::ACCEPTED: + serverResponseCode = AddFriendResponseType::ACCEPTED; + break; + case AddFriendResponseCode::BUSY: + serverResponseCode = AddFriendResponseType::BUSY; + break; + case AddFriendResponseCode::CANCELLED: + serverResponseCode = AddFriendResponseType::CANCELLED; + break; + case AddFriendResponseCode::REJECTED: + serverResponseCode = AddFriendResponseType::DECLINED; + break; } - for (auto friendData : goonB->friends) { - if (friendData.friendID == goonA->playerID) return; + // Now that we have handled the base cases, we need to check the other cases. + if (serverResponseCode == AddFriendResponseType::ACCEPTED) { + for (auto friendData : requestor->friends) { + if (friendData.friendID == requestee->playerID) { + serverResponseCode = AddFriendResponseType::ALREADYFRIEND; + if (friendData.isBestFriend) { + isAlreadyBestFriends = 1U; + } + } + } } - // Add the goons to their friends list - FriendData goonAData; - goonAData.zoneID = goonA->zoneID; - goonAData.friendID = goonA->playerID; - goonAData.friendName = goonA->playerName; - goonAData.isBestFriend = false; - goonAData.isFTP = false; - goonAData.isOnline = true; - goonB->friends.push_back(goonAData); + // This message is NOT sent for best friends and is handled differently for those requests. + if (serverResponseCode == AddFriendResponseType::ACCEPTED) { + // Add the each player to the others friend list. + FriendData requestorData; + requestorData.zoneID = requestor->zoneID; + requestorData.friendID = requestor->playerID; + requestorData.friendName = requestor->playerName; + requestorData.isBestFriend = false; + requestorData.isFTP = false; + requestorData.isOnline = true; + requestee->friends.push_back(requestorData); - FriendData goonBData; - goonBData.zoneID = goonB->zoneID; - goonBData.friendID = goonB->playerID; - goonBData.friendName = goonB->playerName; - goonBData.isBestFriend = false; - goonBData.isFTP = false; - goonBData.isOnline = true; - goonA->friends.push_back(goonBData); + FriendData requesteeData; + requesteeData.zoneID = requestee->zoneID; + requesteeData.friendID = requestee->playerID; + requesteeData.friendName = requestee->playerName; + requesteeData.isBestFriend = false; + requesteeData.isFTP = false; + requesteeData.isOnline = true; + requestor->friends.push_back(requesteeData); + + std::unique_ptr statement(Database::CreatePreppedStmt("INSERT IGNORE INTO `friends` (`player_id`, `friend_id`, `best_friend`) VALUES (?,?,?);")); + statement->setUInt(1, static_cast(requestor->playerID)); + statement->setUInt(2, static_cast(requestee->playerID)); + statement->setInt(3, 0); + statement->execute(); + } - SendFriendResponse(goonB, goonA, responseCode); - SendFriendResponse(goonA, goonB, responseCode); //Do we need to send it to both? I think so so both get the updated friendlist but... idk. - - auto stmt = Database::CreatePreppedStmt("INSERT IGNORE INTO `friends` (`player_id`, `friend_id`, `best_friend`) VALUES (?,?,?)"); - stmt->setUInt(1, static_cast(goonA->playerID)); - stmt->setUInt(2, static_cast(goonB->playerID)); - stmt->setInt(3, 0); - stmt->execute(); - delete stmt; + if (serverResponseCode != AddFriendResponseType::DECLINED) SendFriendResponse(requestor, requestee, serverResponseCode, isAlreadyBestFriends); + if (serverResponseCode != AddFriendResponseType::ALREADYFRIEND) SendFriendResponse(requestee, requestor, serverResponseCode, isAlreadyBestFriends); } void ChatPacketHandler::HandleRemoveFriend(Packet* packet) { @@ -168,11 +322,11 @@ void ChatPacketHandler::HandleRemoveFriend(Packet* packet) { //we'll have to query the db here to find the user, since you can delete them while they're offline. //First, we need to find their ID: - auto stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE name=? LIMIT 1;"); + std::unique_ptr stmt(Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE name=? LIMIT 1;")); stmt->setString(1, friendName.c_str()); LWOOBJID friendID = 0; - auto res = stmt->executeQuery(); + std::unique_ptr res(stmt->executeQuery()); while (res->next()) { friendID = res->getUInt(1); } @@ -181,27 +335,20 @@ void ChatPacketHandler::HandleRemoveFriend(Packet* packet) { GeneralUtils::SetBit(friendID, static_cast(eObjectBits::OBJECT_BIT_PERSISTENT)); GeneralUtils::SetBit(friendID, static_cast(eObjectBits::OBJECT_BIT_CHARACTER)); - delete res; - res = nullptr; - delete stmt; - stmt = nullptr; - - auto deletestmt = Database::CreatePreppedStmt("DELETE FROM friends WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?) LIMIT 1;"); + std::unique_ptr deletestmt(Database::CreatePreppedStmt("DELETE FROM friends WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?) LIMIT 1;")); deletestmt->setUInt(1, static_cast(playerID)); deletestmt->setUInt(2, static_cast(friendID)); deletestmt->setUInt(3, static_cast(friendID)); deletestmt->setUInt(4, static_cast(playerID)); deletestmt->execute(); - delete deletestmt; - deletestmt = nullptr; - //Now, we need to send an update to notify the sender (and possibly, receiver) that their friendship has been ended: auto goonA = playerContainer.GetPlayerData(playerID); if (goonA) { // Remove the friend from our list of friends for (auto friendData = goonA->friends.begin(); friendData != goonA->friends.end(); friendData++) { if ((*friendData).friendID == friendID) { + if ((*friendData).isBestFriend) --goonA->countOfBestFriends; goonA->friends.erase(friendData); break; } @@ -214,6 +361,7 @@ void ChatPacketHandler::HandleRemoveFriend(Packet* packet) { // Do it again for other person for (auto friendData = goonB->friends.begin(); friendData != goonB->friends.end(); friendData++) { if ((*friendData).friendID == playerID) { + if ((*friendData).isBestFriend) --goonB->countOfBestFriends; goonB->friends.erase(friendData); break; } @@ -766,7 +914,7 @@ void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i SEND_PACKET; } -void ChatPacketHandler::SendFriendUpdate(PlayerData* friendData, PlayerData* playerData, uint8_t notifyType) { +void ChatPacketHandler::SendFriendUpdate(PlayerData* friendData, PlayerData* playerData, uint8_t notifyType, uint8_t isBestFriend) { /*chat notification is displayed if log in / out and friend is updated in friends list [u8] - update type Update types @@ -804,19 +952,20 @@ void ChatPacketHandler::SendFriendUpdate(PlayerData* friendData, PlayerData* pla bitStream.Write(playerData->zoneID.GetCloneID()); } - bitStream.Write(0); //isBFF + bitStream.Write(isBestFriend); //isBFF bitStream.Write(0); //isFTP SystemAddress sysAddr = friendData->sysAddr; SEND_PACKET; } -void ChatPacketHandler::SendFriendRequest(PlayerData* receiver, PlayerData* sender, bool isBFFReq) { +void ChatPacketHandler::SendFriendRequest(PlayerData* receiver, PlayerData* sender) { if (!receiver || !sender) return; //Make sure people aren't requesting people that they're already friends with: for (auto fr : receiver->friends) { if (fr.friendID == sender->playerID) { + SendFriendResponse(sender, receiver, AddFriendResponseType::ALREADYFRIEND, fr.isBestFriend); return; //we have this player as a friend, yeet this function so it doesn't send another request. } } @@ -828,29 +977,33 @@ void ChatPacketHandler::SendFriendRequest(PlayerData* receiver, PlayerData* send //portion that will get routed: PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_ADD_FRIEND_REQUEST); PacketUtils::WritePacketWString(sender->playerName.C_String(), 33, &bitStream); - bitStream.Write(0); + bitStream.Write(0); // This is a BFF flag however this is unused in live and does not have an implementation client side. SystemAddress sysAddr = receiver->sysAddr; SEND_PACKET; } -void ChatPacketHandler::SendFriendResponse(PlayerData* receiver, PlayerData* sender, uint8_t responseCode) { +void ChatPacketHandler::SendFriendResponse(PlayerData* receiver, PlayerData* sender, AddFriendResponseType responseCode, uint8_t isBestFriendsAlready, uint8_t isBestFriendRequest) { if (!receiver || !sender) return; CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); - //portion that will get routed: + // Portion that will get routed: PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_ADD_FRIEND_RESPONSE); - bitStream.Write(responseCode); - bitStream.Write(1); //isOnline + bitStream.Write(responseCode); + // For all requests besides accepted, write a flag that says whether or not we are already best friends with the receiver. + bitStream.Write(responseCode != AddFriendResponseType::ACCEPTED ? isBestFriendsAlready : sender->sysAddr != UNASSIGNED_SYSTEM_ADDRESS); + // Then write the player name PacketUtils::WritePacketWString(sender->playerName.C_String(), 33, &bitStream); - bitStream.Write(sender->playerID); - bitStream.Write(sender->zoneID); - bitStream.Write(0); //isBFF - bitStream.Write(0); //isFTP - + // Then if this is an acceptance code, write the following extra info. + if (responseCode == AddFriendResponseType::ACCEPTED) { + bitStream.Write(sender->playerID); + bitStream.Write(sender->zoneID); + bitStream.Write(isBestFriendRequest); //isBFF + bitStream.Write(0); //isFTP + } SystemAddress sysAddr = receiver->sysAddr; SEND_PACKET; } diff --git a/dChatServer/ChatPacketHandler.h b/dChatServer/ChatPacketHandler.h index e38a65c1..fffd1ca4 100644 --- a/dChatServer/ChatPacketHandler.h +++ b/dChatServer/ChatPacketHandler.h @@ -4,6 +4,7 @@ #include "BitStream.h" struct PlayerData; +enum class AddFriendResponseType : uint8_t; namespace ChatPacketHandler { void HandleFriendlistRequest(Packet* packet); @@ -31,10 +32,9 @@ namespace ChatPacketHandler { void SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i64PlayerID, LWOZONEID zoneID); //FriendData is the player we're SENDING this stuff to. Player is the friend that changed state. - void SendFriendUpdate(PlayerData* friendData, PlayerData* playerData, uint8_t notifyType); + void SendFriendUpdate(PlayerData* friendData, PlayerData* playerData, uint8_t notifyType, uint8_t isBestFriend); - void SendFriendRequest(PlayerData* receiver, PlayerData* sender, bool isBFFReq = false); - void SendFriendResponse(PlayerData* receiver, PlayerData* sender, uint8_t responseCode = 3); + void SendFriendRequest(PlayerData* receiver, PlayerData* sender); + void SendFriendResponse(PlayerData* receiver, PlayerData* sender, AddFriendResponseType responseCode, uint8_t isBestFriendsAlready = 0U, uint8_t isBestFriendRequest = 0U); void SendRemoveFriend(PlayerData* receiver, std::string& personToRemove, bool isSuccessful); }; - diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index d261b32f..b40e8386 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -59,7 +59,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { //if (!fr.isOnline) continue; auto fd = this->GetPlayerData(fr.friendID); - if (fd) ChatPacketHandler::SendFriendUpdate(fd, player, 0); + if (fd) ChatPacketHandler::SendFriendUpdate(fd, player, 0, fr.isBestFriend); } auto* team = GetTeam(playerID); diff --git a/dChatServer/PlayerContainer.h b/dChatServer/PlayerContainer.h index dc78d3b0..b1e1defd 100644 --- a/dChatServer/PlayerContainer.h +++ b/dChatServer/PlayerContainer.h @@ -14,6 +14,7 @@ struct PlayerData { LWOZONEID zoneID; std::vector friends; time_t muteExpire; + uint8_t countOfBestFriends = 0; }; struct TeamData { diff --git a/dCommon/AddFriendResponseCode.h b/dCommon/AddFriendResponseCode.h new file mode 100644 index 00000000..bb2faff7 --- /dev/null +++ b/dCommon/AddFriendResponseCode.h @@ -0,0 +1,15 @@ +#pragma once + +#ifndef __ADDFRIENDRESPONSECODE__H__ +#define __ADDFRIENDRESPONSECODE__H__ + +#include + +enum class AddFriendResponseCode : uint8_t { + ACCEPTED = 0, + REJECTED, + BUSY, + CANCELLED +}; + +#endif //!__ADDFRIENDRESPONSECODE__H__ diff --git a/dCommon/AddFriendResponseType.h b/dCommon/AddFriendResponseType.h new file mode 100644 index 00000000..305796e8 --- /dev/null +++ b/dCommon/AddFriendResponseType.h @@ -0,0 +1,24 @@ +#pragma once + +#ifndef __ADDFRIENDRESPONSETYPE__H__ +#define __ADDFRIENDRESPONSETYPE__H__ + +#include + +enum class AddFriendResponseType : uint8_t { + ACCEPTED = 0, + ALREADYFRIEND, + INVALIDCHARACTER, + GENERALERROR, + YOURFRIENDSLISTFULL, + THEIRFRIENDLISTFULL, + DECLINED, + BUSY, + NOTONLINE, + WAITINGAPPROVAL, + MYTHRAN, + CANCELLED, + FRIENDISFREETRIAL +}; + +#endif //!__ADDFRIENDRESPONSETYPE__H__ diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index db60a1d1..da0cf685 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -401,7 +401,7 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr Game::server->Send(&stream, sysAddr, false); } - PacketUtils::SavePacket("[24]_"+std::to_string(entity->GetObjectID()) + "_" + std::to_string(m_SerializationCounter) + ".bin", (char*)stream.GetData(), stream.GetNumberOfBytesUsed()); + // PacketUtils::SavePacket("[24]_"+std::to_string(entity->GetObjectID()) + "_" + std::to_string(m_SerializationCounter) + ".bin", (char*)stream.GetData(), stream.GetNumberOfBytesUsed()); if (entity->IsPlayer()) { diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index 1d14cb0a..3956942a 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -369,10 +369,8 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) } LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); - objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_CHARACTER); - objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_PERSISTENT); - - uint32_t charID = static_cast(objectID); + uint32_t charID = static_cast(objectID); + Game::logger->Log("UserManager", "Received char delete req for ID: %llu (%u)\n", objectID, charID); //Check if this user has this character: @@ -402,10 +400,14 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) } { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("DELETE FROM friends WHERE player_id=? OR friend_id=?;"); - stmt->setUInt64(1, charID); - stmt->setUInt64(2, charID); + stmt->setUInt(1, charID); + stmt->setUInt(2, charID); stmt->execute(); delete stmt; + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); + bitStream.Write(objectID); + Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); } { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("DELETE FROM leaderboard WHERE character_id=?;"); diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index 1d631e88..87e0c7ed 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -102,7 +102,7 @@ PropertySelectQueryProperty PropertyEntranceComponent::SetPropertyValues(Propert return property; } -std::string PropertyEntranceComponent::BuildQuery(Entity* entity, int32_t sortMethod, std::string customQuery, bool wantLimits) { +std::string PropertyEntranceComponent::BuildQuery(Entity* entity, int32_t sortMethod, Character* character, std::string customQuery, bool wantLimits) { std::string base; if (customQuery == "") { base = baseQueryForProperties; @@ -115,15 +115,13 @@ std::string PropertyEntranceComponent::BuildQuery(Entity* entity, int32_t sortMe auto friendsListQuery = Database::CreatePreppedStmt("SELECT * FROM (SELECT CASE WHEN player_id = ? THEN friend_id WHEN friend_id = ? THEN player_id END AS requested_player FROM friends ) AS fr WHERE requested_player IS NOT NULL ORDER BY requested_player DESC;"); - friendsListQuery->setInt64(1, entity->GetObjectID()); - friendsListQuery->setInt64(2, entity->GetObjectID()); + friendsListQuery->setUInt(1, character->GetID()); + friendsListQuery->setUInt(2, character->GetID()); auto friendsListQueryResult = friendsListQuery->executeQuery(); while (friendsListQueryResult->next()) { - auto playerIDToConvert = friendsListQueryResult->getInt64(1); - playerIDToConvert = GeneralUtils::ClearBit(playerIDToConvert, OBJECT_BIT_CHARACTER); - playerIDToConvert = GeneralUtils::ClearBit(playerIDToConvert, OBJECT_BIT_PERSISTENT); + auto playerIDToConvert = friendsListQueryResult->getInt(1); friendsList = friendsList + std::to_string(playerIDToConvert) + ","; } // Replace trailing comma with the closing parenthesis. @@ -193,7 +191,7 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl entries.push_back(playerEntry); - const auto query = BuildQuery(entity, sortMethod); + const auto query = BuildQuery(entity, sortMethod, character); auto propertyLookup = Database::CreatePreppedStmt(query); @@ -262,17 +260,17 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl // Query to get friend and best friend fields auto friendCheck = Database::CreatePreppedStmt("SELECT best_friend FROM friends WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?)"); - friendCheck->setInt64(1, entity->GetObjectID()); - friendCheck->setInt64(2, ownerObjId); - friendCheck->setInt64(3, ownerObjId); - friendCheck->setInt64(4, entity->GetObjectID()); + friendCheck->setUInt(1, character->GetID()); + friendCheck->setUInt(2, ownerObjId); + friendCheck->setUInt(3, ownerObjId); + friendCheck->setUInt(4, character->GetID()); auto friendResult = friendCheck->executeQuery(); // If we got a result than the two players are friends. if (friendResult->next()) { isFriend = true; - if (friendResult->getInt(1) == 2) { + if (friendResult->getInt(1) == 3) { isBestFriend = true; } } @@ -326,7 +324,7 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl // Query here is to figure out whether or not to display the button to go to the next page or not. int32_t numberOfProperties = 0; - auto buttonQuery = BuildQuery(entity, sortMethod, "SELECT COUNT(*) FROM properties as p JOIN charinfo as ci ON ci.prop_clone_id = p.clone_id where p.zone_id = ? AND (p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ?) AND p.privacy_option >= ? ", false); + auto buttonQuery = BuildQuery(entity, sortMethod, character, "SELECT COUNT(*) FROM properties as p JOIN charinfo as ci ON ci.prop_clone_id = p.clone_id where p.zone_id = ? AND (p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ?) AND p.privacy_option >= ? ", false); auto propertiesLeft = Database::CreatePreppedStmt(buttonQuery); propertiesLeft->setUInt(1, this->m_MapID); diff --git a/dGame/dComponents/PropertyEntranceComponent.h b/dGame/dComponents/PropertyEntranceComponent.h index a3be38a6..fe583e92 100644 --- a/dGame/dComponents/PropertyEntranceComponent.h +++ b/dGame/dComponents/PropertyEntranceComponent.h @@ -60,7 +60,7 @@ class PropertyEntranceComponent : public Component { PropertySelectQueryProperty SetPropertyValues(PropertySelectQueryProperty property, LWOCLONEID cloneId = LWOCLONEID_INVALID, std::string ownerName = "", std::string propertyName = "", std::string propertyDescription = "", float reputation = 0, bool isBFF = false, bool isFriend = false, bool isModeratorApproved = false, bool isAlt = false, bool isOwned = false, uint32_t privacyOption = 0, uint32_t timeLastUpdated = 0, float performanceCost = 0.0f); - std::string BuildQuery(Entity* entity, int32_t sortMethod, std::string customQuery = "", bool wantLimits = true); + std::string BuildQuery(Entity* entity, int32_t sortMethod, Character* character, std::string customQuery = "", bool wantLimits = true); private: /** diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 4f1ec400..330263ed 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -669,10 +669,12 @@ void HandlePacket(Packet* packet) { Game::logger->Log("WorldServer", "Deleting player %llu\n", entity->GetObjectID()); EntityManager::Instance()->DestroyEntity(entity); + } + { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); - bitStream.Write(c->GetObjectID()); + bitStream.Write(user->GetLoggedInChar()); Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); } @@ -930,6 +932,19 @@ void HandlePacket(Packet* packet) { playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_CHARACTER); playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_PERSISTENT); + auto user = UserManager::Instance()->GetUser(packet->systemAddress); + + if (user) { + auto lastCharacter = user->GetLoggedInChar(); + // This means we swapped characters and we need to remove the previous player from the container. + if (static_cast(lastCharacter) != playerID) { + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); + bitStream.Write(lastCharacter); + Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); + } + } + UserManager::Instance()->LoginCharacter(packet->systemAddress, static_cast(playerID)); break; } diff --git a/resources/worldconfig.ini b/resources/worldconfig.ini index a665f059..931da28c 100644 --- a/resources/worldconfig.ini +++ b/resources/worldconfig.ini @@ -60,3 +60,7 @@ classic_survival_scoring=0 # If this value is 1, pets will consume imagination as they did in live. if 0 they will not consume imagination at all. pets_take_imagination=1 + +# If you would like to increase the maximum number of best friends a player can have on the server +# Change the value below to what you would like this to be (5 is live accurate) +max_number_of_best_friends=5 \ No newline at end of file From ccb9f7c499a4ea3b054e5b172b5bfc39c0bb7b60 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 12 Jul 2022 20:45:25 -0700 Subject: [PATCH 011/322] Move instruction for database Move the instruction for running the MasterServer migration down to where the command will actually work as well as use a more syntactically correct statement --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index d029ed93..5781c7b8 100644 --- a/README.md +++ b/README.md @@ -152,13 +152,6 @@ now follow the build section for your system ## Setting up the environment -### Database -Darkflame Universe utilizes a MySQL/MariaDB database for account and character information. - -Initial setup can vary drastically based on which operating system or distribution you are running; there are instructions out there for most setups, follow those and come back here when you have a database up and running. -* Create a database for Darkflame Universe to use -* Run the migrations by running `./MasterServer -m` to automatically run them - ### Resources **LEGO® Universe 1.10.64** @@ -202,6 +195,13 @@ certutil -hashfile SHA256 * Move and rename `cdclient.sqlite` into `build/res/CDServer.sqlite` * Run each SQL file in the order at which they appear [here](migrations/cdserver/) on the SQLite database +### Database +Darkflame Universe utilizes a MySQL/MariaDB database for account and character information. + +Initial setup can vary drastically based on which operating system or distribution you are running; there are instructions out there for most setups, follow those and come back here when you have a database up and running. +* Create a database for Darkflame Universe to use +* Use the command `./MasterServer -m` to automatically run them. + **Configuration** After the server has been built there should be four `ini` files in the build director: `authconfig.ini`, `chatconfig.ini`, `masterconfig.ini`, and `worldconfig.ini`. Go through them and fill in the database credentials and configure other settings if necessary. From 9ba297dd2e2a6814646fa755ebaac780d60f6a0e Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 13 Jul 2022 09:10:02 -0700 Subject: [PATCH 012/322] Add code to complete hidden property mission (#641) --- dScripts/BasePropertyServer.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/dScripts/BasePropertyServer.cpp b/dScripts/BasePropertyServer.cpp index e7a95844..ce36caa9 100644 --- a/dScripts/BasePropertyServer.cpp +++ b/dScripts/BasePropertyServer.cpp @@ -169,11 +169,10 @@ void BasePropertyServer::BaseZonePropertyRented(Entity* self, Entity* player) co EntityManager::Instance()->DestructEntity(plaque); } - if (self->GetVar(brickLinkMissionIDFlag) != 0) { - auto plaques = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(PropertyPlaqueGroup)); - for (auto* plaque : plaques) { - EntityManager::Instance()->DestructEntity(plaque); - } + auto brickLinkMissionID = self->GetVar(brickLinkMissionIDFlag); + if (brickLinkMissionID != 0) { + auto missionComponent = player->GetComponent(); + if (missionComponent) missionComponent->CompleteMission(brickLinkMissionID, true); } ActivateSpawner(self->GetVar(PropObjsSpawner)); From 3d46d703b2c10cd8673f518a44054753db7723dc Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 13 Jul 2022 09:11:24 -0700 Subject: [PATCH 013/322] Remove memory leak in player container and warning in Behavior (#640) * Add friends list migration * Change friends to use charID Update friends table to use charID and not LWOOBJID variant. * Fix remove friend Fix remove friend and make the query more readable at a glance. * Add and remove friends in the container Properly add and remove friends in the player container * add enums * Add best friends and basic GM support V1 * Add more features * not online / doesnt exist implementation Implements the not online and invalid character response codes * Address players not being removed Fix an issue where players would not be marked as offline in the friends list due to the message not being sent in all circumstances. Tested changes on 3 clients, switching characters, logging out from character select, switching characters, world transfer and my friends list looked as it was supposed to. * Implement proper friends system Remove debug logs Track count of best friends Add best friends list cap of 5 Add config option and best friend update Add a config option and implement the last missing best friend serialization Added comments and fixed remove best friend bug Added some comments and addressed an issue where removing best friends would not remove them from your internal count of friends. properties and logs fixes whoops, had an issue send reply if already BFFs Send the correct objectID I really need to rename these Fix white space goon * Replace queries with unique ptrs * remove user from player container on deletion Remove the user from the player container when they delete their character. * Bump patch version * Improvements to PlayerContainer Resolved a memory leak in the player container, removed commented out code and resolved a warning in Behavior.cpp * Make it a unique ptr * Improvements to PlayerContainer Resolved a memory leak in the player container, removed commented out code and resolved a warning in Behavior.cpp Make it a unique ptr * Update PlayerContainer.cpp --- dChatServer/PlayerContainer.cpp | 19 ++----------------- dGame/dBehaviors/Behavior.cpp | 2 +- 2 files changed, 3 insertions(+), 18 deletions(-) diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index b40e8386..c5da3a7f 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -49,25 +49,21 @@ void PlayerContainer::RemovePlayer(Packet* packet) { inStream.Read(playerID); //Before they get kicked, we need to also send a message to their friends saying that they disconnected. - auto player = this->GetPlayerData(playerID); + std::unique_ptr player(this->GetPlayerData(playerID)); if (player == nullptr) { return; } for (auto& fr : player->friends) { - //if (!fr.isOnline) continue; - auto fd = this->GetPlayerData(fr.friendID); - if (fd) ChatPacketHandler::SendFriendUpdate(fd, player, 0, fr.isBestFriend); + if (fd) ChatPacketHandler::SendFriendUpdate(fd, player.get(), 0, fr.isBestFriend); } auto* team = GetTeam(playerID); if (team != nullptr) { - //TeamStatusUpdate(team); - const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(player->playerName.C_String())); for (const auto memberId : team->memberIDs) @@ -77,7 +73,6 @@ void PlayerContainer::RemovePlayer(Packet* packet) { if (otherMember == nullptr) continue; ChatPacketHandler::SendTeamSetOffWorldFlag(otherMember, playerID, {0, 0, 0}); - //ChatPacketHandler::SendTeamRemovePlayer(otherMember, false, false, true, false, team->leaderID, player->playerID, memberName); } } @@ -241,12 +236,6 @@ void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(member->playerName.C_String())); ChatPacketHandler::SendTeamInviteConfirm(member, false, leader->playerID, leader->zoneID, team->lootFlag, 0, 0, leaderName); - - /* - ChatPacketHandler::SendTeamAddPlayer(member, false, false, false, leader->playerID, leaderName, leader->zoneID); - - Game::logger->Log("PlayerContainer", "Team invite successfully accepted, leader: %s, member: %s\n", leader->playerName.C_String(), member->playerName.C_String()); - */ if (!team->local) { @@ -383,10 +372,6 @@ void PlayerContainer::TeamStatusUpdate(TeamData* team) { ChatPacketHandler::SendTeamStatus(otherMember, team->leaderID, leader->zoneID, team->lootFlag, 0, leaderName); } - else - { - //ChatPacketHandler::SendTeamStatus(otherMember, LWOOBJID_EMPTY, LWOZONEID(0, 0, 0), 1, 0, u""); - } } UpdateTeamsOnWorld(team, false); diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index a2329f96..489bd1a7 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -409,7 +409,7 @@ Behavior::Behavior(const uint32_t behaviorId) { auto behaviorTemplateTable = CDClientManager::Instance()->GetTable("BehaviorTemplate"); - CDBehaviorTemplate templateInDatabase; + CDBehaviorTemplate templateInDatabase{}; if (behaviorTemplateTable) { auto templateEntry = behaviorTemplateTable->GetByBehaviorID(behaviorId); From 9c0819de4fded129dc17713b5630b382e74093f8 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Sat, 16 Jul 2022 22:55:54 +0100 Subject: [PATCH 014/322] Add MacOS building to the Github Actions (#643) * Add MacOS to CMakePresets.json * Update workflow to run MacOS builds * Update test and build presets * Add libssl install to integration * Update workflow to install libssl and openssl * Prevent brew running as super user --- .github/workflows/build-and-test.yml | 7 +++++-- CMakePresets.json | 28 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 0e7785d9..5a36df4b 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -12,18 +12,21 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ windows-2022, ubuntu-20.04 ] + os: [ windows-2022, ubuntu-20.04, macos-11 ] steps: - uses: actions/checkout@v2 with: submodules: true - - name: Add msbuild to PATH (windows only) + - name: Add msbuild to PATH (Windows only) if: ${{ matrix.os == 'windows-2022' }} uses: microsoft/setup-msbuild@v1.1 with: vs-version: '[17,18)' msbuild-architecture: x64 + - name: Install libssl (Mac Only) + if: ${{ matrix.os == 'macos-11' }} + run: brew install openssl@3 - name: cmake uses: lukka/run-cmake@v10 with: diff --git a/CMakePresets.json b/CMakePresets.json index 241220e0..133d6a3c 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -19,6 +19,15 @@ "description": "Same as default, Used in GitHub actions workflow", "inherits": "default" }, + { + "name": "ci-macos-11", + "displayName": "CI configure step for MacOS", + "description": "Same as default, Used in GitHub actions workflow", + "inherits": "default", + "cacheVariables": { + "OPENSSL_ROOT_DIR": "/usr/local/Cellar/openssl@3/3.0.5/" + } + }, { "name": "ci-windows-2022", "displayName": "CI configure step for Windows", @@ -66,6 +75,13 @@ "displayName": "Linux CI Build", "description": "This preset is used by the CI build on linux", "jobs": 2 + }, + { + "name": "ci-macos-11", + "configurePreset": "ci-macos-11", + "displayName": "MacOS CI Build", + "description": "This preset is used by the CI build on MacOS", + "jobs": 2 } ], "testPresets": [ @@ -81,6 +97,18 @@ "outputOnFailure": true } }, + { + "name": "ci-macos-11", + "configurePreset": "ci-macos-11", + "displayName": "CI Tests on MacOS", + "description": "Runs all tests on a Mac configuration", + "execution": { + "jobs": 2 + }, + "output": { + "outputOnFailure": true + } + }, { "name": "ci-windows-2022", "configurePreset": "ci-windows-2022", From df0f11c95b76c6f5869776272189b6fb81b22e74 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Sun, 17 Jul 2022 00:24:16 +0100 Subject: [PATCH 015/322] Update CMake configuration for easier maintenance (#642) * Update CMake configuration for easier maintenance * Incorrect casing fix * Move package requirement * Update CTest linking * Add logs to the CMake * Add linking for common libraries Added linking for common libraries in tests subdirectory. * Move test subdirectory higher up for some reason * Whitespace a log removal Missed new line * Add dCommon to dChatFilter * Update library output dir * Correct libBcrypt * Further refactor CMake behaviour * Repair bad comments and update library defines * Revert to old include directory method * Implement platform defines * Add missing include Mac needs a specific include for defining platform. Does not compile without this. Co-authored-by: EmosewaMC <39972741+EmosewaMC@users.noreply.github.com> --- CMakeLists.txt | 546 +++++++++-------------------- dAuthServer/CMakeLists.txt | 4 + dChatFilter/CMakeLists.txt | 4 + dChatServer/CMakeLists.txt | 6 + dCommon/CMakeLists.txt | 26 ++ dCommon/ZCompression.cpp | 6 +- dCommon/ZCompression.h | 6 + dCommon/dPlatforms.h | 29 ++ dDatabase/CMakeLists.txt | 13 + dDatabase/Tables/CMakeLists.txt | 38 ++ dGame/CMakeLists.txt | 59 ++++ dGame/dBehaviors/CMakeLists.txt | 51 +++ dGame/dComponents/CMakeLists.txt | 40 +++ dGame/dEntity/CMakeLists.txt | 2 + dGame/dGameMessages/CMakeLists.txt | 4 + dGame/dInventory/CMakeLists.txt | 5 + dGame/dMission/CMakeLists.txt | 3 + dGame/dUtilities/CMakeLists.txt | 9 + dMasterServer/CMakeLists.txt | 10 + dNet/CMakeLists.txt | 11 + dPhysics/CMakeLists.txt | 9 + dScripts/CMakeLists.txt | 253 +++++++++++++ dWorldServer/CMakeLists.txt | 6 + dZoneManager/CMakeLists.txt | 6 + tests/CMakeLists.txt | 20 +- thirdparty/CMakeLists.txt | 102 ++++-- 26 files changed, 839 insertions(+), 429 deletions(-) create mode 100644 dAuthServer/CMakeLists.txt create mode 100644 dChatFilter/CMakeLists.txt create mode 100644 dChatServer/CMakeLists.txt create mode 100644 dCommon/CMakeLists.txt create mode 100644 dCommon/dPlatforms.h create mode 100644 dDatabase/CMakeLists.txt create mode 100644 dDatabase/Tables/CMakeLists.txt create mode 100644 dGame/CMakeLists.txt create mode 100644 dGame/dBehaviors/CMakeLists.txt create mode 100644 dGame/dComponents/CMakeLists.txt create mode 100644 dGame/dEntity/CMakeLists.txt create mode 100644 dGame/dGameMessages/CMakeLists.txt create mode 100644 dGame/dInventory/CMakeLists.txt create mode 100644 dGame/dMission/CMakeLists.txt create mode 100644 dGame/dUtilities/CMakeLists.txt create mode 100644 dMasterServer/CMakeLists.txt create mode 100644 dNet/CMakeLists.txt create mode 100644 dPhysics/CMakeLists.txt create mode 100644 dScripts/CMakeLists.txt create mode 100644 dWorldServer/CMakeLists.txt create mode 100644 dZoneManager/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 5373dfe4..0817412b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,90 +12,67 @@ string(REPLACE "\n" ";" variables ${variables}) # Set the cmake variables, formatted as "VARIABLE #" in variables foreach(variable ${variables}) - # If the string contains a #, skip it - if(NOT "${variable}" MATCHES "#") - - # Split the variable into name and value - string(REPLACE "=" ";" variable ${variable}) + # If the string contains a #, skip it + if(NOT "${variable}" MATCHES "#") + + # Split the variable into name and value + string(REPLACE "=" ";" variable ${variable}) - # Check that the length of the variable is 2 (name and value) - list(LENGTH variable length) - if(${length} EQUAL 2) + # Check that the length of the variable is 2 (name and value) + list(LENGTH variable length) + if(${length} EQUAL 2) - list(GET variable 0 variable_name) - list(GET variable 1 variable_value) + list(GET variable 0 variable_name) + list(GET variable 1 variable_value) - # Set the variable - set(${variable_name} ${variable_value}) + # Set the variable + set(${variable_name} ${variable_value}) - # Add compiler definition - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D${variable_name}=${variable_value}") + # Add compiler definition + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D${variable_name}=${variable_value}") - message(STATUS "Variable: ${variable_name} = ${variable_value}") + message(STATUS "Variable: ${variable_name} = ${variable_value}") endif() endif() endforeach() -# On windows it's better to build this from source, as there's no way FindZLIB is gonna find it -if(NOT WIN32) -find_package(ZLIB REQUIRED) -endif() - -# Fetch External (Non-Submodule) Libraries -if(WIN32) -include(FetchContent) - -FetchContent_Declare( - zlib - URL https://github.com/madler/zlib/archive/refs/tags/v1.2.11.zip - URL_HASH MD5=9d6a627693163bbbf3f26403a3a0b0b1 -) - -FetchContent_MakeAvailable(zlib) - -set(ZLIB_INCLUDE_DIRS ${zlib_SOURCE_DIR} ${zlib_BINARY_DIR}) -set_target_properties(zlib PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${ZLIB_INCLUDE_DIRS}") # Why? -add_library(ZLIB::ZLIB ALIAS zlib) # You're welcome - -endif(WIN32) - -if(UNIX AND NOT APPLE) - include(FetchContent) - if (__include_backtrace__ AND __compile_backtrace__) - FetchContent_Declare( - backtrace - GIT_REPOSITORY https://github.com/ianlancetaylor/libbacktrace.git - ) - - FetchContent_MakeAvailable(backtrace) - - if (NOT EXISTS ${backtrace_SOURCE_DIR}/.libs) - set(backtrace_make_cmd "${backtrace_SOURCE_DIR}/configure --prefix=\"/usr\" --enable-shared --with-system-libunwind") - - execute_process( - COMMAND bash -c "cd ${backtrace_SOURCE_DIR} && ${backtrace_make_cmd} && make && cd ${CMAKE_SOURCE_DIR}" - ) - endif() - - link_directories(${backtrace_SOURCE_DIR}/.libs/) - include_directories(${backtrace_SOURCE_DIR}) - endif() -endif() - # Set the version set(PROJECT_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DPROJECT_VERSION=${PROJECT_VERSION}") - # Echo the version message(STATUS "Version: ${PROJECT_VERSION}") -if(WIN32) - add_compile_definitions(_CRT_SECURE_NO_WARNINGS) -endif(WIN32) +# Compiler flags: +# Disabled deprecated warnings as the MySQL includes have deprecated code in them. +# Disabled misleading indentation as DL_LinkedList from RakNet has a weird indent. +# Disabled no-register +# Disabled unknown pragmas because Linux doesn't understand Windows pragmas. +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DPROJECT_VERSION=${PROJECT_VERSION}") +if(UNIX) + if(APPLE) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++17 -O2 -Wuninitialized -D_GLIBCXX_USE_CXX11_ABI=0 -D_GLIBCXX_USE_CXX17_ABI=0 -fPIC") + else() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++17 -O2 -Wuninitialized -D_GLIBCXX_USE_CXX11_ABI=0 -D_GLIBCXX_USE_CXX17_ABI=0 -static-libgcc -fPIC") + endif() + if (__dynamic) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -rdynamic") + endif() + if (__ggdb) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ggdb") + endif() + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -O2 -fPIC") +elseif(MSVC) + # Skip warning for invalid conversion from size_t to uint32_t for all targets below for now + add_compile_options("/wd4267") +elseif(WIN32) + add_compile_definitions(_CRT_SECURE_NO_WARNINGS) +endif() # Our output dir set(CMAKE_BINARY_DIR ${PROJECT_BINARY_DIR}) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) # Create a /res directory make_directory(${CMAKE_BINARY_DIR}/res) @@ -107,363 +84,172 @@ make_directory(${CMAKE_BINARY_DIR}/locale) make_directory(${CMAKE_BINARY_DIR}/logs) # Copy ini files on first build -if (NOT EXISTS ${PROJECT_BINARY_DIR}/authconfig.ini) - configure_file( - ${CMAKE_SOURCE_DIR}/resources/authconfig.ini ${PROJECT_BINARY_DIR}/authconfig.ini - COPYONLY - ) -endif() -if (NOT EXISTS ${PROJECT_BINARY_DIR}/chatconfig.ini) - configure_file( - ${CMAKE_SOURCE_DIR}/resources/chatconfig.ini ${PROJECT_BINARY_DIR}/chatconfig.ini - COPYONLY - ) -endif() -if (NOT EXISTS ${PROJECT_BINARY_DIR}/worldconfig.ini) - configure_file( - ${CMAKE_SOURCE_DIR}/resources/worldconfig.ini ${PROJECT_BINARY_DIR}/worldconfig.ini - COPYONLY - ) -endif() -if (NOT EXISTS ${PROJECT_BINARY_DIR}/masterconfig.ini) - configure_file( - ${CMAKE_SOURCE_DIR}/resources/masterconfig.ini ${PROJECT_BINARY_DIR}/masterconfig.ini - COPYONLY - ) -endif() +set(INI_FILES "authconfig.ini" "chatconfig.ini" "worldconfig.ini" "masterconfig.ini") +foreach(ini ${INI_FILES}) + if (NOT EXISTS ${PROJECT_BINARY_DIR}/${ini}) + configure_file( + ${CMAKE_SOURCE_DIR}/resources/${ini} ${PROJECT_BINARY_DIR}/${ini} + COPYONLY + ) + endif() +endforeach() -# Copy files to output -configure_file("${CMAKE_SOURCE_DIR}/vanity/CREDITS.md" "${CMAKE_BINARY_DIR}/vanity/CREDITS.md" COPYONLY) -configure_file("${CMAKE_SOURCE_DIR}/vanity/INFO.md" "${CMAKE_BINARY_DIR}/vanity/INFO.md" COPYONLY) -configure_file("${CMAKE_SOURCE_DIR}/vanity/TESTAMENT.md" "${CMAKE_BINARY_DIR}/vanity/TESTAMENT.md" COPYONLY) -configure_file("${CMAKE_SOURCE_DIR}/vanity/NPC.xml" "${CMAKE_BINARY_DIR}/vanity/NPC.xml" COPYONLY) +# Copy vanity files on first build +set(VANITY_FILES "CREDITS.md" "INFO.md" "TESTAMENT.md" "NPC.xml") +foreach(file ${VANITY_FILES}) + configure_file("${CMAKE_SOURCE_DIR}/vanity/${file}" "${CMAKE_BINARY_DIR}/vanity/${file}" COPYONLY) +endforeach() # Move our migrations for MasterServer to run file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/migrations/) file(GLOB SQL_FILES ${CMAKE_SOURCE_DIR}/migrations/dlu/*.sql) -foreach (file ${SQL_FILES}) - get_filename_component(file ${file} NAME) - if (NOT EXISTS ${PROJECT_BINARY_DIR}/migrations/${file}) - configure_file( - ${CMAKE_SOURCE_DIR}/migrations/dlu/${file} ${PROJECT_BINARY_DIR}/migrations/${file} - COPYONLY - ) - endif() +foreach(file ${SQL_FILES}) + get_filename_component(file ${file} NAME) + if (NOT EXISTS ${PROJECT_BINARY_DIR}/migrations/${file}) + configure_file( + ${CMAKE_SOURCE_DIR}/migrations/dlu/${file} ${PROJECT_BINARY_DIR}/migrations/${file} + COPYONLY + ) + endif() endforeach() -# 3rdparty includes -include_directories(${PROJECT_SOURCE_DIR}/thirdparty/raknet/Source/) -if(APPLE) - include_directories(/usr/local/include/) -endif(APPLE) -include_directories(${PROJECT_SOURCE_DIR}/thirdparty/tinyxml2/) -include_directories(${PROJECT_SOURCE_DIR}/thirdparty/recastnavigation/Recast/Include) -include_directories(${PROJECT_SOURCE_DIR}/thirdparty/recastnavigation/Detour/Include) +# Create our list of include directories +set(INCLUDED_DIRECTORIES + "dCommon" + "dChatFilter" + "dGame" + "dGame/dBehaviors" + "dGame/dComponents" + "dGame/dGameMessages" + "dGame/dInventory" + "dGame/dMission" + "dGame/dEntity" + "dGame/dUtilities" + "dPhysics" + "dZoneManager" + "dDatabase" + "dDatabase/Tables" + "dNet" + "dScripts" + + "thirdparty/raknet/Source" + "thirdparty/tinyxml2" + "thirdparty/recastnavigation/Recast/Include" + "thirdparty/recastnavigation/Detour/Include" + "thirdparty/SQLite" + "thirdparty/cpplinq" + ) + +# Add system specfic includes for Apple, Windows and Other Unix OS' (including Linux) +if (APPLE) + include_directories("/usr/local/include/") +endif() + +if (WIN32) + set(INCLUDED_DIRECTORIES ${INCLUDED_DIRECTORIES} "thirdparty/libbcrypt/include") +elseif (UNIX) + set(INCLUDED_DIRECTORIES ${INCLUDED_DIRECTORIES} "thirdparty/libbcrypt") + set(INCLUDED_DIRECTORIES ${INCLUDED_DIRECTORIES} "thirdparty/libbcrypt/include/bcrypt") +endif() + include_directories(${ZLIB_INCLUDE_DIRS}) - -# Bcrypt -if (NOT WIN32) -include_directories(${PROJECT_SOURCE_DIR}/thirdparty/libbcrypt) -include_directories(${PROJECT_SOURCE_DIR}/thirdparty/libbcrypt/include/bcrypt) -else () -include_directories(${PROJECT_SOURCE_DIR}/thirdparty/libbcrypt/include) -endif () - -# Our includes +# Add binary directory as an include directory include_directories(${PROJECT_BINARY_DIR}) -include_directories(${PROJECT_SOURCE_DIR}/dChatFilter/) -include_directories(${PROJECT_SOURCE_DIR}/dCommon/) -include_directories(${PROJECT_SOURCE_DIR}/dGame/) -include_directories(${PROJECT_SOURCE_DIR}/dGame/dBehaviors) -include_directories(${PROJECT_SOURCE_DIR}/dGame/dComponents) -include_directories(${PROJECT_SOURCE_DIR}/dGame/dGameMessages) -include_directories(${PROJECT_SOURCE_DIR}/dGame/dInventory) -include_directories(${PROJECT_SOURCE_DIR}/dGame/dMission) -include_directories(${PROJECT_SOURCE_DIR}/dGame/dEntity) -include_directories(${PROJECT_SOURCE_DIR}/dGame/dUtilities) -include_directories(${PROJECT_SOURCE_DIR}/dPhysics/) -include_directories(${PROJECT_SOURCE_DIR}/dZoneManager/) -include_directories(${PROJECT_SOURCE_DIR}/dDatabase/) -include_directories(${PROJECT_SOURCE_DIR}/dDatabase/Tables/) -include_directories(${PROJECT_SOURCE_DIR}/thirdparty/SQLite/) -include_directories(${PROJECT_SOURCE_DIR}/thirdparty/cpplinq/) -include_directories(${PROJECT_SOURCE_DIR}/dNet/) -include_directories(${PROJECT_SOURCE_DIR}/dScripts/) -# Lib folders: +# Actually include the directories from our list +foreach (dir ${INCLUDED_DIRECTORIES}) + include_directories(${PROJECT_SOURCE_DIR}/${dir}) +endforeach() + +# Add linking directories: link_directories(${PROJECT_BINARY_DIR}) -# Third-Party libraries +# Load all of our third party directories add_subdirectory(thirdparty) -# Source Code +# Glob together all headers that need to be precompiled file( -GLOB SOURCES -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${PROJECT_SOURCE_DIR}/dWorldServer/*.cpp -) - -# Source Code for AuthServer -file( -GLOB SOURCES_AUTH -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${PROJECT_SOURCE_DIR}/dAuthServer/*.cpp -) - -# Source Code for MasterServer -file( -GLOB SOURCES_MASTER -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${PROJECT_SOURCE_DIR}/dMasterServer/*.cpp -) - -# Source Code for ChatServer -file( -GLOB SOURCES_CHAT -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${PROJECT_SOURCE_DIR}/dChatServer/*.cpp -) - -# Source Code for dCommon -file( -GLOB SOURCES_DCOMMON -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${PROJECT_SOURCE_DIR}/dCommon/*.cpp -) - -# Source Code for dChatFilter -file( -GLOB SOURCES_DCHATFILTER -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${PROJECT_SOURCE_DIR}/dChatFilter/*.cpp -) - -# Source Code for dDatabase -file( -GLOB SOURCES_DDATABASE -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${PROJECT_SOURCE_DIR}/dDatabase/*.cpp -${PROJECT_SOURCE_DIR}/dDatabase/Tables/*.cpp + GLOB HEADERS_DDATABASE + LIST_DIRECTORIES false + ${PROJECT_SOURCE_DIR}/dDatabase/*.h + ${PROJECT_SOURCE_DIR}/dDatabase/Tables/*.h + ${PROJECT_SOURCE_DIR}/thirdparty/SQLite/*.h ) file( - GLOB HEADERS_DDATABASE - LIST_DIRECTORIES false - ${PROJECT_SOURCE_DIR}/dDatabase/*.h - ${PROJECT_SOURCE_DIR}/dDatabase/Tables/*.h - ${PROJECT_SOURCE_DIR}/thirdparty/SQLite/*.h + GLOB HEADERS_DZONEMANAGER + LIST_DIRECTORIES false + ${PROJECT_SOURCE_DIR}/dZoneManager/*.h ) file( - GLOB HEADERS_DZONEMANAGER - LIST_DIRECTORIES false - ${PROJECT_SOURCE_DIR}/dZoneManager/*.h + GLOB HEADERS_DCOMMON + LIST_DIRECTORIES false + ${PROJECT_SOURCE_DIR}/dCommon/*.h ) file( - GLOB HEADERS_DCOMMON - LIST_DIRECTORIES false - ${PROJECT_SOURCE_DIR}/dCommon/*.h + GLOB HEADERS_DGAME + LIST_DIRECTORIES false + ${PROJECT_SOURCE_DIR}/dGame/Entity.h + ${PROJECT_SOURCE_DIR}/dGame/dGameMessages/GameMessages.h + ${PROJECT_SOURCE_DIR}/dGame/EntityManager.h + ${PROJECT_SOURCE_DIR}/dScripts/CppScripts.h ) -file( - GLOB HEADERS_DGAME - LIST_DIRECTORIES false - ${PROJECT_SOURCE_DIR}/dGame/Entity.h - ${PROJECT_SOURCE_DIR}/dGame/dGameMessages/GameMessages.h - ${PROJECT_SOURCE_DIR}/dGame/EntityManager.h - ${PROJECT_SOURCE_DIR}/dScripts/CppScripts.h -) +# Add our library subdirectories for creation of the library object +add_subdirectory(dCommon) +add_subdirectory(dDatabase) +add_subdirectory(dChatFilter) +add_subdirectory(dNet) +add_subdirectory(dScripts) # Add for dGame to use +add_subdirectory(dGame) +add_subdirectory(dZoneManager) +add_subdirectory(dPhysics) -# Source Code for dNet -file( -GLOB SOURCES_DNET -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${PROJECT_SOURCE_DIR}/dNet/*.cpp -) +# Create a list of common libraries shared between all binaries +set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "raknet" "mariadbConnCpp") -# Source Code for dGame -file( -GLOB SOURCES_DGAME -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${PROJECT_SOURCE_DIR}/dGame/*.cpp -${PROJECT_SOURCE_DIR}/dGame/dBehaviors/*.cpp -${PROJECT_SOURCE_DIR}/dGame/dComponents/*.cpp -${PROJECT_SOURCE_DIR}/dGame/dGameMessages/*.cpp -${PROJECT_SOURCE_DIR}/dGame/dInventory/*.cpp -${PROJECT_SOURCE_DIR}/dGame/dMission/*.cpp -${PROJECT_SOURCE_DIR}/dGame/dEntity/*.cpp -${PROJECT_SOURCE_DIR}/dGame/dUtilities/*.cpp -${PROJECT_SOURCE_DIR}/dScripts/*.cpp -) +# Add platform specific common libraries +if (UNIX) + set(COMMON_LIBRARIES ${COMMON_LIBRARIES} "dl" "pthread") -# Source Code for dZoneManager -file( -GLOB SOURCES_DZM -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${PROJECT_SOURCE_DIR}/dZoneManager/*.cpp -) + if (NOT APPLE AND __include_backtrace__) + set(COMMON_LIBRARIES ${COMMON_LIBRARIES} "backtrace") + endif() +endif() -# Source Code for dPhysics -file( -GLOB SOURCES_DPHYSICS -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${PROJECT_SOURCE_DIR}/dPhysics/*.cpp -) +add_subdirectory(tests) -if(MSVC) - # Skip warning for invalid conversion from size_t to uint32_t for all targets below for now - add_compile_options("/wd4267") -endif(MSVC) +# Include all of our binary directories +add_subdirectory(dWorldServer) +add_subdirectory(dAuthServer) +add_subdirectory(dChatServer) +add_subdirectory(dMasterServer) # Add MasterServer last so it can rely on the other binaries -# Our static libraries: -add_library(dCommon ${SOURCES_DCOMMON}) -add_library(dChatFilter ${SOURCES_DCHATFILTER}) -add_library(dDatabase ${SOURCES_DDATABASE}) -add_library(dNet ${SOURCES_DNET}) -add_library(dGame ${SOURCES_DGAME}) -add_library(dZoneManager ${SOURCES_DZM}) -add_library(dPhysics ${SOURCES_DPHYSICS}) -target_link_libraries(dDatabase sqlite3) -target_link_libraries(dNet dCommon) #Needed because otherwise linker errors occur. -target_link_libraries(dCommon ZLIB::ZLIB) -target_link_libraries(dCommon libbcrypt) -target_link_libraries(dDatabase mariadbConnCpp) -target_link_libraries(dNet dDatabase) -target_link_libraries(dGame dDatabase) -target_link_libraries(dChatFilter dDatabase) - -if(WIN32) -target_link_libraries(raknet ws2_32) -endif(WIN32) - -# Our executables: -add_executable(WorldServer ${SOURCES}) -add_executable(AuthServer ${SOURCES_AUTH}) -add_executable(MasterServer ${SOURCES_MASTER}) -add_executable(ChatServer ${SOURCES_CHAT}) - -# Add out precompiled headers +# Add our precompiled headers target_precompile_headers( - dGame PRIVATE - ${HEADERS_DGAME} + dGame PRIVATE + ${HEADERS_DGAME} ) target_precompile_headers( - dZoneManager PRIVATE - ${HEADERS_DZONEMANAGER} + dZoneManager PRIVATE + ${HEADERS_DZONEMANAGER} ) # Need to specify to use the CXX compiler language here or else we get errors including . target_precompile_headers( - dDatabase PRIVATE - "$<$:${HEADERS_DDATABASE}>" + dDatabase PRIVATE + "$<$:${HEADERS_DDATABASE}>" ) target_precompile_headers( - dCommon PRIVATE - ${HEADERS_DCOMMON} + dCommon PRIVATE + ${HEADERS_DCOMMON} ) target_precompile_headers( - tinyxml2 PRIVATE - "$<$:${PROJECT_SOURCE_DIR}/thirdparty/tinyxml2/tinyxml2.h>" -) - -# Target libraries to link to: -target_link_libraries(WorldServer dCommon) -target_link_libraries(WorldServer dChatFilter) -target_link_libraries(WorldServer dDatabase) -target_link_libraries(WorldServer dNet) -target_link_libraries(WorldServer dGame) -target_link_libraries(WorldServer dZoneManager) -target_link_libraries(WorldServer dPhysics) -target_link_libraries(WorldServer detour) -target_link_libraries(WorldServer recast) -target_link_libraries(WorldServer raknet) -target_link_libraries(WorldServer mariadbConnCpp) -if(UNIX) -if(NOT APPLE AND __include_backtrace__) -target_link_libraries(WorldServer backtrace) -target_link_libraries(MasterServer backtrace) -target_link_libraries(AuthServer backtrace) -target_link_libraries(ChatServer backtrace) -endif() - -endif(UNIX) -target_link_libraries(WorldServer tinyxml2) - -# Target libraries for Auth: -target_link_libraries(AuthServer dCommon) -target_link_libraries(AuthServer dDatabase) -target_link_libraries(AuthServer dNet) -target_link_libraries(AuthServer raknet) -target_link_libraries(AuthServer mariadbConnCpp) -if(UNIX) -target_link_libraries(AuthServer pthread) -target_link_libraries(AuthServer dl) -endif(UNIX) - -# Target libraries for Master: -target_link_libraries(MasterServer dCommon) -target_link_libraries(MasterServer dDatabase) -target_link_libraries(MasterServer dNet) -target_link_libraries(MasterServer raknet) -target_link_libraries(MasterServer mariadbConnCpp) -if(UNIX) -target_link_libraries(MasterServer pthread) -target_link_libraries(MasterServer dl) -endif(UNIX) - -# Target libraries for Chat: -target_link_libraries(ChatServer dCommon) -target_link_libraries(ChatServer dChatFilter) -target_link_libraries(ChatServer dDatabase) -target_link_libraries(ChatServer dNet) -target_link_libraries(ChatServer raknet) -target_link_libraries(ChatServer mariadbConnCpp) -if(UNIX) -target_link_libraries(ChatServer pthread) -target_link_libraries(ChatServer dl) -endif(UNIX) - -# Compiler flags: -# Disabled deprecated warnings as the MySQL includes have deprecated code in them. -# Disabled misleading indentation as DL_LinkedList from RakNet has a weird indent. -# Disabled no-register -# Disabled unknown pragmas because Linux doesn't understand Windows pragmas. -if(UNIX) - if(APPLE) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++17 -O2 -Wuninitialized -D_GLIBCXX_USE_CXX11_ABI=0 -D_GLIBCXX_USE_CXX17_ABI=0 -fPIC") - else() - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++17 -O2 -Wuninitialized -D_GLIBCXX_USE_CXX11_ABI=0 -D_GLIBCXX_USE_CXX17_ABI=0 -static-libgcc -fPIC") - endif() - if (__dynamic) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -rdynamic") - endif() - if (__ggdb) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ggdb") - endif() -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -O2 -fPIC") -endif(UNIX) - -if(WIN32) -add_dependencies(MasterServer WorldServer) -add_dependencies(MasterServer AuthServer) -add_dependencies(MasterServer ChatServer) -endif() - -# Finally, add the tests -add_subdirectory(tests) - + tinyxml2 PRIVATE + "$<$:${PROJECT_SOURCE_DIR}/thirdparty/tinyxml2/tinyxml2.h>" +) \ No newline at end of file diff --git a/dAuthServer/CMakeLists.txt b/dAuthServer/CMakeLists.txt new file mode 100644 index 00000000..353f2a54 --- /dev/null +++ b/dAuthServer/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DAUTHSERVER_SOURCES "AuthServer.cpp") + +add_executable(AuthServer ${DAUTHSERVER_SOURCES}) +target_link_libraries(AuthServer ${COMMON_LIBRARIES}) diff --git a/dChatFilter/CMakeLists.txt b/dChatFilter/CMakeLists.txt new file mode 100644 index 00000000..24b5e428 --- /dev/null +++ b/dChatFilter/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DCHATFILTER_SOURCES "dChatFilter.cpp") + +add_library(dChatFilter STATIC ${DCHATFILTER_SOURCES}) +target_link_libraries(dChatFilter dDatabase) diff --git a/dChatServer/CMakeLists.txt b/dChatServer/CMakeLists.txt new file mode 100644 index 00000000..948593fb --- /dev/null +++ b/dChatServer/CMakeLists.txt @@ -0,0 +1,6 @@ +set(DCHATSERVER_SOURCES "ChatPacketHandler.cpp" + "ChatServer.cpp" + "PlayerContainer.cpp") + +add_executable(ChatServer ${DCHATSERVER_SOURCES}) +target_link_libraries(ChatServer ${COMMON_LIBRARIES} dChatFilter) diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt new file mode 100644 index 00000000..7e047a9c --- /dev/null +++ b/dCommon/CMakeLists.txt @@ -0,0 +1,26 @@ +set(DCOMMON_SOURCES "AMFFormat.cpp" + "AMFFormat_BitStream.cpp" + "BinaryIO.cpp" + "dConfig.cpp" + "Diagnostics.cpp" + "dLogger.cpp" + "GeneralUtils.cpp" + "LDFFormat.cpp" + "MD5.cpp" + "Metrics.cpp" + "NiPoint3.cpp" + "NiQuaternion.cpp" + "SHA512.cpp" + "Type.cpp" + "ZCompression.cpp") + +include_directories(${PROJECT_SOURCE_DIR}/dCommon/) + +add_library(dCommon STATIC ${DCOMMON_SOURCES}) + +target_link_libraries(dCommon libbcrypt) + +if (UNIX) + find_package(ZLIB REQUIRED) + target_link_libraries(dCommon ZLIB::ZLIB) +endif() diff --git a/dCommon/ZCompression.cpp b/dCommon/ZCompression.cpp index 3a66323d..28588bb8 100644 --- a/dCommon/ZCompression.cpp +++ b/dCommon/ZCompression.cpp @@ -1,5 +1,7 @@ #include "ZCompression.h" +#ifndef _WIN32 + #include namespace ZCompression @@ -70,4 +72,6 @@ namespace ZCompression return(nRet); // -1 or len of output */ } -} \ No newline at end of file +} + +#endif \ No newline at end of file diff --git a/dCommon/ZCompression.h b/dCommon/ZCompression.h index ec870fb8..6db2a600 100644 --- a/dCommon/ZCompression.h +++ b/dCommon/ZCompression.h @@ -2,6 +2,10 @@ #include +#include "dPlatforms.h" + +#ifndef DARKFLAME_PLATFORM_WIN32 + namespace ZCompression { int32_t GetMaxCompressedLength(int32_t nLenSrc); @@ -10,3 +14,5 @@ namespace ZCompression int32_t Decompress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst, int32_t& nErr); } + +#endif diff --git a/dCommon/dPlatforms.h b/dCommon/dPlatforms.h new file mode 100644 index 00000000..d19e8121 --- /dev/null +++ b/dCommon/dPlatforms.h @@ -0,0 +1,29 @@ +#pragma once + +#if defined(_WIN32) + #define DARKFLAME_PLATFORM_WIN32 +#elif defined(__APPLE__) && defined(__MACH__) + #include + #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR + #define DARKFLAME_PLATFORM_IOS + #elif TARGET_OS_MAC + #define DARKFLAME_PLATFORM_MACOS + #else + #error unknown Apple operating system + #endif +#elif defined(__unix__) + #define DARKFLAME_PLATFORM_UNIX + #if defined(__ANDROID__) + #define DARKFLAME_PLATFORM_ANDROID + #elif defined(__linux__) + #define DARKFLAME_PLATFORM_LINUX + #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) + #define DARKFLAME_PLATFORM_FREEBSD + #elif defined(__CYGWIN__) + #define DARKFLAME_PLATFORM_CYGWIN + #else + #error unknown unix operating system + #endif +#else + #error unknown operating system +#endif \ No newline at end of file diff --git a/dDatabase/CMakeLists.txt b/dDatabase/CMakeLists.txt new file mode 100644 index 00000000..9e55fbe2 --- /dev/null +++ b/dDatabase/CMakeLists.txt @@ -0,0 +1,13 @@ +set(DDATABASE_SOURCES "CDClientDatabase.cpp" + "CDClientManager.cpp" + "Database.cpp" + "MigrationRunner.cpp") + +add_subdirectory(Tables) + +foreach(file ${DDATABASE_TABLES_SOURCES}) + set(DDATABASE_SOURCES ${DDATABASE_SOURCES} "Tables/${file}") +endforeach() + +add_library(dDatabase STATIC ${DDATABASE_SOURCES}) +target_link_libraries(dDatabase sqlite3 mariadbConnCpp) diff --git a/dDatabase/Tables/CMakeLists.txt b/dDatabase/Tables/CMakeLists.txt new file mode 100644 index 00000000..b6a02b02 --- /dev/null +++ b/dDatabase/Tables/CMakeLists.txt @@ -0,0 +1,38 @@ +set(DDATABASE_TABLES_SOURCES "CDActivitiesTable.cpp" + "CDActivityRewardsTable.cpp" + "CDAnimationsTable.cpp" + "CDBehaviorParameterTable.cpp" + "CDBehaviorTemplateTable.cpp" + "CDBrickIDTableTable.cpp" + "CDComponentsRegistryTable.cpp" + "CDCurrencyTableTable.cpp" + "CDDestructibleComponentTable.cpp" + "CDEmoteTable.cpp" + "CDFeatureGatingTable.cpp" + "CDInventoryComponentTable.cpp" + "CDItemComponentTable.cpp" + "CDItemSetSkillsTable.cpp" + "CDItemSetsTable.cpp" + "CDLevelProgressionLookupTable.cpp" + "CDLootMatrixTable.cpp" + "CDLootTableTable.cpp" + "CDMissionEmailTable.cpp" + "CDMissionNPCComponentTable.cpp" + "CDMissionsTable.cpp" + "CDMissionTasksTable.cpp" + "CDMovementAIComponentTable.cpp" + "CDObjectSkillsTable.cpp" + "CDObjectsTable.cpp" + "CDPackageComponentTable.cpp" + "CDPhysicsComponentTable.cpp" + "CDPropertyEntranceComponentTable.cpp" + "CDPropertyTemplateTable.cpp" + "CDProximityMonitorComponentTable.cpp" + "CDRailActivatorComponent.cpp" + "CDRarityTableTable.cpp" + "CDRebuildComponentTable.cpp" + "CDRewardsTable.cpp" + "CDScriptComponentTable.cpp" + "CDSkillBehaviorTable.cpp" + "CDVendorComponentTable.cpp" + "CDZoneTableTable.cpp" PARENT_SCOPE) diff --git a/dGame/CMakeLists.txt b/dGame/CMakeLists.txt new file mode 100644 index 00000000..5acdba31 --- /dev/null +++ b/dGame/CMakeLists.txt @@ -0,0 +1,59 @@ +set(DGAME_SOURCES "Character.cpp" + "Entity.cpp" + "EntityManager.cpp" + "LeaderboardManager.cpp" + "Player.cpp" + "TeamManager.cpp" + "TradingManager.cpp" + "User.cpp" + "UserManager.cpp") + +add_subdirectory(dBehaviors) + +foreach(file ${DGAME_DBEHAVIORS_SOURCES}) + set(DGAME_SOURCES ${DGAME_SOURCES} "dBehaviors/${file}") +endforeach() + +add_subdirectory(dComponents) + +foreach(file ${DGAME_DCOMPONENTS_SOURCES}) + set(DGAME_SOURCES ${DGAME_SOURCES} "dComponents/${file}") +endforeach() + +add_subdirectory(dEntity) + +foreach(file ${DGAME_DENTITY_SOURCES}) + set(DGAME_SOURCES ${DGAME_SOURCES} "dEntity/${file}") +endforeach() + +add_subdirectory(dGameMessages) + +foreach(file ${DGAME_DGAMEMESSAGES_SOURCES}) + set(DGAME_SOURCES ${DGAME_SOURCES} "dGameMessages/${file}") +endforeach() + +add_subdirectory(dInventory) + +foreach(file ${DGAME_DINVENTORY_SOURCES}) + set(DGAME_SOURCES ${DGAME_SOURCES} "dInventory/${file}") +endforeach() + +add_subdirectory(dMission) + +foreach(file ${DGAME_DMISSION_SOURCES}) + set(DGAME_SOURCES ${DGAME_SOURCES} "dMission/${file}") +endforeach() + +add_subdirectory(dUtilities) + +foreach(file ${DGAME_DUTILITIES_SOURCES}) + set(DGAME_SOURCES ${DGAME_SOURCES} "dUtilities/${file}") +endforeach() + +foreach(file ${DSCRIPT_SOURCES}) + set(DGAME_SOURCES ${DGAME_SOURCES} "${PROJECT_SOURCE_DIR}/dScripts/${file}") +endforeach() + +add_library(dGame STATIC ${DGAME_SOURCES}) + +target_link_libraries(dGame dDatabase) diff --git a/dGame/dBehaviors/CMakeLists.txt b/dGame/dBehaviors/CMakeLists.txt new file mode 100644 index 00000000..fe8e89b8 --- /dev/null +++ b/dGame/dBehaviors/CMakeLists.txt @@ -0,0 +1,51 @@ +set(DGAME_DBEHAVIORS_SOURCES "AirMovementBehavior.cpp" + "AndBehavior.cpp" + "ApplyBuffBehavior.cpp" + "AreaOfEffectBehavior.cpp" + "AttackDelayBehavior.cpp" + "BasicAttackBehavior.cpp" + "Behavior.cpp" + "BehaviorBranchContext.cpp" + "BehaviorContext.cpp" + "BehaviorTemplates.cpp" + "BlockBehavior.cpp" + "BuffBehavior.cpp" + "CarBoostBehavior.cpp" + "ChainBehavior.cpp" + "ChangeOrientationBehavior.cpp" + "ChargeUpBehavior.cpp" + "ClearTargetBehavior.cpp" + "DamageAbsorptionBehavior.cpp" + "DamageReductionBehavior.cpp" + "DurationBehavior.cpp" + "EmptyBehavior.cpp" + "EndBehavior.cpp" + "ForceMovementBehavior.cpp" + "HealBehavior.cpp" + "ImaginationBehavior.cpp" + "ImmunityBehavior.cpp" + "InterruptBehavior.cpp" + "JetPackBehavior.cpp" + "KnockbackBehavior.cpp" + "LootBuffBehavior.cpp" + "MovementSwitchBehavior.cpp" + "NpcCombatSkillBehavior.cpp" + "OverTimeBehavior.cpp" + "PlayEffectBehavior.cpp" + "ProjectileAttackBehavior.cpp" + "PullToPointBehavior.cpp" + "RepairBehavior.cpp" + "SkillCastFailedBehavior.cpp" + "SkillEventBehavior.cpp" + "SpawnBehavior.cpp" + "SpawnQuickbuildBehavior.cpp" + "SpeedBehavior.cpp" + "StartBehavior.cpp" + "StunBehavior.cpp" + "SwitchBehavior.cpp" + "SwitchMultipleBehavior.cpp" + "TacArcBehavior.cpp" + "TargetCasterBehavior.cpp" + "TauntBehavior.cpp" + "VentureVisionBehavior.cpp" + "VerifyBehavior.cpp" PARENT_SCOPE) diff --git a/dGame/dComponents/CMakeLists.txt b/dGame/dComponents/CMakeLists.txt new file mode 100644 index 00000000..706395ea --- /dev/null +++ b/dGame/dComponents/CMakeLists.txt @@ -0,0 +1,40 @@ +set(DGAME_DCOMPONENTS_SOURCES "BaseCombatAIComponent.cpp" + "BouncerComponent.cpp" + "BuffComponent.cpp" + "BuildBorderComponent.cpp" + "CharacterComponent.cpp" + "Component.cpp" + "ControllablePhysicsComponent.cpp" + "DestroyableComponent.cpp" + "InventoryComponent.cpp" + "LUPExhibitComponent.cpp" + "MissionComponent.cpp" + "MissionOfferComponent.cpp" + "ModelComponent.cpp" + "ModuleAssemblyComponent.cpp" + "MovementAIComponent.cpp" + "MovingPlatformComponent.cpp" + "PetComponent.cpp" + "PhantomPhysicsComponent.cpp" + "PossessableComponent.cpp" + "PossessorComponent.cpp" + "PropertyComponent.cpp" + "PropertyEntranceComponent.cpp" + "PropertyManagementComponent.cpp" + "PropertyVendorComponent.cpp" + "ProximityMonitorComponent.cpp" + "RacingControlComponent.cpp" + "RailActivatorComponent.cpp" + "RebuildComponent.cpp" + "RenderComponent.cpp" + "RigidbodyPhantomPhysicsComponent.cpp" + "RocketLaunchLupComponent.cpp" + "RocketLaunchpadControlComponent.cpp" + "ScriptedActivityComponent.cpp" + "ShootingGalleryComponent.cpp" + "SimplePhysicsComponent.cpp" + "SkillComponent.cpp" + "SoundTriggerComponent.cpp" + "SwitchComponent.cpp" + "VehiclePhysicsComponent.cpp" + "VendorComponent.cpp" PARENT_SCOPE) diff --git a/dGame/dEntity/CMakeLists.txt b/dGame/dEntity/CMakeLists.txt new file mode 100644 index 00000000..4bb49799 --- /dev/null +++ b/dGame/dEntity/CMakeLists.txt @@ -0,0 +1,2 @@ +set(DGAME_DENTITY_SOURCES "EntityCallbackTimer.cpp" + "EntityTimer.cpp" PARENT_SCOPE) diff --git a/dGame/dGameMessages/CMakeLists.txt b/dGame/dGameMessages/CMakeLists.txt new file mode 100644 index 00000000..3c3cb53f --- /dev/null +++ b/dGame/dGameMessages/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DGAME_DGAMEMESSAGES_SOURCES "GameMessageHandler.cpp" + "GameMessages.cpp" + "PropertyDataMessage.cpp" + "PropertySelectQueryProperty.cpp" PARENT_SCOPE) diff --git a/dGame/dInventory/CMakeLists.txt b/dGame/dInventory/CMakeLists.txt new file mode 100644 index 00000000..60cfca75 --- /dev/null +++ b/dGame/dInventory/CMakeLists.txt @@ -0,0 +1,5 @@ +set(DGAME_DINVENTORY_SOURCES "EquippedItem.cpp" + "Inventory.cpp" + "Item.cpp" + "ItemSet.cpp" + "ItemSetPassiveAbility.cpp" PARENT_SCOPE) diff --git a/dGame/dMission/CMakeLists.txt b/dGame/dMission/CMakeLists.txt new file mode 100644 index 00000000..652c3cb2 --- /dev/null +++ b/dGame/dMission/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DGAME_DMISSION_SOURCES "Mission.cpp" + "MissionPrerequisites.cpp" + "MissionTask.cpp" PARENT_SCOPE) diff --git a/dGame/dUtilities/CMakeLists.txt b/dGame/dUtilities/CMakeLists.txt new file mode 100644 index 00000000..0c848bf4 --- /dev/null +++ b/dGame/dUtilities/CMakeLists.txt @@ -0,0 +1,9 @@ +set(DGAME_DUTILITIES_SOURCES "BrickDatabase.cpp" + "dLocale.cpp" + "GameConfig.cpp" + "GUID.cpp" + "Loot.cpp" + "Mail.cpp" + "Preconditions.cpp" + "SlashCommandHandler.cpp" + "VanityUtilities.cpp" PARENT_SCOPE) diff --git a/dMasterServer/CMakeLists.txt b/dMasterServer/CMakeLists.txt new file mode 100644 index 00000000..08fc63db --- /dev/null +++ b/dMasterServer/CMakeLists.txt @@ -0,0 +1,10 @@ +set(DMASTERSERVER_SOURCES "InstanceManager.cpp" + "MasterServer.cpp" + "ObjectIDManager.cpp") + +add_executable(MasterServer ${DMASTERSERVER_SOURCES}) +target_link_libraries(MasterServer ${COMMON_LIBRARIES}) + +if(WIN32) + add_dependencies(MasterServer WorldServer AuthServer ChatServer) +endif() diff --git a/dNet/CMakeLists.txt b/dNet/CMakeLists.txt new file mode 100644 index 00000000..938c0449 --- /dev/null +++ b/dNet/CMakeLists.txt @@ -0,0 +1,11 @@ +set(DNET_SOURCES "AuthPackets.cpp" + "ChatPackets.cpp" + "ClientPackets.cpp" + "dServer.cpp" + "MasterPackets.cpp" + "PacketUtils.cpp" + "WorldPackets.cpp" + "ZoneInstanceManager.cpp") + +add_library(dNet STATIC ${DNET_SOURCES}) +target_link_libraries(dNet dCommon dDatabase) diff --git a/dPhysics/CMakeLists.txt b/dPhysics/CMakeLists.txt new file mode 100644 index 00000000..383393cc --- /dev/null +++ b/dPhysics/CMakeLists.txt @@ -0,0 +1,9 @@ +set(DPHYSICS_SOURCES "dpCollisionChecks.cpp" + "dpEntity.cpp" + "dpGrid.cpp" + "dpShapeBase.cpp" + "dpShapeBox.cpp" + "dpShapeSphere.cpp" + "dpWorld.cpp") + +add_library(dPhysics STATIC ${DPHYSICS_SOURCES}) diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt new file mode 100644 index 00000000..1fa177ba --- /dev/null +++ b/dScripts/CMakeLists.txt @@ -0,0 +1,253 @@ +set(DSCRIPT_SOURCES "ActivityManager.cpp" + "ActMine.cpp" + "ActNinjaTurret.cpp" + "ActParadoxPipeFix.cpp" + "ActPlayerDeathTrigger.cpp" + "ActSharkPlayerDeathTrigger.cpp" + "ActVehicleDeathTrigger.cpp" + "AgBugsprayer.cpp" + "AgBusDoor.cpp" + "AgCagedBricksServer.cpp" + "AgDarkSpiderling.cpp" + "AgFans.cpp" + "AgImagSmashable.cpp" + "AgJetEffectServer.cpp" + "AgLaserSensorServer.cpp" + "AgMonumentBirds.cpp" + "AgMonumentLaserServer.cpp" + "AgMonumentRaceCancel.cpp" + "AgMonumentRaceGoal.cpp" + "AgPicnicBlanket.cpp" + "AgPropGuard.cpp" + "AgPropguards.cpp" + "AgQbElevator.cpp" + "AgSalutingNpcs.cpp" + "AgShipPlayerDeathTrigger.cpp" + "AgShipPlayerShockServer.cpp" + "AgSpaceStuff.cpp" + "AgStagePlatforms.cpp" + "AgStromlingProperty.cpp" + "AgSurvivalBuffStation.cpp" + "AgSurvivalMech.cpp" + "AgSurvivalSpiderling.cpp" + "AgSurvivalStromling.cpp" + "AgTurret.cpp" + "AllCrateChicken.cpp" + "AmBlueX.cpp" + "AmBridge.cpp" + "AmConsoleTeleportServer.cpp" + "AmDarklingDragon.cpp" + "AmDarklingMech.cpp" + "AmDrawBridge.cpp" + "AmDropshipComputer.cpp" + "AmScrollReaderServer.cpp" + "AmShieldGenerator.cpp" + "AmShieldGeneratorQuickbuild.cpp" + "AmSkeletonEngineer.cpp" + "AmSkullkinDrill.cpp" + "AmSkullkinDrillStand.cpp" + "AmSkullkinTower.cpp" + "AmTeapotServer.cpp" + "AmTemplateSkillVolume.cpp" + "AnvilOfArmor.cpp" + "BankInteractServer.cpp" + "BaseConsoleTeleportServer.cpp" + "BaseEnemyApe.cpp" + "BaseEnemyMech.cpp" + "BaseFootRaceManager.cpp" + "BaseInteractDropLootServer.cpp" + "BasePropertyServer.cpp" + "BaseRandomServer.cpp" + "BaseSurvivalServer.cpp" + "BaseWavesGenericEnemy.cpp" + "BaseWavesServer.cpp" + "Binoculars.cpp" + "BootyDigServer.cpp" + "BossSpiderQueenEnemyServer.cpp" + "BuccaneerValiantShip.cpp" + "BurningTile.cpp" + "CatapultBaseServer.cpp" + "CatapultBouncerServer.cpp" + "CauldronOfLife.cpp" + "CavePrisonCage.cpp" + "ChooseYourDestinationNsToNt.cpp" + "ClRing.cpp" + "CppScripts.cpp" + "CrabServer.cpp" + "DamagingPets.cpp" + "Darkitect.cpp" + "DLUVanityNPC.cpp" + "EnemyNjBuff.cpp" + "EnemyRoninSpawner.cpp" + "EnemySkeletonSpawner.cpp" + "EnemySpiderSpawner.cpp" + "ExplodingAsset.cpp" + "FallingTile.cpp" + "FireFirstSkillonStartup.cpp" + "FlameJetServer.cpp" + "ForceVolumeServer.cpp" + "FountainOfImagination.cpp" + "FvBounceOverWall.cpp" + "FvBrickPuzzleServer.cpp" + "FvCandle.cpp" + "FvConsoleLeftQuickbuild.cpp" + "FvConsoleRightQuickbuild.cpp" + "FvDragonSmashingGolemQb.cpp" + "FvFacilityBrick.cpp" + "FvFlyingCreviceDragon.cpp" + "FvFong.cpp" + "FvFreeGfNinjas.cpp" + "FvHorsemenTrigger.cpp" + "FvMaelstromCavalry.cpp" + "FvMaelstromDragon.cpp" + "FvNinjaGuard.cpp" + "FvPandaServer.cpp" + "FvPandaSpawnerServer.cpp" + "FvPassThroughWall.cpp" + "FvRaceSmashEggImagineServer.cpp" + "GfApeSmashingQB.cpp" + "GfBanana.cpp" + "GfBananaCluster.cpp" + "GfCampfire.cpp" + "GfCaptainsCannon.cpp" + "GfJailkeepMission.cpp" + "GfJailWalls.cpp" + "GfOrgan.cpp" + "GfTikiTorch.cpp" + "GrowingFlower.cpp" + "HydrantBroken.cpp" + "HydrantSmashable.cpp" + "ImaginationBackpackHealServer.cpp" + "ImaginationShrineServer.cpp" + "ImgBrickConsoleQB.cpp" + "InstanceExitTransferPlayerToLastNonInstance.cpp" + "InvalidScript.cpp" + "LegoDieRoll.cpp" + "Lieutenant.cpp" + "MaestromExtracticatorServer.cpp" + "MailBoxServer.cpp" + "MastTeleport.cpp" + "MinigameTreasureChestServer.cpp" + "MonCoreNookDoors.cpp" + "MonCoreSmashableDoors.cpp" + "NjColeNPC.cpp" + "NjDragonEmblemChestServer.cpp" + "NjEarthDragonPetServer.cpp" + "NjEarthPetServer.cpp" + "NjGarmadonCelebration.cpp" + "NjhubLavaPlayerDeathTrigger.cpp" + "NjIceRailActivator.cpp" + "NjJayMissionItems.cpp" + "NjMonastryBossInstance.cpp" + "NjNPCMissionSpinjitzuServer.cpp" + "NjNyaMissionitems.cpp" + "NjRailActivatorsServer.cpp" + "NjRailPostServer.cpp" + "NjRailSwitch.cpp" + "NjScrollChestServer.cpp" + "NjWuNPC.cpp" + "NPCAddRemoveItem.cpp" + "NpcAgCourseStarter.cpp" + "NpcCowboyServer.cpp" + "NpcEpsilonServer.cpp" + "NpcNjAssistantServer.cpp" + "NpcNpSpacemanBob.cpp" + "NpcPirateServer.cpp" + "NpcWispServer.cpp" + "NsConcertChoiceBuild.cpp" + "NsConcertChoiceBuildManager.cpp" + "NsConcertInstrument.cpp" + "NsConcertQuickBuild.cpp" + "NsGetFactionMissionServer.cpp" + "NsJohnnyMissionServer.cpp" + "NsLegoClubDoor.cpp" + "NsLupTeleport.cpp" + "NsModularBuild.cpp" + "NsQbImaginationStatue.cpp" + "NsTokenConsoleServer.cpp" + "NtAssemblyTubeServer.cpp" + "NtBeamImaginationCollectors.cpp" + "NtCombatChallengeDummy.cpp" + "NtCombatChallengeExplodingDummy.cpp" + "NtCombatChallengeServer.cpp" + "NtConsoleTeleportServer.cpp" + "NtDarkitectRevealServer.cpp" + "NtDirtCloudServer.cpp" + "NtDukeServer.cpp" + "NtFactionSpyServer.cpp" + "NtHaelServer.cpp" + "NtImagBeamBuffer.cpp" + "NtOverbuildServer.cpp" + "NtParadoxPanelServer.cpp" + "NtParadoxTeleServer.cpp" + "NtSentinelWalkwayServer.cpp" + "NtSleepingGuard.cpp" + "NtVandaServer.cpp" + "NtVentureCannonServer.cpp" + "NtVentureSpeedPadServer.cpp" + "NtXRayServer.cpp" + "PersonalFortress.cpp" + "PetDigBuild.cpp" + "PetDigServer.cpp" + "PetFromDigServer.cpp" + "PetFromObjectServer.cpp" + "PropertyBankInteract.cpp" + "PropertyDeathPlane.cpp" + "PropertyDevice.cpp" + "PropertyFXDamage.cpp" + "PropertyPlatform.cpp" + "PrSeagullFly.cpp" + "PrWhistle.cpp" + "QbEnemyStunner.cpp" + "RaceImagineCrateServer.cpp" + "RaceImaginePowerup.cpp" + "RaceMaelstromGeiser.cpp" + "RaceSmashServer.cpp" + "RainOfArrows.cpp" + "RandomSpawnerFin.cpp" + "RandomSpawnerPit.cpp" + "RandomSpawnerStr.cpp" + "RandomSpawnerZip.cpp" + "RemoveRentalGear.cpp" + "RockHydrantBroken.cpp" + "RockHydrantSmashable.cpp" + "ScriptComponent.cpp" + "ScriptedPowerupSpawner.cpp" + "SGCannon.cpp" + "SpawnGryphonServer.cpp" + "SpawnLionServer.cpp" + "SpawnPetBaseServer.cpp" + "SpawnSaberCatServer.cpp" + "SpawnShrakeServer.cpp" + "SpawnStegoServer.cpp" + "SpecialImaginePowerupSpawner.cpp" + "SpiderBossTreasureChestServer.cpp" + "SsModularBuildServer.cpp" + "StinkyFishTarget.cpp" + "StoryBoxInteractServer.cpp" + "Sunflower.cpp" + "TokenConsoleServer.cpp" + "TouchMissionUpdateServer.cpp" + "TreasureChestDragonServer.cpp" + "TriggerAmbush.cpp" + "VeBricksampleServer.cpp" + "VeEpsilonServer.cpp" + "VeMech.cpp" + "VeMissionConsole.cpp" + "WaveBossApe.cpp" + "WaveBossHammerling.cpp" + "WaveBossHorsemen.cpp" + "WaveBossSpiderling.cpp" + "WhFans.cpp" + "WildAmbients.cpp" + "WishingWellServer.cpp" + "ZoneAgMedProperty.cpp" + "ZoneAgProperty.cpp" + "ZoneAgSpiderQueen.cpp" + "ZoneAgSurvival.cpp" + "ZoneFvProperty.cpp" + "ZoneGfProperty.cpp" + "ZoneNsMedProperty.cpp" + "ZoneNsProperty.cpp" + "ZoneNsWaves.cpp" + "ZoneSGServer.cpp" PARENT_SCOPE) diff --git a/dWorldServer/CMakeLists.txt b/dWorldServer/CMakeLists.txt new file mode 100644 index 00000000..3df808a2 --- /dev/null +++ b/dWorldServer/CMakeLists.txt @@ -0,0 +1,6 @@ +set(DWORLDSERVER_SOURCES "ObjectIDManager.cpp" + "PerformanceManager.cpp" + "WorldServer.cpp") + +add_executable(WorldServer ${DWORLDSERVER_SOURCES}) +target_link_libraries(WorldServer ${COMMON_LIBRARIES} dChatFilter dGame dZoneManager dPhysics detour recast tinyxml2) diff --git a/dZoneManager/CMakeLists.txt b/dZoneManager/CMakeLists.txt new file mode 100644 index 00000000..1dd3841b --- /dev/null +++ b/dZoneManager/CMakeLists.txt @@ -0,0 +1,6 @@ +set(DZONEMANAGER_SOURCES "dZoneManager.cpp" + "Level.cpp" + "Spawner.cpp" + "Zone.cpp") + +add_library(dZoneManager STATIC ${DZONEMANAGER_SOURCES}) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 85f4bda4..b0e2c28d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,17 +1,13 @@ # create the testing file and list of tests create_test_sourcelist (Tests - CommonCxxTests.cpp - TestNiPoint3.cpp - TestLDFFormat.cpp + CommonCxxTests.cpp + TestNiPoint3.cpp + TestLDFFormat.cpp ) - + # add the executable add_executable (CommonCxxTests ${Tests}) -target_link_libraries(CommonCxxTests dCommon raknet) - -if(WIN32) - target_link_libraries(CommonCxxTests ws2_32) -endif(WIN32) +target_link_libraries(CommonCxxTests ${COMMON_LIBRARIES}) # remove the test driver source file set (TestsToRun ${Tests}) @@ -19,7 +15,7 @@ remove (TestsToRun CommonCxxTests.cpp) # Add all the ADD_TEST for each test foreach (test ${TestsToRun}) - get_filename_component (TName ${test} NAME_WE) - add_test (NAME ${TName} COMMAND CommonCxxTests ${TName}) - set_property(TEST ${TName} PROPERTY ENVIRONMENT CTEST_OUTPUT_ON_FAILURE=1) + get_filename_component (TName ${test} NAME_WE) + add_test (NAME ${TName} COMMAND CommonCxxTests ${TName}) + set_property(TEST ${TName} PROPERTY ENVIRONMENT CTEST_OUTPUT_ON_FAILURE=1) endforeach () diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt index ce24ecd3..119ce4fd 100644 --- a/thirdparty/CMakeLists.txt +++ b/thirdparty/CMakeLists.txt @@ -1,50 +1,50 @@ # Source Code for raknet file( -GLOB SOURCES_RAKNET -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${CMAKE_CURRENT_SOURCE_DIR}/raknet/Source/*.cpp + GLOB SOURCES_RAKNET + LIST_DIRECTORIES false + RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" + ${CMAKE_CURRENT_SOURCE_DIR}/raknet/Source/*.cpp ) # Source Code for recast file( -GLOB SOURCES_RECAST -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${CMAKE_CURRENT_SOURCE_DIR}/recastnavigation/Recast/Source/*.cpp + GLOB SOURCES_RECAST + LIST_DIRECTORIES false + RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" + ${CMAKE_CURRENT_SOURCE_DIR}/recastnavigation/Recast/Source/*.cpp ) # Source Code for detour file( -GLOB SOURCES_DETOUR -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${CMAKE_CURRENT_SOURCE_DIR}/recastnavigation/Detour/Source/*.cpp + GLOB SOURCES_DETOUR + LIST_DIRECTORIES false + RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" + ${CMAKE_CURRENT_SOURCE_DIR}/recastnavigation/Detour/Source/*.cpp ) # Source Code for tinyxml2 file( -GLOB SOURCES_TINYXML2 -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${CMAKE_CURRENT_SOURCE_DIR}/tinyxml2/tinyxml2.cpp + GLOB SOURCES_TINYXML2 + LIST_DIRECTORIES false + RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" + ${CMAKE_CURRENT_SOURCE_DIR}/tinyxml2/tinyxml2.cpp ) # Source Code for libbcrypt file( -GLOB SOURCES_LIBBCRYPT -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${CMAKE_CURRENT_SOURCE_DIR}/libbcrypt/*.c -${CMAKE_CURRENT_SOURCE_DIR}/libbcrypt/src/*.c + GLOB SOURCES_LIBBCRYPT + LIST_DIRECTORIES false + RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" + ${CMAKE_CURRENT_SOURCE_DIR}/libbcrypt/*.c + ${CMAKE_CURRENT_SOURCE_DIR}/libbcrypt/src/*.c ) file( -GLOB SOURCES_SQLITE3 -LIST_DIRECTORIES false -RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" -${CMAKE_CURRENT_SOURCE_DIR}/SQLite/*.cpp -${CMAKE_CURRENT_SOURCE_DIR}/SQLite/*.c + GLOB SOURCES_SQLITE3 + LIST_DIRECTORIES false + RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" + ${CMAKE_CURRENT_SOURCE_DIR}/SQLite/*.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/SQLite/*.c ) # mariadb connector cpp @@ -147,7 +147,6 @@ else() # Build from source set(MARIADB_SHARED_LIBRARY_LOCATION "${BINARY_DIR}/RelWithDebInfo/${MARIADB_SHARED_LIBRARY_NAME}") set(MARIADB_SHARED_LIBRARY_COPY_LOCATION "${PROJECT_BINARY_DIR}/$") set(MARIADB_PLUGINS_LOCATION "${BINARY_DIR}/libmariadb/RelWithDebInfo") - message(STATUS "1 ${CMAKE_SOURCE_DIR}") else() set(MARIADB_SHARED_LIBRARY_LOCATION "${BINARY_DIR}/${MARIADB_SHARED_LIBRARY_NAME}") set(MARIADB_SHARED_LIBRARY_COPY_LOCATION "${PROJECT_BINARY_DIR}") @@ -179,16 +178,19 @@ if(EXISTS "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/test/CMakeLists. file(REMOVE "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/test/CMakeLists.txt") endif() +# Create mariadb connector library object add_library(mariadbConnCpp SHARED IMPORTED GLOBAL) set_property(TARGET mariadbConnCpp PROPERTY IMPORTED_LOCATION ${MARIADB_SHARED_LIBRARY_LOCATION}) + if(WIN32) set_property(TARGET mariadbConnCpp PROPERTY IMPORTED_IMPLIB ${MARIADB_IMPLIB_LOCATION}) endif() + +# Add directories to include lists target_include_directories(mariadbConnCpp INTERFACE ${MARIADB_INCLUDE_DIR}) add_dependencies(mariadbConnCpp mariadb_connector_cpp) -# 3rdparty static libraries: -#add_library(zlib ${SOURCES_ZLIB}) +# Create our third party library objects add_library(raknet ${SOURCES_RAKNET}) add_library(tinyxml2 ${SOURCES_TINYXML2}) add_library(detour ${SOURCES_DETOUR}) @@ -196,11 +198,39 @@ add_library(recast ${SOURCES_RECAST}) add_library(libbcrypt ${SOURCES_LIBBCRYPT}) add_library(sqlite3 ${SOURCES_SQLITE3}) -if(UNIX) -target_link_libraries(sqlite3 pthread dl m) +if(WIN32) + # Link Win Sockets 2 to RakNet + target_link_libraries(raknet ws2_32) +elseif(UNIX) + # Add warning disable flags and link Unix libraries to sqlite3 + target_link_libraries(sqlite3 pthread dl m) -# -Wno-unused-result -Wno-unknown-pragmas -fpermissive -target_compile_options(sqlite3 PRIVATE "-Wno-return-local-addr" "-Wno-maybe-uninitialized") -target_compile_options(raknet PRIVATE "-Wno-write-strings" "-Wformat-overflow=0" "-Wformat=0") -target_compile_options(libbcrypt PRIVATE "-Wno-implicit-function-declaration" "-Wno-int-conversion") -endif(UNIX) \ No newline at end of file + # -Wno-unused-result -Wno-unknown-pragmas -fpermissive + target_compile_options(sqlite3 PRIVATE "-Wno-return-local-addr" "-Wno-maybe-uninitialized") + target_compile_options(raknet PRIVATE "-Wno-write-strings" "-Wformat-overflow=0" "-Wformat=0") + target_compile_options(libbcrypt PRIVATE "-Wno-implicit-function-declaration" "-Wno-int-conversion") +endif() + +# Download Backtrace if configured +if(UNIX AND NOT APPLE) + include(FetchContent) + if (__include_backtrace__ AND __compile_backtrace__) + FetchContent_Declare( + backtrace + GIT_REPOSITORY https://github.com/ianlancetaylor/libbacktrace.git + ) + + FetchContent_MakeAvailable(backtrace) + + if (NOT EXISTS ${backtrace_SOURCE_DIR}/.libs) + set(backtrace_make_cmd "${backtrace_SOURCE_DIR}/configure --prefix=\"/usr\" --enable-shared --with-system-libunwind") + + execute_process( + COMMAND bash -c "cd ${backtrace_SOURCE_DIR} && ${backtrace_make_cmd} && make && cd ${CMAKE_SOURCE_DIR}" + ) + endif() + + link_directories(${backtrace_SOURCE_DIR}/.libs/) + include_directories(${backtrace_SOURCE_DIR}) + endif() +endif() \ No newline at end of file From f5ae5aa13e34d2ed879497f9c8cf5592a213476d Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 16 Jul 2022 18:21:35 -0700 Subject: [PATCH 016/322] Address timers being iterated through poorly (#646) * Fix timers * Update Entity.cpp * Fix timers Fix timers Remove debug logs remove _dynamic * I like to move it move it --- dGame/Entity.cpp | 26 +++++++++++++++++++------- dGame/Entity.h | 1 + 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 68277cd8..93fa0609 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -1201,17 +1201,21 @@ void Entity::UpdateXMLDoc(tinyxml2::XMLDocument* doc) { } void Entity::Update(const float deltaTime) { - for (int i = 0; i < m_Timers.size(); i++) { - m_Timers[i]->Update(deltaTime); - if (m_Timers[i]->GetTime() <= 0) { - const auto timerName = m_Timers[i]->GetName(); + uint32_t timerPosition; + timerPosition = 0; + while (timerPosition < m_Timers.size()) { + m_Timers[timerPosition]->Update(deltaTime); + if (m_Timers[timerPosition]->GetTime() <= 0) { + const auto timerName = m_Timers[timerPosition]->GetName(); - delete m_Timers[i]; - m_Timers.erase(m_Timers.begin() + i); + delete m_Timers[timerPosition]; + m_Timers.erase(m_Timers.begin() + timerPosition); for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnTimerDone(this, timerName); } + } else { + timerPosition++; } } @@ -1223,6 +1227,14 @@ void Entity::Update(const float deltaTime) { m_CallbackTimers.erase(m_CallbackTimers.begin() + i); } } + + // Add pending timers to the list of timers so they start next tick. + if (m_PendingTimers.size() > 0) { + for (auto namedTimer : m_PendingTimers) { + m_Timers.push_back(namedTimer); + } + m_PendingTimers.clear(); + } if (IsSleeping()) { @@ -1661,7 +1673,7 @@ void Entity::RemoveChild(Entity* child) { void Entity::AddTimer(std::string name, float time) { EntityTimer* timer = new EntityTimer(name, time); - m_Timers.push_back(timer); + m_PendingTimers.push_back(timer); } void Entity::AddCallbackTimer(float time, std::function callback) { diff --git a/dGame/Entity.h b/dGame/Entity.h index c804deaa..ca12b355 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -309,6 +309,7 @@ protected: std::unordered_map m_Components; //The int is the ID of the component std::vector m_Timers; + std::vector m_PendingTimers; std::vector m_CallbackTimers; bool m_ShouldDestroyAfterUpdate = false; From 9287e5bc4bd61fb469e90ef8c476d754a760df06 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sat, 16 Jul 2022 20:36:09 -0500 Subject: [PATCH 017/322] Split itemType enum into it's own header (#647) * Split itemType enum into it's own header add mount item type * fix whitespace --- dCommon/dCommonVars.h | 27 ------------ dCommon/eItemType.h | 36 ++++++++++++++++ dGame/dComponents/InventoryComponent.cpp | 15 +++---- dGame/dComponents/InventoryComponent.h | 4 +- dGame/dInventory/Inventory.cpp | 52 ++++++++++++------------ 5 files changed, 74 insertions(+), 60 deletions(-) create mode 100644 dCommon/eItemType.h diff --git a/dCommon/dCommonVars.h b/dCommon/dCommonVars.h index e941413b..c458b9fb 100644 --- a/dCommon/dCommonVars.h +++ b/dCommon/dCommonVars.h @@ -440,33 +440,6 @@ enum eInventoryType : uint32_t { INVALID // made up, for internal use!!! }; -enum eItemType : int32_t { - ITEM_TYPE_UNKNOWN = -1, //!< An unknown item type - ITEM_TYPE_BRICK = 1, //!< A brick - ITEM_TYPE_HAT = 2, //!< A hat / head item - ITEM_TYPE_HAIR = 3, //!< A hair item - ITEM_TYPE_NECK = 4, //!< A neck item - ITEM_TYPE_LEFT_HAND = 5, //!< A left handed item - ITEM_TYPE_RIGHT_HAND = 6, //!< A right handed item - ITEM_TYPE_LEGS = 7, //!< A pants item - ITEM_TYPE_LEFT_TRINKET = 8, //!< A left handled trinket item - ITEM_TYPE_RIGHT_TRINKET = 9, //!< A right handed trinket item - ITEM_TYPE_BEHAVIOR = 10, //!< A behavior - ITEM_TYPE_PROPERTY = 11, //!< A property - ITEM_TYPE_MODEL = 12, //!< A model - ITEM_TYPE_COLLECTIBLE = 13, //!< A collectible item - ITEM_TYPE_CONSUMABLE = 14, //!< A consumable item - ITEM_TYPE_CHEST = 15, //!< A chest item - ITEM_TYPE_EGG = 16, //!< An egg - ITEM_TYPE_PET_FOOD = 17, //!< A pet food item - ITEM_TYPE_QUEST_OBJECT = 18, //!< A quest item - ITEM_TYPE_PET_INVENTORY_ITEM = 19, //!< A pet inventory item - ITEM_TYPE_PACKAGE = 20, //!< A package - ITEM_TYPE_LOOT_MODEL = 21, //!< A loot model - ITEM_TYPE_VEHICLE = 22, //!< A vehicle - ITEM_TYPE_CURRENCY = 23 //!< Currency -}; - enum eRebuildState : uint32_t { REBUILD_OPEN, REBUILD_COMPLETED = 2, diff --git a/dCommon/eItemType.h b/dCommon/eItemType.h new file mode 100644 index 00000000..453e8737 --- /dev/null +++ b/dCommon/eItemType.h @@ -0,0 +1,36 @@ +#pragma once + +#ifndef __EITEMTYPE__H__ +#define __EITEMTYPE__H__ + +#include + +enum class eItemType : int32_t { + ITEM_TYPE_UNKNOWN = -1, //!< An unknown item type + ITEM_TYPE_BRICK = 1, //!< A brick + ITEM_TYPE_HAT = 2, //!< A hat / head item + ITEM_TYPE_HAIR = 3, //!< A hair item + ITEM_TYPE_NECK = 4, //!< A neck item + ITEM_TYPE_LEFT_HAND = 5, //!< A left handed item + ITEM_TYPE_RIGHT_HAND = 6, //!< A right handed item + ITEM_TYPE_LEGS = 7, //!< A pants item + ITEM_TYPE_LEFT_TRINKET = 8, //!< A left handled trinket item + ITEM_TYPE_RIGHT_TRINKET = 9, //!< A right handed trinket item + ITEM_TYPE_BEHAVIOR = 10, //!< A behavior + ITEM_TYPE_PROPERTY = 11, //!< A property + ITEM_TYPE_MODEL = 12, //!< A model + ITEM_TYPE_COLLECTIBLE = 13, //!< A collectible item + ITEM_TYPE_CONSUMABLE = 14, //!< A consumable item + ITEM_TYPE_CHEST = 15, //!< A chest item + ITEM_TYPE_EGG = 16, //!< An egg + ITEM_TYPE_PET_FOOD = 17, //!< A pet food item + ITEM_TYPE_QUEST_OBJECT = 18, //!< A quest item + ITEM_TYPE_PET_INVENTORY_ITEM = 19, //!< A pet inventory item + ITEM_TYPE_PACKAGE = 20, //!< A package + ITEM_TYPE_LOOT_MODEL = 21, //!< A loot model + ITEM_TYPE_VEHICLE = 22, //!< A vehicle + ITEM_TYPE_CURRENCY = 23, //!< Currency + ITEM_TYPE_MOUNT = 24 //!< A Mount +}; + +#endif //!__EITEMTYPE__H__ \ No newline at end of file diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 8ae6e93f..0772482c 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -25,6 +25,7 @@ #include "PropertyManagementComponent.h" #include "DestroyableComponent.h" #include "dConfig.h" +#include "eItemType.h" InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document) : Component(parent) { @@ -1024,13 +1025,13 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) return; } - if (type == ITEM_TYPE_LOOT_MODEL || type == ITEM_TYPE_VEHICLE) + if (type == eItemType::ITEM_TYPE_LOOT_MODEL || type == eItemType::ITEM_TYPE_VEHICLE) { return; } } - if (type != ITEM_TYPE_LOOT_MODEL && type != ITEM_TYPE_MODEL) + if (type != eItemType::ITEM_TYPE_LOOT_MODEL && type != eItemType::ITEM_TYPE_MODEL) { if (!item->GetBound() && !item->GetPreconditionExpression()->Check(m_Parent)) { @@ -1411,15 +1412,15 @@ void InventoryComponent::RemoveDatabasePet(LWOOBJID id) BehaviorSlot InventoryComponent::FindBehaviorSlot(const eItemType type) { switch (type) { - case ITEM_TYPE_HAT: + case eItemType::ITEM_TYPE_HAT: return BehaviorSlot::Head; - case ITEM_TYPE_NECK: + case eItemType::ITEM_TYPE_NECK: return BehaviorSlot::Neck; - case ITEM_TYPE_LEFT_HAND: + case eItemType::ITEM_TYPE_LEFT_HAND: return BehaviorSlot::Offhand; - case ITEM_TYPE_RIGHT_HAND: + case eItemType::ITEM_TYPE_RIGHT_HAND: return BehaviorSlot::Primary; - case ITEM_TYPE_CONSUMABLE: + case eItemType::ITEM_TYPE_CONSUMABLE: return BehaviorSlot::Consumable; default: return BehaviorSlot::Invalid; diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index 1fda5942..a7d3f8ea 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef INVENTORYCOMPONENT_H #define INVENTORYCOMPONENT_H @@ -25,6 +25,8 @@ class ItemSet; typedef std::map EquipmentMap; +enum class eItemType : int32_t; + /** * Handles the inventory of entity, including the items they possess and have equipped. An entity can have inventories * of different types, each type representing a different group of items, see `eInventoryType` for a list of diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index 6e8be6aa..53ff37b4 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -1,7 +1,8 @@ -#include "Inventory.h" +#include "Inventory.h" #include "GameMessages.h" #include "Game.h" #include "Item.h" +#include "eItemType.h" std::vector Inventory::m_GameMasterRestrictedItems = { 1727, // GM Only - JetPack @@ -274,40 +275,41 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) const auto itemType = static_cast(itemComponent.itemType); switch (itemType) { - case ITEM_TYPE_BRICK: + case eItemType::ITEM_TYPE_BRICK: return BRICKS; - case ITEM_TYPE_BEHAVIOR: + case eItemType::ITEM_TYPE_BEHAVIOR: return BEHAVIORS; - case ITEM_TYPE_PROPERTY: + case eItemType::ITEM_TYPE_PROPERTY: return PROPERTY_DEEDS; - case ITEM_TYPE_MODEL: - case ITEM_TYPE_VEHICLE: - case ITEM_TYPE_LOOT_MODEL: + case eItemType::ITEM_TYPE_MODEL: + case eItemType::ITEM_TYPE_VEHICLE: + case eItemType::ITEM_TYPE_LOOT_MODEL: + case eItemType::ITEM_TYPE_MOUNT: return MODELS; - case ITEM_TYPE_HAT: - case ITEM_TYPE_HAIR: - case ITEM_TYPE_NECK: - case ITEM_TYPE_LEFT_HAND: - case ITEM_TYPE_RIGHT_HAND: - case ITEM_TYPE_LEGS: - case ITEM_TYPE_LEFT_TRINKET: - case ITEM_TYPE_RIGHT_TRINKET: - case ITEM_TYPE_COLLECTIBLE: - case ITEM_TYPE_CONSUMABLE: - case ITEM_TYPE_CHEST: - case ITEM_TYPE_EGG: - case ITEM_TYPE_PET_FOOD: - case ITEM_TYPE_PET_INVENTORY_ITEM: - case ITEM_TYPE_PACKAGE: - case ITEM_TYPE_CURRENCY: + case eItemType::ITEM_TYPE_HAT: + case eItemType::ITEM_TYPE_HAIR: + case eItemType::ITEM_TYPE_NECK: + case eItemType::ITEM_TYPE_LEFT_HAND: + case eItemType::ITEM_TYPE_RIGHT_HAND: + case eItemType::ITEM_TYPE_LEGS: + case eItemType::ITEM_TYPE_LEFT_TRINKET: + case eItemType::ITEM_TYPE_RIGHT_TRINKET: + case eItemType::ITEM_TYPE_COLLECTIBLE: + case eItemType::ITEM_TYPE_CONSUMABLE: + case eItemType::ITEM_TYPE_CHEST: + case eItemType::ITEM_TYPE_EGG: + case eItemType::ITEM_TYPE_PET_FOOD: + case eItemType::ITEM_TYPE_PET_INVENTORY_ITEM: + case eItemType::ITEM_TYPE_PACKAGE: + case eItemType::ITEM_TYPE_CURRENCY: return ITEMS; - case ITEM_TYPE_QUEST_OBJECT: - case ITEM_TYPE_UNKNOWN: + case eItemType::ITEM_TYPE_QUEST_OBJECT: + case eItemType::ITEM_TYPE_UNKNOWN: default: return HIDDEN; } From 77d35019cc7258229a99934ed41d2efca48ccb88 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Sun, 17 Jul 2022 04:40:46 +0100 Subject: [PATCH 018/322] Replace the usage of RakString (#648) --- dChatServer/ChatPacketHandler.cpp | 22 +++++++-------- dChatServer/PlayerContainer.cpp | 26 +++++++++++------- dChatServer/PlayerContainer.h | 4 +-- dGame/dUtilities/SlashCommandHandler.cpp | 12 ++++++--- dMasterServer/MasterServer.cpp | 34 +++++++++++++++++------- dNet/MasterPackets.cpp | 12 ++++++--- dWorldServer/WorldServer.cpp | 29 +++++++++++++------- 7 files changed, 91 insertions(+), 48 deletions(-) diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index b84c3eef..4f055121 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -123,7 +123,7 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { requestee.reset(new PlayerData()); // Setup the needed info since you can add a best friend offline. requestee->playerID = friendDataCandidate.friendID; - requestee->playerName = RakNet::RakString(friendDataCandidate.friendName.c_str()); + requestee->playerName = friendDataCandidate.friendName; requestee->zoneID = LWOZONEID(); FriendData requesteeFriendData{}; @@ -147,7 +147,7 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { std::unique_ptr result(nameQuery->executeQuery()); requestee.reset(new PlayerData()); - requestee->playerName = RakNet::RakString(playerName.c_str()); + requestee->playerName = playerName; SendFriendResponse(requestor, requestee.get(), result->next() ? AddFriendResponseType::NOTONLINE : AddFriendResponseType::INVALIDCHARACTER); return; @@ -384,7 +384,7 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) if (playerContainer.GetIsMuted(sender)) return; - const auto senderName = std::string(sender->playerName.C_String()); + const auto senderName = std::string(sender->playerName.c_str()); inStream.SetReadOffset(0x14 * 8); @@ -407,7 +407,7 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) if (otherMember == nullptr) return; - const auto otherName = std::string(otherMember->playerName.C_String()); + const auto otherName = std::string(otherMember->playerName.c_str()); CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); @@ -443,8 +443,8 @@ void ChatPacketHandler::HandlePrivateChatMessage(Packet* packet) { if (playerContainer.GetIsMuted(goonA)) return; - std::string goonAName = goonA->playerName.C_String(); - std::string goonBName = goonB->playerName.C_String(); + std::string goonAName = goonA->playerName.c_str(); + std::string goonBName = goonB->playerName.c_str(); //To the sender: { @@ -720,7 +720,7 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) playerContainer.TeamStatusUpdate(team); - const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(data->playerName.C_String())); + const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(data->playerName.c_str())); for (const auto memberId : team->memberIDs) { @@ -750,7 +750,7 @@ void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) //portion that will get routed: PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_TEAM_INVITE); - PacketUtils::WritePacketWString(sender->playerName.C_String(), 33, &bitStream); + PacketUtils::WritePacketWString(sender->playerName.c_str(), 33, &bitStream); bitStream.Write(sender->playerID); SystemAddress sysAddr = receiver->sysAddr; @@ -936,7 +936,7 @@ void ChatPacketHandler::SendFriendUpdate(PlayerData* friendData, PlayerData* pla PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_UPDATE_FRIEND_NOTIFY); bitStream.Write(notifyType); - std::string playerName = playerData->playerName.C_String(); + std::string playerName = playerData->playerName.c_str(); PacketUtils::WritePacketWString(playerName, 33, &bitStream); @@ -976,7 +976,7 @@ void ChatPacketHandler::SendFriendRequest(PlayerData* receiver, PlayerData* send //portion that will get routed: PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_ADD_FRIEND_REQUEST); - PacketUtils::WritePacketWString(sender->playerName.C_String(), 33, &bitStream); + PacketUtils::WritePacketWString(sender->playerName.c_str(), 33, &bitStream); bitStream.Write(0); // This is a BFF flag however this is unused in live and does not have an implementation client side. SystemAddress sysAddr = receiver->sysAddr; @@ -996,7 +996,7 @@ void ChatPacketHandler::SendFriendResponse(PlayerData* receiver, PlayerData* sen // For all requests besides accepted, write a flag that says whether or not we are already best friends with the receiver. bitStream.Write(responseCode != AddFriendResponseType::ACCEPTED ? isBestFriendsAlready : sender->sysAddr != UNASSIGNED_SYSTEM_ADDRESS); // Then write the player name - PacketUtils::WritePacketWString(sender->playerName.C_String(), 33, &bitStream); + PacketUtils::WritePacketWString(sender->playerName.c_str(), 33, &bitStream); // Then if this is an acceptance code, write the following extra info. if (responseCode == AddFriendResponseType::ACCEPTED) { bitStream.Write(sender->playerID); diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index c5da3a7f..1517153d 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -20,17 +20,25 @@ PlayerContainer::~PlayerContainer() { void PlayerContainer::InsertPlayer(Packet* packet) { CINSTREAM; PlayerData* data = new PlayerData(); + inStream.SetReadOffset(inStream.GetReadOffset() + 64); inStream.Read(data->playerID); - inStream.Read(data->playerID); - inStream.Read(data->playerName); + + uint32_t len; + inStream.Read(len); + + for (int i = 0; i < len; i++) { + char character; inStream.Read(character); + data->playerName += character; + } + inStream.Read(data->zoneID); inStream.Read(data->muteExpire); data->sysAddr = packet->systemAddress; - mNames[data->playerID] = GeneralUtils::ASCIIToUTF16(std::string(data->playerName.C_String())); + mNames[data->playerID] = GeneralUtils::ASCIIToUTF16(std::string(data->playerName.c_str())); mPlayers.insert(std::make_pair(data->playerID, data)); - Game::logger->Log("PlayerContainer", "Added user: %s (%llu), zone: %i\n", data->playerName.C_String(), data->playerID, data->zoneID.GetMapID()); + Game::logger->Log("PlayerContainer", "Added user: %s (%llu), zone: %i\n", data->playerName.c_str(), data->playerID, data->zoneID.GetMapID()); auto* insertLog = Database::CreatePreppedStmt("INSERT INTO activity_log (character_id, activity, time, map_id) VALUES (?, ?, ?, ?);"); @@ -64,7 +72,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { if (team != nullptr) { - const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(player->playerName.C_String())); + const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(player->playerName.c_str())); for (const auto memberId : team->memberIDs) { @@ -232,8 +240,8 @@ void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) if (leader == nullptr || member == nullptr) return; - const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(leader->playerName.C_String())); - const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(member->playerName.C_String())); + const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(leader->playerName.c_str())); + const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(member->playerName.c_str())); ChatPacketHandler::SendTeamInviteConfirm(member, false, leader->playerID, leader->zoneID, team->lootFlag, 0, 0, leaderName); @@ -337,7 +345,7 @@ void PlayerContainer::DisbandTeam(TeamData* team) if (otherMember == nullptr) continue; - const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(otherMember->playerName.C_String())); + const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(otherMember->playerName.c_str())); ChatPacketHandler::SendTeamSetLeader(otherMember, LWOOBJID_EMPTY); ChatPacketHandler::SendTeamRemovePlayer(otherMember, true, false, false, team->local, team->leaderID, otherMember->playerID, memberName); @@ -360,7 +368,7 @@ void PlayerContainer::TeamStatusUpdate(TeamData* team) if (leader == nullptr) return; - const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(leader->playerName.C_String())); + const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(leader->playerName.c_str())); for (const auto memberId : team->memberIDs) { diff --git a/dChatServer/PlayerContainer.h b/dChatServer/PlayerContainer.h index b1e1defd..9216a361 100644 --- a/dChatServer/PlayerContainer.h +++ b/dChatServer/PlayerContainer.h @@ -9,7 +9,7 @@ struct PlayerData { LWOOBJID playerID; - RakNet::RakString playerName; + std::string playerName; SystemAddress sysAddr; LWOZONEID zoneID; std::vector friends; @@ -46,7 +46,7 @@ public: PlayerData* GetPlayerData(const std::string& playerName) { for (auto player : mPlayers) { if (player.second) { - std::string pn = player.second->playerName.C_String(); + std::string pn = player.second->playerName.c_str(); if (pn == playerName) return player.second; } } diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index ae8e7969..74d44ce7 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -2017,11 +2017,15 @@ void SlashCommandHandler::SendAnnouncement(const std::string& title, const std:: CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ANNOUNCEMENT); - RakNet::RakString rsTitle(title.c_str()); - RakNet::RakString rsMsg(message.c_str()); + bitStream.Write(title.size()); + for (auto character : title) { + bitStream.Write(character); + } - bitStream.Write(rsTitle); - bitStream.Write(rsMsg); + bitStream.Write(message.size()); + for (auto character : message) { + bitStream.Write(character); + } Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); } diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 1cfd7d4a..2e881934 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -497,7 +497,10 @@ void HandlePacket(Packet* packet) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_NEW_SESSION_ALERT); bitStream.Write(sessionKey); - bitStream.Write(RakNet::RakString(username.c_str())); + bitStream.Write(username.size()); + for (auto character : username) { + bitStream.Write(character); + } SEND_PACKET_BROADCAST; break; @@ -572,14 +575,20 @@ void HandlePacket(Packet* packet) { uint32_t mapId; LWOCLONEID cloneId; - RakNet::RakString password; + std::string password; inStream.Read(mapId); inStream.Read(cloneId); - inStream.Read(password); - Game::im->CreatePrivateInstance(mapId, cloneId, - password.C_String()); + uint32_t len; + inStream.Read(len); + for (int i = 0; len > i; i++) { + char character; + inStream.Read(character); + password += character; + } + + Game::im->CreatePrivateInstance(mapId, cloneId, password.c_str()); break; } @@ -591,15 +600,22 @@ void HandlePacket(Packet* packet) { uint64_t requestID = 0; uint8_t mythranShift = false; - RakNet::RakString password; + std::string password; inStream.Read(requestID); inStream.Read(mythranShift); - inStream.Read(password); + + uint32_t len; + inStream.Read(len); - auto* instance = Game::im->FindPrivateInstance(password.C_String()); + for (int i = 0; i < len; i++) { + char character; inStream.Read(character); + password += character; + } - Game::logger->Log( "MasterServer", "Join private zone: %llu %d %s %p\n", requestID, mythranShift, password.C_String(), instance); + auto* instance = Game::im->FindPrivateInstance(password.c_str()); + + Game::logger->Log( "MasterServer", "Join private zone: %llu %d %s %p\n", requestID, mythranShift, password.c_str(), instance); if (instance == nullptr) { return; diff --git a/dNet/MasterPackets.cpp b/dNet/MasterPackets.cpp index 96ad1b81..bf58d71c 100644 --- a/dNet/MasterPackets.cpp +++ b/dNet/MasterPackets.cpp @@ -43,8 +43,10 @@ void MasterPackets::SendZoneCreatePrivate(dServer* server, uint32_t zoneID, uint bitStream.Write(zoneID); bitStream.Write(cloneID); - RakNet::RakString passwd(password.c_str()); - bitStream.Write(passwd); + bitStream.Write(password.size()); + for (auto character : password) { + bitStream.Write(character); + } server->SendToMaster(&bitStream); } @@ -56,8 +58,10 @@ void MasterPackets::SendZoneRequestPrivate(dServer* server, uint64_t requestID, bitStream.Write(requestID); bitStream.Write(static_cast(mythranShift)); - RakNet::RakString passwd(password.c_str()); - bitStream.Write(passwd); + bitStream.Write(password.size()); + for (auto character : password) { + bitStream.Write(character); + } server->SendToMaster(&bitStream); } diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 330263ed..9e5ff8c1 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -546,18 +546,31 @@ void HandlePacketChat(Packet* packet) { LWOOBJID header; inStream.Read(header); - RakNet::RakString title; - RakNet::RakString msg; + std::string title; + std::string msg; - inStream.Read(title); - inStream.Read(msg); + uint32_t len; + inStream.Read(len); + for (int i = 0; len > i; i++) { + char character; + inStream.Read(character); + title += character; + } + + len = 0; + inStream.Read(len); + for (int i = 0; len > i; i++) { + char character; + inStream.Read(character); + msg += character; + } //Send to our clients: AMFArrayValue args; auto* titleValue = new AMFStringValue(); - titleValue->SetStringValue(title.C_String()); + titleValue->SetStringValue(title.c_str()); auto* messageValue = new AMFStringValue(); - messageValue->SetStringValue(msg.C_String()); + messageValue->SetStringValue(msg.c_str()); args.InsertValue("title", titleValue); args.InsertValue("message", messageValue); @@ -1122,14 +1135,12 @@ void HandlePacket(Packet* packet) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_ADDED_NOTIFICATION); bitStream.Write(player->GetObjectID()); - bitStream.Write(playerName.size()); + bitStream.Write(playerName.size()); for (size_t i = 0; i < playerName.size(); i++) { bitStream.Write(playerName[i]); } - //bitStream.Write(playerName); - auto zone = dZoneManager::Instance()->GetZone()->GetZoneID(); bitStream.Write(zone.GetMapID()); bitStream.Write(zone.GetInstanceID()); From c689b3d3d1a6af247c5c72da25162dc32a23b852 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 16 Jul 2022 21:39:13 -0700 Subject: [PATCH 019/322] Parent and Child Deletion Improvements (#649) * Fix timers * Update Entity.cpp * Fix timers Fix timers Remove debug logs remove _dynamic * I like to move it move it * Child Deletion Improvements * Check bounds --- dGame/Entity.cpp | 19 +++++++++++++++---- dGame/Entity.h | 1 + 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 93fa0609..a063b3c6 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -109,6 +109,11 @@ Entity::~Entity() { m_Components.erase(pair.first); } + + for (auto child : m_ChildEntities) { + if (child) child->RemoveParent(); + } + if (m_ParentEntity) { m_ParentEntity->RemoveChild(this); } @@ -1662,15 +1667,21 @@ void Entity::AddChild(Entity* child) { void Entity::RemoveChild(Entity* child) { if (!child) return; - for (auto entity = m_ChildEntities.begin(); entity != m_ChildEntities.end(); entity++) { - if (*entity && (*entity)->GetObjectID() == child->GetObjectID()) { + uint32_t entityPosition = 0; + while (entityPosition < m_ChildEntities.size()) { + if (!m_ChildEntities[entityPosition] || (m_ChildEntities[entityPosition])->GetObjectID() == child->GetObjectID()) { m_IsParentChildDirty = true; - m_ChildEntities.erase(entity); - return; + m_ChildEntities.erase(m_ChildEntities.begin() + entityPosition); + } else { + entityPosition++; } } } +void Entity::RemoveParent() { + this->m_ParentEntity = nullptr; +} + void Entity::AddTimer(std::string name, float time) { EntityTimer* timer = new EntityTimer(name, time); m_PendingTimers.push_back(timer); diff --git a/dGame/Entity.h b/dGame/Entity.h index ca12b355..85f992e8 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -144,6 +144,7 @@ public: void AddChild(Entity* child); void RemoveChild(Entity* child); + void RemoveParent(); void AddTimer(std::string name, float time); void AddCallbackTimer(float time, std::function callback); bool HasTimer(const std::string& name); From 0d4f86b20b9527028ae0ccfca2b207f4d9fe767a Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Sun, 17 Jul 2022 06:57:00 +0100 Subject: [PATCH 020/322] Resolve missing RakNet replacement (#650) Repair issue from PR earlier, crucial fix. --- dWorldServer/WorldServer.cpp | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 9e5ff8c1..d7a3b41e 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -817,19 +817,27 @@ void HandlePacket(Packet* packet) { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); uint32_t sessionKey = inStream.Read(sessionKey); - RakNet::RakString username; - inStream.Read(username); + + std::string username; + + uint32_t len; + inStream.Read(len); + + for (int i = 0; i < len; i++) { + char character; inStream.Read(character); + username += character; + } //Find them: - User* user = UserManager::Instance()->GetUser(username.C_String()); + User* user = UserManager::Instance()->GetUser(username.c_str()); if (!user) { - Game::logger->Log("WorldServer", "Got new session alert for user %s, but they're not logged in.\n", username.C_String()); + Game::logger->Log("WorldServer", "Got new session alert for user %s, but they're not logged in.\n", username.c_str()); return; } //Check the key: if (sessionKey != std::atoi(user->GetSessionKey().c_str())) { - Game::logger->Log("WorldServer", "Got new session alert for user %s, but the session key is invalid.\n", username.C_String()); + Game::logger->Log("WorldServer", "Got new session alert for user %s, but the session key is invalid.\n", username.c_str()); Game::server->Disconnect(user->GetSystemAddress(), SERVER_DISCON_INVALID_SESSION_KEY); return; } From fab8a1e982c7617e3dd4469804f9fe55c0003d4a Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Sun, 17 Jul 2022 07:54:36 +0100 Subject: [PATCH 021/322] Implement new chat features --- CMakeLists.txt | 9 ++-- dChatFilter/dChatFilter.cpp | 65 +++++++++++++++++++---------- dChatFilter/dChatFilter.h | 15 +++---- dGame/dComponents/PetComponent.cpp | 2 +- dNet/ClientPackets.cpp | 15 ++++++- dNet/WorldPackets.cpp | 23 +++++----- resources/blacklist.dcf | Bin 0 -> 16160 bytes 7 files changed, 84 insertions(+), 45 deletions(-) create mode 100644 resources/blacklist.dcf diff --git a/CMakeLists.txt b/CMakeLists.txt index 0817412b..caa61e4e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -84,13 +84,14 @@ make_directory(${CMAKE_BINARY_DIR}/locale) make_directory(${CMAKE_BINARY_DIR}/logs) # Copy ini files on first build -set(INI_FILES "authconfig.ini" "chatconfig.ini" "worldconfig.ini" "masterconfig.ini") -foreach(ini ${INI_FILES}) - if (NOT EXISTS ${PROJECT_BINARY_DIR}/${ini}) +set(RESOURCE_FILES "authconfig.ini" "chatconfig.ini" "worldconfig.ini" "masterconfig.ini" "blacklist.dcf") +foreach(resource_file ${RESOURCE_FILES}) + if (NOT EXISTS ${PROJECT_BINARY_DIR}/${resource_file}) configure_file( - ${CMAKE_SOURCE_DIR}/resources/${ini} ${PROJECT_BINARY_DIR}/${ini} + ${CMAKE_SOURCE_DIR}/resources/${resource_file} ${PROJECT_BINARY_DIR}/${resource_file} COPYONLY ) + message("Moved ${resource_file} to project binary directory") endif() endforeach() diff --git a/dChatFilter/dChatFilter.cpp b/dChatFilter/dChatFilter.cpp index 7f8187a5..fe8a0d10 100644 --- a/dChatFilter/dChatFilter.cpp +++ b/dChatFilter/dChatFilter.cpp @@ -8,8 +8,9 @@ #include #include "dCommonVars.h" -#include "Database.h" #include "dLogger.h" +#include "dConfig.h" +#include "Database.h" #include "Game.h" using namespace dChatFilterDCF; @@ -21,25 +22,30 @@ dChatFilter::dChatFilter(const std::string& filepath, bool dontGenerateDCF) { ReadWordlistPlaintext(filepath + ".txt"); if (!m_DontGenerateDCF) ExportWordlistToDCF(filepath + ".dcf"); } - else if (!ReadWordlistDCF(filepath + ".dcf")) { + else if (!ReadWordlistDCF(filepath + ".dcf", true)) { ReadWordlistPlaintext(filepath + ".txt"); ExportWordlistToDCF(filepath + ".dcf"); } + if (BinaryIO::DoesFileExist("blacklist.dcf")) { + ReadWordlistDCF("blacklist.dcf", false); + } + //Read player names that are ok as well: auto stmt = Database::CreatePreppedStmt("select name from charinfo;"); auto res = stmt->executeQuery(); while (res->next()) { std::string line = res->getString(1).c_str(); std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Transform to lowercase - m_Words.push_back(CalculateHash(line)); + m_YesYesWords.push_back(CalculateHash(line)); } delete res; delete stmt; } dChatFilter::~dChatFilter() { - m_Words.clear(); + m_YesYesWords.clear(); + m_NoNoWords.clear(); } void dChatFilter::ReadWordlistPlaintext(const std::string& filepath) { @@ -49,12 +55,12 @@ void dChatFilter::ReadWordlistPlaintext(const std::string& filepath) { while (std::getline(file, line)) { line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Transform to lowercase - m_Words.push_back(CalculateHash(line)); + m_YesYesWords.push_back(CalculateHash(line)); } } } -bool dChatFilter::ReadWordlistDCF(const std::string& filepath) { +bool dChatFilter::ReadWordlistDCF(const std::string& filepath, bool whiteList) { std::ifstream file(filepath, std::ios::binary); if (file) { fileHeader hdr; @@ -67,12 +73,14 @@ bool dChatFilter::ReadWordlistDCF(const std::string& filepath) { if (hdr.formatVersion == formatVersion) { size_t wordsToRead = 0; BinaryIO::BinaryRead(file, wordsToRead); - m_Words.reserve(wordsToRead); + if (whiteList) m_YesYesWords.reserve(wordsToRead); + else m_NoNoWords.reserve(wordsToRead); size_t word = 0; for (size_t i = 0; i < wordsToRead; ++i) { BinaryIO::BinaryRead(file, word); - m_Words.push_back(word); + if (whiteList) m_YesYesWords.push_back(word); + else m_NoNoWords.push_back(word); } return true; @@ -91,9 +99,9 @@ void dChatFilter::ExportWordlistToDCF(const std::string& filepath) { if (file) { BinaryIO::BinaryWrite(file, uint32_t(dChatFilterDCF::header)); BinaryIO::BinaryWrite(file, uint32_t(dChatFilterDCF::formatVersion)); - BinaryIO::BinaryWrite(file, size_t(m_Words.size())); + BinaryIO::BinaryWrite(file, size_t(m_YesYesWords.size())); - for (size_t word : m_Words) { + for (size_t word : m_YesYesWords) { BinaryIO::BinaryWrite(file, word); } @@ -101,31 +109,44 @@ void dChatFilter::ExportWordlistToDCF(const std::string& filepath) { } } -bool dChatFilter::IsSentenceOkay(const std::string& message, int gmLevel) { - if (gmLevel > GAME_MASTER_LEVEL_FORUM_MODERATOR) return true; //If anything but a forum mod, return true. - if (message.empty()) return true; +std::vector dChatFilter::IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList) { + if (gmLevel > GAME_MASTER_LEVEL_FORUM_MODERATOR) return { }; //If anything but a forum mod, return true. + if (message.empty()) return { }; + if (!whiteList && m_NoNoWords.empty()) return { "" }; std::stringstream sMessage(message); std::string segment; std::regex reg("(!*|\\?*|\\;*|\\.*|\\,*)"); + std::vector listOfBadSegments = std::vector(); + while (std::getline(sMessage, segment, ' ')) { + std::string originalSegment = segment; + std::transform(segment.begin(), segment.end(), segment.begin(), ::tolower); //Transform to lowercase segment = std::regex_replace(segment, reg, ""); size_t hash = CalculateHash(segment); if (std::find(m_UserUnapprovedWordCache.begin(), m_UserUnapprovedWordCache.end(), hash) != m_UserUnapprovedWordCache.end()) { - return false; + listOfBadSegments.push_back(originalSegment); // found word that isn't ok, just deny this code works for both white and black list } - if (!IsInWordlist(hash)) { - m_UserUnapprovedWordCache.push_back(hash); - return false; + if (!IsInWordlist(hash, whiteList)) { + if (whiteList) { + m_UserUnapprovedWordCache.push_back(hash); + listOfBadSegments.push_back(originalSegment); + } + } + else { + if (!whiteList) { + m_UserUnapprovedWordCache.push_back(hash); + listOfBadSegments.push_back(originalSegment); + } } } - return true; + return listOfBadSegments; } size_t dChatFilter::CalculateHash(const std::string& word) { @@ -136,6 +157,8 @@ size_t dChatFilter::CalculateHash(const std::string& word) { return value; } -bool dChatFilter::IsInWordlist(size_t word) { - return std::find(m_Words.begin(), m_Words.end(), word) != m_Words.end(); -} +bool dChatFilter::IsInWordlist(size_t word, bool whiteList) { + auto* list = whiteList ? &m_YesYesWords : &m_NoNoWords; + + return std::find(list->begin(), list->end(), word) != list->end(); +} \ No newline at end of file diff --git a/dChatFilter/dChatFilter.h b/dChatFilter/dChatFilter.h index e8ae67d0..5acd6063 100644 --- a/dChatFilter/dChatFilter.h +++ b/dChatFilter/dChatFilter.h @@ -20,17 +20,18 @@ public: dChatFilter(const std::string& filepath, bool dontGenerateDCF); ~dChatFilter(); - void ReadWordlistPlaintext(const std::string & filepath); - bool ReadWordlistDCF(const std::string & filepath); - void ExportWordlistToDCF(const std::string & filepath); - bool IsSentenceOkay(const std::string& message, int gmLevel); + void ReadWordlistPlaintext(const std::string& filepath); + bool ReadWordlistDCF(const std::string& filepath, bool whiteList); + void ExportWordlistToDCF(const std::string& filepath); + std::vector IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList = true); private: bool m_DontGenerateDCF; - std::vector m_Words; + std::vector m_NoNoWords; + std::vector m_YesYesWords; std::vector m_UserUnapprovedWordCache; //Private functions: size_t CalculateHash(const std::string& word); - bool IsInWordlist(size_t word); -}; + bool IsInWordlist(size_t word, bool whiteList); +}; \ No newline at end of file diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index d54087aa..3cfb4e8d 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -1193,7 +1193,7 @@ void PetComponent::SetPetNameForModeration(const std::string& petName) { int approved = 1; //default, in mod //Make sure that the name isn't already auto-approved: - if (Game::chatFilter->IsSentenceOkay(petName, 0)) { + if (Game::chatFilter->IsSentenceOkay(petName, 0).empty()) { approved = 2; //approved } diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index ef5b68ef..187ee12f 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -276,6 +276,7 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa std::string message = ""; stream.Read(chatLevel); + printf("%d", chatLevel); stream.Read(requestID); for (uint32_t i = 0; i < 42; ++i) { @@ -292,9 +293,19 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa } std::unordered_map unacceptedItems; - bool bAllClean = Game::chatFilter->IsSentenceOkay(message, user->GetLastUsedChar()->GetGMLevel()); + std::vector segments = Game::chatFilter->IsSentenceOkay(message, entity->GetGMLevel()); + + bool bAllClean = segments.empty(); + if (!bAllClean) { - unacceptedItems.insert(std::make_pair((char)0, (char)message.length())); + for (const auto& item : segments) { + if (item == "") { + unacceptedItems.insert({ (char)0, (char)message.length()}); + break; + } + + unacceptedItems.insert({ message.find(item), item.length() }); + } } if (user->GetIsMuted()) { diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index ae8f71a4..94792c91 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -192,19 +192,22 @@ void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool CBITSTREAM PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); - bitStream.Write(static_cast(requestAccepted)); - bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(requestID)); - bitStream.Write(static_cast(0)); + bitStream.Write(unacceptedItems.empty()); // Is sentence ok? + bitStream.Write(0x16); // Source ID, unknown - for (uint32_t i = 0; i < 33; ++i) { - bitStream.Write(static_cast(receiver[i])); + bitStream.Write(static_cast(requestID)); // request ID + bitStream.Write(static_cast(0)); // chat mode + + PacketUtils::WritePacketWString(receiver, 42, &bitStream); // receiver name + + for (auto it : unacceptedItems) { + bitStream.Write(it.first); // start index + bitStream.Write(it.second); // length } - for (std::unordered_map::iterator it = unacceptedItems.begin(); it != unacceptedItems.end(); ++it) { - bitStream.Write(it->first); - bitStream.Write(it->second); - } + for (int i = unacceptedItems.size(); 64 > i; i++) { + bitStream.Write(0); + } SEND_PACKET } diff --git a/resources/blacklist.dcf b/resources/blacklist.dcf new file mode 100644 index 0000000000000000000000000000000000000000..cdc64c2f5b245f4526974ab9cb1770fd8355b783 GIT binary patch literal 16160 zcmb8WQ*@ng+^rqkwyh>jnxsL4#)`&)c}=08B7$HbARxQY|MT@fpElkFH(YVzllBzTzeX_kifo?`EU;^FVlctFCR;Gt zVO*!NUR^kIRvaVO41_6+xzcPAR zI#^)SH38|@5H3U9xz%`P$Lw}BTEL+2xWxKVrYHRKYWIzS>kmVV^A?N%XRcP^;!i`I zvsPEa#fs35lm0ncQoploec61(zBGPt$yy_BB+&IC53NPMzg^zTd}SO4EHZ zjF{6jaIFXqQCJ|64;|3G@eqBj1NdTyy{SD+djC`g>uWglue-&yBe?MAbC!+;#Cx|C z6?W>qUjJwn=fWzHQOfFe8a)v%>=nQ(tw{)gc`Y#$9{h&0c}UOEzuD^BSoY~djX>DV zD8nRb{1WNw=SQfdnKKN9qy@+4$OXFl2o=(d@$PtXKaNervM(D%U{gxq2#$Lfptdo+ z&So+wFDpxKfGu`glWF4S#J6Y{5O0V|C|vzkd~FPgT|BC4WMjsFND_k-U|_y3po8i$ z!?qXu;~Jd;VBL4$g7+W_u$zi;krq7SKWQELFf<70!Ve+l3oaC-HMQ&|5L3$Cvh;5E z@e(zO6_zeT8Fn+?yDXPKG?9Cmg<5Y8sK1g$A?>tX-}Orw zeJ~#uwltVL+4b$BMHE7 z3OgaWj*=3#-BP&JuD6mm{S}eryCe?7_ABpFD?(YyUs-tS65;p<h8} zuIy3W84<*hXyDkGp0_!=1k93-znu#{=~uKeYTlB*ctLMn9ga^r6cGk6&S^vfT61um zxqF+)yUXzv299U>tx{sFemWS}ziN%iKF(mx$sN*53taJR<2a@|XCcdk3_ckbZ73nm zYg(f$j={+a_jM^4aob%b$JcA1^8yN1qD}3jH~8nEd4#sPCLxU`FAZn>;SZ5;O>M=y z9PB4;-=P}#_7Uj}rgRr$e2e1Ue72UnJKtzIEo@K&wsz@Y<>iCb1P;)?AN-ot_E4E1 zW(a4wB;arQX(0vv!sZs)8xO^rTb|IZtsJFf8xs9Vc*cjo_T<50elP@O;un zkvDeDI5>j?tSK7h7H-2_Ioc*Ns0;kd7#m>-7gYjIZD{0}b8_sRk0ZWDe@wh*HH&el zWzPtoX=ceI3hKVxI3EU0gsf){9kma#rh7D~ua7YS+%lE1GhTDFJ{>-~ccv#H12c$T z$s`7(XWEytr8}R7f_4zPZDrgQ0P~TX2KXIcWXM^PMWWw{({|%@r?&-q`P`+V0#TZ? z$E(^fiWpQ-sfjBQf_%;_UbBOuvr(H0Yx#4mpNg8>XC<0wz}x2EVL`?o0`ut7vyPtm zZb-_}S{#43gQGAp8JG}xXatNCwi55d9MZeSxm}K@XTpZ_!71mv&e5w%iexFp{!~P+ zmm}Xf;C;T2Q`MQqLFZQISKxhaWoFr6V{KvF*b!}4Sytbud*y&3K?Il|%-C;E$(Ia} zN@IE8R$!%Lb*|AEGvYWYo9ILz5)bOHi^HX z@bcTwWRU@AY?O$bRZ6JQNHYU*S^d-v~_Dcmn-jD#9`;VJ*QOSp__;Vr_HCO~nH z!LR>Q{lI&nYR(z#s1`0LoBRj?I{~)ZC1MCx!z!EVApg+HGiQ6{z6KWF<%X(OY-=w| z4cQP;8kcvT7q@~gd7PT$`;*ifC9}pQx8VWV=WSoBsKRbIuV4H}qUQbrODx71A8zjN zAdNb5#<~Xbt-9&OkjyK&m}EB?$ib@>JPcuzM6TF_x%5<5fyyKk2(4u)m{>xOUFG$2 z-ek?aS??!EK3BG77%oUb*G-m?>ScOUCBk>k)0s^ltV_xMvi~!5W{~YBbVG6uXvOVI@bTEk&V>e~vpmpu zy0m2x-N%E!EB<*<)hjeS)Q=i<6SvLWV9<;EX zjh%=<>CmRjOM19|N-`WAtmrgRUKQI~nCM#z`A3@2`x9ms=<`C(0i14`mLk)+YR^af zO)VpN3bA|uYwQ!}lwodc2Cq2PeVbLXYhSb&9u2TZ0#W4>$;!OKedNHz?omGD5Pf(} zgs_{l=rRZrFF@Kxe^(7YWqOzydyCAw%LC3)YIKBLpdABXlvA}$N`Hb`7TATNCpDPy z?1b80Eyk)R-}KIic?Vs&%e~`35QLFNqtDUZQX60Iry}dg589a?fViMl6V87MrL_J| z`Un#25p#C4m25TUne%>Iw&+knhhD_7dQfJnHm((hy7NxyaJndxy74(q+kX!@z@<1Y z_@o`D5UV8bwN|OhpVV)+Ed=OETJfT37Ox5rJv*yEkIZ@9{~%(|_>2AOVzR zG_C)})&KC7o8?)lb9cliDM)5RuM>G&;5+o|@XJPJ!w(Z0YGR+R@nn%h3@X>1&Mp_D zuE&vth?=#X=ExTrX2Y(0Zyz@z&YxT7`5mn20f-$!O480EbTwEdCriU~#a3+%lo&EH zPS`RNKPKzssp3u&u76ul1y({TwJ6z-3QzfeO$LM5a+|YYy zFE>xF(Y{~4nzJKkPzo5HO?~Kp#c+o~c4gp+rx~f*S}l%pSU&a>VzUy-e_kYPX~A5y z0w|@reW5&_Cjl_I7an8ZL(J}c28hd1+D*%# z(_j{Vxr;6`eKG8F1(PiII1D=0(K3UGt~IIqu?Ck}3-FfDckNyyq_YN$u6o#AfJiqD zinSdz32GiKErqp*Cj(#}oNBf;%{>yXrE)nlL*Qc72dY!so%%C1)dTTQlNJ8VqXnWJV zDM}@j7Pfm7#12B_YlC*60VYBW9zE5k)&MN( zQx^C0u!;pJyBC8Ckrg=&FiH$YaYkR|ydt8N^|}6wF2LQSNs$aIiN@eSi>r{LF<8ZX z2%*gGM<)c@q&0n+TvGFm{@*030%0)jOXKOQpI&pD{fRg9@UJ(W{;0l+10SqIVLzHY z3zJypd-M$~MjND~YYxFE_MisPTSWpXyDtTjyvk>14?$O7tu=j4Fzymc)N{qILT7#j z99@)Ye9xL#7&1ZYD{?K?>YkKi;&XU>`B3@Nzm6+~$>MJPr~4dWe_E#LJ;-GjO8Stc z=%}qQKr?4XnqT<)e_0u>?TR~gsWQy(a?mt52V-P-1?!E+Bmg?Ok@OUa^Q!|C%onrz zK0R~;5G8iIK-+F@lroeIyki;dxDOY??4egW7NE+9CIb(xS)?uMueVV`7#Dz7$NO@R z)ZnNGer>M?Z2{N-Ctqp&c{<)1xDKlYHu_BL&bep36}fT01H5R1-(GeaVgQJsxX2~R z`qIl6SWeg-0lA$;h!}(gPJ#rmeDSMC7MczB6h-9zwC$P8^_1R<_gAZgGK)p!0G~$0 zzeW3EHAz=yI@dP_B-r!AGpx{)oPx zi4(71R3$@$dHA7Tbjc-ul|M3mP+@frrq$11!{mGpn~Xz2n~yj+#R*B-NwdS@kUNQ{MO5j*e$jz zm|JK{NBQ+Y1|u&2W;|@ABTVPbxx>d+k{j#W&Qc*PDt8+?gMC|dIXl53iPlMqakMT_ zkFI4I-$L^#NW1eiNG<7Vg;QNmU)lvPv-F4Jfx;8dbK?3 zx-}mlfb}N=<@@7mp_ErhOy zUx>4<1`W$>Cyg-3*L|o2o8v-;Ef$!YNTq^v1*W!fNkZD^4+i^$JX7+Ebd4VIW9(kL zd{COmOhS6FC2&5&FkI0f`8qUAgUu}p2R=bDb}Sf9H+VtQ%~Dlp!kuy_LHz0*b30E4 z5^t`YmAaCm%DyaBB@$2Y=rx-U6KcZS7Fk{sQkiFX2F9)!4ZpmO%k|k1(g={sa5DLP zkH{KgJ5_>ZP%7r z?;sMT4O5&n>U~mM6Frxzj;vAuAq!P(qaR+uvi(5Ow&6A4BheQ$IFBEXj5dRpOYy=| zDdBFfzfRx_?a==ctW~78c%l_7pGPbT1p_UTm8Anv#|I-(H|hiupuCps&x>DQ*bail z%fOCThlH0|zp@6hV5%2?Y9sPK>r^dQDDpfgJ^&2l8T|dEe@+9isdE*-Sb#o0sS*JPgWcn2UG+Xhdr#?UwJ2KuKZ z(98z6pJE*4hJ(_{caA)$hZ$m*eT@_#sV3$_cAsit>*|d6!4)4&fpPpoUjAIEwSSAB ziKG@?sWHz8gr-C|5S2b>5Yibal1959e>-L3Y*h^1v+HxZbbwv(<$XmLy01KLVtqwl zCo_uyft^N^p7D>pKGYjnO#S}G4{twH64KJ^BRS@jN}E-4r9O$4|9@Ni13B zT%2}VW-w3|`WVe1G0fy_O?vI}h2Uy=h6JBJ&3F5r&JS~?W2f1%I3)m0X{mFvn7iTT zXyX()7VH}2yHbdu$cBY@N^2G<>;(n2eAaa|Kawptb!mo9yFu>ZyEmyqD?F|g zCZwUIoH>)!!%pwzy%8kK%+~AUW--4FQ(_}Lx)5cfjHjE2<^(=*lVC9iA1aQmKiKG9 zg#?xB*f+Q*v3=5@k(Vjj4X5L+~gb)Wz}lDj^71(+yH9^nGsbw|H=bwG=x>Si3oKw z{N*!SM0Pq25CYRypIvHG`nz`92L^g#qh+%HyINs4GC&6LbIU7wenx+}0HKc8Bra>DF-2ZND0nW)p>mwXWSrIvH0-1+KS!`MSzC@Ibb! zuo1S>bNp4Dm&C|{T88GG&1CiuSpdK>yT&{$?1lc&Lu_Qx+kW?erY46+GsjbaQ|~V_ zKgJKN0`Gs&{f5fv1Zd@e4NanTIu9@cn>{KoPx&68%JWULfTnq80XrTIQP@2`#~X-s z?vqDsJ$pF)ivmqOK#T5I`l*_b@rr{#V(Bl_o&ebp&!u=Uay25cuxvC;3WSD=+9>GequgQ_HOm;JK{U)EfM5r zfz4VBZ48V@E`O|k5F+;uhoZ;O6_-DD7RRz8Q~}$XE!Q+YP=6U5Woj001;%zAt}uX(6>~^CEh}sCf(h!x9_LLpucjNHI zR9(piT{at!6CmEF*Z?XH{7yWP#xU6+@JOSk+#EumA$v-3=XY-Zny@wPOzP6$)1lM} zKF}tL2)oHvfGBtXVa<|RMuNf+Em1-!#yI4aLXUi>swl80vYK1>&NI*FBrjTrwudiv zD1c*$nWHk51uG-vR+@QoYnvNYBq}WaVA${}dzBUmUP#`In0y2;f4{@5G|A1IINsSa zaP%#cf>3$|y&!fcRFA8b;&MvkkE_pU!MO2RiRVeq`A)j?mlqlDioM5<=z@-&_o&UY zxgqu%=Fix*W)h8n(xZUD{vnFT!PCOU_@S^(ek@ghP$`tFHLDHVLPt|4L!pJt(B|%n zpXp$kZX(Nu*$}v|JPN;sr1X=R0iqGHDYkuJ8mPdiz|a-QC#PT_a~;872HDcRC=Z4q ztoRFK4ubMMy)Is@cO%joN~!GaGhOP0io5-3#(@JtKHRj-QH1YZgWMY?{oSLhx!~8- z!ku@-ZdY^nt}Yv4{%HRd$5I?vSp_Lb`X!HgpObrfQ;^$%nFrTTl@75?121GQ z$0Oc-zE&TFn{d5A=#5Btis;WXQMJl#LGA0T`&x?dE{ti|qVM`QgnjUgwn?QcQAM{1zpMDw3Hba}IzgFL$j9i$4yA zIc=5ok&CVhTB6Kzn+D+M3}$^=WVWqyW4Vj zyEt?@+3?WVuDz0rx`Ua6Uq^Td-YbT6bWj=nD?|bsP2FYPM1>%`1p&oWl}8p%fuo`r zg|lWX>em2MvK=+oS9si)HqAhbK;B_x^Mrp~>38qrseK<+;X{6-T;On5;w1T90Sd z692*#x6F#U>ruB3how%9L>JqkB@tl5;`=iNz^|qLxk@OHA>r4L= z!@-4I9MX?AGseXLjeFwQ-mr;b-pn&Kw$U`wM|OUS)Mg|31Spq^Ama!$Ne->bRo*As zEIkWHjQGcOzb;PWzuQb7v@?b&Mj_u_N}Q{WED@?e_I^yN_fvUYQiL|s{egpFe?T{d z5;1a)Nt@@~Y*-sXZou35Wr(L_>GI1 zzhgeS8S<pwdd%ooRlkBXmG*b~&7kCEnxU8uL6{Va>U2t=2J?uDJ6(fwt=j zyC(2_(ai+^kXlz*Jtxm4iG{mbve`j&r;xpRX@sXK1-W*_Zlug!^`PJp5@FU{7tH2(^RB zXd~ixD}B8uZFlH+!Yq2*Q$?D5;&Gjd;jMS5mmpUXfhq>RCzLMC#W7@@vVHv5eZm|U z)l7<6O8>8WR&I;*x8&2|V4PnGIk#fB>y!>ELoS~ep7CdhJt734Jh@s5l{&e zhdb+E;Ml5(WL@HEMRAQDwam8!cyXXk9F*>%x6xRy!CllvX-NI;mNFS>v+^VYV0+Xg zoS+4|Wa^q`*&gcwPS%y#3B6Uk1I$;fgRa9ISogfty=sI8;f~_54vqf0QzTAhV}%)043wHH}R+7>)&ue3(boV;BzVIK`;xmRMb}c!(mReAIA`T7`{dTPG-$>gWmN zl;Dfu%ls{jH%6ky=&;iP9DSMCcY{y1y)C0)BLe&*FxNGrL}Ks)+k zL~AAuD(B~#Ai~p^K5CuvvLcV|GfviQ%yZt_+I(E{!n7$S?YlC{NRTd$(3n$s^O=b7 zaf+!Mg$5JLsOnS^IB>tV1u|CJQ>F#lktW@5E-wUEg^7QYt6qpt(7euya~0K~3Z~x% zFUd4>fUF~=7Ipk(a)pGAc*<5!Q;fNA;_?LY#bD>9WYb{(^f+0f#WV9=;gpHcGYxcg)bu=D>EoPWl-_73HY-sZVbxwa+xs8%Bvi|#mmdy z;XUVZe-Uy*>%;saJJO9bua^zLti$offgRPJ})7gy>Ur`uftK+mxL*Z{t zmXmOY|D|kw^EY}ji-DQgfZ4Op&$tlozDy|pQtR4<-)*2H6&goh%idX@ZRgM3S6;oY za7YH?ixLn^j`Lr=37P_q6BnNuhlCZcVq$ACqmhr|M=S1w`{t%69^H&3P!UYhD)O6m zjup8}^G&_4&ru%MKj1MnPz7`O9gI^4A+sMlX zVQNnxG`%m^%cXfcO%$a8@!?|b=Qk{@S(x4ripE^h{06@=MU^QrY--~Ws+2`t0|bQK zbO+Q9Ki-jb6wje>wd!v(+F|R`U>7yhYaW&-ym#nbVx;sS*#YqzSKq{&6YaAa2}s_e zL_cuKI}I}T+NoA@f^cc_wbjLHXYSA%bdP6Ts;^Nl)U(Y$L4$P*a(Xt!AEQVkRlbiR z5)gmL+@o`{f@_-5N2Jeg1@`7npWcq5;8ov4+f~;zlqhSwC*|I1qG-Gug}rx4g0w91 z5DM}NDnaTxPK4)`m(T4%5(P~R%ieI(l(BC`$GZ2O;f?r0Fq!&0L>_k9eQ6`vmQX@C zGvi6oH&xD-WXh-Pb+(yU2Iv-HaQ>!0bB39qey1IHLpR&%D6AQBH>m8aH@YdZngWnd zkc*!*eSn(RVvCrK^mcBq=9^c_#9IcyrX;mOZ?-z;Gz&$UMrb<*p~MLFl^$PzVk{wR z#LJD%4>uh{Fjy)>K29)Qv}(BOm})p&e9248zwE)RXxkk|^m9bfmFsRh-|UL9$!*73 z_G|=PEMc4@h2L(xwod^pAVBCEZ( z`S$SsptLfl((oG^u9gfVE%9rKJmosi7i4R5f~~_C_~iY#kYlQjhzO{B!(-TVGF)Z8y&!fE$GJc zpX@A@3erKd3r&;8NxL9*6Vh*=fAo{i%b3|on30O=AviqCvn%8;fE;bjn4ii^^=53O46^5T_%rR3-$3A<=>a1ZVQ&V0f09!47|Iw ztbd1Ebxr)kqfSh^E-`i9*+fp&Loaice!QM6;G5K3dOR6uz(0zZxTn?PvO)!{?1Axa zqJ$s5x`j##JC3j&Z4!uq`_2Zcwm=AJpmiRyw+_)iqjs6LxaE9fh?T6wX-&qPn6_2n zip7$kgE31v;MW`sKx-9p*a|kvIlymBOV|@Y61Q3B?men1XP!0Mv}D92C?nq5-mQ_6 z4EqlEvO0`{af|x)$Pu^3(oRJaT z&W_q4y{MCgn!(P4UcT$Bf8&^BR!7FW7)+!bqtb6v{eF5+BnoNfAYE9v_HMK~Ykd9g zc#`9&0eFx{=`_0Y2til6zMNSJayv>%>Ou02mn?eG*IM7H0`J>5GxO7%UN-fxubs$> zh6#x6jTUOPnynJt!s{B-4OCeNN@5T`7n1&*?{)EmT89i#xI9!1q*@p;#0^p+5xWacP$N7of_4u)}cy5mlh8C2&DcSM}aR@@>?F z<1jw@q@*_19bU$w%k-=b&HYqq z?liigm5kxi!c>TE;_;{cVhvn0St=RGtTca*>xRAgPBg6i@c!<;`SqkSa)41O2m2Zg zE?hB+_Ile2{N{T#tt0mLJqGPzvm(|*iDXxXK?g~~$$ANid;vMQ*o25Q040J<-aQ`E zKI}U~D|O}h`y4K=cPztA#^KH8P~JO0BB#!OS2vThc8zGveHA79$J^idY;?cxtK(O#|6A%NHy0>9v-W zp!HY&p=q}C>Xl91dMGqkIK?T$Rq0e#TV$j`0k#HCfK|x9-3r#)^+iB zG@L)hU7d}r7IfEBudJld&0uobbX!^DRr!NDSB`Z(FZA@B)dm>0d$KPpK6}a4+R^j- z8y^Y#MH9=YB!PCPcbDuJ$n;Gv$YWw&;c!^XX)F0PVXwzA7TithaF-LEj_s&YKw zN|oD?e;!G8jyiF{$G5p>_6u(`MRwJW7zBI@&4I5bYDnJ!s%2&DaRN76eKElKUWd}8 zFa(NkaP5iMO*vx9xHRoNp(iv9S56oo5@wa)q=**#lj;jE?x1YcH<ZNfK zu<>6Ena+UMo|7PCM8O-JxiDQfQN92#uaT#=tjNIK++wbezUz zve#~Q@Fi|T?9gB*j0L}`Hv4?QW-Q6*;-s#Dy38yP33Pz)qRw!z{^DVVW9J!zN>yR} zgpePB_h8d%i1&Q54)-s$)p1_@eMFVw3vLw1GH#<{s~xG2`dX6Ik48A!kE}D^^bq{Z z-hbv#tB(e>n~pq&vnIF^HZ4tp(5qmF(;UETr|l31C`pZ`8yQ|OWls9J-En1+3$EKU zYRft0zfpRux;O5eu!E2-5YTrpF?|VXzbYyiL>TOwoGYal!nCLAHu(aI;Ga;H6#|Ob zuOGp6m59+YCtKPg@+^18kIY2RBII1#!u?`O)BK>@YC3otf_F(T*Hntag4WF$coHCC zQ4adm@Ho<&6Rl!RlpYLCcE|eK-R!o*6qnwta*U&`<9R&h8hzT=vFT7y>gvhxjkjy4 zrV)q{N`H@Is@y(WO>RE0rFK>(YMEY%8lYpP!8ui(>IwGni`k8$?NrjrRwqyGa(6kd zCX7JCJdzOr9KIQB;wqZ9dA;VJf)k|kM$bAnVLAKu=8lZ#JS#GiNlXO>$RDcHu6x$ytCg?rNQM9NcXAZXj1494ttXZ~xK0XQH>KlcHubZ|@qz^xtQr@DEIanYvO^Eigfw;fM-gpe)yTa2dS<7lbyF1BX<9 zSgHAuRLD}%pomY2!9InrOZaxuVt}XGBBjkgm8FC598&0MC%Q@2n7>^*`n$>Yy_*Q; zt#bdMqD;B^xcFU`uOGkJY&r8R?j-{cKNUB*>q1s(`v*ZQeXBR-D1hyA&u{a~-9Coe zZW9Z1q5D4Qno&Pr=gLgegFZtVCkb}S;r_LOtJ!WRG;hZApTJnR?n|?6#Xxg~HGKS6 z*aJAJ6VnOHv1z>0MXHc&awP_)uDkzglfPx>I<&jKUNEp!r6w+qX$3PeG?lJt zlBi90ySIYw1R z%9+v`-gSDDZzsEh!-u1&>zuw=CJYUM4@E}fM%DbX@b~iM_w#aS=Z?m@2Y*33 z8H+mmIm*>zp&J`a#&v|M%FYP}I~!7>A``f}aU%)qwrMopPoldeC;guA!k?&?5IJ=H zdo3{f7WQ8xO-`J9!AcTlFP*SA-hZ03<3o%{Cs^mfBSwkzw32o6Thf$HQ!`j~F!Ae| zchM)QvFo?pAm!(hv$r42@vT4Atcg;G;j%Wg$%7wOdLYzxjew`CtJO0jr+jEe9+W?l z&PSP_+GlC#R&J|S`W^M|f2}>5)LrYDBv9e7XE|6<0q?h@p+DpgdS(Hb`|}Q^-npd% zwYSh;PBj5WrlB5so^Of_)fH8MMCBFn9VHBkQ6BVTc0^p_Q`6mMuKbi0bnG-aa~RU7 zwC;{RJfn}c`Uck7^W(<4grh}vEYOw{mXN33D3S@UnVq!g}{oZBM9xCs$5 z17n>x8hAmAXejYau04ekNVylBY0W636@Xm|8oD7pP=a(Sxl3OcZz7UYop+9f$EWY+ z!qqGG-lHK$p~KO8w-2ZQrQB3NW9a_i=t~iri;}S}CZQJU=oW@=xw9%;wEMn#c}+(Z zmWV;G)$zpKNiL5vl`BUaMJOZOC#6Lp-Qjt^B#hO0(7skSGjix`Jj z?|iS^gpIfF6m$=%|vsK*1VQ@pZ& z#5E&|)%uWxH9du3^}EOY5h1|y)=kg#Mc2X&+bIdu_{puu#-(LXYwx=qCBcWvWGq_U zZ@9NX9|Fh5u4w3%l%0>%F39gUHsg{Z1{`7+B}vw*ww$~(v8K=<&LM6%d#U211=fGE zS<+|=qsJ-kCvvI+=bb2gb2*T1gg&ynjG`S|(ZQ1`&cdI}woV96^ye26ik= zy-o@TGDIv;hrL?X0%j`BG#|6B_+|0MC;8-MVw8DhHNc(bhh(urdm}m3H7vGuchFJg zq|lQ`AbE@cTF3yGl4Wn@Pl*d=+%*uW0}&Py|Dkm?Va;P`t>Y^!iikzr=lJyP=NS2W zXoxLNgc@P$7gS+&?9eO4^&tM(rW3x`dKvkwrYrBQ^k-K!lsK3G`dI`76@I79ZEumW z8{~?DRBe}jgul({Lkoq|gz&1UwwLxWs)vxK0r=;&ujw$CG9yT}hI0awBuVNYw2<4! zi_B=^IKlx!9e9EEM7v$1H(#^gMe+=Gaty_QUDCfhBVb?j?~VxA4gJ6Fh5p?M0lOez z4+QLhfc+1!`}wcE53uw3-*!F!+nxv5@c_FRVCMqtRe&7_u-gFk8UOAvfc*rpcK~({ zz^(z<1pr<@;OqbE%L5)c;Ew~|IN*f?UiZHqH|PKLumR8dUvC=lrT@#52K;Eii~iqy z=>PJd|Mj2$^_~H*8Ss<;%QFVNV!-zWd|kk|{V%^3@MQr{_Fpd+@L>V(^>K2l%(& z2YPs*Z~wPX2l{iMp9cD5pbrLmT%eBy`c|M%1^UZ>drP2)1bRoHUj%wWpdSQ!K%nOW zdMlup0{SDMzXAFhpoana7NBPVdJUk*0D6mm`w5_z0CN9-bMk+4Zy=ZcH;)E#Um)iN z^4ov&)&DI|1#(g#_XP4sAZPqHPXzKpAQ$}KazG$w1M)K~a|K=J0<`zIs@oygSUpd5o Date: Sun, 17 Jul 2022 02:35:11 -0500 Subject: [PATCH 022/322] Framework for GM's and helpers for mounts (#651) * Framework for GM's and helpers for mounts * docs and spacing * whitespace --- dGame/dComponents/CharacterComponent.h | 17 + dGame/dComponents/PossessableComponent.cpp | 3 + dGame/dComponents/PossessableComponent.h | 17 + dGame/dComponents/PossessorComponent.h | 18 ++ dGame/dGameMessages/GameMessages.cpp | 359 +++++++++++---------- dGame/dGameMessages/GameMessages.h | 30 +- dNet/dMessageIdentifiers.h | 2 + 7 files changed, 281 insertions(+), 165 deletions(-) diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index c7706325..009530c4 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -179,6 +179,18 @@ public: */ void SetLastRocketItemID(LWOOBJID lastRocketItemID) { m_LastRocketItemID = lastRocketItemID; } + /** + * Gets the object ID of the mount item that is being used + * @return the object ID of the mount item that is being used + */ + LWOOBJID GetMountItemID() const { return m_MountItemID; } + + /** + * Sets the object ID of the mount item that is being used + * @param m_MountItemID the object ID of the mount item that is being used + */ + void SetMountItemID(LWOOBJID mountItemID) { m_MountItemID = mountItemID; } + /** * Gives the player rewards for the last level that they leveled up from */ @@ -579,6 +591,11 @@ private: * ID of the last rocket used */ LWOOBJID m_LastRocketItemID = LWOOBJID_EMPTY; + + /** + * Mount Item ID + */ + LWOOBJID m_MountItemID = LWOOBJID_EMPTY; }; #endif // CHARACTERCOMPONENT_H diff --git a/dGame/dComponents/PossessableComponent.cpp b/dGame/dComponents/PossessableComponent.cpp index 1d721466..8190b9eb 100644 --- a/dGame/dComponents/PossessableComponent.cpp +++ b/dGame/dComponents/PossessableComponent.cpp @@ -1,10 +1,13 @@ #include "PossessableComponent.h" #include "PossessorComponent.h" #include "EntityManager.h" +#include "Inventory.h" #include "Item.h" PossessableComponent::PossessableComponent(Entity* parent, uint32_t componentId) : Component(parent){ m_Possessor = LWOOBJID_EMPTY; + CDItemComponent item = Inventory::FindItemComponent(m_Parent->GetLOT()); + m_AnimationFlag = static_cast(item.animationFlag); // Get the possession Type from the CDClient auto query = CDClientDatabase::CreatePreppedStmt("SELECT possessionType, depossessOnHit FROM PossessableComponent WHERE id = ?;"); diff --git a/dGame/dComponents/PossessableComponent.h b/dGame/dComponents/PossessableComponent.h index 5eefaaf4..a37b6e34 100644 --- a/dGame/dComponents/PossessableComponent.h +++ b/dGame/dComponents/PossessableComponent.h @@ -54,6 +54,18 @@ class PossessableComponent : public Component { */ void ForceDepossess() { m_ImmediatelyDepossess = true; m_DirtyPossessable = true;}; + /** + * Set if the parent entity was spawned from an item + * @param value if the parent entity was spawned from an item + */ + void SetItemSpawned(bool value) { m_ItemSpawned = value;}; + + /** + * Returns if the parent entity was spawned from an item + * @return if the parent entity was spawned from an item + */ + LWOOBJID GetItemSpawned() const { return m_ItemSpawned; }; + /** * Handles an OnUsed event by some other entity, if said entity has a Possessor it becomes the possessor * of this entity @@ -95,4 +107,9 @@ class PossessableComponent : public Component { */ bool m_ImmediatelyDepossess = false; + /** + * @brief Whether the parent entity was spawned from an item + * + */ + bool m_ItemSpawned = false; }; diff --git a/dGame/dComponents/PossessorComponent.h b/dGame/dComponents/PossessorComponent.h index f202b907..a81868a5 100644 --- a/dGame/dComponents/PossessorComponent.h +++ b/dGame/dComponents/PossessorComponent.h @@ -36,6 +36,18 @@ class PossessorComponent : public Component { */ LWOOBJID GetPossessable() const { return m_Possessable; } + /** + * Sets if we are busy mounting or dismounting + * @param value if we are busy mounting or dismounting + */ + void SetIsBusy(bool value) { m_IsBusy = value; } + + /** + * Returns if we are busy mounting or dismounting + * @return if we are busy mounting or dismounting + */ + bool GetIsBusy() const { return m_IsBusy; } + /** * Sets the possesible type that's currently used, merely used by the shooting gallery if it's 0 * @param value the possesible type to set @@ -60,4 +72,10 @@ class PossessorComponent : public Component { * */ bool m_DirtyPossesor = false; + + /** + * @brief if the possessor is busy mounting or dismounting + * + */ + bool m_IsBusy = false; }; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 4f5cb1f4..292afc71 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -147,7 +147,7 @@ void GameMessages::SendPlayAnimation(Entity* entity, const std::u16string& anima PacketUtils::WriteWString(bitStream, animationName, animationIDLength); bitStream.Write(bExpectAnimToExist); - + bitStream.Write(bPlayImmediate); bitStream.Write(bTriggerOnCompleteMsg); @@ -427,7 +427,7 @@ void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const System LWONameValue extraInfo; auto config = item->GetConfig(); - + for (auto* data : config) { extraInfo.name += GeneralUtils::ASCIIToUTF16(data->GetString()) + u","; @@ -435,7 +435,7 @@ void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const System if (extraInfo.name.length() > 0) extraInfo.name.pop_back(); // remove the last comma - bitStream.Write(extraInfo.name.size()); + bitStream.Write(extraInfo.name.size()); if (extraInfo.name.size() > 0) { for (uint32_t i = 0; i < extraInfo.name.size(); ++i) { bitStream.Write(static_cast(extraInfo.name[i])); @@ -447,10 +447,10 @@ void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const System bitStream.Write(subKey != LWOOBJID_EMPTY); if (subKey != LWOOBJID_EMPTY) bitStream.Write(subKey); - + auto* inventory = item->GetInventory(); const auto inventoryType = inventory->GetType(); - + bitStream.Write(inventoryType != eInventoryType::ITEMS); if (inventoryType != eInventoryType::ITEMS) bitStream.Write(inventoryType); @@ -458,7 +458,7 @@ void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const System if (itemCount != 1) bitStream.Write(itemCount); const auto count = item->GetCount(); - + bitStream.Write(count != 0); //items total if (count != 0) bitStream.Write(count); @@ -1008,7 +1008,7 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, if (GameConfig::GetValue("no_drops") == 1) { return; } - + bool bUsePosition = false; NiPoint3 finalPosition; LWOOBJID lootID = LWOOBJID_EMPTY; @@ -1063,7 +1063,7 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, if (spawnPos != NiPoint3::ZERO) bitStream.Write(spawnPos); auto* team = TeamManager::Instance()->GetTeam(owner); - + // Currency and powerups should not sync if (team != nullptr && currency == 0) { @@ -1086,7 +1086,7 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, return; } } - + SystemAddress sysAddr = entity->GetSystemAddress(); SEND_PACKET; } @@ -1097,7 +1097,7 @@ void GameMessages::SendSetPlayerControlScheme(Entity* entity, eControlSceme cont bool bDelayCamSwitchIfInCinematic = true; bool bSwitchCam = true; - + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_PLAYER_CONTROL_SCHEME)); @@ -1265,7 +1265,7 @@ void GameMessages::SendVendorStatusUpdate(Entity* entity, const SystemAddress& s bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_VENDOR_STATUS_UPDATE); - bitStream.Write(bUpdateOnly); + bitStream.Write(bUpdateOnly); bitStream.Write(static_cast(vendorItems.size())); for (std::pair item : vendorItems) { @@ -1282,7 +1282,7 @@ void GameMessages::SendVendorTransactionResult(Entity* entity, const SystemAddre CMSGHEADER int iResult = 0x02; // success, seems to be the only relevant one - + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_VENDOR_TRANSACTION_RESULT); bitStream.Write(iResult); @@ -1537,7 +1537,7 @@ void GameMessages::NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sy bitStream.Write(level); bitStream.Write(sending_rewards); - + SEND_PACKET } @@ -1549,7 +1549,7 @@ void GameMessages::SendSetShootingGalleryParams(LWOOBJID objectId, const SystemA NiPoint3 playerPosOffset, float projectileVelocity, float timeLimit, - bool bUseLeaderboards) + bool bUseLeaderboards) { CBITSTREAM CMSGHEADER @@ -1585,7 +1585,7 @@ void GameMessages::SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const float addTime, int32_t score, LWOOBJID target, - NiPoint3 targetPos) + NiPoint3 targetPos) { CBITSTREAM CMSGHEADER @@ -1602,7 +1602,7 @@ void GameMessages::SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const } -void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { float angle = 0.0f; NiPoint3 facing = NiPoint3::ZERO; @@ -1833,13 +1833,13 @@ void GameMessages::SendNotifyClientObject(const LWOOBJID& objectID, std::u16stri for (auto character : name) { bitStream.Write(character); } - + bitStream.Write(param1); - + bitStream.Write(param2); bitStream.Write(paramObj); - + bitStream.Write(uint32_t(paramStr.size())); for (auto character : paramStr) { bitStream.Write(character); @@ -1988,7 +1988,7 @@ void GameMessages::SendDownloadPropertyData(const LWOOBJID objectId, const Prope data.Serialize(bitStream); Game::logger->Log("SendDownloadPropertyData", "(%llu) sending property data (%d)\n", objectId, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); - + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; } @@ -2000,12 +2000,12 @@ void GameMessages::SendPropertyRentalResponse(const LWOOBJID objectId, const LWO bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_PROPERTY_RENTAL_RESPONSE); - + bitStream.Write(cloneId); bitStream.Write(code); bitStream.Write(propertyId); bitStream.Write(rentDue); - + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; } @@ -2078,7 +2078,7 @@ void GameMessages::SendZonePropertyModelEquipped(LWOOBJID objectId, LWOOBJID pla bitStream.Write(playerId); bitStream.Write(propertyId); - + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; } @@ -2115,7 +2115,7 @@ void GameMessages::SendPlaceModelResponse(LWOOBJID objectId, const SystemAddress { bitStream.Write(response); } - + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -2131,7 +2131,7 @@ void GameMessages::SendUGCEquipPreCreateBasedOnEditMode(LWOOBJID objectId, const bitStream.Write(modelCount); bitStream.Write(model); - + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; } @@ -2250,7 +2250,7 @@ void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entit NiPoint3 startPosition = NiPoint3::ZERO; inStream->Read(start); - + if (inStream->ReadBit()) inStream->Read(distanceType); @@ -2273,7 +2273,7 @@ void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entit player->GetCharacter()->SetBuildMode(start); Game::logger->Log("GameMessages", "Sending build mode confirm (%i): (%d) (%i) (%d) (%i) (%llu)\n", entity->GetLOT(), start, distanceType, modePaused, modeValue, playerId); - + SendSetBuildModeConfirmed(entity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS, start, false, modePaused, modeValue, playerId, startPosition); } @@ -2283,7 +2283,7 @@ void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Enti { return; } - + bool firstTime{}; bool success{}; int32_t sourceBag{}; @@ -2311,11 +2311,11 @@ void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Enti } Game::logger->Log("GameMessages", "Handling start building with item (%i): (%d) (%d) (%i) (%llu) (%i) (%i) (%llu) (%i) (%i)\n", entity->GetLOT(), firstTime, success, sourceBag, sourceId, sourceLot, sourceType, targetId, targetLot, targetType); - + auto* user = UserManager::Instance()->GetUser(sysAddr); auto* player = EntityManager::Instance()->GetEntity(user->GetLoggedInChar()); - + SendStartArrangingWithItem( player, sysAddr, @@ -2336,7 +2336,7 @@ void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Enti void GameMessages::HandlePropertyEditorBegin(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { PropertyManagementComponent::Instance()->OnStartBuilding(); - + dZoneManager::Instance()->GetZoneControlObject()->OnZonePropertyEditBegin(); } @@ -2366,7 +2366,7 @@ void GameMessages::HandlePlacePropertyModel(RakNet::BitStream* inStream, Entity* LWOOBJID model; inStream->Read(model); - + PropertyManagementComponent::Instance()->UpdateModelPosition(model, NiPoint3::ZERO, NiQuaternion::IDENTITY); } @@ -2383,7 +2383,7 @@ void GameMessages::HandleUpdatePropertyModel(RakNet::BitStream* inStream, Entity { inStream->Read(rotation); } - + PropertyManagementComponent::Instance()->UpdateModelPosition(model, position, rotation); } @@ -2422,18 +2422,18 @@ void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { /* - ___ ___ - /\ /\___ _ __ ___ / __\ ___ / \_ __ __ _ __ _ ___ _ __ ___ + ___ ___ + /\ /\___ _ __ ___ / __\ ___ / \_ __ __ _ __ _ ___ _ __ ___ / /_/ / _ \ '__/ _ \ /__\/// _ \ / /\ / '__/ _` |/ _` |/ _ \| '_ \/ __| / __ / __/ | | __/ / \/ \ __/ / /_//| | | (_| | (_| | (_) | | | \__ \ \/ /_/ \___|_| \___| \_____/\___| /___,' |_| \__,_|\__, |\___/|_| |_|___/ - |___/ - ___ _ - / __\ _____ ____ _ _ __ ___ / \ - /__\/// _ \ \ /\ / / _` | '__/ _ \/ / - / \/ \ __/\ V V / (_| | | | __/\_/ - \_____/\___| \_/\_/ \__,_|_| \___\/ - + |___/ + ___ _ + / __\ _____ ____ _ _ __ ___ / \ + /__\/// _ \ \ /\ / / _` | '__/ _ \/ / + / \/ \ __/\ V V / (_| | | | __/\_/ + \_____/\___| \_/\_/ \__,_|_| \___\/ + <>=======() (/\___ /|\\ ()==========<>_ \_/ | \\ //|\ ______/ \) @@ -2463,7 +2463,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent uint8_t c; inStream->Read(c); } - + uint32_t lxfmlSize; inStream->Read(lxfmlSize); uint8_t* inData = static_cast(std::malloc(lxfmlSize)); @@ -2471,13 +2471,13 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent if (inData == nullptr) { return; } - + for (uint32_t i = 0; i < lxfmlSize; ++i) { uint8_t c; inStream->Read(c); inData[i] = c; } - + inStream->Read(timeTaken); /* @@ -2505,7 +2505,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //Now, the cave of dragons: - //We runs this in async because the http library here is blocking, meaning it'll halt the thread. + //We runs this in async because the http library here is blocking, meaning it'll halt the thread. //But we don't want the server to go unresponsive, because then the client would disconnect. std::async(std::launch::async, [&]() { @@ -2595,7 +2595,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent */ ////Send off to UGC for processing, if enabled: - //if (Game::config->GetValue("ugc_remote") == "1") { + //if (Game::config->GetValue("ugc_remote") == "1") { // std::string ugcIP = Game::config->GetValue("ugc_ip"); // int ugcPort = std::stoi(Game::config->GetValue("ugc_port")); @@ -2750,7 +2750,7 @@ void GameMessages::HandleEnterProperty(RakNet::BitStream* inStream, Entity* enti } } -void GameMessages::HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LOT lot; @@ -2763,10 +2763,10 @@ void GameMessages::HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* inventory->SetConsumable(lot); } -void GameMessages::SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, +void GameMessages::SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, bool allowGhostUpdates, bool bCloseMultiInteract, bool bSendServerNotify, bool bUseControlledObjectForAudioListener, int endBehavior, bool hidePlayerDuringCine, float leadIn, bool leavePlayerLockedWhenFinished, - bool lockPlayer, bool result, bool skipIfSamePath, float startTimeAdvance) + bool lockPlayer, bool result, bool skipIfSamePath, float startTimeAdvance) { CBITSTREAM; CMSGHEADER; @@ -2806,7 +2806,7 @@ void GameMessages::SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, } void GameMessages::SendEndCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, - float leadOut, bool leavePlayerLocked) + float leadOut, bool leavePlayerLocked) { CBITSTREAM; CMSGHEADER; @@ -2880,7 +2880,7 @@ void GameMessages::SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, bool bCantAttackOutChangeWasApplied, bool bCantEquipOutChangeWasApplied, bool bCantInteractOutChangeWasApplied, bool bCantJumpOutChangeWasApplied, bool bCantMoveOutChangeWasApplied, bool bCantTurnOutChangeWasApplied, - bool bCantUseItemOutChangeWasApplied) + bool bCantUseItemOutChangeWasApplied) { CBITSTREAM; CMSGHEADER; @@ -2915,7 +2915,7 @@ void GameMessages::SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, bitStream.Write(bCantUseItemOutChangeWasApplied); bitStream.Write(bDontTerminateInteract); - + bitStream.Write(bIgnoreImmunity); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; @@ -2923,7 +2923,7 @@ void GameMessages::SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, } -void GameMessages::SendOrientToAngle(LWOOBJID objectId, bool bRelativeToCurrent, float fAngle, const SystemAddress& sysAddr) +void GameMessages::SendOrientToAngle(LWOOBJID objectId, bool bRelativeToCurrent, float fAngle, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -2939,7 +2939,7 @@ void GameMessages::SendOrientToAngle(LWOOBJID objectId, bool bRelativeToCurrent, } -void GameMessages::SendAddRunSpeedModifier(LWOOBJID objectId, LWOOBJID caster, uint32_t modifier, const SystemAddress& sysAddr) +void GameMessages::SendAddRunSpeedModifier(LWOOBJID objectId, LWOOBJID caster, uint32_t modifier, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -2957,7 +2957,7 @@ void GameMessages::SendAddRunSpeedModifier(LWOOBJID objectId, LWOOBJID caster, u SEND_PACKET; } -void GameMessages::SendRemoveRunSpeedModifier(LWOOBJID objectId, uint32_t modifier, const SystemAddress& sysAddr) +void GameMessages::SendRemoveRunSpeedModifier(LWOOBJID objectId, uint32_t modifier, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3009,7 +3009,7 @@ void GameMessages::SendPropertySelectQuery(LWOOBJID objectId, int32_t navOffset, SEND_PACKET; } -void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std::u16string name, const SystemAddress& sysAddr, int param1, int param2) +void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std::u16string name, const SystemAddress& sysAddr, int param1, int param2) { CBITSTREAM; CMSGHEADER; @@ -3023,7 +3023,7 @@ void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std { bitStream.Write(character); } - + bitStream.Write(param1); bitStream.Write(param2); @@ -3031,7 +3031,7 @@ void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std SEND_PACKET; } -void GameMessages::HandleVerifyAck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleVerifyAck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bDifferent; std::string sBitStream; @@ -3053,7 +3053,7 @@ void GameMessages::HandleVerifyAck(RakNet::BitStream* inStream, Entity* entity, } } -void GameMessages::SendTeamPickupItem(LWOOBJID objectId, LWOOBJID lootID, LWOOBJID lootOwnerID, const SystemAddress& sysAddr) +void GameMessages::SendTeamPickupItem(LWOOBJID objectId, LWOOBJID lootID, LWOOBJID lootOwnerID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3063,7 +3063,7 @@ void GameMessages::SendTeamPickupItem(LWOOBJID objectId, LWOOBJID lootID, LWOOBJ bitStream.Write(lootID); bitStream.Write(lootOwnerID); - + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; } @@ -3144,7 +3144,7 @@ void GameMessages::SendServerTradeAccept(LWOOBJID objectId, bool bFirst, const S SEND_PACKET; } -void GameMessages::SendServerTradeCancel(LWOOBJID objectId, const SystemAddress& sysAddr) +void GameMessages::SendServerTradeCancel(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3156,7 +3156,7 @@ void GameMessages::SendServerTradeCancel(LWOOBJID objectId, const SystemAddress& SEND_PACKET; } -void GameMessages::SendServerTradeUpdate(LWOOBJID objectId, uint64_t coins, const std::vector& items, const SystemAddress& sysAddr) +void GameMessages::SendServerTradeUpdate(LWOOBJID objectId, uint64_t coins, const std::vector& items, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3242,7 +3242,7 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* { TradingManager::Instance()->NewTrade(entity->GetObjectID(), i64Invitee); } - + SendServerTradeInvite( i64Invitee, bNeedInvitePopUp, @@ -3256,7 +3256,7 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* void GameMessages::HandleClientTradeCancel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); - + if (trade == nullptr) return; Game::logger->Log("GameMessages", "Trade canceled from (%llu)\n", entity->GetObjectID()); @@ -3269,9 +3269,9 @@ void GameMessages::HandleClientTradeAccept(RakNet::BitStream* inStream, Entity* bool bFirst = inStream->ReadBit(); Game::logger->Log("GameMessages", "Trade accepted from (%llu) -> (%d)\n", entity->GetObjectID(), bFirst); - + auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); - + if (trade == nullptr) return; trade->SetAccepted(entity->GetObjectID(), bFirst); @@ -3343,9 +3343,9 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* Game::logger->Log("GameMessages", "Trade item from (%llu) -> (%llu)/(%llu), (%i), (%llu), (%i), (%i)\n", entity->GetObjectID(), itemId, itemId2, lot, unknown1, unknown2, unknown3); } - + auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); - + if (trade == nullptr) return; trade->SetCoins(entity->GetObjectID(), currency); @@ -3355,7 +3355,7 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* //Pets: -void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId, LWOOBJID playerTamingId, bool bForceTeleport, uint32_t notifyType, NiPoint3 petsDestPos, NiPoint3 telePos, NiQuaternion teleRot, const SystemAddress& sysAddr) +void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId, LWOOBJID playerTamingId, bool bForceTeleport, uint32_t notifyType, NiPoint3 petsDestPos, NiPoint3 telePos, NiQuaternion teleRot, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3378,7 +3378,7 @@ void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId SEND_PACKET; } -void GameMessages::SendNotifyTamingModelLoadedOnServer(LWOOBJID objectId, const SystemAddress& sysAddr) +void GameMessages::SendNotifyTamingModelLoadedOnServer(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3390,7 +3390,7 @@ void GameMessages::SendNotifyTamingModelLoadedOnServer(LWOOBJID objectId, const SEND_PACKET; } -void GameMessages::SendNotifyPetTamingPuzzleSelected(LWOOBJID objectId, std::vector& bricks, const SystemAddress& sysAddr) +void GameMessages::SendNotifyPetTamingPuzzleSelected(LWOOBJID objectId, std::vector& bricks, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3409,7 +3409,7 @@ void GameMessages::SendNotifyPetTamingPuzzleSelected(LWOOBJID objectId, std::vec SEND_PACKET; } -void GameMessages::SendPetTamingTryBuildResult(LWOOBJID objectId, bool bSuccess, int32_t iNumCorrect, const SystemAddress& sysAddr) +void GameMessages::SendPetTamingTryBuildResult(LWOOBJID objectId, bool bSuccess, int32_t iNumCorrect, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3425,7 +3425,7 @@ void GameMessages::SendPetTamingTryBuildResult(LWOOBJID objectId, bool bSuccess, SEND_PACKET; } -void GameMessages::SendPetResponse(LWOOBJID objectId, LWOOBJID objIDPet, int32_t iPetCommandType, int32_t iResponse, int32_t iTypeID, const SystemAddress& sysAddr) +void GameMessages::SendPetResponse(LWOOBJID objectId, LWOOBJID objIDPet, int32_t iPetCommandType, int32_t iResponse, int32_t iTypeID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3442,7 +3442,7 @@ void GameMessages::SendPetResponse(LWOOBJID objectId, LWOOBJID objIDPet, int32_t SEND_PACKET; } -void GameMessages::SendAddPetToPlayer(LWOOBJID objectId, int32_t iElementalType, std::u16string name, LWOOBJID petDBID, LOT petLOT, const SystemAddress& sysAddr) +void GameMessages::SendAddPetToPlayer(LWOOBJID objectId, int32_t iElementalType, std::u16string name, LWOOBJID petDBID, LOT petLOT, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3456,7 +3456,7 @@ void GameMessages::SendAddPetToPlayer(LWOOBJID objectId, int32_t iElementalType, { bitStream.Write(character); } - + bitStream.Write(petDBID); bitStream.Write(petLOT); @@ -3464,7 +3464,7 @@ void GameMessages::SendAddPetToPlayer(LWOOBJID objectId, int32_t iElementalType, SEND_PACKET; } -void GameMessages::SendRegisterPetID(LWOOBJID objectId, LWOOBJID objID, const SystemAddress& sysAddr) +void GameMessages::SendRegisterPetID(LWOOBJID objectId, LWOOBJID objID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3478,7 +3478,7 @@ void GameMessages::SendRegisterPetID(LWOOBJID objectId, LWOOBJID objID, const Sy SEND_PACKET; } -void GameMessages::SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, const SystemAddress& sysAddr) +void GameMessages::SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3492,7 +3492,7 @@ void GameMessages::SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, cons SEND_PACKET; } -void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, int32_t iType, LWOOBJID itemID, const SystemAddress& sysAddr) +void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, int32_t iType, LWOOBJID itemID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3501,7 +3501,7 @@ void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive bitStream.Write(GAME_MSG::GAME_MSG_MARK_INVENTORY_ITEM_AS_ACTIVE); bitStream.Write(bActive); - + bitStream.Write(iType != 0); if (iType != 0) bitStream.Write(iType); @@ -3512,7 +3512,7 @@ void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive SEND_PACKET; } -void GameMessages::SendClientExitTamingMinigame(LWOOBJID objectId, bool bVoluntaryExit, const SystemAddress& sysAddr) +void GameMessages::SendClientExitTamingMinigame(LWOOBJID objectId, bool bVoluntaryExit, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3526,7 +3526,7 @@ void GameMessages::SendClientExitTamingMinigame(LWOOBJID objectId, bool bVolunta SEND_PACKET; } -void GameMessages::SendShowPetActionButton(LWOOBJID objectId, int32_t buttonLabel, bool bShow, const SystemAddress& sysAddr) +void GameMessages::SendShowPetActionButton(LWOOBJID objectId, int32_t buttonLabel, bool bShow, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3557,7 +3557,7 @@ void GameMessages::SendPlayEmote(LWOOBJID objectId, int32_t emoteID, LWOOBJID ta } -void GameMessages::SendBouncerActiveStatus(LWOOBJID objectId, bool bActive, const SystemAddress& sysAddr) +void GameMessages::SendBouncerActiveStatus(LWOOBJID objectId, bool bActive, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3572,7 +3572,7 @@ void GameMessages::SendBouncerActiveStatus(LWOOBJID objectId, bool bActive, cons } -void GameMessages::SendSetPetName(LWOOBJID objectId, std::u16string name, LWOOBJID petDBID, const SystemAddress& sysAddr) +void GameMessages::SendSetPetName(LWOOBJID objectId, std::u16string name, LWOOBJID petDBID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3585,7 +3585,7 @@ void GameMessages::SendSetPetName(LWOOBJID objectId, std::u16string name, LWOOBJ { bitStream.Write(character); } - + bitStream.Write(petDBID != LWOOBJID_EMPTY); if (petDBID != LWOOBJID_EMPTY) bitStream.Write(petDBID); @@ -3594,14 +3594,14 @@ void GameMessages::SendSetPetName(LWOOBJID objectId, std::u16string name, LWOOBJ } -void GameMessages::SendSetPetNameModerated(LWOOBJID objectId, LWOOBJID petDBID, int32_t nModerationStatus, const SystemAddress& sysAddr) +void GameMessages::SendSetPetNameModerated(LWOOBJID objectId, LWOOBJID petDBID, int32_t nModerationStatus, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_SET_PET_NAME_MODERATED); - + bitStream.Write(petDBID != LWOOBJID_EMPTY); if (petDBID != LWOOBJID_EMPTY) bitStream.Write(petDBID); @@ -3612,7 +3612,7 @@ void GameMessages::SendSetPetNameModerated(LWOOBJID objectId, LWOOBJID petDBID, } -void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatus, std::u16string name, std::u16string ownerName, const SystemAddress& sysAddr) +void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatus, std::u16string name, std::u16string ownerName, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3627,7 +3627,7 @@ void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatu { bitStream.Write(character); } - + bitStream.Write(static_cast(ownerName.size())); for (const auto character : ownerName) { @@ -3639,7 +3639,7 @@ void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatu } -void GameMessages::HandleClientExitTamingMinigame(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleClientExitTamingMinigame(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bVoluntaryExit = inStream->ReadBit(); @@ -3653,7 +3653,7 @@ void GameMessages::HandleClientExitTamingMinigame(RakNet::BitStream* inStream, E petComponent->ClientExitTamingMinigame(bVoluntaryExit); } -void GameMessages::HandleStartServerPetMinigameTimer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleStartServerPetMinigameTimer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); @@ -3665,7 +3665,7 @@ void GameMessages::HandleStartServerPetMinigameTimer(RakNet::BitStream* inStream petComponent->StartTimer(); } -void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t brickCount; std::vector bricks; @@ -3696,7 +3696,7 @@ void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* petComponent->TryBuild(bricks.size(), clientFailed); } -void GameMessages::HandleNotifyTamingBuildSuccess(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleNotifyTamingBuildSuccess(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { NiPoint3 position; @@ -3712,7 +3712,7 @@ void GameMessages::HandleNotifyTamingBuildSuccess(RakNet::BitStream* inStream, E petComponent->NotifyTamingBuildSuccess(position); } -void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t nameLength; std::u16string name; @@ -3725,7 +3725,7 @@ void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* inStream->Read(character); name.push_back(character); } - + auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); if (petComponent == nullptr) @@ -3741,14 +3741,14 @@ void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* petComponent->RequestSetPetName(name); } -void GameMessages::HandleCommandPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleCommandPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { NiPoint3 genericPosInfo; LWOOBJID objIdSource; int32_t iPetCommandType; int32_t iTypeID; bool overrideObey; - + inStream->Read(genericPosInfo); inStream->Read(objIdSource); inStream->Read(iPetCommandType); @@ -3765,7 +3765,7 @@ void GameMessages::HandleCommandPet(RakNet::BitStream* inStream, Entity* entity, petComponent->Command(genericPosInfo, objIdSource, iPetCommandType, iTypeID, overrideObey); } -void GameMessages::HandleDespawnPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleDespawnPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bDeletePet; @@ -3788,7 +3788,7 @@ void GameMessages::HandleDespawnPet(RakNet::BitStream* inStream, Entity* entity, } } -void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { int32_t iButton; uint32_t identifierLength; @@ -3813,7 +3813,7 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* inStream->Read(character); userData.push_back(character); } - + Game::logger->Log("HandleMessageBoxResponse", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " identifier: " + GeneralUtils::UTF16ToWTF8(identifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(userData) + "\n"); auto* user = UserManager::Instance()->GetUser(sysAddr); @@ -3852,7 +3852,7 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* } } -void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { int32_t iButton; uint32_t buttonIdentifierLength; @@ -3877,7 +3877,7 @@ void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* e inStream->Read(character); identifier.push_back(character); } - + Game::logger->Log("HandleChoiceBoxRespond", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " buttonIdentifier: " + GeneralUtils::UTF16ToWTF8(buttonIdentifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(identifier) + "\n"); auto* user = UserManager::Instance()->GetUser(sysAddr); @@ -3897,7 +3897,7 @@ void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* e entity->OnChoiceBoxResponse(userEntity, iButton, buttonIdentifier, identifier); } -void GameMessages::SendDisplayZoneSummary(LWOOBJID objectId, const SystemAddress& sysAddr, bool isPropertyMap, bool isZoneStart, LWOOBJID sender) +void GameMessages::SendDisplayZoneSummary(LWOOBJID objectId, const SystemAddress& sysAddr, bool isPropertyMap, bool isZoneStart, LWOOBJID sender) { CBITSTREAM; CMSGHEADER; @@ -3916,7 +3916,7 @@ void GameMessages::SendDisplayZoneSummary(LWOOBJID objectId, const SystemAddress //UI -void GameMessages::SendNotifyNotEnoughInvSpace(LWOOBJID objectId, uint32_t freeSlotsNeeded, eInventoryType inventoryType, const SystemAddress& sysAddr) +void GameMessages::SendNotifyNotEnoughInvSpace(LWOOBJID objectId, uint32_t freeSlotsNeeded, eInventoryType inventoryType, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3932,7 +3932,7 @@ void GameMessages::SendNotifyNotEnoughInvSpace(LWOOBJID objectId, uint32_t freeS SEND_PACKET; } -void GameMessages::SendDisplayMessageBox(LWOOBJID objectId, bool bShow, LWOOBJID callbackClient, const std::u16string& identifier, int32_t imageID, const std::u16string& text, const std::u16string& userData, const SystemAddress& sysAddr) +void GameMessages::SendDisplayMessageBox(LWOOBJID objectId, bool bShow, LWOOBJID callbackClient, const std::u16string& identifier, int32_t imageID, const std::u16string& text, const std::u16string& userData, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3950,7 +3950,7 @@ void GameMessages::SendDisplayMessageBox(LWOOBJID objectId, bool bShow, LWOOBJID } bitStream.Write(imageID); - + bitStream.Write(static_cast(text.size())); for (const auto character : text) { @@ -3986,6 +3986,47 @@ void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string SEND_PACKET; } +// Mounts + +void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objectID, const SystemAddress& sysAddr){ + CBITSTREAM; + CMSGHEADER; + + bitStream.Write(entity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_SET_MOUNT_INVENTORY_ID); + bitStream.Write(objectID); + + SEND_PACKET_BROADCAST; +} + + +void GameMessages::HandleDismountComplete(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr){ + LWOOBJID objectId{}; + inStream->Read(objectId); + auto* mount = EntityManager::Instance()->GetEntity(objectId); + + if (objectId != LWOOBJID_EMPTY) { + PossessorComponent* possessor; + if (entity->TryGetComponent(COMPONENT_TYPE_POSSESSOR, possessor)) { + if (mount) { + possessor->SetIsBusy(false); + possessor->SetPossessable(LWOOBJID_EMPTY); + possessor->SetPossessableType(ePossessionType::NO_POSSESSION); + + GameMessages::SendSetStunned(entity->GetObjectID(), eStunState::POP, UNASSIGNED_SYSTEM_ADDRESS, LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); + + EntityManager::Instance()->SerializeEntity(entity); + } + } + } +} + + +void GameMessages::HandleAcknowledgePossession(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + Game::logger->Log("HandleAcknowledgePossession", "Got AcknowledgePossession from %i\n", entity->GetLOT()); + EntityManager::Instance()->SerializeEntity(entity); +} + //Racing void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) @@ -3998,12 +4039,12 @@ void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, En { Game::logger->Log("HandleModuleAssemblyQueryData", "Returning assembly %s\n", GeneralUtils::UTF16ToWTF8(moduleAssemblyComponent->GetAssemblyPartsLOTs()).c_str()); - SendModuleAssemblyDBDataForClient(entity->GetObjectID(), moduleAssemblyComponent->GetSubKey(), moduleAssemblyComponent->GetAssemblyPartsLOTs(), UNASSIGNED_SYSTEM_ADDRESS); + SendModuleAssemblyDBDataForClient(entity->GetObjectID(), moduleAssemblyComponent->GetSubKey(), moduleAssemblyComponent->GetAssemblyPartsLOTs(), UNASSIGNED_SYSTEM_ADDRESS); } } -void GameMessages::HandleModularAssemblyNIFCompleted(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleModularAssemblyNIFCompleted(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID objectID; @@ -4011,14 +4052,14 @@ void GameMessages::HandleModularAssemblyNIFCompleted(RakNet::BitStream* inStream } -void GameMessages::HandleVehicleSetWheelLockState(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleVehicleSetWheelLockState(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bExtraFriction = inStream->ReadBit(); bool bLocked = inStream->ReadBit(); } -void GameMessages::HandleRacingClientReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleRacingClientReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID playerID; @@ -4042,15 +4083,7 @@ void GameMessages::HandleRacingClientReady(RakNet::BitStream* inStream, Entity* } -void GameMessages::HandleAcknowledgePossession(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ - Game::logger->Log("HandleAcknowledgePossession", "Got AcknowledgePossession from %i\n", entity->GetLOT()); - - EntityManager::Instance()->SerializeEntity(entity); -} - - -void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bClientDeath; bool bSpawnLoot; @@ -4064,7 +4097,7 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, bClientDeath = inStream->ReadBit(); bSpawnLoot = inStream->ReadBit(); - + uint32_t deathTypeLength = 0; inStream->Read(deathTypeLength); @@ -4123,13 +4156,13 @@ void GameMessages::HandleVehicleNotifyServerAddPassiveBoostAction(RakNet::BitStr } -void GameMessages::HandleVehicleNotifyServerRemovePassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleVehicleNotifyServerRemovePassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { //SendVehicleRemovePassiveBoostAction(entity->GetObjectID(), sysAddr); } -void GameMessages::HandleRacingPlayerInfoResetFinished(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleRacingPlayerInfoResetFinished(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID playerID; @@ -4190,7 +4223,7 @@ void GameMessages::HandleUpdatePropertyPerformanceCost(RakNet::BitStream* inStre updatePerformanceCostQuery = nullptr; } -void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID pickupObjID = LWOOBJID_EMPTY; LWOOBJID pickupSpawnerID = LWOOBJID_EMPTY; @@ -4350,7 +4383,7 @@ void GameMessages::SendRacingResetPlayerToLastReset(LWOOBJID objectId, LWOOBJID } -void GameMessages::SendNotifyRacingClient(LWOOBJID objectId, int32_t eventType, int32_t param1, LWOOBJID paramObj, std::u16string paramStr, LWOOBJID singleClient, const SystemAddress& sysAddr) +void GameMessages::SendNotifyRacingClient(LWOOBJID objectId, int32_t eventType, int32_t param1, LWOOBJID paramObj, std::u16string paramStr, LWOOBJID singleClient, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4378,7 +4411,7 @@ void GameMessages::SendNotifyRacingClient(LWOOBJID objectId, int32_t eventType, } -void GameMessages::SendActivityEnter(LWOOBJID objectId, const SystemAddress& sysAddr) +void GameMessages::SendActivityEnter(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4391,7 +4424,7 @@ void GameMessages::SendActivityEnter(LWOOBJID objectId, const SystemAddress& sys } -void GameMessages::SendActivityStart(LWOOBJID objectId, const SystemAddress& sysAddr) +void GameMessages::SendActivityStart(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4404,7 +4437,7 @@ void GameMessages::SendActivityStart(LWOOBJID objectId, const SystemAddress& sys } -void GameMessages::SendActivityExit(LWOOBJID objectId, const SystemAddress& sysAddr) +void GameMessages::SendActivityExit(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4417,7 +4450,7 @@ void GameMessages::SendActivityExit(LWOOBJID objectId, const SystemAddress& sysA } -void GameMessages::SendActivityStop(LWOOBJID objectId, bool bExit, bool bUserCancel, const SystemAddress& sysAddr) +void GameMessages::SendActivityStop(LWOOBJID objectId, bool bExit, bool bUserCancel, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4459,7 +4492,7 @@ void GameMessages::SendVehicleRemovePassiveBoostAction(LWOOBJID objectId, const } -void GameMessages::SendVehicleNotifyFinishedRace(LWOOBJID objectId, const SystemAddress& sysAddr) +void GameMessages::SendVehicleNotifyFinishedRace(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4561,7 +4594,7 @@ void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* } -void GameMessages::SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditionalSound, bool bPlayCountdownSound, std::u16string sndName, int32_t stateToPlaySoundOn, const SystemAddress& sysAddr) +void GameMessages::SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditionalSound, bool bPlayCountdownSound, std::u16string sndName, int32_t stateToPlaySoundOn, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4590,7 +4623,7 @@ void GameMessages::SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditi //------------------------------------------------------------------- Handlers ------------------------------------------------------------------ //----------------------------------------------------------------------------------------------------------------------------------------------- -void GameMessages::HandleToggleGhostReferenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleToggleGhostReferenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bOverride = false; @@ -4601,13 +4634,13 @@ void GameMessages::HandleToggleGhostReferenceOverride(RakNet::BitStream* inStrea if (player != nullptr) { player->SetGhostOverride(bOverride); - + EntityManager::Instance()->UpdateGhosting(player); } } -void GameMessages::HandleSetGhostReferencePosition(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) +void GameMessages::HandleSetGhostReferencePosition(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { NiPoint3 position; @@ -4650,7 +4683,7 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti } const auto isCommendationVendor = entity->GetLOT() == 13806; - + VendorComponent* vend = static_cast(entity->GetComponent(COMPONENT_TYPE_VENDOR)); if (!vend && !isCommendationVendor) return; @@ -4923,7 +4956,7 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity LWOCLONEID cloneId = 0; LWOMAPID mapId = 0; - + auto* rocketPad = entity->GetComponent(); if (rocketPad == nullptr) return; @@ -4948,7 +4981,7 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity } Game::logger->Log("FireEventServerSide", "Player %llu has requested zone transfer to (%i, %i).\n", sender->GetObjectID(), (int) mapId, (int) cloneId); - + auto* character = player->GetCharacter(); if (mapId <= 0) { @@ -4957,7 +4990,7 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, mapId, cloneId, false, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); - + if (character) { character->SetZoneID(zoneID); character->SetZoneInstance(zoneInstance); @@ -5011,12 +5044,12 @@ void GameMessages::HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, return; } - + if (interactedObject->GetLOT() == 9524) { entity->GetCharacter()->SetBuildMode(true); } - + if (bIsMultiInteractUse) { if (multiInteractType == 0) @@ -5039,7 +5072,7 @@ void GameMessages::HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, //Perform use task if possible: auto missionComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION)); - + if (missionComponent == nullptr) return; missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MISSION_INTERACTION, interactedObject->GetLOT(), interactedObject->GetObjectID()); @@ -5054,7 +5087,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) inStream->Read(targetID); Game::logger->Log("GameMessages", "Emote (%i) (%llu)\n", emoteID, targetID); - + //TODO: If targetID != 0, and we have one of the "perform emote" missions, complete them. if (emoteID == 0) return; @@ -5064,13 +5097,13 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) if (mission) { mission->Progress(MissionTaskType::MISSION_TASK_TYPE_EMOTE, emoteID, targetID); } - + if (targetID != LWOOBJID_EMPTY) { auto* targetEntity = EntityManager::Instance()->GetEntity(targetID); Game::logger->Log("GameMessages", "Emote target found (%d)\n", targetEntity != nullptr); - + if (targetEntity != nullptr) { targetEntity->OnEmoteReceived(emoteID, entity); @@ -5222,7 +5255,7 @@ void GameMessages::HandleRequestLinkedMission(RakNet::BitStream* inStream, Entit auto* player = EntityManager::Instance()->GetEntity(playerId); auto* missionOfferComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION_OFFER)); - + if (missionOfferComponent != nullptr) { missionOfferComponent->OfferMissions(player, 0); @@ -5245,7 +5278,7 @@ void GameMessages::HandleHasBeenCollected(RakNet::BitStream* inStream, Entity* e void GameMessages::HandleNotifyServerLevelProcessingComplete(RakNet::BitStream* inStream, Entity* entity) { auto* character = static_cast(entity->GetComponent(COMPONENT_TYPE_CHARACTER)); if (!character) return; - + //Update our character's level in memory: character->SetLevel(character->GetLevel() + 1); @@ -5281,7 +5314,7 @@ void GameMessages::HandleNotifyServerLevelProcessingComplete(RakNet::BitStream* void GameMessages::HandlePickupCurrency(RakNet::BitStream* inStream, Entity* entity) { unsigned int currency; inStream->Read(currency); - + if (currency == 0) return; auto* ch = entity->GetCharacter(); @@ -5306,7 +5339,7 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity) inStream->Read(bClientDeath); inStream->Read(bDieAccepted); inStream->Read(bSpawnLoot); - + bool coinSpawnTimeIsDefault{}; inStream->Read(coinSpawnTimeIsDefault); if (coinSpawnTimeIsDefault != 0) inStream->Read(coinSpawnTime); @@ -5343,7 +5376,7 @@ void GameMessages::HandleEquipItem(RakNet::BitStream* inStream, Entity* entity) if (!item) return; item->Equip(); - + EntityManager::Instance()->SerializeEntity(entity); } @@ -5361,9 +5394,9 @@ void GameMessages::HandleUnequipItem(RakNet::BitStream* inStream, Entity* entity auto* item = inv->FindItemById(objectID); if (!item) return; - + item->UnEquip(); - + EntityManager::Instance()->SerializeEntity(entity); } @@ -5439,9 +5472,9 @@ void GameMessages::HandleRemoveItemFromInventory(RakNet::BitStream* inStream, En { return; } - + iStackCount = std::min(item->GetCount(), iStackCount); - + if (bConfirmed) { for (auto i = 0; i < iStackCount; ++i) { if (eInvType == eInventoryType::MODELS) @@ -5454,7 +5487,7 @@ void GameMessages::HandleRemoveItemFromInventory(RakNet::BitStream* inStream, En EntityManager::Instance()->SerializeEntity(entity); auto* missionComponent = entity->GetComponent(); - + if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, item->GetLot(), LWOOBJID_EMPTY, "", -iStackCount); @@ -5525,7 +5558,7 @@ void GameMessages::HandleMoveItemBetweenInventoryTypes(RakNet::BitStream* inStre } } } - + if (entity->GetCharacter()) { if (entity->GetCharacter()->GetBuildMode()) { showFlyingLoot = false; @@ -5543,7 +5576,7 @@ void GameMessages::HandleBuildModeSet(RakNet::BitStream* inStream, Entity* entit // there's more here but we don't need it (for now?) Game::logger->Log("GameMessages", "Set build mode to (%d) for (%llu)\n", bStart, entity->GetObjectID()); - + if (entity->GetCharacter()) { entity->GetCharacter()->SetBuildMode(bStart); } @@ -5607,7 +5640,7 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* } auto* missionComponent = character->GetComponent(); - + if (entity->GetLOT() != 9980 || Game::server->GetZoneID() != 1200) { if (missionComponent != nullptr) @@ -5686,7 +5719,7 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti inStream->Read(oldItemTYPE); /* - Game::logger->Log("GameMessages", + Game::logger->Log("GameMessages", "\nnewSourceBAG: %d\nnewSourceID: %llu\nnewSourceLOT: %d\nnewSourceTYPE: %d\nnewTargetID: %llu\nnewTargetLOT: %d\nnewTargetTYPE: %d\nnewTargetPOS: %f, %f, %f\noldItemBAG: %d\noldItemID: %llu\noldItemLOT: %d\noldItemTYPE: %d\n", newSourceBAG, newSourceID, newSourceLOT, newSourceTYPE, newTargetID, newTargetLOT, newTargetTYPE, newTargetPOS.x, newTargetPOS.y, newTargetPOS.z, oldItemBAG, oldItemID, oldItemLOT, oldItemTYPE ); @@ -5694,7 +5727,7 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti if (PropertyManagementComponent::Instance() != nullptr) { const auto& buildAreas = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_BUILD_BORDER); - + const auto& entities = EntityManager::Instance()->GetEntitiesInGroup("PropertyPlaque"); Entity* buildArea; @@ -5704,7 +5737,7 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti } else if (!entities.empty()) { buildArea = entities[0]; - + Game::logger->Log("BuildBorderComponent", "Using PropertyPlaque\n"); } else { @@ -5839,7 +5872,7 @@ void GameMessages::HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* inStream->Read(itemConsumed); auto* inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); - + if (inventory == nullptr) { return; @@ -5866,13 +5899,13 @@ void GameMessages::HandleUseNonEquipmentItem(RakNet::BitStream* inStream, Entity LWOOBJID itemConsumed; inStream->Read(itemConsumed); - + auto* inv = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); - + if (!inv) return; auto* item = inv->FindItemById(itemConsumed); - + if (item == nullptr) { return; diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 1d42eebc..18e1467e 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -328,6 +328,34 @@ namespace GameMessages { void SendDisplayChatBubble(LWOOBJID objectId, const std::u16string& text, const SystemAddress& sysAddr); + // Mounts + /** + * @brief Set the Inventory LWOOBJID of the mount + * + * @param entity The entity that is mounting + * @param sysAddr the system address to send game message responses to + * @param objectID LWOOBJID of the item in inventory that is being used + */ + void SendSetMountInventoryID(Entity* entity, const LWOOBJID& objectID, const SystemAddress& sysAddr); + + /** + * @brief Handle client dismounting mount + * + * @param inStream Raknet BitStream of incoming data + * @param entity The Entity that is dismounting + * @param sysAddr the system address to send game message responses to + */ + void HandleDismountComplete(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + + /** + * @brief Handle acknowledging that the client possessed something + * + * @param inStream Raknet BitStream of incoming data + * @param entity The Entity that is possessing + * @param sysAddr the system address to send game message responses to + */ + void HandleAcknowledgePossession(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + //Racing: void HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -337,8 +365,6 @@ namespace GameMessages { void HandleRacingClientReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleAcknowledgePossession(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleVehicleNotifyServerAddPassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); diff --git a/dNet/dMessageIdentifiers.h b/dNet/dMessageIdentifiers.h index 5b2ff639..5ad3921c 100644 --- a/dNet/dMessageIdentifiers.h +++ b/dNet/dMessageIdentifiers.h @@ -535,8 +535,10 @@ enum GAME_MSG : unsigned short { GAME_MSG_REQUEST_MOVE_ITEM_BETWEEN_INVENTORY_TYPES = 1666, GAME_MSG_RESPONSE_MOVE_ITEM_BETWEEN_INVENTORY_TYPES = 1667, GAME_MSG_PLAYER_SET_CAMERA_CYCLING_MODE = 1676, + GAME_MSG_SET_MOUNT_INVENTORY_ID = 1726, GAME_MSG_NOTIFY_SERVER_LEVEL_PROCESSING_COMPLETE = 1734, GAME_MSG_NOTIFY_LEVEL_REWARDS = 1735, + GAME_MSG_DISMOUNT_COMPLETE = 1756, GAME_MSG_MARK_INVENTORY_ITEM_AS_ACTIVE = 1767, END }; \ No newline at end of file From 945e57249393d8b3586016afd4a795c507caee87 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Sun, 17 Jul 2022 09:40:34 +0100 Subject: [PATCH 023/322] Add best friend check and complete blacklist --- dChatFilter/dChatFilter.cpp | 46 ++++++++++++----------------- dChatFilter/dChatFilter.h | 5 ++-- dGame/User.cpp | 2 ++ dGame/User.h | 5 ++++ dNet/ClientPackets.cpp | 56 ++++++++++++++++++++++++++++++++++-- resources/blacklist.dcf | Bin 16160 -> 16160 bytes 6 files changed, 82 insertions(+), 32 deletions(-) diff --git a/dChatFilter/dChatFilter.cpp b/dChatFilter/dChatFilter.cpp index fe8a0d10..eb6674a4 100644 --- a/dChatFilter/dChatFilter.cpp +++ b/dChatFilter/dChatFilter.cpp @@ -19,12 +19,12 @@ dChatFilter::dChatFilter(const std::string& filepath, bool dontGenerateDCF) { m_DontGenerateDCF = dontGenerateDCF; if (!BinaryIO::DoesFileExist(filepath + ".dcf") || m_DontGenerateDCF) { - ReadWordlistPlaintext(filepath + ".txt"); - if (!m_DontGenerateDCF) ExportWordlistToDCF(filepath + ".dcf"); + ReadWordlistPlaintext(filepath + ".txt", true); + if (!m_DontGenerateDCF) ExportWordlistToDCF(filepath + ".dcf", true); } else if (!ReadWordlistDCF(filepath + ".dcf", true)) { - ReadWordlistPlaintext(filepath + ".txt"); - ExportWordlistToDCF(filepath + ".dcf"); + ReadWordlistPlaintext(filepath + ".txt", true); + ExportWordlistToDCF(filepath + ".dcf", true); } if (BinaryIO::DoesFileExist("blacklist.dcf")) { @@ -48,14 +48,15 @@ dChatFilter::~dChatFilter() { m_NoNoWords.clear(); } -void dChatFilter::ReadWordlistPlaintext(const std::string& filepath) { +void dChatFilter::ReadWordlistPlaintext(const std::string& filepath, bool whiteList) { std::ifstream file(filepath); if (file) { std::string line; while (std::getline(file, line)) { line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Transform to lowercase - m_YesYesWords.push_back(CalculateHash(line)); + if (whiteList) m_YesYesWords.push_back(CalculateHash(line)); + else m_NoNoWords.push_back(CalculateHash(line)); } } } @@ -94,14 +95,14 @@ bool dChatFilter::ReadWordlistDCF(const std::string& filepath, bool whiteList) { return false; } -void dChatFilter::ExportWordlistToDCF(const std::string& filepath) { +void dChatFilter::ExportWordlistToDCF(const std::string& filepath, bool whiteList) { std::ofstream file(filepath, std::ios::binary | std::ios_base::out); if (file) { BinaryIO::BinaryWrite(file, uint32_t(dChatFilterDCF::header)); BinaryIO::BinaryWrite(file, uint32_t(dChatFilterDCF::formatVersion)); - BinaryIO::BinaryWrite(file, size_t(m_YesYesWords.size())); + BinaryIO::BinaryWrite(file, size_t(whiteList ? m_YesYesWords.size() : m_NoNoWords.size())); - for (size_t word : m_YesYesWords) { + for (size_t word : whiteList ? m_YesYesWords : m_NoNoWords) { BinaryIO::BinaryWrite(file, word); } @@ -128,21 +129,18 @@ std::vector dChatFilter::IsSentenceOkay(const std::string& message, size_t hash = CalculateHash(segment); - if (std::find(m_UserUnapprovedWordCache.begin(), m_UserUnapprovedWordCache.end(), hash) != m_UserUnapprovedWordCache.end()) { - listOfBadSegments.push_back(originalSegment); // found word that isn't ok, just deny this code works for both white and black list + if (std::find(m_UserUnapprovedWordCache.begin(), m_UserUnapprovedWordCache.end(), hash) != m_UserUnapprovedWordCache.end() && whiteList) { + listOfBadSegments.push_back(originalSegment); } - if (!IsInWordlist(hash, whiteList)) { - if (whiteList) { - m_UserUnapprovedWordCache.push_back(hash); - listOfBadSegments.push_back(originalSegment); - } + if (std::find(m_YesYesWords.begin(), m_YesYesWords.end(), hash) == m_YesYesWords.end() && whiteList) { + m_UserUnapprovedWordCache.push_back(hash); + listOfBadSegments.push_back(originalSegment); } - else { - if (!whiteList) { - m_UserUnapprovedWordCache.push_back(hash); - listOfBadSegments.push_back(originalSegment); - } + + if (std::find(m_NoNoWords.begin(), m_NoNoWords.end(), hash) != m_NoNoWords.end() && !whiteList) { + m_UserUnapprovedWordCache.push_back(hash); + listOfBadSegments.push_back(originalSegment); } } @@ -155,10 +153,4 @@ size_t dChatFilter::CalculateHash(const std::string& word) { size_t value = hash(word); return value; -} - -bool dChatFilter::IsInWordlist(size_t word, bool whiteList) { - auto* list = whiteList ? &m_YesYesWords : &m_NoNoWords; - - return std::find(list->begin(), list->end(), word) != list->end(); } \ No newline at end of file diff --git a/dChatFilter/dChatFilter.h b/dChatFilter/dChatFilter.h index 5acd6063..62a47242 100644 --- a/dChatFilter/dChatFilter.h +++ b/dChatFilter/dChatFilter.h @@ -20,9 +20,9 @@ public: dChatFilter(const std::string& filepath, bool dontGenerateDCF); ~dChatFilter(); - void ReadWordlistPlaintext(const std::string& filepath); + void ReadWordlistPlaintext(const std::string& filepath, bool whiteList); bool ReadWordlistDCF(const std::string& filepath, bool whiteList); - void ExportWordlistToDCF(const std::string& filepath); + void ExportWordlistToDCF(const std::string& filepath, bool whiteList); std::vector IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList = true); private: @@ -33,5 +33,4 @@ private: //Private functions: size_t CalculateHash(const std::string& word); - bool IsInWordlist(size_t word, bool whiteList); }; \ No newline at end of file diff --git a/dGame/User.cpp b/dGame/User.cpp index 3efc4d0a..98a37954 100644 --- a/dGame/User.cpp +++ b/dGame/User.cpp @@ -18,6 +18,8 @@ User::User(const SystemAddress& sysAddr, const std::string& username, const std: m_SystemAddress = sysAddr; m_Username = username; m_LoggedInCharID = 0; + + m_IsBestFriendMap = std::unordered_map(); //HACK HACK HACK //This needs to be re-enabled / updated whenever the mute stuff is moved to another table. diff --git a/dGame/User.h b/dGame/User.h index 3be9148e..78640b38 100644 --- a/dGame/User.h +++ b/dGame/User.h @@ -42,6 +42,9 @@ public: bool GetLastChatMessageApproved() { return m_LastChatMessageApproved; } void SetLastChatMessageApproved(bool approved) { m_LastChatMessageApproved = approved; } + std::unordered_map GetIsBestFriendMap() { return m_IsBestFriendMap; } + void SetIsBestFriendMap(std::unordered_map mapToSet) { m_IsBestFriendMap = mapToSet; } + bool GetIsMuted() const; time_t GetMuteExpire() const; @@ -63,6 +66,8 @@ private: std::vector m_Characters; LWOOBJID m_LoggedInCharID; + std::unordered_map m_IsBestFriendMap; + bool m_LastChatMessageApproved = false; int m_AmountOfTimesOutOfSync = 0; const int m_MaxDesyncAllowed = 12; diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index 187ee12f..abb08688 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -30,6 +30,9 @@ #include "VehiclePhysicsComponent.h" #include "dConfig.h" #include "CharacterComponent.h" +#include "Database.h" + + void ClientPackets::HandleChatMessage(const SystemAddress& sysAddr, Packet* packet) { User* user = UserManager::Instance()->GetUser(sysAddr); @@ -276,7 +279,6 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa std::string message = ""; stream.Read(chatLevel); - printf("%d", chatLevel); stream.Read(requestID); for (uint32_t i = 0; i < 42; ++i) { @@ -285,6 +287,12 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa receiver.push_back(static_cast(character)); } + if (!receiver.empty()) { + if (std::string(receiver.c_str(), 4) == "[GM]") { + receiver = std::string(receiver.c_str() + 4, receiver.size() - 4); + } + } + stream.Read(messageLength); for (uint32_t i = 0; i < messageLength; ++i) { uint16_t character; @@ -292,8 +300,52 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa message.push_back(static_cast(character)); } + bool isBestFriend = false; + + if (chatLevel == 1) { + // Private chat + LWOOBJID idOfReceiver = LWOOBJID_EMPTY; + + { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT name FROM charinfo WHERE name = ?"); + stmt->setString(1, receiver); + + sql::ResultSet* res = stmt->executeQuery(); + + if (res->next()) { + idOfReceiver = res->getInt("id"); + } + } + + if (user->GetIsBestFriendMap().find(receiver) == user->GetIsBestFriendMap().end() && idOfReceiver != LWOOBJID_EMPTY) { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT * FROM friends WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?) LIMIT 1;"); + stmt->setInt(1, entity->GetObjectID()); + stmt->setInt(2, idOfReceiver); + stmt->setInt(3, idOfReceiver); + stmt->setInt(4, entity->GetObjectID()); + + sql::ResultSet* res = stmt->executeQuery(); + + if (res->next()) { + isBestFriend = res->getInt("best_friend") == 3; + } + + if (isBestFriend) { + auto tmpBestFriendMap = user->GetIsBestFriendMap(); + tmpBestFriendMap[receiver] = true; + user->SetIsBestFriendMap(tmpBestFriendMap); + } + + delete res; + delete stmt; + } + else if (user->GetIsBestFriendMap().find(receiver) != user->GetIsBestFriendMap().end()) { + isBestFriend = true; + } + } + std::unordered_map unacceptedItems; - std::vector segments = Game::chatFilter->IsSentenceOkay(message, entity->GetGMLevel()); + std::vector segments = Game::chatFilter->IsSentenceOkay(message, entity->GetGMLevel(), !(isBestFriend && chatLevel == 1)); bool bAllClean = segments.empty(); diff --git a/resources/blacklist.dcf b/resources/blacklist.dcf index cdc64c2f5b245f4526974ab9cb1770fd8355b783..ca4db242aa20dbc20082100845e658ab7d958bb6 100644 GIT binary patch literal 16160 zcmb8WRaBJ?)UFNE(#=A;yFt2Jx;v#irMsl0yF;W)x*O?6I;2~=+3R3G-#><9yyN?~ z2V7&qa*1&A%=^BkxR|8qI|vAfZ8-1;@SkZ4keZ>b_c_~TRuxi_ab2-DmEvLwKAZ&h zcctkS!LNzn>{0Z49O-$x05+`i#zV*AM)$b6qifT zBO8CP+wbsVGM>|#MG6%d7wK)-wHks;T2kIV!)Qp?LMEDhV5jLE?1n+zk1xmi#msS7 zM)WqGv~kN+>e&$7zLgRx#bsh*Z0AhVup$s5D;yDH%5bOs5pk_Y4@`E%wV-7wtHuL{ z%IEZKjz$7|McMHn!4M{xufpmRW2>jV{VE|m1dZI%6gv0LFrZfL{RTOFqM%quZGi1e z;a}bG>(xSJpW-^C4qGV-Z@1`1tH&+hj&%qhQ^>XmkTzg5P#lH7euu! zqoJg$h_U_UDqlhq#xjN#mwCVS*!Um!^VAZ8G5B4^^yaG`d2u6RyifVvM+jN&&FS|h#1px)wriK<^prJP(l&AwT- z&EzC`x}19*^0&=6KOckOoW2ALUQGM2bwp}+xb11@Phq?#U|h}KLKu+m>M}^c5u2n$ z|BT?HvYqyTQp~Mk@Bt5v?N=MjVxU*syQRC>;pp|IU6JCpV!z+m$ z%l!23g+Pno(V4K9@@YSor)`?}!tX@Pbm4aIDU}Dt({JJ=*@e-BZ8Pws8M7`^;OR5t zlZv!$ET-hvlN93V8GiPwlx4p2%D8auRzX&m_hjsUmt9D)yq=x}Cj9dH0*o-q`}D@C zWSrUVW+}g>nSe{(pnlRu4KEQ)5UChMQwdCZrh$v^vqNw^_sB@~%Qp>CVn!IAo)iHh zKcnFJ1Ug0hPoui9y}>H;Mv%DdvH6qK+!`xauDWN0-0xhs&t|8h1k98Jve zoj(qdSo@gsRlJuKt}I`rJ*2~1vN8Fwz#zK;C%X`O%_WYbU9?Ov508`n zoIbkz2V{7)(y0C?Rf%*vZME~()xMNJW5K~J89W)s*gW*BrfHBM#n_pJ*= zHe43_{29UQZtd;ML3DUL@6&H=ukHa@gxoUb+qk1UL*yspeZl`a#SG>n|LenF>n&f= zasOae@chL8YE&N~<9#dhy2~Mb<-2T@_mF+PY$@mPNOZ0Cr;x?pW=tP9`^2hh`=M+q z0QoXa`DbX2Rxuv5!Qhcw>#3NR;b|#JOtDCbs+ocgd;o}l@HEOapRb`JtV`tQ~ znKysY5UN3@vRoRRxrIFhEj-&|Rmb{hBIHmRuF_rhW4DyzcZA|HNPzWGW6IUlm1h9Y zU}Z5uqVf>80rjfC>ZzXAFMhYw9hgPEyE$yd@gD3CeC#>qk-S^xvdYe|k))oZ@w>&0 z!1@%9ZV4vbr*MCCt;f-H_ztJSft0%6d-8C-U>@zs6WAcIxr>lfCM#A9W**XyUp-e3 zW)3os?}dITKQ}<;4?upOUH3?*wYAI#ck@#w9y$e$eT)eILP6M8yeYLvwS|jR|8abTFQq&E0YvoSQ zk?L$csCkdtKoU_Y53?QVG3Ct$Q_(D#i_kwz8I~_+m}wR1X9l2{-(UQ;Z=w&xdCh%R zMIOgCnVUhex;UenCw)CUfjv&NX59{Ea!*Swpqc!{Mp1CfJCq5L*zozyA)+2$v2TBW zOF6n^tHbAVs4^u1<9okUwhkufqcH@`XVxUCiLA590W*~*n+@4e)9YZ|o^0#VfIE4H zP6ZpXV*aCL=OFi?kf-g;^QpH{R~=LIrhA0H&LltaIFQ&lVYO{1V;={!E`A+2w{P75 zjJ!W&+Kz+i|8Z8cow@4q7Q9<~vZC-w0ANUnrww_-UTpn4=Hn{F#ki})qmLMQI0-mC zX;3$DFw`}mOak=^v3(3|v-1oWKbdUga+-m%6TL)|lHX9fkAw>7s98|^fr?mE1Ndgt zh4*;1gSfNlcVF{c4<0^kx}C-^Qx`jKnojdeCr`$|!;@$3ML5aACH5;d&PAJG*xmE{ zJ5^5WHS?*ygG=mp8+~XDo$NteD0PFf-u^jt6TS*-yx*qRDKF{x^d>V5>2t;GX&<(TdwNY`EDb(cO{Hxfr>UQPzk?6rTx=RF z^Tpp0buP4GGk%v5OgPgQ{1SNY`U%#IZ*cCtYmkA`aNJ*8<->)>ls;%mcL6#R;&r_J zZnel6rfKjjL1!}G$h_ZeP(0Hphz9E}XTk8bJ3~IYYakflM_;n<#5-P9(C_?8K?4R2 zQx!z8?lK+>4_d_L(eCKgnKp%t8MI9F0QWeaQR0)w9#(ujjf1Z(T>Q;3iQ-9lurj8< zMWCl&E9l$(RT0#G@-NYHCX8qG#-wkZq@p0ep#!-74gH;Z{X)2ws^_3u3nFnHil9au zZ)GlQHGxJPTWBu-g&aaMa#i#cWb3$~a+MZ=K?ZyCTl_1)XM~f1lP9YR0fN2nAC6N> zx4Bt$b6@gu2G&Zk<7cCw^`vVszSe7S8CRdvLK z0S;WpsoK!RJy&0yq@Fg6qv%GT^yZk;?zBsRSJeRQ-**>Kt8ELyUeGA_l~qv{EiyIk z0tJ=w*IRWz+w=Q!$JiMHQ;_wzHl!?s9DA+E?0FilxVUaA&6X4^rDK?7RBh`UX_OcsV`|3=}h~6H#T63*yA#HkI`_E+cR)RhKEa<$_V{t4zLIJH7({r zzg1GA_%5Tms2sz-`Hfjnb_% z)B#^c#@(E1Wxe0ffysQItu!HYgr#5D~k;Z=qeg3eM1%^lsTV} z6A1LG)?JYRl9<R1;{Gz_E%E7<9Ezg@b?J^a~rq()|Yc{9UnOU(wBo~8UL8~ zio_nQ&8Ko%z{u+THPEvyI66*M663ZXYH*N(D5tonm-NSZ0;6*QXTXt+w6aQ8z81W7 zbH21-05?)-DE;r2wl#rDv$!;u9wg9N%Z=0x3(iIvIWNF>$p@uYM`G~+ZM3Dn2a(%< z2Iyb^>CiKYEg4{A=lE7mz|?|YXa|RLA0sTl1TiSvKD7*g)XOoUQzZVqyN^b4r>%26 z{YIz9y&P*m#4D9tz;0&WXYX=J&!Gt z_6gjNoVSa}>Ei0Hh;z1+<9)MGe=uR^4z#w9Q}3ph0(fw#f~^TdG5QTw8C`SpYahVI zQOu>uWTHbJA##jPf4TS^4Si+^mgxf(;KTB*wPX+&08OI6zn|xp8^|wA zya?8rGytEm%!FNhksGDsweEA3&Y(PV{9b3sLSO+-_11|yGeG|WI8zIr$)JBF&K0)N z(Kd^R2kHgT8OyB##330Ywv<+9h>oIvBCxslN#O#M=iaA1BkzMH{a1=s$l&+;IXGMO zra|xbMR2yDOD0$>G-E?KzfqlQK81EI?I{m-B5)oMemiEd(5eaD8Q7fb^n-lYtg$fH z8G8-MPCEhrbZFsY-c-V3pCS3e_7i$3HLKS(YU`tk+I3HvV+^b3`k0Jne3 z<93d(egTMYtMRcfG<=~yaIrQx3YpW93-(W<=KKcbcLBY0$hTF$gHk8Fhix-cQaPyc;d)9jr!9AQJE7ni*7xvu+tpi(i+&5bv_Z z(uLJD4+3m07wot&Px_^f1jIl!!=0N7?${`po+`Ku89Ke`pA$ZMlS}rd zyLx>*^&YmNl>WRT@f826K)TBTFha}z8jttK$n4vhgN5bin`jgNfd}hKwAC1OGEVJF ztLddJ{%YJBe9sKrV#E&T)vQ$crzNp0{i}g{Y@hx;ls= zXrB=t)*wmZ_je#rF#9#PL7uz_ALe%>5VfRFs`TI%Vzi=!Qr?Me=~=**#9TANJ!hliE`_nS#pk2dtYx8wq~k_cuVwWF zr)#dv%&1>kP%#+D^3Uh^VyhwRv>c}s8|7hB&<--oJs#zJs*Sd>k9=U`J~M$?2$kPt zoEe_0s4Rkf!}1i(hxK^~>9{mv{-{!OOnl_`(}F}^$RJaMTmPLi^!iB-p+=C!?dOGh z1uNr$bvKe7%=j}2-L_l06cvb1rqyMr>cJmC_T{|=9u)^pR z(Sox8{SeTcyz@f8+adV$Xn#~HiLV0C?eE^^Dbpznz`Sng^mp^Mxjss(kxZ2kW@vbRlCs&AtQP!}oI+i*kU6#n-nQK_q?UcO@Q1TSd) z&A>adYpo-Mv|CWu7zxYKlX08{>LrS=u%@ZQ=0tEHR$aNvP<+Lx&2;m`9ml3*L)n}& zpXDp0ti@EISR?!i?V@2dm}GQx2Pl4@Csfqx$rgUkLydS6Tv2c&VuiZ=N(;4xBPJ!- zwi^2A-CPDoxrO|YetURSHJgItX-IzF0lE2#=i9QHK9W_@aci6?G2bj%Cf);SPg#iL zX~TMceuA3RA&q27h6Wu(7VFh)ngo^9!ToB1U5FJ#78u)1d3l-G!GB~y$(AOvJHpLO zHau-c7JU~gg~t7*r;P|pl7{q4&krapR25CTjvGVr_vqmFHDo;}xf)DPv!HVjYm_5iaa^`#CR9MhF9EH%1S|MoUNg7S{Pp?%D+TyF5{*huf;3 ziKZ9FQ%~bOyH}6AyN=bXSiEnF24Xshs7HX*Gu|1}YSKDQ*JftUSq$p1aIpSBNtan> z^CFB8KVXo?6A>3J2GkNwK<;06FQ#s`x&Ea1!L?Ry6E}*Yd9OZ7X$IFhyHkaFjdhte z>4j+qi-EV)F1nG@c)POQ0=v0@tk+5BIhEK|A_n%$A;cRRW{&09-^)fPTIvVMFiCV+ zj*n5RpL0+zJRob!TDiwA=!eD{t9EkdPNnh!WtKd^o>5=SZ<;!=W!y^H{^)Y?TpH`aC}QX*S*b^EC@W7haJ2+srL~i| z+6_PFu{2ybLZ(N%5iol&0IC`IW@Nqj5J?HZBYEOotp1?^6X{}={b+a6x}EUlz=G$_ zNhB#WiHH)(6B}bK*hC!PSp}i55v92Eh-hN{qJ5JRgY)?UHoEt0Z=(~1=P5-%d&0wORWx z)bs~>wo#{QK_qPx;AiT^4@3E@(0jpNsSByO!XJk%3DxXm`xxAjSPaHL@$hwdPK6T` z$4x|aE_|c-8zoQ$o-vB!BANOGhejAgSvrnDNTTTFVw^oE?iWsrMat@4S&Ma z(hzsuBneFE`8uyoel3KyA7g&%*7 z0|@gWjaXh}I0&Fp;c-eEE>B*z{S3koEdI{1TS5(|-4AOx=Mm%~fzo3>8Swvqs8q6U zQcSjq-Zp198Y zO&o29P%MO-{Ox}0DR=+18}RSnGj7#>F{ zy<>*?4XQDG0rvO=(Wtoi5SQxr^C%HL_&^YSW9*pU;1h(>fp+$JABC!z-G2Czvj%Xk z3jDqX7jrdGjhDWJ8Y9J|C+twHBBRx>x*wrzSZ2ltBLX|xM<+MX{7zLl8h*Pa&J;Eh z>FD(#M|4J1W=9MRSVKEU5k*NOrJTOIKvcqR+7s+_=9cIul398uoxvc?b+j8dv1iOX zYSuird0?|?TK0&iu|21YS^(znxqCQ%YUdw{!zU`z)Xp{f!(_D=E^EV~{N`+7Yd%*! zaxY|yVUk+puzc-jTSChxt zg#NIFagCO2pxW#R`&P)=X6Y*JdCF{DhWqz?(6rfj8u#yKp|6uK?XS=PF=4QfOk9+c z*m)17zKU zEFdZu_8%<<4RG46@E@AI{l;MVgz-nYPrMMJ^Ij=MF1#>GN;I2pm_gWv>>KQ1eq*mv z!lMy$VU2j?$1j8qeq&P%!q{gei(aZ?K914g8J$u1m1%!+IoYdb^*z1f(WpL4fs&v| zd-abm=|lS8dZ8Qw&HIH{yj)F!tN6cec~z9fte{1hjdMdpW-BL|jq{>J&PTd|{~dPW z`vz~9@p$Y)2*+rb@l4u6E6hU853CepwN~YRV^1!^Yb}Aaw{P4HnFW*r-bLChbVg}E z+Bamo4nh|)G`H$?q87GNv_2U1?NcW+u_NHF%F~01h`UNDoQ;63UT-vO zx{f|(zaEf4=ei&!s2WntBA^2xI7knI z`9|M$fI(9_%8BR?ikz~gN zEN(}1Rfadm1t^Gx~ZnYpRozr;=Z11U4gN2A%g zhha{)ZU(=`Xi`x9#|Qa&sl`7R?6mz_q>JfM=VwLpr7^vaCh32TNEd^W&-0c%MbGon zIf)AHJY>ZR(L59Vdt<&j#}@lKFfTs+f`^nHp;#REz9lj0Ypt8`ZIRN*@m+*cFg@f3 z-5;!zLE@c|Fa7XZRNrI1zdLAuhEUv9mxVJ$`*>ViO-JgdML$iG21UxtzjvB-O22qB z09o=gQ~SsdO^IJTNsP;YD=kuq2iY01@=CNf5OdxDjT=@wsaAL zb*n!xH+Qi{a1vm8rMdkgf}_WZs7I^~%g+h>+s#)iovc#HxI1huijO z_mYxDJ-C+66JFkxnR;w06o_I}DoV#y8Sf8l~m)aT`TWx#4I%nfdG zr~vaQxXD$ywjx2g&{Sx5w~MC}&0k)7e!ZYx4a ze*)vgFpDM%q%4TpzP4`1B|>vM8e*;#wP1ziJIk4yM(HcK%0=mNt8Ez?Qi3V4Wq4Q$ zX4ICU*4Jmx+AY^UfR9^3sGt02y*$hXP(Nu*dDVVa+l{QSJoQB2tMxKiZI5hWM-Z>e zv>U!-MiBp%YFCqQJ5iudMQob?zK2kFVuZ*gp9#;;Q}N^*GgRV>NZQBtL7de7>}#fb zD1u9I>QvP{rauMSBx1jpv%j66{32>p9MvT97_err!uk#nj$Bb$VshiJhD6G z1e;m-Lx(fL>J1Y(g88C5yiAN5&V*_8KlFG+0e{|dxOUUo4^_k{eHh^+ zj0r(_Sl<;(3{_@{1t6Vu&(oPoIkv}p@cT*!n^E2Dxl@`enFGw1mC%^bC_)j2?o7=R zj-+ZfK3&9qec{Cq2NUa+*9JHHfG|>wUKHFw^5hEzJ^MxqY#)^$NA#7Zxd|dD_i&xBG9C z#o2ftUTzMg^l*$2cE_&$!`p4*j!oVI@#=dE`qQa4JQCF>>0?`$y!++T-uPthH8xbg zb5XW+!@B`Y5G{!#YBDnX+x~WufU=0}MA1E@sGg@@U(lxP^piLdp-UYFb_m|f`UPwG)Va7)CjvtJ*FZmIt5=;cx zE+Muee|IAdqFQ?JEBZ& z0W>EUdWTX1#f0-J8zvz@*VkvtZ8}y)>OAFm2_oMlxnnB}mSrtLsBHDMO)v1h&(E5D zmPZ(Bcd?e6BL!t);{S2FD!tngDaiyNH^M;KlwYvJ( z-qf>!<-T>iaVL>oawR&R|*TFoIrlY$EcNHqRom z?ezv^hoPUbiUlOXh8?58%TeU#7jSLVsp`FZ$yI*gFKcT2!&(Cr*#1R*S;jp=@+POh zpt1*p@;Hm#HfgVzM%;w$5Hp8mfK}0)1rD2e_563-+bb6H-`(H80}4Y!;(noFy19>b6){Wi13|$BhFL)BM-1Tved#h!lU7JBy!?g>IU6xC&i1!@mjT`^@dxr>hG-ZCH)l@BzCN!!n#Knd(&iu)HQ(vrQV;=` zq6SDW^UKvshYzQI(L70MR5XPr9y3C-(lkDUP{JzgOq_hY?!e-K3@3_zcqsa74tuuX zCL~tpM^2P1=g{qXFjJgE-x($7KKnp7Sh>{ZQ1C%2eZ9A@{2qc*>k-pOheB)M;!?vx zjdCer3xU>_ilh)pzbdeviez3-UqJ?@Mm@bOgIf`VV+5Of38D*b$X^vNDexQ+!RGhe zl4(tj&%q6n(?ha6@1>SE(?g0t?jukzp+TyX$UdszN7aCb%!Ag>Lws-`Q9tgxF3+fb+{BXk}T?oACNij^Gr z{ow*^+1a$HQJ!6G)!j&Jv2vDc0B+&a+hSGi*Z9JMS+HN@`C)s@nP ziqePidas=R5g9PubNY$fwbfOb(i5ir9qQn8&Iq&MFlLBRHtkULB-|xMt4MN5W)vLF z{vu(DEKd_(=GbuxtR0@9ERAW&Ow+hx4sYF;^QLjp zZeG8l2>zDa!`%i#OjbyL8ZU*qb}lS=DCvbGZ@-)^fjaI}=rcEE6kKh4CwOt34(EOl zTX_%KZ^Bfq0V7aJ-Pcew4F}@Iqb@>%OY|d6NZbazSG_x}*dPx|!-5gpThx@4{Sryr zTX5`@mo?Kg182DnnRqyJco%exh}kisEK9<9;bhx-phUhPZY7a9yj6Wh-DvmLIxO^% z3^(w6sn5v9_OgZdflZRH3ru@9$x)vPFrOr_)VK|hcvG?cQX01L3=yU9ezn;3lBy$F zMy1*HGBP6h%5v};O)1K_$9^1i$7yAnZ}*Y6VGXdU*r9ux&p46~`3bq!D!595ZA{>CJ_*o9n=I};m`}=Tc!B9UDZ3F(v7CGOasv>vFaSGmBGBOZXZ%-aZ&ut7-!ifD z{^l7pSE@BZKOtEBgf?nquwpz~+X4R^Z7(EOYiC((U)Tm$za`vBe=fc?_k9ErX5|$W zICxGd?2IyHt_QB;X>baOkS5}Y@*5wH-U-r(uCyX3yU>zPIZ#FQ&ZFGnVMbZcsYahg z{5U``DnppC!MVoERwTtz_1;Xh(g4$cGtqMVvDQW@V-Mg;p7b3a#-z0kHVq3t0aP}? zW4vIa!S0N$Ybcy9xop}cQ72=X(FBCKLTPI<84Y2e$uK_xsLeO3 z&XK1s@={lf;>)MJNR^*tN7U*Fpz`!6c9Oc4NPdYZ6@2hqm>z{`p1Be!P8TIE$1y@v zLi6dDkn2%I_m){j-D7p9#Pr+EX-j*gy`TD9BH@5D3coCV0f|!N0cFaE(R4zPHe@x6 zH;GVn3lxveegs+%37WrT_T|X9Bt*VIo?>I8dgZL5T4SXZBwwJ6mxy*LdMc*+6P@qj6(zm%diJGs>#%iRC)W+7D(YEqOrUf#4U zn(&B4hflZO>r--C4LZLhf830YZI$MqThFF$2c2KAK6d-Q$V>kSB{uYL4_!^oh@njd zvp6G$g!}B*fGihht)x$Oy|X%L@ktX&~-%1UikE@?Ieq4oOQw2R|?^>F{n zorf*mpw=C&%Z=u<-JsQZKt`Ao>xk94bxv5CQhe`JyU|zZ@2dvqOiwOWd^3jU6a;Q1 z=s&mBqO#hEna!hI^t61L?09FoR*|Q5h?RIQ9bw!I{0b{M2rfRtkA?o|%36yMjj`fo z*pJqY3LrjfmC|9zgqlwL#wHlknuYm++BL;cIc49Wt2&XKZnes}PSFW9%tpa%r|AbB zyrj^uZ%Xs2Th;{pF`3tL@bYGd>T6!Y!d8@@g5Db5=m&Y(-aa88jiAtVf|swf&rufF z_L3aF;y1=#X69z)rv*$$;>F;`+8fmRmLb=r{cnUxZ1 z>r+}oRfd|kjDG{feRL1Fzcf;EPNlW`lZtXgs8)HJe-+FuFPopianrd72~Na0@0o|{ z{tAPpcsn|tDZQ0%60zQ~iF1QaGwz^|XpS~+5;1VGS#9x6e`w*#qsEi?-g-p4!<^lD zyXyxt>?FNaOVP#P&yy)MujU2ggOtr9yH%+lr`4+9ueUM7{`Jd)LTS6w=O)G(qoftA zqOr~EBV@}y&!Xo*NKBGX)xH#DMjR>_XFC7V5A(w zb-NSd7{3<;{<-}$=wZOG_qK_&C?&>9mPo@=+Kd&J2F;oqeEJ~pSH3c``k-f*|HUbc zdHf`%0Z!>J{I`#^0ie3OF2p_hXqnrXJj*{RP4HQ?if81MD%T~jhuW1zo**a72C~S5 zDcv01fHsD$R>rDf` z^nZEMfFBKb(f^wd{a+sRzy9;T-ZS7e1Ag*&Mc7SIG_;vr~mjNExzy28Dg#kX-zupz#69HZh z;L8Ah%zybXfCmHkFaPDe{Fm?Y|LUy(p31*I%D)~8;GY1V#{a9I@vn~o_zZx*0Qd)h zcK~<>fIk5E0RQ&;Ko1Y}?f>@aKz|PO(?FjL^ua)n3-qx--wO1pK!5pfZwd5}K<^0j zi$G5Z^n*YT2=rV)Zw2&HKz{`EH$Yzl^e{l*0`x3EuL1NJKyUGHKLPX-K<@u3xQnlf6D=ZoDIm&fV>OH zpMd-b$bo>o$0Q0DC{M-~YQ; z1A8>EHv@Ytutx%W9?!|u&-ix_0G``{=WXD57So|{{UYoH%$Nl literal 16160 zcmb8WQ*@ng+^rqkwyh>jnxsL4#)`&)c}=08B7$HbARxQY|MT@fpElkFH(YVzllBzTzeX_kifo?`EU;^FVlctFCR;Gt zVO*!NUR^kIRvaVO41_6+xzcPAR zI#^)SH38|@5H3U9xz%`P$Lw}BTEL+2xWxKVrYHRKYWIzS>kmVV^A?N%XRcP^;!i`I zvsPEa#fs35lm0ncQoploec61(zBGPt$yy_BB+&IC53NPMzg^zTd}SO4EHZ zjF{6jaIFXqQCJ|64;|3G@eqBj1NdTyy{SD+djC`g>uWglue-&yBe?MAbC!+;#Cx|C z6?W>qUjJwn=fWzHQOfFe8a)v%>=nQ(tw{)gc`Y#$9{h&0c}UOEzuD^BSoY~djX>DV zD8nRb{1WNw=SQfdnKKN9qy@+4$OXFl2o=(d@$PtXKaNervM(D%U{gxq2#$Lfptdo+ z&So+wFDpxKfGu`glWF4S#J6Y{5O0V|C|vzkd~FPgT|BC4WMjsFND_k-U|_y3po8i$ z!?qXu;~Jd;VBL4$g7+W_u$zi;krq7SKWQELFf<70!Ve+l3oaC-HMQ&|5L3$Cvh;5E z@e(zO6_zeT8Fn+?yDXPKG?9Cmg<5Y8sK1g$A?>tX-}Orw zeJ~#uwltVL+4b$BMHE7 z3OgaWj*=3#-BP&JuD6mm{S}eryCe?7_ABpFD?(YyUs-tS65;p<h8} zuIy3W84<*hXyDkGp0_!=1k93-znu#{=~uKeYTlB*ctLMn9ga^r6cGk6&S^vfT61um zxqF+)yUXzv299U>tx{sFemWS}ziN%iKF(mx$sN*53taJR<2a@|XCcdk3_ckbZ73nm zYg(f$j={+a_jM^4aob%b$JcA1^8yN1qD}3jH~8nEd4#sPCLxU`FAZn>;SZ5;O>M=y z9PB4;-=P}#_7Uj}rgRr$e2e1Ue72UnJKtzIEo@K&wsz@Y<>iCb1P;)?AN-ot_E4E1 zW(a4wB;arQX(0vv!sZs)8xO^rTb|IZtsJFf8xs9Vc*cjo_T<50elP@O;un zkvDeDI5>j?tSK7h7H-2_Ioc*Ns0;kd7#m>-7gYjIZD{0}b8_sRk0ZWDe@wh*HH&el zWzPtoX=ceI3hKVxI3EU0gsf){9kma#rh7D~ua7YS+%lE1GhTDFJ{>-~ccv#H12c$T z$s`7(XWEytr8}R7f_4zPZDrgQ0P~TX2KXIcWXM^PMWWw{({|%@r?&-q`P`+V0#TZ? z$E(^fiWpQ-sfjBQf_%;_UbBOuvr(H0Yx#4mpNg8>XC<0wz}x2EVL`?o0`ut7vyPtm zZb-_}S{#43gQGAp8JG}xXatNCwi55d9MZeSxm}K@XTpZ_!71mv&e5w%iexFp{!~P+ zmm}Xf;C;T2Q`MQqLFZQISKxhaWoFr6V{KvF*b!}4Sytbud*y&3K?Il|%-C;E$(Ia} zN@IE8R$!%Lb*|AEGvYWYo9ILz5)bOHi^HX z@bcTwWRU@AY?O$bRZ6JQNHYU*S^d-v~_Dcmn-jD#9`;VJ*QOSp__;Vr_HCO~nH z!LR>Q{lI&nYR(z#s1`0LoBRj?I{~)ZC1MCx!z!EVApg+HGiQ6{z6KWF<%X(OY-=w| z4cQP;8kcvT7q@~gd7PT$`;*ifC9}pQx8VWV=WSoBsKRbIuV4H}qUQbrODx71A8zjN zAdNb5#<~Xbt-9&OkjyK&m}EB?$ib@>JPcuzM6TF_x%5<5fyyKk2(4u)m{>xOUFG$2 z-ek?aS??!EK3BG77%oUb*G-m?>ScOUCBk>k)0s^ltV_xMvi~!5W{~YBbVG6uXvOVI@bTEk&V>e~vpmpu zy0m2x-N%E!EB<*<)hjeS)Q=i<6SvLWV9<;EX zjh%=<>CmRjOM19|N-`WAtmrgRUKQI~nCM#z`A3@2`x9ms=<`C(0i14`mLk)+YR^af zO)VpN3bA|uYwQ!}lwodc2Cq2PeVbLXYhSb&9u2TZ0#W4>$;!OKedNHz?omGD5Pf(} zgs_{l=rRZrFF@Kxe^(7YWqOzydyCAw%LC3)YIKBLpdABXlvA}$N`Hb`7TATNCpDPy z?1b80Eyk)R-}KIic?Vs&%e~`35QLFNqtDUZQX60Iry}dg589a?fViMl6V87MrL_J| z`Un#25p#C4m25TUne%>Iw&+knhhD_7dQfJnHm((hy7NxyaJndxy74(q+kX!@z@<1Y z_@o`D5UV8bwN|OhpVV)+Ed=OETJfT37Ox5rJv*yEkIZ@9{~%(|_>2AOVzR zG_C)})&KC7o8?)lb9cliDM)5RuM>G&;5+o|@XJPJ!w(Z0YGR+R@nn%h3@X>1&Mp_D zuE&vth?=#X=ExTrX2Y(0Zyz@z&YxT7`5mn20f-$!O480EbTwEdCriU~#a3+%lo&EH zPS`RNKPKzssp3u&u76ul1y({TwJ6z-3QzfeO$LM5a+|YYy zFE>xF(Y{~4nzJKkPzo5HO?~Kp#c+o~c4gp+rx~f*S}l%pSU&a>VzUy-e_kYPX~A5y z0w|@reW5&_Cjl_I7an8ZL(J}c28hd1+D*%# z(_j{Vxr;6`eKG8F1(PiII1D=0(K3UGt~IIqu?Ck}3-FfDckNyyq_YN$u6o#AfJiqD zinSdz32GiKErqp*Cj(#}oNBf;%{>yXrE)nlL*Qc72dY!so%%C1)dTTQlNJ8VqXnWJV zDM}@j7Pfm7#12B_YlC*60VYBW9zE5k)&MN( zQx^C0u!;pJyBC8Ckrg=&FiH$YaYkR|ydt8N^|}6wF2LQSNs$aIiN@eSi>r{LF<8ZX z2%*gGM<)c@q&0n+TvGFm{@*030%0)jOXKOQpI&pD{fRg9@UJ(W{;0l+10SqIVLzHY z3zJypd-M$~MjND~YYxFE_MisPTSWpXyDtTjyvk>14?$O7tu=j4Fzymc)N{qILT7#j z99@)Ye9xL#7&1ZYD{?K?>YkKi;&XU>`B3@Nzm6+~$>MJPr~4dWe_E#LJ;-GjO8Stc z=%}qQKr?4XnqT<)e_0u>?TR~gsWQy(a?mt52V-P-1?!E+Bmg?Ok@OUa^Q!|C%onrz zK0R~;5G8iIK-+F@lroeIyki;dxDOY??4egW7NE+9CIb(xS)?uMueVV`7#Dz7$NO@R z)ZnNGer>M?Z2{N-Ctqp&c{<)1xDKlYHu_BL&bep36}fT01H5R1-(GeaVgQJsxX2~R z`qIl6SWeg-0lA$;h!}(gPJ#rmeDSMC7MczB6h-9zwC$P8^_1R<_gAZgGK)p!0G~$0 zzeW3EHAz=yI@dP_B-r!AGpx{)oPx zi4(71R3$@$dHA7Tbjc-ul|M3mP+@frrq$11!{mGpn~Xz2n~yj+#R*B-NwdS@kUNQ{MO5j*e$jz zm|JK{NBQ+Y1|u&2W;|@ABTVPbxx>d+k{j#W&Qc*PDt8+?gMC|dIXl53iPlMqakMT_ zkFI4I-$L^#NW1eiNG<7Vg;QNmU)lvPv-F4Jfx;8dbK?3 zx-}mlfb}N=<@@7mp_ErhOy zUx>4<1`W$>Cyg-3*L|o2o8v-;Ef$!YNTq^v1*W!fNkZD^4+i^$JX7+Ebd4VIW9(kL zd{COmOhS6FC2&5&FkI0f`8qUAgUu}p2R=bDb}Sf9H+VtQ%~Dlp!kuy_LHz0*b30E4 z5^t`YmAaCm%DyaBB@$2Y=rx-U6KcZS7Fk{sQkiFX2F9)!4ZpmO%k|k1(g={sa5DLP zkH{KgJ5_>ZP%7r z?;sMT4O5&n>U~mM6Frxzj;vAuAq!P(qaR+uvi(5Ow&6A4BheQ$IFBEXj5dRpOYy=| zDdBFfzfRx_?a==ctW~78c%l_7pGPbT1p_UTm8Anv#|I-(H|hiupuCps&x>DQ*bail z%fOCThlH0|zp@6hV5%2?Y9sPK>r^dQDDpfgJ^&2l8T|dEe@+9isdE*-Sb#o0sS*JPgWcn2UG+Xhdr#?UwJ2KuKZ z(98z6pJE*4hJ(_{caA)$hZ$m*eT@_#sV3$_cAsit>*|d6!4)4&fpPpoUjAIEwSSAB ziKG@?sWHz8gr-C|5S2b>5Yibal1959e>-L3Y*h^1v+HxZbbwv(<$XmLy01KLVtqwl zCo_uyft^N^p7D>pKGYjnO#S}G4{twH64KJ^BRS@jN}E-4r9O$4|9@Ni13B zT%2}VW-w3|`WVe1G0fy_O?vI}h2Uy=h6JBJ&3F5r&JS~?W2f1%I3)m0X{mFvn7iTT zXyX()7VH}2yHbdu$cBY@N^2G<>;(n2eAaa|Kawptb!mo9yFu>ZyEmyqD?F|g zCZwUIoH>)!!%pwzy%8kK%+~AUW--4FQ(_}Lx)5cfjHjE2<^(=*lVC9iA1aQmKiKG9 zg#?xB*f+Q*v3=5@k(Vjj4X5L+~gb)Wz}lDj^71(+yH9^nGsbw|H=bwG=x>Si3oKw z{N*!SM0Pq25CYRypIvHG`nz`92L^g#qh+%HyINs4GC&6LbIU7wenx+}0HKc8Bra>DF-2ZND0nW)p>mwXWSrIvH0-1+KS!`MSzC@Ibb! zuo1S>bNp4Dm&C|{T88GG&1CiuSpdK>yT&{$?1lc&Lu_Qx+kW?erY46+GsjbaQ|~V_ zKgJKN0`Gs&{f5fv1Zd@e4NanTIu9@cn>{KoPx&68%JWULfTnq80XrTIQP@2`#~X-s z?vqDsJ$pF)ivmqOK#T5I`l*_b@rr{#V(Bl_o&ebp&!u=Uay25cuxvC;3WSD=+9>GequgQ_HOm;JK{U)EfM5r zfz4VBZ48V@E`O|k5F+;uhoZ;O6_-DD7RRz8Q~}$XE!Q+YP=6U5Woj001;%zAt}uX(6>~^CEh}sCf(h!x9_LLpucjNHI zR9(piT{at!6CmEF*Z?XH{7yWP#xU6+@JOSk+#EumA$v-3=XY-Zny@wPOzP6$)1lM} zKF}tL2)oHvfGBtXVa<|RMuNf+Em1-!#yI4aLXUi>swl80vYK1>&NI*FBrjTrwudiv zD1c*$nWHk51uG-vR+@QoYnvNYBq}WaVA${}dzBUmUP#`In0y2;f4{@5G|A1IINsSa zaP%#cf>3$|y&!fcRFA8b;&MvkkE_pU!MO2RiRVeq`A)j?mlqlDioM5<=z@-&_o&UY zxgqu%=Fix*W)h8n(xZUD{vnFT!PCOU_@S^(ek@ghP$`tFHLDHVLPt|4L!pJt(B|%n zpXp$kZX(Nu*$}v|JPN;sr1X=R0iqGHDYkuJ8mPdiz|a-QC#PT_a~;872HDcRC=Z4q ztoRFK4ubMMy)Is@cO%joN~!GaGhOP0io5-3#(@JtKHRj-QH1YZgWMY?{oSLhx!~8- z!ku@-ZdY^nt}Yv4{%HRd$5I?vSp_Lb`X!HgpObrfQ;^$%nFrTTl@75?121GQ z$0Oc-zE&TFn{d5A=#5Btis;WXQMJl#LGA0T`&x?dE{ti|qVM`QgnjUgwn?QcQAM{1zpMDw3Hba}IzgFL$j9i$4yA zIc=5ok&CVhTB6Kzn+D+M3}$^=WVWqyW4Vj zyEt?@+3?WVuDz0rx`Ua6Uq^Td-YbT6bWj=nD?|bsP2FYPM1>%`1p&oWl}8p%fuo`r zg|lWX>em2MvK=+oS9si)HqAhbK;B_x^Mrp~>38qrseK<+;X{6-T;On5;w1T90Sd z692*#x6F#U>ruB3how%9L>JqkB@tl5;`=iNz^|qLxk@OHA>r4L= z!@-4I9MX?AGseXLjeFwQ-mr;b-pn&Kw$U`wM|OUS)Mg|31Spq^Ama!$Ne->bRo*As zEIkWHjQGcOzb;PWzuQb7v@?b&Mj_u_N}Q{WED@?e_I^yN_fvUYQiL|s{egpFe?T{d z5;1a)Nt@@~Y*-sXZou35Wr(L_>GI1 zzhgeS8S<pwdd%ooRlkBXmG*b~&7kCEnxU8uL6{Va>U2t=2J?uDJ6(fwt=j zyC(2_(ai+^kXlz*Jtxm4iG{mbve`j&r;xpRX@sXK1-W*_Zlug!^`PJp5@FU{7tH2(^RB zXd~ixD}B8uZFlH+!Yq2*Q$?D5;&Gjd;jMS5mmpUXfhq>RCzLMC#W7@@vVHv5eZm|U z)l7<6O8>8WR&I;*x8&2|V4PnGIk#fB>y!>ELoS~ep7CdhJt734Jh@s5l{&e zhdb+E;Ml5(WL@HEMRAQDwam8!cyXXk9F*>%x6xRy!CllvX-NI;mNFS>v+^VYV0+Xg zoS+4|Wa^q`*&gcwPS%y#3B6Uk1I$;fgRa9ISogfty=sI8;f~_54vqf0QzTAhV}%)043wHH}R+7>)&ue3(boV;BzVIK`;xmRMb}c!(mReAIA`T7`{dTPG-$>gWmN zl;Dfu%ls{jH%6ky=&;iP9DSMCcY{y1y)C0)BLe&*FxNGrL}Ks)+k zL~AAuD(B~#Ai~p^K5CuvvLcV|GfviQ%yZt_+I(E{!n7$S?YlC{NRTd$(3n$s^O=b7 zaf+!Mg$5JLsOnS^IB>tV1u|CJQ>F#lktW@5E-wUEg^7QYt6qpt(7euya~0K~3Z~x% zFUd4>fUF~=7Ipk(a)pGAc*<5!Q;fNA;_?LY#bD>9WYb{(^f+0f#WV9=;gpHcGYxcg)bu=D>EoPWl-_73HY-sZVbxwa+xs8%Bvi|#mmdy z;XUVZe-Uy*>%;saJJO9bua^zLti$offgRPJ})7gy>Ur`uftK+mxL*Z{t zmXmOY|D|kw^EY}ji-DQgfZ4Op&$tlozDy|pQtR4<-)*2H6&goh%idX@ZRgM3S6;oY za7YH?ixLn^j`Lr=37P_q6BnNuhlCZcVq$ACqmhr|M=S1w`{t%69^H&3P!UYhD)O6m zjup8}^G&_4&ru%MKj1MnPz7`O9gI^4A+sMlX zVQNnxG`%m^%cXfcO%$a8@!?|b=Qk{@S(x4ripE^h{06@=MU^QrY--~Ws+2`t0|bQK zbO+Q9Ki-jb6wje>wd!v(+F|R`U>7yhYaW&-ym#nbVx;sS*#YqzSKq{&6YaAa2}s_e zL_cuKI}I}T+NoA@f^cc_wbjLHXYSA%bdP6Ts;^Nl)U(Y$L4$P*a(Xt!AEQVkRlbiR z5)gmL+@o`{f@_-5N2Jeg1@`7npWcq5;8ov4+f~;zlqhSwC*|I1qG-Gug}rx4g0w91 z5DM}NDnaTxPK4)`m(T4%5(P~R%ieI(l(BC`$GZ2O;f?r0Fq!&0L>_k9eQ6`vmQX@C zGvi6oH&xD-WXh-Pb+(yU2Iv-HaQ>!0bB39qey1IHLpR&%D6AQBH>m8aH@YdZngWnd zkc*!*eSn(RVvCrK^mcBq=9^c_#9IcyrX;mOZ?-z;Gz&$UMrb<*p~MLFl^$PzVk{wR z#LJD%4>uh{Fjy)>K29)Qv}(BOm})p&e9248zwE)RXxkk|^m9bfmFsRh-|UL9$!*73 z_G|=PEMc4@h2L(xwod^pAVBCEZ( z`S$SsptLfl((oG^u9gfVE%9rKJmosi7i4R5f~~_C_~iY#kYlQjhzO{B!(-TVGF)Z8y&!fE$GJc zpX@A@3erKd3r&;8NxL9*6Vh*=fAo{i%b3|on30O=AviqCvn%8;fE;bjn4ii^^=53O46^5T_%rR3-$3A<=>a1ZVQ&V0f09!47|Iw ztbd1Ebxr)kqfSh^E-`i9*+fp&Loaice!QM6;G5K3dOR6uz(0zZxTn?PvO)!{?1Axa zqJ$s5x`j##JC3j&Z4!uq`_2Zcwm=AJpmiRyw+_)iqjs6LxaE9fh?T6wX-&qPn6_2n zip7$kgE31v;MW`sKx-9p*a|kvIlymBOV|@Y61Q3B?men1XP!0Mv}D92C?nq5-mQ_6 z4EqlEvO0`{af|x)$Pu^3(oRJaT z&W_q4y{MCgn!(P4UcT$Bf8&^BR!7FW7)+!bqtb6v{eF5+BnoNfAYE9v_HMK~Ykd9g zc#`9&0eFx{=`_0Y2til6zMNSJayv>%>Ou02mn?eG*IM7H0`J>5GxO7%UN-fxubs$> zh6#x6jTUOPnynJt!s{B-4OCeNN@5T`7n1&*?{)EmT89i#xI9!1q*@p;#0^p+5xWacP$N7of_4u)}cy5mlh8C2&DcSM}aR@@>?F z<1jw@q@*_19bU$w%k-=b&HYqq z?liigm5kxi!c>TE;_;{cVhvn0St=RGtTca*>xRAgPBg6i@c!<;`SqkSa)41O2m2Zg zE?hB+_Ile2{N{T#tt0mLJqGPzvm(|*iDXxXK?g~~$$ANid;vMQ*o25Q040J<-aQ`E zKI}U~D|O}h`y4K=cPztA#^KH8P~JO0BB#!OS2vThc8zGveHA79$J^idY;?cxtK(O#|6A%NHy0>9v-W zp!HY&p=q}C>Xl91dMGqkIK?T$Rq0e#TV$j`0k#HCfK|x9-3r#)^+iB zG@L)hU7d}r7IfEBudJld&0uobbX!^DRr!NDSB`Z(FZA@B)dm>0d$KPpK6}a4+R^j- z8y^Y#MH9=YB!PCPcbDuJ$n;Gv$YWw&;c!^XX)F0PVXwzA7TithaF-LEj_s&YKw zN|oD?e;!G8jyiF{$G5p>_6u(`MRwJW7zBI@&4I5bYDnJ!s%2&DaRN76eKElKUWd}8 zFa(NkaP5iMO*vx9xHRoNp(iv9S56oo5@wa)q=**#lj;jE?x1YcH<ZNfK zu<>6Ena+UMo|7PCM8O-JxiDQfQN92#uaT#=tjNIK++wbezUz zve#~Q@Fi|T?9gB*j0L}`Hv4?QW-Q6*;-s#Dy38yP33Pz)qRw!z{^DVVW9J!zN>yR} zgpePB_h8d%i1&Q54)-s$)p1_@eMFVw3vLw1GH#<{s~xG2`dX6Ik48A!kE}D^^bq{Z z-hbv#tB(e>n~pq&vnIF^HZ4tp(5qmF(;UETr|l31C`pZ`8yQ|OWls9J-En1+3$EKU zYRft0zfpRux;O5eu!E2-5YTrpF?|VXzbYyiL>TOwoGYal!nCLAHu(aI;Ga;H6#|Ob zuOGp6m59+YCtKPg@+^18kIY2RBII1#!u?`O)BK>@YC3otf_F(T*Hntag4WF$coHCC zQ4adm@Ho<&6Rl!RlpYLCcE|eK-R!o*6qnwta*U&`<9R&h8hzT=vFT7y>gvhxjkjy4 zrV)q{N`H@Is@y(WO>RE0rFK>(YMEY%8lYpP!8ui(>IwGni`k8$?NrjrRwqyGa(6kd zCX7JCJdzOr9KIQB;wqZ9dA;VJf)k|kM$bAnVLAKu=8lZ#JS#GiNlXO>$RDcHu6x$ytCg?rNQM9NcXAZXj1494ttXZ~xK0XQH>KlcHubZ|@qz^xtQr@DEIanYvO^Eigfw;fM-gpe)yTa2dS<7lbyF1BX<9 zSgHAuRLD}%pomY2!9InrOZaxuVt}XGBBjkgm8FC598&0MC%Q@2n7>^*`n$>Yy_*Q; zt#bdMqD;B^xcFU`uOGkJY&r8R?j-{cKNUB*>q1s(`v*ZQeXBR-D1hyA&u{a~-9Coe zZW9Z1q5D4Qno&Pr=gLgegFZtVCkb}S;r_LOtJ!WRG;hZApTJnR?n|?6#Xxg~HGKS6 z*aJAJ6VnOHv1z>0MXHc&awP_)uDkzglfPx>I<&jKUNEp!r6w+qX$3PeG?lJt zlBi90ySIYw1R z%9+v`-gSDDZzsEh!-u1&>zuw=CJYUM4@E}fM%DbX@b~iM_w#aS=Z?m@2Y*33 z8H+mmIm*>zp&J`a#&v|M%FYP}I~!7>A``f}aU%)qwrMopPoldeC;guA!k?&?5IJ=H zdo3{f7WQ8xO-`J9!AcTlFP*SA-hZ03<3o%{Cs^mfBSwkzw32o6Thf$HQ!`j~F!Ae| zchM)QvFo?pAm!(hv$r42@vT4Atcg;G;j%Wg$%7wOdLYzxjew`CtJO0jr+jEe9+W?l z&PSP_+GlC#R&J|S`W^M|f2}>5)LrYDBv9e7XE|6<0q?h@p+DpgdS(Hb`|}Q^-npd% zwYSh;PBj5WrlB5so^Of_)fH8MMCBFn9VHBkQ6BVTc0^p_Q`6mMuKbi0bnG-aa~RU7 zwC;{RJfn}c`Uck7^W(<4grh}vEYOw{mXN33D3S@UnVq!g}{oZBM9xCs$5 z17n>x8hAmAXejYau04ekNVylBY0W636@Xm|8oD7pP=a(Sxl3OcZz7UYop+9f$EWY+ z!qqGG-lHK$p~KO8w-2ZQrQB3NW9a_i=t~iri;}S}CZQJU=oW@=xw9%;wEMn#c}+(Z zmWV;G)$zpKNiL5vl`BUaMJOZOC#6Lp-Qjt^B#hO0(7skSGjix`Jj z?|iS^gpIfF6m$=%|vsK*1VQ@pZ& z#5E&|)%uWxH9du3^}EOY5h1|y)=kg#Mc2X&+bIdu_{puu#-(LXYwx=qCBcWvWGq_U zZ@9NX9|Fh5u4w3%l%0>%F39gUHsg{Z1{`7+B}vw*ww$~(v8K=<&LM6%d#U211=fGE zS<+|=qsJ-kCvvI+=bb2gb2*T1gg&ynjG`S|(ZQ1`&cdI}woV96^ye26ik= zy-o@TGDIv;hrL?X0%j`BG#|6B_+|0MC;8-MVw8DhHNc(bhh(urdm}m3H7vGuchFJg zq|lQ`AbE@cTF3yGl4Wn@Pl*d=+%*uW0}&Py|Dkm?Va;P`t>Y^!iikzr=lJyP=NS2W zXoxLNgc@P$7gS+&?9eO4^&tM(rW3x`dKvkwrYrBQ^k-K!lsK3G`dI`76@I79ZEumW z8{~?DRBe}jgul({Lkoq|gz&1UwwLxWs)vxK0r=;&ujw$CG9yT}hI0awBuVNYw2<4! zi_B=^IKlx!9e9EEM7v$1H(#^gMe+=Gaty_QUDCfhBVb?j?~VxA4gJ6Fh5p?M0lOez z4+QLhfc+1!`}wcE53uw3-*!F!+nxv5@c_FRVCMqtRe&7_u-gFk8UOAvfc*rpcK~({ zz^(z<1pr<@;OqbE%L5)c;Ew~|IN*f?UiZHqH|PKLumR8dUvC=lrT@#52K;Eii~iqy z=>PJd|Mj2$^_~H*8Ss<;%QFVNV!-zWd|kk|{V%^3@MQr{_Fpd+@L>V(^>K2l%(& z2YPs*Z~wPX2l{iMp9cD5pbrLmT%eBy`c|M%1^UZ>drP2)1bRoHUj%wWpdSQ!K%nOW zdMlup0{SDMzXAFhpoana7NBPVdJUk*0D6mm`w5_z0CN9-bMk+4Zy=ZcH;)E#Um)iN z^4ov&)&DI|1#(g#_XP4sAZPqHPXzKpAQ$}KazG$w1M)K~a|K=J0<`zIs@oygSUpd5o Date: Mon, 18 Jul 2022 10:01:43 +0100 Subject: [PATCH 024/322] Efficiency and naming changes. --- CMakeLists.txt | 6 ++--- dChatFilter/dChatFilter.cpp | 44 ++++++++++++++++++++----------------- dChatFilter/dChatFilter.h | 8 +++---- dNet/ClientPackets.cpp | 21 +++++------------- dNet/WorldPackets.cpp | 18 +++++++-------- dNet/WorldPackets.h | 2 +- 6 files changed, 47 insertions(+), 52 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index caa61e4e..a9218bdf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,10 +15,10 @@ foreach(variable ${variables}) # If the string contains a #, skip it if(NOT "${variable}" MATCHES "#") - # Split the variable into name and value + # Split the variable into name and value string(REPLACE "=" ";" variable ${variable}) - # Check that the length of the variable is 2 (name and value) + # Check that the length of the variable is 2 (name and value) list(LENGTH variable length) if(${length} EQUAL 2) @@ -83,7 +83,7 @@ make_directory(${CMAKE_BINARY_DIR}/locale) # Create a /logs directory make_directory(${CMAKE_BINARY_DIR}/logs) -# Copy ini files on first build +# Copy resource files on first build set(RESOURCE_FILES "authconfig.ini" "chatconfig.ini" "worldconfig.ini" "masterconfig.ini" "blacklist.dcf") foreach(resource_file ${RESOURCE_FILES}) if (NOT EXISTS ${PROJECT_BINARY_DIR}/${resource_file}) diff --git a/dChatFilter/dChatFilter.cpp b/dChatFilter/dChatFilter.cpp index eb6674a4..6389623e 100644 --- a/dChatFilter/dChatFilter.cpp +++ b/dChatFilter/dChatFilter.cpp @@ -37,15 +37,15 @@ dChatFilter::dChatFilter(const std::string& filepath, bool dontGenerateDCF) { while (res->next()) { std::string line = res->getString(1).c_str(); std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Transform to lowercase - m_YesYesWords.push_back(CalculateHash(line)); + m_ApprovedWords.push_back(CalculateHash(line)); } delete res; delete stmt; } dChatFilter::~dChatFilter() { - m_YesYesWords.clear(); - m_NoNoWords.clear(); + m_ApprovedWords.clear(); + m_DeniedWords.clear(); } void dChatFilter::ReadWordlistPlaintext(const std::string& filepath, bool whiteList) { @@ -55,8 +55,8 @@ void dChatFilter::ReadWordlistPlaintext(const std::string& filepath, bool whiteL while (std::getline(file, line)) { line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Transform to lowercase - if (whiteList) m_YesYesWords.push_back(CalculateHash(line)); - else m_NoNoWords.push_back(CalculateHash(line)); + if (whiteList) m_ApprovedWords.push_back(CalculateHash(line)); + else m_DeniedWords.push_back(CalculateHash(line)); } } } @@ -74,14 +74,14 @@ bool dChatFilter::ReadWordlistDCF(const std::string& filepath, bool whiteList) { if (hdr.formatVersion == formatVersion) { size_t wordsToRead = 0; BinaryIO::BinaryRead(file, wordsToRead); - if (whiteList) m_YesYesWords.reserve(wordsToRead); - else m_NoNoWords.reserve(wordsToRead); + if (whiteList) m_ApprovedWords.reserve(wordsToRead); + else m_DeniedWords.reserve(wordsToRead); size_t word = 0; for (size_t i = 0; i < wordsToRead; ++i) { BinaryIO::BinaryRead(file, word); - if (whiteList) m_YesYesWords.push_back(word); - else m_NoNoWords.push_back(word); + if (whiteList) m_ApprovedWords.push_back(word); + else m_DeniedWords.push_back(word); } return true; @@ -100,9 +100,9 @@ void dChatFilter::ExportWordlistToDCF(const std::string& filepath, bool whiteLis if (file) { BinaryIO::BinaryWrite(file, uint32_t(dChatFilterDCF::header)); BinaryIO::BinaryWrite(file, uint32_t(dChatFilterDCF::formatVersion)); - BinaryIO::BinaryWrite(file, size_t(whiteList ? m_YesYesWords.size() : m_NoNoWords.size())); + BinaryIO::BinaryWrite(file, size_t(whiteList ? m_ApprovedWords.size() : m_DeniedWords.size())); - for (size_t word : whiteList ? m_YesYesWords : m_NoNoWords) { + for (size_t word : whiteList ? m_ApprovedWords : m_DeniedWords) { BinaryIO::BinaryWrite(file, word); } @@ -110,16 +110,18 @@ void dChatFilter::ExportWordlistToDCF(const std::string& filepath, bool whiteLis } } -std::vector dChatFilter::IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList) { +std::vector> dChatFilter::IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList) { if (gmLevel > GAME_MASTER_LEVEL_FORUM_MODERATOR) return { }; //If anything but a forum mod, return true. if (message.empty()) return { }; - if (!whiteList && m_NoNoWords.empty()) return { "" }; + if (!whiteList && m_DeniedWords.empty()) return { { 0, message.length() } }; std::stringstream sMessage(message); std::string segment; std::regex reg("(!*|\\?*|\\;*|\\.*|\\,*)"); - std::vector listOfBadSegments = std::vector(); + std::vector> listOfBadSegments = std::vector>(); + + uint32_t position = 0; while (std::getline(sMessage, segment, ' ')) { std::string originalSegment = segment; @@ -130,18 +132,20 @@ std::vector dChatFilter::IsSentenceOkay(const std::string& message, size_t hash = CalculateHash(segment); if (std::find(m_UserUnapprovedWordCache.begin(), m_UserUnapprovedWordCache.end(), hash) != m_UserUnapprovedWordCache.end() && whiteList) { - listOfBadSegments.push_back(originalSegment); + listOfBadSegments.emplace_back(position, originalSegment.length()); } - if (std::find(m_YesYesWords.begin(), m_YesYesWords.end(), hash) == m_YesYesWords.end() && whiteList) { + if (std::find(m_ApprovedWords.begin(), m_ApprovedWords.end(), hash) == m_ApprovedWords.end() && whiteList) { m_UserUnapprovedWordCache.push_back(hash); - listOfBadSegments.push_back(originalSegment); + listOfBadSegments.emplace_back(position, originalSegment.length()); } - if (std::find(m_NoNoWords.begin(), m_NoNoWords.end(), hash) != m_NoNoWords.end() && !whiteList) { + if (std::find(m_DeniedWords.begin(), m_DeniedWords.end(), hash) != m_DeniedWords.end() && !whiteList) { m_UserUnapprovedWordCache.push_back(hash); - listOfBadSegments.push_back(originalSegment); + listOfBadSegments.emplace_back(position, originalSegment.length()); } + + position += segment.length() + 1; } return listOfBadSegments; @@ -153,4 +157,4 @@ size_t dChatFilter::CalculateHash(const std::string& word) { size_t value = hash(word); return value; -} \ No newline at end of file +} diff --git a/dChatFilter/dChatFilter.h b/dChatFilter/dChatFilter.h index 62a47242..7e7dd859 100644 --- a/dChatFilter/dChatFilter.h +++ b/dChatFilter/dChatFilter.h @@ -23,14 +23,14 @@ public: void ReadWordlistPlaintext(const std::string& filepath, bool whiteList); bool ReadWordlistDCF(const std::string& filepath, bool whiteList); void ExportWordlistToDCF(const std::string& filepath, bool whiteList); - std::vector IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList = true); + std::vector> IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList = true); private: bool m_DontGenerateDCF; - std::vector m_NoNoWords; - std::vector m_YesYesWords; + std::vector m_DeniedWords; + std::vector m_ApprovedWords; std::vector m_UserUnapprovedWordCache; //Private functions: size_t CalculateHash(const std::string& word); -}; \ No newline at end of file +}; diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index abb08688..b9f715ad 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -288,7 +288,7 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa } if (!receiver.empty()) { - if (std::string(receiver.c_str(), 4) == "[GM]") { + if (std::string(receiver.c_str(), 4) == "[GM]") { // Shift the string forward if we are speaking to a GM as the client appends "[GM]" if they are receiver = std::string(receiver.c_str() + 4, receiver.size() - 4); } } @@ -315,6 +315,9 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa if (res->next()) { idOfReceiver = res->getInt("id"); } + + delete stmt; + delete res; } if (user->GetIsBestFriendMap().find(receiver) == user->GetIsBestFriendMap().end() && idOfReceiver != LWOOBJID_EMPTY) { @@ -344,26 +347,14 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa } } - std::unordered_map unacceptedItems; - std::vector segments = Game::chatFilter->IsSentenceOkay(message, entity->GetGMLevel(), !(isBestFriend && chatLevel == 1)); + std::vector> segments = Game::chatFilter->IsSentenceOkay(message, entity->GetGMLevel(), !(isBestFriend && chatLevel == 1)); bool bAllClean = segments.empty(); - if (!bAllClean) { - for (const auto& item : segments) { - if (item == "") { - unacceptedItems.insert({ (char)0, (char)message.length()}); - break; - } - - unacceptedItems.insert({ message.find(item), item.length() }); - } - } - if (user->GetIsMuted()) { bAllClean = false; } user->SetLastChatMessageApproved(bAllClean); - WorldPackets::SendChatModerationResponse(sysAddr, bAllClean, requestID, receiver, unacceptedItems); + WorldPackets::SendChatModerationResponse(sysAddr, bAllClean, requestID, receiver, segments); } diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index 94792c91..54c925d6 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -188,28 +188,28 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu\n", entity->GetObjectID()); } -void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::unordered_map unacceptedItems) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); +void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector> unacceptedItems) { + CBITSTREAM + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); bitStream.Write(unacceptedItems.empty()); // Is sentence ok? bitStream.Write(0x16); // Source ID, unknown bitStream.Write(static_cast(requestID)); // request ID - bitStream.Write(static_cast(0)); // chat mode + bitStream.Write(static_cast(0)); // chat mode PacketUtils::WritePacketWString(receiver, 42, &bitStream); // receiver name - for (auto it : unacceptedItems) { - bitStream.Write(it.first); // start index - bitStream.Write(it.second); // length - } + for (auto it : unacceptedItems) { + bitStream.Write(it.first); // start index + bitStream.Write(it.second); // length + } for (int i = unacceptedItems.size(); 64 > i; i++) { bitStream.Write(0); } - SEND_PACKET + SEND_PACKET } void WorldPackets::SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel) { diff --git a/dNet/WorldPackets.h b/dNet/WorldPackets.h index 3508d6f0..b88602a4 100644 --- a/dNet/WorldPackets.h +++ b/dNet/WorldPackets.h @@ -18,7 +18,7 @@ namespace WorldPackets { void SendTransferToWorld(const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift); void SendServerState(const SystemAddress& sysAddr); void SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm); - void SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::unordered_map unacceptedItems); + void SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector> unacceptedItems); void SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel); } From b55606d41e562f635e202a84535082b56d059b44 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 18 Jul 2022 16:08:33 -0700 Subject: [PATCH 025/322] Fix the issue where we would create new worlds on ports that were still being used (#625) * Wait for world to shutdown We need to wait for the message that the world has shutdown before shutting it down. * Dont sent people to dead instances * Added shutting down check Added check for isShuttingDown * Update when we remove from master --- dMasterServer/InstanceManager.cpp | 4 ++-- dMasterServer/InstanceManager.h | 4 ++++ dMasterServer/MasterServer.cpp | 7 ++++--- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index 41d34cfc..7df1449f 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -280,7 +280,7 @@ bool InstanceManager::IsInstanceFull(Instance* instance, bool isFriendTransfer) Instance * InstanceManager::FindInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneId) { for (Instance* i : m_Instances) { - if (i && i->GetMapID() == mapID && i->GetCloneID() == cloneId && !IsInstanceFull(i, isFriendTransfer) && !i->GetIsPrivate() && !i->GetShutdownComplete()) { + if (i && i->GetMapID() == mapID && i->GetCloneID() == cloneId && !IsInstanceFull(i, isFriendTransfer) && !i->GetIsPrivate() && !i->GetShutdownComplete() && !i->GetIsShuttingDown()) { return i; } } @@ -290,7 +290,7 @@ Instance * InstanceManager::FindInstance(LWOMAPID mapID, bool isFriendTransfer, Instance * InstanceManager::FindInstance(LWOMAPID mapID, LWOINSTANCEID instanceID) { for (Instance* i : m_Instances) { - if (i && i->GetMapID() == mapID && i->GetInstanceID() == instanceID && !i->GetIsPrivate()) { + if (i && i->GetMapID() == mapID && i->GetInstanceID() == instanceID && !i->GetIsPrivate() && !i->GetShutdownComplete() && !i->GetIsShuttingDown()) { return i; } } diff --git a/dMasterServer/InstanceManager.h b/dMasterServer/InstanceManager.h index 5dc93849..ea261343 100644 --- a/dMasterServer/InstanceManager.h +++ b/dMasterServer/InstanceManager.h @@ -31,6 +31,7 @@ public: m_PendingAffirmations = {}; m_PendingRequests = {}; m_Ready = false; + m_IsShuttingDown = false; } const std::string& GetIP() const { return m_IP; } @@ -46,6 +47,8 @@ public: bool GetIsReady() const { return m_Ready; } void SetIsReady(bool value) { m_Ready = value; } + bool GetIsShuttingDown() const { return m_IsShuttingDown; } + void SetIsShuttingDown(bool value) { m_IsShuttingDown = value; } std::vector& GetPendingRequests() { return m_PendingRequests; } std::vector& GetPendingAffirmations() { return m_PendingAffirmations; } @@ -82,6 +85,7 @@ private: std::vector m_Players; SystemAddress m_SysAddr; bool m_Ready; + bool m_IsShuttingDown; std::vector m_PendingRequests; std::vector m_PendingAffirmations; diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 2e881934..634c98c4 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -311,7 +311,7 @@ int main(int argc, char** argv) { if (affirmTimeout == 1000) { instance->Shutdown(); - instance->SetShutdownComplete(true); + instance->SetIsShuttingDown(true); Game::im->RedirectPendingRequests(instance); } @@ -358,6 +358,7 @@ void HandlePacket(Packet* packet) { Instance* instance = Game::im->GetInstanceBySysAddr(packet->systemAddress); if (instance) { + Game::logger->Log("MasterServer", "Actually disconnected from zone %i clone %i instance %i port %i\n", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); Game::im->RemoveInstance(instance); //Delete the old } @@ -694,8 +695,8 @@ void HandlePacket(Packet* packet) { return; } - Game::logger->Log("MasterServer", "Got shutdown response\n"); - instance->SetShutdownComplete(true); + Game::logger->Log("MasterServer", "Got shutdown response from zone %i clone %i instance %i port %i\n", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); + instance->SetIsShuttingDown(true); break; } From ec4ed8fa7e37d1a9457a17580273e3db79e4e818 Mon Sep 17 00:00:00 2001 From: Demetri Van Sickle Date: Mon, 18 Jul 2022 16:44:21 -0700 Subject: [PATCH 026/322] Adding migration command to build script (updated) (#653) * Added checks for migration runner * Added migration command to build script --- build.sh | 5 +- dMasterServer/MasterServer.cpp | 107 +++++++++++++++++++-------------- 2 files changed, 66 insertions(+), 46 deletions(-) diff --git a/build.sh b/build.sh index 11562359..31eaa2c7 100755 --- a/build.sh +++ b/build.sh @@ -6,4 +6,7 @@ cd build cmake .. # Run make to build the project. To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `make -j8` -make \ No newline at end of file +make + +# Run migrations +./MasterServer -m diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 634c98c4..f71fd408 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -84,56 +84,73 @@ int main(int argc, char** argv) { Game::config = &config; Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); - - //Check CDClient exists - const std::string cdclient_path = "./res/CDServer.sqlite"; - std::ifstream cdclient_fd(cdclient_path); - if (!cdclient_fd.good()) { - Game::logger->Log("WorldServer", "%s could not be opened\n", cdclient_path.c_str()); - return EXIT_FAILURE; - } - cdclient_fd.close(); - - //Connect to CDClient - try { - CDClientDatabase::Connect(cdclient_path); - } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database\n"); - Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); - return EXIT_FAILURE; - } - - //Get CDClient initial information - try { - CDClientManager::Instance()->Initialize(); - } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database\n"); - Game::logger->Log("WorldServer", "May be caused by corrupted file: %s\n", cdclient_path.c_str()); - Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); - return EXIT_FAILURE; - } - - //Connect to the MySQL Database - std::string mysql_host = config.GetValue("mysql_host"); - std::string mysql_database = config.GetValue("mysql_database"); - std::string mysql_username = config.GetValue("mysql_username"); - std::string mysql_password = config.GetValue("mysql_password"); - - try { - Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); - } catch (sql::SQLException& ex) { - Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s\n", ex.what()); - return EXIT_FAILURE; - } - + if (argc > 1 && (strcmp(argv[1], "-m") == 0 || strcmp(argv[1], "--migrations") == 0)) { + //Connect to the MySQL Database + std::string mysql_host = config.GetValue("mysql_host"); + std::string mysql_database = config.GetValue("mysql_database"); + std::string mysql_username = config.GetValue("mysql_username"); + std::string mysql_password = config.GetValue("mysql_password"); + + try { + Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); + } catch (sql::SQLException& ex) { + Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s\n", ex.what()); + Game::logger->Log("MigrationRunner", "Migrations not run\n"); + return EXIT_FAILURE; + } + MigrationRunner::RunMigrations(); Game::logger->Log("MigrationRunner", "Finished running migrations\n"); return EXIT_SUCCESS; } + else { + + //Check CDClient exists + const std::string cdclient_path = "./res/CDServer.sqlite"; + std::ifstream cdclient_fd(cdclient_path); + if (!cdclient_fd.good()) { + Game::logger->Log("WorldServer", "%s could not be opened\n", cdclient_path.c_str()); + return EXIT_FAILURE; + } + cdclient_fd.close(); + + //Connect to CDClient + try { + CDClientDatabase::Connect(cdclient_path); + } catch (CppSQLite3Exception& e) { + Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database\n"); + Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); + return EXIT_FAILURE; + } + + //Get CDClient initial information + try { + CDClientManager::Instance()->Initialize(); + } catch (CppSQLite3Exception& e) { + Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database\n"); + Game::logger->Log("WorldServer", "May be caused by corrupted file: %s\n", cdclient_path.c_str()); + Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); + return EXIT_FAILURE; + } + + //Connect to the MySQL Database + std::string mysql_host = config.GetValue("mysql_host"); + std::string mysql_database = config.GetValue("mysql_database"); + std::string mysql_username = config.GetValue("mysql_username"); + std::string mysql_password = config.GetValue("mysql_password"); + + try { + Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); + } catch (sql::SQLException& ex) { + Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s\n", ex.what()); + 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. @@ -824,4 +841,4 @@ int FinalizeShutdown() { exit(EXIT_SUCCESS); return EXIT_SUCCESS; -} \ No newline at end of file +} From 3dfe363a6b05b6b8245b299755e59aecc7634ee3 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Tue, 19 Jul 2022 09:29:26 -0500 Subject: [PATCH 027/322] Added Aronwk and Simon to the readme (#657) * Added myself and Simon to the readme Me, since I've started to work on implementing mounts again. Simon for his work in Reverse engineering the client which has been helping over the years. Venture Vision and moving platforms/simple movers being two recent things that his RE has helped fix. moved the special thanks out a header at the suggestion of Xipho and Max, since these people have not directly contributed to the DLU codebase. made a section under the DLU team recognizing Blaster for the Logo that DLU uses bumped up the credits header to make formatting make more sense * Update based on feedback Credit Blaster builder as they requested. Remove duplicate entries for under DLU Team as requested --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 5781c7b8..9acd9abf 100644 --- a/README.md +++ b/README.md @@ -417,10 +417,11 @@ Here is a summary of the commands available in-game. All commands are prefixed b -## Credits +# Credits ## Active Contributors * [EmosewaMC](https://github.com/EmosewaMC) * [Jettford](https://github.com/Jettford) +* [Aaron K.](https://github.com/aronwk-aaron) ## DLU Team * [DarwinAnim8or](https://github.com/DarwinAnim8or) @@ -429,10 +430,6 @@ Here is a summary of the commands available in-game. All commands are prefixed b * [averysumner](https://github.com/codeshaunted) * [Jon002](https://github.com/jaller200) * [Jonny](https://github.com/cuzitsjonny) -* TheMachine -* Matthew -* [Raine](https://github.com/Rainebannister) -* Bricknave ### Research and tools * [lcdr](https://github.com/lcdr) @@ -444,11 +441,14 @@ Here is a summary of the commands available in-game. All commands are prefixed b ### Former contributors * TheMachine * Matthew -* Raine +* [Raine](https://github.com/Rainebannister) * Bricknave -### Special thanks +### Logo +* Cole Peterson (BlasterBuilder) + +## Special thanks * humanoid24 * pwjones1969 -* BlasterBuilder for the logo +* [Simon](https://github.com/SimonNitzsche) * ALL OF THE NETDEVIL AND LEGO TEAMS! From ed5ced0beda35910799aabb06d01d6830e1766eb Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 19 Jul 2022 14:51:35 -0700 Subject: [PATCH 028/322] Fix Model Component Serialization (#655) * Fix model component serialization * Update ModelComponent.h --- dCommon/dCommonVars.h | 3 +- dGame/Entity.cpp | 52 ++++++++----- dGame/dComponents/DestroyableComponent.cpp | 4 +- dGame/dComponents/DestroyableComponent.h | 2 +- dGame/dComponents/ModelComponent.cpp | 48 +++++------- dGame/dComponents/ModelComponent.h | 73 +++++++++---------- .../PropertyManagementComponent.cpp | 49 +++++++------ 7 files changed, 120 insertions(+), 111 deletions(-) diff --git a/dCommon/dCommonVars.h b/dCommon/dCommonVars.h index c458b9fb..77d51125 100644 --- a/dCommon/dCommonVars.h +++ b/dCommon/dCommonVars.h @@ -387,6 +387,7 @@ enum eReplicaComponentType : int32_t { COMPONENT_TYPE_PROPERTY = 36, //!< The Property Component COMPONENT_TYPE_SCRIPTED_ACTIVITY = 39, //!< The ScriptedActivity Component COMPONENT_TYPE_PHANTOM_PHYSICS = 40, //!< The PhantomPhysics Component + COMPONENT_TYPE_MODEL = 42, //!< The Model Component COMPONENT_TYPE_PROPERTY_ENTRANCE = 43, //!< The PhantomPhysics Component COMPONENT_TYPE_PROPERTY_MANAGEMENT = 45, //!< The PropertyManagement Component COMPONENT_TYPE_REBUILD = 48, //!< The Rebuild Component @@ -411,8 +412,6 @@ enum eReplicaComponentType : int32_t { COMPONENT_TYPE_POSSESSOR = 110, //!< The Possessor Component COMPONENT_TYPE_BUILD_BORDER = 114, //!< The Build Border Component COMPONENT_TYPE_DESTROYABLE = 1000, //!< The Destroyable Component - - COMPONENT_TYPE_MODEL = 5398484 //look man idk }; enum class UseItemResponse : uint32_t { diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index a063b3c6..c44db6f1 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -182,12 +182,18 @@ void Entity::Initialize() SimplePhysicsComponent* comp = new SimplePhysicsComponent(simplePhysicsComponentID, this); m_Components.insert(std::make_pair(COMPONENT_TYPE_SIMPLE_PHYSICS, comp)); - ModelComponent* modelcomp = new ModelComponent(0, this); + ModelComponent* modelcomp = new ModelComponent(this); m_Components.insert(std::make_pair(COMPONENT_TYPE_MODEL, modelcomp)); RenderComponent* render = new RenderComponent(this); m_Components.insert(std::make_pair(COMPONENT_TYPE_RENDER, render)); + auto destroyableComponent = new DestroyableComponent(this); + destroyableComponent->SetHealth(1); + destroyableComponent->SetMaxHealth(1.0f); + destroyableComponent->SetFaction(-1, true); + destroyableComponent->SetIsSmashable(true); + m_Components.insert(std::make_pair(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)); // We have all our components. return; } @@ -226,11 +232,6 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_RACING_STATS, nullptr)); } - PetComponent* petComponent; - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_ITEM) > 0 && !TryGetComponent(COMPONENT_TYPE_PET, petComponent)) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_ITEM, nullptr)); - } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_EXHIBIT, -1) >= 0) { m_Components.insert(std::make_pair(COMPONENT_TYPE_EXHIBIT, new LUPExhibitComponent(this))); } @@ -628,6 +629,23 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_SCRIPTED_ACTIVITY, new ScriptedActivityComponent(this, scriptedActivityID))); } + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MODEL, -1) != -1 && !GetComponent()) { + m_Components.insert(std::make_pair(COMPONENT_TYPE_MODEL, new ModelComponent(this))); + if (m_Components.find(COMPONENT_TYPE_DESTROYABLE) == m_Components.end()) { + auto destroyableComponent = new DestroyableComponent(this); + destroyableComponent->SetHealth(1); + destroyableComponent->SetMaxHealth(1.0f); + destroyableComponent->SetFaction(-1, true); + destroyableComponent->SetIsSmashable(true); + m_Components.insert(std::make_pair(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)); + } + } + + PetComponent* petComponent; + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_ITEM) > 0 && !TryGetComponent(COMPONENT_TYPE_PET, petComponent) && !HasComponent(COMPONENT_TYPE_MODEL)) { + m_Components.insert(std::make_pair(COMPONENT_TYPE_ITEM, nullptr)); + } + // Shooting gallery component if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SHOOTING_GALLERY) > 0) { m_Components.insert(std::make_pair(COMPONENT_TYPE_SHOOTING_GALLERY, new ShootingGalleryComponent(this))); @@ -876,8 +894,8 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke const auto& syncLDF = GetVar>(u"syncLDF"); - //limiting it to lot 14 right now - if (m_Settings.size() > 0 && m_TemplateID == 14) { + // Only sync for models. + if (m_Settings.size() > 0 && (GetComponent() && !GetComponent())) { outBitStream->Write1(); //ldf data RakNet::BitStream settingStream; @@ -1170,23 +1188,23 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType renderComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } + if (modelComponent) { + DestroyableComponent* destroyableComponent; + if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent) && !destroyableSerialized) { + destroyableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); + destroyableSerialized = true; + } + } + if (HasComponent(COMPONENT_TYPE_ZONE_CONTROL)) { outBitStream->Write(0x40000000); } // BBB Component, unused currently - // Need to to write0 so that is serlaizese correctly + // Need to to write0 so that is serialized correctly // TODO: Implement BBB Component outBitStream->Write0(); - - /* - if (m_Trigger != nullptr) - { - outBitStream->Write1(); - outBitStream->Write(m_Trigger->id); - } - */ } void Entity::ResetFlags() { diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 72194568..37d74a55 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -829,11 +829,11 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType m_Parent->Kill(owner); } -void DestroyableComponent::SetFaction(int32_t factionID) { +void DestroyableComponent::SetFaction(int32_t factionID, bool ignoreChecks) { m_FactionIDs.clear(); m_EnemyFactionIDs.clear(); - AddFaction(factionID); + AddFaction(factionID, ignoreChecks); } void DestroyableComponent::PushImmunity(int32_t stacks) diff --git a/dGame/dComponents/DestroyableComponent.h b/dGame/dComponents/DestroyableComponent.h index a1f57be4..ade3f4e8 100644 --- a/dGame/dComponents/DestroyableComponent.h +++ b/dGame/dComponents/DestroyableComponent.h @@ -282,7 +282,7 @@ public: * Sets the faction ID of this entity, overriding all previously set entries * @param factionID the faction ID to set */ - void SetFaction(int32_t factionID); + void SetFaction(int32_t factionID, bool ignoreChecks = false); /** * Returns whether or not the provided entity is an enemy of this entity diff --git a/dGame/dComponents/ModelComponent.cpp b/dGame/dComponents/ModelComponent.cpp index bb8bdfe4..65259912 100644 --- a/dGame/dComponents/ModelComponent.cpp +++ b/dGame/dComponents/ModelComponent.cpp @@ -1,42 +1,32 @@ #include "ModelComponent.h" #include "Entity.h" -ModelComponent::ModelComponent(uint32_t componentID, Entity* parent) : Component(parent) +ModelComponent::ModelComponent(Entity* parent) : Component(parent) { - m_Position = m_Parent->GetDefaultPosition(); - m_Rotation = m_Parent->GetDefaultRotation(); + m_OriginalPosition = m_Parent->GetDefaultPosition(); + m_OriginalRotation = m_Parent->GetDefaultRotation(); m_userModelID = m_Parent->GetVarAs(u"userModelID"); - - /* - for (auto set : m_Parent->GetInfo().settings) { - if (set && set->GetKey() == u"userModelID") { - m_userModelID = std::stoull(set->GetValueAsString()); - } - } - */ -} - -ModelComponent::~ModelComponent() { } void ModelComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - //item component: - outBitStream->Write1(); - outBitStream->Write(m_userModelID); - outBitStream->Write(0); - outBitStream->Write0(); + // ItemComponent Serialization. Pets do not get this serialization. + if (!m_Parent->HasComponent(COMPONENT_TYPE_PET)) { + outBitStream->Write1(); + outBitStream->Write(m_userModelID != LWOOBJID_EMPTY ? m_userModelID : m_Parent->GetObjectID()); + outBitStream->Write(0); + outBitStream->Write0(); + } //actual model component: - outBitStream->Write1(); //yes we are writing model info - outBitStream->Write0(); //?? - outBitStream->Write(2); //model type, always 2 for BBB + outBitStream->Write1(); // Yes we are writing model info + outBitStream->Write0(); // Is pickable + outBitStream->Write(2); // Physics type + outBitStream->Write(m_OriginalPosition); // Original position + outBitStream->Write(m_OriginalRotation); // Original rotation - outBitStream->Write(m_Position); - outBitStream->Write(m_Rotation); - - outBitStream->Write1(); //second data flag, all unknown. Maybe skip? - outBitStream->Write(0); - outBitStream->Write1(); - outBitStream->Write0(); + outBitStream->Write1(); // We are writing behavior info + outBitStream->Write(0); // Number of behaviors + outBitStream->Write1(); // Is this model paused + if (bIsInitialUpdate) outBitStream->Write0(); // We are not writing model editing info } diff --git a/dGame/dComponents/ModelComponent.h b/dGame/dComponents/ModelComponent.h index 3b13bab8..81342059 100644 --- a/dGame/dComponents/ModelComponent.h +++ b/dGame/dComponents/ModelComponent.h @@ -12,51 +12,50 @@ class Entity; */ class ModelComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MODEL; + static const uint32_t ComponentType = COMPONENT_TYPE_MODEL; - ModelComponent(uint32_t componentID, Entity* parent); - ~ModelComponent() override; + ModelComponent(Entity* parent); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Returns the position of the model - * @return the position of the model - */ - NiPoint3& GetPosition() { return m_Position; } + /** + * Returns the original position of the model + * @return the original position of the model + */ + const NiPoint3& GetPosition() { return m_OriginalPosition; } - /** - * Sets the position of the model - * @param pos the position to set - */ - void SetPosition(const NiPoint3& pos) { m_Position = pos; } + /** + * Sets the original position of the model + * @param pos the original position to set + */ + void SetPosition(const NiPoint3& pos) { m_OriginalPosition = pos; } - /** - * Returns the rotation of the model - * @return the rotation of the model - */ - NiQuaternion& GetRotation() { return m_Rotation; } + /** + * Returns the original rotation of the model + * @return the original rotation of the model + */ + const NiQuaternion& GetRotation() { return m_OriginalRotation; } - /** - * Sets the rotation of the model - * @param rot the rotation to set - */ - void SetRotation(const NiQuaternion& rot) { m_Rotation = rot; } + /** + * Sets the original rotation of the model + * @param rot the original rotation to set + */ + void SetRotation(const NiQuaternion& rot) { m_OriginalRotation = rot; } private: - /** - * The position of the model - */ - NiPoint3 m_Position; + /** + * The original position of the model + */ + NiPoint3 m_OriginalPosition; - /** - * The rotation of the model - */ - NiQuaternion m_Rotation; + /** + * The rotation original of the model + */ + NiQuaternion m_OriginalRotation; - /** - * The ID of the user that made the model - */ - LWOOBJID m_userModelID; -}; \ No newline at end of file + /** + * The ID of the user that made the model + */ + LWOOBJID m_userModelID; +}; diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index f27ea283..1168209c 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -360,20 +360,17 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N if (newEntity != nullptr) { EntityManager::Instance()->ConstructEntity(newEntity); - //Make sure the propMgmt doesn't delete our model after the server dies - //Trying to do this after the entity is constructed. Shouldn't really change anything but - //There was an issue with builds not appearing since it was placed above ConstructEntity. + // Make sure the propMgmt doesn't delete our model after the server dies + // Trying to do this after the entity is constructed. Shouldn't really change anything but + // There was an issue with builds not appearing since it was placed above ConstructEntity. PropertyManagementComponent::Instance()->AddModel(newEntity->GetObjectID(), spawnerID); } item->SetCount(item->GetCount() - 1); - //item->UnEquip(); - return; } item->SetCount(item->GetCount() - 1); - //item->UnEquip(); auto* node = new SpawnerNode(); @@ -402,6 +399,17 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N auto* spawner = dZoneManager::Instance()->GetSpawner(spawnerId); + auto ldfModelBehavior = new LDFData(u"modelBehaviors", 0); + auto userModelID = new LDFData(u"userModelID", id); + auto modelType = new LDFData(u"modelType", 2); + auto propertyObjectID = new LDFData(u"propertyObjectID", true); + auto componentWhitelist = new LDFData(u"componentWhitelist", 1); + info.nodes[0]->config.push_back(componentWhitelist); + info.nodes[0]->config.push_back(ldfModelBehavior); + info.nodes[0]->config.push_back(modelType); + info.nodes[0]->config.push_back(propertyObjectID); + info.nodes[0]->config.push_back(userModelID); + auto* model = spawner->Spawn(); models.insert_or_assign(model->GetObjectID(), spawnerId); @@ -412,8 +420,6 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N GameMessages::SendGetModelsOnProperty(entity->GetObjectID(), GetModels(), UNASSIGNED_SYSTEM_ADDRESS); - //item->SetCount(item->GetCount() - 1); - EntityManager::Instance()->GetZoneControlEntity()->OnZonePropertyModelPlaced(entity); }); // Progress place model missions @@ -669,6 +675,18 @@ void PropertyManagementComponent::Load() settings.push_back(modelType); settings.push_back(propertyObjectID); settings.push_back(userModelID); + } else { + auto modelType = new LDFData(u"modelType", 2); + auto userModelID = new LDFData(u"userModelID", id); + auto ldfModelBehavior = new LDFData(u"modelBehaviors", 0); + auto propertyObjectID = new LDFData(u"propertyObjectID", true); + auto componentWhitelist = new LDFData(u"componentWhitelist", 1); + + settings.push_back(componentWhitelist); + settings.push_back(ldfModelBehavior); + settings.push_back(modelType); + settings.push_back(propertyObjectID); + settings.push_back(userModelID); } node->config = settings; @@ -680,21 +698,6 @@ void PropertyManagementComponent::Load() auto* model = spawner->Spawn(); models.insert_or_assign(model->GetObjectID(), spawnerId); - - /* - EntityInfo info; - info.lot = lot; - info.pos = position; - info.rot = rotation; - info.settings = settings; - info.spawnerID = id; - - auto* model = EntityManager::Instance()->CreateEntity(info); - - EntityManager::Instance()->ConstructEntity(model); - - models.insert_or_assign(model->GetObjectID(), id); - */ } delete lookup; From 74343be871d9948b3a226b5f8c5dfcef056c3da9 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 19 Jul 2022 14:52:39 -0700 Subject: [PATCH 029/322] Enable _dynamic by default (#656) --- CMakeVariables.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeVariables.txt b/CMakeVariables.txt index db89fef7..fb59f455 100644 --- a/CMakeVariables.txt +++ b/CMakeVariables.txt @@ -8,7 +8,7 @@ LICENSE=AGPL-3.0 # 171022 - Unmodded client NET_VERSION=171022 # Debugging -# __dynamic=1 +__dynamic=1 # Set __dynamic to 1 to enable the -rdynamic flag for the linker, yielding some symbols in crashlogs. # __ggdb=1 # Set __ggdb to 1 to enable the -ggdb flag for the linker, including more debug info. From 835cf2b794d33827c99218a2a4191ffe4c62998e Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 19 Jul 2022 21:51:05 -0700 Subject: [PATCH 030/322] Add an AMF Deserializer as well as corresponding Unit Tests (#599) * Add AMFDeserializer Add an AMFDeserializer Reverted unrelated changes Add unit tests for AMFDeserializer Added unit tests for the AMFDeserializer Finish tests Finish the AMF deserializer tests. This commit finishes the positive test case and implements a load test case that is expected to take less than 1.5 seconds to process. Modularized tests Made tests a bit modular and split into more methods Specified binary read from file Specified that on the IO stream we are reading a binary file otherwise windows will terminate reading the binary file on seeing a 1A byte. Added more tests Added tests for unimplemented values and edited a test file to be more modular Updated test text Fix spacing Update AMFDeserializeTests.cpp * Update CMakeLists.txt * Update AMFDeserializeTests.cpp f Actually follow the AMF spec Update AMFDeserializeTests.cpp tabs Add in commented tests * Follow spec formatting Add Integer Tests Follow Spec more Follow spec * Use unique_ptr * Update AMFDeserialize.cpp Semantics Update AMFDeserialize.cpp Add new lines to EOF CMake fix * Add better std string read Co-authored-by: Daniel Seiler * make not static Co-authored-by: Daniel Seiler --- .gitignore | 4 +- dCommon/AMFDeserialize.cpp | 158 +++++++ dCommon/AMFDeserialize.h | 71 +++ dCommon/AMFFormat.h | 12 + dCommon/CMakeLists.txt | 1 + tests/AMFDeserializeTests.cpp | 404 ++++++++++++++++++ tests/CMakeLists.txt | 12 + tests/TestBitStreams/AMFBitStreamTest.bin | Bin 0 -> 329 bytes .../AMFBitStreamUnimplementedTest.bin | 1 + 9 files changed, 662 insertions(+), 1 deletion(-) create mode 100644 dCommon/AMFDeserialize.cpp create mode 100644 dCommon/AMFDeserialize.h create mode 100644 tests/AMFDeserializeTests.cpp create mode 100644 tests/TestBitStreams/AMFBitStreamTest.bin create mode 100644 tests/TestBitStreams/AMFBitStreamUnimplementedTest.bin diff --git a/.gitignore b/.gitignore index 28f8f297..3777608d 100644 --- a/.gitignore +++ b/.gitignore @@ -119,4 +119,6 @@ thirdparty/zlib-1.2.11/ .env docker/__pycache__ -docker-compose.override.yml \ No newline at end of file +docker-compose.override.yml + +!/tests/TestBitStreams/*.bin diff --git a/dCommon/AMFDeserialize.cpp b/dCommon/AMFDeserialize.cpp new file mode 100644 index 00000000..7f3f6d95 --- /dev/null +++ b/dCommon/AMFDeserialize.cpp @@ -0,0 +1,158 @@ +#include "AMFDeserialize.h" + +#include "AMFFormat.h" + +/** + * AMF3 Reference document https://rtmp.veriskope.com/pdf/amf3-file-format-spec.pdf + * AMF3 Deserializer written by EmosewaMC + */ + +AMFValue* AMFDeserialize::Read(RakNet::BitStream* inStream) { + if (!inStream) return nullptr; + AMFValue* returnValue = nullptr; + // Read in the value type from the bitStream + int8_t marker; + inStream->Read(marker); + // Based on the typing, create the value associated with that and return the base value class + switch (marker) { + case AMFValueType::AMFUndefined: { + returnValue = new AMFUndefinedValue(); + break; + } + + case AMFValueType::AMFNull: { + returnValue = new AMFNullValue(); + break; + } + + case AMFValueType::AMFFalse: { + returnValue = new AMFFalseValue(); + break; + } + + case AMFValueType::AMFTrue: { + returnValue = new AMFTrueValue(); + break; + } + + case AMFValueType::AMFInteger: { + returnValue = ReadAmfInteger(inStream); + break; + } + + case AMFValueType::AMFDouble: { + returnValue = ReadAmfDouble(inStream); + break; + } + + case AMFValueType::AMFString: { + returnValue = ReadAmfString(inStream); + break; + } + + case AMFValueType::AMFArray: { + returnValue = ReadAmfArray(inStream); + break; + } + + // TODO We do not need these values, but if someone wants to implement them + // then please do so and add the corresponding unit tests. + case AMFValueType::AMFXMLDoc: + case AMFValueType::AMFDate: + case AMFValueType::AMFObject: + case AMFValueType::AMFXML: + case AMFValueType::AMFByteArray: + case AMFValueType::AMFVectorInt: + case AMFValueType::AMFVectorUInt: + case AMFValueType::AMFVectorDouble: + case AMFValueType::AMFVectorObject: + case AMFValueType::AMFDictionary: { + throw static_cast(marker); + break; + } + default: + throw static_cast(marker); + break; + } + return returnValue; +} + +uint32_t AMFDeserialize::ReadU29(RakNet::BitStream* inStream) { + bool byteFlag = true; + uint32_t actualNumber{}; + uint8_t numberOfBytesRead{}; + while (byteFlag && numberOfBytesRead < 4) { + uint8_t byte{}; + inStream->Read(byte); + // Parse the byte + if (numberOfBytesRead < 3) { + byteFlag = byte & static_cast(1 << 7); + byte = byte << 1UL; + } + // Combine the read byte with our current read in number + actualNumber <<= 8UL; + actualNumber |= static_cast(byte); + // If we are not done reading in bytes, shift right 1 bit + if (numberOfBytesRead < 3) actualNumber = actualNumber >> 1UL; + numberOfBytesRead++; + } + return actualNumber; +} + +std::string AMFDeserialize::ReadString(RakNet::BitStream* inStream) { + auto length = ReadU29(inStream); + // Check if this is a reference + bool isReference = length % 2 == 1; + // Right shift by 1 bit to get index if reference or size of next string if value + length = length >> 1; + if (isReference) { + std::string value(length, 0); + inStream->Read(&value[0], length); + // Empty strings are never sent by reference + if (!value.empty()) accessedElements.push_back(value); + return value; + } else { + // Length is a reference to a previous index - use that as the read in value + return accessedElements[length]; + } +} + +AMFValue* AMFDeserialize::ReadAmfDouble(RakNet::BitStream* inStream) { + auto doubleValue = new AMFDoubleValue(); + double value; + inStream->Read(value); + doubleValue->SetDoubleValue(value); + return doubleValue; +} + +AMFValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream* inStream) { + auto arrayValue = new AMFArrayValue(); + auto sizeOfDenseArray = (ReadU29(inStream) >> 1); + if (sizeOfDenseArray >= 1) { + char valueType; + inStream->Read(valueType); // Unused + for (uint32_t i = 0; i < sizeOfDenseArray; i++) { + arrayValue->PushBackValue(Read(inStream)); + } + } else { + while (true) { + auto key = ReadString(inStream); + // No more values when we encounter an empty string + if (key.size() == 0) break; + arrayValue->InsertValue(key, Read(inStream)); + } + } + return arrayValue; +} + +AMFValue* AMFDeserialize::ReadAmfString(RakNet::BitStream* inStream) { + auto stringValue = new AMFStringValue(); + stringValue->SetStringValue(ReadString(inStream)); + return stringValue; +} + +AMFValue* AMFDeserialize::ReadAmfInteger(RakNet::BitStream* inStream) { + auto integerValue = new AMFIntegerValue(); + integerValue->SetIntegerValue(ReadU29(inStream)); + return integerValue; +} diff --git a/dCommon/AMFDeserialize.h b/dCommon/AMFDeserialize.h new file mode 100644 index 00000000..d03c150f --- /dev/null +++ b/dCommon/AMFDeserialize.h @@ -0,0 +1,71 @@ +#pragma once + +#include "BitStream.h" + +#include +#include + +class AMFValue; +class AMFDeserialize { + public: + /** + * Read an AMF3 value from a bitstream. + * + * @param inStream inStream to read value from. + * @return Returns an AMFValue with all the information from the bitStream in it. + */ + AMFValue* Read(RakNet::BitStream* inStream); + private: + /** + * @brief Private method to read a U29 integer from a bitstream + * + * @param inStream bitstream to read data from + * @return The number as an unsigned 29 bit integer + */ + uint32_t ReadU29(RakNet::BitStream* inStream); + + /** + * @brief Reads a string from a bitstream + * + * @param inStream bitStream to read data from + * @return The read string + */ + std::string ReadString(RakNet::BitStream* inStream); + + /** + * @brief Read an AMFDouble value from a bitStream + * + * @param inStream bitStream to read data from + * @return Double value represented as an AMFValue + */ + AMFValue* ReadAmfDouble(RakNet::BitStream* inStream); + + /** + * @brief Read an AMFArray from a bitStream + * + * @param inStream bitStream to read data from + * @return Array value represented as an AMFValue + */ + AMFValue* ReadAmfArray(RakNet::BitStream* inStream); + + /** + * @brief Read an AMFString from a bitStream + * + * @param inStream bitStream to read data from + * @return String value represented as an AMFValue + */ + AMFValue* ReadAmfString(RakNet::BitStream* inStream); + + /** + * @brief Read an AMFInteger from a bitStream + * + * @param inStream bitStream to read data from + * @return Integer value represented as an AMFValue + */ + AMFValue* ReadAmfInteger(RakNet::BitStream* inStream); + + /** + * List of strings read so far saved to be read by reference. + */ + std::vector accessedElements; +}; diff --git a/dCommon/AMFFormat.h b/dCommon/AMFFormat.h index 95863594..c3d0936c 100644 --- a/dCommon/AMFFormat.h +++ b/dCommon/AMFFormat.h @@ -308,6 +308,18 @@ public: \return Where the iterator ends */ _AMFArrayList_::iterator GetDenseIteratorEnd(); + + //! Returns the associative map + /*! + \return The associative map + */ + _AMFArrayMap_ GetAssociativeMap() { return this->associative; }; + + //! Returns the dense array + /*! + \return The dense array + */ + _AMFArrayList_ GetDenseArray() { return this->dense; }; }; //! The anonymous object value AMF type diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 7e047a9c..7262bfef 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -1,4 +1,5 @@ set(DCOMMON_SOURCES "AMFFormat.cpp" + "AMFDeserialize.cpp" "AMFFormat_BitStream.cpp" "BinaryIO.cpp" "dConfig.cpp" diff --git a/tests/AMFDeserializeTests.cpp b/tests/AMFDeserializeTests.cpp new file mode 100644 index 00000000..88405803 --- /dev/null +++ b/tests/AMFDeserializeTests.cpp @@ -0,0 +1,404 @@ +#include +#include +#include +#include + +#include "AMFDeserialize.h" +#include "AMFFormat.h" +#include "CommonCxxTests.h" + +std::unique_ptr ReadFromBitStream(RakNet::BitStream* bitStream) { + AMFDeserialize deserializer; + std::unique_ptr returnValue(deserializer.Read(bitStream)); + return returnValue; +} + +int ReadAMFUndefinedFromBitStream() { + CBITSTREAM + bitStream.Write(0x00); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFUndefined); + return 0; +} + +int ReadAMFNullFromBitStream() { + CBITSTREAM + bitStream.Write(0x01); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFNull); + return 0; +} + +int ReadAMFFalseFromBitStream() { + CBITSTREAM + bitStream.Write(0x02); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFFalse); + return 0; +} + +int ReadAMFTrueFromBitStream() { + CBITSTREAM + bitStream.Write(0x03); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFTrue); + return 0; +} + +int ReadAMFIntegerFromBitStream() { + CBITSTREAM + { + bitStream.Write(0x04); + // 127 == 01111111 + bitStream.Write(127); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); + // Check that the max value of a byte can be read correctly + ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 127); + } + bitStream.Reset(); + { + bitStream.Write(0x04); + bitStream.Write(UINT32_MAX); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); + // Check that we can read the maximum value correctly + ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 536870911); + } + bitStream.Reset(); + { + bitStream.Write(0x04); + // 131 == 10000011 + bitStream.Write(131); + // 255 == 11111111 + bitStream.Write(255); + // 127 == 01111111 + bitStream.Write(127); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); + // Check that short max can be read correctly + ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), UINT16_MAX); + } + bitStream.Reset(); + { + bitStream.Write(0x04); + // 255 == 11111111 + bitStream.Write(255); + // 127 == 01111111 + bitStream.Write(127); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); + // Check that 2 byte max can be read correctly + ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 16383); + } + return 0; +} + +int ReadAMFDoubleFromBitStream() { + CBITSTREAM + bitStream.Write(0x05); + bitStream.Write(25346.4f); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFDouble); + ASSERT_EQ(static_cast(res.get())->GetDoubleValue(), 25346.4f); + return 0; +} + +int ReadAMFStringFromBitStream() { + CBITSTREAM + bitStream.Write(0x06); + bitStream.Write(0x0F); + std::string toWrite = "stateID"; + for (auto e : toWrite) bitStream.Write(e); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFString); + ASSERT_EQ(static_cast(res.get())->GetStringValue(), "stateID"); + return 0; +} + +int ReadAMFArrayFromBitStream() { + CBITSTREAM + // Test empty AMFArray + bitStream.Write(0x09); + bitStream.Write(0x01); + bitStream.Write(0x01); + { + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFArray); + ASSERT_EQ(static_cast(res.get())->GetAssociativeMap().size(), 0); + ASSERT_EQ(static_cast(res.get())->GetDenseArray().size(), 0); + } + bitStream.Reset(); + // Test a key'd value + bitStream.Write(0x09); + bitStream.Write(0x01); + bitStream.Write(0x15); + for (auto e : "BehaviorID") if (e != '\0') bitStream.Write(e); + bitStream.Write(0x06); + bitStream.Write(0x0B); + for (auto e : "10447") if (e != '\0') bitStream.Write(e); + bitStream.Write(0x01); + { + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFArray); + ASSERT_EQ(static_cast(res.get())->GetAssociativeMap().size(), 1); + ASSERT_EQ(static_cast(static_cast(res.get())->FindValue("BehaviorID"))->GetStringValue(), "10447"); + } + // Test a dense array + return 0; +} + +/** + * This test checks that if we recieve an unimplemented AMFValueType + * we correctly throw an error and can actch it. + */ +int TestUnimplementedAMFValues() { + std::vector unimplementedValues = { + AMFValueType::AMFXMLDoc, + AMFValueType::AMFDate, + AMFValueType::AMFObject, + AMFValueType::AMFXML, + AMFValueType::AMFByteArray, + AMFValueType::AMFVectorInt, + AMFValueType::AMFVectorUInt, + AMFValueType::AMFVectorDouble, + AMFValueType::AMFVectorObject, + AMFValueType::AMFDictionary + }; + // Run unimplemented tests to check that errors are thrown if + // unimplemented AMF values are attempted to be parsed. + std::ifstream fileStream; + fileStream.open("AMFBitStreamUnimplementedTest.bin", std::ios::binary); + + // Read a test BitStream from a file + std::vector baseBitStream; + char byte = 0; + while (fileStream.get(byte)) { + baseBitStream.push_back(byte); + } + + fileStream.close(); + + for (auto amfValueType : unimplementedValues) { + RakNet::BitStream testBitStream; + for (auto element : baseBitStream) { + testBitStream.Write(element); + } + testBitStream.Write(amfValueType); + bool caughtException = false; + try { + ReadFromBitStream(&testBitStream); + } catch (AMFValueType unimplementedValueType) { + caughtException = true; + } + std::cout << "Testing unimplemented value " << amfValueType << " Did we catch an exception: " << (caughtException ? "YES" : "NO") << std::endl; + ASSERT_EQ(caughtException, true); + } + return 0; +} + +int TestLiveCapture() { + std::ifstream testFileStream; + testFileStream.open("AMFBitStreamTest.bin", std::ios::binary); + + // Read a test BitStream from a file + RakNet::BitStream testBitStream; + char byte = 0; + while (testFileStream.get(byte)) { + testBitStream.Write(byte); + } + + testFileStream.close(); + + auto resultFromFn = ReadFromBitStream(&testBitStream); + auto result = static_cast(resultFromFn.get()); + // Test the outermost array + + ASSERT_EQ(dynamic_cast(result->FindValue("BehaviorID"))->GetStringValue(), "10447"); + ASSERT_EQ(dynamic_cast(result->FindValue("objectID"))->GetStringValue(), "288300744895913279") + + // Test the execution state array + auto executionState = dynamic_cast(result->FindValue("executionState")); + ASSERT_NE(executionState, nullptr); + + auto strips = dynamic_cast(executionState->FindValue("strips"))->GetDenseArray(); + + ASSERT_EQ(strips.size(), 1); + + auto stripsPosition0 = dynamic_cast(strips[0]); + + auto actionIndex = dynamic_cast(stripsPosition0->FindValue("actionIndex")); + + ASSERT_EQ(actionIndex->GetDoubleValue(), 0.0f); + + auto stripIDExecution = dynamic_cast(stripsPosition0->FindValue("id")); + + ASSERT_EQ(stripIDExecution->GetDoubleValue(), 0.0f); + + auto stateIDExecution = dynamic_cast(executionState->FindValue("stateID")); + + ASSERT_EQ(stateIDExecution->GetDoubleValue(), 0.0f); + + auto states = dynamic_cast(result->FindValue("states"))->GetDenseArray(); + + ASSERT_EQ(states.size(), 1); + + auto firstState = dynamic_cast(states[0]); + + auto stateID = dynamic_cast(firstState->FindValue("id")); + + ASSERT_EQ(stateID->GetDoubleValue(), 0.0f); + + auto stripsInState = dynamic_cast(firstState->FindValue("strips"))->GetDenseArray(); + + ASSERT_EQ(stripsInState.size(), 1); + + auto firstStrip = dynamic_cast(stripsInState[0]); + + auto actionsInFirstStrip = dynamic_cast(firstStrip->FindValue("actions"))->GetDenseArray(); + + ASSERT_EQ(actionsInFirstStrip.size(), 3); + + auto actionID = dynamic_cast(firstStrip->FindValue("id")); + + ASSERT_EQ(actionID->GetDoubleValue(), 0.0f) + + auto uiArray = dynamic_cast(firstStrip->FindValue("ui")); + + auto xPos = dynamic_cast(uiArray->FindValue("x")); + auto yPos = dynamic_cast(uiArray->FindValue("y")); + + ASSERT_EQ(xPos->GetDoubleValue(), 103.0f); + ASSERT_EQ(yPos->GetDoubleValue(), 82.0f); + + auto stripID = dynamic_cast(firstStrip->FindValue("id")); + + ASSERT_EQ(stripID->GetDoubleValue(), 0.0f) + + auto firstAction = dynamic_cast(actionsInFirstStrip[0]); + + auto firstType = dynamic_cast(firstAction->FindValue("Type")); + + ASSERT_EQ(firstType->GetStringValue(), "OnInteract"); + + auto firstCallback = dynamic_cast(firstAction->FindValue("__callbackID__")); + + ASSERT_EQ(firstCallback->GetStringValue(), ""); + + auto secondAction = dynamic_cast(actionsInFirstStrip[1]); + + auto secondType = dynamic_cast(secondAction->FindValue("Type")); + + ASSERT_EQ(secondType->GetStringValue(), "FlyUp"); + + auto secondCallback = dynamic_cast(secondAction->FindValue("__callbackID__")); + + ASSERT_EQ(secondCallback->GetStringValue(), ""); + + auto secondDistance = dynamic_cast(secondAction->FindValue("Distance")); + + ASSERT_EQ(secondDistance->GetDoubleValue(), 25.0f); + + auto thirdAction = dynamic_cast(actionsInFirstStrip[2]); + + auto thirdType = dynamic_cast(thirdAction->FindValue("Type")); + + ASSERT_EQ(thirdType->GetStringValue(), "FlyDown"); + + auto thirdCallback = dynamic_cast(thirdAction->FindValue("__callbackID__")); + + ASSERT_EQ(thirdCallback->GetStringValue(), ""); + + auto thirdDistance = dynamic_cast(thirdAction->FindValue("Distance")); + + ASSERT_EQ(thirdDistance->GetDoubleValue(), 25.0f); + + return 0; +} + +int TestNullStream() { + auto result = ReadFromBitStream(nullptr); + ASSERT_EQ(result.get(), nullptr); + return 0; +} + +int AMFDeserializeTests(int argc, char** const argv) { + std::cout << "Checking that using a null bitstream doesnt cause exception" << std::endl; + if (TestNullStream()) return 1; + std::cout << "passed nullptr test, checking basic tests" << std::endl; + if (ReadAMFUndefinedFromBitStream() != 0) return 1; + if (ReadAMFNullFromBitStream() != 0) return 1; + if (ReadAMFFalseFromBitStream() != 0) return 1; + if (ReadAMFTrueFromBitStream() != 0) return 1; + if (ReadAMFIntegerFromBitStream() != 0) return 1; + if (ReadAMFDoubleFromBitStream() != 0) return 1; + if (ReadAMFStringFromBitStream() != 0) return 1; + if (ReadAMFArrayFromBitStream() != 0) return 1; + std::cout << "Passed basic test, checking live capture" << std::endl; + if (TestLiveCapture() != 0) return 1; + std::cout << "Passed live capture, checking unimplemented amf values" << std::endl; + if (TestUnimplementedAMFValues() != 0) return 1; + std::cout << "Passed all tests." << std::endl; + return 0; +} + +/** + * Below is the AMF that is in the AMFBitStreamTest.bin file that we are reading in + * from a bitstream to test. +args: amf3! +{ + "objectID": "288300744895913279", + "BehaviorID": "10447", + "executionState": amf3! + { + "strips": amf3! + [ + amf3! + { + "actionIndex": 0.0, + "id": 0.0, + }, + ], + "stateID": 0.0, + }, + "states": amf3! + [ + amf3! + { + "id": 0.0, + "strips": amf3! + [ + amf3! + { + "actions": amf3! + [ + amf3! + { + "Type": "OnInteract", + "__callbackID__": "", + }, + amf3! + { + "Distance": 25.0, + "Type": "FlyUp", + "__callbackID__": "", + }, + amf3! + { + "Distance": 25.0, + "Type": "FlyDown", + "__callbackID__": "", + }, + ], + "id": 0.0, + "ui": amf3! + { + "x": 103.0, + "y": 82.0, + }, + }, + ], + }, + ], +} + */ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index b0e2c28d..9c6e57d3 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,6 +1,7 @@ # create the testing file and list of tests create_test_sourcelist (Tests CommonCxxTests.cpp + AMFDeserializeTests.cpp TestNiPoint3.cpp TestLDFFormat.cpp ) @@ -13,6 +14,17 @@ target_link_libraries(CommonCxxTests ${COMMON_LIBRARIES}) set (TestsToRun ${Tests}) remove (TestsToRun CommonCxxTests.cpp) +# Copy test files to testing directory +configure_file( + ${CMAKE_SOURCE_DIR}/tests/TestBitStreams/AMFBitStreamTest.bin ${PROJECT_BINARY_DIR}/tests/AMFBitStreamTest.bin + COPYONLY +) + +configure_file( + ${CMAKE_SOURCE_DIR}/tests/TestBitStreams/AMFBitStreamUnimplementedTest.bin ${PROJECT_BINARY_DIR}/tests/AMFBitStreamUnimplementedTest.bin + COPYONLY +) + # Add all the ADD_TEST for each test foreach (test ${TestsToRun}) get_filename_component (TName ${test} NAME_WE) diff --git a/tests/TestBitStreams/AMFBitStreamTest.bin b/tests/TestBitStreams/AMFBitStreamTest.bin new file mode 100644 index 0000000000000000000000000000000000000000..05241f3517e805abc4e514b272b138709e6b1c49 GIT binary patch literal 329 zcmd;N6m?3?NG!|DFYESEy>K!3oc14N#$hZF9y+`F02etz*}5W zlvz;B$;`;fD4v)MQtFwPl3D>*z?zu?XEQPi<|k#PCYJy$P&Kl!Fg7qSH!-oWG_^D| zHZr#angui*Vipfv69?FAeu&w{oa{i0I72E6QrSfPfmW5I76D~s|Q^2_r;G6CLL>d49 literal 0 HcmV?d00001 diff --git a/tests/TestBitStreams/AMFBitStreamUnimplementedTest.bin b/tests/TestBitStreams/AMFBitStreamUnimplementedTest.bin new file mode 100644 index 00000000..624bc5c3 --- /dev/null +++ b/tests/TestBitStreams/AMFBitStreamUnimplementedTest.bin @@ -0,0 +1 @@ + BehaviorID \ No newline at end of file From 082a2a418f345c6c39ff6bca4f8ac60e39e0285f Mon Sep 17 00:00:00 2001 From: EmosewaMC <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 19 Jul 2022 23:25:50 -0700 Subject: [PATCH 031/322] Use radii from settings Override the DB aggro and tether radii from the settings if they are present. --- dGame/dComponents/BaseCombatAIComponent.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 0903e621..4623e4dd 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -61,6 +61,15 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) componentResult.finalize(); + // Get aggro and tether radius from settings and use this if it is present. Only overwrite the + // radii if it is greater than the one in the database. + if (m_Parent) { + auto aggroRadius = m_Parent->GetVar(u"aggroRadius"); + m_AggroRadius = std::max(aggroRadius, m_AggroRadius); + auto tetherRadius = m_Parent->GetVar(u"tetherRadius"); + m_HardTetherRadius = std::max(tetherRadius, m_HardTetherRadius); + } + /* * Find skills */ From 74bca382534ea4f898855b22271cbbc99ede3ee1 Mon Sep 17 00:00:00 2001 From: Daniel Seiler Date: Wed, 20 Jul 2022 10:23:53 +0200 Subject: [PATCH 032/322] MSVC: set source / target encoding (#659) --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a9218bdf..65df9a35 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -63,7 +63,7 @@ if(UNIX) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -O2 -fPIC") elseif(MSVC) # Skip warning for invalid conversion from size_t to uint32_t for all targets below for now - add_compile_options("/wd4267") + add_compile_options("/wd4267" "/utf-8") elseif(WIN32) add_compile_definitions(_CRT_SECURE_NO_WARNINGS) endif() From 45a7dbdadd1a30ef3b54fc0e0507f627efb251bb Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 20 Jul 2022 01:28:57 -0700 Subject: [PATCH 033/322] Add Unimplemented GameMessages (#662) --- dGame/dGameMessages/GameMessageHandler.cpp | 4 +++ dGame/dGameMessages/GameMessages.cpp | 36 ++++++++++++++++++++++ dGame/dGameMessages/GameMessages.h | 33 ++++++++++++++++++++ dNet/dMessageIdentifiers.h | 3 ++ 4 files changed, 76 insertions(+) diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index cdaae38c..261a3105 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -535,6 +535,10 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleBBBSaveRequest(inStream, entity, sysAddr); break; + case GAME_MSG_CONTROL_BEHAVIOR: + GameMessages::HandleControlBehaviors(inStream, entity, sysAddr); + break; + case GAME_MSG_PROPERTY_ENTRANCE_SYNC: GameMessages::HandlePropertyEntranceSync(inStream, entity, sysAddr); break; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 292afc71..ba410b70 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -2420,6 +2420,42 @@ void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* SEND_PACKET; } +void GameMessages::SendSmash(Entity* entity, float force, float ghostOpacity, LWOOBJID killerID, bool ignoreObjectVisibility) { + CBITSTREAM + CMSGHEADER + + bitStream.Write(entity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_SMASH); + + bitStream.Write(ignoreObjectVisibility); + bitStream.Write(force); + bitStream.Write(ghostOpacity); + bitStream.Write(killerID); + + SEND_PACKET_BROADCAST +} + +void GameMessages::SendUnSmash(Entity* entity, LWOOBJID builderID, float duration) { + CBITSTREAM + CMSGHEADER + + bitStream.Write(entity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_UNSMASH); + + bitStream.Write(builderID != LWOOBJID_EMPTY); + if (builderID != LWOOBJID_EMPTY) bitStream.Write(builderID); + + bitStream.Write(duration != 3.0f); + if (duration != 3.0f) bitStream.Write(duration); + + SEND_PACKET_BROADCAST +} + +void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + // TODO + Game::logger->Log("GameMessages", "Recieved Control Behavior GameMessage, but property behaviors are unimplemented.\n"); +} + void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { /* ___ ___ diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 18e1467e..fc49ad70 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -122,6 +122,39 @@ namespace GameMessages { void SendStartCelebrationEffect(Entity* entity, const SystemAddress& sysAddr, int celebrationID); + /** + * Sends a message to an Entity to smash itself, but not delete or destroy itself from the world + * + * @param entity The Entity that will smash itself into bricks + * @param force The force the Entity will be smashed with + * @param ghostOpacity The ghosting opacity of the smashed Entity + * @param killerID The Entity that invoked the smash, if none exists, this should be LWOOBJID_EMPTY + * @param ignoreObjectVisibility Whether or not to ignore the objects visibility + */ + void SendSmash(Entity* entity, float force, float ghostOpacity, LWOOBJID killerID, bool ignoreObjectVisibility = false); + + /** + * Sends a message to an Entity to UnSmash itself (aka rebuild itself over a duration) + * + * @param entity The Entity that will UnSmash itself + * @param builderID The Entity that invoked the build (LWOOBJID_EMPTY if none exists or invoked the rebuild) + * @param duration The duration for the Entity to rebuild over. 3 seconds by default + */ + void SendUnSmash(Entity* entity, LWOOBJID builderID = LWOOBJID_EMPTY, float duration = 3.0f); + + /** + * @brief This GameMessage is the one that handles all of the property behavior incoming messages from the client. + * + * The GameMessage struct can be located here https://lcdruniverse.org/lu_packets/lu_packets/world/gm/server/struct.ControlBehaviors.html + * For information on the AMF3 format can be found here https://rtmp.veriskope.com/pdf/amf3-file-format-spec.pdf + * For any questions regarding AMF3 you can contact EmosewaMC on GitHub + * + * @param inStream The incoming data sent from the client + * @param entity The Entity that sent the message + * @param sysAddr The SystemAddress that sent the message + */ + void HandleControlBehaviors(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + // Rails stuff void SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForward, std::u16string pathName, uint32_t pathStart, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, diff --git a/dNet/dMessageIdentifiers.h b/dNet/dMessageIdentifiers.h index 5ad3921c..cb46b5d1 100644 --- a/dNet/dMessageIdentifiers.h +++ b/dNet/dMessageIdentifiers.h @@ -274,6 +274,7 @@ enum GAME_MSG : unsigned short { GAME_MSG_REQUEST_DIE = 38, GAME_MSG_PLAY_EMOTE = 41, GAME_MSG_PLAY_ANIMATION = 43, + GAME_MSG_CONTROL_BEHAVIOR = 48, GAME_MSG_SET_NAME = 72, GAME_MSG_ECHO_START_SKILL = 118, GAME_MSG_START_SKILL = 119, @@ -345,6 +346,8 @@ enum GAME_MSG : unsigned short { GAME_MSG_DISPLAY_MESSAGE_BOX = 529, GAME_MSG_MESSAGE_BOX_RESPOND = 530, GAME_MSG_CHOICE_BOX_RESPOND = 531, + GAME_MSG_SMASH = 537, + GAME_MSG_UNSMASH = 538, GAME_MSG_SET_SHOOTING_GALLERY_RETICULE_EFFECT = 548, GAME_MSG_PLACE_MODEL_RESPONSE = 0x223, GAME_MSG_SET_JET_PACK_MODE = 561, From 40a9aefb5bacd2d5c5a6f357ec2d46fdc6c04718 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 20 Jul 2022 20:26:52 -0700 Subject: [PATCH 034/322] Aggro radius (#665) --- dGame/dComponents/BaseCombatAIComponent.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 4623e4dd..bfa000f2 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -65,9 +65,9 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) // radii if it is greater than the one in the database. if (m_Parent) { auto aggroRadius = m_Parent->GetVar(u"aggroRadius"); - m_AggroRadius = std::max(aggroRadius, m_AggroRadius); + m_AggroRadius = aggroRadius != 0 ? aggroRadius : m_AggroRadius; auto tetherRadius = m_Parent->GetVar(u"tetherRadius"); - m_HardTetherRadius = std::max(tetherRadius, m_HardTetherRadius); + m_HardTetherRadius = tetherRadius != 0 ? tetherRadius : m_HardTetherRadius; } /* From 5523b6aafc346f1e368682badda9b4fe49279e84 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Thu, 21 Jul 2022 21:09:25 -0500 Subject: [PATCH 035/322] Refactor UpdateEntities to not lose items if we add them while processing (#664) * if we are deleting entities, and we add an entity to delete, dont throw it out * made it all uniform * change update back to how it was since it's an unordere map and wouldn't be guaranteed to update even in this secnario --- dGame/EntityManager.cpp | 125 +++++++++++++++------------------------- 1 file changed, 48 insertions(+), 77 deletions(-) diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index da0cf685..d6e6256f 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -74,7 +74,7 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE // For non player entites, we'll generate a new ID or set the appropiate flags else if (user == nullptr || info.lot != 1) { - + // Entities with no ID already set, often spawned entities, we'll generate a new sequencial ID if (info.id == 0) { id = ObjectIDManager::Instance()->GenerateObjectID(); @@ -104,7 +104,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 @@ -117,7 +117,7 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE // Initialize the entity entity->Initialize(); - + // Add the entity to the entity map m_Entities.insert_or_assign(id, entity); @@ -162,110 +162,81 @@ void EntityManager::DestroyEntity(Entity* entity) { void EntityManager::UpdateEntities(const float deltaTime) { for (const auto& e : m_Entities) { - e.second->Update(deltaTime); + e.second->Update(deltaTime); } - for (const auto entityId : m_EntitiesToSerialize) - { - auto* entity = GetEntity(entityId); + for (auto entry = m_EntitiesToSerialize.begin(); entry != m_EntitiesToSerialize.end(); entry++) { + auto* entity = GetEntity(*entry); if (entity == nullptr) continue; m_SerializationCounter++; RakNet::BitStream stream; - stream.Write(static_cast(ID_REPLICA_MANAGER_SERIALIZE)); stream.Write(static_cast(entity->GetNetworkId())); entity->WriteBaseReplicaData(&stream, PACKET_TYPE_SERIALIZATION); entity->WriteComponents(&stream, PACKET_TYPE_SERIALIZATION); - if (entity->GetIsGhostingCandidate()) - { - for (auto* player : Player::GetAllPlayers()) - { - if (player->IsObserved(entityId)) - { + if (entity->GetIsGhostingCandidate()) { + for (auto* player : Player::GetAllPlayers()) { + if (player->IsObserved(*entry)) { Game::server->Send(&stream, player->GetSystemAddress(), false); } } - } - else - { + } else { Game::server->Send(&stream, UNASSIGNED_SYSTEM_ADDRESS, true); } } - m_EntitiesToSerialize.clear(); - for (const auto& entry : m_EntitiesToKill) - { - auto* entity = GetEntity(entry); + for (auto entry = m_EntitiesToKill.begin(); entry != m_EntitiesToKill.end(); entry++) { + auto* entity = GetEntity(*entry); if (!entity) continue; - if (entity->GetScheduledKiller()) - { + if (entity->GetScheduledKiller()) { entity->Smash(entity->GetScheduledKiller()->GetObjectID(), SILENT); - } - else - { - entity->Smash(LWOOBJID_EMPTY, SILENT); + } else { + entity->Smash(LWOOBJID_EMPTY, SILENT); } } - m_EntitiesToKill.clear(); - for (const auto entry : m_EntitiesToDelete) - { + for (auto entry = m_EntitiesToDelete.begin(); entry != m_EntitiesToDelete.end(); entry++) { + // Get all this info first before we delete the player. - auto entityToDelete = GetEntity(entry); - + auto entityToDelete = GetEntity(*entry); auto networkIdToErase = entityToDelete->GetNetworkId(); - const auto& ghostingToDelete = std::find(m_EntitiesToGhost.begin(), m_EntitiesToGhost.end(), entityToDelete); - if (entityToDelete) - { + if (entityToDelete) { // If we are a player run through the player destructor. - if (entityToDelete->IsPlayer()) - { + if (entityToDelete->IsPlayer()) { delete dynamic_cast(entityToDelete); - } - else - { + } else { delete entityToDelete; } - entityToDelete = nullptr; - - if (networkIdToErase != 0) - { - m_LostNetworkIds.push(networkIdToErase); - } + if (networkIdToErase != 0) m_LostNetworkIds.push(networkIdToErase); } - if (ghostingToDelete != m_EntitiesToGhost.end()) - { - m_EntitiesToGhost.erase(ghostingToDelete); - } + if (ghostingToDelete != m_EntitiesToGhost.end()) m_EntitiesToGhost.erase(ghostingToDelete); - m_Entities.erase(entry); - + m_Entities.erase(*entry); } - m_EntitiesToDelete.clear(); } Entity * EntityManager::GetEntity(const LWOOBJID& objectId) const { const auto& index = m_Entities.find(objectId); - + if (index == m_Entities.end()) { return nullptr; } - + return index->second; } @@ -286,7 +257,7 @@ std::vector EntityManager::GetEntitiesByComponent(const int componentTy std::vector withComp; for (const auto& entity : m_Entities) { if (componentType != -1 && !entity.second->HasComponent(componentType)) continue; - + withComp.push_back(entity.second); } return withComp; @@ -331,7 +302,7 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr if (entity->GetNetworkId() == 0) { uint16_t networkId; - + if (!m_LostNetworkIds.empty()) { networkId = m_LostNetworkIds.top(); @@ -344,7 +315,7 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr entity->SetNetworkId(networkId); } - + const auto checkGhosting = entity->GetIsGhostingCandidate(); if (checkGhosting) @@ -365,13 +336,13 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr } m_SerializationCounter++; - + RakNet::BitStream stream; stream.Write(static_cast(ID_REPLICA_MANAGER_CONSTRUCTION)); stream.Write(true); stream.Write(static_cast(entity->GetNetworkId())); - + entity->WriteBaseReplicaData(&stream, PACKET_TYPE_CONSTRUCTION); entity->WriteComponents(&stream, PACKET_TYPE_CONSTRUCTION); @@ -430,7 +401,7 @@ void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr) { return; } - + RakNet::BitStream stream; stream.Write(static_cast(ID_REPLICA_MANAGER_DESTRUCTION)); @@ -467,7 +438,7 @@ void EntityManager::DestructAllEntities(const SystemAddress& sysAddr) { } } -void EntityManager::SetGhostDistanceMax(float value) +void EntityManager::SetGhostDistanceMax(float value) { m_GhostDistanceMaxSquared = value * value; } @@ -477,7 +448,7 @@ float EntityManager::GetGhostDistanceMax() const return std::sqrt(m_GhostDistanceMaxSquared); } -void EntityManager::SetGhostDistanceMin(float value) +void EntityManager::SetGhostDistanceMin(float value) { m_GhostDistanceMinSqaured = value * value; } @@ -487,7 +458,7 @@ float EntityManager::GetGhostDistanceMin() const return std::sqrt(m_GhostDistanceMinSqaured); } -void EntityManager::QueueGhostUpdate(LWOOBJID playerID) +void EntityManager::QueueGhostUpdate(LWOOBJID playerID) { const auto& iter = std::find(m_PlayersToUpdateGhosting.begin(), m_PlayersToUpdateGhosting.end(), playerID); @@ -497,7 +468,7 @@ void EntityManager::QueueGhostUpdate(LWOOBJID playerID) } } -void EntityManager::UpdateGhosting() +void EntityManager::UpdateGhosting() { for (const auto playerID : m_PlayersToUpdateGhosting) { @@ -514,7 +485,7 @@ void EntityManager::UpdateGhosting() m_PlayersToUpdateGhosting.clear(); } -void EntityManager::UpdateGhosting(Player* player) +void EntityManager::UpdateGhosting(Player* player) { if (player == nullptr) { @@ -575,15 +546,15 @@ void EntityManager::UpdateGhosting(Player* player) } player->ObserveEntity(id); - + ConstructEntity(entity, player->GetSystemAddress()); - + entity->SetObservers(entity->GetObservers() + 1); } } } -void EntityManager::CheckGhosting(Entity* entity) +void EntityManager::CheckGhosting(Entity* entity) { if (entity == nullptr) { @@ -591,7 +562,7 @@ void EntityManager::CheckGhosting(Entity* entity) } const auto& referencePoint = entity->GetPosition(); - + auto ghostingDistanceMax = m_GhostDistanceMaxSquared; auto ghostingDistanceMin = m_GhostDistanceMinSqaured; @@ -618,15 +589,15 @@ void EntityManager::CheckGhosting(Entity* entity) else if (!observed && ghostingDistanceMin > distance) { player->ObserveEntity(id); - + ConstructEntity(entity, player->GetSystemAddress()); - + entity->SetObservers(entity->GetObservers() + 1); } } } -Entity* EntityManager::GetGhostCandidate(int32_t id) +Entity* EntityManager::GetGhostCandidate(int32_t id) { for (auto* entity : m_EntitiesToGhost) { @@ -635,7 +606,7 @@ Entity* EntityManager::GetGhostCandidate(int32_t id) return entity; } } - + return nullptr; } @@ -654,7 +625,7 @@ void EntityManager::ScheduleForKill(Entity* entity) { // Deactivate switches if they die if (!entity) return; - + SwitchComponent* switchComp = entity->GetComponent(); if (switchComp) { entity->TriggerEvent("OnDectivated"); @@ -670,7 +641,7 @@ void EntityManager::ScheduleForKill(Entity* entity) { m_EntitiesToKill.push_back(objectId); } -void EntityManager::ScheduleForDeletion(LWOOBJID entity) +void EntityManager::ScheduleForDeletion(LWOOBJID entity) { if (std::count(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity)) { @@ -689,7 +660,7 @@ void EntityManager::FireEventServerSide(Entity* origin, std::string args) { } } -bool EntityManager::IsExcludedFromGhosting(LOT lot) +bool EntityManager::IsExcludedFromGhosting(LOT lot) { return std::find(m_GhostingExcludedLOTs.begin(), m_GhostingExcludedLOTs.end(), lot) != m_GhostingExcludedLOTs.end(); } From 6a38b67ed5508ec7bffdb985baf278a8ee833e1d Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 21 Jul 2022 22:26:09 -0700 Subject: [PATCH 036/322] General AMF cleanup (#663) * General AMF cleanup Proper memory management as well as style cleanup * General optimizations Fix AMFArray so values are properly deleted when you leave the scope it was created in. Add bounds check for deletion so you don't double delete. Remove all AMFdeletions that are contained in an array since the array now manages its own memory and deletes it when it is no longer needed. * Better tests and fix de-serialize Fix de-serialize to be correct and implement a test to check this * Update AMFDeserializeTests.cpp * Update AMFFormat.cpp --- dCommon/AMFDeserialize.cpp | 28 +- dCommon/AMFFormat.cpp | 14 + dCommon/AMFFormat.h | 4 + dCommon/AMFFormat_BitStream.cpp | 373 +++++++++--------- dCommon/AMFFormat_BitStream.h | 158 ++++---- dGame/dComponents/DestroyableComponent.cpp | 11 +- .../dComponents/PropertyEntranceComponent.cpp | 2 - dGame/dGameMessages/GameMessages.cpp | 5 +- dGame/dUtilities/SlashCommandHandler.cpp | 22 +- dScripts/BankInteractServer.cpp | 7 +- dScripts/MailBoxServer.cpp | 1 - dScripts/NsLegoClubDoor.cpp | 39 -- dScripts/PropertyBankInteract.cpp | 6 +- dScripts/StoryBoxInteractServer.cpp | 8 +- dWorldServer/WorldServer.cpp | 5 - tests/AMFDeserializeTests.cpp | 9 +- 16 files changed, 303 insertions(+), 389 deletions(-) diff --git a/dCommon/AMFDeserialize.cpp b/dCommon/AMFDeserialize.cpp index 7f3f6d95..afe2b61b 100644 --- a/dCommon/AMFDeserialize.cpp +++ b/dCommon/AMFDeserialize.cpp @@ -127,21 +127,23 @@ AMFValue* AMFDeserialize::ReadAmfDouble(RakNet::BitStream* inStream) { AMFValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream* inStream) { auto arrayValue = new AMFArrayValue(); + + // Read size of dense array auto sizeOfDenseArray = (ReadU29(inStream) >> 1); - if (sizeOfDenseArray >= 1) { - char valueType; - inStream->Read(valueType); // Unused - for (uint32_t i = 0; i < sizeOfDenseArray; i++) { - arrayValue->PushBackValue(Read(inStream)); - } - } else { - while (true) { - auto key = ReadString(inStream); - // No more values when we encounter an empty string - if (key.size() == 0) break; - arrayValue->InsertValue(key, Read(inStream)); - } + + // Then read Key'd portion + while (true) { + auto key = ReadString(inStream); + // No more values when we encounter an empty string + if (key.size() == 0) break; + arrayValue->InsertValue(key, Read(inStream)); } + + // Finally read dense portion + for (uint32_t i = 0; i < sizeOfDenseArray; i++) { + arrayValue->PushBackValue(Read(inStream)); + } + return arrayValue; } diff --git a/dCommon/AMFFormat.cpp b/dCommon/AMFFormat.cpp index d4cf6531..741a8bc4 100644 --- a/dCommon/AMFFormat.cpp +++ b/dCommon/AMFFormat.cpp @@ -108,6 +108,14 @@ _AMFArrayList_::iterator AMFArrayValue::GetDenseIteratorEnd() { return this->dense.end(); } +AMFArrayValue::~AMFArrayValue() { + for (auto valueToDelete : GetDenseArray()) { + if (valueToDelete) delete valueToDelete; + } + for (auto valueToDelete : GetAssociativeMap()) { + if (valueToDelete.second) delete valueToDelete.second; + } +} // AMFObject Constructor AMFObjectValue::AMFObjectValue(std::vector> traits) { @@ -155,3 +163,9 @@ _AMFObjectTraits_::iterator AMFObjectValue::GetTraitsIteratorEnd() { uint32_t AMFObjectValue::GetTraitArrayCount() { return (uint32_t)this->traits.size(); } + +AMFObjectValue::~AMFObjectValue() { + for (auto valueToDelete = GetTraitsIteratorBegin(); valueToDelete != GetTraitsIteratorEnd(); valueToDelete++) { + if (valueToDelete->second.second) delete valueToDelete->second.second; + } +} diff --git a/dCommon/AMFFormat.h b/dCommon/AMFFormat.h index c3d0936c..54a02944 100644 --- a/dCommon/AMFFormat.h +++ b/dCommon/AMFFormat.h @@ -59,6 +59,7 @@ public: \return The AMF value type */ virtual AMFValueType GetValueType() = 0; + virtual ~AMFValue() {}; }; //! A typedef for a pointer to an AMF value @@ -233,6 +234,7 @@ public: }; //! The array value AMF type +// This object will manage it's own memory map and list. Do not delete its values. class AMFArrayValue : public AMFValue { private: _AMFArrayMap_ associative; //!< The array map (associative part) @@ -245,6 +247,7 @@ private: AMFValueType GetValueType() { return AMFArray; } public: + ~AMFArrayValue() override; //! Inserts an item into the array map for a specific key /*! \param key The key to set @@ -332,6 +335,7 @@ private: \return The AMF value type */ AMFValueType GetValueType() { return AMFObject; } + ~AMFObjectValue() override; public: //! Constructor diff --git a/dCommon/AMFFormat_BitStream.cpp b/dCommon/AMFFormat_BitStream.cpp index 57497951..96ccdab3 100644 --- a/dCommon/AMFFormat_BitStream.cpp +++ b/dCommon/AMFFormat_BitStream.cpp @@ -3,269 +3,248 @@ // Writes an AMFValue pointer to a RakNet::BitStream template<> void RakNet::BitStream::Write(AMFValue* value) { - if (value != nullptr) { - AMFValueType type = value->GetValueType(); - - switch (type) { - case AMFUndefined: { - AMFUndefinedValue* v = (AMFUndefinedValue*)value; - this->Write(*v); - break; - } - - case AMFNull: { - AMFNullValue* v = (AMFNullValue*)value; - this->Write(*v); - break; - } - - case AMFFalse: { - AMFFalseValue* v = (AMFFalseValue*)value; - this->Write(*v); - break; - } - - case AMFTrue: { - AMFTrueValue* v = (AMFTrueValue*)value; - this->Write(*v); - break; - } - - case AMFInteger: { - AMFIntegerValue* v = (AMFIntegerValue*)value; - this->Write(*v); - break; - } - - case AMFString: { - AMFStringValue* v = (AMFStringValue*)value; - this->Write(*v); - break; - } - - case AMFXMLDoc: { - AMFXMLDocValue* v = (AMFXMLDocValue*)value; - this->Write(*v); - break; - } - - case AMFDate: { - AMFDateValue* v = (AMFDateValue*)value; - this->Write(*v); - break; - } - - case AMFArray: { - AMFArrayValue* v = (AMFArrayValue*)value; - this->Write(*v); - break; - } - } - } + if (value != nullptr) { + AMFValueType type = value->GetValueType(); + + switch (type) { + case AMFUndefined: { + AMFUndefinedValue* v = (AMFUndefinedValue*)value; + this->Write(*v); + break; + } + + case AMFNull: { + AMFNullValue* v = (AMFNullValue*)value; + this->Write(*v); + break; + } + + case AMFFalse: { + AMFFalseValue* v = (AMFFalseValue*)value; + this->Write(*v); + break; + } + + case AMFTrue: { + AMFTrueValue* v = (AMFTrueValue*)value; + this->Write(*v); + break; + } + + case AMFInteger: { + AMFIntegerValue* v = (AMFIntegerValue*)value; + this->Write(*v); + break; + } + + case AMFDouble: { + AMFDoubleValue* v = (AMFDoubleValue*)value; + this->Write(*v); + break; + } + + case AMFString: { + AMFStringValue* v = (AMFStringValue*)value; + this->Write(*v); + break; + } + + case AMFXMLDoc: { + AMFXMLDocValue* v = (AMFXMLDocValue*)value; + this->Write(*v); + break; + } + + case AMFDate: { + AMFDateValue* v = (AMFDateValue*)value; + this->Write(*v); + break; + } + + case AMFArray: { + this->Write((AMFArrayValue*)value); + break; + } + } + } } -// A private function to write an value to a RakNet::BitStream +/** + * A private function to write an value to a RakNet::BitStream + * RakNet writes in the correct byte order - do not reverse this. + */ void WriteUInt29(RakNet::BitStream* bs, uint32_t v) { - unsigned char b4 = (unsigned char)v; - if (v < 0x00200000) { - b4 = b4 & 0x7F; - if (v > 0x7F) { - unsigned char b3; - v = v >> 7; - b3 = ((unsigned char)(v)) | 0x80; - if (v > 0x7F) { - unsigned char b2; - v = v >> 7; - b2 = ((unsigned char)(v)) | 0x80; - bs->Write(b2); - } - - bs->Write(b3); - } - } else { - unsigned char b1; - unsigned char b2; - unsigned char b3; - - v = v >> 8; - b3 = ((unsigned char)(v)) | 0x80; - v = v >> 7; - b2 = ((unsigned char)(v)) | 0x80; - v = v >> 7; - b1 = ((unsigned char)(v)) | 0x80; - - bs->Write(b1); - bs->Write(b2); - bs->Write(b3); - } - - bs->Write(b4); + unsigned char b4 = (unsigned char)v; + if (v < 0x00200000) { + b4 = b4 & 0x7F; + if (v > 0x7F) { + unsigned char b3; + v = v >> 7; + b3 = ((unsigned char)(v)) | 0x80; + if (v > 0x7F) { + unsigned char b2; + v = v >> 7; + b2 = ((unsigned char)(v)) | 0x80; + bs->Write(b2); + } + + bs->Write(b3); + } + } else { + unsigned char b1; + unsigned char b2; + unsigned char b3; + + v = v >> 8; + b3 = ((unsigned char)(v)) | 0x80; + v = v >> 7; + b2 = ((unsigned char)(v)) | 0x80; + v = v >> 7; + b1 = ((unsigned char)(v)) | 0x80; + + bs->Write(b1); + bs->Write(b2); + bs->Write(b3); + } + + bs->Write(b4); } -// Writes a flag number to a RakNet::BitStream +/** + * Writes a flag number to a RakNet::BitStream + * RakNet writes in the correct byte order - do not reverse this. + */ void WriteFlagNumber(RakNet::BitStream* bs, uint32_t v) { - v = (v << 1) | 0x01; - WriteUInt29(bs, v); + v = (v << 1) | 0x01; + WriteUInt29(bs, v); } -// Writes an AMFString to a RakNet::BitStream +/** + * Writes an AMFString to a RakNet::BitStream + * + * RakNet writes in the correct byte order - do not reverse this. + */ void WriteAMFString(RakNet::BitStream* bs, const std::string& str) { - WriteFlagNumber(bs, (uint32_t)str.size()); - bs->Write(str.c_str(), (uint32_t)str.size()); + WriteFlagNumber(bs, (uint32_t)str.size()); + bs->Write(str.c_str(), (uint32_t)str.size()); } -// Writes an AMF U16 to a RakNet::BitStream +/** + * Writes an U16 to a bitstream + * + * RakNet writes in the correct byte order - do not reverse this. + */ void WriteAMFU16(RakNet::BitStream* bs, uint16_t value) { - unsigned char b2; - b2 = (unsigned char)value; - value = value >> 8; - bs->Write((unsigned char)value); - bs->Write(b2); + bs->Write(value); } -// Writes an AMF U32 to RakNet::BitStream +/** + * Writes an U32 to a bitstream + * + * RakNet writes in the correct byte order - do not reverse this. + */ void WriteAMFU32(RakNet::BitStream* bs, uint32_t value) { - unsigned char b2; - unsigned char b3; - unsigned char b4; - - b4 = (unsigned char)value; - value = value >> 8; - b3 = (unsigned char)value; - value = value >> 8; - b2 = (unsigned char)value; - value = value >> 8; - - bs->Write((unsigned char)value); - bs->Write(b2); - bs->Write(b3); - bs->Write(b4); + bs->Write(value); } -// Writes an AMF U64 to RakNet::BitStream +/** + * Writes an U64 to a bitstream + * + * RakNet writes in the correct byte order - do not reverse this. + */ void WriteAMFU64(RakNet::BitStream* bs, uint64_t value) { - unsigned char b2; - unsigned char b3; - unsigned char b4; - unsigned char b5; - unsigned char b6; - unsigned char b7; - unsigned char b8; - - b8 = (unsigned char)value; - value = value >> 8; - b7 = (unsigned char)value; - value = value >> 8; - b6 = (unsigned char)value; - value = value >> 8; - b5 = (unsigned char)value; - value = value >> 8; - b4 = (unsigned char)value; - value = value >> 8; - b3 = (unsigned char)value; - value = value >> 8; - b2 = (unsigned char)value; - value = value >> 8; - - bs->Write((unsigned char)value); - bs->Write(b2); - bs->Write(b3); - bs->Write(b4); - bs->Write(b5); - bs->Write(b6); - bs->Write(b7); - bs->Write(b8); + bs->Write(value); } // Writes an AMFUndefinedValue to BitStream template<> void RakNet::BitStream::Write(AMFUndefinedValue value) { - this->Write(AMFUndefined); + this->Write(AMFUndefined); } // Writes an AMFNullValue to BitStream template<> void RakNet::BitStream::Write(AMFNullValue value) { - this->Write(AMFNull); + this->Write(AMFNull); } // Writes an AMFFalseValue to BitStream template<> void RakNet::BitStream::Write(AMFFalseValue value) { - this->Write(AMFFalse); + this->Write(AMFFalse); } // Writes an AMFTrueValue to BitStream template<> void RakNet::BitStream::Write(AMFTrueValue value) { - this->Write(AMFTrue); + this->Write(AMFTrue); } // Writes an AMFIntegerValue to BitStream template<> void RakNet::BitStream::Write(AMFIntegerValue value) { - this->Write(AMFInteger); - WriteUInt29(this, value.GetIntegerValue()); + this->Write(AMFInteger); + WriteUInt29(this, value.GetIntegerValue()); } // Writes an AMFDoubleValue to BitStream template<> void RakNet::BitStream::Write(AMFDoubleValue value) { - this->Write(AMFDouble); - double d = value.GetDoubleValue(); - WriteAMFU64(this, *((unsigned long long*)&d)); + this->Write(AMFDouble); + double d = value.GetDoubleValue(); + WriteAMFU64(this, *((unsigned long long*)&d)); } // Writes an AMFStringValue to BitStream template<> void RakNet::BitStream::Write(AMFStringValue value) { - this->Write(AMFString); - std::string v = value.GetStringValue(); - WriteAMFString(this, v); + this->Write(AMFString); + std::string v = value.GetStringValue(); + WriteAMFString(this, v); } // Writes an AMFXMLDocValue to BitStream template<> void RakNet::BitStream::Write(AMFXMLDocValue value) { - this->Write(AMFXMLDoc); - std::string v = value.GetXMLDocValue(); - WriteAMFString(this, v); + this->Write(AMFXMLDoc); + std::string v = value.GetXMLDocValue(); + WriteAMFString(this, v); } // Writes an AMFDateValue to BitStream template<> void RakNet::BitStream::Write(AMFDateValue value) { - this->Write(AMFDate); - uint64_t date = value.GetDateValue(); - WriteAMFU64(this, date); + this->Write(AMFDate); + uint64_t date = value.GetDateValue(); + WriteAMFU64(this, date); } // Writes an AMFArrayValue to BitStream template<> -void RakNet::BitStream::Write(AMFArrayValue value) { - this->Write(AMFArray); - uint32_t denseSize = value.GetDenseValueSize(); - WriteFlagNumber(this, denseSize); - - _AMFArrayMap_::iterator it = value.GetAssociativeIteratorValueBegin(); - _AMFArrayMap_::iterator end = value.GetAssociativeIteratorValueEnd(); - - while (it != end) { - WriteAMFString(this, it->first); - this->Write(it->second); - it++; - } - - this->Write(AMFNull); - - if (denseSize > 0) { - _AMFArrayList_::iterator it2 = value.GetDenseIteratorBegin(); - _AMFArrayList_::iterator end2 = value.GetDenseIteratorEnd(); - - while (it2 != end2) { - this->Write(*it2); - it2++; - } - } +void RakNet::BitStream::Write(AMFArrayValue* value) { + this->Write(AMFArray); + uint32_t denseSize = value->GetDenseValueSize(); + WriteFlagNumber(this, denseSize); + + _AMFArrayMap_::iterator it = value->GetAssociativeIteratorValueBegin(); + _AMFArrayMap_::iterator end = value->GetAssociativeIteratorValueEnd(); + + while (it != end) { + WriteAMFString(this, it->first); + this->Write(it->second); + it++; + } + + this->Write(AMFNull); + + if (denseSize > 0) { + _AMFArrayList_::iterator it2 = value->GetDenseIteratorBegin(); + _AMFArrayList_::iterator end2 = value->GetDenseIteratorEnd(); + + while (it2 != end2) { + this->Write(*it2); + it2++; + } + } } diff --git a/dCommon/AMFFormat_BitStream.h b/dCommon/AMFFormat_BitStream.h index 69dd0896..ff72a180 100644 --- a/dCommon/AMFFormat_BitStream.h +++ b/dCommon/AMFFormat_BitStream.h @@ -7,86 +7,86 @@ #include /*! - \file AMFBitStream.hpp - \brief A class that implements native writing of AMF values to RakNet::BitStream + \file AMFFormat_BitStream.h + \brief A class that implements native writing of AMF values to RakNet::BitStream */ // We are using the RakNet namespace namespace RakNet { - //! Writes an AMFValue pointer to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFValue* value); - - //! Writes an AMFUndefinedValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFUndefinedValue value); - - //! Writes an AMFNullValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFNullValue value); - - //! Writes an AMFFalseValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFFalseValue value); - - //! Writes an AMFTrueValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFTrueValue value); - - //! Writes an AMFIntegerValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFIntegerValue value); - - //! Writes an AMFDoubleValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFDoubleValue value); - - //! Writes an AMFStringValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFStringValue value); - - //! Writes an AMFXMLDocValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFXMLDocValue value); - - //! Writes an AMFDateValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFDateValue value); - - //! Writes an AMFArrayValue to a RakNet::BitStream - /*! - \param value The value to write - */ - template<> - void RakNet::BitStream::Write(AMFArrayValue value); -} + //! Writes an AMFValue pointer to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFValue* value); + + //! Writes an AMFUndefinedValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFUndefinedValue value); + + //! Writes an AMFNullValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFNullValue value); + + //! Writes an AMFFalseValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFFalseValue value); + + //! Writes an AMFTrueValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFTrueValue value); + + //! Writes an AMFIntegerValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFIntegerValue value); + + //! Writes an AMFDoubleValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFDoubleValue value); + + //! Writes an AMFStringValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFStringValue value); + + //! Writes an AMFXMLDocValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFXMLDocValue value); + + //! Writes an AMFDateValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFDateValue value); + + //! Writes an AMFArrayValue to a RakNet::BitStream + /*! + \param value The value to write + */ + template <> + void RakNet::BitStream::Write(AMFArrayValue* value); +} // namespace RakNet diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 37d74a55..efcfb5cb 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -234,10 +234,8 @@ void DestroyableComponent::SetMaxHealth(float value, bool playAnim) { AMFArrayValue args; args.InsertValue("amount", amount); args.InsertValue("type", type); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", &args); - delete amount; - delete type; + GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", &args); } EntityManager::Instance()->SerializeEntity(m_Parent); @@ -283,9 +281,6 @@ void DestroyableComponent::SetMaxArmor(float value, bool playAnim) { args.InsertValue("type", type); GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", &args); - - delete amount; - delete type; } EntityManager::Instance()->SerializeEntity(m_Parent); @@ -328,10 +323,8 @@ void DestroyableComponent::SetMaxImagination(float value, bool playAnim) { AMFArrayValue args; args.InsertValue("amount", amount); args.InsertValue("type", type); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", &args); - delete amount; - delete type; + GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", &args); } EntityManager::Instance()->SerializeEntity(m_Parent); } diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index 87e0c7ed..4be059ed 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -40,8 +40,6 @@ void PropertyEntranceComponent::OnUse(Entity* entity) { args.InsertValue("state", state); GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "pushGameState", &args); - - delete state; } void PropertyEntranceComponent::OnEnterProperty(Entity* entity, uint32_t index, bool returnToZone, const SystemAddress& sysAddr) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index ba410b70..a971b723 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -4978,12 +4978,9 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity } if (args == u"toggleMail") { - AMFFalseValue* value = new AMFFalseValue(); - AMFArrayValue args; - args.InsertValue("visible", value); + args.InsertValue("visible", new AMFFalseValue()); GameMessages::SendUIMessageServerToSingleClient(entity, sysAddr, "ToggleMail", &args); - delete value; } // This should probably get it's own "ServerEvents" system or something at some point diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 74d44ce7..22fbb680 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -276,27 +276,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit args.InsertValue("state", state); GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "pushGameState", &args); - - delete state; } entity->AddCallbackTimer(0.5f, [customText, entity] () { AMFArrayValue args; - auto* visiable = new AMFTrueValue(); auto* text = new AMFStringValue(); text->SetStringValue(customText); - args.InsertValue("visible", visiable); + args.InsertValue("visible", new AMFTrueValue()); args.InsertValue("text", text); Game::logger->Log("SlashCommandHandler", "Sending \n%s\n", customText.c_str()); GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "ToggleStoryBox", &args); - - delete visiable; - delete text; }); return; @@ -556,8 +550,6 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Switched UI state."); - delete value; - return; } @@ -570,8 +562,6 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Toggled UI state."); - delete value; - return; } @@ -1578,11 +1568,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "debugui") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { ChatPackets::SendSystemMessage(sysAddr, u"Opening UIDebugger..."); - AMFStringValue* value = new AMFStringValue(); - value->SetStringValue("ToggleUIDebugger;"); AMFArrayValue args; - GameMessages::SendUIMessageServerToSingleClient(entity, sysAddr, value->GetStringValue(), &args); - delete value; + GameMessages::SendUIMessageServerToSingleClient(entity, sysAddr, "ToggleUIDebugger;", nullptr); } if ((chatCommand == "boost") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { @@ -2008,11 +1995,6 @@ void SlashCommandHandler::SendAnnouncement(const std::string& title, const std:: GameMessages::SendUIMessageServerToAllClients("ToggleAnnounce", &args); - delete titleValue; - delete messageValue; - titleValue = nullptr; - messageValue = nullptr; - //Notify chat about it CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ANNOUNCEMENT); diff --git a/dScripts/BankInteractServer.cpp b/dScripts/BankInteractServer.cpp index 9bea375a..dc119056 100644 --- a/dScripts/BankInteractServer.cpp +++ b/dScripts/BankInteractServer.cpp @@ -9,8 +9,6 @@ void BankInteractServer::OnUse(Entity* self, Entity* user) args.InsertValue("state", bank); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); - - delete bank; } void BankInteractServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, @@ -19,13 +17,10 @@ void BankInteractServer::OnFireEventServerSide(Entity *self, Entity *sender, std if (args == "ToggleBank") { AMFArrayValue args; - AMFFalseValue* amfFalse = new AMFFalseValue(); - args.InsertValue("visible", amfFalse); + args.InsertValue("visible", new AMFFalseValue()); GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleBank", &args); - delete amfFalse; - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"CloseBank", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); } } diff --git a/dScripts/MailBoxServer.cpp b/dScripts/MailBoxServer.cpp index 3e4e9687..56e7793e 100644 --- a/dScripts/MailBoxServer.cpp +++ b/dScripts/MailBoxServer.cpp @@ -8,5 +8,4 @@ void MailBoxServer::OnUse(Entity* self, Entity* user) { AMFArrayValue args; args.InsertValue("state", value); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); - delete value; } \ No newline at end of file diff --git a/dScripts/NsLegoClubDoor.cpp b/dScripts/NsLegoClubDoor.cpp index 0b773b09..0a73c6d0 100644 --- a/dScripts/NsLegoClubDoor.cpp +++ b/dScripts/NsLegoClubDoor.cpp @@ -13,21 +13,6 @@ void NsLegoClubDoor::OnStartup(Entity* self) args = {}; - /** - { {0,{ - {"image", "textures/ui/zone_thumnails/Nimbus_Station.dds"}, - {"caption", "%[UI_CHOICE_NS]"}, -- "%[LOC_STRING]" is the format for sending localization tokens to the choice box - {"identifier", "zoneID_1200"}, - {"tooltipText", "%[UI_CHOICE_NS_HOVER]"} - }}, - {1,{ - {"image", "textures/ui/zone_thumnails/Nexus_Tower.dds"}, - {"caption", "%[UI_CHOICE_NT]"}, - {"identifier", "zoneID_1900"}, - {"tooltipText", "%[UI_CHOICE_NT_HOVER]"} - } } } - */ - AMFStringValue* callbackClient = new AMFStringValue(); callbackClient->SetStringValue(std::to_string(self->GetObjectID())); args.InsertValue("callbackClient", callbackClient); @@ -97,12 +82,6 @@ void NsLegoClubDoor::OnUse(Entity* self, Entity* user) if (CheckChoice(self, player)) { - /** - { {"callbackClient", self}, - {"strIdentifier", "choiceDoor"}, - {"title", "%[UI_CHOICE_DESTINATION]"}, - {"options", choiceOptions} } - */ AMFArrayValue* multiArgs = new AMFArrayValue(); AMFStringValue* callbackClient = new AMFStringValue(); @@ -120,19 +99,9 @@ void NsLegoClubDoor::OnUse(Entity* self, Entity* user) multiArgs->InsertValue("options", options); GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "QueueChoiceBox", multiArgs); - - delete multiArgs; - delete callbackClient; - delete strIdentifier; - delete title; } else if (self->GetVar(u"currentZone") != m_ChoiceZoneID) { - /** - { {"state", "Lobby"}, - {"context", {{"user", msg.user}, {"callbackObj", self}, - {"HelpVisible", "show" }, {"type", "Lego_Club_Valid"}} }} - */ AMFArrayValue* multiArgs = new AMFArrayValue(); AMFStringValue* state = new AMFStringValue(); @@ -160,14 +129,6 @@ void NsLegoClubDoor::OnUse(Entity* self, Entity* user) multiArgs->InsertValue("context", context); GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "pushGameState", multiArgs); - - delete multiArgs; - delete state; - delete context; - delete user; - delete callbackObj; - delete helpVisible; - delete type; } else { diff --git a/dScripts/PropertyBankInteract.cpp b/dScripts/PropertyBankInteract.cpp index 974b33a6..d564c503 100644 --- a/dScripts/PropertyBankInteract.cpp +++ b/dScripts/PropertyBankInteract.cpp @@ -24,7 +24,6 @@ void PropertyBankInteract::OnUse(Entity *self, Entity *user) { args.InsertValue("state", value); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); - delete value; GameMessages::SendNotifyClientObject(self->GetObjectID(), u"OpenBank", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); @@ -34,13 +33,10 @@ void PropertyBankInteract::OnFireEventServerSide(Entity *self, Entity *sender, s int32_t param2, int32_t param3) { if (args == "ToggleBank") { AMFArrayValue amfArgs; - auto* amfFalse = new AMFFalseValue(); - amfArgs.InsertValue("visible", amfFalse); + amfArgs.InsertValue("visible", new AMFFalseValue()); GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleBank", &amfArgs); - delete amfFalse; - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"CloseBank", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); } diff --git a/dScripts/StoryBoxInteractServer.cpp b/dScripts/StoryBoxInteractServer.cpp index e5899f5d..187d05a2 100644 --- a/dScripts/StoryBoxInteractServer.cpp +++ b/dScripts/StoryBoxInteractServer.cpp @@ -18,24 +18,18 @@ void StoryBoxInteractServer::OnUse(Entity* self, Entity* user) { args.InsertValue("state", state); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); - - delete state; } user->AddCallbackTimer(0.1f, [user, customText] () { AMFArrayValue args; - auto* visiable = new AMFTrueValue(); auto* text = new AMFStringValue(); text->SetStringValue(customText); - args.InsertValue("visible", visiable); + args.InsertValue("visible", new AMFTrueValue()); args.InsertValue("text", text); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "ToggleStoryBox", &args); - - delete visiable; - delete text; }); return; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index d7a3b41e..96149ae4 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -577,11 +577,6 @@ void HandlePacketChat(Packet* packet) { GameMessages::SendUIMessageServerToAllClients("ToggleAnnounce", &args); - delete titleValue; - delete messageValue; - titleValue = nullptr; - messageValue = nullptr; - break; } diff --git a/tests/AMFDeserializeTests.cpp b/tests/AMFDeserializeTests.cpp index 88405803..58d7eea4 100644 --- a/tests/AMFDeserializeTests.cpp +++ b/tests/AMFDeserializeTests.cpp @@ -129,20 +129,25 @@ int ReadAMFArrayFromBitStream() { ASSERT_EQ(static_cast(res.get())->GetDenseArray().size(), 0); } bitStream.Reset(); - // Test a key'd value + // Test a key'd value and dense value bitStream.Write(0x09); - bitStream.Write(0x01); + bitStream.Write(0x03); bitStream.Write(0x15); for (auto e : "BehaviorID") if (e != '\0') bitStream.Write(e); bitStream.Write(0x06); bitStream.Write(0x0B); for (auto e : "10447") if (e != '\0') bitStream.Write(e); bitStream.Write(0x01); + bitStream.Write(0x06); + bitStream.Write(0x0B); + for (auto e : "10447") if (e != '\0') bitStream.Write(e); { std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFArray); ASSERT_EQ(static_cast(res.get())->GetAssociativeMap().size(), 1); + ASSERT_EQ(static_cast(res.get())->GetDenseArray().size(), 1); ASSERT_EQ(static_cast(static_cast(res.get())->FindValue("BehaviorID"))->GetStringValue(), "10447"); + ASSERT_EQ(static_cast(static_cast(res.get())->GetDenseArray()[0])->GetStringValue(), "10447"); } // Test a dense array return 0; From ef0a3c6d0b153535659df4adeba51b266ea99228 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 22 Jul 2022 19:58:20 -0700 Subject: [PATCH 037/322] Add Hot Properties struct and address some whitespace (no functionality change) (#667) * Add GameMessages * General AMF cleanup Proper memory management as well as style cleanup * General AMF cleanup Proper memory management as well as style cleanup * General optimizations Fix AMFArray so values are properly deleted when you leave the scope it was created in. Add bounds check for deletion so you don't double delete. Remove all AMFdeletions that are contained in an array since the array now manages its own memory and deletes it when it is no longer needed. * Better tests and fix de-serialize Fix de-serialize to be correct and implement a test to check this * Update AMFDeserializeTests.cpp * Update GameMessages.h * Add GM * Comment out function * Spacing * eof --- dGame/dGameMessages/GameMessageHandler.cpp | 236 ++++---- dGame/dGameMessages/GameMessages.cpp | 613 +++++++++++---------- dGame/dGameMessages/GameMessages.h | 137 +++-- dNet/dMessageIdentifiers.h | 28 +- 4 files changed, 547 insertions(+), 467 deletions(-) diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 261a3105..53cce60e 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -30,7 +30,7 @@ using namespace std; void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, GAME_MSG messageID) { - + CBITSTREAM // Get the entity @@ -38,19 +38,19 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System User * usr = UserManager::Instance()->GetUser(sysAddr); - if (!entity) - { + if (!entity) + { Game::logger->Log("GameMessageHandler", "Failed to find associated entity (%llu), aborting GM (%X)!\n", objectID, messageID); - return; - } + return; + } - switch (messageID) { + switch (messageID) { - case GAME_MSG_PLAY_EMOTE: { - GameMessages::HandlePlayEmote(inStream, entity); - break; - } + case GAME_MSG_PLAY_EMOTE: { + GameMessages::HandlePlayEmote(inStream, entity); + break; + } case GAME_MSG_MOVE_ITEM_IN_INVENTORY: { GameMessages::HandleMoveItemInInventory(inStream, entity); @@ -69,27 +69,27 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_UN_EQUIP_ITEM: GameMessages::HandleUnequipItem(inStream, entity); break; - - case GAME_MSG_RESPOND_TO_MISSION: { - GameMessages::HandleRespondToMission(inStream, entity); - break; - } - - case GAME_MSG_REQUEST_USE: { - GameMessages::HandleRequestUse(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_SET_FLAG: { - GameMessages::HandleSetFlag(inStream, entity); - break; - } - - case GAME_MSG_HAS_BEEN_COLLECTED: { - GameMessages::HandleHasBeenCollected(inStream, entity); - break; - } - + + case GAME_MSG_RESPOND_TO_MISSION: { + GameMessages::HandleRespondToMission(inStream, entity); + break; + } + + case GAME_MSG_REQUEST_USE: { + GameMessages::HandleRequestUse(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_SET_FLAG: { + GameMessages::HandleSetFlag(inStream, entity); + break; + } + + case GAME_MSG_HAS_BEEN_COLLECTED: { + GameMessages::HandleHasBeenCollected(inStream, entity); + break; + } + case GAME_MSG_PLAYER_LOADED: { GameMessages::SendRestoreToPostLoadStats(entity, sysAddr); entity->SetPlayerReadyForUpdates(); @@ -160,57 +160,57 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System Game::logger->Log("GameMessageHandler", "Player %s (%llu) loaded.\n", entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); // After we've done our thing, tell the client they're ready - GameMessages::SendPlayerReady(dZoneManager::Instance()->GetZoneControlObject(), sysAddr); - GameMessages::SendPlayerReady(entity, sysAddr); + GameMessages::SendPlayerReady(dZoneManager::Instance()->GetZoneControlObject(), sysAddr); + GameMessages::SendPlayerReady(entity, sysAddr); - break; - } - - case GAME_MSG_REQUEST_LINKED_MISSION: { - GameMessages::HandleRequestLinkedMission(inStream, entity); - break; - } - - case GAME_MSG_MISSION_DIALOGUE_OK: { - GameMessages::HandleMissionDialogOK(inStream, entity); - break; - } + break; + } + + case GAME_MSG_REQUEST_LINKED_MISSION: { + GameMessages::HandleRequestLinkedMission(inStream, entity); + break; + } + + case GAME_MSG_MISSION_DIALOGUE_OK: { + GameMessages::HandleMissionDialogOK(inStream, entity); + break; + } case GAME_MSG_MISSION_DIALOGUE_CANCELLED: { //This message is pointless for our implementation, as the client just carries on after //rejecting a mission offer. We dont need to do anything. This is just here to remove a warning in our logs :) break; } - - case GAME_MSG_REQUEST_PLATFORM_RESYNC: { - GameMessages::HandleRequestPlatformResync(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_FIRE_EVENT_SERVER_SIDE: { + + case GAME_MSG_REQUEST_PLATFORM_RESYNC: { + GameMessages::HandleRequestPlatformResync(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_FIRE_EVENT_SERVER_SIDE: { GameMessages::HandleFireEventServerSide(inStream, entity, sysAddr); - break; - } + break; + } - case GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { - GameMessages::HandleActivitySummaryLeaderboardData(inStream, entity, sysAddr); - break; - } + case GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { + GameMessages::HandleActivitySummaryLeaderboardData(inStream, entity, sysAddr); + break; + } - case GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { - GameMessages::HandleRequestActivitySummaryLeaderboardData(inStream, entity, sysAddr); - break; - } + case GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { + GameMessages::HandleRequestActivitySummaryLeaderboardData(inStream, entity, sysAddr); + break; + } - case GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST: { - GameMessages::HandleActivityStateChangeRequest(inStream, entity); - break; - } - - case GAME_MSG_PARSE_CHAT_MESSAGE: { - GameMessages::HandleParseChatMessage(inStream, entity, sysAddr); - break; - } + case GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST: { + GameMessages::HandleActivityStateChangeRequest(inStream, entity); + break; + } + + case GAME_MSG_PARSE_CHAT_MESSAGE: { + GameMessages::HandleParseChatMessage(inStream, entity, sysAddr); + break; + } case GAME_MSG_NOTIFY_SERVER_LEVEL_PROCESSING_COMPLETE: { GameMessages::HandleNotifyServerLevelProcessingComplete(inStream, entity); @@ -228,8 +228,8 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System } case GAME_MSG_RESURRECT: { - GameMessages::HandleResurrect(inStream, entity); - break; + GameMessages::HandleResurrect(inStream, entity); + break; } case GAME_MSG_REQUEST_RESURRECT: { @@ -243,10 +243,14 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System }*/ break; } + case GAME_MSG_HANDLE_HOT_PROPERTY_DATA: { + GameMessages::HandleGetHotPropertyData(inStream, entity, sysAddr); + break; + } - case GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT: - { - auto message = GameMessages::RequestServerProjectileImpact(); + case GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT: + { + auto message = GameMessages::RequestServerProjectileImpact(); message.Deserialize(inStream); @@ -260,10 +264,10 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System delete bs; } - - break; - } - + + break; + } + case GAME_MSG_START_SKILL: { GameMessages::StartSkill startSkill = GameMessages::StartSkill(); startSkill.Deserialize(inStream); // inStream replaces &bitStream @@ -279,7 +283,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System unsigned int behaviorId = skillTable->GetSkillByID(startSkill.skillID).behaviorID; bool success = false; - + if (behaviorId > 0) { RakNet::BitStream * bs = new RakNet::BitStream((unsigned char *)startSkill.sBitStream.c_str(), startSkill.sBitStream.size(), false); @@ -374,7 +378,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_MODULAR_BUILD_FINISH: GameMessages::HandleModularBuildFinish(inStream, entity, sysAddr); break; - + case GAME_MSG_PUSH_EQUIPPED_ITEMS_STATE: GameMessages::HandlePushEquippedItemsState(inStream, entity); break; @@ -486,7 +490,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleChoiceBoxRespond(inStream, entity, sysAddr); break; - // Property + // Property case GAME_MSG_QUERY_PROPERTY_DATA: GameMessages::HandleQueryPropertyData(inStream, entity, sysAddr); break; @@ -531,7 +535,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleBBBLoadItemRequest(inStream, entity, sysAddr); break; - case GAME_MSG_BBB_SAVE_REQUEST: + case GAME_MSG_BBB_SAVE_REQUEST: GameMessages::HandleBBBSaveRequest(inStream, entity, sysAddr); break; @@ -554,7 +558,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK: GameMessages::HandleUpdatePropertyOrModelForFilterCheck(inStream, entity, sysAddr); break; - + case GAME_MSG_SET_PROPERTY_ACCESS: GameMessages::HandleSetPropertyAccess(inStream, entity, sysAddr); break; @@ -620,41 +624,41 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleSetGhostReferencePosition(inStream, entity, sysAddr); break; - case GAME_MSG_READY_FOR_UPDATES: - //We don't really care about this message, as it's simply here to inform us that the client is done loading an object. - //In the event we _do_ send an update to an object that hasn't finished loading, the client will handle it anyway. - break; + case GAME_MSG_READY_FOR_UPDATES: + //We don't really care about this message, as it's simply here to inform us that the client is done loading an object. + //In the event we _do_ send an update to an object that hasn't finished loading, the client will handle it anyway. + break; case GAME_MSG_REPORT_BUG: GameMessages::HandleReportBug(inStream, entity); break; - case GAME_MSG_CLIENT_RAIL_MOVEMENT_READY: - GameMessages::HandleClientRailMovementReady(inStream, entity, sysAddr); - break; - - case GAME_MSG_CANCEL_RAIL_MOVEMENT: - GameMessages::HandleCancelRailMovement(inStream, entity, sysAddr); - break; - - case GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION: - GameMessages::HandlePlayerRailArrivedNotification(inStream, entity, sysAddr); - break; - - case GAME_MSG_CINEMATIC_UPDATE: - GameMessages::HandleCinematicUpdate(inStream, entity, sysAddr); - break; - - case GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC: - GameMessages::HandleModifyPlayerZoneStatistic(inStream, entity); - break; - - case GAME_MSG_UPDATE_PLAYER_STATISTIC: - GameMessages::HandleUpdatePlayerStatistic(inStream, entity); - break; - - default: - //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X\n", messageID); + case GAME_MSG_CLIENT_RAIL_MOVEMENT_READY: + GameMessages::HandleClientRailMovementReady(inStream, entity, sysAddr); break; - } + + case GAME_MSG_CANCEL_RAIL_MOVEMENT: + GameMessages::HandleCancelRailMovement(inStream, entity, sysAddr); + break; + + case GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION: + GameMessages::HandlePlayerRailArrivedNotification(inStream, entity, sysAddr); + break; + + case GAME_MSG_CINEMATIC_UPDATE: + GameMessages::HandleCinematicUpdate(inStream, entity, sysAddr); + break; + + case GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC: + GameMessages::HandleModifyPlayerZoneStatistic(inStream, entity); + break; + + case GAME_MSG_UPDATE_PLAYER_STATISTIC: + GameMessages::HandleUpdatePlayerStatistic(inStream, entity); + break; + + default: + //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X\n", messageID); + break; + } } diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index a971b723..2f193170 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -170,14 +170,14 @@ void GameMessages::SendPlayerReady(Entity* entity, const SystemAddress& sysAddr) } void GameMessages::SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptRespawn, const SystemAddress &sysAddr) { - CBITSTREAM - CMSGHEADER; + CBITSTREAM + CMSGHEADER; - bitStream.Write(entityID); - bitStream.Write(GAME_MSG::GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN); - bitStream.Write(doNotPromptRespawn); + bitStream.Write(entityID); + bitStream.Write(GAME_MSG::GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN); + bitStream.Write(doNotPromptRespawn); - SEND_PACKET; + SEND_PACKET; } void GameMessages::SendInvalidZoneTransferList(Entity* entity, const SystemAddress& sysAddr, const std::u16string& feedbackURL, const std::u16string& invalidMapTransferList, bool feedbackOnExit, bool feedbackOnInvalidTransfer) { @@ -266,7 +266,7 @@ void GameMessages::SendStartArrangingWithItem( } void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, const SystemAddress& sysAddr, - bool bAllowCyclingWhileDeadOnly, eCyclingMode cyclingMode) { + bool bAllowCyclingWhileDeadOnly, eCyclingMode cyclingMode) { CBITSTREAM CMSGHEADER @@ -277,7 +277,7 @@ void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, cons bitStream.Write(cyclingMode != ALLOW_CYCLE_TEAMMATES); if (cyclingMode != ALLOW_CYCLE_TEAMMATES) { - bitStream.Write(cyclingMode); + bitStream.Write(cyclingMode); } SEND_PACKET @@ -672,7 +672,7 @@ void GameMessages::SendStopFXEffect(Entity* entity, bool killImmediate, std::str bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_STOP_FX_EFFECT); - bitStream.Write(killImmediate); + bitStream.Write(killImmediate); bitStream.Write(name.size()); bitStream.Write(name.c_str(), name.size()); @@ -1456,76 +1456,76 @@ void GameMessages::SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, } void GameMessages::SendRequestActivitySummaryLeaderboardData(const LWOOBJID& objectID, const LWOOBJID& targetID, - const SystemAddress& sysAddr, const int32_t& gameID, - const int32_t& queryType, const int32_t& resultsEnd, - const int32_t& resultsStart, bool weekly) { - CBITSTREAM - CMSGHEADER + const SystemAddress& sysAddr, const int32_t& gameID, + const int32_t& queryType, const int32_t& resultsEnd, + const int32_t& resultsStart, bool weekly) { + CBITSTREAM + CMSGHEADER - bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA); + bitStream.Write(objectID); + bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA); - bitStream.Write(gameID != 0); - if (gameID != 0) { - bitStream.Write(gameID); - } + bitStream.Write(gameID != 0); + if (gameID != 0) { + bitStream.Write(gameID); + } - bitStream.Write(queryType != 1); - if (queryType != 1) { - bitStream.Write(queryType); - } + bitStream.Write(queryType != 1); + if (queryType != 1) { + bitStream.Write(queryType); + } - bitStream.Write(resultsEnd != 10); - if (resultsEnd != 10) { - bitStream.Write(resultsEnd); - } + bitStream.Write(resultsEnd != 10); + if (resultsEnd != 10) { + bitStream.Write(resultsEnd); + } - bitStream.Write(resultsStart != 0); - if (resultsStart != 0) { - bitStream.Write(resultsStart); - } + bitStream.Write(resultsStart != 0); + if (resultsStart != 0) { + bitStream.Write(resultsStart); + } - bitStream.Write(targetID); - bitStream.Write(weekly); + bitStream.Write(targetID); + bitStream.Write(weekly); - SEND_PACKET + SEND_PACKET } void GameMessages::SendActivityPause(LWOOBJID objectId, bool pause, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM + CMSGHEADER - bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_ACTIVITY_PAUSE); - bitStream.Write(pause); + bitStream.Write(objectId); + bitStream.Write(GAME_MSG::GAME_MSG_ACTIVITY_PAUSE); + bitStream.Write(pause); - if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET } void GameMessages::SendStartActivityTime(LWOOBJID objectId, float_t startTime, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM + CMSGHEADER - bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_START_ACTIVITY_TIME); - bitStream.Write(startTime); + bitStream.Write(objectId); + bitStream.Write(GAME_MSG::GAME_MSG_START_ACTIVITY_TIME); + bitStream.Write(startTime); - if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET } void GameMessages::SendRequestActivityEnter(LWOOBJID objectId, const SystemAddress& sysAddr, bool bStart, LWOOBJID userID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM + CMSGHEADER - bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_ENTER); - bitStream.Write(bStart); + bitStream.Write(objectId); + bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_ENTER); + bitStream.Write(bStart); bitStream.Write(userID); - if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET } void GameMessages::NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sysAddr, int level, bool sending_rewards) { @@ -1614,87 +1614,87 @@ void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStre void GameMessages::HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, - const SystemAddress& sysAddr) { - Game::logger->Log("AGS", "We got mail!\n"); + const SystemAddress& sysAddr) { + Game::logger->Log("AGS", "We got mail!\n"); } void GameMessages::SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM + CMSGHEADER - bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA); + bitStream.Write(objectID); + bitStream.Write(GAME_MSG::GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA); - bitStream.Write(leaderboard->GetGameID()); - bitStream.Write(leaderboard->GetInfoType()); + bitStream.Write(leaderboard->GetGameID()); + bitStream.Write(leaderboard->GetInfoType()); - // Leaderboard is written back as LDF string - const auto leaderboardString = leaderboard->ToString(); - bitStream.Write(leaderboardString.size()); - for (const auto c : leaderboardString) { - bitStream.Write(c); - } - if (!leaderboardString.empty()) bitStream.Write(uint16_t(0)); + // Leaderboard is written back as LDF string + const auto leaderboardString = leaderboard->ToString(); + bitStream.Write(leaderboardString.size()); + for (const auto c : leaderboardString) { + bitStream.Write(c); + } + if (!leaderboardString.empty()) bitStream.Write(uint16_t(0)); - bitStream.Write0(); - bitStream.Write0(); + bitStream.Write0(); + bitStream.Write0(); - SEND_PACKET + SEND_PACKET } void GameMessages::HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - int32_t gameID = 0; - if (inStream->ReadBit()) inStream->Read(gameID); + int32_t gameID = 0; + if (inStream->ReadBit()) inStream->Read(gameID); - int32_t queryType = 1; - if (inStream->ReadBit()) inStream->Read(queryType); + int32_t queryType = 1; + if (inStream->ReadBit()) inStream->Read(queryType); - int32_t resultsEnd = 10; - if (inStream->ReadBit()) inStream->Read(resultsEnd); + int32_t resultsEnd = 10; + if (inStream->ReadBit()) inStream->Read(resultsEnd); - int32_t resultsStart = 0; - if (inStream->ReadBit()) inStream->Read(resultsStart); + int32_t resultsStart = 0; + if (inStream->ReadBit()) inStream->Read(resultsStart); - LWOOBJID target {}; - inStream->Read(target); + LWOOBJID target {}; + inStream->Read(target); - bool weekly = inStream->ReadBit(); + bool weekly = inStream->ReadBit(); - const auto* leaderboard = LeaderboardManager::GetLeaderboard(gameID, (InfoType)queryType, weekly, entity->GetObjectID()); - SendActivitySummaryLeaderboardData(entity->GetObjectID(), leaderboard, sysAddr); - delete leaderboard; + const auto* leaderboard = LeaderboardManager::GetLeaderboard(gameID, (InfoType)queryType, weekly, entity->GetObjectID()); + SendActivitySummaryLeaderboardData(entity->GetObjectID(), leaderboard, sysAddr); + delete leaderboard; } void GameMessages::HandleActivityStateChangeRequest(RakNet::BitStream *inStream, Entity *entity) { - LWOOBJID objectID; - inStream->Read(objectID); + LWOOBJID objectID; + inStream->Read(objectID); - int32_t value1; - inStream->Read(value1); + int32_t value1; + inStream->Read(value1); - int32_t value2; - inStream->Read(value2); + int32_t value2; + inStream->Read(value2); - uint32_t stringValueLength; - inStream->Read(stringValueLength); + uint32_t stringValueLength; + inStream->Read(stringValueLength); - std::u16string stringValue; - for (uint32_t i = 0; i < stringValueLength; ++i) { - uint16_t character; - inStream->Read(character); - stringValue.push_back(character); - } + std::u16string stringValue; + for (uint32_t i = 0; i < stringValueLength; ++i) { + uint16_t character; + inStream->Read(character); + stringValue.push_back(character); + } auto* assosiate = EntityManager::Instance()->GetEntity(objectID); - Game::logger->Log("Activity State Change", "%s [%i, %i] from %i to %i\n", GeneralUtils::UTF16ToWTF8(stringValue).c_str(), value1, value2, entity->GetLOT(), assosiate != nullptr ? assosiate->GetLOT() : 0); + Game::logger->Log("Activity State Change", "%s [%i, %i] from %i to %i\n", GeneralUtils::UTF16ToWTF8(stringValue).c_str(), value1, value2, entity->GetLOT(), assosiate != nullptr ? assosiate->GetLOT() : 0); std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SHOOTING_GALLERY); for (Entity* scriptEntity : scriptedActs) { scriptEntity->OnActivityStateChangeRequest(objectID, value1, value2, stringValue); } - entity->OnActivityStateChangeRequest(objectID, value1, value2, stringValue); + entity->OnActivityStateChangeRequest(objectID, value1, value2, stringValue); } void GameMessages::SendStartCelebrationEffect(Entity* entity, const SystemAddress& sysAddr, int celebrationID) { @@ -1727,99 +1727,99 @@ void GameMessages::SendStartCelebrationEffect(Entity* entity, const SystemAddres void GameMessages::SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForward, std::u16string pathName, - uint32_t pathStart, const SystemAddress& sysAddr, int32_t railActivatorComponentID, - LWOOBJID railActivatorObjectID) { - CBITSTREAM; - CMSGHEADER; + uint32_t pathStart, const SystemAddress& sysAddr, int32_t railActivatorComponentID, + LWOOBJID railActivatorObjectID) { + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_SET_RAIL_MOVEMENT); + bitStream.Write(objectID); + bitStream.Write(GAME_MSG::GAME_MSG_SET_RAIL_MOVEMENT); - bitStream.Write(pathGoForward); + bitStream.Write(pathGoForward); - bitStream.Write(uint32_t(pathName.size())); - for (auto character : pathName) { - bitStream.Write(character); - } + bitStream.Write(uint32_t(pathName.size())); + for (auto character : pathName) { + bitStream.Write(character); + } - bitStream.Write(pathStart); + bitStream.Write(pathStart); - const auto componentIDIsDefault = railActivatorComponentID == -1; - bitStream.Write(!componentIDIsDefault); - if (!componentIDIsDefault) - bitStream.Write(railActivatorComponentID); + const auto componentIDIsDefault = railActivatorComponentID == -1; + bitStream.Write(!componentIDIsDefault); + if (!componentIDIsDefault) + bitStream.Write(railActivatorComponentID); - const auto activatorObjectIDIsDefault = railActivatorObjectID == LWOOBJID_EMPTY; - bitStream.Write(!activatorObjectIDIsDefault); - if (!activatorObjectIDIsDefault) - bitStream.Write(railActivatorObjectID); + const auto activatorObjectIDIsDefault = railActivatorObjectID == LWOOBJID_EMPTY; + bitStream.Write(!activatorObjectIDIsDefault); + if (!activatorObjectIDIsDefault) + bitStream.Write(railActivatorObjectID); - if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET; + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET; } void GameMessages::SendStartRailMovement(const LWOOBJID &objectID, std::u16string pathName, std::u16string startSound, - std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr, - uint32_t pathStart, bool goForward, bool damageImmune, bool noAggro, bool notifyActor, - bool showNameBillboard, bool cameraLocked, bool collisionEnabled, bool useDB, - int32_t railComponentID, LWOOBJID railActivatorObjectID) { - CBITSTREAM; - CMSGHEADER; + std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr, + uint32_t pathStart, bool goForward, bool damageImmune, bool noAggro, bool notifyActor, + bool showNameBillboard, bool cameraLocked, bool collisionEnabled, bool useDB, + int32_t railComponentID, LWOOBJID railActivatorObjectID) { + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_START_RAIL_MOVEMENT); + bitStream.Write(objectID); + bitStream.Write(GAME_MSG::GAME_MSG_START_RAIL_MOVEMENT); - bitStream.Write(damageImmune); - bitStream.Write(noAggro); - bitStream.Write(notifyActor); - bitStream.Write(showNameBillboard); - bitStream.Write(cameraLocked); - bitStream.Write(collisionEnabled); + bitStream.Write(damageImmune); + bitStream.Write(noAggro); + bitStream.Write(notifyActor); + bitStream.Write(showNameBillboard); + bitStream.Write(cameraLocked); + bitStream.Write(collisionEnabled); - bitStream.Write(uint32_t(loopSound.size())); - for (auto character : loopSound) { - bitStream.Write(character); - } + bitStream.Write(uint32_t(loopSound.size())); + for (auto character : loopSound) { + bitStream.Write(character); + } - bitStream.Write(goForward); + bitStream.Write(goForward); - bitStream.Write(uint32_t(pathName.size())); - for (auto character : pathName) { - bitStream.Write(character); - } + bitStream.Write(uint32_t(pathName.size())); + for (auto character : pathName) { + bitStream.Write(character); + } - const auto pathStartIsDefault = pathStart == 0; - bitStream.Write(!pathStartIsDefault); - if (!pathStartIsDefault) { - bitStream.Write(pathStart); - } + const auto pathStartIsDefault = pathStart == 0; + bitStream.Write(!pathStartIsDefault); + if (!pathStartIsDefault) { + bitStream.Write(pathStart); + } - const auto railComponentIDIsDefault = railComponentID == -1; - bitStream.Write(!railComponentIDIsDefault); - if (!railComponentIDIsDefault) { - bitStream.Write(railComponentID); - } + const auto railComponentIDIsDefault = railComponentID == -1; + bitStream.Write(!railComponentIDIsDefault); + if (!railComponentIDIsDefault) { + bitStream.Write(railComponentID); + } - const auto railObjectIDIsDefault = railActivatorObjectID == LWOOBJID_EMPTY; - bitStream.Write(!railObjectIDIsDefault); - if (!railObjectIDIsDefault) { - bitStream.Write(railActivatorObjectID); - } + const auto railObjectIDIsDefault = railActivatorObjectID == LWOOBJID_EMPTY; + bitStream.Write(!railObjectIDIsDefault); + if (!railObjectIDIsDefault) { + bitStream.Write(railActivatorObjectID); + } - bitStream.Write(uint32_t(startSound.size())); - for (auto character : startSound) { - bitStream.Write(character); - } + bitStream.Write(uint32_t(startSound.size())); + for (auto character : startSound) { + bitStream.Write(character); + } - bitStream.Write(uint32_t(stopSound.size())); - for (auto character : stopSound) { - bitStream.Write(character); - } + bitStream.Write(uint32_t(stopSound.size())); + for (auto character : stopSound) { + bitStream.Write(character); + } - bitStream.Write(useDB); + bitStream.Write(useDB); - if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET; + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET; } void GameMessages::SendNotifyClientObject(const LWOOBJID& objectID, std::u16string name, int param1, int param2, const LWOOBJID& paramObj, std::string paramStr, const SystemAddress& sysAddr) { @@ -2865,48 +2865,48 @@ void GameMessages::SendEndCinematic(LWOOBJID objectId, std::u16string pathName, } void GameMessages::HandleCinematicUpdate(RakNet::BitStream *inStream, Entity *entity, const SystemAddress &sysAddr) { - eCinematicEvent event; - if (!inStream->ReadBit()) { - event = STARTED; - } else { - inStream->Read(event); - } + eCinematicEvent event; + if (!inStream->ReadBit()) { + event = STARTED; + } else { + inStream->Read(event); + } - float_t overallTime; - if (!inStream->ReadBit()) { - overallTime = -1.0f; - } else { - inStream->Read(overallTime); - } + float_t overallTime; + if (!inStream->ReadBit()) { + overallTime = -1.0f; + } else { + inStream->Read(overallTime); + } - uint32_t pathNameLength; - inStream->Read(pathNameLength); + uint32_t pathNameLength; + inStream->Read(pathNameLength); - std::u16string pathName; - for (size_t i = 0; i < pathNameLength; i++) { - char16_t character; - inStream->Read(character); - pathName.push_back(character); - } + std::u16string pathName; + for (size_t i = 0; i < pathNameLength; i++) { + char16_t character; + inStream->Read(character); + pathName.push_back(character); + } - float_t pathTime; - if (!inStream->ReadBit()) { - pathTime = -1.0f; - } else { - inStream->Read(pathTime); - } + float_t pathTime; + if (!inStream->ReadBit()) { + pathTime = -1.0f; + } else { + inStream->Read(pathTime); + } - int32_t waypoint; - if (!inStream->ReadBit()) { - waypoint = -1; - } else { - inStream->Read(waypoint); - } + int32_t waypoint; + if (!inStream->ReadBit()) { + waypoint = -1; + } else { + inStream->Read(waypoint); + } - std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); - for (Entity* scriptEntity : scriptedActs) { - scriptEntity->OnCinematicUpdate(scriptEntity, entity, event, pathName, pathTime, overallTime, waypoint); - } + std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); + for (Entity* scriptEntity : scriptedActs) { + scriptEntity->OnCinematicUpdate(scriptEntity, entity, event, pathName, pathTime, overallTime, waypoint); + } } void GameMessages::SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, const SystemAddress& sysAddr, @@ -4290,10 +4290,10 @@ void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* in } } - auto* characterComponent = entity->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(RacingImaginationPowerUpsCollected); - } + auto* characterComponent = entity->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(RacingImaginationPowerUpsCollected); + } pickup->OnFireEventServerSide(entity, "powerup"); @@ -4541,9 +4541,9 @@ void GameMessages::SendVehicleNotifyFinishedRace(LWOOBJID objectId, const System } void GameMessages::SendAddBuff(LWOOBJID& objectID, const LWOOBJID& casterID, uint32_t buffID, uint32_t msDuration, - bool addImmunity, bool cancelOnDamaged, bool cancelOnDeath, bool cancelOnLogout, - bool cancelOnRemoveBuff, bool cancelOnUi, bool cancelOnUnequip, bool cancelOnZone, - const SystemAddress& sysAddr) { + bool addImmunity, bool cancelOnDamaged, bool cancelOnDeath, bool cancelOnLogout, + bool cancelOnRemoveBuff, bool cancelOnUi, bool cancelOnUnequip, bool cancelOnZone, + const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4735,11 +4735,11 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti 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); - } + // 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) { @@ -5035,7 +5035,7 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity }); } - entity->OnFireEventServerSide(sender, GeneralUtils::UTF16ToWTF8(args), param1, param2, param3); + entity->OnFireEventServerSide(sender, GeneralUtils::UTF16ToWTF8(args), param1, param2, param3); } void GameMessages::HandleRequestPlatformResync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { @@ -5867,21 +5867,21 @@ void GameMessages::HandlePickupItem(RakNet::BitStream* inStream, Entity* entity) } void GameMessages::HandleResurrect(RakNet::BitStream* inStream, Entity* entity) { - bool immediate = inStream->ReadBit(); + bool immediate = inStream->ReadBit(); - Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerResurrected(zoneControl, entity); - } + Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { + script->OnPlayerResurrected(zoneControl, entity); + } - std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_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->OnPlayerResurrected(scriptEntity, entity); - } - } - } + std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_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->OnPlayerResurrected(scriptEntity, entity); + } + } + } } void GameMessages::HandlePushEquippedItemsState(RakNet::BitStream* inStream, Entity* entity) { @@ -5923,7 +5923,7 @@ void GameMessages::HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* auto* missions = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION)); if (missions != nullptr) { - missions->Progress(MissionTaskType::MISSION_TASK_TYPE_FOOD, item->GetLot()); + missions->Progress(MissionTaskType::MISSION_TASK_TYPE_FOOD, item->GetLot()); } } @@ -5995,6 +5995,51 @@ void GameMessages::HandleMatchRequest(RakNet::BitStream* inStream, Entity* entit } } +void GameMessages::HandleGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + SendGetHotPropertyData(inStream, entity, sysAddr); +} + +void GameMessages::SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + CBITSTREAM + CMSGHEADER + /** + * [u32] - Number of properties + * [objid] - property id + * [objid] - property owner id + * [wstring] - property owner name + * [u64] - total reputation + * [i32] - property template id + * [wstring] - property name + * [wstring] - property description + * [float] - performance cost + * [timestamp] - time last published + * [cloneid] - clone id + * + */ + // TODO This needs to be implemented when reputation is implemented for getting hot properties. + /** + bitStream.Write(entity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_SEND_HOT_PROPERTY_DATA); + std::vector t = {25166, 25188, 25191, 25194}; + bitStream.Write(4); + for (uint8_t i = 0; i < 4; i++) { + bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(42069); + bitStream.Write(t[i]); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(420.69f); + bitStream.Write(1658376385); + bitStream.Write(25166); + } + SEND_PACKET*/ +} + void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) { //Definitely not stolen from autogenerated code, no sir: std::u16string body; @@ -6060,25 +6105,25 @@ void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) void GameMessages::HandleClientRailMovementReady(RakNet::BitStream *inStream, Entity *entity, const SystemAddress &sysAddr) { - const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); - for (const auto* possibleRail : possibleRails) { - const auto* rail = possibleRail->GetComponent(); - if (rail != nullptr) { - rail->OnRailMovementReady(entity); - } - } + const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); + for (const auto* possibleRail : possibleRails) { + const auto* rail = possibleRail->GetComponent(); + if (rail != nullptr) { + rail->OnRailMovementReady(entity); + } + } } void GameMessages::HandleCancelRailMovement(RakNet::BitStream *inStream, Entity *entity, const SystemAddress &sysAddr) { - const auto immediate = inStream->ReadBit(); + const auto immediate = inStream->ReadBit(); - const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); - for (const auto* possibleRail : possibleRails) { - auto* rail = possibleRail->GetComponent(); - if (rail != nullptr) { - rail->OnCancelRailMovement(entity); - } - } + const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); + for (const auto* possibleRail : possibleRails) { + auto* rail = possibleRail->GetComponent(); + if (rail != nullptr) { + rail->OnCancelRailMovement(entity); + } + } } void GameMessages::HandlePlayerRailArrivedNotification(RakNet::BitStream *inStream, Entity *entity, @@ -6105,43 +6150,43 @@ void GameMessages::HandlePlayerRailArrivedNotification(RakNet::BitStream *inStre } void GameMessages::HandleModifyPlayerZoneStatistic(RakNet::BitStream *inStream, Entity *entity) { - const auto set = inStream->ReadBit(); - const auto statisticsName = GeneralUtils::ReadWString(inStream); + const auto set = inStream->ReadBit(); + const auto statisticsName = GeneralUtils::ReadWString(inStream); - int32_t value; - if (inStream->ReadBit()) { - inStream->Read(value); - } else { - value = 0; - } + int32_t value; + if (inStream->ReadBit()) { + inStream->Read(value); + } else { + value = 0; + } - LWOMAPID zone; - if (inStream->ReadBit()) { - inStream->Read(zone); - } else { - zone = LWOMAPID_INVALID; - } + LWOMAPID zone; + if (inStream->ReadBit()) { + inStream->Read(zone); + } else { + zone = LWOMAPID_INVALID; + } - // Notify the character component that something's changed - auto* characterComponent = entity->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->HandleZoneStatisticsUpdate(zone, statisticsName, value); - } + // Notify the character component that something's changed + auto* characterComponent = entity->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->HandleZoneStatisticsUpdate(zone, statisticsName, value); + } } void GameMessages::HandleUpdatePlayerStatistic(RakNet::BitStream* inStream, Entity* entity) { - int32_t updateID; - inStream->Read(updateID); + int32_t updateID; + inStream->Read(updateID); - int64_t updateValue; - if (inStream->ReadBit()) { - inStream->Read(updateValue); - } else { - updateValue = 1; - } + int64_t updateValue; + if (inStream->ReadBit()) { + inStream->Read(updateValue); + } else { + updateValue = 1; + } - auto* characterComponent = entity->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic((StatisticID) updateID, (uint64_t) std::max(updateValue, int64_t(0))); - } + auto* characterComponent = entity->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic((StatisticID) updateID, (uint64_t) std::max(updateValue, int64_t(0))); + } } diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index fc49ad70..c5b7888d 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -24,7 +24,7 @@ namespace GameMessages { class PropertyDataMessage; void SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender); void SendTeleport(const LWOOBJID& objectID, const NiPoint3& pos, const NiQuaternion& rot, const SystemAddress& sysAddr, bool bSetRotation = false, bool noGravTeleport = true); - void SendPlayAnimation(Entity* entity, const std::u16string& animationName, float fPriority = 0.0f, float fScale = 1.0f); + void SendPlayAnimation(Entity* entity, const std::u16string& animationName, float fPriority = 0.0f, float fScale = 1.0f); void SendPlayerReady(Entity * entity, const SystemAddress& sysAddr); void SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptRespawn, const SystemAddress& systemAddress); void SendInvalidZoneTransferList(Entity * entity, const SystemAddress& sysAddr, const std::u16string& feedbackURL, const std::u16string& invalidMapTransferList, bool feedbackOnExit, bool feedbackOnInvalidTransfer); @@ -47,27 +47,27 @@ namespace GameMessages { ); void SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, const SystemAddress& sysAddr, - bool bAllowCyclingWhileDeadOnly = true, eCyclingMode cyclingMode = ALLOW_CYCLE_TEAMMATES); + bool bAllowCyclingWhileDeadOnly = true, eCyclingMode cyclingMode = ALLOW_CYCLE_TEAMMATES); void SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& sysAddr, std::string audioGUID); void SendStartPathing(Entity* entity); void SendPlatformResync(Entity* entity, const SystemAddress& sysAddr, bool bStopAtDesiredWaypoint = false, - int iIndex = 0, int iDesiredWaypointIndex = 1, int nextIndex = 1, - MovementPlatformState movementState = MovementPlatformState::Moving); - + int iIndex = 0, int iDesiredWaypointIndex = 1, int nextIndex = 1, + MovementPlatformState movementState = MovementPlatformState::Moving); + void SendRestoreToPostLoadStats(Entity * entity, const SystemAddress& sysAddr); void SendServerDoneLoadingAllObjects(Entity * entity, const SystemAddress& sysAddr); - void SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level); - void SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level); - + void SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level); + void SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level); + void SendAddItemToInventoryClientSync(Entity* entity, const SystemAddress& sysAddr, Item* item, const LWOOBJID& objectID, bool showFlyingLoot, int itemCount, LWOOBJID subKey = LWOOBJID_EMPTY, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); - void SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFlagID, bool bFlag, const SystemAddress& sysAddr); + void SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFlagID, bool bFlag, const SystemAddress& sysAddr); void SendChangeObjectWorldState(const LWOOBJID& objectID, int state, const SystemAddress& sysAddr); - void SendOfferMission(const LWOOBJID& entity, const SystemAddress& sysAddr, int32_t missionID, const LWOOBJID& offererID); - void SendNotifyMission(Entity * entity, const SystemAddress& sysAddr, int missionID, int missionState, bool sendingRewards); - void SendNotifyMissionTask(Entity * entity, const SystemAddress& sysAddr, int missionID, int taskMask, std::vector updates); + void SendOfferMission(const LWOOBJID& entity, const SystemAddress& sysAddr, int32_t missionID, const LWOOBJID& offererID); + void SendNotifyMission(Entity * entity, const SystemAddress& sysAddr, int missionID, int missionState, bool sendingRewards); + void SendNotifyMissionTask(Entity * entity, const SystemAddress& sysAddr, int missionID, int taskMask, std::vector updates); void NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sysAddr, int level, bool sending_rewards); void SendModifyLEGOScore(Entity* entity, const SystemAddress& sysAddr, int64_t score, eLootSourceType sourceType); @@ -92,7 +92,7 @@ namespace GameMessages { void SendSetInventorySize(Entity* entity, int invType, int size); void SendSetEmoteLockState(Entity* entity, bool bLock, int emoteID); - void SendSetJetPackMode(Entity* entity, bool use, bool bypassChecks = false, bool doHover = false, int effectID = -1, float airspeed = 10, float maxAirspeed = 15, float verticalVelocity = 1, int warningEffectID = -1); + void SendSetJetPackMode(Entity* entity, bool use, bool bypassChecks = false, bool doHover = false, int effectID = -1, float airspeed = 10, float maxAirspeed = 15, float verticalVelocity = 1, int warningEffectID = -1); void SendResurrect(Entity* entity); void SendStop2DAmbientSound(Entity* entity, bool force, std::string audioGUID, bool result = false); void SendPlay2DAmbientSound(Entity* entity, std::string audioGUID, bool result = false); @@ -157,15 +157,15 @@ namespace GameMessages { // Rails stuff void SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForward, std::u16string pathName, uint32_t pathStart, - const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, - int32_t railActivatorComponentID = -1, LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); + const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, + int32_t railActivatorComponentID = -1, LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); void SendStartRailMovement(const LWOOBJID& objectID, std::u16string pathName, std::u16string startSound, - std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, - uint32_t pathStart = 0, bool goForward = true, bool damageImmune = true, bool noAggro = true, - bool notifyActor = false, bool showNameBillboard = true, bool cameraLocked = true, - bool collisionEnabled = true, bool useDB = true, int32_t railComponentID = -1, - LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); + std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, + uint32_t pathStart = 0, bool goForward = true, bool damageImmune = true, bool noAggro = true, + bool notifyActor = false, bool showNameBillboard = true, bool cameraLocked = true, + bool collisionEnabled = true, bool useDB = true, int32_t railComponentID = -1, + LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); void HandleClientRailMovementReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleCancelRailMovement(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -180,9 +180,9 @@ namespace GameMessages { void SendBBBSaveResponse(const LWOOBJID& objectId, const LWOOBJID& localID, unsigned char* buffer, uint32_t bufferSize, const SystemAddress& sysAddr); void SendAddBuff(LWOOBJID& objectID, const LWOOBJID& casterID, uint32_t buffID, uint32_t msDuration, - bool addImmunity = false, bool cancelOnDamaged = false, bool cancelOnDeath = true, - bool cancelOnLogout = false, bool cancelOnRemoveBuff = true, bool cancelOnUi = false, - bool cancelOnUnequip = false, bool cancelOnZone = false, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); + bool addImmunity = false, bool cancelOnDamaged = false, bool cancelOnDeath = true, + bool cancelOnLogout = false, bool cancelOnRemoveBuff = true, bool cancelOnUi = false, + bool cancelOnUnequip = false, bool cancelOnZone = false, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void SendToggleGMInvis(LWOOBJID objectId, bool enabled, const SystemAddress& sysAddr); @@ -252,7 +252,7 @@ namespace GameMessages { bool lockPlayer = true, bool result = false, bool skipIfSamePath = false, float startTimeAdvance = 0); void SendEndCinematic(LWOOBJID objectID, std::u16string pathName, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, - float leadOut = -1.0f, bool leavePlayerLocked = false); + float leadOut = -1.0f, bool leavePlayerLocked = false); void HandleCinematicUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, const SystemAddress& sysAddr, @@ -389,6 +389,38 @@ namespace GameMessages { */ void HandleAcknowledgePossession(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + /** + * @brief A request from a client to get the hot properties that would appear on the news feed + * This incoming message has NO DATA and is simply a request that expects to send a reply to the sender. + * + * @param inStream packet of data + * @param entity The Entity that sent the request + * @param sysAddr The SystemAddress of the Entity that sent the request + */ + void HandleGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + + /** + * @brief A request from a client to get the hot properties that would appear on the news feed + * The struct of data to send is as follows + * + * [u32] - Number of properties + * [objid] - property id + * [objid] - property owner id + * [wstring] - property owner name + * [u64] - total reputation + * [i32] - property template id + * [wstring] - property name + * [wstring] - property description + * [float] - performance cost + * [timestamp] - time last published + * [cloneid] - clone id + * + * @param inStream packet of data + * @param entity The Entity that sent the request + * @param sysAddr The SystemAddress of the Entity that sent the request + */ + void SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + //Racing: void HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -459,16 +491,16 @@ namespace GameMessages { void SendUpdateReputation(const LWOOBJID objectId, const int64_t reputation, const SystemAddress& sysAddr); - // Leaderboards - void SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, - const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); - void HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, const SystemAddress& sysAddr); - void SendRequestActivitySummaryLeaderboardData(const LWOOBJID& objectID, const LWOOBJID& targetID, - const SystemAddress& sysAddr, const int32_t& gameID = 0, - const int32_t& queryType = 1, const int32_t& resultsEnd = 10, - const int32_t& resultsStart = 0, bool weekly = false); - void HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleActivityStateChangeRequest(RakNet::BitStream* inStream, Entity* entity); + // Leaderboards + void SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, + const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); + void HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, const SystemAddress& sysAddr); + void SendRequestActivitySummaryLeaderboardData(const LWOOBJID& objectID, const LWOOBJID& targetID, + const SystemAddress& sysAddr, const int32_t& gameID = 0, + const int32_t& queryType = 1, const int32_t& resultsEnd = 10, + const int32_t& resultsStart = 0, bool weekly = false); + void HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleActivityStateChangeRequest(RakNet::BitStream* inStream, Entity* entity); void SendVehicleAddPassiveBoostAction(LWOOBJID objectId, const SystemAddress& sysAddr); @@ -482,8 +514,8 @@ namespace GameMessages { void SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditionalSound, bool bPlayCountdownSound, std::u16string sndName, int32_t stateToPlaySoundOn, const SystemAddress& sysAddr); - //Handlers: - + //Handlers: + void HandleToggleGhostReferenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleSetGhostReferencePosition(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -491,19 +523,19 @@ namespace GameMessages { void HandleSellToVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleParseChatMessage(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleToggleGhostReffrenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleSetGhostReffrenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleFireEventServerSide(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleRequestPlatformResync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleToggleGhostReffrenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleSetGhostReffrenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleFireEventServerSide(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleRequestPlatformResync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleRebuildCancel(RakNet::BitStream* inStream, Entity* entity); - void HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity); + void HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity); void HandleModularBuildConvertModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleSetFlag(RakNet::BitStream* inStream, Entity* entity); - void HandleRespondToMission(RakNet::BitStream* inStream, Entity* entity); - void HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* entity); - void HandleRequestLinkedMission(RakNet::BitStream* inStream, Entity* entity); - void HandleHasBeenCollected(RakNet::BitStream* inStream, Entity* entity); + void HandleSetFlag(RakNet::BitStream* inStream, Entity* entity); + void HandleRespondToMission(RakNet::BitStream* inStream, Entity* entity); + void HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* entity); + void HandleRequestLinkedMission(RakNet::BitStream* inStream, Entity* entity); + void HandleHasBeenCollected(RakNet::BitStream* inStream, Entity* entity); void HandleNotifyServerLevelProcessingComplete(RakNet::BitStream* inStream, Entity* entity); void HandlePickupCurrency(RakNet::BitStream* inStream, Entity* entity); void HandleRequestDie(RakNet::BitStream* inStream, Entity* entity); @@ -537,7 +569,7 @@ namespace GameMessages { class EchoSyncSkill { static const GAME_MSG MsgID = GAME_MSG_ECHO_SYNC_SKILL; - public: + public: EchoSyncSkill() { bDone = false; } @@ -598,7 +630,7 @@ namespace GameMessages { class SyncSkill { static const GAME_MSG MsgID = GAME_MSG_SYNC_SKILL; - public: + public: SyncSkill() { bDone = false; } @@ -659,7 +691,7 @@ namespace GameMessages { class RequestServerProjectileImpact { static const GAME_MSG MsgID = GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT; - public: + public: RequestServerProjectileImpact() { i64LocalID = LWOOBJID_EMPTY; i64TargetID = LWOOBJID_EMPTY; @@ -728,7 +760,7 @@ namespace GameMessages { class DoClientProjectileImpact { static const GAME_MSG MsgID = GAME_MSG_DO_CLIENT_PROJECTILE_IMPACT; - public: + public: DoClientProjectileImpact() { i64OrgID = LWOOBJID_EMPTY; i64OwnerID = LWOOBJID_EMPTY; @@ -1078,7 +1110,4 @@ namespace GameMessages { }; }; - - - #endif // GAMEMESSAGES_H diff --git a/dNet/dMessageIdentifiers.h b/dNet/dMessageIdentifiers.h index cb46b5d1..4e88a9af 100644 --- a/dNet/dMessageIdentifiers.h +++ b/dNet/dMessageIdentifiers.h @@ -354,8 +354,8 @@ enum GAME_MSG : unsigned short { GAME_MSG_REGISTER_PET_ID = 565, GAME_MSG_REGISTER_PET_DBID = 566, GAME_MSG_SHOW_ACTIVITY_COUNTDOWN = 568, - GAME_MSG_START_ACTIVITY_TIME = 576, - GAME_MSG_ACTIVITY_PAUSE = 602, + GAME_MSG_START_ACTIVITY_TIME = 576, + GAME_MSG_ACTIVITY_PAUSE = 602, GAME_MSG_USE_NON_EQUIPMENT_ITEM = 603, GAME_MSG_USE_ITEM_RESULT = 607, GAME_MSG_COMMAND_PET = 640, @@ -386,14 +386,14 @@ enum GAME_MSG : unsigned short { GAME_MSG_PROPERTY_EDITOR_BEGIN = 724, GAME_MSG_PROPERTY_EDITOR_END = 725, GAME_MSG_START_PATHING = 735, - GAME_MSG_NOTIFY_CLIENT_ZONE_OBJECT = 737, + GAME_MSG_NOTIFY_CLIENT_ZONE_OBJECT = 737, GAME_MSG_UPDATE_REPUTATION = 746, GAME_MSG_PROPERTY_RENTAL_RESPONSE = 750, GAME_MSG_REQUEST_PLATFORM_RESYNC = 760, GAME_MSG_PLATFORM_RESYNC = 761, GAME_MSG_PLAY_CINEMATIC = 762, GAME_MSG_END_CINEMATIC = 763, - GAME_MSG_CINEMATIC_UPDATE = 764, + GAME_MSG_CINEMATIC_UPDATE = 764, GAME_MSG_TOGGLE_GHOST_REFERENCE_OVERRIDE = 767, GAME_MSG_SET_GHOST_REFERENCE_POSITION = 768, GAME_MSG_FIRE_EVENT_SERVER_SIDE = 770, @@ -438,8 +438,8 @@ enum GAME_MSG : unsigned short { GAME_MSG_BBB_SAVE_RESPONSE = 1006, GAME_MSG_NOTIFY_CLIENT_OBJECT = 1042, GAME_MSG_DISPLAY_ZONE_SUMMARY = 1043, - GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST = 1053, - GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC = 1046, + GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST = 1053, + GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC = 1046, GAME_MSG_START_BUILDING_WITH_ITEM = 1057, GAME_MSG_START_ARRANGING_WITH_ITEM = 1061, GAME_MSG_FINISH_ARRANGING_WITH_ITEM = 1062, @@ -460,7 +460,7 @@ enum GAME_MSG : unsigned short { GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT = 1148, GAME_MSG_DO_CLIENT_PROJECTILE_IMPACT = 1151, GAME_MSG_MODULAR_BUILD_CONVERT_MODEL = 1155, - GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN = 1165, + GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN = 1165, GAME_MSG_UI_MESSAGE_SERVER_TO_SINGLE_CLIENT = 1184, GAME_MSG_UI_MESSAGE_SERVER_TO_ALL_CLIENTS = 1185, GAME_MSG_PET_TAMING_TRY_BUILD = 1197, @@ -515,10 +515,10 @@ enum GAME_MSG : unsigned short { GAME_MSG_RESTORE_TO_POST_LOAD_STATS = 1468, GAME_MSG_SET_RAIL_MOVEMENT = 1471, GAME_MSG_START_RAIL_MOVEMENT = 1472, - GAME_MSG_CANCEL_RAIL_MOVEMENT = 1474, - GAME_MSG_CLIENT_RAIL_MOVEMENT_READY = 1476, - GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION = 1477, - GAME_MSG_UPDATE_PLAYER_STATISTIC = 1481, + GAME_MSG_CANCEL_RAIL_MOVEMENT = 1474, + GAME_MSG_CLIENT_RAIL_MOVEMENT_READY = 1476, + GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION = 1477, + GAME_MSG_UPDATE_PLAYER_STATISTIC = 1481, GAME_MSG_MODULAR_ASSEMBLY_NIF_COMPLETED = 1498, GAME_MSG_NOTIFY_NOT_ENOUGH_INV_SPACE = 1516, GAME_MSG_TEAM_SET_LEADER = 0x0615, @@ -527,11 +527,13 @@ enum GAME_MSG : unsigned short { GAME_MSG_TEAM_ADD_PLAYER = 0x061a, GAME_MSG_TEAM_REMOVE_PLAYER = 0x061b, GAME_MSG_START_CELEBRATION_EFFECT = 1618, - GAME_MSG_ADD_BUFF = 1647, + GAME_MSG_ADD_BUFF = 1647, GAME_MSG_SERVER_DONE_LOADING_ALL_OBJECTS = 1642, GAME_MSG_PLACE_PROPERTY_MODEL = 1170, GAME_MSG_VEHICLE_NOTIFY_HIT_IMAGINATION_SERVER = 1606, GAME_MSG_ADD_RUN_SPEED_MODIFIER = 1505, + GAME_MSG_HANDLE_HOT_PROPERTY_DATA = 1511, + GAME_MSG_SEND_HOT_PROPERTY_DATA = 1510, GAME_MSG_REMOVE_RUN_SPEED_MODIFIER = 1506, GAME_MSG_UPDATE_PROPERTY_PERFORMANCE_COST = 1547, GAME_MSG_PROPERTY_ENTRANCE_BEGIN = 1553, @@ -544,4 +546,4 @@ enum GAME_MSG : unsigned short { GAME_MSG_DISMOUNT_COMPLETE = 1756, GAME_MSG_MARK_INVENTORY_ITEM_AS_ACTIVE = 1767, END -}; \ No newline at end of file +}; From f2d1c5d26d16678d57be92b43844a3fc4da24092 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sun, 24 Jul 2022 13:04:02 -0500 Subject: [PATCH 038/322] Split out Level progression component (#671) * Split out Level progression component from Character Component This is to get to the Player forced movement Comp in a sane way * move XML to component insted of abusing charComp * use overrides should probably make everything that calls that call it correctly * fix linking issue --- dCommon/dCommonVars.h | 3 +- dGame/Entity.cpp | 23 +++++- dGame/dComponents/CMakeLists.txt | 1 + dGame/dComponents/CharacterComponent.cpp | 70 ------------------ dGame/dComponents/CharacterComponent.h | 22 ------ .../dComponents/LevelProgressionComponent.cpp | 74 +++++++++++++++++++ dGame/dComponents/LevelProgressionComponent.h | 63 ++++++++++++++++ dGame/dGameMessages/GameMessages.cpp | 22 +++--- dGame/dMission/Mission.cpp | 6 +- dGame/dUtilities/Preconditions.cpp | 7 +- dGame/dUtilities/SlashCommandHandler.cpp | 11 ++- 11 files changed, 185 insertions(+), 117 deletions(-) create mode 100644 dGame/dComponents/LevelProgressionComponent.cpp create mode 100644 dGame/dComponents/LevelProgressionComponent.h diff --git a/dCommon/dCommonVars.h b/dCommon/dCommonVars.h index 77d51125..f6efdcf8 100644 --- a/dCommon/dCommonVars.h +++ b/dCommon/dCommonVars.h @@ -402,13 +402,14 @@ enum eReplicaComponentType : int32_t { COMPONENT_TYPE_RACING_CONTROL = 71, //!< The RacingControl Component COMPONENT_TYPE_MISSION_OFFER = 73, //!< The MissionOffer Component COMPONENT_TYPE_EXHIBIT = 75, //!< The Exhibit Component - COMPONENT_TYPE_RACING_STATS = 74, //!< The Exhibit Component + COMPONENT_TYPE_RACING_STATS = 74, //!< The Racing Stats Component COMPONENT_TYPE_SOUND_TRIGGER = 77, //!< The Sound Trigger Component COMPONENT_TYPE_PROXIMITY_MONITOR = 78, //!< The Proximity Monitor Component COMPONENT_TYPE_MISSION = 84, //!< The Mission Component COMPONENT_TYPE_ROCKET_LAUNCH_LUP = 97, //!< The LUP Launchpad Componen COMPONENT_TYPE_RAIL_ACTIVATOR = 104, COMPONENT_TYPE_POSSESSABLE = 108, //!< The Possessable Component + COMPONENT_TYPE_LEVEL_PROGRESSION = 109, //!< The Level Progression Component COMPONENT_TYPE_POSSESSOR = 110, //!< The Possessor Component COMPONENT_TYPE_BUILD_BORDER = 114, //!< The Build Border Component COMPONENT_TYPE_DESTROYABLE = 1000, //!< The Destroyable Component diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index c44db6f1..45287bd8 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -28,6 +28,7 @@ #include "BuffComponent.h" #include "BouncerComponent.h" #include "InventoryComponent.h" +#include "LevelProgressionComponent.h" #include "ScriptComponent.h" #include "SkillComponent.h" #include "SimplePhysicsComponent.h" @@ -442,8 +443,14 @@ void Entity::Initialize() }*/ if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_CHARACTER) > 0 || m_Character) { - // Character Component always has a possessor component + // Character Component always has a possessor and level components m_Components.insert(std::make_pair(COMPONENT_TYPE_POSSESSOR, new PossessorComponent(this))); + + // load in the xml for the level + auto* levelComp = new LevelProgressionComponent(this); + levelComp->LoadFromXml(m_Character->GetXMLDoc()); + m_Components.insert(std::make_pair(COMPONENT_TYPE_LEVEL_PROGRESSION, levelComp)); + CharacterComponent* comp = new CharacterComponent(this, m_Character); m_Components.insert(std::make_pair(COMPONENT_TYPE_CHARACTER, comp)); } @@ -770,10 +777,9 @@ void Entity::Initialize() if (m_Character) { auto* controllablePhysicsComponent = GetComponent(); - auto* characterComponent = GetComponent(); + auto* levelComponent = GetComponent(); - if (controllablePhysicsComponent != nullptr && characterComponent->GetLevel() >= 20) - { + if (controllablePhysicsComponent != nullptr && levelComponent->GetLevel() >= 20) { controllablePhysicsComponent->SetSpeedMultiplier(525.0f / 500.0f); } } @@ -1088,6 +1094,15 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType // Should never happen, but just to be safe outBitStream->Write0(); } + + LevelProgressionComponent* levelProgressionComponent; + if (TryGetComponent(COMPONENT_TYPE_LEVEL_PROGRESSION, levelProgressionComponent)) { + levelProgressionComponent->Serialize(outBitStream, bIsInitialUpdate, flags); + } else { + // Should never happen, but just to be safe + outBitStream->Write0(); + } + characterComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } diff --git a/dGame/dComponents/CMakeLists.txt b/dGame/dComponents/CMakeLists.txt index 706395ea..ebf93dde 100644 --- a/dGame/dComponents/CMakeLists.txt +++ b/dGame/dComponents/CMakeLists.txt @@ -7,6 +7,7 @@ set(DGAME_DCOMPONENTS_SOURCES "BaseCombatAIComponent.cpp" "ControllablePhysicsComponent.cpp" "DestroyableComponent.cpp" "InventoryComponent.cpp" + "LevelProgressionComponent.cpp" "LUPExhibitComponent.cpp" "MissionComponent.cpp" "MissionOfferComponent.cpp" diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index dd2b69bb..a1eb3c62 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -21,7 +21,6 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C m_IsGM = false; m_IsLanding = false; m_IsLEGOClubMember = true; - m_Level = 1; m_DirtyCurrentActivity = false; m_DirtyGMInfo = false; @@ -80,8 +79,6 @@ CharacterComponent::~CharacterComponent() { } void CharacterComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - outBitStream->Write1(); - outBitStream->Write(m_Level); outBitStream->Write0(); if (bIsInitialUpdate) { @@ -181,57 +178,6 @@ void CharacterComponent::SetPvpEnabled(const bool value) m_PvpEnabled = value; } -void CharacterComponent::HandleLevelUp() -{ - auto* rewardsTable = CDClientManager::Instance()->GetTable("Rewards"); - - const auto& rewards = rewardsTable->GetByLevelID(m_Level); - bool rewardingItem = rewards.size() > 0; - - auto* parent = m_Character->GetEntity(); - - if (parent == nullptr) - { - return; - } - - auto* inventoryComponent = parent->GetComponent(); - auto* controllablePhysicsComponent = parent->GetComponent(); - - if (inventoryComponent == nullptr || controllablePhysicsComponent == nullptr) - { - return; - } - // Tell the client we beginning to send level rewards. - if(rewardingItem) GameMessages::NotifyLevelRewards(parent->GetObjectID(), parent->GetSystemAddress(), m_Level, rewardingItem); - - for (auto* reward : rewards) - { - switch (reward->rewardType) - { - case 0: - inventoryComponent->AddItem(reward->value, reward->count, eLootSourceType::LOOT_SOURCE_LEVEL_REWARD); - break; - case 4: - { - auto* items = inventoryComponent->GetInventory(eInventoryType::ITEMS); - items->SetSize(items->GetSize() + reward->value); - } - break; - case 9: - controllablePhysicsComponent->SetSpeedMultiplier(static_cast(reward->value) / 500.0f); - break; - case 11: - case 12: - break; - default: - break; - } - } - // Tell the client we have finished sending level rewards. - if(rewardingItem) GameMessages::NotifyLevelRewards(parent->GetObjectID(), parent->GetSystemAddress(), m_Level, !rewardingItem); -} - void CharacterComponent::SetGMLevel(int gmlevel) { m_DirtyGMInfo = true; if (gmlevel > 0) m_IsGM = true; @@ -332,14 +278,6 @@ void CharacterComponent::LoadFromXML() { } } - tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); - if (!level) { - Game::logger->Log("CharacterComponent", "Failed to find lvl tag while loading XML!\n"); - return; - } - - level->QueryAttribute("l", &m_Level); - if (character->FindAttribute("time")) { character->QueryUnsigned64Attribute("time", &m_TotalTimePlayed); } else { @@ -419,14 +357,6 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { // End custom attributes // - tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); - if (!level) { - Game::logger->Log("CharacterComponent", "Failed to find lvl tag while updating XML!\n"); - return; - } - - level->SetAttribute("l", m_Level); - auto newUpdateTimestamp = std::time(nullptr); Game::logger->Log("TotalTimePlayed", "Time since last save: %d\n", newUpdateTimestamp - m_LastUpdateTimestamp); diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index 009530c4..83b67a17 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -95,18 +95,6 @@ public: */ void RocketUnEquip(Entity* player); - /** - * Gets the current level of the entity - * @return the current level of the entity - */ - const uint32_t GetLevel() const { return m_Level; } - - /** - * Sets the level of the entity - * @param level the level to set - */ - void SetLevel(uint32_t level) { m_Level = level; } - /** * Gets the universe score of the entity * @return the universe score of the entity @@ -191,11 +179,6 @@ public: */ void SetMountItemID(LWOOBJID mountItemID) { m_MountItemID = mountItemID; } - /** - * Gives the player rewards for the last level that they leveled up from - */ - void HandleLevelUp(); - /** * Gets the name of this character * @return the name of this character @@ -323,11 +306,6 @@ private: */ uint8_t m_PossessableType = 1; - /** - * Level of the entity - */ - uint32_t m_Level; - /** * Universe score of the entity */ diff --git a/dGame/dComponents/LevelProgressionComponent.cpp b/dGame/dComponents/LevelProgressionComponent.cpp new file mode 100644 index 00000000..96d31970 --- /dev/null +++ b/dGame/dComponents/LevelProgressionComponent.cpp @@ -0,0 +1,74 @@ +#include "LevelProgressionComponent.h" +#include "ControllablePhysicsComponent.h" +#include "InventoryComponent.h" +#include "CharacterComponent.h" +#include "tinyxml2.h" + +LevelProgressionComponent::LevelProgressionComponent(Entity* parent) : Component(parent) { + m_Parent = parent; + m_Level = 1; +} + +void LevelProgressionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { + tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); + if (!level) { + Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while updating XML!\n"); + return; + } + level->SetAttribute("l", m_Level); + +} + +void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc){ + tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); + if (!level) { + Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while loading XML!\n"); + return; + } + level->QueryAttribute("l", &m_Level); + +} + +void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags){ + outBitStream->Write(bIsInitialUpdate || m_DirtyLevelInfo); + if (bIsInitialUpdate || m_DirtyLevelInfo) outBitStream->Write(m_Level); + m_DirtyLevelInfo = false; +} + +void LevelProgressionComponent::HandleLevelUp() { + auto* rewardsTable = CDClientManager::Instance()->GetTable("Rewards"); + + const auto& rewards = rewardsTable->GetByLevelID(m_Level); + bool rewardingItem = rewards.size() > 0; + + auto* inventoryComponent = m_Parent->GetComponent(); + auto* controllablePhysicsComponent = m_Parent->GetComponent(); + + if (!inventoryComponent || !controllablePhysicsComponent) return; + // Tell the client we beginning to send level rewards. + if(rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, rewardingItem); + + for (auto* reward : rewards) { + switch (reward->rewardType) { + case 0: + inventoryComponent->AddItem(reward->value, reward->count, eLootSourceType::LOOT_SOURCE_LEVEL_REWARD); + break; + case 4: + { + auto* items = inventoryComponent->GetInventory(eInventoryType::ITEMS); + items->SetSize(items->GetSize() + reward->value); + } + break; + case 9: + controllablePhysicsComponent->SetSpeedMultiplier(static_cast(reward->value) / 500.0f); + break; + case 11: + case 12: + break; + default: + break; + } + } + // Tell the client we have finished sending level rewards. + if(rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, !rewardingItem); +} diff --git a/dGame/dComponents/LevelProgressionComponent.h b/dGame/dComponents/LevelProgressionComponent.h new file mode 100644 index 00000000..ead3edfb --- /dev/null +++ b/dGame/dComponents/LevelProgressionComponent.h @@ -0,0 +1,63 @@ +#pragma once + +#include "Entity.h" +#include "GameMessages.h" +#include "Component.h" + +/** + * Component that handles level progression and serilization. + * + */ +class LevelProgressionComponent : public Component { +public: + static const uint32_t ComponentType = eReplicaComponentType::COMPONENT_TYPE_LEVEL_PROGRESSION; + + /** + * Constructor for this component + * @param parent parent that contains this component + */ + LevelProgressionComponent(Entity* parent); + ~LevelProgressionComponent() override {}; + + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + + /** + * Save data from this componennt to character XML + * @param doc the document to write data to + */ + void UpdateXml(tinyxml2::XMLDocument* doc) override; + + /** + * Load base data for this component from character XML + * @param doc the document to read data from + */ + void LoadFromXml(tinyxml2::XMLDocument* doc) override; + + /** + * Gets the current level of the entity + * @return the current level of the entity + */ + const uint32_t GetLevel() const { return m_Level; } + + /** + * Sets the level of the entity + * @param level the level to set + */ + void SetLevel(uint32_t level) { m_Level = level; m_DirtyLevelInfo = true; } + + /** + * Gives the player rewards for the last level that they leveled up from + */ + void HandleLevelUp(); + +private: + /** + * whether the level is dirty + */ + bool m_DirtyLevelInfo = false; + + /** + * Level of the entity + */ + uint32_t m_Level; +}; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 2f193170..935a7ccb 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -58,6 +58,7 @@ #include "PossessorComponent.h" #include "RacingControlComponent.h" #include "RailActivatorComponent.h" +#include "LevelProgressionComponent.h" // Message includes: #include "dZoneManager.h" @@ -912,14 +913,11 @@ void GameMessages::SendResurrect(Entity* entity) { DestroyableComponent* dest = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); if (dest != nullptr && entity->GetLOT() == 1) { - auto* characterComponent = entity->GetComponent(); - - if (characterComponent == nullptr) { - return; + auto* levelComponent = entity->GetComponent(); + if (levelComponent) { + dest->SetHealth(levelComponent->GetLevel() >= 45 ? 8 : 4); + dest->SetImagination(levelComponent->GetLevel() >= 45 ? 20 : 6); } - - dest->SetHealth(characterComponent->GetLevel() >= 45 ? 8 : 4); - dest->SetImagination(characterComponent->GetLevel() >= 45 ? 20 : 6); } auto cont = static_cast(entity->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); @@ -5309,13 +5307,15 @@ void GameMessages::HandleHasBeenCollected(RakNet::BitStream* inStream, Entity* e } void GameMessages::HandleNotifyServerLevelProcessingComplete(RakNet::BitStream* inStream, Entity* entity) { - auto* character = static_cast(entity->GetComponent(COMPONENT_TYPE_CHARACTER)); + auto* levelComp = entity->GetComponent(); + if (!levelComp) return; + auto* character = entity->GetComponent(); if (!character) return; //Update our character's level in memory: - character->SetLevel(character->GetLevel() + 1); + levelComp->SetLevel(levelComp->GetLevel() + 1); - character->HandleLevelUp(); + levelComp->HandleLevelUp(); auto* inventoryComponent = entity->GetComponent(); @@ -5333,7 +5333,7 @@ void GameMessages::HandleNotifyServerLevelProcessingComplete(RakNet::BitStream* //Send a notification in chat: std::stringstream wss; wss << "level=1:"; - wss << character->GetLevel(); + wss << levelComp->GetLevel(); wss << "\n"; wss << "name=0:"; wss << character->GetName(); diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index aeb26838..e51a6901 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -1,10 +1,11 @@ -#include "Mission.h" +#include "Mission.h" #include #include "CDClientManager.h" #include "Character.h" #include "CharacterComponent.h" +#include "LevelProgressionComponent.h" #include "DestroyableComponent.h" #include "EntityManager.h" #include "Game.h" @@ -406,6 +407,7 @@ void Mission::YieldRewards() { auto* character = GetUser()->GetLastUsedChar(); auto* inventoryComponent = entity->GetComponent(); + auto* levelComponent = entity->GetComponent(); auto* characterComponent = entity->GetComponent(); auto* destroyableComponent = entity->GetComponent(); auto* missionComponent = entity->GetComponent(); @@ -433,7 +435,7 @@ void Mission::YieldRewards() { int32_t coinsToSend = 0; if (info->LegoScore > 0) { eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; - if(characterComponent->GetLevel() >= dZoneManager::Instance()->GetMaxLevel()) { + if(levelComponent->GetLevel() >= dZoneManager::Instance()->GetMaxLevel()) { // Since the character is at the level cap we reward them with coins instead of UScore. coinsToSend += info->LegoScore * dZoneManager::Instance()->GetLevelCapCurrencyConversion(); } else { diff --git a/dGame/dUtilities/Preconditions.cpp b/dGame/dUtilities/Preconditions.cpp index bd10b814..2e006ec4 100644 --- a/dGame/dUtilities/Preconditions.cpp +++ b/dGame/dUtilities/Preconditions.cpp @@ -1,4 +1,4 @@ -#include "Preconditions.h" +#include "Preconditions.h" #include "Game.h" #include "dLogger.h" @@ -9,6 +9,7 @@ #include "MissionComponent.h" #include "Character.h" #include "CharacterComponent.h" +#include "LevelProgressionComponent.h" #include "DestroyableComponent.h" #include "GameMessages.h" @@ -128,7 +129,7 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluat auto* missionComponent = player->GetComponent(); auto* inventoryComponent = player->GetComponent(); auto* destroyableComponent = player->GetComponent(); - auto* characterComponent = player->GetComponent(); + auto* levelComponent = player->GetComponent(); auto* character = player->GetCharacter(); Mission* mission; @@ -207,7 +208,7 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluat case PreconditionType::NoInteraction: return false; // TODO case PreconditionType::HasLevel: - return characterComponent->GetLevel() >= value; + return levelComponent->GetLevel() >= value; default: return true; // There are a couple more unknown preconditions. Always return true in this case. } diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 22fbb680..4172884f 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -62,6 +62,7 @@ #include "VanityUtilities.h" #include "GameConfig.h" #include "ScriptedActivityComponent.h" +#include "LevelProgressionComponent.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { std::string chatCommand; @@ -1329,6 +1330,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit // query to set our uscore to the correct value for this level auto characterComponent = entity->GetComponent(); + if (!characterComponent) return; + auto levelComponent = entity->GetComponent(); auto query = CDClientDatabase::CreatePreppedStmt("SELECT requiredUScore from LevelProgressionLookup WHERE id = ?;"); query.bind(1, (int)requestedLevel); auto result = query.execQuery(); @@ -1336,18 +1339,18 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (result.eof()) return; // Set the UScore first - oldLevel = characterComponent->GetLevel(); + oldLevel = levelComponent->GetLevel(); characterComponent->SetUScore(result.getIntField(0, characterComponent->GetUScore())); // handle level up for each level we have passed if we set our level to be higher than the current one. if (oldLevel < requestedLevel) { while (oldLevel < requestedLevel) { oldLevel+=1; - characterComponent->SetLevel(oldLevel); - characterComponent->HandleLevelUp(); + levelComponent->SetLevel(oldLevel); + levelComponent->HandleLevelUp(); } } else { - characterComponent->SetLevel(requestedLevel); + levelComponent->SetLevel(requestedLevel); } if (requestedPlayerToSetLevelOf != "") { From b57cacc676dcdbf4fe6ec75bb0cf6d3dbd13abc3 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sun, 24 Jul 2022 13:25:10 -0500 Subject: [PATCH 039/322] Player forced movement component (#672) * Split out Level progression component from Character Component This is to get to the Player forced movement Comp in a sane way * move XML to component insted of abusing charComp * use overrides should probably make everything that calls that call it correctly * fix linking issue * Add proper Player Force movement component Not used, yet --- dCommon/dCommonVars.h | 95 ++++++++++--------- dGame/Entity.cpp | 19 ++-- dGame/dComponents/CMakeLists.txt | 1 + .../PlayerForcedMovementComponent.cpp | 16 ++++ .../PlayerForcedMovementComponent.h | 70 ++++++++++++++ 5 files changed, 147 insertions(+), 54 deletions(-) create mode 100644 dGame/dComponents/PlayerForcedMovementComponent.cpp create mode 100644 dGame/dComponents/PlayerForcedMovementComponent.h diff --git a/dCommon/dCommonVars.h b/dCommon/dCommonVars.h index f6efdcf8..9f62eaa4 100644 --- a/dCommon/dCommonVars.h +++ b/dCommon/dCommonVars.h @@ -366,53 +366,54 @@ enum eNotifyType { }; enum eReplicaComponentType : int32_t { - COMPONENT_TYPE_CONTROLLABLE_PHYSICS = 1, //!< The ControllablePhysics Component - COMPONENT_TYPE_RENDER = 2, //!< The Render Component - COMPONENT_TYPE_SIMPLE_PHYSICS = 3, //!< The SimplePhysics Component - COMPONENT_TYPE_CHARACTER = 4, //!< The Character Component - COMPONENT_TYPE_SCRIPT = 5, //!< The Script Component - COMPONENT_TYPE_BOUNCER = 6, //!< The Bouncer Component - COMPONENT_TYPE_BUFF = 7, //!< The Buff Component - COMPONENT_TYPE_SKILL = 9, //!< The Skill Component - COMPONENT_TYPE_ITEM = 11, //!< The Item Component - COMPONENT_TYPE_VENDOR = 16, //!< The Vendor Component - COMPONENT_TYPE_INVENTORY = 17, //!< The Inventory Component - COMPONENT_TYPE_SHOOTING_GALLERY = 19, //!< The Shooting Gallery Component - COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS = 20, //!< The RigidBodyPhantomPhysics Component - COMPONENT_TYPE_COLLECTIBLE = 23, //!< The Collectible Component - COMPONENT_TYPE_MOVING_PLATFORM = 25, //!< The MovingPlatform Component - COMPONENT_TYPE_PET = 26, //!< The Pet Component - COMPONENT_TYPE_VEHICLE_PHYSICS = 30, //!< The VehiclePhysics Component - COMPONENT_TYPE_MOVEMENT_AI = 31, //!< The MovementAI Component - COMPONENT_TYPE_PROPERTY = 36, //!< The Property Component - COMPONENT_TYPE_SCRIPTED_ACTIVITY = 39, //!< The ScriptedActivity Component - COMPONENT_TYPE_PHANTOM_PHYSICS = 40, //!< The PhantomPhysics Component - COMPONENT_TYPE_MODEL = 42, //!< The Model Component - COMPONENT_TYPE_PROPERTY_ENTRANCE = 43, //!< The PhantomPhysics Component - COMPONENT_TYPE_PROPERTY_MANAGEMENT = 45, //!< The PropertyManagement Component - COMPONENT_TYPE_REBUILD = 48, //!< The Rebuild Component - COMPONENT_TYPE_SWITCH = 49, //!< The Switch Component - COMPONENT_TYPE_ZONE_CONTROL = 50, //!< The ZoneControl Component - COMPONENT_TYPE_PACKAGE = 53, //!< The Package Component - COMPONENT_TYPE_PLAYER_FLAG = 58, //!< The PlayerFlag Component - COMPONENT_TYPE_BASE_COMBAT_AI = 60, //!< The BaseCombatAI Component - COMPONENT_TYPE_MODULE_ASSEMBLY = 61, //!< The ModuleAssembly Component - COMPONENT_TYPE_PROPERTY_VENDOR = 65, //!< The PropertyVendor Component - COMPONENT_TYPE_ROCKET_LAUNCH = 67, //!< The RocketLaunch Component - COMPONENT_TYPE_RACING_CONTROL = 71, //!< The RacingControl Component - COMPONENT_TYPE_MISSION_OFFER = 73, //!< The MissionOffer Component - COMPONENT_TYPE_EXHIBIT = 75, //!< The Exhibit Component - COMPONENT_TYPE_RACING_STATS = 74, //!< The Racing Stats Component - COMPONENT_TYPE_SOUND_TRIGGER = 77, //!< The Sound Trigger Component - COMPONENT_TYPE_PROXIMITY_MONITOR = 78, //!< The Proximity Monitor Component - COMPONENT_TYPE_MISSION = 84, //!< The Mission Component - COMPONENT_TYPE_ROCKET_LAUNCH_LUP = 97, //!< The LUP Launchpad Componen - COMPONENT_TYPE_RAIL_ACTIVATOR = 104, - COMPONENT_TYPE_POSSESSABLE = 108, //!< The Possessable Component - COMPONENT_TYPE_LEVEL_PROGRESSION = 109, //!< The Level Progression Component - COMPONENT_TYPE_POSSESSOR = 110, //!< The Possessor Component - COMPONENT_TYPE_BUILD_BORDER = 114, //!< The Build Border Component - COMPONENT_TYPE_DESTROYABLE = 1000, //!< The Destroyable Component + COMPONENT_TYPE_CONTROLLABLE_PHYSICS = 1, //!< The ControllablePhysics Component + COMPONENT_TYPE_RENDER = 2, //!< The Render Component + COMPONENT_TYPE_SIMPLE_PHYSICS = 3, //!< The SimplePhysics Component + COMPONENT_TYPE_CHARACTER = 4, //!< The Character Component + COMPONENT_TYPE_SCRIPT = 5, //!< The Script Component + COMPONENT_TYPE_BOUNCER = 6, //!< The Bouncer Component + COMPONENT_TYPE_BUFF = 7, //!< The Buff Component + COMPONENT_TYPE_SKILL = 9, //!< The Skill Component + COMPONENT_TYPE_ITEM = 11, //!< The Item Component + COMPONENT_TYPE_VENDOR = 16, //!< The Vendor Component + COMPONENT_TYPE_INVENTORY = 17, //!< The Inventory Component + COMPONENT_TYPE_SHOOTING_GALLERY = 19, //!< The Shooting Gallery Component + COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS = 20, //!< The RigidBodyPhantomPhysics Component + COMPONENT_TYPE_COLLECTIBLE = 23, //!< The Collectible Component + COMPONENT_TYPE_MOVING_PLATFORM = 25, //!< The MovingPlatform Component + COMPONENT_TYPE_PET = 26, //!< The Pet Component + COMPONENT_TYPE_VEHICLE_PHYSICS = 30, //!< The VehiclePhysics Component + COMPONENT_TYPE_MOVEMENT_AI = 31, //!< The MovementAI Component + COMPONENT_TYPE_PROPERTY = 36, //!< The Property Component + COMPONENT_TYPE_SCRIPTED_ACTIVITY = 39, //!< The ScriptedActivity Component + COMPONENT_TYPE_PHANTOM_PHYSICS = 40, //!< The PhantomPhysics Component + COMPONENT_TYPE_MODEL = 42, //!< The Model Component + COMPONENT_TYPE_PROPERTY_ENTRANCE = 43, //!< The PhantomPhysics Component + COMPONENT_TYPE_PROPERTY_MANAGEMENT = 45, //!< The PropertyManagement Component + COMPONENT_TYPE_REBUILD = 48, //!< The Rebuild Component + COMPONENT_TYPE_SWITCH = 49, //!< The Switch Component + COMPONENT_TYPE_ZONE_CONTROL = 50, //!< The ZoneControl Component + COMPONENT_TYPE_PACKAGE = 53, //!< The Package Component + COMPONENT_TYPE_PLAYER_FLAG = 58, //!< The PlayerFlag Component + COMPONENT_TYPE_BASE_COMBAT_AI = 60, //!< The BaseCombatAI Component + COMPONENT_TYPE_MODULE_ASSEMBLY = 61, //!< The ModuleAssembly Component + COMPONENT_TYPE_PROPERTY_VENDOR = 65, //!< The PropertyVendor Component + COMPONENT_TYPE_ROCKET_LAUNCH = 67, //!< The RocketLaunch Component + COMPONENT_TYPE_RACING_CONTROL = 71, //!< The RacingControl Component + COMPONENT_TYPE_MISSION_OFFER = 73, //!< The MissionOffer Component + COMPONENT_TYPE_EXHIBIT = 75, //!< The Exhibit Component + COMPONENT_TYPE_RACING_STATS = 74, //!< The Racing Stats Component + COMPONENT_TYPE_SOUND_TRIGGER = 77, //!< The Sound Trigger Component + COMPONENT_TYPE_PROXIMITY_MONITOR = 78, //!< The Proximity Monitor Component + COMPONENT_TYPE_MISSION = 84, //!< The Mission Component + COMPONENT_TYPE_ROCKET_LAUNCH_LUP = 97, //!< The LUP Launchpad Componen + COMPONENT_TYPE_RAIL_ACTIVATOR = 104, //!< The Rail Activator Component + COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT = 106, //!< The Player Forced Movement Component + COMPONENT_TYPE_POSSESSABLE = 108, //!< The Possessable Component + COMPONENT_TYPE_LEVEL_PROGRESSION = 109, //!< The Level Progression Component + COMPONENT_TYPE_POSSESSOR = 110, //!< The Possessor Component + COMPONENT_TYPE_BUILD_BORDER = 114, //!< The Build Border Component + COMPONENT_TYPE_DESTROYABLE = 1000, //!< The Destroyable Component }; enum class UseItemResponse : uint32_t { diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 45287bd8..32fa7d5b 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -29,6 +29,7 @@ #include "BouncerComponent.h" #include "InventoryComponent.h" #include "LevelProgressionComponent.h" +#include "PlayerForcedMovementComponent.h" #include "ScriptComponent.h" #include "SkillComponent.h" #include "SimplePhysicsComponent.h" @@ -436,14 +437,8 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_DESTROYABLE, comp)); } - /*if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_DESTROYABLE) > 0 || m_Character) { - DestroyableComponent* comp = new DestroyableComponent(); - if (m_Character) comp->LoadFromXML(m_Character->GetXMLDoc()); - m_Components.push_back(std::make_pair(COMPONENT_TYPE_DESTROYABLE, comp)); - }*/ - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_CHARACTER) > 0 || m_Character) { - // Character Component always has a possessor and level components + // Character Component always has a possessor, level, and forced movement components m_Components.insert(std::make_pair(COMPONENT_TYPE_POSSESSOR, new PossessorComponent(this))); // load in the xml for the level @@ -451,6 +446,8 @@ void Entity::Initialize() levelComp->LoadFromXml(m_Character->GetXMLDoc()); m_Components.insert(std::make_pair(COMPONENT_TYPE_LEVEL_PROGRESSION, levelComp)); + m_Components.insert(std::make_pair(COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT, new PlayerForcedMovementComponent(this))); + CharacterComponent* comp = new CharacterComponent(this, m_Character); m_Components.insert(std::make_pair(COMPONENT_TYPE_CHARACTER, comp)); } @@ -1103,6 +1100,14 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType outBitStream->Write0(); } + PlayerForcedMovementComponent* playerForcedMovementComponent; + if (TryGetComponent(COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT, playerForcedMovementComponent)) { + playerForcedMovementComponent->Serialize(outBitStream, bIsInitialUpdate, flags); + } else { + // Should never happen, but just to be safe + outBitStream->Write0(); + } + characterComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } diff --git a/dGame/dComponents/CMakeLists.txt b/dGame/dComponents/CMakeLists.txt index ebf93dde..0995428b 100644 --- a/dGame/dComponents/CMakeLists.txt +++ b/dGame/dComponents/CMakeLists.txt @@ -17,6 +17,7 @@ set(DGAME_DCOMPONENTS_SOURCES "BaseCombatAIComponent.cpp" "MovingPlatformComponent.cpp" "PetComponent.cpp" "PhantomPhysicsComponent.cpp" + "PlayerForcedMovementComponent.cpp" "PossessableComponent.cpp" "PossessorComponent.cpp" "PropertyComponent.cpp" diff --git a/dGame/dComponents/PlayerForcedMovementComponent.cpp b/dGame/dComponents/PlayerForcedMovementComponent.cpp new file mode 100644 index 00000000..94b79188 --- /dev/null +++ b/dGame/dComponents/PlayerForcedMovementComponent.cpp @@ -0,0 +1,16 @@ +#include "PlayerForcedMovementComponent.h" + +PlayerForcedMovementComponent::PlayerForcedMovementComponent(Entity* parent) : Component(parent) { + m_Parent = parent; +} + +PlayerForcedMovementComponent::~PlayerForcedMovementComponent() {} + +void PlayerForcedMovementComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags){ + outBitStream->Write(m_DirtyInfo); + if (m_DirtyInfo) { + outBitStream->Write(m_PlayerOnRail); + outBitStream->Write(m_ShowBillboard); + } + m_DirtyInfo = false; +} \ No newline at end of file diff --git a/dGame/dComponents/PlayerForcedMovementComponent.h b/dGame/dComponents/PlayerForcedMovementComponent.h new file mode 100644 index 00000000..5745a42f --- /dev/null +++ b/dGame/dComponents/PlayerForcedMovementComponent.h @@ -0,0 +1,70 @@ +#pragma once + +#include "Entity.h" +#include "GameMessages.h" +#include "Component.h" + +/** + * Component that handles player forced movement + * + */ +class PlayerForcedMovementComponent : public Component { +public: + static const uint32_t ComponentType = eReplicaComponentType::COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT; + + /** + * Constructor for this component + * @param parent parent that contains this component + */ + PlayerForcedMovementComponent(Entity* parent); + ~PlayerForcedMovementComponent() override; + + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + + /** + * @brief Set the Player On Rail object + * + * @param value if the player is on a rail + */ + void SetPlayerOnRail(bool value){ m_PlayerOnRail = value; m_DirtyInfo = true; } + + /** + * @brief Set the Show Billboard object + * + * @param value if the billboard should be shown + */ + void SetShowBillboard(bool value){ m_ShowBillboard = value; m_DirtyInfo = true; } + + /** + * @brief Get the Player On Rail object + * + * @return true + * @return false + */ + + /** + * @brief Get the Player On Rail object + * + * @return true + * @return false + */ + bool GetPlayerOnRail(){ return m_PlayerOnRail; } + bool GetShowBillboard(){ return m_ShowBillboard; } + +private: + /** + * whether the info is dirty + */ + bool m_DirtyInfo = false; + + /** + * whether the player is on a rail + */ + bool m_PlayerOnRail = false; + + /** + * whether the billboard should be showing + */ + bool m_ShowBillboard = false; + +}; From 9ed4a4f47fe45fe7b3aa2b80fd10be3d93c4765a Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sun, 24 Jul 2022 16:17:01 -0500 Subject: [PATCH 040/322] Remove uneeded include (#674) --- dGame/dComponents/CharacterComponent.cpp | 1 - dGame/dComponents/PlayerForcedMovementComponent.h | 1 - 2 files changed, 2 deletions(-) diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index a1eb3c62..c7078f42 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -79,7 +79,6 @@ CharacterComponent::~CharacterComponent() { } void CharacterComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - outBitStream->Write0(); if (bIsInitialUpdate) { outBitStream->Write0(); diff --git a/dGame/dComponents/PlayerForcedMovementComponent.h b/dGame/dComponents/PlayerForcedMovementComponent.h index 5745a42f..d023155c 100644 --- a/dGame/dComponents/PlayerForcedMovementComponent.h +++ b/dGame/dComponents/PlayerForcedMovementComponent.h @@ -1,7 +1,6 @@ #pragma once #include "Entity.h" -#include "GameMessages.h" #include "Component.h" /** From a7fb6eb3f3108f2cf64b0f2bacd64733e2c6c971 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sun, 24 Jul 2022 21:03:22 -0500 Subject: [PATCH 041/322] make LoadFromXml usage consistent across comps (#673) --- dGame/Entity.cpp | 9 +++++---- dGame/dComponents/BuffComponent.cpp | 2 +- dGame/dComponents/BuffComponent.h | 2 +- dGame/dComponents/CharacterComponent.cpp | 9 +-------- dGame/dComponents/CharacterComponent.h | 2 +- dGame/dComponents/ControllablePhysicsComponent.cpp | 2 +- dGame/dComponents/ControllablePhysicsComponent.h | 2 +- dGame/dComponents/DestroyableComponent.cpp | 4 ++-- dGame/dComponents/DestroyableComponent.h | 2 +- dGame/dComponents/LevelProgressionComponent.h | 1 - 10 files changed, 14 insertions(+), 21 deletions(-) diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 32fa7d5b..fbb61437 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -252,7 +252,7 @@ void Entity::Initialize() ControllablePhysicsComponent* controllablePhysics = new ControllablePhysicsComponent(this); if (m_Character) { - controllablePhysics->LoadFromXML(m_Character->GetXMLDoc()); + controllablePhysics->LoadFromXml(m_Character->GetXMLDoc()); const auto mapID = Game::server->GetZoneID(); @@ -362,7 +362,7 @@ void Entity::Initialize() if (buffComponentID > 0 || collectibleComponentID > 0) { DestroyableComponent* comp = new DestroyableComponent(this); if (m_Character) { - comp->LoadFromXML(m_Character->GetXMLDoc()); + comp->LoadFromXml(m_Character->GetXMLDoc()); } else { if (componentID > 0) { @@ -448,8 +448,9 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT, new PlayerForcedMovementComponent(this))); - CharacterComponent* comp = new CharacterComponent(this, m_Character); - m_Components.insert(std::make_pair(COMPONENT_TYPE_CHARACTER, comp)); + CharacterComponent* charComp = new CharacterComponent(this, m_Character); + charComp->LoadFromXml(m_Character->GetXMLDoc()); + m_Components.insert(std::make_pair(COMPONENT_TYPE_CHARACTER, charComp)); } if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_INVENTORY) > 0 || m_Character) { diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index 9c12e87d..dcc74214 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -289,7 +289,7 @@ Entity* BuffComponent::GetParent() const return m_Parent; } -void BuffComponent::LoadFromXML(tinyxml2::XMLDocument* doc) +void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { // Load buffs auto* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); diff --git a/dGame/dComponents/BuffComponent.h b/dGame/dComponents/BuffComponent.h index ba22c08b..49d7fec4 100644 --- a/dGame/dComponents/BuffComponent.h +++ b/dGame/dComponents/BuffComponent.h @@ -49,7 +49,7 @@ public: Entity* GetParent() const; - void LoadFromXML(tinyxml2::XMLDocument* doc); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; void UpdateXml(tinyxml2::XMLDocument* doc) override; diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index c7078f42..f854c2b8 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -37,8 +37,6 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C m_CountryCode = 0; m_LastUpdateTimestamp = std::time(nullptr); - LoadFromXML(); - //Check to see if we're landing: if (character->GetZoneID() != Game::server->GetZoneID()) { m_IsLanding = true; @@ -184,12 +182,7 @@ void CharacterComponent::SetGMLevel(int gmlevel) { m_GMLevel = gmlevel; } -void CharacterComponent::LoadFromXML() { - if (!m_Character) return; - - tinyxml2::XMLDocument* doc = m_Character->GetXMLDoc(); - if (!doc) return; - +void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { Game::logger->Log("CharacterComponent", "Failed to find char tag while loading XML!\n"); diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index 83b67a17..cd5809f0 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -64,7 +64,7 @@ public: CharacterComponent(Entity* parent, Character* character); ~CharacterComponent() override; - void LoadFromXML(); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; void UpdateXml(tinyxml2::XMLDocument* doc) override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); diff --git a/dGame/dComponents/ControllablePhysicsComponent.cpp b/dGame/dComponents/ControllablePhysicsComponent.cpp index 648b1471..5d9cdd40 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/ControllablePhysicsComponent.cpp @@ -130,7 +130,7 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bo if (!bIsInitialUpdate) outBitStream->Write0(); } -void ControllablePhysicsComponent::LoadFromXML(tinyxml2::XMLDocument* doc) { +void ControllablePhysicsComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { Game::logger->Log("ControllablePhysicsComponent", "Failed to find char tag!\n"); diff --git a/dGame/dComponents/ControllablePhysicsComponent.h b/dGame/dComponents/ControllablePhysicsComponent.h index c7acec62..73b3bb69 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.h +++ b/dGame/dComponents/ControllablePhysicsComponent.h @@ -25,7 +25,7 @@ public: void Update(float deltaTime) override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void LoadFromXML(tinyxml2::XMLDocument* doc); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; void ResetFlags(); void UpdateXml(tinyxml2::XMLDocument* doc) override; diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index efcfb5cb..e7a6d385 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -159,7 +159,7 @@ void DestroyableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIn } } -void DestroyableComponent::LoadFromXML(tinyxml2::XMLDocument* doc) { +void DestroyableComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); if (!dest) { Game::logger->Log("DestroyableComponent", "Failed to find dest tag!\n"); @@ -169,7 +169,7 @@ void DestroyableComponent::LoadFromXML(tinyxml2::XMLDocument* doc) { auto* buffComponent = m_Parent->GetComponent(); if (buffComponent != nullptr) { - buffComponent->LoadFromXML(doc); + buffComponent->LoadFromXml(doc); } dest->QueryAttribute("hc", &m_iHealth); diff --git a/dGame/dComponents/DestroyableComponent.h b/dGame/dComponents/DestroyableComponent.h index ade3f4e8..9d2b228f 100644 --- a/dGame/dComponents/DestroyableComponent.h +++ b/dGame/dComponents/DestroyableComponent.h @@ -19,7 +19,7 @@ public: ~DestroyableComponent() override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags); - void LoadFromXML(tinyxml2::XMLDocument* doc); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; void UpdateXml(tinyxml2::XMLDocument* doc) override; /** diff --git a/dGame/dComponents/LevelProgressionComponent.h b/dGame/dComponents/LevelProgressionComponent.h index ead3edfb..53f6693e 100644 --- a/dGame/dComponents/LevelProgressionComponent.h +++ b/dGame/dComponents/LevelProgressionComponent.h @@ -17,7 +17,6 @@ public: * @param parent parent that contains this component */ LevelProgressionComponent(Entity* parent); - ~LevelProgressionComponent() override {}; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); From e97ae92624c436f118a36c60c4a2b8bcc456617d Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Sun, 24 Jul 2022 21:26:51 -0500 Subject: [PATCH 042/322] Make logger automatically put a newline (#675) at the end of the line remove all the newlines in log calls --- dAuthServer/AuthServer.cpp | 12 +- dChatServer/ChatPacketHandler.cpp | 66 ++++---- dChatServer/ChatServer.cpp | 24 +-- dChatServer/PlayerContainer.cpp | 56 +++---- dCommon/dLogger.cpp | 6 +- dDatabase/Database.cpp | 12 +- dDatabase/MigrationRunner.cpp | 8 +- dDatabase/Tables/CDSkillBehaviorTable.cpp | 6 +- dGame/Character.cpp | 136 ++++++++-------- dGame/Player.cpp | 30 ++-- dGame/TradingManager.cpp | 60 +++---- dGame/User.cpp | 24 +-- dGame/UserManager.cpp | 150 +++++++++--------- dGame/dBehaviors/AreaOfEffectBehavior.cpp | 14 +- dGame/dBehaviors/BasicAttackBehavior.cpp | 10 +- dGame/dBehaviors/Behavior.cpp | 10 +- dGame/dBehaviors/BehaviorContext.cpp | 40 ++--- dGame/dBehaviors/BlockBehavior.cpp | 4 +- dGame/dBehaviors/BuffBehavior.cpp | 14 +- dGame/dBehaviors/CarBoostBehavior.cpp | 8 +- dGame/dBehaviors/DamageAbsorptionBehavior.cpp | 10 +- dGame/dBehaviors/DamageReductionBehavior.cpp | 10 +- dGame/dBehaviors/HealBehavior.cpp | 6 +- dGame/dBehaviors/ImmunityBehavior.cpp | 8 +- dGame/dBehaviors/MovementSwitchBehavior.cpp | 8 +- dGame/dBehaviors/ProjectileAttackBehavior.cpp | 16 +- dGame/dBehaviors/RepairBehavior.cpp | 6 +- dGame/dBehaviors/SpawnBehavior.cpp | 14 +- dGame/dBehaviors/StunBehavior.cpp | 12 +- dGame/dBehaviors/SwitchBehavior.cpp | 12 +- dGame/dBehaviors/TacArcBehavior.cpp | 16 +- dGame/dBehaviors/TauntBehavior.cpp | 8 +- dGame/dBehaviors/VerifyBehavior.cpp | 4 +- dGame/dComponents/BaseCombatAIComponent.cpp | 48 +++--- dGame/dComponents/BouncerComponent.cpp | 18 +-- dGame/dComponents/BuffComponent.cpp | 40 ++--- dGame/dComponents/BuildBorderComponent.cpp | 6 +- dGame/dComponents/CharacterComponent.cpp | 31 ++-- .../ControllablePhysicsComponent.cpp | 10 +- dGame/dComponents/DestroyableComponent.cpp | 16 +- dGame/dComponents/InventoryComponent.cpp | 46 +++--- .../dComponents/LevelProgressionComponent.cpp | 4 +- dGame/dComponents/MissionComponent.cpp | 14 +- dGame/dComponents/MissionOfferComponent.cpp | 26 +-- dGame/dComponents/MovingPlatformComponent.cpp | 40 ++--- dGame/dComponents/PetComponent.cpp | 94 +++++------ dGame/dComponents/PhantomPhysicsComponent.cpp | 24 +-- .../dComponents/PropertyEntranceComponent.cpp | 8 +- .../PropertyManagementComponent.cpp | 74 ++++----- dGame/dComponents/PropertyVendorComponent.cpp | 10 +- dGame/dComponents/RacingControlComponent.cpp | 22 +-- dGame/dComponents/RebuildComponent.cpp | 26 +-- .../RocketLaunchpadControlComponent.cpp | 4 +- .../dComponents/ScriptedActivityComponent.cpp | 16 +- dGame/dComponents/SkillComponent.cpp | 10 +- dGame/dGameMessages/GameMessageHandler.cpp | 60 +++---- dGame/dGameMessages/GameMessages.cpp | 86 +++++----- dGame/dInventory/Inventory.cpp | 36 ++--- dGame/dInventory/Item.cpp | 50 +++--- dGame/dMission/Mission.cpp | 4 +- dGame/dMission/MissionTask.cpp | 44 ++--- dGame/dUtilities/Mail.cpp | 8 +- dGame/dUtilities/Preconditions.cpp | 2 +- dGame/dUtilities/SlashCommandHandler.cpp | 20 +-- dGame/dUtilities/VanityUtilities.cpp | 34 ++-- dMasterServer/InstanceManager.cpp | 52 +++--- dMasterServer/MasterServer.cpp | 88 +++++----- dMasterServer/ObjectIDManager.cpp | 4 +- dNet/AuthPackets.cpp | 74 ++++----- dNet/ClientPackets.cpp | 10 +- dNet/WorldPackets.cpp | 36 ++--- dNet/dServer.cpp | 14 +- dPhysics/dpWorld.cpp | 22 +-- dScripts/ActivityManager.cpp | 10 +- dScripts/AgJetEffectServer.cpp | 10 +- dScripts/BaseRandomServer.cpp | 28 ++-- dScripts/BossSpiderQueenEnemyServer.cpp | 138 ++++++++-------- dScripts/CppScripts.cpp | 2 +- dScripts/FlameJetServer.cpp | 8 +- dScripts/FvMaelstromDragon.cpp | 12 +- dScripts/NjMonastryBossInstance.cpp | 4 +- dScripts/SGCannon.cpp | 70 ++++---- dWorldServer/WorldServer.cpp | 94 ++++++----- dZoneManager/Level.cpp | 20 ++- dZoneManager/Zone.cpp | 36 ++--- dZoneManager/dZoneManager.cpp | 18 +-- 86 files changed, 1249 insertions(+), 1252 deletions(-) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index fef3124b..f5c85c3f 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -37,9 +37,9 @@ int main(int argc, char** argv) { //Create all the objects we need to run our service: Game::logger = SetupLogger(); if (!Game::logger) return 0; - Game::logger->Log("AuthServer", "Starting Auth server...\n"); - Game::logger->Log("AuthServer", "Version: %i.%i\n", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); - Game::logger->Log("AuthServer", "Compiled on: %s\n", __TIMESTAMP__); + Game::logger->Log("AuthServer", "Starting Auth server..."); + Game::logger->Log("AuthServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); + Game::logger->Log("AuthServer", "Compiled on: %s", __TIMESTAMP__); //Read our config: dConfig config("authconfig.ini"); @@ -56,7 +56,7 @@ int main(int argc, char** argv) { try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); } catch (sql::SQLException& ex) { - Game::logger->Log("AuthServer", "Got an error while connecting to the database: %s\n", ex.what()); + Game::logger->Log("AuthServer", "Got an error while connecting to the database: %s", ex.what()); Database::Destroy("AuthServer"); delete Game::server; delete Game::logger; @@ -78,10 +78,10 @@ int main(int argc, char** argv) { //It's safe to pass 'localhost' here, as the IP is only used as the external IP. int maxClients = 50; - int ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. + int ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); - + Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth); //Run it until server gets a kill message from Master: diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index 4f055121..213e1948 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -79,7 +79,7 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { bitStream.Write(0); bitStream.Write(1); //Length of packet -- just writing one as it doesn't matter, client skips it. bitStream.Write((uint16_t)friends.size()); - + for (auto& data : friends) { data.Serialize(bitStream); } @@ -139,7 +139,7 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { } } - // If at this point we dont have a target, then they arent online and we cant send the request. + // If at this point we dont have a target, then they arent online and we cant send the request. // Send the response code that corresponds to what the error is. if (!requestee) { std::unique_ptr nameQuery(Database::CreatePreppedStmt("SELECT name from charinfo where name = ?;")); @@ -232,7 +232,7 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { // Do not send this if we are requesting to be a best friend. SendFriendRequest(requestee.get(), requestor); } - + // If the player is actually a player and not a ghost one defined above, release it from being deleted. if (requestee->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) requestee.release(); } @@ -301,7 +301,7 @@ void ChatPacketHandler::HandleFriendResponse(Packet* packet) { requesteeData.isFTP = false; requesteeData.isOnline = true; requestor->friends.push_back(requesteeData); - + std::unique_ptr statement(Database::CreatePreppedStmt("INSERT IGNORE INTO `friends` (`player_id`, `friend_id`, `best_friend`) VALUES (?,?,?);")); statement->setUInt(1, static_cast(requestor->playerID)); statement->setUInt(2, static_cast(requestee->playerID)); @@ -371,7 +371,7 @@ void ChatPacketHandler::HandleRemoveFriend(Packet* packet) { SendRemoveFriend(goonB, goonAName, true); } -void ChatPacketHandler::HandleChatMessage(Packet* packet) +void ChatPacketHandler::HandleChatMessage(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; @@ -390,10 +390,10 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) uint8_t channel = 0; inStream.Read(channel); - + std::string message = PacketUtils::ReadString(0x66, packet, true); - Game::logger->Log("ChatPacketHandler", "Got a message from (%s) [%d]: %s\n", senderName.c_str(), channel, message.c_str()); + Game::logger->Log("ChatPacketHandler", "Got a message from (%s) [%d]: %s", senderName.c_str(), channel, message.c_str()); if (channel != 8) return; @@ -530,16 +530,16 @@ void ChatPacketHandler::HandleTeamInvite(Packet* packet) if (team->memberIDs.size() > 3) { // no more teams greater than 4 - Game::logger->Log("ChatPacketHandler", "Someone tried to invite a 5th player to a team\n"); + Game::logger->Log("ChatPacketHandler", "Someone tried to invite a 5th player to a team"); return; } SendTeamInvite(other, player); - Game::logger->Log("ChatPacketHandler", "Got team invite: %llu -> %s\n", playerID, invitedPlayer.c_str()); + Game::logger->Log("ChatPacketHandler", "Got team invite: %llu -> %s", playerID, invitedPlayer.c_str()); } -void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) +void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; @@ -552,7 +552,7 @@ void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) LWOOBJID leaderID = LWOOBJID_EMPTY; inStream.Read(leaderID); - Game::logger->Log("ChatPacketHandler", "Accepted invite: %llu -> %llu (%d)\n", playerID, leaderID, declined); + Game::logger->Log("ChatPacketHandler", "Accepted invite: %llu -> %llu (%d)", playerID, leaderID, declined); if (declined) { @@ -563,21 +563,21 @@ void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) if (team == nullptr) { - Game::logger->Log("ChatPacketHandler", "Failed to find team for leader (%llu)\n", leaderID); + Game::logger->Log("ChatPacketHandler", "Failed to find team for leader (%llu)", leaderID); team = playerContainer.GetTeam(playerID); } - + if (team == nullptr) { - Game::logger->Log("ChatPacketHandler", "Failed to find team for player (%llu)\n", playerID); + Game::logger->Log("ChatPacketHandler", "Failed to find team for player (%llu)", playerID); return; } playerContainer.AddMember(team, playerID); } -void ChatPacketHandler::HandleTeamLeave(Packet* packet) +void ChatPacketHandler::HandleTeamLeave(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; @@ -588,7 +588,7 @@ void ChatPacketHandler::HandleTeamLeave(Packet* packet) auto* team = playerContainer.GetTeam(playerID); - Game::logger->Log("ChatPacketHandler", "(%llu) leaving team\n", playerID); + Game::logger->Log("ChatPacketHandler", "(%llu) leaving team", playerID); if (team != nullptr) { @@ -596,16 +596,16 @@ void ChatPacketHandler::HandleTeamLeave(Packet* packet) } } -void ChatPacketHandler::HandleTeamKick(Packet* packet) +void ChatPacketHandler::HandleTeamKick(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); inStream.Read(playerID); - + std::string kickedPlayer = PacketUtils::ReadString(0x14, packet, true); - Game::logger->Log("ChatPacketHandler", "(%llu) kicking (%s) from team\n", playerID, kickedPlayer.c_str()); + Game::logger->Log("ChatPacketHandler", "(%llu) kicking (%s) from team", playerID, kickedPlayer.c_str()); auto* kicked = playerContainer.GetPlayerData(kickedPlayer); @@ -632,16 +632,16 @@ void ChatPacketHandler::HandleTeamKick(Packet* packet) } } -void ChatPacketHandler::HandleTeamPromote(Packet* packet) +void ChatPacketHandler::HandleTeamPromote(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); inStream.Read(playerID); - + std::string promotedPlayer = PacketUtils::ReadString(0x14, packet, true); - Game::logger->Log("ChatPacketHandler", "(%llu) promoting (%s) to team leader\n", playerID, promotedPlayer.c_str()); + Game::logger->Log("ChatPacketHandler", "(%llu) promoting (%s) to team leader", playerID, promotedPlayer.c_str()); auto* promoted = playerContainer.GetPlayerData(promotedPlayer); @@ -657,7 +657,7 @@ void ChatPacketHandler::HandleTeamPromote(Packet* packet) } } -void ChatPacketHandler::HandleTeamLootOption(Packet* packet) +void ChatPacketHandler::HandleTeamLootOption(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; @@ -665,7 +665,7 @@ void ChatPacketHandler::HandleTeamLootOption(Packet* packet) inStream.Read(playerID); uint32_t size = 0; inStream.Read(size); - + char option; inStream.Read(option); @@ -678,12 +678,12 @@ void ChatPacketHandler::HandleTeamLootOption(Packet* packet) team->lootFlag = option; playerContainer.TeamStatusUpdate(team); - + playerContainer.UpdateTeamsOnWorld(team, false); } } -void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) +void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; @@ -729,7 +729,7 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) if (memberId == playerID) continue; const auto memberName = playerContainer.GetName(memberId); - + if (otherMember != nullptr) { ChatPacketHandler::SendTeamSetOffWorldFlag(otherMember, data->playerID, data->zoneID); @@ -741,7 +741,7 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) } } -void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) +void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); @@ -757,7 +757,7 @@ void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) SEND_PACKET; } -void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeaderIsFreeTrial, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, uint8_t ucResponseCode, std::u16string wsLeaderName) +void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeaderIsFreeTrial, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, uint8_t ucResponseCode, std::u16string wsLeaderName) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); @@ -813,7 +813,7 @@ void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderI SEND_PACKET; } -void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64PlayerID) +void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64PlayerID) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); @@ -831,7 +831,7 @@ void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64Play SEND_PACKET; } -void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTrial, bool bLocal, bool bNoLootOnDeath, LWOOBJID i64PlayerID, std::u16string wsPlayerName, LWOZONEID zoneID) +void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTrial, bool bLocal, bool bNoLootOnDeath, LWOOBJID i64PlayerID, std::u16string wsPlayerName, LWOZONEID zoneID) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); @@ -863,7 +863,7 @@ void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTria SEND_PACKET; } -void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband, bool bIsKicked, bool bIsLeaving, bool bLocal, LWOOBJID i64LeaderID, LWOOBJID i64PlayerID, std::u16string wsPlayerName) +void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband, bool bIsKicked, bool bIsLeaving, bool bLocal, LWOOBJID i64LeaderID, LWOOBJID i64PlayerID, std::u16string wsPlayerName) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); @@ -891,7 +891,7 @@ void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband SEND_PACKET; } -void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i64PlayerID, LWOZONEID zoneID) +void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i64PlayerID, LWOZONEID zoneID) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index 9ba3ba1b..639d7b70 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -40,9 +40,9 @@ int main(int argc, char** argv) { //Create all the objects we need to run our service: Game::logger = SetupLogger(); if (!Game::logger) return 0; - Game::logger->Log("ChatServer", "Starting Chat server...\n"); - Game::logger->Log("ChatServer", "Version: %i.%i\n", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); - Game::logger->Log("ChatServer", "Compiled on: %s\n", __TIMESTAMP__); + Game::logger->Log("ChatServer", "Starting Chat server..."); + Game::logger->Log("ChatServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); + Game::logger->Log("ChatServer", "Compiled on: %s", __TIMESTAMP__); //Read our config: dConfig config("chatconfig.ini"); @@ -60,7 +60,7 @@ int main(int argc, char** argv) { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); } catch (sql::SQLException& ex) { - Game::logger->Log("ChatServer", "Got an error while connecting to the database: %s\n", ex.what()); + Game::logger->Log("ChatServer", "Got an error while connecting to the database: %s", ex.what()); Database::Destroy("ChatServer"); delete Game::server; delete Game::logger; @@ -172,11 +172,11 @@ dLogger * SetupLogger() { void HandlePacket(Packet* packet) { if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || packet->data[0] == ID_CONNECTION_LOST) { - Game::logger->Log("ChatServer", "A server has disconnected, erasing their connected players from the list.\n"); + Game::logger->Log("ChatServer", "A server has disconnected, erasing their connected players from the list."); } if (packet->data[0] == ID_NEW_INCOMING_CONNECTION) { - Game::logger->Log("ChatServer", "A server is connecting, awaiting user list.\n"); + Game::logger->Log("ChatServer", "A server is connecting, awaiting user list."); } if (packet->data[1] == CHAT_INTERNAL) { @@ -205,7 +205,7 @@ void HandlePacket(Packet* packet) { } default: - Game::logger->Log("ChatServer", "Unknown CHAT_INTERNAL id: %i\n", int(packet->data[3])); + Game::logger->Log("ChatServer", "Unknown CHAT_INTERNAL id: %i", int(packet->data[3])); } } @@ -216,7 +216,7 @@ void HandlePacket(Packet* packet) { break; case MSG_CHAT_GET_IGNORE_LIST: - Game::logger->Log("ChatServer", "Asked for ignore list, but is unimplemented right now.\n"); + Game::logger->Log("ChatServer", "Asked for ignore list, but is unimplemented right now."); break; case MSG_CHAT_TEAM_GET_STATUS: @@ -272,21 +272,21 @@ void HandlePacket(Packet* packet) { case MSG_CHAT_TEAM_SET_LOOT: ChatPacketHandler::HandleTeamLootOption(packet); break; - + default: - Game::logger->Log("ChatServer", "Unknown CHAT id: %i\n", int(packet->data[3])); + Game::logger->Log("ChatServer", "Unknown CHAT id: %i", int(packet->data[3])); } } if (packet->data[1] == WORLD) { switch (packet->data[3]) { case MSG_WORLD_CLIENT_ROUTE_PACKET: { - printf("routing packet from world\n"); + Game::logger->Log("ChatServer", "Routing packet from world"); break; } default: - Game::logger->Log("ChatServer", "Unknown World id: %i\n", int(packet->data[3])); + Game::logger->Log("ChatServer", "Unknown World id: %i", int(packet->data[3])); } } } diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index 1517153d..73a22ba9 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -28,7 +28,7 @@ void PlayerContainer::InsertPlayer(Packet* packet) { for (int i = 0; i < len; i++) { char character; inStream.Read(character); - data->playerName += character; + data->playerName += character; } inStream.Read(data->zoneID); @@ -38,7 +38,7 @@ void PlayerContainer::InsertPlayer(Packet* packet) { mNames[data->playerID] = GeneralUtils::ASCIIToUTF16(std::string(data->playerName.c_str())); mPlayers.insert(std::make_pair(data->playerID, data)); - Game::logger->Log("PlayerContainer", "Added user: %s (%llu), zone: %i\n", data->playerName.c_str(), data->playerID, data->zoneID.GetMapID()); + Game::logger->Log("PlayerContainer", "Added user: %s (%llu), zone: %i", data->playerName.c_str(), data->playerID, data->zoneID.GetMapID()); auto* insertLog = Database::CreatePreppedStmt("INSERT INTO activity_log (character_id, activity, time, map_id) VALUES (?, ?, ?, ?);"); @@ -73,7 +73,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { if (team != nullptr) { const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(player->playerName.c_str())); - + for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); @@ -84,7 +84,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { } } - Game::logger->Log("PlayerContainer", "Removed user: %llu\n", playerID); + Game::logger->Log("PlayerContainer", "Removed user: %llu", playerID); mPlayers.erase(playerID); auto* insertLog = Database::CreatePreppedStmt("INSERT INTO activity_log (character_id, activity, time, map_id) VALUES (?, ?, ?, ?);"); @@ -97,7 +97,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { insertLog->executeUpdate(); } -void PlayerContainer::MuteUpdate(Packet* packet) +void PlayerContainer::MuteUpdate(Packet* packet) { CINSTREAM; LWOOBJID playerID; @@ -110,7 +110,7 @@ void PlayerContainer::MuteUpdate(Packet* packet) if (player == nullptr) { - Game::logger->Log("PlayerContainer", "Failed to find user: %llu\n", playerID); + Game::logger->Log("PlayerContainer", "Failed to find user: %llu", playerID); return; } @@ -120,7 +120,7 @@ void PlayerContainer::MuteUpdate(Packet* packet) BroadcastMuteUpdate(playerID, expire); } -void PlayerContainer::CreateTeamServer(Packet* packet) +void PlayerContainer::CreateTeamServer(Packet* packet) { CINSTREAM; LWOOBJID playerID; @@ -143,7 +143,7 @@ void PlayerContainer::CreateTeamServer(Packet* packet) LWOZONEID zoneId; inStream.Read(zoneId); - + auto* team = CreateLocalTeam(members); if (team != nullptr) @@ -154,7 +154,7 @@ void PlayerContainer::CreateTeamServer(Packet* packet) UpdateTeamsOnWorld(team, false); } -void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) +void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_MUTE_UPDATE); @@ -165,7 +165,7 @@ void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); } -TeamData* PlayerContainer::CreateLocalTeam(std::vector members) +TeamData* PlayerContainer::CreateLocalTeam(std::vector members) { if (members.empty()) { @@ -200,14 +200,14 @@ TeamData* PlayerContainer::CreateLocalTeam(std::vector members) return newTeam; } -TeamData* PlayerContainer::CreateTeam(LWOOBJID leader, bool local) +TeamData* PlayerContainer::CreateTeam(LWOOBJID leader, bool local) { auto* team = new TeamData(); - + team->teamID = ++mTeamIDCounter; team->leaderID = leader; team->local = local; - + mTeams.push_back(team); AddMember(team, leader); @@ -215,7 +215,7 @@ TeamData* PlayerContainer::CreateTeam(LWOOBJID leader, bool local) return team; } -TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) +TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) { for (auto* team : mTeams) { @@ -223,11 +223,11 @@ TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) return team; } - + return nullptr; } -void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) +void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) { const auto index = std::find(team->memberIDs.begin(), team->memberIDs.end(), playerID); @@ -263,7 +263,7 @@ void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) if (otherMember == member) continue; const auto otherMemberName = GetName(memberId); - + ChatPacketHandler::SendTeamAddPlayer(member, false, team->local, false, memberId, otherMemberName, otherMember != nullptr ? otherMember->zoneID : LWOZONEID(0, 0, 0)); if (otherMember != nullptr) @@ -273,14 +273,14 @@ void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) } } -void PlayerContainer::RemoveMember(TeamData* team, LWOOBJID playerID, bool disband, bool kicked, bool leaving, bool silent) +void PlayerContainer::RemoveMember(TeamData* team, LWOOBJID playerID, bool disband, bool kicked, bool leaving, bool silent) { const auto index = std::find(team->memberIDs.begin(), team->memberIDs.end(), playerID); if (index == team->memberIDs.end()) return; auto* member = GetPlayerData(playerID); - + if (member != nullptr && !silent) { ChatPacketHandler::SendTeamSetLeader(member, LWOOBJID_EMPTY); @@ -319,7 +319,7 @@ void PlayerContainer::RemoveMember(TeamData* team, LWOOBJID playerID, bool disba } } -void PlayerContainer::PromoteMember(TeamData* team, LWOOBJID newLeader) +void PlayerContainer::PromoteMember(TeamData* team, LWOOBJID newLeader) { team->leaderID = newLeader; @@ -333,7 +333,7 @@ void PlayerContainer::PromoteMember(TeamData* team, LWOOBJID newLeader) } } -void PlayerContainer::DisbandTeam(TeamData* team) +void PlayerContainer::DisbandTeam(TeamData* team) { const auto index = std::find(mTeams.begin(), mTeams.end(), team); @@ -350,7 +350,7 @@ void PlayerContainer::DisbandTeam(TeamData* team) ChatPacketHandler::SendTeamSetLeader(otherMember, LWOOBJID_EMPTY); ChatPacketHandler::SendTeamRemovePlayer(otherMember, true, false, false, team->local, team->leaderID, otherMember->playerID, memberName); } - + UpdateTeamsOnWorld(team, true); mTeams.erase(index); @@ -358,7 +358,7 @@ void PlayerContainer::DisbandTeam(TeamData* team) delete team; } -void PlayerContainer::TeamStatusUpdate(TeamData* team) +void PlayerContainer::TeamStatusUpdate(TeamData* team) { const auto index = std::find(mTeams.begin(), mTeams.end(), team); @@ -385,7 +385,7 @@ void PlayerContainer::TeamStatusUpdate(TeamData* team) UpdateTeamsOnWorld(team, false); } -void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) +void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_TEAM_UPDATE); @@ -406,7 +406,7 @@ void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); } -std::u16string PlayerContainer::GetName(LWOOBJID playerID) +std::u16string PlayerContainer::GetName(LWOOBJID playerID) { const auto& pair = mNames.find(playerID); @@ -415,7 +415,7 @@ std::u16string PlayerContainer::GetName(LWOOBJID playerID) return pair->second; } -LWOOBJID PlayerContainer::GetId(const std::u16string& playerName) +LWOOBJID PlayerContainer::GetId(const std::u16string& playerName) { for (const auto& pair : mNames) { @@ -424,11 +424,11 @@ LWOOBJID PlayerContainer::GetId(const std::u16string& playerName) return pair.first; } } - + return LWOOBJID_EMPTY; } -bool PlayerContainer::GetIsMuted(PlayerData* data) +bool PlayerContainer::GetIsMuted(PlayerData* data) { return data->muteExpire == 1 || data->muteExpire > time(NULL); } diff --git a/dCommon/dLogger.cpp b/dCommon/dLogger.cpp index 825c10cb..532a0cee 100644 --- a/dCommon/dLogger.cpp +++ b/dCommon/dLogger.cpp @@ -44,14 +44,14 @@ void dLogger::vLog(const char* format, va_list args) { strftime(timeStr, sizeof(timeStr), "%d-%m-%y %H:%M:%S", time); char message[2048]; vsprintf(message, format, args); - + if (m_logToConsole) { fputs("[", stdout); fputs(timeStr, stdout); fputs("] ", stdout); fputs(message, stdout); } - + if (fp != nullptr) { fputs("[", fp); fputs(timeStr, fp); @@ -76,7 +76,7 @@ void dLogger::LogBasic(const std::string & message) { void dLogger::Log(const char * className, const char * format, ...) { va_list args; - std::string log = "[" + std::string(className) + "] " + std::string(format); + std::string log = "[" + std::string(className) + "] " + std::string(format) + "\n"; va_start(args, format); vLog(log.c_str(), args); va_end(args); diff --git a/dDatabase/Database.cpp b/dDatabase/Database.cpp index 26a45359..7ab7b752 100644 --- a/dDatabase/Database.cpp +++ b/dDatabase/Database.cpp @@ -41,10 +41,10 @@ void Database::Connect() { void Database::Destroy(std::string source, bool log) { if (!con) return; - + if (log) { - if (source != "") Game::logger->Log("Database", "Destroying MySQL connection from %s!\n", source.c_str()); - else Game::logger->Log("Database", "Destroying MySQL connection!\n"); + if (source != "") Game::logger->Log("Database", "Destroying MySQL connection from %s!", source.c_str()); + else Game::logger->Log("Database", "Destroying MySQL connection!"); } con->close(); @@ -63,7 +63,7 @@ sql::PreparedStatement* Database::CreatePreppedStmt(const std::string& query) { if (!con) { Connect(); - Game::logger->Log("Database", "Trying to reconnect to MySQL\n"); + Game::logger->Log("Database", "Trying to reconnect to MySQL"); } if (!con->isValid() || con->isClosed()) @@ -73,9 +73,9 @@ sql::PreparedStatement* Database::CreatePreppedStmt(const std::string& query) { con = nullptr; Connect(); - Game::logger->Log("Database", "Trying to reconnect to MySQL from invalid or closed connection\n"); + Game::logger->Log("Database", "Trying to reconnect to MySQL from invalid or closed connection"); } - + auto* stmt = con->prepareStatement(str); return stmt; diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index a058b85e..186368fd 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -31,7 +31,7 @@ void MigrationRunner::RunMigrations() { delete stmt; if (doExit) continue; - Game::logger->Log("MigrationRunner", "Running migration: " + migration.name + "\n"); + Game::logger->Log("MigrationRunner", "Running migration: " + migration.name + ""); finalSQL.append(migration.data); finalSQL.append('\n'); @@ -49,7 +49,7 @@ void MigrationRunner::RunMigrations() { delete simpleStatement; } catch (sql::SQLException e) { - Game::logger->Log("MigrationRunner", std::string("Encountered error running migration: ") + e.what() + "\n"); + Game::logger->Log("MigrationRunner", std::string("Encountered error running migration: ") + e.what() + ""); } } } @@ -60,7 +60,7 @@ Migration MigrationRunner::LoadMigration(std::string path) { if (file.is_open()) { std::hash hash; - + std::string line; std::string total = ""; @@ -73,6 +73,6 @@ Migration MigrationRunner::LoadMigration(std::string path) { migration.name = path; migration.data = total; } - + return migration; } diff --git a/dDatabase/Tables/CDSkillBehaviorTable.cpp b/dDatabase/Tables/CDSkillBehaviorTable.cpp index ad79997d..88124161 100644 --- a/dDatabase/Tables/CDSkillBehaviorTable.cpp +++ b/dDatabase/Tables/CDSkillBehaviorTable.cpp @@ -13,9 +13,9 @@ CDSkillBehaviorTable::CDSkillBehaviorTable(void) { tableSize.nextRow(); } - + tableSize.finalize(); - + // Reserve the size //this->entries.reserve(size); @@ -68,7 +68,7 @@ std::vector CDSkillBehaviorTable::Query(std::function data; //So MSVC shuts up return data; } diff --git a/dGame/Character.cpp b/dGame/Character.cpp index ce61ae70..d92f8345 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -25,9 +25,9 @@ Character::Character(uint32_t id, User* parentUser) { ); stmt->setInt64(1, id); - + sql::ResultSet* res = stmt->executeQuery(); - + while (res->next()) { m_Name = res->getString(1).c_str(); m_UnapprovedName = res->getString(2).c_str(); @@ -35,25 +35,25 @@ Character::Character(uint32_t id, User* parentUser) { m_PropertyCloneID = res->getUInt(4); m_PermissionMap = static_cast(res->getUInt64(5)); } - + delete res; delete stmt; - + //Load the xmlData now: sql::PreparedStatement* xmlStmt = Database::CreatePreppedStmt( "SELECT xml_data FROM charxml WHERE id=? LIMIT 1;" ); xmlStmt->setInt64(1, id); - + sql::ResultSet* xmlRes = xmlStmt->executeQuery(); while (xmlRes->next()) { m_XMLData = xmlRes->getString(1).c_str(); } - + delete xmlRes; delete xmlStmt; - + m_ZoneID = 0; //TEMP! Set back to 0 when done. This is so we can see loading screen progress for testing. m_ZoneInstanceID = 0; //These values don't really matter, these are only used on the char select screen and seem unused. m_ZoneCloneID = 0; @@ -62,12 +62,12 @@ Character::Character(uint32_t id, User* parentUser) { //Quickly and dirtly parse the xmlData to get the info we need: DoQuickXMLDataParse(); - + //Set our objectID: m_ObjectID = m_ID; m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); - + m_ParentUser = parentUser; m_OurEntity = nullptr; m_BuildMode = false; @@ -78,16 +78,16 @@ Character::~Character() { m_Doc = nullptr; } -void Character::UpdateFromDatabase() +void Character::UpdateFromDatabase() { sql::PreparedStatement* stmt = Database::CreatePreppedStmt( "SELECT name, pending_name, needs_rename, prop_clone_id, permission_map FROM charinfo WHERE id=? LIMIT 1;" ); stmt->setInt64(1, m_ID); - + sql::ResultSet* res = stmt->executeQuery(); - + while (res->next()) { m_Name = res->getString(1).c_str(); m_UnapprovedName = res->getString(2).c_str(); @@ -95,24 +95,24 @@ void Character::UpdateFromDatabase() m_PropertyCloneID = res->getUInt(4); m_PermissionMap = static_cast(res->getUInt64(5)); } - + delete res; delete stmt; - + //Load the xmlData now: sql::PreparedStatement* xmlStmt = Database::CreatePreppedStmt( "SELECT xml_data FROM charxml WHERE id=? LIMIT 1;" ); xmlStmt->setInt64(1, m_ID); - + sql::ResultSet* xmlRes = xmlStmt->executeQuery(); while (xmlRes->next()) { m_XMLData = xmlRes->getString(1).c_str(); } - + delete xmlRes; delete xmlStmt; - + m_ZoneID = 0; //TEMP! Set back to 0 when done. This is so we can see loading screen progress for testing. m_ZoneInstanceID = 0; //These values don't really matter, these are only used on the char select screen and seem unused. m_ZoneCloneID = 0; @@ -122,67 +122,67 @@ void Character::UpdateFromDatabase() //Quickly and dirtly parse the xmlData to get the info we need: DoQuickXMLDataParse(); - + //Set our objectID: m_ObjectID = m_ID; m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); - + m_OurEntity = nullptr; m_BuildMode = false; } void Character::DoQuickXMLDataParse() { if (m_XMLData.size() == 0) return; - + delete m_Doc; m_Doc = new tinyxml2::XMLDocument(); if (!m_Doc) return; - + if (m_Doc->Parse(m_XMLData.c_str(), m_XMLData.size()) == 0) { - Game::logger->Log("Character", "Loaded xmlData for character %s (%i)!\n", m_Name.c_str(), m_ID); + Game::logger->Log("Character", "Loaded xmlData for character %s (%i)!", m_Name.c_str(), m_ID); } else { - Game::logger->Log("Character", "Failed to load xmlData!\n"); + Game::logger->Log("Character", "Failed to load xmlData!"); //Server::rakServer->CloseConnection(m_ParentUser->GetSystemAddress(), true); return; } - + tinyxml2::XMLElement* mf = m_Doc->FirstChildElement("obj")->FirstChildElement("mf"); if (!mf) { - Game::logger->Log("Character", "Failed to find mf tag!\n"); + Game::logger->Log("Character", "Failed to find mf tag!"); return; } - + mf->QueryAttribute("hc", &m_HairColor); mf->QueryAttribute("hs", &m_HairStyle); - + mf->QueryAttribute("t", &m_ShirtColor); mf->QueryAttribute("l", &m_PantsColor); - + mf->QueryAttribute("lh", &m_LeftHand); mf->QueryAttribute("rh", &m_RightHand); - + mf->QueryAttribute("es", &m_Eyebrows); mf->QueryAttribute("ess", &m_Eyes); mf->QueryAttribute("ms", &m_Mouth); - + tinyxml2::XMLElement* inv = m_Doc->FirstChildElement("obj")->FirstChildElement("inv"); if (!inv) { - Game::logger->Log("Character", "Char has no inv!\n"); + Game::logger->Log("Character", "Char has no inv!"); return; } - + tinyxml2::XMLElement* bag = inv->FirstChildElement("items")->FirstChildElement("in"); if (!bag) { - Game::logger->Log("Character", "Couldn't find bag0!\n"); + Game::logger->Log("Character", "Couldn't find bag0!"); return; } - + while (bag != nullptr) { auto* sib = bag->FirstChildElement(); - + while (sib != nullptr) { bool eq = false; sib->QueryAttribute("eq", &eq); @@ -198,8 +198,8 @@ void Character::DoQuickXMLDataParse() { bag = bag->NextSiblingElement(); } - - + + tinyxml2::XMLElement* character = m_Doc->FirstChildElement("obj")->FirstChildElement("char"); if (character) { character->QueryAttribute("cc", &m_Coins); @@ -261,7 +261,7 @@ void Character::DoQuickXMLDataParse() { character->QueryAttribute("lzrz", &m_OriginalRotation.z); character->QueryAttribute("lzrw", &m_OriginalRotation.w); } - + auto* flags = m_Doc->FirstChildElement("obj")->FirstChildElement("flag"); if (flags) { auto* currentChild = flags->FirstChildElement(); @@ -269,10 +269,10 @@ void Character::DoQuickXMLDataParse() { uint32_t index = 0; uint64_t value = 0; const auto* temp = currentChild->Attribute("v"); - + index = std::stoul(currentChild->Attribute("id")); value = std::stoull(temp); - + m_PlayerFlags.insert(std::make_pair(index, value)); currentChild = currentChild->NextSiblingElement(); } @@ -296,10 +296,10 @@ void Character::SetBuildMode(bool buildMode) void Character::SaveXMLToDatabase() { if (!m_Doc) return; - + //For metrics, we'll record the time it took to save: auto start = std::chrono::system_clock::now(); - + tinyxml2::XMLElement* character = m_Doc->FirstChildElement("obj")->FirstChildElement("char"); if (character) { character->SetAttribute("gm", m_GMLevel); @@ -323,7 +323,7 @@ void Character::SaveXMLToDatabase() { auto emotes = character->FirstChildElement("ue"); if (!emotes) emotes = m_Doc->NewElement("ue"); - + emotes->DeleteChildren(); for (int emoteID : m_UnlockedEmotes) { auto emote = m_Doc->NewElement("e"); @@ -334,53 +334,53 @@ void Character::SaveXMLToDatabase() { character->LinkEndChild(emotes); } - + //Export our flags: auto* flags = m_Doc->FirstChildElement("obj")->FirstChildElement("flag"); if (!flags) { flags = m_Doc->NewElement("flag"); //Create a flags tag if we don't have one m_Doc->FirstChildElement("obj")->LinkEndChild(flags); //Link it to the obj tag so we can find next time } - + flags->DeleteChildren(); //Clear it if we have anything, so that we can fill it up again without dupes for (std::pair flag : m_PlayerFlags) { auto* f = m_Doc->NewElement("f"); f->SetAttribute("id", flag.first); - + //Because of the joy that is tinyxml2, it doesn't offer a function to set a uint64 as an attribute. //Only signed 64-bits ints would work. std::string v = std::to_string(flag.second); f->SetAttribute("v", v.c_str()); - + flags->LinkEndChild(f); } SaveXmlRespawnCheckpoints(); - //Call upon the entity to update our xmlDoc: + //Call upon the entity to update our xmlDoc: if (!m_OurEntity) { - Game::logger->Log("Character", "We didn't have an entity set while saving! CHARACTER WILL NOT BE SAVED!\n"); + Game::logger->Log("Character", "We didn't have an entity set while saving! CHARACTER WILL NOT BE SAVED!"); return; } - + m_OurEntity->UpdateXMLDoc(m_Doc); - + //Dump our xml into m_XMLData: auto* printer = new tinyxml2::XMLPrinter(0, true, 0); m_Doc->Print(printer); m_XMLData = printer->CStr(); - + //Finally, save to db: sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charxml SET xml_data=? WHERE id=?"); stmt->setString(1, m_XMLData.c_str()); stmt->setUInt(2, m_ID); stmt->execute(); delete stmt; - + //For metrics, log the time it took to save: auto end = std::chrono::system_clock::now(); std::chrono::duration elapsed = end - start; - Game::logger->Log("Character", "Saved character to Database in: %fs\n", elapsed.count()); + Game::logger->Log("Character", "Saved character to Database in: %fs", elapsed.count()); delete printer; } @@ -404,7 +404,7 @@ void Character::SetPlayerFlag(const uint32_t flagId, const bool value) { } } } - + // Calculate the index first auto flagIndex = uint32_t(std::floor(flagId / 64)); @@ -425,9 +425,9 @@ void Character::SetPlayerFlag(const uint32_t flagId, const bool value) { if (value) { // Otherwise, insert the value uint64_t flagValue = 0; - + flagValue |= shiftedValue; - + m_PlayerFlags.insert(std::make_pair(flagIndex, flagValue)); } } @@ -458,7 +458,7 @@ void Character::SetRetroactiveFlags() { } } -void Character::SaveXmlRespawnCheckpoints() +void Character::SaveXmlRespawnCheckpoints() { //Export our respawn points: auto* points = m_Doc->FirstChildElement("obj")->FirstChildElement("res"); @@ -466,21 +466,21 @@ void Character::SaveXmlRespawnCheckpoints() points = m_Doc->NewElement("res"); m_Doc->FirstChildElement("obj")->LinkEndChild(points); } - + points->DeleteChildren(); for (const auto& point : m_WorldRespawnCheckpoints) { auto* r = m_Doc->NewElement("r"); r->SetAttribute("w", point.first); - + r->SetAttribute("x", point.second.x); r->SetAttribute("y", point.second.y); r->SetAttribute("z", point.second.z); - + points->LinkEndChild(r); } } -void Character::LoadXmlRespawnCheckpoints() +void Character::LoadXmlRespawnCheckpoints() { m_WorldRespawnCheckpoints.clear(); @@ -504,10 +504,10 @@ void Character::LoadXmlRespawnCheckpoints() m_WorldRespawnCheckpoints[map] = point; } - + } -void Character::OnZoneLoad() +void Character::OnZoneLoad() { if (m_OurEntity == nullptr) { return; @@ -530,8 +530,8 @@ void Character::OnZoneLoad() } /** - * Restrict old character to 1 million coins - */ + * Restrict old character to 1 million coins + */ if (HasPermission(PermissionMap::Old)) { if (GetCoins() > 1000000) { SetCoins(1000000, eLootSourceType::LOOT_SOURCE_NONE); @@ -560,7 +560,7 @@ bool Character::HasPermission(PermissionMap permission) const return (static_cast(m_PermissionMap) & static_cast(permission)) != 0; } -void Character::SetRespawnPoint(LWOMAPID map, const NiPoint3& point) +void Character::SetRespawnPoint(LWOMAPID map, const NiPoint3& point) { m_WorldRespawnCheckpoints[map] = point; } @@ -604,7 +604,7 @@ void Character::SendMuteNotice() const // Format: Mo, 15.06.2009 20:20:00 std::strftime(buffer, 32, "%a, %d.%m.%Y %H:%M:%S", ptm); } - + const auto timeStr = GeneralUtils::ASCIIToUTF16(std::string(buffer)); ChatPackets::SendSystemMessage(GetEntity()->GetSystemAddress(), u"You are muted until " + timeStr); diff --git a/dGame/Player.cpp b/dGame/Player.cpp index 350ddca5..56ae5a70 100644 --- a/dGame/Player.cpp +++ b/dGame/Player.cpp @@ -26,7 +26,7 @@ Player::Player(const LWOOBJID& objectID, const EntityInfo info, User* user, Enti m_SystemAddress = m_ParentUser->GetSystemAddress(); m_DroppedLoot = {}; m_DroppedCoins = 0; - + m_GhostReferencePoint = NiPoint3::ZERO; m_GhostOverridePoint = NiPoint3::ZERO; m_GhostOverride = false; @@ -121,7 +121,7 @@ void Player::SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId) }); } -void Player::AddLimboConstruction(LWOOBJID objectId) +void Player::AddLimboConstruction(LWOOBJID objectId) { const auto& iter = std::find(m_LimboConstructions.begin(), m_LimboConstructions.end(), objectId); @@ -133,7 +133,7 @@ void Player::AddLimboConstruction(LWOOBJID objectId) m_LimboConstructions.push_back(objectId); } -void Player::RemoveLimboConstruction(LWOOBJID objectId) +void Player::RemoveLimboConstruction(LWOOBJID objectId) { const auto& iter = std::find(m_LimboConstructions.begin(), m_LimboConstructions.end(), objectId); @@ -158,7 +158,7 @@ void Player::ConstructLimboEntities() EntityManager::Instance()->ConstructEntity(entity, m_SystemAddress); } - + m_LimboConstructions.clear(); } @@ -177,12 +177,12 @@ const NiPoint3& Player::GetOriginGhostReferencePoint() const return m_GhostReferencePoint; } -void Player::SetGhostReferencePoint(const NiPoint3& value) +void Player::SetGhostReferencePoint(const NiPoint3& value) { m_GhostReferencePoint = value; } -void Player::SetGhostOverridePoint(const NiPoint3& value) +void Player::SetGhostOverridePoint(const NiPoint3& value) { m_GhostOverridePoint = value; } @@ -192,7 +192,7 @@ const NiPoint3& Player::GetGhostOverridePoint() const return m_GhostOverridePoint; } -void Player::SetGhostOverride(bool value) +void Player::SetGhostOverride(bool value) { m_GhostOverride = value; } @@ -202,7 +202,7 @@ bool Player::GetGhostOverride() const return m_GhostOverride; } -void Player::ObserveEntity(int32_t id) +void Player::ObserveEntity(int32_t id) { for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { @@ -226,7 +226,7 @@ void Player::ObserveEntity(int32_t id) m_ObservedEntities[index] = id; } -bool Player::IsObserved(int32_t id) +bool Player::IsObserved(int32_t id) { for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { @@ -239,7 +239,7 @@ bool Player::IsObserved(int32_t id) return false; } -void Player::GhostEntity(int32_t id) +void Player::GhostEntity(int32_t id) { for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { @@ -257,7 +257,7 @@ Player* Player::GetPlayer(const SystemAddress& sysAddr) return static_cast(entity); } -Player* Player::GetPlayer(const std::string& name) +Player* Player::GetPlayer(const std::string& name) { const auto characters = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER); @@ -274,7 +274,7 @@ Player* Player::GetPlayer(const std::string& name) return nullptr; } -Player* Player::GetPlayer(LWOOBJID playerID) +Player* Player::GetPlayer(LWOOBJID playerID) { for (auto* player : m_Players) { @@ -283,11 +283,11 @@ Player* Player::GetPlayer(LWOOBJID playerID) return player; } } - + return nullptr; } -const std::vector& Player::GetAllPlayers() +const std::vector& Player::GetAllPlayers() { return m_Players; } @@ -302,7 +302,7 @@ void Player::SetDroppedCoins(uint64_t value) { Player::~Player() { - Game::logger->Log("Player", "Deleted player\n"); + Game::logger->Log("Player", "Deleted player"); for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { diff --git a/dGame/TradingManager.cpp b/dGame/TradingManager.cpp index 04a0501d..1d23126a 100644 --- a/dGame/TradingManager.cpp +++ b/dGame/TradingManager.cpp @@ -12,16 +12,16 @@ TradingManager* TradingManager::m_Address = nullptr; -Trade::Trade(LWOOBJID tradeId, LWOOBJID participantA, LWOOBJID participantB) +Trade::Trade(LWOOBJID tradeId, LWOOBJID participantA, LWOOBJID participantB) { m_TradeId = tradeId; m_ParticipantA = participantA; m_ParticipantB = participantB; } -Trade::~Trade() +Trade::~Trade() { - + } LWOOBJID Trade::GetTradeId() const @@ -54,7 +54,7 @@ Entity* Trade::GetParticipantBEntity() const return EntityManager::Instance()->GetEntity(m_ParticipantB); } -void Trade::SetCoins(LWOOBJID participant, uint64_t coins) +void Trade::SetCoins(LWOOBJID participant, uint64_t coins) { if (participant == m_ParticipantA) { @@ -66,7 +66,7 @@ void Trade::SetCoins(LWOOBJID participant, uint64_t coins) } } -void Trade::SetItems(LWOOBJID participant, std::vector items) +void Trade::SetItems(LWOOBJID participant, std::vector items) { if (participant == m_ParticipantA) { @@ -78,13 +78,13 @@ void Trade::SetItems(LWOOBJID participant, std::vector items) } } -void Trade::SetAccepted(LWOOBJID participant, bool value) +void Trade::SetAccepted(LWOOBJID participant, bool value) { if (participant == m_ParticipantA) { m_AcceptedA = !value; - Game::logger->Log("Trade", "Accepted from A (%d), B: (%d)\n", value, m_AcceptedB); + Game::logger->Log("Trade", "Accepted from A (%d), B: (%d)", value, m_AcceptedB); auto* entityB = GetParticipantBEntity(); @@ -97,7 +97,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) { m_AcceptedB = !value; - Game::logger->Log("Trade", "Accepted from B (%d), A: (%d)\n", value, m_AcceptedA); + Game::logger->Log("Trade", "Accepted from B (%d), A: (%d)", value, m_AcceptedA); auto* entityA = GetParticipantAEntity(); @@ -106,7 +106,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) GameMessages::SendServerTradeAccept(m_ParticipantA, value, entityA->GetSystemAddress()); } } - + if (m_AcceptedA && m_AcceptedB) { auto* entityB = GetParticipantBEntity(); @@ -119,7 +119,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) { return; } - + auto* entityA = GetParticipantAEntity(); if (entityA != nullptr) @@ -130,16 +130,16 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) { return; } - + Complete(); } } -void Trade::Complete() +void Trade::Complete() { auto* entityA = GetParticipantAEntity(); auto* entityB = GetParticipantBEntity(); - + if (entityA == nullptr || entityB == nullptr) return; auto* inventoryA = entityA->GetComponent(); @@ -160,7 +160,7 @@ void Trade::Complete() missionsA->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); } - + for (const auto& tradeItem : m_ItemsB) { inventoryB->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true); @@ -184,26 +184,26 @@ void Trade::Complete() characterB->SaveXMLToDatabase(); } -void Trade::Cancel() +void Trade::Cancel() { auto* entityA = GetParticipantAEntity(); auto* entityB = GetParticipantBEntity(); - + if (entityA == nullptr || entityB == nullptr) return; GameMessages::SendServerTradeCancel(entityA->GetObjectID(), entityA->GetSystemAddress()); GameMessages::SendServerTradeCancel(entityB->GetObjectID(), entityB->GetSystemAddress()); } -void Trade::SendUpdateToOther(LWOOBJID participant) +void Trade::SendUpdateToOther(LWOOBJID participant) { Entity* other = nullptr; Entity* self = nullptr; uint64_t coins; std::vector itemIds; - Game::logger->Log("Trade", "Attempting to send trade update\n"); - + Game::logger->Log("Trade", "Attempting to send trade update"); + if (participant == m_ParticipantA) { other = GetParticipantBEntity(); @@ -222,11 +222,11 @@ void Trade::SendUpdateToOther(LWOOBJID participant) { return; } - + if (other == nullptr || self == nullptr) return; std::vector items {}; - + auto* inventoryComponent = self->GetComponent(); if (inventoryComponent == nullptr) return; @@ -242,8 +242,8 @@ void Trade::SendUpdateToOther(LWOOBJID participant) items.push_back(tradeItem); } - Game::logger->Log("Trade", "Sending trade update\n"); - + Game::logger->Log("Trade", "Sending trade update"); + GameMessages::SendServerTradeUpdate(other->GetObjectID(), coins, items, other->GetSystemAddress()); } @@ -257,7 +257,7 @@ TradingManager::~TradingManager() { delete pair.second; } - + trades.clear(); } @@ -279,30 +279,30 @@ Trade* TradingManager::GetPlayerTrade(LWOOBJID playerId) const return pair.second; } } - + return nullptr; } -void TradingManager::CancelTrade(LWOOBJID tradeId) +void TradingManager::CancelTrade(LWOOBJID tradeId) { auto* trade = GetTrade(tradeId); if (trade == nullptr) return; - + delete trade; trades.erase(tradeId); } -Trade* TradingManager::NewTrade(LWOOBJID participantA, LWOOBJID participantB) +Trade* TradingManager::NewTrade(LWOOBJID participantA, LWOOBJID participantB) { const LWOOBJID tradeId = ObjectIDManager::Instance()->GenerateObjectID(); auto* trade = new Trade(tradeId, participantA, participantB); - + trades[tradeId] = trade; - Game::logger->Log("TradingManager", "Created new trade between (%llu) <-> (%llu)\n", participantA, participantB); + Game::logger->Log("TradingManager", "Created new trade between (%llu) <-> (%llu)", participantA, participantB); return trade; } diff --git a/dGame/User.cpp b/dGame/User.cpp index 98a37954..33329199 100644 --- a/dGame/User.cpp +++ b/dGame/User.cpp @@ -20,40 +20,40 @@ User::User(const SystemAddress& sysAddr, const std::string& username, const std: m_LoggedInCharID = 0; m_IsBestFriendMap = std::unordered_map(); - + //HACK HACK HACK //This needs to be re-enabled / updated whenever the mute stuff is moved to another table. //This was only done because otherwise the website's account page dies and the website is waiting on a migration to wordpress. - + //sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id, gmlevel, mute_expire FROM accounts WHERE name=? LIMIT 1;"); sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id, gm_level FROM accounts WHERE name=? LIMIT 1;"); stmt->setString(1, username.c_str()); - + sql::ResultSet* res = stmt->executeQuery(); while (res->next()) { m_AccountID = res->getUInt(1); m_MaxGMLevel = res->getInt(2); m_MuteExpire = 0; //res->getUInt64(3); } - + delete res; delete stmt; - + //If we're loading a zone, we'll load the last used (aka current) character: if (Game::server->GetZoneID() != 0) { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE account_id=? ORDER BY last_login DESC LIMIT 1;"); stmt->setUInt(1, m_AccountID); - + sql::ResultSet* res = stmt->executeQuery(); if (res->rowsCount() > 0) { while (res->next()) { LWOOBJID objID = res->getUInt64(1); Character* character = new Character(uint32_t(objID), this); m_Characters.push_back(character); - Game::logger->Log("User", "Loaded %llu as it is the last used char\n", objID); + Game::logger->Log("User", "Loaded %llu as it is the last used char", objID); } } - + delete res; delete stmt; } @@ -92,7 +92,7 @@ User& User::operator= ( const User& other ) { bool User::operator== ( const User& other ) const { if (m_Username == other.m_Username || m_SessionKey == other.m_SessionKey || m_SystemAddress == other.m_SystemAddress) return true; - + return false; } @@ -104,7 +104,7 @@ Character * User::GetLastUsedChar() { for (size_t i = 0; i < m_Characters.size(); ++i) { if (m_Characters[i]->GetLastLogin() > toReturn->GetLastLogin()) toReturn = m_Characters[i]; } - + return toReturn; } } @@ -119,7 +119,7 @@ time_t User::GetMuteExpire() const return m_MuteExpire; } -void User::SetMuteExpire(time_t value) +void User::SetMuteExpire(time_t value) { m_MuteExpire = value; } @@ -128,7 +128,7 @@ void User::UserOutOfSync() { m_AmountOfTimesOutOfSync++; if (m_AmountOfTimesOutOfSync > m_MaxDesyncAllowed) { //YEET - Game::logger->Log("User", "User %s was out of sync %i times out of %i, disconnecting for suspected speedhacking.\n", m_Username.c_str(), m_AmountOfTimesOutOfSync, m_MaxDesyncAllowed); + Game::logger->Log("User", "User %s was out of sync %i times out of %i, disconnecting for suspected speedhacking.", m_Username.c_str(), m_AmountOfTimesOutOfSync, m_MaxDesyncAllowed); Game::server->Disconnect(this->m_SystemAddress, SERVER_DISCON_KICK); } } diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index 3956942a..5a320b51 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -62,7 +62,7 @@ void UserManager::Initialize() { fnFile.close(); mnFile.close(); lnFile.close(); - + //Load our pre-approved names: std::fstream chatList("./res/chatplus_en_us.txt", std::ios::in); while (std::getline(chatList, line, '\n')) { @@ -72,7 +72,7 @@ void UserManager::Initialize() { } UserManager::~UserManager() { - + } User* UserManager::CreateUser ( const SystemAddress& sysAddr, const std::string& username, const std::string& sessionKey ) { @@ -114,20 +114,20 @@ bool UserManager::DeleteUser ( const SystemAddress& sysAddr ) { if (std::count(m_UsersToDelete.begin(), m_UsersToDelete.end(), it->second)) return false; m_UsersToDelete.push_back(it->second); - + m_Users.erase(it); return true; } - + return false; } -void UserManager::DeletePendingRemovals() +void UserManager::DeletePendingRemovals() { for (auto* user : m_UsersToDelete) { - Game::logger->Log("UserManager", "Deleted user %i\n", user->GetAccountID()); + Game::logger->Log("UserManager", "Deleted user %i", user->GetAccountID()); delete user; } @@ -140,10 +140,10 @@ bool UserManager::IsNameAvailable ( const std::string& requestedName ) { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE name=? OR pending_name=? LIMIT 1;"); stmt->setString(1, requestedName.c_str()); stmt->setString(2, requestedName.c_str()); - + sql::ResultSet* res = stmt->executeQuery(); if (res->rowsCount() == 0) toReturn = true; - + delete stmt; delete res; return toReturn; @@ -158,33 +158,33 @@ bool UserManager::IsNamePreapproved ( const std::string& requestedName ) { for (std::string& s : m_PreapprovedNames) { if (s == requestedName) return true; } - + for (std::string& s : m_FirstNames) { if (s == requestedName) return true; } - + for (std::string& s : m_MiddleNames) { if (s == requestedName) return true; } - + for (std::string& s : m_LastNames) { if (s == requestedName) return true; } - + return false; } void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { User* u = GetUser(sysAddr); if (!u) return; - + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE account_id=? ORDER BY last_login DESC LIMIT 4;"); stmt->setUInt(1, u->GetAccountID()); - + sql::ResultSet* res = stmt->executeQuery(); if (res->rowsCount() > 0) { std::vector& chars = u->GetCharacters(); - + for (size_t i = 0; i < chars.size(); ++i) { if (chars[i]->GetEntity() == nullptr) // We don't have entity data to save @@ -209,9 +209,9 @@ void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { delete chars[i]; } - + chars.clear(); - + while (res->next()) { LWOOBJID objID = res->getUInt64(1); Character* character = new Character(uint32_t(objID), u); @@ -221,14 +221,14 @@ void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { delete res; delete stmt; - + WorldPackets::SendCharacterList(sysAddr, u); } void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) { User* u = GetUser(sysAddr); if (!u) return; - + std::string name = PacketUtils::ReadString(8, packet, true); uint32_t firstNameIndex = PacketUtils::ReadPacketU32(74, packet); @@ -246,29 +246,29 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) uint32_t eyebrows = PacketUtils::ReadPacketU32(123, packet); uint32_t eyes = PacketUtils::ReadPacketU32(127, packet); uint32_t mouth = PacketUtils::ReadPacketU32(131, packet); - + LOT shirtLOT = FindCharShirtID(shirtColor, shirtStyle); LOT pantsLOT = FindCharPantsID(pantsColor); - + if (name != "" && !UserManager::IsNameAvailable(name)) { - Game::logger->Log("UserManager", "AccountID: %i chose unavailable name: %s\n", u->GetAccountID(), name.c_str()); + Game::logger->Log("UserManager", "AccountID: %i chose unavailable name: %s", u->GetAccountID(), name.c_str()); WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_CUSTOM_NAME_IN_USE); return; } - + if (!IsNameAvailable(predefinedName)) { - Game::logger->Log("UserManager", "AccountID: %i chose unavailable predefined name: %s\n", u->GetAccountID(), predefinedName.c_str()); + Game::logger->Log("UserManager", "AccountID: %i chose unavailable predefined name: %s", u->GetAccountID(), predefinedName.c_str()); WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_PREDEFINED_NAME_IN_USE); return; } - + if (name == "") { - Game::logger->Log("UserManager", "AccountID: %i is creating a character with predefined name: %s\n", u->GetAccountID(), predefinedName.c_str()); + Game::logger->Log("UserManager", "AccountID: %i is creating a character with predefined name: %s", u->GetAccountID(), predefinedName.c_str()); } else { - Game::logger->Log("UserManager", "AccountID: %i is creating a character with name: %s (temporary: %s)\n", u->GetAccountID(), name.c_str(), predefinedName.c_str()); + Game::logger->Log("UserManager", "AccountID: %i is creating a character with name: %s (temporary: %s)", u->GetAccountID(), name.c_str(), predefinedName.c_str()); } - + //Now that the name is ok, we can get an objectID from Master: ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t objectID) { sql::PreparedStatement* overlapStmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE id = ?"); @@ -277,47 +277,47 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) auto* overlapResult = overlapStmt->executeQuery(); if (overlapResult->next()) { - Game::logger->Log("UserManager", "Character object id unavailable, check objectidtracker!\n"); + Game::logger->Log("UserManager", "Character object id unavailable, check objectidtracker!"); WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_OBJECT_ID_UNAVAILABLE); return; } - + std::stringstream xml; xml << ""; - + xml << "GetAccountID() << "\" cc=\"0\" gm=\"0\" ft=\"0\" llog=\"" << time(NULL) << "\" "; xml << "ls=\"0\" lzx=\"-626.5847\" lzy=\"613.3515\" lzz=\"-28.6374\" lzrx=\"0.0\" lzry=\"0.7015\" lzrz=\"0.0\" lzrw=\"0.7126\" "; xml << "stt=\"0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;\">"; xml << ""; xml << ""; std::string xmlSave1 = xml.str(); - + ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t idforshirt) { std::stringstream xml2; - + LWOOBJID lwoidforshirt = idforshirt; lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_CHARACTER); lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_PERSISTENT); xml2 << xmlSave1 << ""; - + std::string xmlSave2 = xml2.str(); - + ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t idforpants) { LWOOBJID lwoidforpants = idforpants; lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_CHARACTER); lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_PERSISTENT); - + std::stringstream xml3; xml3 << xmlSave2 << ""; - + xml3 << ""; - + //Check to see if our name was pre-approved: bool nameOk = IsNamePreapproved(name); if (!nameOk && u->GetMaxGMLevel() > 1) nameOk = true; - + if (name != "") { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charinfo`(`id`, `account_id`, `name`, `pending_name`, `needs_rename`, `last_login`) VALUES (?,?,?,?,?,?)"); stmt->setUInt(1, objectID); @@ -326,12 +326,12 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) stmt->setString(4, name.c_str()); stmt->setBoolean(5, false); stmt->setUInt64(6, time(NULL)); - + if (nameOk) { stmt->setString(3, name.c_str()); stmt->setString(4, ""); } - + stmt->execute(); delete stmt; } else { @@ -342,18 +342,18 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) stmt->setString(4, ""); stmt->setBoolean(5, false); stmt->setUInt64(6, time(NULL)); - + stmt->execute(); delete stmt; } - + //Now finally insert our character xml: sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charxml`(`id`, `xml_data`) VALUES (?,?)"); stmt->setUInt(1, objectID); stmt->setString(2, xml3.str().c_str()); stmt->execute(); delete stmt; - + WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_SUCCESS); UserManager::RequestCharacterList(sysAddr); }); @@ -364,28 +364,28 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) { User* u = GetUser(sysAddr); if (!u) { - Game::logger->Log("UserManager", "Couldn't get user to delete character\n"); + Game::logger->Log("UserManager", "Couldn't get user to delete character"); return; } - + LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); uint32_t charID = static_cast(objectID); - Game::logger->Log("UserManager", "Received char delete req for ID: %llu (%u)\n", objectID, charID); - + Game::logger->Log("UserManager", "Received char delete req for ID: %llu (%u)", objectID, charID); + //Check if this user has this character: bool hasCharacter = false; std::vector& characters = u->GetCharacters(); for (size_t i = 0; i < characters.size(); ++i) { if (characters[i]->GetID() == charID) { hasCharacter = true; } } - + if (!hasCharacter) { - Game::logger->Log("UserManager", "User %i tried to delete a character that it does not own!\n", u->GetAccountID()); + Game::logger->Log("UserManager", "User %i tried to delete a character that it does not own!", u->GetAccountID()); WorldPackets::SendCharacterDeleteResponse(sysAddr, false); } else { - Game::logger->Log("UserManager", "Deleting character %i\n", charID); + Game::logger->Log("UserManager", "Deleting character %i", charID); { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("DELETE FROM charxml WHERE id=? LIMIT 1;"); stmt->setUInt64(1, charID); @@ -453,7 +453,7 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) stmt->execute(); delete stmt; } - + WorldPackets::SendCharacterDeleteResponse(sysAddr, true); } } @@ -461,37 +461,37 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) { User* u = GetUser(sysAddr); if (!u) { - Game::logger->Log("UserManager", "Couldn't get user to delete character\n"); + Game::logger->Log("UserManager", "Couldn't get user to delete character"); return; } - + LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_CHARACTER); objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_PERSISTENT); - + uint32_t charID = static_cast(objectID); - Game::logger->Log("UserManager", "Received char rename request for ID: %llu (%u)\n", objectID, charID); - + Game::logger->Log("UserManager", "Received char rename request for ID: %llu (%u)", objectID, charID); + std::string newName = PacketUtils::ReadString(16, packet, true); - + Character* character = nullptr; - + //Check if this user has this character: bool hasCharacter = false; std::vector& characters = u->GetCharacters(); for (size_t i = 0; i < characters.size(); ++i) { if (characters[i]->GetID() == charID) { hasCharacter = true; character = characters[i]; } } - + if (!hasCharacter || !character) { - Game::logger->Log("UserManager", "User %i tried to rename a character that it does not own!\n", u->GetAccountID()); + Game::logger->Log("UserManager", "User %i tried to rename a character that it does not own!", u->GetAccountID()); WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); } else if (hasCharacter && character) { if (newName == character->GetName()) { WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_UNAVAILABLE); return; } - + if (IsNameAvailable(newName)) { if (IsNamePreapproved(newName)) { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET name=?, pending_name='', needs_rename=0, last_login=? WHERE id=? LIMIT 1"); @@ -500,8 +500,8 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) stmt->setUInt(3, character->GetID()); stmt->execute(); delete stmt; - - Game::logger->Log("UserManager", "Character %s now known as %s\n", character->GetName().c_str(), newName.c_str()); + + Game::logger->Log("UserManager", "Character %s now known as %s", character->GetName().c_str(), newName.c_str()); WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); UserManager::RequestCharacterList(sysAddr); } else { @@ -511,8 +511,8 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) stmt->setUInt(3, character->GetID()); stmt->execute(); delete stmt; - - Game::logger->Log("UserManager", "Character %s has been renamed to %s and is pending approval by a moderator.\n", character->GetName().c_str(), newName.c_str()); + + Game::logger->Log("UserManager", "Character %s has been renamed to %s and is pending approval by a moderator.", character->GetName().c_str(), newName.c_str()); WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); UserManager::RequestCharacterList(sysAddr); } @@ -520,7 +520,7 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_IN_USE); } } else { - Game::logger->Log("UserManager", "Unknown error occurred when renaming character, either hasCharacter or character variable != true.\n"); + Game::logger->Log("UserManager", "Unknown error occurred when renaming character, either hasCharacter or character variable != true."); WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); } } @@ -528,30 +528,30 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID) { User* u = GetUser(sysAddr); if (!u) { - Game::logger->Log("UserManager", "Couldn't get user to log in character\n"); + Game::logger->Log("UserManager", "Couldn't get user to log in character"); return; } - + Character* character = nullptr; bool hasCharacter = false; std::vector& characters = u->GetCharacters(); - + for (size_t i = 0; i < characters.size(); ++i) { if (characters[i]->GetID() == playerID) { hasCharacter = true; character = characters[i]; } } - + if (hasCharacter && character) { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET last_login=? WHERE id=? LIMIT 1"); stmt->setUInt64(1, time(NULL)); stmt->setUInt(2, playerID); stmt->execute(); delete stmt; - + uint32_t zoneID = character->GetZoneID(); if (zoneID == LWOZONEID_INVALID) zoneID = 1000; //Send char to VE - + ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, zoneID, character->GetZoneClone(), false, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (character) { character->SetZoneID(zoneID); character->SetZoneInstance(zoneInstance); @@ -561,7 +561,7 @@ void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID return; }); } else { - Game::logger->Log("UserManager", "Unknown error occurred when logging in a character, either hasCharacter or character variable != true.\n"); + Game::logger->Log("UserManager", "Unknown error occurred when logging in a character, either hasCharacter or character variable != true."); } } diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.cpp b/dGame/dBehaviors/AreaOfEffectBehavior.cpp index 6568f9b8..e3f992e7 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.cpp +++ b/dGame/dBehaviors/AreaOfEffectBehavior.cpp @@ -37,7 +37,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b for (auto target : targets) { branch.target = target; - + this->m_action->Handle(context, bitStream, branch); } } @@ -48,7 +48,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream if (self == nullptr) { - Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!\n", context->originator); + Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!", context->originator); return; } @@ -81,7 +81,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream if (entity == nullptr) { - Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!\n", validTarget, context->originator); + Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!", validTarget, context->originator); continue; } @@ -90,7 +90,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream { continue; } - + auto* destroyableComponent = entity->GetComponent(); if (destroyableComponent == nullptr) @@ -120,7 +120,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream }); const uint32_t size = targets.size(); - + bitStream->Write(size); if (size == 0) @@ -133,10 +133,10 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream for (auto* target : targets) { bitStream->Write(target->GetObjectID()); - + PlayFx(u"cast", context->originator, target->GetObjectID()); } - + for (auto* target : targets) { branch.target = target->GetObjectID(); diff --git a/dGame/dBehaviors/BasicAttackBehavior.cpp b/dGame/dBehaviors/BasicAttackBehavior.cpp index a9a58245..8f0fd287 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.cpp +++ b/dGame/dBehaviors/BasicAttackBehavior.cpp @@ -21,7 +21,7 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi return; } - + bitStream->AlignReadToByteBoundary(); uint16_t allocatedBits; @@ -69,7 +69,7 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi this->m_onSuccess->Handle(context, bitStream, branch); break; default: - Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!\n", successState); + Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!", successState); break; } @@ -79,10 +79,10 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* self = EntityManager::Instance()->GetEntity(context->originator); if (self == nullptr) { - Game::logger->Log("BasicAttackBehavior", "Invalid self entity (%llu)!\n", context->originator); + Game::logger->Log("BasicAttackBehavior", "Invalid self entity (%llu)!", context->originator); return; } - + bitStream->AlignWriteToByteBoundary(); const auto allocatedAddress = bitStream->GetWriteOffset(); @@ -127,7 +127,7 @@ void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* this->m_onSuccess->Calculate(context, bitStream, branch); break; default: - Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!\n", successState); + Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!", successState); break; } diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index 489bd1a7..a1b746cd 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -175,7 +175,7 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) behavior = new SpeedBehavior(behaviorId); break; case BehaviorTemplates::BEHAVIOR_DARK_INSPIRATION: break; - case BehaviorTemplates::BEHAVIOR_LOOT_BUFF: + case BehaviorTemplates::BEHAVIOR_LOOT_BUFF: behavior = new LootBuffBehavior(behaviorId); break; case BehaviorTemplates::BEHAVIOR_VENTURE_VISION: @@ -269,13 +269,13 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) case BehaviorTemplates::BEHAVIOR_MOUNT: break; case BehaviorTemplates::BEHAVIOR_SKILL_SET: break; default: - //Game::logger->Log("Behavior", "Failed to load behavior with invalid template id (%i)!\n", templateId); + //Game::logger->Log("Behavior", "Failed to load behavior with invalid template id (%i)!", templateId); break; } if (behavior == nullptr) { - //Game::logger->Log("Behavior", "Failed to load unimplemented template id (%i)!\n", templateId); + //Game::logger->Log("Behavior", "Failed to load unimplemented template id (%i)!", templateId); behavior = new EmptyBehavior(behaviorId); } @@ -298,7 +298,7 @@ BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) { } if (templateID == BehaviorTemplates::BEHAVIOR_EMPTY && behaviorId != 0) { - Game::logger->Log("Behavior", "Failed to load behavior template with id (%i)!\n", behaviorId); + Game::logger->Log("Behavior", "Failed to load behavior template with id (%i)!", behaviorId); } return templateID; @@ -432,7 +432,7 @@ Behavior::Behavior(const uint32_t behaviorId) // Make sure we do not proceed if we are trying to load an invalid behavior if (templateInDatabase.behaviorID == 0) { - Game::logger->Log("Behavior", "Failed to load behavior with id (%i)!\n", behaviorId); + Game::logger->Log("Behavior", "Failed to load behavior with id (%i)!", behaviorId); this->m_effectId = 0; this->m_effectHandle = nullptr; diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index c7bf912f..87e63a59 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -33,7 +33,7 @@ uint32_t BehaviorContext::GetUniqueSkillId() const if (entity == nullptr) { - Game::logger->Log("BehaviorContext", "Invalid entity for (%llu)!\n", this->originator); + Game::logger->Log("BehaviorContext", "Invalid entity for (%llu)!", this->originator); return 0; } @@ -42,7 +42,7 @@ uint32_t BehaviorContext::GetUniqueSkillId() const if (component == nullptr) { - Game::logger->Log("BehaviorContext", "No skill component attached to (%llu)!\n", this->originator);; + Game::logger->Log("BehaviorContext", "No skill component attached to (%llu)!", this->originator);; return 0; } @@ -65,7 +65,7 @@ void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* beha void BehaviorContext::RegisterTimerBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, const LWOOBJID second) { BehaviorTimerEntry entry; - + entry.time = branchContext.duration; entry.behavior = behavior; entry.branchContext = branchContext; @@ -103,7 +103,7 @@ void BehaviorContext::ExecuteUpdates() auto* entity = EntityManager::Instance()->GetEntity(id); if (entity == nullptr) continue; - + EntityManager::Instance()->SerializeEntity(entity); } @@ -111,7 +111,7 @@ void BehaviorContext::ExecuteUpdates() } void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bitStream) -{ +{ BehaviorSyncEntry entry; auto found = false; @@ -121,7 +121,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bit for (auto i = 0u; i < this->syncEntries.size(); ++i) { const auto syncEntry = this->syncEntries.at(i); - + if (syncEntry.handle == syncId) { found = true; @@ -135,7 +135,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bit if (!found) { - Game::logger->Log("BehaviorContext", "Failed to find behavior sync entry with sync id (%i)!\n", syncId); + Game::logger->Log("BehaviorContext", "Failed to find behavior sync entry with sync id (%i)!", syncId); return; } @@ -145,8 +145,8 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bit if (behavior == nullptr) { - Game::logger->Log("BehaviorContext", "Invalid behavior for sync id (%i)!\n", syncId); - + Game::logger->Log("BehaviorContext", "Invalid behavior for sync id (%i)!", syncId); + return; } @@ -166,7 +166,7 @@ void BehaviorContext::Update(const float deltaTime) this->timerEntries[i] = entry; } - + if (entry.time > 0) { continue; @@ -174,7 +174,7 @@ void BehaviorContext::Update(const float deltaTime) entry.behavior->Timer(this, entry.branchContext, entry.second); } - + std::vector valid; for (const auto& entry : this->timerEntries) @@ -226,7 +226,7 @@ void BehaviorContext::InvokeEnd(const uint32_t id) bool BehaviorContext::CalculateUpdate(const float deltaTime) { auto any = false; - + for (auto i = 0u; i < this->syncEntries.size(); ++i) { auto entry = this->syncEntries.at(i); @@ -241,7 +241,7 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) if (entry.time > 0) { any = true; - + continue; } @@ -267,7 +267,7 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) PacketUtils::WriteHeader(message, CLIENT, MSG_CLIENT_GAME_MSG); message.Write(this->originator); echo.Serialize(&message); - + Game::server->Send(&message, UNASSIGNED_SYSTEM_ADDRESS, true); } @@ -293,7 +293,7 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) return any; } -void BehaviorContext::Interrupt() +void BehaviorContext::Interrupt() { std::vector keptSync {}; @@ -303,7 +303,7 @@ void BehaviorContext::Interrupt() keptSync.push_back(entry); } - + this->syncEntries = keptSync; } @@ -330,10 +330,10 @@ std::vector BehaviorContext::GetValidTargets(int32_t ignoreFaction, in auto* entity = EntityManager::Instance()->GetEntity(this->caster); std::vector targets; - + if (entity == nullptr) { - Game::logger->Log("BehaviorContext", "Invalid entity for (%llu)!\n", this->originator); + Game::logger->Log("BehaviorContext", "Invalid entity for (%llu)!", this->originator); return targets; } @@ -360,12 +360,12 @@ std::vector BehaviorContext::GetValidTargets(int32_t ignoreFaction, in { return targets; } - + auto entities = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS); for (auto* candidate : entities) { const auto id = candidate->GetObjectID(); - + if ((id != entity->GetObjectID() || targetSelf) && destroyableComponent->CheckValidity(id, ignoreFaction || includeFaction, targetEnemy, targetFriend)) { targets.push_back(id); diff --git a/dGame/dBehaviors/BlockBehavior.cpp b/dGame/dBehaviors/BlockBehavior.cpp index 8f66b182..13012f98 100644 --- a/dGame/dBehaviors/BlockBehavior.cpp +++ b/dGame/dBehaviors/BlockBehavior.cpp @@ -15,7 +15,7 @@ void BlockBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea if (entity == nullptr) { - Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; } @@ -52,7 +52,7 @@ void BlockBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branc if (entity == nullptr) { - Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; } diff --git a/dGame/dBehaviors/BuffBehavior.cpp b/dGame/dBehaviors/BuffBehavior.cpp index e2490f16..09b70e03 100644 --- a/dGame/dBehaviors/BuffBehavior.cpp +++ b/dGame/dBehaviors/BuffBehavior.cpp @@ -10,12 +10,12 @@ void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator; - + auto* entity = EntityManager::Instance()->GetEntity(target); if (entity == nullptr) { - Game::logger->Log("BuffBehavior", "Invalid target (%llu)!\n", target); + Game::logger->Log("BuffBehavior", "Invalid target (%llu)!", target); return; } @@ -24,7 +24,7 @@ void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream if (component == nullptr) { - Game::logger->Log("BuffBehavior", "Invalid target, no destroyable component (%llu)!\n", target); + Game::logger->Log("BuffBehavior", "Invalid target, no destroyable component (%llu)!", target); return; } @@ -51,12 +51,12 @@ void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator; - + auto* entity = EntityManager::Instance()->GetEntity(target); if (entity == nullptr) { - Game::logger->Log("BuffBehavior", "Invalid target (%llu)!\n", target); + Game::logger->Log("BuffBehavior", "Invalid target (%llu)!", target); return; } @@ -65,7 +65,7 @@ void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch if (component == nullptr) { - Game::logger->Log("BuffBehavior", "Invalid target, no destroyable component (%llu)!\n", target); + Game::logger->Log("BuffBehavior", "Invalid target, no destroyable component (%llu)!", target); return; } @@ -73,7 +73,7 @@ void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch component->SetMaxHealth(component->GetMaxHealth() - this->m_health); component->SetMaxArmor(component->GetMaxArmor() - this->m_armor); component->SetMaxImagination(component->GetMaxImagination() - this->m_imagination); - + EntityManager::Instance()->SerializeEntity(entity); } diff --git a/dGame/dBehaviors/CarBoostBehavior.cpp b/dGame/dBehaviors/CarBoostBehavior.cpp index 7c726030..adfae01b 100644 --- a/dGame/dBehaviors/CarBoostBehavior.cpp +++ b/dGame/dBehaviors/CarBoostBehavior.cpp @@ -8,7 +8,7 @@ #include "dLogger.h" #include "PossessableComponent.h" -void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) +void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { GameMessages::SendVehicleAddPassiveBoostAction(branch.target, UNASSIGNED_SYSTEM_ADDRESS); @@ -19,7 +19,7 @@ void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt return; } - Game::logger->Log("Car boost", "Activating car boost!\n"); + Game::logger->Log("Car boost", "Activating car boost!"); auto* possessableComponent = entity->GetComponent(); if (possessableComponent != nullptr) { @@ -29,7 +29,7 @@ void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt auto* characterComponent = possessor->GetComponent(); if (characterComponent != nullptr) { - Game::logger->Log("Car boost", "Tracking car boost!\n"); + Game::logger->Log("Car boost", "Tracking car boost!"); characterComponent->UpdatePlayerStatistic(RacingCarBoostsActivated); } } @@ -43,7 +43,7 @@ void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt }); } -void CarBoostBehavior::Load() +void CarBoostBehavior::Load() { m_Action = GetAction("action"); diff --git a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp index bb94f9b3..f02c4eea 100644 --- a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp +++ b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp @@ -13,7 +13,7 @@ void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStrea if (target == nullptr) { - Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; } @@ -32,7 +32,7 @@ void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStrea context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void DamageAbsorptionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) +void DamageAbsorptionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } @@ -43,11 +43,11 @@ void DamageAbsorptionBehavior::Timer(BehaviorContext* context, BehaviorBranchCon if (target == nullptr) { - Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!\n", second); + Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", second); return; } - + auto* destroyable = target->GetComponent(); if (destroyable == nullptr) @@ -56,7 +56,7 @@ void DamageAbsorptionBehavior::Timer(BehaviorContext* context, BehaviorBranchCon } const auto present = static_cast(destroyable->GetDamageToAbsorb()); - + const auto toRemove = std::min(present, this->m_absorbAmount); destroyable->SetDamageToAbsorb(present - toRemove); diff --git a/dGame/dBehaviors/DamageReductionBehavior.cpp b/dGame/dBehaviors/DamageReductionBehavior.cpp index 96c32a03..45a30975 100644 --- a/dGame/dBehaviors/DamageReductionBehavior.cpp +++ b/dGame/dBehaviors/DamageReductionBehavior.cpp @@ -13,7 +13,7 @@ void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream if (target == nullptr) { - Game::logger->Log("DamageReductionBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("DamageReductionBehavior", "Failed to find target (%llu)!", branch.target); return; } @@ -26,11 +26,11 @@ void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream } destroyable->SetDamageReduction(m_ReductionAmount); - + context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void DamageReductionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) +void DamageReductionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } @@ -41,11 +41,11 @@ void DamageReductionBehavior::Timer(BehaviorContext* context, BehaviorBranchCont if (target == nullptr) { - Game::logger->Log("DamageReductionBehavior", "Failed to find target (%llu)!\n", second); + Game::logger->Log("DamageReductionBehavior", "Failed to find target (%llu)!", second); return; } - + auto* destroyable = target->GetComponent(); if (destroyable == nullptr) diff --git a/dGame/dBehaviors/HealBehavior.cpp b/dGame/dBehaviors/HealBehavior.cpp index eebf24f8..41107203 100644 --- a/dGame/dBehaviors/HealBehavior.cpp +++ b/dGame/dBehaviors/HealBehavior.cpp @@ -12,7 +12,7 @@ void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_strea if (entity == nullptr) { - Game::logger->Log("HealBehavior", "Failed to find entity for (%llu)!\n", branch.target); + Game::logger->Log("HealBehavior", "Failed to find entity for (%llu)!", branch.target); return; } @@ -21,11 +21,11 @@ void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_strea if (destroyable == nullptr) { - Game::logger->Log("HealBehavior", "Failed to find destroyable component for %(llu)!\n", branch.target); + Game::logger->Log("HealBehavior", "Failed to find destroyable component for %(llu)!", branch.target); return; } - + destroyable->Heal(this->m_health); } diff --git a/dGame/dBehaviors/ImmunityBehavior.cpp b/dGame/dBehaviors/ImmunityBehavior.cpp index 73dde1fa..4e72ba36 100644 --- a/dGame/dBehaviors/ImmunityBehavior.cpp +++ b/dGame/dBehaviors/ImmunityBehavior.cpp @@ -13,7 +13,7 @@ void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt if (target == nullptr) { - Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; } @@ -31,11 +31,11 @@ void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt } destroyable->PushImmunity(); - + context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void ImmunityBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) +void ImmunityBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } @@ -46,7 +46,7 @@ void ImmunityBehavior::Timer(BehaviorContext* context, BehaviorBranchContext bra if (target == nullptr) { - Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!\n", second); + Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", second); return; } diff --git a/dGame/dBehaviors/MovementSwitchBehavior.cpp b/dGame/dBehaviors/MovementSwitchBehavior.cpp index a77b114e..066f6224 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.cpp +++ b/dGame/dBehaviors/MovementSwitchBehavior.cpp @@ -8,13 +8,13 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* if (this->m_groundAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_jumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_fallingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && - this->m_doubleJumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && + this->m_doubleJumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_airAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_jetpackAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { return; } - + uint32_t movementType; bitStream->Read(movementType); @@ -40,13 +40,13 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* this->m_jetpackAction->Handle(context, bitStream, branch); break; default: - Game::logger->Log("MovementSwitchBehavior", "Invalid movement behavior type (%i)!\n", movementType); + Game::logger->Log("MovementSwitchBehavior", "Invalid movement behavior type (%i)!", movementType); break; } } void MovementSwitchBehavior::Load() -{ +{ this->m_airAction = GetAction("air_action"); this->m_doubleJumpAction = GetAction("double_jump_action"); diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.cpp b/dGame/dBehaviors/ProjectileAttackBehavior.cpp index 905a630c..5bf8b6a1 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.cpp +++ b/dGame/dBehaviors/ProjectileAttackBehavior.cpp @@ -12,12 +12,12 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea LWOOBJID target; bitStream->Read(target); - + auto* entity = EntityManager::Instance()->GetEntity(context->originator); if (entity == nullptr) { - Game::logger->Log("ProjectileAttackBehavior", "Failed to find originator (%llu)!\n", context->originator); + Game::logger->Log("ProjectileAttackBehavior", "Failed to find originator (%llu)!", context->originator); return; } @@ -26,7 +26,7 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea if (skillComponent == nullptr) { - Game::logger->Log("ProjectileAttackBehavior", "Failed to find skill component for (%llu)!\n", -context->originator); + Game::logger->Log("ProjectileAttackBehavior", "Failed to find skill component for (%llu)!", -context->originator); return; } @@ -44,7 +44,7 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea LWOOBJID projectileId; bitStream->Read(projectileId); - + branch.target = target; branch.isProjectile = true; branch.referencePosition = targetEntity == nullptr ? entity->GetPosition() : targetEntity->GetPosition(); @@ -61,7 +61,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt if (entity == nullptr) { - Game::logger->Log("ProjectileAttackBehavior", "Failed to find originator (%llu)!\n", context->originator); + Game::logger->Log("ProjectileAttackBehavior", "Failed to find originator (%llu)!", context->originator); return; } @@ -70,7 +70,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt if (skillComponent == nullptr) { - Game::logger->Log("ProjectileAttackBehavior", "Failed to find skill component for (%llu)!\n", context->originator); + Game::logger->Log("ProjectileAttackBehavior", "Failed to find skill component for (%llu)!", context->originator); return; @@ -80,8 +80,8 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt if (other == nullptr) { - Game::logger->Log("ProjectileAttackBehavior", "Invalid projectile target (%llu)!\n", branch.target); - + Game::logger->Log("ProjectileAttackBehavior", "Invalid projectile target (%llu)!", branch.target); + return; } diff --git a/dGame/dBehaviors/RepairBehavior.cpp b/dGame/dBehaviors/RepairBehavior.cpp index 1a418cae..c3e8a4d3 100644 --- a/dGame/dBehaviors/RepairBehavior.cpp +++ b/dGame/dBehaviors/RepairBehavior.cpp @@ -12,7 +12,7 @@ void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_str if (entity == nullptr) { - Game::logger->Log("RepairBehavior", "Failed to find entity for (%llu)!\n", branch.target); + Game::logger->Log("RepairBehavior", "Failed to find entity for (%llu)!", branch.target); return; } @@ -21,11 +21,11 @@ void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_str if (destroyable == nullptr) { - Game::logger->Log("RepairBehavior", "Failed to find destroyable component for %(llu)!\n", branch.target); + Game::logger->Log("RepairBehavior", "Failed to find destroyable component for %(llu)!", branch.target); return; } - + destroyable->Repair(this->m_armor); } diff --git a/dGame/dBehaviors/SpawnBehavior.cpp b/dGame/dBehaviors/SpawnBehavior.cpp index 800eb86d..6d0e7490 100644 --- a/dGame/dBehaviors/SpawnBehavior.cpp +++ b/dGame/dBehaviors/SpawnBehavior.cpp @@ -14,7 +14,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea if (origin == nullptr) { - Game::logger->Log("SpawnBehavior", "Failed to find self entity (%llu)!\n", context->originator); + Game::logger->Log("SpawnBehavior", "Failed to find self entity (%llu)!", context->originator); return; } @@ -28,7 +28,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea origin = target; } } - + EntityInfo info; info.lot = this->m_lot; info.pos = origin->GetPosition(); @@ -47,7 +47,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea if (entity == nullptr) { - Game::logger->Log("SpawnBehavior", "Failed to spawn entity (%i)!\n", this->m_lot); + Game::logger->Log("SpawnBehavior", "Failed to spawn entity (%i)!", this->m_lot); return; } @@ -61,7 +61,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea { rebuildComponent->SetRepositionPlayer(false); } - + EntityManager::Instance()->ConstructEntity(entity); if (branch.duration > 0) @@ -79,7 +79,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea }); } -void SpawnBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) +void SpawnBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } @@ -90,7 +90,7 @@ void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext if (entity == nullptr) { - Game::logger->Log("SpawnBehavior", "Failed to find spawned entity (%llu)!\n", second); + Game::logger->Log("SpawnBehavior", "Failed to find spawned entity (%llu)!", second); return; } @@ -100,7 +100,7 @@ void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext if (destroyable == nullptr) { entity->Smash(context->originator); - + return; } diff --git a/dGame/dBehaviors/StunBehavior.cpp b/dGame/dBehaviors/StunBehavior.cpp index 994295bd..5c0ea310 100644 --- a/dGame/dBehaviors/StunBehavior.cpp +++ b/dGame/dBehaviors/StunBehavior.cpp @@ -22,7 +22,7 @@ void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream if (target == nullptr) { - Game::logger->Log("StunBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("StunBehavior", "Failed to find target (%llu)!", branch.target); return; } @@ -30,7 +30,7 @@ void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream /* * If our target is an enemy we can go ahead and stun it. */ - + auto* combatAiComponent = static_cast(target->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); if (combatAiComponent == nullptr) @@ -49,7 +49,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr if (self == nullptr) { - Game::logger->Log("StunBehavior", "Invalid self entity (%llu)!\n", context->originator); + Game::logger->Log("StunBehavior", "Invalid self entity (%llu)!", context->originator); return; } @@ -57,7 +57,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr /* * See if we can stun ourselves */ - + auto* combatAiComponent = static_cast(self->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); if (combatAiComponent == nullptr) @@ -66,7 +66,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr } combatAiComponent->Stun(branch.duration); - + return; } @@ -88,7 +88,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr if (target == nullptr) { - Game::logger->Log("StunBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("StunBehavior", "Failed to find target (%llu)!", branch.target); return; } diff --git a/dGame/dBehaviors/SwitchBehavior.cpp b/dGame/dBehaviors/SwitchBehavior.cpp index d6cb1438..8af8a334 100644 --- a/dGame/dBehaviors/SwitchBehavior.cpp +++ b/dGame/dBehaviors/SwitchBehavior.cpp @@ -23,13 +23,13 @@ void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre } auto* destroyableComponent = entity->GetComponent(); - + if (destroyableComponent == nullptr) { return; } - Game::logger->Log("SwitchBehavior", "[%i] State: (%d), imagination: (%i) / (%f)\n", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination()); + Game::logger->Log("SwitchBehavior", "[%i] State: (%d), imagination: (%i) / (%f)", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination()); if (state || (entity->GetLOT() == 8092 && destroyableComponent->GetImagination() >= m_imagination)) { @@ -44,7 +44,7 @@ void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre void SwitchBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto state = true; - + if (this->m_imagination > 0 || !this->m_isEnemyFaction) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); @@ -77,11 +77,11 @@ void SwitchBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS void SwitchBehavior::Load() { this->m_actionTrue = GetAction("action_true"); - + this->m_actionFalse = GetAction("action_false"); - + this->m_imagination = GetInt("imagination"); - + this->m_isEnemyFaction = GetBoolean("isEnemyFaction"); this->m_targetHasBuff = GetInt("target_has_buff"); diff --git a/dGame/dBehaviors/TacArcBehavior.cpp b/dGame/dBehaviors/TacArcBehavior.cpp index 46ec03b9..2d012305 100644 --- a/dGame/dBehaviors/TacArcBehavior.cpp +++ b/dGame/dBehaviors/TacArcBehavior.cpp @@ -27,7 +27,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre if (this->m_checkEnv) { bool blocked = false; - + bitStream->Read(blocked); if (blocked) @@ -63,7 +63,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre for (auto target : targets) { branch.target = target; - + this->m_action->Handle(context, bitStream, branch); } } @@ -77,7 +77,7 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS { auto* self = EntityManager::Instance()->GetEntity(context->originator); if (self == nullptr) { - Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!\n", context->originator); + Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!", context->originator); return; } @@ -102,7 +102,7 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS } auto* combatAi = self->GetComponent(); - + const auto casterPosition = self->GetPosition(); auto reference = self->GetPosition(); //+ m_offset; @@ -144,7 +144,7 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS if (entity == nullptr) { - Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!\n", validTarget, context->originator); + Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!", validTarget, context->originator); continue; } @@ -171,7 +171,7 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS // otherPosition is the position of the target. // reference is the position of the caster. // If we cast a ray forward from the caster, does it come within m_farWidth of the target? - + const auto distance = Vector3::Distance(reference, otherPosition); if (m_method == 2) @@ -185,7 +185,7 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS } auto normalized = (reference - otherPosition) / distance; - + const float degreeAngle = std::abs(Vector3::Angle(forward, normalized) * (180 / 3.14) - 180); if (distance >= this->m_minDistance && this->m_maxDistance >= distance && degreeAngle <= 2 * this->m_angle) @@ -221,7 +221,7 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS } context->foundTarget = true; // We want to continue with this behavior - + const auto count = static_cast(targets.size()); bitStream->Write(count); diff --git a/dGame/dBehaviors/TauntBehavior.cpp b/dGame/dBehaviors/TauntBehavior.cpp index 7240dc14..8ccc3abc 100644 --- a/dGame/dBehaviors/TauntBehavior.cpp +++ b/dGame/dBehaviors/TauntBehavior.cpp @@ -12,13 +12,13 @@ void TauntBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea if (target == nullptr) { - Game::logger->Log("TauntBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("TauntBehavior", "Failed to find target (%llu)!", branch.target); return; } auto* combatComponent = target->GetComponent(); - + if (combatComponent != nullptr) { combatComponent->Taunt(context->originator, m_threatToAdd); @@ -31,13 +31,13 @@ void TauntBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitSt if (target == nullptr) { - Game::logger->Log("TauntBehavior", "Failed to find target (%llu)!\n", branch.target); + Game::logger->Log("TauntBehavior", "Failed to find target (%llu)!", branch.target); return; } auto* combatComponent = target->GetComponent(); - + if (combatComponent != nullptr) { combatComponent->Taunt(context->originator, m_threatToAdd); diff --git a/dGame/dBehaviors/VerifyBehavior.cpp b/dGame/dBehaviors/VerifyBehavior.cpp index f4edfece..17ba1001 100644 --- a/dGame/dBehaviors/VerifyBehavior.cpp +++ b/dGame/dBehaviors/VerifyBehavior.cpp @@ -23,11 +23,11 @@ void VerifyBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS if (self == nullptr) { - Game::logger->Log("VerifyBehavior", "Invalid self for (%llu)\n", context->originator); + Game::logger->Log("VerifyBehavior", "Invalid self for (%llu)", context->originator); return; } - + const auto distance = Vector3::DistanceSquared(self->GetPosition(), entity->GetPosition()); if (distance > this->m_range * this->m_range) diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index bfa000f2..022b3e6c 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -38,7 +38,7 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) auto componentQuery = CDClientDatabase::CreatePreppedStmt( "SELECT aggroRadius, tetherSpeed, pursuitSpeed, softTetherRadius, hardTetherRadius FROM BaseCombatAIComponent WHERE id = ?;"); componentQuery.bind(1, (int) id); - + auto componentResult = componentQuery.execQuery(); if (!componentResult.eof()) @@ -76,7 +76,7 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) auto skillQuery = CDClientDatabase::CreatePreppedStmt( "SELECT skillID, cooldown, behaviorID FROM SkillBehavior WHERE skillID IN (SELECT skillID FROM ObjectSkills WHERE objectTemplate = ?);"); skillQuery.bind(1, (int) parent->GetLOT()); - + auto result = skillQuery.execQuery(); while (!result.eof()) { @@ -254,7 +254,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { } skillComponent->CalculateUpdate(deltaTime); - + if (m_Disabled) return; if (m_StunTime > 0.0f) @@ -362,19 +362,19 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { if (m_Target == LWOOBJID_EMPTY) { m_State = AiState::idle; - + return; } m_Downtime = 0.5f; - + auto* target = GetTargetEntity(); if (target != nullptr) { LookAt(target->GetPosition()); } - + for (auto i = 0; i < m_SkillEntries.size(); ++i) { auto entry = m_SkillEntries.at(i); @@ -413,11 +413,11 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { if (m_MovementAI) reference = m_MovementAI->ApproximateLocation(); auto* target = GetTargetEntity(); - + if (target != nullptr && !m_DirtyThreat) { const auto targetPosition = target->GetPosition(); - + if (Vector3::DistanceSquared(targetPosition, m_StartPosition) < m_HardTetherRadius * m_HardTetherRadius) { return m_Target; @@ -492,7 +492,7 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { } std::vector deadThreats {}; - + for (const auto& threatTarget : m_ThreatEntries) { auto* entity = EntityManager::Instance()->GetEntity(threatTarget.first); @@ -526,7 +526,7 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { } m_DirtyThreat = false; - + if (optimalTarget == nullptr) { return LWOOBJID_EMPTY; @@ -577,7 +577,7 @@ bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const { auto* entity = EntityManager::Instance()->GetEntity(target); if (entity == nullptr) { - Game::logger->Log("BaseCombatAIComponent", "Invalid entity for checking validity (%llu)!\n", target); + Game::logger->Log("BaseCombatAIComponent", "Invalid entity for checking validity (%llu)!", target); return false; } @@ -591,7 +591,7 @@ bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const { auto* referenceDestroyable = m_Parent->GetComponent(); if (referenceDestroyable == nullptr) { - Game::logger->Log("BaseCombatAIComponent", "Invalid reference destroyable component on (%llu)!\n", m_Parent->GetObjectID()); + Game::logger->Log("BaseCombatAIComponent", "Invalid reference destroyable component on (%llu)!", m_Parent->GetObjectID()); return false; } @@ -601,7 +601,7 @@ bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const { if (quickbuild != nullptr) { const auto state = quickbuild->GetState(); - + if (state != REBUILD_COMPLETED) { return false; @@ -662,7 +662,7 @@ const NiPoint3& BaseCombatAIComponent::GetStartPosition() const return m_StartPosition; } -void BaseCombatAIComponent::ClearThreat() +void BaseCombatAIComponent::ClearThreat() { m_ThreatEntries.clear(); @@ -675,12 +675,12 @@ void BaseCombatAIComponent::Wander() { } m_MovementAI->SetHaltDistance(0); - + const auto& info = m_MovementAI->GetInfo(); const auto div = static_cast(info.wanderDelayMax); m_Timer = (div == 0 ? 0 : GeneralUtils::GenerateRandomNumber(0, div)) + info.wanderDelayMin; //set a random timer to stay put. - + const float radius = info.wanderRadius * sqrt(static_cast(GeneralUtils::GenerateRandomNumber(0, 1))); //our wander radius + a bit of random range const float theta = ((static_cast(GeneralUtils::GenerateRandomNumber(0, 1)) * 2 * PI)); @@ -720,7 +720,7 @@ void BaseCombatAIComponent::OnAggro() { } m_MovementAI->SetHaltDistance(m_AttackRadius); - + NiPoint3 targetPos = target->GetPosition(); NiPoint3 currentPos = m_MovementAI->GetCurrentPosition(); @@ -731,7 +731,7 @@ void BaseCombatAIComponent::OnAggro() { else if (Vector3::DistanceSquared(m_StartPosition, targetPos) > m_HardTetherRadius * m_HardTetherRadius) //Return to spawn if we're too far { m_MovementAI->SetSpeed(m_PursuitSpeed); - + m_MovementAI->SetDestination(m_StartPosition); } else //Chase the player's new position @@ -768,7 +768,7 @@ void BaseCombatAIComponent::OnTether() { m_MovementAI->SetSpeed(m_PursuitSpeed); m_MovementAI->SetDestination(m_StartPosition); - + m_State = AiState::aggro; } else { @@ -795,7 +795,7 @@ bool BaseCombatAIComponent::GetStunImmune() const return m_StunImmune; } -void BaseCombatAIComponent::SetStunImmune(bool value) +void BaseCombatAIComponent::SetStunImmune(bool value) { m_StunImmune = value; } @@ -805,7 +805,7 @@ float BaseCombatAIComponent::GetTetherSpeed() const return m_TetherSpeed; } -void BaseCombatAIComponent::SetTetherSpeed(float value) +void BaseCombatAIComponent::SetTetherSpeed(float value) { m_TetherSpeed = value; } @@ -816,7 +816,7 @@ void BaseCombatAIComponent::Stun(const float time) { } m_StunTime = time; - + m_Stunned = true; } @@ -848,13 +848,13 @@ bool BaseCombatAIComponent::GetDistabled() const return m_Disabled; } -void BaseCombatAIComponent::Sleep() +void BaseCombatAIComponent::Sleep() { m_dpEntity->SetSleeping(true); m_dpEntityEnemy->SetSleeping(true); } -void BaseCombatAIComponent::Wake() +void BaseCombatAIComponent::Wake() { m_dpEntity->SetSleeping(false); m_dpEntityEnemy->SetSleeping(false); diff --git a/dGame/dComponents/BouncerComponent.cpp b/dGame/dComponents/BouncerComponent.cpp index 38370f39..2e24b1ed 100644 --- a/dGame/dComponents/BouncerComponent.cpp +++ b/dGame/dComponents/BouncerComponent.cpp @@ -12,7 +12,7 @@ BouncerComponent::BouncerComponent(Entity* parent) : Component(parent) { m_PetEnabled = false; m_PetBouncerEnabled = false; m_PetSwitchLoaded = false; - + if (parent->GetLOT() == 7625) { LookupPetSwitch(); @@ -34,14 +34,14 @@ Entity* BouncerComponent::GetParentEntity() const return m_Parent; } -void BouncerComponent::SetPetEnabled(bool value) +void BouncerComponent::SetPetEnabled(bool value) { m_PetEnabled = value; EntityManager::Instance()->SerializeEntity(m_Parent); } -void BouncerComponent::SetPetBouncerEnabled(bool value) +void BouncerComponent::SetPetBouncerEnabled(bool value) { m_PetBouncerEnabled = value; @@ -57,7 +57,7 @@ void BouncerComponent::SetPetBouncerEnabled(bool value) { GameMessages::SendStopFXEffect(m_Parent, true, "PetOnSwitch"); } - + } bool BouncerComponent::GetPetEnabled() const @@ -70,7 +70,7 @@ bool BouncerComponent::GetPetBouncerEnabled() const return m_PetBouncerEnabled; } -void BouncerComponent::LookupPetSwitch() +void BouncerComponent::LookupPetSwitch() { const auto& groups = m_Parent->GetGroups(); @@ -85,21 +85,21 @@ void BouncerComponent::LookupPetSwitch() if (switchComponent != nullptr) { switchComponent->SetPetBouncer(this); - + m_PetSwitchLoaded = true; m_PetEnabled = true; EntityManager::Instance()->SerializeEntity(m_Parent); - Game::logger->Log("BouncerComponent", "Loaded pet bouncer\n"); + Game::logger->Log("BouncerComponent", "Loaded pet bouncer"); } } } if (!m_PetSwitchLoaded) { - Game::logger->Log("BouncerComponent", "Failed to load pet bouncer\n"); - + Game::logger->Log("BouncerComponent", "Failed to load pet bouncer"); + m_Parent->AddCallbackTimer(0.5f, [this]() { LookupPetSwitch(); }); diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index dcc74214..5874f8a6 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -49,11 +49,11 @@ void BuffComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUp outBitStream->Write(0); } } - + outBitStream->Write0(); } -void BuffComponent::Update(float deltaTime) +void BuffComponent::Update(float deltaTime) { /** * Loop through all buffs and apply deltaTime to ther time. @@ -138,7 +138,7 @@ void BuffComponent::ApplyBuff(const int32_t id, const float duration, const LWOO m_Buffs.emplace(id, buff); } -void BuffComponent::RemoveBuff(int32_t id) +void BuffComponent::RemoveBuff(int32_t id) { const auto& iter = m_Buffs.find(id); @@ -146,18 +146,18 @@ void BuffComponent::RemoveBuff(int32_t id) { return; } - + m_Buffs.erase(iter); RemoveBuffEffect(id); } -bool BuffComponent::HasBuff(int32_t id) +bool BuffComponent::HasBuff(int32_t id) { return m_Buffs.find(id) != m_Buffs.end(); } -void BuffComponent::ApplyBuffEffect(int32_t id) +void BuffComponent::ApplyBuffEffect(int32_t id) { const auto& parameters = GetBuffParameters(id); for (const auto& parameter : parameters) @@ -209,7 +209,7 @@ void BuffComponent::ApplyBuffEffect(int32_t id) } } -void BuffComponent::RemoveBuffEffect(int32_t id) +void BuffComponent::RemoveBuffEffect(int32_t id) { const auto& parameters = GetBuffParameters(id); for (const auto& parameter : parameters) @@ -261,7 +261,7 @@ void BuffComponent::RemoveBuffEffect(int32_t id) } } -void BuffComponent::RemoveAllBuffs() +void BuffComponent::RemoveAllBuffs() { for (const auto& buff : m_Buffs) { @@ -271,12 +271,12 @@ void BuffComponent::RemoveAllBuffs() m_Buffs.clear(); } -void BuffComponent::Reset() +void BuffComponent::Reset() { RemoveAllBuffs(); } -void BuffComponent::ReApplyBuffs() +void BuffComponent::ReApplyBuffs() { for (const auto& buff : m_Buffs) { @@ -293,10 +293,10 @@ void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { // Load buffs auto* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); - + // Make sure we have a clean buff element. auto* buffElement = dest->FirstChildElement("buff"); - + // Old character, no buffs to load if (buffElement == nullptr) { @@ -328,14 +328,14 @@ void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) } } -void BuffComponent::UpdateXml(tinyxml2::XMLDocument* doc) +void BuffComponent::UpdateXml(tinyxml2::XMLDocument* doc) { // Save buffs auto* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); - + // Make sure we have a clean buff element. auto* buffElement = dest->FirstChildElement("buff"); - + if (buffElement == nullptr) { buffElement = doc->NewElement("buff"); @@ -357,12 +357,12 @@ void BuffComponent::UpdateXml(tinyxml2::XMLDocument* doc) buffEntry->SetAttribute("s", buff.second.stacks); buffEntry->SetAttribute("sr", buff.second.source); buffEntry->SetAttribute("b", buff.second.behaviorID); - + buffElement->LinkEndChild(buffEntry); } } -const std::vector& BuffComponent::GetBuffParameters(int32_t buffId) +const std::vector& BuffComponent::GetBuffParameters(int32_t buffId) { const auto& pair = m_Cache.find(buffId); @@ -376,7 +376,7 @@ const std::vector& BuffComponent::GetBuffParameters(int32_t buffI query.bind(1, (int) buffId); auto result = query.execQuery(); - + std::vector parameters {}; while (!result.eof()) @@ -402,7 +402,7 @@ const std::vector& BuffComponent::GetBuffParameters(int32_t buffI } catch (std::invalid_argument& exception) { - Game::logger->Log("BuffComponent", "Failed to parse value (%s): (%s)!\n", token.c_str(), exception.what()); + Game::logger->Log("BuffComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); } } } @@ -411,7 +411,7 @@ const std::vector& BuffComponent::GetBuffParameters(int32_t buffI result.nextRow(); } - + m_Cache.insert_or_assign(buffId, parameters); return m_Cache.find(buffId)->second; diff --git a/dGame/dComponents/BuildBorderComponent.cpp b/dGame/dComponents/BuildBorderComponent.cpp index 1747f0ed..c565af97 100644 --- a/dGame/dComponents/BuildBorderComponent.cpp +++ b/dGame/dComponents/BuildBorderComponent.cpp @@ -26,8 +26,8 @@ void BuildBorderComponent::OnUse(Entity* originator) { if (!entities.empty()) { buildArea = entities[0]->GetObjectID(); - - Game::logger->Log("BuildBorderComponent", "Using PropertyPlaque\n"); + + Game::logger->Log("BuildBorderComponent", "Using PropertyPlaque"); } auto* inventoryComponent = originator->GetComponent(); @@ -44,7 +44,7 @@ void BuildBorderComponent::OnUse(Entity* originator) { inventoryComponent->PushEquippedItems(); - Game::logger->Log("BuildBorderComponent", "Starting with %llu\n", buildArea); + Game::logger->Log("BuildBorderComponent", "Starting with %llu", buildArea); if (PropertyManagementComponent::Instance() != nullptr) { GameMessages::SendStartArrangingWithItem( diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index f854c2b8..1f726a79 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -41,7 +41,7 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C if (character->GetZoneID() != Game::server->GetZoneID()) { m_IsLanding = true; } - + if (LandingAnimDisabled(character->GetZoneID()) || LandingAnimDisabled(Game::server->GetZoneID()) || m_LastRocketConfig.empty()) { m_IsLanding = false; //Don't make us land on VE/minigames lol } @@ -77,13 +77,13 @@ CharacterComponent::~CharacterComponent() { } void CharacterComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - + if (bIsInitialUpdate) { outBitStream->Write0(); outBitStream->Write0(); outBitStream->Write0(); outBitStream->Write0(); - + outBitStream->Write(m_Character->GetHairColor()); outBitStream->Write(m_Character->GetHairStyle()); outBitStream->Write(0); //Default "head" @@ -128,7 +128,7 @@ void CharacterComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInit outBitStream->Write(m_RacingSmashablesSmashed); outBitStream->Write(m_RacesFinished); outBitStream->Write(m_FirstPlaceRaceFinishes); - + outBitStream->Write0(); outBitStream->Write(m_IsLanding); if (m_IsLanding) { @@ -147,17 +147,17 @@ void CharacterComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInit outBitStream->Write(m_EditorEnabled); outBitStream->Write(m_EditorLevel); } - + outBitStream->Write(m_DirtyCurrentActivity); if (m_DirtyCurrentActivity) outBitStream->Write(m_CurrentActivity); - + outBitStream->Write(m_DirtySocialInfo); if (m_DirtySocialInfo) { outBitStream->Write(m_GuildID); outBitStream->Write(static_cast(m_GuildName.size())); if (!m_GuildName.empty()) outBitStream->WriteBits(reinterpret_cast(m_GuildName.c_str()), static_cast(m_GuildName.size()) * sizeof(wchar_t) * 8); - + outBitStream->Write(m_IsLEGOClubMember); outBitStream->Write(m_CountryCode); } @@ -171,7 +171,7 @@ bool CharacterComponent::GetPvpEnabled() const void CharacterComponent::SetPvpEnabled(const bool value) { m_DirtyGMInfo = true; - + m_PvpEnabled = value; } @@ -183,15 +183,16 @@ void CharacterComponent::SetGMLevel(int gmlevel) { } void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { + tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { - Game::logger->Log("CharacterComponent", "Failed to find char tag while loading XML!\n"); + Game::logger->Log("CharacterComponent", "Failed to find char tag while loading XML!"); return; } if (character->QueryAttribute("rpt", &m_Reputation) == tinyxml2::XML_NO_ATTRIBUTE) { SetReputation(0); } - + character->QueryInt64Attribute("ls", &m_Uscore); // Load the statistics @@ -280,11 +281,11 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* minifig = doc->FirstChildElement("obj")->FirstChildElement("mf"); if (!minifig) { - Game::logger->Log("CharacterComponent", "Failed to find mf tag while updating XML!\n"); + Game::logger->Log("CharacterComponent", "Failed to find mf tag while updating XML!"); return; } - // write minifig information that might have been changed by commands + // write minifig information that might have been changed by commands minifig->SetAttribute("es", m_Character->GetEyebrows()); minifig->SetAttribute("ess", m_Character->GetEyes()); @@ -300,7 +301,7 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { - Game::logger->Log("CharacterComponent", "Failed to find char tag while updating XML!\n"); + Game::logger->Log("CharacterComponent", "Failed to find char tag while updating XML!"); return; } @@ -350,7 +351,7 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { // auto newUpdateTimestamp = std::time(nullptr); - Game::logger->Log("TotalTimePlayed", "Time since last save: %d\n", newUpdateTimestamp - m_LastUpdateTimestamp); + Game::logger->Log("TotalTimePlayed", "Time since last save: %d", newUpdateTimestamp - m_LastUpdateTimestamp); m_TotalTimePlayed += newUpdateTimestamp - m_LastUpdateTimestamp; character->SetAttribute("time", m_TotalTimePlayed); @@ -380,7 +381,7 @@ Item* CharacterComponent::GetRocket(Entity* player) { } if (!rocket) { - Game::logger->Log("CharacterComponent", "Unable to find rocket to equip!\n"); + Game::logger->Log("CharacterComponent", "Unable to find rocket to equip!"); return rocket; } return rocket; diff --git a/dGame/dComponents/ControllablePhysicsComponent.cpp b/dGame/dComponents/ControllablePhysicsComponent.cpp index 5d9cdd40..19c17035 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/ControllablePhysicsComponent.cpp @@ -36,7 +36,7 @@ ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Com return; if (entity->GetLOT() == 1) { - Game::logger->Log("ControllablePhysicsComponent", "Using patch to load minifig physics\n"); + Game::logger->Log("ControllablePhysicsComponent", "Using patch to load minifig physics"); float radius = 1.5f; m_dpEntity = new dpEntity(m_Parent->GetObjectID(), radius, false); @@ -133,10 +133,10 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bo void ControllablePhysicsComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { - Game::logger->Log("ControllablePhysicsComponent", "Failed to find char tag!\n"); + Game::logger->Log("ControllablePhysicsComponent", "Failed to find char tag!"); return; } - + m_Parent->GetCharacter()->LoadXmlRespawnCheckpoints(); character->QueryAttribute("lzx", &m_Position.x); @@ -159,7 +159,7 @@ void ControllablePhysicsComponent::ResetFlags() { void ControllablePhysicsComponent::UpdateXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { - Game::logger->Log("ControllablePhysicsComponent", "Failed to find char tag while updating XML!\n"); + Game::logger->Log("ControllablePhysicsComponent", "Failed to find char tag while updating XML!"); return; } @@ -254,7 +254,7 @@ void ControllablePhysicsComponent::RemovePickupRadiusScale(float value) { if (pos != m_ActivePickupRadiusScales.end()) { m_ActivePickupRadiusScales.erase(pos); } else { - Game::logger->Log("ControllablePhysicsComponent", "Warning: Could not find pickup radius %f in list of active radii. List has %i active radii.\n", value, m_ActivePickupRadiusScales.size()); + Game::logger->Log("ControllablePhysicsComponent", "Warning: Could not find pickup radius %f in list of active radii. List has %i active radii.", value, m_ActivePickupRadiusScales.size()); return; } diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index e7a6d385..c2532f42 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -162,7 +162,7 @@ void DestroyableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIn void DestroyableComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); if (!dest) { - Game::logger->Log("DestroyableComponent", "Failed to find dest tag!\n"); + Game::logger->Log("DestroyableComponent", "Failed to find dest tag!"); return; } @@ -184,7 +184,7 @@ void DestroyableComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { void DestroyableComponent::UpdateXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); if (!dest) { - Game::logger->Log("DestroyableComponent", "Failed to find dest tag!\n"); + Game::logger->Log("DestroyableComponent", "Failed to find dest tag!"); return; } @@ -246,7 +246,7 @@ void DestroyableComponent::SetArmor(int32_t value) { // If Destroyable Component already has zero armor do not trigger the passive ability again. bool hadArmor = m_iArmor > 0; - + auto* characterComponent = m_Parent->GetComponent(); if (characterComponent != nullptr) { characterComponent->TrackArmorDelta(value - m_iArmor); @@ -499,7 +499,7 @@ bool DestroyableComponent::CheckValidity(const LWOOBJID target, const bool ignor if (targetEntity == nullptr) { - Game::logger->Log("DestroyableComponent", "Invalid entity for checking validity (%llu)!\n", target); + Game::logger->Log("DestroyableComponent", "Invalid entity for checking validity (%llu)!", target); return false; } @@ -777,22 +777,22 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType else { //Check if this zone allows coin drops - if (dZoneManager::Instance()->GetPlayerLoseCoinOnDeath()) + if (dZoneManager::Instance()->GetPlayerLoseCoinOnDeath()) { auto* character = m_Parent->GetCharacter(); uint64_t coinsTotal = character->GetCoins(); - if (coinsTotal > 0) + if (coinsTotal > 0) { uint64_t coinsToLoose = 1; - if (coinsTotal >= 200) + if (coinsTotal >= 200) { float hundreth = (coinsTotal / 100.0f); coinsToLoose = static_cast(hundreth); } - if (coinsToLoose > 10000) + if (coinsToLoose > 10000) { coinsToLoose = 10000; } diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 0772482c..ea6c8368 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -157,7 +157,7 @@ void InventoryComponent::AddItem( { if (count == 0) { - Game::logger->Log("InventoryComponent", "Attempted to add 0 of item (%i) to the inventory!\n", lot); + Game::logger->Log("InventoryComponent", "Attempted to add 0 of item (%i) to the inventory!", lot); return; } @@ -166,7 +166,7 @@ void InventoryComponent::AddItem( { if (lot > 0) { - Game::logger->Log("InventoryComponent", "Attempted to add invalid item (%i) to the inventory!\n", lot); + Game::logger->Log("InventoryComponent", "Attempted to add invalid item (%i) to the inventory!", lot); } return; @@ -187,7 +187,7 @@ void InventoryComponent::AddItem( if (slot == -1) { - Game::logger->Log("InventoryComponent", "Failed to find empty slot for inventory (%i)!\n", inventoryType); + Game::logger->Log("InventoryComponent", "Failed to find empty slot for inventory (%i)!", inventoryType); return; } @@ -303,7 +303,7 @@ void InventoryComponent::RemoveItem(const LOT lot, const uint32_t count, eInvent { if (count == 0) { - Game::logger->Log("InventoryComponent", "Attempted to remove 0 of item (%i) from the inventory!\n", lot); + Game::logger->Log("InventoryComponent", "Attempted to remove 0 of item (%i) from the inventory!", lot); return; } @@ -532,7 +532,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) if (inventoryElement == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find 'inv' xml element!\n"); + Game::logger->Log("InventoryComponent", "Failed to find 'inv' xml element!"); return; } @@ -541,7 +541,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) if (bags == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find 'bags' xml element!\n"); + Game::logger->Log("InventoryComponent", "Failed to find 'bags' xml element!"); return; } @@ -569,7 +569,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) if (items == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find 'items' xml element!\n"); + Game::logger->Log("InventoryComponent", "Failed to find 'items' xml element!"); return; } @@ -586,7 +586,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) if (inventory == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find inventory (%i)!\n", type); + Game::logger->Log("InventoryComponent", "Failed to find inventory (%i)!", type); return; } @@ -666,7 +666,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) if (inventoryElement == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find 'inv' xml element!\n"); + Game::logger->Log("InventoryComponent", "Failed to find 'inv' xml element!"); return; } @@ -691,7 +691,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) if (bags == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find 'bags' xml element!\n"); + Game::logger->Log("InventoryComponent", "Failed to find 'bags' xml element!"); return; } @@ -712,7 +712,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) if (items == nullptr) { - Game::logger->Log("InventoryComponent", "Failed to find 'items' xml element!\n"); + Game::logger->Log("InventoryComponent", "Failed to find 'items' xml element!"); return; } @@ -819,7 +819,7 @@ void InventoryComponent::Serialize(RakNet::BitStream* outBitStream, const bool b outBitStream->Write(0); // Don't compress outBitStream->Write(ldfStream); } - + outBitStream->Write1(); } @@ -932,9 +932,9 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) const auto building = character->GetBuildMode(); const auto type = static_cast(item->GetInfo().itemType); - + if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == false) - { + { auto startPosition = m_Parent->GetPosition(); auto startRotation = NiQuaternion::LookAt(startPosition, startPosition + NiPoint3::UNIT_X); @@ -1055,11 +1055,11 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) } GenerateProxies(item); - + UpdateSlot(item->GetInfo().equipLocation, { item->GetId(), item->GetLot(), item->GetCount(), item->GetSlot(), item->GetConfig() }); ApplyBuff(item); - + AddItemSkills(item->GetLot()); EntityManager::Instance()->SerializeEntity(m_Parent); @@ -1087,7 +1087,7 @@ void InventoryComponent::UnEquipItem(Item* item) } RemoveBuff(item); - + RemoveItemSkills(item->GetLot()); RemoveSlot(item->GetInfo().equipLocation); @@ -1162,7 +1162,7 @@ void InventoryComponent::PopEquippedItems() m_Pushed.clear(); auto destroyableComponent = m_Parent->GetComponent(); - + // Reset stats to full if (destroyableComponent) { destroyableComponent->SetHealth(static_cast(destroyableComponent->GetMaxHealth())); @@ -1265,10 +1265,10 @@ void InventoryComponent::AddItemSkills(const LOT lot) if (index != m_Skills.end()) { const auto old = index->second; - + GameMessages::SendRemoveSkill(m_Parent, old); } - + GameMessages::SendAddSkill(m_Parent, skill, static_cast(slot)); m_Skills.insert_or_assign(slot, skill); @@ -1474,7 +1474,7 @@ std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip if (entry.skillID == 0) { - Game::logger->Log("InventoryComponent", "Failed to find buff behavior for skill (%i)!\n", result.skillID); + Game::logger->Log("InventoryComponent", "Failed to find buff behavior for skill (%i)!", result.skillID); continue; } @@ -1483,7 +1483,7 @@ std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip { missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, result.skillID); } - + // If item is not a proxy, add its buff to the added buffs. if (item->GetParent() == LWOOBJID_EMPTY) buffs.push_back(static_cast(entry.behaviorID)); } @@ -1553,7 +1553,7 @@ std::vector InventoryComponent::GenerateProxies(Item* parent) } catch (std::invalid_argument& exception) { - Game::logger->Log("InventoryComponent", "Failed to parse proxy (%s): (%s)!\n", segment.c_str(), exception.what()); + Game::logger->Log("InventoryComponent", "Failed to parse proxy (%s): (%s)!", segment.c_str(), exception.what()); } } diff --git a/dGame/dComponents/LevelProgressionComponent.cpp b/dGame/dComponents/LevelProgressionComponent.cpp index 96d31970..ff4f3f85 100644 --- a/dGame/dComponents/LevelProgressionComponent.cpp +++ b/dGame/dComponents/LevelProgressionComponent.cpp @@ -12,7 +12,7 @@ LevelProgressionComponent::LevelProgressionComponent(Entity* parent) : Component void LevelProgressionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); if (!level) { - Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while updating XML!\n"); + Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while updating XML!"); return; } level->SetAttribute("l", m_Level); @@ -22,7 +22,7 @@ void LevelProgressionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc){ tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); if (!level) { - Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while loading XML!\n"); + Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while loading XML!"); return; } level->QueryAttribute("l", &m_Level); diff --git a/dGame/dComponents/MissionComponent.cpp b/dGame/dComponents/MissionComponent.cpp index 1b809f48..03cb65ea 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -220,7 +220,7 @@ void MissionComponent::ForceProgressTaskType(const uint32_t missionId, const uin } } -void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission) +void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission) { auto* mission = GetMission(missionId); @@ -357,7 +357,7 @@ bool MissionComponent::LookForAchievements(MissionTaskType type, int32_t value, } } catch (std::invalid_argument& exception) { - Game::logger->Log("MissionComponent", "Failed to parse target (%s): (%s)!\n", token.c_str(), exception.what()); + Game::logger->Log("MissionComponent", "Failed to parse target (%s): (%s)!", token.c_str(), exception.what()); } } @@ -383,7 +383,7 @@ bool MissionComponent::LookForAchievements(MissionTaskType type, int32_t value, #endif } -const std::vector& MissionComponent::QueryAchievements(MissionTaskType type, int32_t value, const std::string targets) { +const std::vector& MissionComponent::QueryAchievements(MissionTaskType type, int32_t value, const std::string targets) { // Create a hash which represent this query for achievements size_t hash = 0; GeneralUtils::hash_combine(hash, type); @@ -471,7 +471,7 @@ bool MissionComponent::RequiresItem(const LOT lot) { } result.finalize(); - + for (const auto& pair : m_Missions) { auto* mission = pair.second; @@ -594,7 +594,7 @@ void MissionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { } } -void MissionComponent::AddCollectible(int32_t collectibleID) +void MissionComponent::AddCollectible(int32_t collectibleID) { // Check if this collectible is already in the list if (HasCollectible(collectibleID)) { @@ -604,12 +604,12 @@ void MissionComponent::AddCollectible(int32_t collectibleID) m_Collectibles.push_back(collectibleID); } -bool MissionComponent::HasCollectible(int32_t collectibleID) +bool MissionComponent::HasCollectible(int32_t collectibleID) { return std::find(m_Collectibles.begin(), m_Collectibles.end(), collectibleID) != m_Collectibles.end(); } -bool MissionComponent::HasMission(uint32_t missionId) +bool MissionComponent::HasMission(uint32_t missionId) { return GetMission(missionId) != nullptr; } \ No newline at end of file diff --git a/dGame/dComponents/MissionOfferComponent.cpp b/dGame/dComponents/MissionOfferComponent.cpp index 8a9abb57..6e44d2e3 100644 --- a/dGame/dComponents/MissionOfferComponent.cpp +++ b/dGame/dComponents/MissionOfferComponent.cpp @@ -50,7 +50,7 @@ MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot // Now lookup the missions in the MissionNPCComponent table auto* missionNpcComponentTable = CDClientManager::Instance()->GetTable("MissionNPCComponent"); - + auto missions = missionNpcComponentTable->Query([=](const CDMissionNPCComponent& entry) { return entry.id == static_cast(componentId); @@ -73,11 +73,11 @@ MissionOfferComponent::~MissionOfferComponent() mission = nullptr; } } - + offeredMissions.clear(); } -void MissionOfferComponent::OnUse(Entity* originator) +void MissionOfferComponent::OnUse(Entity* originator) { OfferMissions(originator); } @@ -86,9 +86,9 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi { // First, get the entity's MissionComponent. If there is not one, then we cannot offer missions to this entity. auto* missionComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION)); - + if (!missionComponent) { - Game::logger->Log("MissionOfferComponent", "Unable to get mission component for Entity %llu\n", entity->GetObjectID()); + Game::logger->Log("MissionOfferComponent", "Unable to get mission component for Entity %llu", entity->GetObjectID()); return; } @@ -137,7 +137,7 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi continue; } } - + const auto canAccept = MissionPrerequisites::CanAccept(missionId, missionComponent->GetMissions()); // Mission has not yet been accepted - check the prereqs @@ -148,10 +148,10 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi { continue; } - + const auto& randomPool = info.randomPool; const auto isRandom = info.isRandom; - + if (isRandom && randomPool.empty()) // This means the mission is part of a random pool of missions. { continue; @@ -163,7 +163,7 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi std::string token; std::vector randomMissionPool; - + while (std::getline(stream, token, ',')) { try @@ -174,7 +174,7 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi } catch (std::invalid_argument& exception) { - Game::logger->Log("MissionOfferComponent", "Failed to parse value (%s): (%s)!\n", token.c_str(), exception.what()); + Game::logger->Log("MissionOfferComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); } } @@ -195,7 +195,7 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi for (const auto sample : randomMissionPool) { const auto state = missionComponent->GetMissionState(sample); - + if (state == MissionState::MISSION_STATE_ACTIVE || state == MissionState::MISSION_STATE_COMPLETE_ACTIVE || state == MissionState::MISSION_STATE_READY_TO_COMPLETE || @@ -212,10 +212,10 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), sample, m_Parent->GetObjectID()); canAcceptPool.clear(); - + break; } - + if (std::find(offered.begin(), offered.end(), sample) == offered.end() && MissionPrerequisites::CanAccept(sample, missionComponent->GetMissions())) { canAcceptPool.push_back(sample); diff --git a/dGame/dComponents/MovingPlatformComponent.cpp b/dGame/dComponents/MovingPlatformComponent.cpp index bf3ea9d5..4e99e6d6 100644 --- a/dGame/dComponents/MovingPlatformComponent.cpp +++ b/dGame/dComponents/MovingPlatformComponent.cpp @@ -20,12 +20,12 @@ MoverSubComponent::MoverSubComponent(const NiPoint3& startPos) { mDesiredWaypointIndex = 0; // -1; mInReverse = false; mShouldStopAtDesiredWaypoint = false; - + mPercentBetweenPoints = 0.0f; - + mCurrentWaypointIndex = 0; mNextWaypointIndex = 0; //mCurrentWaypointIndex + 1; - + mIdleTimeElapsed = 0.0f; } @@ -38,16 +38,16 @@ void MoverSubComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIniti outBitStream->Write(mDesiredWaypointIndex); outBitStream->Write(mShouldStopAtDesiredWaypoint); outBitStream->Write(mInReverse); - + outBitStream->Write(mPercentBetweenPoints); outBitStream->Write(mPosition.x); outBitStream->Write(mPosition.y); outBitStream->Write(mPosition.z); - + outBitStream->Write(mCurrentWaypointIndex); outBitStream->Write(mNextWaypointIndex); - + outBitStream->Write(mIdleTimeElapsed); outBitStream->Write(0.0f); // Move time elapsed } @@ -62,7 +62,7 @@ MovingPlatformComponent::MovingPlatformComponent(Entity* parent, const std::stri m_NoAutoStart = false; if (m_Path == nullptr) { - Game::logger->Log("MovingPlatformComponent", "Path not found: %s\n", pathName.c_str()); + Game::logger->Log("MovingPlatformComponent", "Path not found: %s", pathName.c_str()); } } @@ -72,7 +72,7 @@ MovingPlatformComponent::~MovingPlatformComponent() { void MovingPlatformComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { // Here we don't serialize the moving platform to let the client simulate the movement - + if (!m_Serialize) { outBitStream->Write(false); @@ -89,7 +89,7 @@ void MovingPlatformComponent::Serialize(RakNet::BitStream* outBitStream, bool bI if (hasPath) { // Is on rail outBitStream->Write1(); - + outBitStream->Write(static_cast(m_PathName.size())); for (const auto& c : m_PathName) { outBitStream->Write(static_cast(c)); @@ -128,7 +128,7 @@ void MovingPlatformComponent::OnCompleteRebuild() { StartPathing(); } -void MovingPlatformComponent::SetMovementState(MovementPlatformState value) +void MovingPlatformComponent::SetMovementState(MovementPlatformState value) { auto* subComponent = static_cast(m_MoverSubComponent); @@ -137,10 +137,10 @@ void MovingPlatformComponent::SetMovementState(MovementPlatformState value) EntityManager::Instance()->SerializeEntity(m_Parent); } -void MovingPlatformComponent::GotoWaypoint(uint32_t index, bool stopAtWaypoint) +void MovingPlatformComponent::GotoWaypoint(uint32_t index, bool stopAtWaypoint) { auto* subComponent = static_cast(m_MoverSubComponent); - + subComponent->mDesiredWaypointIndex = index; subComponent->mNextWaypointIndex = index; subComponent->mShouldStopAtDesiredWaypoint = stopAtWaypoint; @@ -148,13 +148,13 @@ void MovingPlatformComponent::GotoWaypoint(uint32_t index, bool stopAtWaypoint) StartPathing(); } -void MovingPlatformComponent::StartPathing() +void MovingPlatformComponent::StartPathing() { //GameMessages::SendStartPathing(m_Parent); m_PathingStopped = false; - + auto* subComponent = static_cast(m_MoverSubComponent); - + subComponent->mShouldStopAtDesiredWaypoint = true; subComponent->mState = MovementPlatformState::Stationary; @@ -206,7 +206,7 @@ void MovingPlatformComponent::StartPathing() void MovingPlatformComponent::ContinuePathing() { auto* subComponent = static_cast(m_MoverSubComponent); - + subComponent->mState = MovementPlatformState::Stationary; subComponent->mCurrentWaypointIndex = subComponent->mNextWaypointIndex; @@ -258,7 +258,7 @@ void MovingPlatformComponent::ContinuePathing() case PathBehavior::Once: EntityManager::Instance()->SerializeEntity(m_Parent); return; - + case PathBehavior::Bounce: subComponent->mInReverse = true; break; @@ -266,7 +266,7 @@ void MovingPlatformComponent::ContinuePathing() case PathBehavior::Loop: subComponent->mNextWaypointIndex = 0; break; - + default: break; } @@ -347,7 +347,7 @@ void MovingPlatformComponent::StopPathing() //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); } -void MovingPlatformComponent::SetSerialized(bool value) +void MovingPlatformComponent::SetSerialized(bool value) { m_Serialize = value; } @@ -357,7 +357,7 @@ bool MovingPlatformComponent::GetNoAutoStart() const return m_NoAutoStart; } -void MovingPlatformComponent::SetNoAutoStart(const bool value) +void MovingPlatformComponent::SetNoAutoStart(const bool value) { m_NoAutoStart = value; } diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 3cfb4e8d..0151fbf4 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -98,7 +98,7 @@ PetComponent::PetComponent(Entity* parent, uint32_t componentId) : Component(par result.finalize(); } -void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) +void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { const bool tamed = m_Owner != LWOOBJID_EMPTY; @@ -114,7 +114,7 @@ void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpd { outBitStream->Write(m_Interaction); } - + outBitStream->Write(tamed); if (tamed) { @@ -143,7 +143,7 @@ void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpd } } -void PetComponent::OnUse(Entity* originator) +void PetComponent::OnUse(Entity* originator) { if (m_Owner != LWOOBJID_EMPTY) { @@ -158,7 +158,7 @@ void PetComponent::OnUse(Entity* originator) { return; } - + m_Tamer = LWOOBJID_EMPTY; } @@ -179,7 +179,7 @@ void PetComponent::OnUse(Entity* originator) { movementAIComponent->Stop(); } - + inventoryComponent->DespawnPet(); const auto& cached = buildCache.find(m_Parent->GetLOT()); @@ -245,7 +245,7 @@ void PetComponent::OnUse(Entity* originator) } auto* destroyableComponent = originator->GetComponent(); - + if (destroyableComponent == nullptr) { return; @@ -263,7 +263,7 @@ void PetComponent::OnUse(Entity* originator) if (bricks.empty()) { ChatPackets::SendSystemMessage(originator->GetSystemAddress(), u"Failed to load the puzzle minigame for this pet."); - Game::logger->Log("PetComponent", "Couldn't find %s for minigame!\n", buildFile.c_str()); + Game::logger->Log("PetComponent", "Couldn't find %s for minigame!", buildFile.c_str()); return; } @@ -282,7 +282,7 @@ void PetComponent::OnUse(Entity* originator) } auto position = originatorPosition; - + NiPoint3 forward = NiQuaternion::LookAt(m_Parent->GetPosition(), originator->GetPosition()).GetForwardVector(); forward.y = 0; @@ -297,7 +297,7 @@ void PetComponent::OnUse(Entity* originator) const NiPoint3 forward = m_Parent->GetRotation().GetForwardVector(); attempt = originatorPosition + forward * interactionDistance; - + y = dpWorld::Instance().GetHeightAtPoint(attempt); interactionDistance -= 0.5f; @@ -309,10 +309,10 @@ void PetComponent::OnUse(Entity* originator) { position = petPosition + forward * interactionDistance; } - + auto rotation = NiQuaternion::LookAt(position, petPosition); - + GameMessages::SendNotifyPetTamingMinigame( originator->GetObjectID(), m_Parent->GetObjectID(), @@ -350,7 +350,7 @@ void PetComponent::OnUse(Entity* originator) } } -void PetComponent::Update(float deltaTime) +void PetComponent::Update(float deltaTime) { if (m_StartPosition == NiPoint3::ZERO) { @@ -422,7 +422,7 @@ void PetComponent::Update(float deltaTime) } m_TresureTime -= deltaTime; - + m_MovementAI->Stop(); if (m_TresureTime <= 0) @@ -466,7 +466,7 @@ void PetComponent::Update(float deltaTime) if (m_Timer > 0) { m_Timer -= deltaTime; - + return; } @@ -509,7 +509,7 @@ void PetComponent::Update(float deltaTime) if (distance < 3 * 3) { m_Interaction = closestTresure->GetObjectID(); - + Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 1, 202, true); m_TresureTime = 2; @@ -525,7 +525,7 @@ void PetComponent::Update(float deltaTime) skipTresure: m_MovementAI->SetHaltDistance(haltDistance); - + m_MovementAI->SetSpeed(2.5f); m_MovementAI->SetDestination(destination); @@ -573,7 +573,7 @@ void PetComponent::TryBuild(uint32_t numBricks, bool clientFailed) { GameMessages::SendPetTamingTryBuildResult(m_Tamer, !clientFailed, numBricks, tamer->GetSystemAddress()); } -void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) +void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { if (m_Tamer == LWOOBJID_EMPTY) return; @@ -603,7 +603,7 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) info.spawnerID = tamer->GetObjectID(); auto* modelEntity = EntityManager::Instance()->CreateEntity(info); - + m_ModelId = modelEntity->GetObjectID(); EntityManager::Instance()->ConstructEntity(modelEntity); @@ -625,26 +625,26 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) petSubKey = GeneralUtils::SetBit(petSubKey, OBJECT_BIT_PERSISTENT); m_DatabaseId = petSubKey; - + std::string petName = tamer->GetCharacter()->GetName(); petName += "'s Pet"; GameMessages::SendAddPetToPlayer(m_Tamer, 0, GeneralUtils::ASCIIToUTF16(petName), petSubKey, m_Parent->GetLOT(), tamer->GetSystemAddress()); - + GameMessages::SendRegisterPetID(m_Tamer, m_Parent->GetObjectID(), tamer->GetSystemAddress()); GameMessages::SendRegisterPetDBID(m_Tamer, petSubKey, tamer->GetSystemAddress()); - + inventoryComponent->AddItem(m_Parent->GetLOT(), 1, eLootSourceType::LOOT_SOURCE_ACTIVITY, eInventoryType::MODELS, {}, LWOOBJID_EMPTY, true, false, petSubKey); auto* item = inventoryComponent->FindItemBySubKey(petSubKey, MODELS); - + if (item == nullptr) { return; } DatabasePet databasePet {}; - + databasePet.lot = m_Parent->GetLOT(); databasePet.moderationState = 1; databasePet.name = petName; @@ -687,7 +687,7 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) } } -void PetComponent::RequestSetPetName(std::u16string name) +void PetComponent::RequestSetPetName(std::u16string name) { if (m_Tamer == LWOOBJID_EMPTY) { @@ -717,7 +717,7 @@ void PetComponent::RequestSetPetName(std::u16string name) return; } - Game::logger->Log("PetComponent", "Got set pet name (%s)\n", GeneralUtils::UTF16ToWTF8(name).c_str()); + Game::logger->Log("PetComponent", "Got set pet name (%s)", GeneralUtils::UTF16ToWTF8(name).c_str()); auto* inventoryComponent = tamer->GetComponent(); @@ -770,7 +770,7 @@ void PetComponent::RequestSetPetName(std::u16string name) } } -void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) +void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) { if (m_Tamer == LWOOBJID_EMPTY) return; @@ -804,7 +804,7 @@ void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) SetStatus(67108866); m_Tamer = LWOOBJID_EMPTY; m_Timer = 0; - + EntityManager::Instance()->SerializeEntity(m_Parent); // Notify the end of a pet taming minigame @@ -813,7 +813,7 @@ void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) } } -void PetComponent::StartTimer() +void PetComponent::StartTimer() { const auto& cached = buildCache.find(m_Parent->GetLOT()); @@ -825,8 +825,8 @@ void PetComponent::StartTimer() m_Timer = cached->second.timeLimit; } -void PetComponent::ClientFailTamingMinigame() -{ +void PetComponent::ClientFailTamingMinigame() +{ if (m_Tamer == LWOOBJID_EMPTY) return; auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); @@ -859,7 +859,7 @@ void PetComponent::ClientFailTamingMinigame() SetStatus(67108866); m_Tamer = LWOOBJID_EMPTY; m_Timer = 0; - + EntityManager::Instance()->SerializeEntity(m_Parent); // Notify the end of a pet taming minigame @@ -868,7 +868,7 @@ void PetComponent::ClientFailTamingMinigame() } } -void PetComponent::Wander() +void PetComponent::Wander() { m_MovementAI = m_Parent->GetComponent(); @@ -877,12 +877,12 @@ void PetComponent::Wander() } m_MovementAI->SetHaltDistance(0); - + const auto& info = m_MovementAI->GetInfo(); const auto div = static_cast(info.wanderDelayMax); m_Timer = (div == 0 ? 0 : GeneralUtils::GenerateRandomNumber(0, div)) + info.wanderDelayMin; //set a random timer to stay put. - + const float radius = info.wanderRadius * sqrt(static_cast(GeneralUtils::GenerateRandomNumber(0, 1))); //our wander radius + a bit of random range const float theta = ((static_cast(GeneralUtils::GenerateRandomNumber(0, 1)) * 2 * PI)); @@ -912,13 +912,13 @@ void PetComponent::Wander() m_Timer += (m_MovementAI->GetCurrentPosition().x - destination.x) / info.wanderSpeed; } -void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) +void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) { AddDrainImaginationTimer(item, fromTaming); m_ItemId = item->GetId(); m_DatabaseId = item->GetSubKey(); - + auto* inventoryComponent = item->GetInventory()->GetComponent(); if (inventoryComponent == nullptr) return; @@ -1006,10 +1006,10 @@ void PetComponent::AddDrainImaginationTimer(Item* item, bool fromTaming) { // Set this to a variable so when this is called back from the player the timer doesn't fire off. m_Parent->AddCallbackTimer(imaginationDrainRate, [playerDestroyableComponent, this, item](){ if (!playerDestroyableComponent) { - Game::logger->Log("PetComponent", "No petComponent and/or no playerDestroyableComponent\n"); + Game::logger->Log("PetComponent", "No petComponent and/or no playerDestroyableComponent"); return; } - + // If we are out of imagination despawn the pet. if (playerDestroyableComponent->GetImagination() == 0) { this->Deactivate(); @@ -1023,7 +1023,7 @@ void PetComponent::AddDrainImaginationTimer(Item* item, bool fromTaming) { }); } -void PetComponent::Deactivate() +void PetComponent::Deactivate() { GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), -1, u"despawn", "", LWOOBJID_EMPTY, 1, 1, true); @@ -1036,7 +1036,7 @@ void PetComponent::Deactivate() auto* owner = GetOwner(); if (owner == nullptr) return; - + GameMessages::SendAddPetToPlayer(m_Owner, 0, u"", LWOOBJID_EMPTY, LOT_NULL, owner->GetSystemAddress()); GameMessages::SendRegisterPetID(m_Owner, LWOOBJID_EMPTY, owner->GetSystemAddress()); @@ -1046,7 +1046,7 @@ void PetComponent::Deactivate() GameMessages::SendShowPetActionButton(m_Owner, 0, false, owner->GetSystemAddress()); } -void PetComponent::Release() +void PetComponent::Release() { auto* inventoryComponent = GetOwner()->GetComponent(); @@ -1054,7 +1054,7 @@ void PetComponent::Release() { return; } - + Deactivate(); inventoryComponent->RemoveDatabasePet(m_DatabaseId); @@ -1064,7 +1064,7 @@ void PetComponent::Release() item->SetCount(0, false, false); } -void PetComponent::Command(NiPoint3 position, LWOOBJID source, int32_t commandType, int32_t typeId, bool overrideObey) +void PetComponent::Command(NiPoint3 position, LWOOBJID source, int32_t commandType, int32_t typeId, bool overrideObey) { auto* owner = GetOwner(); @@ -1133,12 +1133,12 @@ void PetComponent::SetStatus(uint32_t value) m_Status = value; } -void PetComponent::SetAbility(PetAbilityType value) +void PetComponent::SetAbility(PetAbilityType value) { m_Ability = value; } -PetComponent* PetComponent::GetTamingPet(LWOOBJID tamer) +PetComponent* PetComponent::GetTamingPet(LWOOBJID tamer) { const auto& pair = currentActivities.find(tamer); @@ -1159,7 +1159,7 @@ PetComponent* PetComponent::GetTamingPet(LWOOBJID tamer) return entity->GetComponent(); } -PetComponent* PetComponent::GetActivePet(LWOOBJID owner) +PetComponent* PetComponent::GetActivePet(LWOOBJID owner) { const auto& pair = activePets.find(owner); @@ -1173,7 +1173,7 @@ PetComponent* PetComponent::GetActivePet(LWOOBJID owner) if (entity == nullptr) { activePets.erase(owner); - + return nullptr; } diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index e1c2e842..3c8394f6 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -30,18 +30,18 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par m_Rotation = m_Parent->GetDefaultRotation(); m_Scale = m_Parent->GetDefaultScale(); m_dpEntity = nullptr; - + m_EffectInfoDirty = false; m_PositionInfoDirty = false; - + m_IsPhysicsEffectActive = false; m_EffectType = 0; m_DirectionalMultiplier = 0.0f; - + m_MinMax = false; m_Min = 0; m_Max = 1; - + m_IsDirectional = false; m_Direction = NiPoint3(); // * m_DirectionalMultiplier @@ -82,7 +82,7 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par } // HF - RespawnPoints. Legacy respawn entity. - if (m_Parent->GetLOT() == 4945) + if (m_Parent->GetLOT() == 4945) { m_IsRespawnVolume = true; m_RespawnPos = m_Position; @@ -218,7 +218,7 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par dpWorld::Instance().AddEntity(m_dpEntity); } else { - //Game::logger->Log("PhantomPhysicsComponent", "This one is supposed to have %s\n", info->physicsAsset.c_str()); + //Game::logger->Log("PhantomPhysicsComponent", "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); @@ -262,7 +262,7 @@ void PhantomPhysicsComponent::CreatePhysics() { CDPhysicsComponentTable* physComp = CDClientManager::Instance()->GetTable("PhysicsComponent"); if (physComp == nullptr) return; - + auto info = physComp->GetByID(componentID); if (info == nullptr) return; @@ -315,15 +315,15 @@ void PhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bI m_PositionInfoDirty = false; } - + outBitStream->Write(m_EffectInfoDirty || bIsInitialUpdate); if (m_EffectInfoDirty || bIsInitialUpdate) { outBitStream->Write(m_IsPhysicsEffectActive); - + if (m_IsPhysicsEffectActive) { outBitStream->Write(m_EffectType); outBitStream->Write(m_DirectionalMultiplier); - + // forgive me father for i have sinned outBitStream->Write0(); //outBitStream->Write(m_MinMax); @@ -331,7 +331,7 @@ void PhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bI //outBitStream->Write(m_Min); //outBitStream->Write(m_Max); //} - + outBitStream->Write(m_IsDirectional); if (m_IsDirectional) { outBitStream->Write(m_Direction.x); @@ -379,7 +379,7 @@ void PhantomPhysicsComponent::SetDirection(const NiPoint3& pos) { m_Direction.x *= m_DirectionalMultiplier; m_Direction.y *= m_DirectionalMultiplier; m_Direction.z *= m_DirectionalMultiplier; - + m_EffectInfoDirty = true; m_IsDirectional = true; } diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index 4be059ed..5bc24a9f 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -192,7 +192,7 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl const auto query = BuildQuery(entity, sortMethod, character); auto propertyLookup = Database::CreatePreppedStmt(query); - + const auto searchString = "%" + filterText + "%"; propertyLookup->setUInt(1, this->m_MapID); propertyLookup->setString(2, searchString.c_str()); @@ -230,7 +230,7 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl delete nameLookup; nameLookup = nullptr; - Game::logger->Log("PropertyEntranceComponent", "Failed to find property owner name for %llu!\n", cloneId); + Game::logger->Log("PropertyEntranceComponent", "Failed to find property owner name for %llu!", cloneId); continue; } else { @@ -318,7 +318,7 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl propertyLookup = nullptr; propertyQueries[entity->GetObjectID()] = entries; - + // Query here is to figure out whether or not to display the button to go to the next page or not. int32_t numberOfProperties = 0; @@ -337,7 +337,7 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl delete result; result = nullptr; - + delete propertiesLeft; propertiesLeft = nullptr; diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index 1168209c..fa9a7e52 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -37,7 +37,7 @@ PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Compo instance = this; const auto& worldId = dZoneManager::Instance()->GetZone()->GetZoneID(); - + const auto zoneId = worldId.GetMapID(); const auto cloneId = worldId.GetCloneID(); @@ -51,7 +51,7 @@ PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Compo { return; } - + templateId = result.getIntField(0); result.finalize(); @@ -80,7 +80,7 @@ PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Compo this->reputation = propertyEntry->getUInt(14); Load(); - } + } delete propertyLookup; } @@ -111,14 +111,14 @@ std::vector PropertyManagementComponent::GetPaths() const auto result = query.execQuery(); std::vector paths {}; - + if (result.eof()) { return paths; } std::vector points; - + std::istringstream stream(result.getStringField(0)); std::string token; @@ -132,7 +132,7 @@ std::vector PropertyManagementComponent::GetPaths() const } catch (std::invalid_argument& exception) { - Game::logger->Log("PropertyManagementComponent", "Failed to parse value (%s): (%s)!\n", token.c_str(), exception.what()); + Game::logger->Log("PropertyManagementComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); } } @@ -149,7 +149,7 @@ PropertyPrivacyOption PropertyManagementComponent::GetPrivacyOption() const return privacyOption; } -void PropertyManagementComponent::SetPrivacyOption(PropertyPrivacyOption value) +void PropertyManagementComponent::SetPrivacyOption(PropertyPrivacyOption value) { if (owner == LWOOBJID_EMPTY) return; @@ -241,7 +241,7 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) } catch (sql::SQLException& exception) { - Game::logger->Log("PropertyManagementComponent", "Failed to execute query: (%s)!\n", exception.what()); + Game::logger->Log("PropertyManagementComponent", "Failed to execute query: (%s)!", exception.what()); throw exception; return false; @@ -254,7 +254,7 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) return true; } -void PropertyManagementComponent::OnStartBuilding() +void PropertyManagementComponent::OnStartBuilding() { auto* ownerEntity = GetOwner(); @@ -307,7 +307,7 @@ void PropertyManagementComponent::OnFinishBuilding() void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const NiPoint3 position, NiQuaternion rotation) { - Game::logger->Log("PropertyManagementComponent", "Placing model <%f, %f, %f>\n", position.x, position.y, position.z); + Game::logger->Log("PropertyManagementComponent", "Placing model <%f, %f, %f>", position.x, position.y, position.z); auto* entity = GetOwner(); @@ -327,7 +327,7 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N if (item == nullptr) { - Game::logger->Log("PropertyManagementComponent", "Failed to find item with id %d\n", id); + Game::logger->Log("PropertyManagementComponent", "Failed to find item with id %d", id); return; } @@ -369,7 +369,7 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N item->SetCount(item->GetCount() - 1); return; } - + item->SetCount(item->GetCount() - 1); auto* node = new SpawnerNode(); @@ -394,7 +394,7 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N LWOOBJID id = static_cast(persistentId) | 1ull << OBJECT_BIT_CLIENT; info.spawnerID = id; - + const auto spawnerId = dZoneManager::Instance()->MakeSpawner(info); auto* spawner = dZoneManager::Instance()->GetSpawner(spawnerId); @@ -429,7 +429,7 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int deleteReason) { - Game::logger->Log("PropertyManagementComponent", "Delete model: (%llu) (%i)\n", id, deleteReason); + Game::logger->Log("PropertyManagementComponent", "Delete model: (%llu) (%i)", id, deleteReason); auto* entity = GetOwner(); @@ -449,34 +449,34 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet if (index == models.end()) { - Game::logger->Log("PropertyManagementComponent", "Failed to find model\n"); + Game::logger->Log("PropertyManagementComponent", "Failed to find model"); return; } const auto spawnerId = index->second; - + auto* spawner = dZoneManager::Instance()->GetSpawner(spawnerId); models.erase(id); - + if (spawner == nullptr) { - Game::logger->Log("PropertyManagementComponent", "Failed to find spawner\n"); + Game::logger->Log("PropertyManagementComponent", "Failed to find spawner"); } auto* model = EntityManager::Instance()->GetEntity(id); if (model == nullptr) { - Game::logger->Log("PropertyManagementComponent", "Failed to find model entity\n"); + Game::logger->Log("PropertyManagementComponent", "Failed to find model entity"); return; } EntityManager::Instance()->DestructEntity(model); - Game::logger->Log("PropertyManagementComponent", "Deleting model LOT %i\n", model->GetLOT()); + Game::logger->Log("PropertyManagementComponent", "Deleting model LOT %i", model->GetLOT()); if (model->GetLOT() == 14) { @@ -536,7 +536,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet return; } - + inventoryComponent->AddItem(model->GetLOT(), 1, eLootSourceType::LOOT_SOURCE_DELETION, INVALID, {}, LWOOBJID_EMPTY, false); auto* item = inventoryComponent->FindItemByLot(model->GetLOT()); @@ -572,10 +572,10 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet } default: { - Game::logger->Log("PropertyManagementComponent", "Invalid delete reason\n"); + Game::logger->Log("PropertyManagementComponent", "Invalid delete reason"); } } - + GameMessages::SendGetModelsOnProperty(entity->GetObjectID(), GetModels(), UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3::ZERO, LWOOBJID_EMPTY, 16, NiQuaternion::IDENTITY); @@ -593,7 +593,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet void PropertyManagementComponent::UpdateApprovedStatus(const bool value) { if (owner == LWOOBJID_EMPTY) return; - + auto* update = Database::CreatePreppedStmt("UPDATE properties SET mod_approved = ? WHERE id = ?;"); update->setBoolean(1, value); @@ -610,11 +610,11 @@ void PropertyManagementComponent::Load() { return; } - + auto* lookup = Database::CreatePreppedStmt("SELECT id, lot, x, y, z, rx, ry, rz, rw, ugc_id FROM properties_contents WHERE property_id = ?;"); lookup->setUInt64(1, propertyId); - + auto* lookupResult = lookup->executeQuery(); while (lookupResult->next()) @@ -622,7 +622,7 @@ void PropertyManagementComponent::Load() const LWOOBJID id = lookupResult->getUInt64(1); const LOT lot = lookupResult->getInt(2); - const NiPoint3 position = + const NiPoint3 position = { static_cast(lookupResult->getDouble(3)), static_cast(lookupResult->getDouble(4)), @@ -641,7 +641,7 @@ void PropertyManagementComponent::Load() node->position = position; node->rotation = rotation; - + SpawnerInfo info{}; info.templateID = lot; @@ -720,7 +720,7 @@ void PropertyManagementComponent::Save() try { lookupResult = lookup->executeQuery(); } catch (sql::SQLException& ex) { - Game::logger->Log("PropertyManagementComponent", "lookup error %s\n", ex.what()); + Game::logger->Log("PropertyManagementComponent", "lookup error %s", ex.what()); } std::vector present; @@ -734,7 +734,7 @@ void PropertyManagementComponent::Save() delete lookupResult; std::vector modelIds; - + for (const auto& pair : models) { const auto id = pair.second; @@ -767,7 +767,7 @@ void PropertyManagementComponent::Save() try { insertion->execute(); } catch (sql::SQLException& ex) { - Game::logger->Log("PropertyManagementComponent", "Error inserting into properties_contents. Error %s\n", ex.what()); + Game::logger->Log("PropertyManagementComponent", "Error inserting into properties_contents. Error %s", ex.what()); } } else @@ -784,7 +784,7 @@ void PropertyManagementComponent::Save() try { update->executeUpdate(); } catch (sql::SQLException& ex) { - Game::logger->Log("PropertyManagementComponent", "Error updating properties_contents. Error: %s\n", ex.what()); + Game::logger->Log("PropertyManagementComponent", "Error updating properties_contents. Error: %s", ex.what()); } } } @@ -800,7 +800,7 @@ void PropertyManagementComponent::Save() try { remove->execute(); } catch (sql::SQLException& ex) { - Game::logger->Log("PropertyManagementComponent", "Error removing from properties_contents. Error %s\n", ex.what()); + Game::logger->Log("PropertyManagementComponent", "Error removing from properties_contents. Error %s", ex.what()); } } @@ -815,7 +815,7 @@ void PropertyManagementComponent::Save() delete remove; } -void PropertyManagementComponent::AddModel(LWOOBJID modelId, LWOOBJID spawnerId) +void PropertyManagementComponent::AddModel(LWOOBJID modelId, LWOOBJID spawnerId) { models[modelId] = spawnerId; } @@ -834,7 +834,7 @@ void PropertyManagementComponent::OnQueryPropertyData(Entity* originator, const const auto& worldId = dZoneManager::Instance()->GetZone()->GetZoneID(); const auto zoneId = worldId.GetMapID(); - Game::logger->Log("Properties", "Getting property info for %d\n", zoneId); + Game::logger->Log("Properties", "Getting property info for %d", zoneId); GameMessages::PropertyDataMessage message = GameMessages::PropertyDataMessage(zoneId); const auto isClaimed = GetOwnerId() != LWOOBJID_EMPTY; @@ -845,7 +845,7 @@ void PropertyManagementComponent::OnQueryPropertyData(Entity* originator, const std::string description = ""; uint64_t claimed = 0; char privacy = 0; - + if (isClaimed) { const auto cloneId = worldId.GetCloneID(); @@ -904,7 +904,7 @@ void PropertyManagementComponent::OnQueryPropertyData(Entity* originator, const // send rejection here? } -void PropertyManagementComponent::OnUse(Entity* originator) +void PropertyManagementComponent::OnUse(Entity* originator) { OnQueryPropertyData(originator, UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendOpenPropertyManagment(m_Parent->GetObjectID(), originator->GetSystemAddress()); diff --git a/dGame/dComponents/PropertyVendorComponent.cpp b/dGame/dComponents/PropertyVendorComponent.cpp index 72e8ad64..5ab8340b 100644 --- a/dGame/dComponents/PropertyVendorComponent.cpp +++ b/dGame/dComponents/PropertyVendorComponent.cpp @@ -22,7 +22,7 @@ void PropertyVendorComponent::OnUse(Entity* originator) if (PropertyManagementComponent::Instance()->GetOwnerId() == LWOOBJID_EMPTY) { - Game::logger->Log("PropertyVendorComponent", "Property vendor opening!\n"); + Game::logger->Log("PropertyVendorComponent", "Property vendor opening!"); GameMessages::SendOpenPropertyVendor(m_Parent->GetObjectID(), originator->GetSystemAddress()); @@ -42,7 +42,7 @@ void PropertyVendorComponent::OnBuyFromVendor(Entity* originator, const bool con if (PropertyManagementComponent::Instance() == nullptr) return; if (PropertyManagementComponent::Instance()->Claim(originator->GetObjectID()) == false) { - Game::logger->Log("PropertyVendorComponent", "FAILED TO CLAIM PROPERTY. PLAYER ID IS %llu\n", originator->GetObjectID()); + Game::logger->Log("PropertyVendorComponent", "FAILED TO CLAIM PROPERTY. PLAYER ID IS %llu", originator->GetObjectID()); return; } @@ -51,11 +51,11 @@ void PropertyVendorComponent::OnBuyFromVendor(Entity* originator, const bool con auto* controller = dZoneManager::Instance()->GetZoneControlObject(); controller->OnFireEventServerSide(m_Parent, "propertyRented"); - + PropertyManagementComponent::Instance()->SetOwner(originator); - + PropertyManagementComponent::Instance()->OnQueryPropertyData(originator, originator->GetSystemAddress()); - Game::logger->Log("PropertyVendorComponent", "Fired event; (%d) (%i) (%i)\n", confirmed, lot, count); + Game::logger->Log("PropertyVendorComponent", "Fired event; (%d) (%i) (%i)", confirmed, lot, count); } diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 7bea03f6..e157ca5f 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -91,7 +91,7 @@ void RacingControlComponent::OnPlayerLoaded(Entity *player) { m_LoadedPlayers++; - Game::logger->Log("RacingControlComponent", "Loading player %i\n", + Game::logger->Log("RacingControlComponent", "Loading player %i", m_LoadedPlayers); m_LobbyPlayers.push_back(objectID); @@ -116,7 +116,7 @@ void RacingControlComponent::LoadPlayerVehicle(Entity *player, auto *item = inventoryComponent->FindItemByLot(8092); if (item == nullptr) { - Game::logger->Log("RacingControlComponent", "Failed to find item\n"); + Game::logger->Log("RacingControlComponent", "Failed to find item"); return; } @@ -149,7 +149,7 @@ void RacingControlComponent::LoadPlayerVehicle(Entity *player, startRotation = NiQuaternion::FromEulerAngles(angles); Game::logger->Log("RacingControlComponent", - "Start position <%f, %f, %f>, <%f, %f, %f>\n", + "Start position <%f, %f, %f>, <%f, %f, %f>", startPosition.x, startPosition.y, startPosition.z, angles.x * (180.0f / M_PI), angles.y * (180.0f / M_PI), angles.z * (180.0f / M_PI)); @@ -565,11 +565,11 @@ void RacingControlComponent::Update(float deltaTime) { // to load in, can raise this if it's too low if (m_LoadTimer >= 15) { Game::logger->Log("RacingControlComponent", - "Loading all players...\n"); + "Loading all players..."); for (size_t i = 0; i < m_LobbyPlayers.size(); i++) { Game::logger->Log("RacingControlComponent", - "Loading player now!\n"); + "Loading player now!"); auto *player = EntityManager::Instance()->GetEntity(m_LobbyPlayers[i]); @@ -579,7 +579,7 @@ void RacingControlComponent::Update(float deltaTime) { } Game::logger->Log("RacingControlComponent", - "Loading player now NOW!\n"); + "Loading player now NOW!"); LoadPlayerVehicle(player, true); @@ -729,7 +729,7 @@ void RacingControlComponent::Update(float deltaTime) { m_Started = true; - Game::logger->Log("RacingControlComponent", "Starting race\n"); + Game::logger->Log("RacingControlComponent", "Starting race"); EntityManager::Instance()->SerializeEntity(m_Parent); @@ -833,7 +833,7 @@ void RacingControlComponent::Update(float deltaTime) { player.bestLapTime = lapTime; Game::logger->Log("RacingControlComponent", - "Best lap time (%llu)\n", lapTime); + "Best lap time (%llu)", lapTime); } auto *missionComponent = @@ -854,7 +854,7 @@ void RacingControlComponent::Update(float deltaTime) { player.raceTime = raceTime; Game::logger->Log("RacingControlComponent", - "Completed time %llu, %llu\n", + "Completed time %llu, %llu", raceTime, raceTime * 1000); // Entire race time @@ -870,12 +870,12 @@ void RacingControlComponent::Update(float deltaTime) { } Game::logger->Log("RacingControlComponent", - "Lapped (%i) in (%llu)\n", player.lap, + "Lapped (%i) in (%llu)", player.lap, lapTime); } Game::logger->Log("RacingControlComponent", - "Reached point (%i)/(%i)\n", player.respawnIndex, + "Reached point (%i)/(%i)", player.respawnIndex, path->pathWaypoints.size()); break; diff --git a/dGame/dComponents/RebuildComponent.cpp b/dGame/dComponents/RebuildComponent.cpp index 603a18cc..f2c2707f 100644 --- a/dGame/dComponents/RebuildComponent.cpp +++ b/dGame/dComponents/RebuildComponent.cpp @@ -28,12 +28,12 @@ RebuildComponent::RebuildComponent(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 && + if (positionAsVector.size() == 3 && GeneralUtils::TryParse(positionAsVector[0], m_ActivatorPosition.x) && - GeneralUtils::TryParse(positionAsVector[1], m_ActivatorPosition.y) && + GeneralUtils::TryParse(positionAsVector[1], m_ActivatorPosition.y) && GeneralUtils::TryParse(positionAsVector[2], m_ActivatorPosition.z)) { } else { - Game::logger->Log("RebuildComponent", "Failed to find activator position for lot %i. Defaulting to parents position.\n", m_Parent->GetLOT()); + Game::logger->Log("RebuildComponent", "Failed to find activator position for lot %i. Defaulting to parents position.", m_Parent->GetLOT()); m_ActivatorPosition = m_Parent->GetPosition(); } @@ -47,7 +47,7 @@ RebuildComponent::~RebuildComponent() { if (builder) { CancelRebuild(builder, eFailReason::REASON_BUILD_ENDED, true); } - + DespawnActivator(); } @@ -61,7 +61,7 @@ void RebuildComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitia outBitStream->Write(false); } - // If build state is completed and we've already serialized once in the completed state, + // If build state is completed and we've already serialized once in the completed state, // don't serializing this component anymore as this will cause the build to jump again. // If state changes, serialization will begin again. if (!m_StateDirty && m_State == REBUILD_COMPLETED) { @@ -93,7 +93,7 @@ void RebuildComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitia outBitStream->Write(m_ShowResetEffect); outBitStream->Write(m_Activator != nullptr); - + outBitStream->Write(m_Timer); outBitStream->Write(m_TimerIncomplete); @@ -146,7 +146,7 @@ void RebuildComponent::Update(float deltaTime) { } } } - + break; } case REBUILD_COMPLETED: { @@ -272,7 +272,7 @@ void RebuildComponent::SpawnActivator() { void RebuildComponent::DespawnActivator() { if (m_Activator) { EntityManager::Instance()->DestructEntity(m_Activator); - + m_Activator->ScheduleKillAfterUpdate(); m_Activator = nullptr; @@ -281,7 +281,7 @@ void RebuildComponent::DespawnActivator() { } } -Entity* RebuildComponent::GetActivator() +Entity* RebuildComponent::GetActivator() { return EntityManager::Instance()->GetEntity(m_ActivatorId); } @@ -431,13 +431,13 @@ void RebuildComponent::CompleteRebuild(Entity* user) { if (user == nullptr) { return; } - + auto* characterComponent = user->GetComponent(); if (characterComponent != nullptr) { characterComponent->SetCurrentActivity(eGameActivities::ACTIVITY_NONE); characterComponent->TrackRebuildComplete(); } else { - Game::logger->Log("RebuildComponent", "Some user tried to finish the rebuild but they didn't have a character somehow.\n"); + Game::logger->Log("RebuildComponent", "Some user tried to finish the rebuild but they didn't have a character somehow."); return; } @@ -447,7 +447,7 @@ void RebuildComponent::CompleteRebuild(Entity* user) { GameMessages::SendPlayFXEffect(m_Parent, 507, u"create", "BrickFadeUpVisCompleteEffect", LWOOBJID_EMPTY, 0.4f, 1.0f, true); GameMessages::SendEnableRebuild(m_Parent, false, false, true, eFailReason::REASON_NOT_GIVEN, m_ResetTime, user->GetObjectID()); GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); - + m_State = eRebuildState::REBUILD_COMPLETED; m_StateDirty = true; @@ -528,7 +528,7 @@ void RebuildComponent::ResetRebuild(bool failed) { m_TimerIncomplete = 0.0f; m_ShowResetEffect = false; m_DrainedImagination = 0; - + EntityManager::Instance()->SerializeEntity(m_Parent); // Notify scripts and possible subscribers diff --git a/dGame/dComponents/RocketLaunchpadControlComponent.cpp b/dGame/dComponents/RocketLaunchpadControlComponent.cpp index 357fb2d0..108335ae 100644 --- a/dGame/dComponents/RocketLaunchpadControlComponent.cpp +++ b/dGame/dComponents/RocketLaunchpadControlComponent.cpp @@ -57,7 +57,7 @@ void RocketLaunchpadControlComponent::Launch(Entity* originator, LWOMAPID mapId, auto* rocket = characterComponent->GetRocket(originator); if (!rocket) { - Game::logger->Log("RocketLaunchpadControlComponent", "Unable to find rocket!\n"); + Game::logger->Log("RocketLaunchpadControlComponent", "Unable to find rocket!"); return; } @@ -79,7 +79,7 @@ void RocketLaunchpadControlComponent::Launch(Entity* originator, LWOMAPID mapId, SetSelectedMapId(originator->GetObjectID(), zone); GameMessages::SendFireEventClientSide(m_Parent->GetObjectID(), originator->GetSystemAddress(), u"RocketEquipped", rocket->GetId(), cloneId, -1, originator->GetObjectID()); - + GameMessages::SendChangeObjectWorldState(rocket->GetId(), WORLDSTATE_ATTACHED, UNASSIGNED_SYSTEM_ADDRESS); EntityManager::Instance()->SerializeEntity(originator); diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index 4d62fb0b..edc6b70d 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -185,7 +185,7 @@ void ScriptedActivityComponent::PlayerLeave(LWOOBJID playerID) { delete lobby->players[i]; lobby->players[i] = nullptr; lobby->players.erase(lobby->players.begin() + i); - + return; } } @@ -246,7 +246,7 @@ void ScriptedActivityComponent::Update(float deltaTime) { // The timer has elapsed, start the instance if (lobby->timer <= 0.0f) { - Game::logger->Log("ScriptedActivityComponent", "Setting up instance.\n"); + Game::logger->Log("ScriptedActivityComponent", "Setting up instance."); ActivityInstance* instance = NewInstance(); LoadPlayersIntoInstance(instance, lobby->players); @@ -397,7 +397,7 @@ void ScriptedActivityComponent::ClearInstances() { m_Instances.clear(); } -ActivityPlayer* ScriptedActivityComponent::GetActivityPlayerData(LWOOBJID playerID) +ActivityPlayer* ScriptedActivityComponent::GetActivityPlayerData(LWOOBJID playerID) { for (auto* activityData : m_ActivityPlayers) { @@ -410,7 +410,7 @@ ActivityPlayer* ScriptedActivityComponent::GetActivityPlayerData(LWOOBJID player return nullptr; } -void ScriptedActivityComponent::RemoveActivityPlayerData(LWOOBJID playerID) +void ScriptedActivityComponent::RemoveActivityPlayerData(LWOOBJID playerID) { for (size_t i = 0; i < m_ActivityPlayers.size(); i++) { @@ -427,7 +427,7 @@ void ScriptedActivityComponent::RemoveActivityPlayerData(LWOOBJID playerID) } } -ActivityPlayer* ScriptedActivityComponent::AddActivityPlayerData(LWOOBJID playerID) +ActivityPlayer* ScriptedActivityComponent::AddActivityPlayerData(LWOOBJID playerID) { auto* data = GetActivityPlayerData(playerID); if (data != nullptr) @@ -515,7 +515,7 @@ void ActivityInstance::StartZone() { if (player == nullptr) return; - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", player->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", player->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (player->GetCharacter()) { player->GetCharacter()->SetZoneID(zoneID); player->GetCharacter()->SetZoneInstance(zoneInstance); @@ -526,7 +526,7 @@ void ActivityInstance::StartZone() { return; }); } - + m_NextZoneCloneID++; } @@ -565,7 +565,7 @@ std::vector ActivityInstance::GetParticipants() const { if (entity != nullptr) entities.push_back(entity); } - + return entities; } diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index 7aa29523..608eced6 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -52,7 +52,7 @@ void SkillComponent::SyncPlayerSkill(const uint32_t skillUid, const uint32_t syn if (index == this->m_managedBehaviors.end()) { - Game::logger->Log("SkillComponent", "Failed to find skill with uid (%i)!\n", skillUid, syncId); + Game::logger->Log("SkillComponent", "Failed to find skill with uid (%i)!", skillUid, syncId); return; } @@ -81,7 +81,7 @@ void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::B if (index == -1) { - Game::logger->Log("SkillComponent", "Failed to find projectile id (%llu)!\n", projectileId); + Game::logger->Log("SkillComponent", "Failed to find projectile id (%llu)!", projectileId); return; } @@ -95,7 +95,7 @@ void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::B auto result = query.execQuery(); if (result.eof()) { - Game::logger->Log("SkillComponent", "Failed to find skill id for (%i)!\n", sync_entry.lot); + Game::logger->Log("SkillComponent", "Failed to find skill id for (%i)!", sync_entry.lot); return; } @@ -432,7 +432,7 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) if (other == nullptr) { if (entry.branchContext.target != LWOOBJID_EMPTY) { - Game::logger->Log("SkillComponent", "Invalid projectile target (%llu)!\n", entry.branchContext.target); + Game::logger->Log("SkillComponent", "Invalid projectile target (%llu)!", entry.branchContext.target); } return; @@ -444,7 +444,7 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) auto result = query.execQuery(); if (result.eof()) { - Game::logger->Log("SkillComponent", "Failed to find skill id for (%i)!\n", entry.lot); + Game::logger->Log("SkillComponent", "Failed to find skill id for (%i)!", entry.lot); return; } diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 53cce60e..9cd8995a 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -30,7 +30,7 @@ using namespace std; void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, GAME_MSG messageID) { - + CBITSTREAM // Get the entity @@ -40,7 +40,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System if (!entity) { - Game::logger->Log("GameMessageHandler", "Failed to find associated entity (%llu), aborting GM (%X)!\n", objectID, messageID); + Game::logger->Log("GameMessageHandler", "Failed to find associated entity (%llu), aborting GM (%X)!", objectID, messageID); return; } @@ -69,31 +69,31 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_UN_EQUIP_ITEM: GameMessages::HandleUnequipItem(inStream, entity); break; - + case GAME_MSG_RESPOND_TO_MISSION: { GameMessages::HandleRespondToMission(inStream, entity); break; } - + case GAME_MSG_REQUEST_USE: { GameMessages::HandleRequestUse(inStream, entity, sysAddr); break; } - + case GAME_MSG_SET_FLAG: { GameMessages::HandleSetFlag(inStream, entity); break; } - + case GAME_MSG_HAS_BEEN_COLLECTED: { GameMessages::HandleHasBeenCollected(inStream, entity); break; } - + case GAME_MSG_PLAYER_LOADED: { GameMessages::SendRestoreToPostLoadStats(entity, sysAddr); entity->SetPlayerReadyForUpdates(); - + auto* player = dynamic_cast(entity); if (player != nullptr) { @@ -157,20 +157,20 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System character->OnZoneLoad(); } - Game::logger->Log("GameMessageHandler", "Player %s (%llu) loaded.\n", entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); + Game::logger->Log("GameMessageHandler", "Player %s (%llu) loaded.", entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); // After we've done our thing, tell the client they're ready GameMessages::SendPlayerReady(dZoneManager::Instance()->GetZoneControlObject(), sysAddr); GameMessages::SendPlayerReady(entity, sysAddr); - + break; } - + case GAME_MSG_REQUEST_LINKED_MISSION: { GameMessages::HandleRequestLinkedMission(inStream, entity); break; } - + case GAME_MSG_MISSION_DIALOGUE_OK: { GameMessages::HandleMissionDialogOK(inStream, entity); break; @@ -181,12 +181,12 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System //rejecting a mission offer. We dont need to do anything. This is just here to remove a warning in our logs :) break; } - + case GAME_MSG_REQUEST_PLATFORM_RESYNC: { GameMessages::HandleRequestPlatformResync(inStream, entity, sysAddr); break; } - + case GAME_MSG_FIRE_EVENT_SERVER_SIDE: { GameMessages::HandleFireEventServerSide(inStream, entity, sysAddr); break; @@ -206,7 +206,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleActivityStateChangeRequest(inStream, entity); break; } - + case GAME_MSG_PARSE_CHAT_MESSAGE: { GameMessages::HandleParseChatMessage(inStream, entity, sysAddr); break; @@ -259,31 +259,31 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System if (skill_component != nullptr) { auto* bs = new RakNet::BitStream((unsigned char*) message.sBitStream.c_str(), message.sBitStream.size(), false); - + skill_component->SyncPlayerProjectile(message.i64LocalID, bs, message.i64TargetID); delete bs; } - + break; } - + case GAME_MSG_START_SKILL: { GameMessages::StartSkill startSkill = GameMessages::StartSkill(); startSkill.Deserialize(inStream); // inStream replaces &bitStream - + if (startSkill.skillID == 1561 || startSkill.skillID == 1562 || startSkill.skillID == 1541) return; MissionComponent* comp = entity->GetComponent(); if (comp) { comp->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, startSkill.skillID); } - + CDSkillBehaviorTable* skillTable = CDClientManager::Instance()->GetTable("SkillBehavior"); unsigned int behaviorId = skillTable->GetSkillByID(startSkill.skillID).behaviorID; bool success = false; - + if (behaviorId > 0) { RakNet::BitStream * bs = new RakNet::BitStream((unsigned char *)startSkill.sBitStream.c_str(), startSkill.sBitStream.size(), false); @@ -295,10 +295,10 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System DestroyableComponent* destComp = entity->GetComponent(); destComp->SetImagination(destComp->GetImagination() - skillTable->GetSkillByID(startSkill.skillID).imaginationcost); } - + delete bs; } - + if (Game::server->GetZoneID() == 1302) { break; } @@ -345,7 +345,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System } //cout << buffer.str() << endl; - + if(usr != nullptr) { RakNet::BitStream * bs = new RakNet::BitStream((unsigned char *)sync.sBitStream.c_str(), sync.sBitStream.size(), false); @@ -378,7 +378,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_MODULAR_BUILD_FINISH: GameMessages::HandleModularBuildFinish(inStream, entity, sysAddr); break; - + case GAME_MSG_PUSH_EQUIPPED_ITEMS_STATE: GameMessages::HandlePushEquippedItemsState(inStream, entity); break; @@ -386,7 +386,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_POP_EQUIPPED_ITEMS_STATE: GameMessages::HandlePopEquippedItemsState(inStream, entity); break; - + case GAME_MSG_BUY_FROM_VENDOR: GameMessages::HandleBuyFromVendor(inStream, entity, sysAddr); break; @@ -477,7 +477,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_COMMAND_PET: GameMessages::HandleCommandPet(inStream, entity, sysAddr); break; - + case GAME_MSG_DESPAWN_PET: GameMessages::HandleDespawnPet(inStream, entity, sysAddr); break; @@ -558,7 +558,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK: GameMessages::HandleUpdatePropertyOrModelForFilterCheck(inStream, entity, sysAddr); break; - + case GAME_MSG_SET_PROPERTY_ACCESS: GameMessages::HandleSetPropertyAccess(inStream, entity, sysAddr); break; @@ -657,8 +657,8 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleUpdatePlayerStatistic(inStream, entity); break; - default: - //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X\n", messageID); + default: + //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X", messageID); break; } } diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 935a7ccb..365485f2 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -126,7 +126,7 @@ void GameMessages::SendTeleport(const LWOOBJID& objectID, const NiPoint3& pos, c void GameMessages::SendPlayAnimation(Entity* entity, const std::u16string& animationName, float fPriority, float fScale) { if (!entity) { - Game::logger->Log("SendPlayAnimation", "Trying to play animation, but entity var is nullptr!\n"); + Game::logger->Log("SendPlayAnimation", "Trying to play animation, but entity var is nullptr!"); return; } @@ -1613,7 +1613,7 @@ void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStre void GameMessages::HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, const SystemAddress& sysAddr) { - Game::logger->Log("AGS", "We got mail!\n"); + Game::logger->Log("AGS", "We got mail!"); } void GameMessages::SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, const SystemAddress& sysAddr) { @@ -1685,7 +1685,7 @@ void GameMessages::HandleActivityStateChangeRequest(RakNet::BitStream *inStream, auto* assosiate = EntityManager::Instance()->GetEntity(objectID); - Game::logger->Log("Activity State Change", "%s [%i, %i] from %i to %i\n", GeneralUtils::UTF16ToWTF8(stringValue).c_str(), value1, value2, entity->GetLOT(), assosiate != nullptr ? assosiate->GetLOT() : 0); + Game::logger->Log("Activity State Change", "%s [%i, %i] from %i to %i", GeneralUtils::UTF16ToWTF8(stringValue).c_str(), value1, value2, entity->GetLOT(), assosiate != nullptr ? assosiate->GetLOT() : 0); std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SHOOTING_GALLERY); for (Entity* scriptEntity : scriptedActs) { @@ -1985,7 +1985,7 @@ void GameMessages::SendDownloadPropertyData(const LWOOBJID objectId, const Prope data.Serialize(bitStream); - Game::logger->Log("SendDownloadPropertyData", "(%llu) sending property data (%d)\n", objectId, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); + Game::logger->Log("SendDownloadPropertyData", "(%llu) sending property data (%d)", objectId, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -2060,7 +2060,7 @@ void GameMessages::SendGetModelsOnProperty(LWOOBJID objectId, std::mapLog("SendGetModelsOnProperty", "Sending property models to (%llu) (%d)\n", objectId, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); + Game::logger->Log("SendGetModelsOnProperty", "Sending property models to (%llu) (%d)", objectId, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -2167,7 +2167,7 @@ void GameMessages::HandleSetPropertyAccess(RakNet::BitStream* inStream, Entity* inStream->Read(renewIsDefault); if (renewIsDefault != 0) inStream->Read(renew); - Game::logger->Log("GameMessages", "Set privacy option to: %i\n", accessType); + Game::logger->Log("GameMessages", "Set privacy option to: %i", accessType); if (PropertyManagementComponent::Instance() == nullptr) return; @@ -2211,7 +2211,7 @@ void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* void GameMessages::HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - Game::logger->Log("HandleQueryPropertyData", "Entity (%i) requesting data\n", entity->GetLOT()); + Game::logger->Log("HandleQueryPropertyData", "Entity (%i) requesting data", entity->GetLOT()); /* auto entites = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_PROPERTY_VENDOR); @@ -2270,7 +2270,7 @@ void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entit player->GetCharacter()->SetBuildMode(start); - Game::logger->Log("GameMessages", "Sending build mode confirm (%i): (%d) (%i) (%d) (%i) (%llu)\n", entity->GetLOT(), start, distanceType, modePaused, modeValue, playerId); + Game::logger->Log("GameMessages", "Sending build mode confirm (%i): (%d) (%i) (%d) (%i) (%llu)", entity->GetLOT(), start, distanceType, modePaused, modeValue, playerId); SendSetBuildModeConfirmed(entity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS, start, false, modePaused, modeValue, playerId, startPosition); } @@ -2308,7 +2308,7 @@ void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Enti sourceType = 4; } - Game::logger->Log("GameMessages", "Handling start building with item (%i): (%d) (%d) (%i) (%llu) (%i) (%i) (%llu) (%i) (%i)\n", entity->GetLOT(), firstTime, success, sourceBag, sourceId, sourceLot, sourceType, targetId, targetLot, targetType); + Game::logger->Log("GameMessages", "Handling start building with item (%i): (%d) (%d) (%i) (%llu) (%i) (%i) (%llu) (%i) (%i)", entity->GetLOT(), firstTime, success, sourceBag, sourceId, sourceLot, sourceType, targetId, targetLot, targetType); auto* user = UserManager::Instance()->GetUser(sysAddr); @@ -2408,7 +2408,7 @@ void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* LWOOBJID itemID = LWOOBJID_EMPTY; inStream->Read(itemID); - Game::logger->Log("BBB", "Load item request for: " + std::to_string(itemID) + "\n"); + Game::logger->Log("BBB", "Load item request for: " + std::to_string(itemID) + ""); CBITSTREAM; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_LOAD_RESPONSE_ITEMID); @@ -2451,7 +2451,7 @@ void GameMessages::SendUnSmash(Entity* entity, LWOOBJID builderID, float duratio void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { // TODO - Game::logger->Log("GameMessages", "Recieved Control Behavior GameMessage, but property behaviors are unimplemented.\n"); + Game::logger->Log("GameMessages", "Recieved Control Behavior GameMessage, but property behaviors are unimplemented."); } void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { @@ -2531,7 +2531,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //int32_t size = ZCompression::Decompress(inData, lxfmlSize, outData, 327680, error); //if (size == -1) { - // Game::logger->Log("GameMessages", "Failed to decompress LXFML: (%i)\n", error); + // Game::logger->Log("GameMessages", "Failed to decompress LXFML: (%i)", error); // return; //} // @@ -3259,7 +3259,7 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* return; } - Game::logger->Log("GameMessages", "Trade request to (%llu)\n", i64Invitee); + Game::logger->Log("GameMessages", "Trade request to (%llu)", i64Invitee); auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); @@ -3293,7 +3293,7 @@ void GameMessages::HandleClientTradeCancel(RakNet::BitStream* inStream, Entity* if (trade == nullptr) return; - Game::logger->Log("GameMessages", "Trade canceled from (%llu)\n", entity->GetObjectID()); + Game::logger->Log("GameMessages", "Trade canceled from (%llu)", entity->GetObjectID()); TradingManager::Instance()->CancelTrade(trade->GetTradeId()); } @@ -3302,7 +3302,7 @@ void GameMessages::HandleClientTradeAccept(RakNet::BitStream* inStream, Entity* { bool bFirst = inStream->ReadBit(); - Game::logger->Log("GameMessages", "Trade accepted from (%llu) -> (%d)\n", entity->GetObjectID(), bFirst); + Game::logger->Log("GameMessages", "Trade accepted from (%llu) -> (%d)", entity->GetObjectID(), bFirst); auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); @@ -3319,7 +3319,7 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* inStream->Read(currency); inStream->Read(itemCount); - Game::logger->Log("GameMessages", "Trade update from (%llu) -> (%llu), (%i)\n", entity->GetObjectID(), currency, itemCount); + Game::logger->Log("GameMessages", "Trade update from (%llu) -> (%llu), (%i)", entity->GetObjectID(), currency, itemCount); std::vector items {}; @@ -3375,7 +3375,7 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* items.push_back({itemId, lot, unknown2}); - Game::logger->Log("GameMessages", "Trade item from (%llu) -> (%llu)/(%llu), (%i), (%llu), (%i), (%i)\n", entity->GetObjectID(), itemId, itemId2, lot, unknown1, unknown2, unknown3); + Game::logger->Log("GameMessages", "Trade item from (%llu) -> (%llu)/(%llu), (%i), (%llu), (%i), (%i)", entity->GetObjectID(), itemId, itemId2, lot, unknown1, unknown2, unknown3); } auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); @@ -3848,7 +3848,7 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* userData.push_back(character); } - Game::logger->Log("HandleMessageBoxResponse", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " identifier: " + GeneralUtils::UTF16ToWTF8(identifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(userData) + "\n"); + Game::logger->Log("HandleMessageBoxResponse", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " identifier: " + GeneralUtils::UTF16ToWTF8(identifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(userData)); auto* user = UserManager::Instance()->GetUser(sysAddr); @@ -3912,7 +3912,7 @@ void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* e identifier.push_back(character); } - Game::logger->Log("HandleChoiceBoxRespond", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " buttonIdentifier: " + GeneralUtils::UTF16ToWTF8(buttonIdentifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(identifier) + "\n"); + Game::logger->Log("HandleChoiceBoxRespond", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " buttonIdentifier: " + GeneralUtils::UTF16ToWTF8(buttonIdentifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(identifier)); auto* user = UserManager::Instance()->GetUser(sysAddr); @@ -4057,7 +4057,7 @@ void GameMessages::HandleDismountComplete(RakNet::BitStream* inStream, Entity* e void GameMessages::HandleAcknowledgePossession(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - Game::logger->Log("HandleAcknowledgePossession", "Got AcknowledgePossession from %i\n", entity->GetLOT()); + Game::logger->Log("HandleAcknowledgePossession", "Got AcknowledgePossession from %i", entity->GetLOT()); EntityManager::Instance()->SerializeEntity(entity); } @@ -4067,11 +4067,11 @@ void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, En { auto* moduleAssemblyComponent = entity->GetComponent(); - Game::logger->Log("HandleModuleAssemblyQueryData", "Got Query from %i\n", entity->GetLOT()); + Game::logger->Log("HandleModuleAssemblyQueryData", "Got Query from %i", entity->GetLOT()); if (moduleAssemblyComponent != nullptr) { - Game::logger->Log("HandleModuleAssemblyQueryData", "Returning assembly %s\n", GeneralUtils::UTF16ToWTF8(moduleAssemblyComponent->GetAssemblyPartsLOTs()).c_str()); + Game::logger->Log("HandleModuleAssemblyQueryData", "Returning assembly %s", GeneralUtils::UTF16ToWTF8(moduleAssemblyComponent->GetAssemblyPartsLOTs()).c_str()); SendModuleAssemblyDBDataForClient(entity->GetObjectID(), moduleAssemblyComponent->GetSubKey(), moduleAssemblyComponent->GetAssemblyPartsLOTs(), UNASSIGNED_SYSTEM_ADDRESS); } @@ -4163,7 +4163,7 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, auto* racingControlComponent = zoneController->GetComponent(); - Game::logger->Log("HandleRequestDie", "Got die request: %i\n", entity->GetLOT()); + Game::logger->Log("HandleRequestDie", "Got die request: %i", entity->GetLOT()); if (racingControlComponent != nullptr) { @@ -4213,7 +4213,7 @@ void GameMessages::HandleRacingPlayerInfoResetFinished(RakNet::BitStream* inStre auto* racingControlComponent = zoneController->GetComponent(); - Game::logger->Log("HandleRacingPlayerInfoResetFinished", "Got finished: %i\n", entity->GetLOT()); + Game::logger->Log("HandleRacingPlayerInfoResetFinished", "Got finished: %i", entity->GetLOT()); if (racingControlComponent != nullptr) { @@ -5011,7 +5011,7 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity mapId = dZoneManager::Instance()->GetZoneID().GetMapID(); // Fallback to sending the player back to the same zone. } - Game::logger->Log("FireEventServerSide", "Player %llu has requested zone transfer to (%i, %i).\n", sender->GetObjectID(), (int) mapId, (int) cloneId); + Game::logger->Log("FireEventServerSide", "Player %llu has requested zone transfer to (%i, %i).", sender->GetObjectID(), (int) mapId, (int) cloneId); auto* character = player->GetCharacter(); @@ -5020,7 +5020,7 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity } ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, mapId, cloneId, false, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (character) { character->SetZoneID(zoneID); @@ -5071,7 +5071,7 @@ void GameMessages::HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, if (interactedObject == nullptr) { - Game::logger->Log("GameMessages", "Object %llu tried to interact, but doesn't exist!\n", objectID); + Game::logger->Log("GameMessages", "Object %llu tried to interact, but doesn't exist!", objectID); return; } @@ -5117,7 +5117,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) inStream->Read(emoteID); inStream->Read(targetID); - Game::logger->Log("GameMessages", "Emote (%i) (%llu)\n", emoteID, targetID); + Game::logger->Log("GameMessages", "Emote (%i) (%llu)", emoteID, targetID); //TODO: If targetID != 0, and we have one of the "perform emote" missions, complete them. @@ -5133,7 +5133,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) { auto* targetEntity = EntityManager::Instance()->GetEntity(targetID); - Game::logger->Log("GameMessages", "Emote target found (%d)\n", targetEntity != nullptr); + Game::logger->Log("GameMessages", "Emote target found (%d)", targetEntity != nullptr); if (targetEntity != nullptr) { @@ -5218,7 +5218,7 @@ void GameMessages::HandleRespondToMission(RakNet::BitStream* inStream, Entity* e MissionComponent* missionComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION)); if (!missionComponent) { - Game::logger->Log("GameMessages", "Unable to get mission component for entity %llu to handle RespondToMission\n", playerID); + Game::logger->Log("GameMessages", "Unable to get mission component for entity %llu to handle RespondToMission", playerID); return; } @@ -5227,13 +5227,13 @@ void GameMessages::HandleRespondToMission(RakNet::BitStream* inStream, Entity* e mission->SetReward(reward); } else { - Game::logger->Log("GameMessages", "Unable to get mission %i for entity %llu to update reward in RespondToMission\n", missionID, playerID); + Game::logger->Log("GameMessages", "Unable to get mission %i for entity %llu to update reward in RespondToMission", missionID, playerID); } Entity* offerer = EntityManager::Instance()->GetEntity(receiverID); if (offerer == nullptr) { - Game::logger->Log("GameMessages", "Unable to get receiver entity %llu for RespondToMission\n", receiverID); + Game::logger->Log("GameMessages", "Unable to get receiver entity %llu for RespondToMission", receiverID); return; } @@ -5262,7 +5262,7 @@ void GameMessages::HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* en // Get the player's mission component MissionComponent* missionComponent = static_cast(player->GetComponent(COMPONENT_TYPE_MISSION)); if (!missionComponent) { - Game::logger->Log("GameMessages", "Unable to get mission component for entity %llu to handle MissionDialogueOK\n", player->GetObjectID()); + Game::logger->Log("GameMessages", "Unable to get mission component for entity %llu to handle MissionDialogueOK", player->GetObjectID()); return; } @@ -5608,7 +5608,7 @@ void GameMessages::HandleBuildModeSet(RakNet::BitStream* inStream, Entity* entit inStream->Read(bStart); // there's more here but we don't need it (for now?) - Game::logger->Log("GameMessages", "Set build mode to (%d) for (%llu)\n", bStart, entity->GetObjectID()); + Game::logger->Log("GameMessages", "Set build mode to (%d) for (%llu)", bStart, entity->GetObjectID()); if (entity->GetCharacter()) { entity->GetCharacter()->SetBuildMode(bStart); @@ -5623,7 +5623,7 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* InventoryComponent* inv = static_cast(character->GetComponent(COMPONENT_TYPE_INVENTORY)); if (!inv) return; - Game::logger->Log("GameMessages", "Build finished\n"); + Game::logger->Log("GameMessages", "Build finished"); GameMessages::SendFinishArrangingWithItem(character, entity->GetObjectID()); // kick them from modular build GameMessages::SendModularBuildEnd(character); // i dont know if this does anything but DLUv2 did it @@ -5753,7 +5753,7 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti /* Game::logger->Log("GameMessages", - "\nnewSourceBAG: %d\nnewSourceID: %llu\nnewSourceLOT: %d\nnewSourceTYPE: %d\nnewTargetID: %llu\nnewTargetLOT: %d\nnewTargetTYPE: %d\nnewTargetPOS: %f, %f, %f\noldItemBAG: %d\noldItemID: %llu\noldItemLOT: %d\noldItemTYPE: %d\n", + "\nnewSourceBAG: %d\nnewSourceID: %llu\nnewSourceLOT: %d\nnewSourceTYPE: %d\nnewTargetID: %llu\nnewTargetLOT: %d\nnewTargetTYPE: %d\nnewTargetPOS: %f, %f, %f\noldItemBAG: %d\noldItemID: %llu\noldItemLOT: %d\noldItemTYPE: %d", newSourceBAG, newSourceID, newSourceLOT, newSourceTYPE, newTargetID, newTargetLOT, newTargetTYPE, newTargetPOS.x, newTargetPOS.y, newTargetPOS.z, oldItemBAG, oldItemID, oldItemLOT, oldItemTYPE ); */ @@ -5771,15 +5771,15 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti else if (!entities.empty()) { buildArea = entities[0]; - Game::logger->Log("BuildBorderComponent", "Using PropertyPlaque\n"); + Game::logger->Log("BuildBorderComponent", "Using PropertyPlaque"); } else { - Game::logger->Log("BuildBorderComponent", "No build area found\n"); + Game::logger->Log("BuildBorderComponent", "No build area found"); return; } - Game::logger->Log("GameMessages", "Build area found: %llu\n", buildArea->GetObjectID()); + Game::logger->Log("GameMessages", "Build area found: %llu", buildArea->GetObjectID()); GameMessages::SendStartArrangingWithItem( character, @@ -5798,7 +5798,7 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti ); } - Game::logger->Log("GameMessages", "Done Arranging\n"); + Game::logger->Log("GameMessages", "Done Arranging"); //GenericInventory* models = inv->GetGenericInventory(MODELS); //GenericInventory* tempModels = inv->GetGenericInventory(TEMP_MODELS); @@ -5824,7 +5824,7 @@ void GameMessages::HandleModularBuildMoveAndEquip(RakNet::BitStream* inStream, E Entity* character = EntityManager::Instance()->GetEntity(user->GetLoggedInChar()); if (!character) return; - Game::logger->Log("GameMessages", "Build and move\n"); + Game::logger->Log("GameMessages", "Build and move"); LOT templateID; @@ -6014,7 +6014,7 @@ void GameMessages::SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* e * [float] - performance cost * [timestamp] - time last published * [cloneid] - clone id - * + * */ // TODO This needs to be implemented when reputation is implemented for getting hot properties. /** @@ -6099,7 +6099,7 @@ void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) delete insertBug; } catch (sql::SQLException& e) { - Game::logger->Log("HandleReportBug", "Couldn't save bug report! (%s)\n", e.what()); + Game::logger->Log("HandleReportBug", "Couldn't save bug report! (%s)", e.what()); } } diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index 53ff37b4..012bcacf 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -81,7 +81,7 @@ uint32_t Inventory::GetLotCount(const LOT lot) const void Inventory::SetSize(const uint32_t value) { free += static_cast(value) - static_cast(size); - + size = value; GameMessages::SendSetInventorySize(component->GetParent(), type, static_cast(size)); @@ -107,7 +107,7 @@ int32_t Inventory::FindEmptySlot() { newSize += 10u; } - + if (newSize > GetSize()) { SetSize(newSize); @@ -121,7 +121,7 @@ int32_t Inventory::FindEmptySlot() } const auto slots = GetSlots(); - + for (auto i = 0u; i < size; ++i) { if (slots.find(i) == slots.end()) @@ -133,15 +133,15 @@ int32_t Inventory::FindEmptySlot() return -1; } -int32_t Inventory::GetEmptySlots() +int32_t Inventory::GetEmptySlots() { return free; } -bool Inventory::IsSlotEmpty(int32_t slot) +bool Inventory::IsSlotEmpty(int32_t slot) { const auto slots = GetSlots(); - + const auto& index = slots.find(slot); return index == slots.end(); @@ -201,7 +201,7 @@ Item* Inventory::FindItemByLot(const LOT lot, const bool ignoreEquipped, const b Item* Inventory::FindItemBySlot(const uint32_t slot) const { const auto slots = GetSlots(); - + const auto index = slots.find(slot); if (index == slots.end()) @@ -228,21 +228,21 @@ Item* Inventory::FindItemBySubKey(LWOOBJID id) const void Inventory::AddManagedItem(Item* item) { const auto id = item->GetId(); - + if (items.find(id) != items.end()) { - Game::logger->Log("Inventory", "Attempting to add an item with an already present id (%llu)!\n", id); + Game::logger->Log("Inventory", "Attempting to add an item with an already present id (%llu)!", id); return; } - + const auto slots = GetSlots(); const auto slot = item->GetSlot(); if (slots.find(slot) != slots.end()) { - Game::logger->Log("Inventory", "Attempting to add an item with an already present slot (%i)!\n", slot); + Game::logger->Log("Inventory", "Attempting to add an item with an already present slot (%i)!", slot); return; } @@ -258,7 +258,7 @@ void Inventory::RemoveManagedItem(Item* item) if (items.find(id) == items.end()) { - Game::logger->Log("Inventory", "Attempting to remove an item with an invalid id (%llu), lot (%i)!\n", id, item->GetLot()); + Game::logger->Log("Inventory", "Attempting to remove an item with an invalid id (%llu), lot (%i)!", id, item->GetLot()); return; } @@ -277,7 +277,7 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) switch (itemType) { case eItemType::ITEM_TYPE_BRICK: return BRICKS; - + case eItemType::ITEM_TYPE_BEHAVIOR: return BEHAVIORS; @@ -289,7 +289,7 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) case eItemType::ITEM_TYPE_LOOT_MODEL: case eItemType::ITEM_TYPE_MOUNT: return MODELS; - + case eItemType::ITEM_TYPE_HAT: case eItemType::ITEM_TYPE_HAIR: case eItemType::ITEM_TYPE_NECK: @@ -307,7 +307,7 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) case eItemType::ITEM_TYPE_PACKAGE: case eItemType::ITEM_TYPE_CURRENCY: return ITEMS; - + case eItemType::ITEM_TYPE_QUEST_OBJECT: case eItemType::ITEM_TYPE_UNKNOWN: default: @@ -325,11 +325,11 @@ const CDItemComponent& Inventory::FindItemComponent(const LOT lot) if (componentId == 0) { - Game::logger->Log("Inventory", "Failed to find item component for (%i)!\n", lot); + Game::logger->Log("Inventory", "Failed to find item component for (%i)!", lot); return CDItemComponentTable::Default; } - + const auto& itemComponent = itemComponents->GetItemComponentByID(componentId); return itemComponent; @@ -344,7 +344,7 @@ bool Inventory::IsValidItem(const LOT lot) return componentId != 0; } -const std::vector& Inventory::GetAllGMItems() +const std::vector& Inventory::GetAllGMItems() { return m_GameMasterRestrictedItems; } diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 0d254e5b..71ded509 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -20,7 +20,7 @@ Item::Item(const LWOOBJID id, const LOT lot, Inventory* inventory, const uint32_ { return; } - + this->id = id; this->lot = lot; this->inventory = inventory; @@ -32,7 +32,7 @@ Item::Item(const LWOOBJID id, const LOT lot, Inventory* inventory, const uint32_ this->info = &Inventory::FindItemComponent(lot); this->preconditions = new PreconditionExpression(this->info->reqPrecondition); this->subKey = subKey; - + inventory->AddManagedItem(this); } @@ -48,7 +48,7 @@ Item::Item( LWOOBJID subKey, bool bound, eLootSourceType lootSourceType) -{ +{ if (!Inventory::IsValidItem(lot)) { return; @@ -87,7 +87,7 @@ Item::Item( { Equip(); - Game::logger->Log("Item", "Move and equipped (%i) from (%i)\n", this->lot, this->inventory->GetType()); + Game::logger->Log("Item", "Move and equipped (%i) from (%i)", this->lot, this->inventory->GetType()); EntityManager::Instance()->SerializeEntity(inventory->GetComponent()->GetParent()); } @@ -154,7 +154,7 @@ void Item::SetCount(const uint32_t value, const bool silent, const bool disassem { return; } - + const auto delta = std::abs(static_cast(value) - static_cast(count)); const auto type = static_cast(info->itemType); @@ -169,11 +169,11 @@ void Item::SetCount(const uint32_t value, const bool silent, const bool disassem } } } - + if (!silent) { auto* entity = inventory->GetComponent()->GetParent(); - + if (value > count) { GameMessages::SendAddItemToInventoryClientSync(entity, entity->GetSystemAddress(), this, id, showFlyingLoot, delta, LWOOBJID_EMPTY, lootSourceType); @@ -217,7 +217,7 @@ void Item::SetBound(const bool value) bound = value; } -void Item::SetSubKey(LWOOBJID value) +void Item::SetSubKey(LWOOBJID value) { subKey = value; } @@ -271,14 +271,14 @@ bool Item::IsEquipped() const bool Item::Consume() { auto* skillsTable = CDClientManager::Instance()->GetTable("ObjectSkills"); - + auto skills = skillsTable->Query([=](const CDObjectSkills entry) { return entry.objectTemplate == static_cast(lot); }); auto success = false; - + for (auto& skill : skills) { if (skill.castOnType == 3) // Consumable type @@ -287,7 +287,7 @@ bool Item::Consume() } } - Game::logger->Log("Item", "Consumed (%i) / (%llu) with (%d)\n", lot, id, success); + Game::logger->Log("Item", "Consumed (%i) / (%llu) with (%d)", lot, id, success); GameMessages::SendUseItemResult(inventory->GetComponent()->GetParent(), lot, success); @@ -343,7 +343,7 @@ bool Item::UseNonEquip() LootGenerator::Instance().GiveLoot(inventory->GetComponent()->GetParent(), result, eLootSourceType::LOOT_SOURCE_CONSUMPTION); } - Game::logger->Log("Item", "Used (%i)\n", lot); + Game::logger->Log("Item", "Used (%i)", lot); inventory->GetComponent()->RemoveItem(lot, 1); } @@ -357,11 +357,11 @@ void Item::Disassemble(const eInventoryType inventoryType) if (data->GetKey() == u"assemblyPartLOTs") { auto modStr = data->GetValueAsString(); - + std::vector modArray; std::stringstream ssData(modStr); - + std::string token; const auto deliminator = '+'; @@ -369,7 +369,7 @@ void Item::Disassemble(const eInventoryType inventoryType) while (std::getline(ssData, token, deliminator)) { const auto modLot = std::stoi(token.substr(2, token.size() - 1)); - + modArray.push_back(modLot); } @@ -397,7 +397,7 @@ void Item::DisassembleModel() { return; } - + std::string renderAsset = result.fieldIsNull(0) ? "" : std::string(result.getStringField(0)); std::vector renderAssetSplit = GeneralUtils::SplitString(renderAsset, '\\'); @@ -410,7 +410,7 @@ void Item::DisassembleModel() { return; } - + std::stringstream data; data << file.rdbuf(); @@ -420,7 +420,7 @@ void Item::DisassembleModel() } auto* doc = new tinyxml2::XMLDocument(); - + if (!doc) { return; @@ -436,26 +436,26 @@ void Item::DisassembleModel() auto* lxfml = doc->FirstChildElement("LXFML"); auto* bricks = lxfml->FirstChildElement("Bricks"); std::string searchTerm = "Brick"; - + if (!bricks) { searchTerm = "Part"; bricks = lxfml->FirstChildElement("Scene")->FirstChildElement("Model")->FirstChildElement("Group"); - + if (!bricks) { return; } } - + auto* currentBrick = bricks->FirstChildElement(searchTerm.c_str()); while (currentBrick) { - if (currentBrick->Attribute("designID") != nullptr) + if (currentBrick->Attribute("designID") != nullptr) { parts.push_back(std::stoi(currentBrick->Attribute("designID"))); } - + currentBrick = currentBrick->NextSiblingElement(searchTerm.c_str()); } @@ -472,7 +472,7 @@ void Item::DisassembleModel() { continue; } - + GetInventory()->GetComponent()->AddItem(brickID[0].NDObjectID, 1, eLootSourceType::LOOT_SOURCE_DELETION); } } @@ -480,7 +480,7 @@ void Item::DisassembleModel() void Item::RemoveFromInventory() { UnEquip(); - + count = 0; inventory->RemoveManagedItem(this); diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index e51a6901..4e7a5826 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -35,7 +35,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { info = missionsTable->GetPtrByMissionID(missionId); if (info == &CDMissionsTable::Default) { - Game::logger->Log("Missions", "Failed to find mission (%i)!\n", missionId); + Game::logger->Log("Missions", "Failed to find mission (%i)!", missionId); return; } @@ -491,7 +491,7 @@ void Mission::YieldRewards() { if (pair.second < 0 || (m_Reward > 0 && pair.first != m_Reward)) { continue; } - + // If a mission rewards zero of an item, make it reward 1. auto count = pair.second > 0 ? pair.second : 1; diff --git a/dGame/dMission/MissionTask.cpp b/dGame/dMission/MissionTask.cpp index 2dd59887..36051305 100644 --- a/dGame/dMission/MissionTask.cpp +++ b/dGame/dMission/MissionTask.cpp @@ -31,7 +31,7 @@ MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) parameters.push_back(parameter); } } - + stream = std::istringstream(info->targetGroup); while (std::getline(stream, token, ',')) { @@ -61,14 +61,14 @@ void MissionTask::SetProgress(const uint32_t value, const bool echo) { return; } - + progress = value; if (!echo) { return; } - + auto* entity = mission->GetAssociate(); if (entity == nullptr) @@ -101,7 +101,7 @@ void MissionTask::AddProgress(int32_t value) { value = 0; } - + SetProgress(value); } @@ -211,7 +211,7 @@ void MissionTask::CheckCompletion() const void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& targets, int32_t count) { if (IsComplete() && count > 0) return; - + const auto type = GetType(); if (count < 0) @@ -250,11 +250,11 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& uint32_t lot; uint32_t collectionId; std::vector settings; - + switch (type) { case MissionTaskType::MISSION_TASK_TYPE_UNKNOWN: break; - + case MissionTaskType::MISSION_TASK_TYPE_ACTIVITY: { if (InAllTargets(value)) { @@ -265,7 +265,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& entity = EntityManager::Instance()->GetEntity(associate); if (entity == nullptr) { if (associate != LWOOBJID_EMPTY) { - Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!\n", associate); + Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!", associate); } break; } @@ -305,12 +305,12 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& case MissionTaskType::MISSION_TASK_TYPE_EMOTE: { if (!InParameters(value)) break; - + entity = EntityManager::Instance()->GetEntity(associate); if (entity == nullptr) { - Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!\n", associate); + Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!", associate); break; } @@ -320,10 +320,10 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& if (GetTarget() != lot) break; AddProgress(count); - + break; } - + case MissionTaskType::MISSION_TASK_TYPE_SKILL: { // This is a complicated check because for some missions we need to check for the associate being in the parameters instead of the value being in the parameters. @@ -331,7 +331,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& if (InParameters(value)) AddProgress(count); } else { if (InParameters(associate) && InAllTargets(value)) AddProgress(count); - } + } break; } @@ -373,19 +373,19 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& AddProgress(count); unique.push_back(associate); - + break; } case MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT: { if (!InAllTargets(value)) break; - + entity = EntityManager::Instance()->GetEntity(associate); if (entity == nullptr) { - Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!\n", associate); + Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!", associate); break; } @@ -397,7 +397,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& if (std::find(unique.begin(), unique.end(), collectionId) != unique.end()) break; unique.push_back(collectionId); - + SetProgress(unique.size()); auto* entity = mission->GetAssociate(); @@ -409,7 +409,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& if (missionComponent == nullptr) break; missionComponent->AddCollectible(collectionId); - + break; } @@ -418,10 +418,10 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& if (info->targetGroup != targets) break; AddProgress(count); - + break; } - + case MissionTaskType::MISSION_TASK_TYPE_RACING: { // The meaning of associate can be found in RacingTaskParam.h @@ -452,7 +452,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& { // If the player did not crash during the race, progress this task by count. if (value != 0) break; - + AddProgress(count); } else if (associate == 4 || associate == 5 || associate == 14) @@ -495,7 +495,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } default: - Game::logger->Log("MissionTask", "Invalid mission task type (%i)!\n", static_cast(type)); + Game::logger->Log("MissionTask", "Invalid mission task type (%i)!", static_cast(type)); return; } diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index 7e77cd77..b15d3bb6 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -93,7 +93,7 @@ void Mail::SendMail(const LWOOBJID sender, const std::string& senderName, LWOOBJ delete ins; if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) return; // TODO: Echo to chat server - + SendNotification(sysAddr, 1); //Show the "one new mail" message } @@ -152,7 +152,7 @@ void Mail::HandleMailStuff(RakNet::BitStream* packet, const SystemAddress& sysAd Mail::HandleSendMail(packet, sysAddr, entity); break; default: - Game::logger->Log("Mail", "Unhandled and possibly undefined MailStuffID: %i\n", int(stuffID)); + Game::logger->Log("Mail", "Unhandled and possibly undefined MailStuffID: %i", int(stuffID)); } }); } @@ -264,10 +264,10 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd Mail::SendSendResponse(sysAddr, Mail::MailSendResponse::Success); entity->GetCharacter()->SetCoins(entity->GetCharacter()->GetCoins() - mailCost, eLootSourceType::LOOT_SOURCE_MAIL); - Game::logger->Log("Mail", "Seeing if we need to remove item with ID/count/LOT: %i %i %i\n", itemID, attachmentCount, itemLOT); + Game::logger->Log("Mail", "Seeing if we need to remove item with ID/count/LOT: %i %i %i", itemID, attachmentCount, itemLOT); if (inv && itemLOT != 0 && attachmentCount > 0 && item) { - Game::logger->Log("Mail", "Trying to remove item with ID/count/LOT: %i %i %i\n", itemID, attachmentCount, itemLOT); + Game::logger->Log("Mail", "Trying to remove item with ID/count/LOT: %i %i %i", itemID, attachmentCount, itemLOT); inv->RemoveItem(itemLOT, attachmentCount, INVALID, true); auto* missionCompoent = entity->GetComponent(); diff --git a/dGame/dUtilities/Preconditions.cpp b/dGame/dUtilities/Preconditions.cpp index 2e006ec4..1b442f49 100644 --- a/dGame/dUtilities/Preconditions.cpp +++ b/dGame/dUtilities/Preconditions.cpp @@ -29,7 +29,7 @@ Precondition::Precondition(const uint32_t condition) { this->count = 1; this->values = { 0 }; - Game::logger->Log("Precondition", "Failed to find precondition of id (%i)!\n", condition); + Game::logger->Log("Precondition", "Failed to find precondition of id (%i)!", condition); return; } diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 4172884f..ecb3bbda 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -102,7 +102,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit break; } - //Game::logger->Log("SlashCommandHandler", "Received chat command \"%s\"\n", GeneralUtils::UTF16ToWTF8(command).c_str()); + //Game::logger->Log("SlashCommandHandler", "Received chat command \"%s\"", GeneralUtils::UTF16ToWTF8(command).c_str()); User* user = UserManager::Instance()->GetUser(sysAddr); if ((chatCommand == "setgmlevel" || chatCommand == "makegm" || chatCommand == "gmlevel") && user->GetMaxGMLevel() > GAME_MASTER_LEVEL_CIVILIAN) { @@ -145,7 +145,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit WorldPackets::SendGMLevelChange(sysAddr, success, user->GetMaxGMLevel(), entity->GetGMLevel(), level); GameMessages::SendChatModeUpdate(entity->GetObjectID(), level); entity->SetGMLevel(level); - Game::logger->Log("SlashCommandHandler", "User %s (%i) has changed their GM level to %i for charID %llu\n", user->GetUsername().c_str(), user->GetAccountID(), level, entity->GetObjectID()); + Game::logger->Log("SlashCommandHandler", "User %s (%i) has changed their GM level to %i for charID %llu", user->GetUsername().c_str(), user->GetAccountID(), level, entity->GetObjectID()); } } @@ -170,7 +170,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto* character = entity->GetComponent(); if (character == nullptr) { - Game::logger->Log("SlashCommandHandler", "Failed to find character component!\n"); + Game::logger->Log("SlashCommandHandler", "Failed to find character component!"); return; } @@ -289,7 +289,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit args.InsertValue("visible", new AMFTrueValue()); args.InsertValue("text", text); - Game::logger->Log("SlashCommandHandler", "Sending \n%s\n", customText.c_str()); + Game::logger->Log("SlashCommandHandler", "Sending %s", customText.c_str()); GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "ToggleStoryBox", &args); }); @@ -324,7 +324,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit const auto sysAddr = entity->GetSystemAddress(); - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", entity->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", entity->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (entity->GetCharacter()) { entity->GetCharacter()->SetZoneID(zoneID); @@ -344,7 +344,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ZoneInstanceManager::Instance()->RequestPrivateZone(Game::server, false, password, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (entity->GetCharacter()) { entity->GetCharacter()->SetZoneID(zoneID); @@ -920,7 +920,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit pos.SetY(y); pos.SetZ(z); - Game::logger->Log("SlashCommandHandler", "Teleporting objectID: %llu to %f, %f, %f\n", entity->GetObjectID(), pos.x, pos.y, pos.z); + Game::logger->Log("SlashCommandHandler", "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) { @@ -942,7 +942,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit pos.SetY(0.0f); pos.SetZ(z); - Game::logger->Log("SlashCommandHandler", "Teleporting objectID: %llu to X: %f, Z: %f\n", entity->GetObjectID(), pos.x, pos.z); + Game::logger->Log("SlashCommandHandler", "Teleporting objectID: %llu to X: %f, Z: %f", entity->GetObjectID(), pos.x, pos.z); GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /teleport () - if no Y given, will teleport to the height of the terrain (or any physics object)."); @@ -964,7 +964,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit EntityManager::Instance()->SerializeEntity(possassableEntity); - Game::logger->Log("ClientPackets", "Forced updated vehicle position\n"); + Game::logger->Log("ClientPackets", "Forced updated vehicle position"); } } } @@ -1522,7 +1522,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Transfering map..."); - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i\n", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (entity->GetCharacter()) { entity->GetCharacter()->SetZoneID(zoneID); entity->GetCharacter()->SetZoneInstance(zoneInstance); diff --git a/dGame/dUtilities/VanityUtilities.cpp b/dGame/dUtilities/VanityUtilities.cpp index c3f8f6b4..1b85077b 100644 --- a/dGame/dUtilities/VanityUtilities.cpp +++ b/dGame/dUtilities/VanityUtilities.cpp @@ -48,7 +48,7 @@ void VanityUtilities::SpawnVanity() std::vector npcList = m_NPCs; std::vector taken = {}; - Game::logger->Log("VanityUtilities", "Spawning party with %i locations\n", party.m_Locations.size()); + Game::logger->Log("VanityUtilities", "Spawning party with %i locations", party.m_Locations.size()); // Loop through all locations for (const auto& location : party.m_Locations) { @@ -187,7 +187,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* npcs = doc.FirstChildElement("npcs"); if (npcs == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPCs\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPCs"); return; } @@ -211,7 +211,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* locations = party->FirstChildElement("locations"); if (locations == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party locations\n"); + Game::logger->Log("VanityUtilities", "Failed to parse party locations"); continue; } @@ -228,7 +228,7 @@ void VanityUtilities::ParseXML(const std::string& file) if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr || rz == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party location data\n"); + Game::logger->Log("VanityUtilities", "Failed to parse party location data"); continue; } @@ -246,7 +246,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* partyPhrases = npcs->FirstChildElement("partyphrases"); if (partyPhrases == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party phrases\n"); + Game::logger->Log("VanityUtilities", "Failed to parse party phrases"); return; } @@ -256,7 +256,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* text = phrase->GetText(); if (text == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party phrase\n"); + Game::logger->Log("VanityUtilities", "Failed to parse party phrase"); continue; } @@ -268,7 +268,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* name = npc->Attribute("name"); if (name == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC name\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC name"); continue; } @@ -276,7 +276,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* lot = npc->Attribute("lot"); if (lot == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC lot\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC lot"); continue; } @@ -284,7 +284,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* equipment = npc->FirstChildElement("equipment"); if (equipment == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC equipment\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC equipment"); continue; } @@ -306,7 +306,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* phrases = npc->FirstChildElement("phrases"); if (phrases == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC phrases\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC phrases"); continue; } @@ -318,7 +318,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* text = phrase->GetText(); if (text == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC phrase\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC phrase"); continue; } @@ -334,7 +334,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* scriptNameAttribute = scriptElement->Attribute("name"); if (scriptNameAttribute == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC script name\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC script name"); continue; } @@ -358,7 +358,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* name = flag->Attribute("name"); if (name == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC flag name\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC flag name"); continue; } @@ -366,7 +366,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* value = flag->Attribute("value"); if (value == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC flag value\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC flag value"); continue; } @@ -380,7 +380,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* zoneID = zone->Attribute("id"); if (zoneID == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC zone ID\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC zone ID"); continue; } @@ -388,7 +388,7 @@ void VanityUtilities::ParseXML(const std::string& file) auto* locations = zone->FirstChildElement("locations"); if (locations == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC locations\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC locations"); continue; } @@ -405,7 +405,7 @@ void VanityUtilities::ParseXML(const std::string& file) if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr || rz == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC location data\n"); + Game::logger->Log("VanityUtilities", "Failed to parse NPC location data"); continue; } diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index 7df1449f..2c4c3287 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -26,7 +26,7 @@ InstanceManager::~InstanceManager() { } Instance * InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneID) { - mLogger->Log("InstanceManager", "Searching for an instance for mapID %i/%i\n", mapID, cloneID); + mLogger->Log("InstanceManager", "Searching for an instance for mapID %i/%i", mapID, cloneID); Instance* instance = FindInstance(mapID, isFriendTransfer, cloneID); if (instance) return instance; @@ -78,10 +78,10 @@ Instance * InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, L m_Instances.push_back(instance); if (instance) { - mLogger->Log("InstanceManager", "Created new instance: %i/%i/%i with min/max %i/%i\n", mapID, m_LastInstanceID, cloneID, softCap, maxPlayers); + mLogger->Log("InstanceManager", "Created new instance: %i/%i/%i with min/max %i/%i", mapID, m_LastInstanceID, cloneID, softCap, maxPlayers); return instance; } - else mLogger->Log("InstanceManager", "Failed to create a new instance!\n"); + else mLogger->Log("InstanceManager", "Failed to create a new instance!"); return nullptr; } @@ -92,7 +92,7 @@ bool InstanceManager::IsPortInUse(uint32_t port) { return true; } } - + return false; } @@ -102,7 +102,7 @@ uint32_t InstanceManager::GetFreePort() { for (Instance* i : m_Instances) { usedPorts.push_back(i->GetPort()); } - + std::sort(usedPorts.begin(), usedPorts.end()); int portIdx = 0; @@ -142,7 +142,7 @@ std::vector InstanceManager::GetInstances() const void InstanceManager::AddInstance(Instance* instance) { if (instance == nullptr) return; - + m_Instances.push_back(instance); } @@ -152,9 +152,9 @@ void InstanceManager::RemoveInstance(Instance* instance) { if (m_Instances[i] == instance) { instance->SetShutdownComplete(true); - + RedirectPendingRequests(instance); - + delete m_Instances[i]; m_Instances.erase(m_Instances.begin() + i); @@ -174,7 +174,7 @@ void InstanceManager::ReadyInstance(Instance* instance) { const auto& zoneId = instance->GetZoneID(); - Game::logger->Log("InstanceManager", "Responding to pending request %llu -> %i (%i)\n", request, zoneId.GetMapID(), zoneId.GetCloneID()); + Game::logger->Log("InstanceManager", "Responding to pending request %llu -> %i (%i)", request, zoneId.GetMapID(), zoneId.GetCloneID()); MasterPackets::SendZoneTransferResponse( Game::server, @@ -188,7 +188,7 @@ void InstanceManager::ReadyInstance(Instance* instance) instance->GetPort() ); } - + pending.clear(); } @@ -201,10 +201,10 @@ void InstanceManager::RequestAffirmation(Instance* instance, const PendingInstan PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_AFFIRM_TRANSFER_REQUEST); bitStream.Write(request.id); - + Game::server->Send(&bitStream, instance->GetSysAddr(), false); - - Game::logger->Log("MasterServer", "Sent affirmation request %llu to %i/%i\n", request.id, + + Game::logger->Log("MasterServer", "Sent affirmation request %llu to %i/%i", request.id, static_cast(instance->GetZoneID().GetMapID()), static_cast(instance->GetZoneID().GetCloneID()) ); @@ -217,7 +217,7 @@ void InstanceManager::AffirmTransfer(Instance* instance, const uint64_t transfer for (auto i = 0u; i < pending.size(); ++i) { const auto& request = pending[i]; - + if (request.id != transferID) continue; const auto& zoneId = instance->GetZoneID(); @@ -233,7 +233,7 @@ void InstanceManager::AffirmTransfer(Instance* instance, const uint64_t transfer instance->GetIP(), instance->GetPort() ); - + pending.erase(pending.begin() + i); break; @@ -243,7 +243,7 @@ void InstanceManager::AffirmTransfer(Instance* instance, const uint64_t transfer void InstanceManager::RedirectPendingRequests(Instance* instance) { const auto& zoneId = instance->GetZoneID(); - + for (const auto& request : instance->GetPendingAffirmations()) { auto* in = Game::im->GetInstance(zoneId.GetMapID(), false, zoneId.GetCloneID()); @@ -270,11 +270,11 @@ Instance* InstanceManager::GetInstanceBySysAddr(SystemAddress& sysAddr) { } bool InstanceManager::IsInstanceFull(Instance* instance, bool isFriendTransfer) { - if (!isFriendTransfer && instance->GetSoftCap() > instance->GetCurrentClientCount()) + if (!isFriendTransfer && instance->GetSoftCap() > instance->GetCurrentClientCount()) return false; - else if (isFriendTransfer && instance->GetHardCap() > instance->GetCurrentClientCount()) + else if (isFriendTransfer && instance->GetHardCap() > instance->GetCurrentClientCount()) return false; - + return true; } @@ -308,7 +308,7 @@ Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID clon } int maxPlayers = 999; - + uint32_t port = GetFreePort(); instance = new Instance(mExternalIP, port, mapID, ++m_LastInstanceID, cloneID, maxPlayers, maxPlayers, true, password); @@ -339,7 +339,7 @@ Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID clon m_Instances.push_back(instance); if (instance) return instance; - else mLogger->Log("InstanceManager", "Failed to create a new instance!\n"); + else mLogger->Log("InstanceManager", "Failed to create a new instance!"); return instance; } @@ -355,7 +355,7 @@ Instance* InstanceManager::FindPrivateInstance(const std::string& password) continue; } - mLogger->Log("InstanceManager", "Password: %s == %s => %d\n", password.c_str(), instance->GetPassword().c_str(), password == instance->GetPassword()); + mLogger->Log("InstanceManager", "Password: %s == %s => %d", password.c_str(), instance->GetPassword().c_str(), password == instance->GetPassword()); if (instance->GetPassword() == password) { @@ -375,7 +375,7 @@ int InstanceManager::GetSoftCap(LWOMAPID mapID) { return zone->population_soft_cap; } } - + return 8; } @@ -405,10 +405,10 @@ bool Instance::GetShutdownComplete() const void Instance::Shutdown() { CBITSTREAM; - + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SHUTDOWN); Game::server->Send(&bitStream, this->m_SysAddr, false); - - Game::logger->Log("Instance", "Triggered world shutdown\n"); + + Game::logger->Log("Instance", "Triggered world shutdown"); } diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index f71fd408..e679940b 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -75,16 +75,16 @@ int main(int argc, char** argv) { Game::logger = SetupLogger(); if (!Game::logger) return EXIT_FAILURE; - Game::logger->Log("MasterServer", "Starting Master server...\n"); - Game::logger->Log("MasterServer", "Version: %i.%i\n", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); - Game::logger->Log("MasterServer", "Compiled on: %s\n", __TIMESTAMP__); + Game::logger->Log("MasterServer", "Starting Master server..."); + Game::logger->Log("MasterServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); + Game::logger->Log("MasterServer", "Compiled on: %s", __TIMESTAMP__); //Read our config: dConfig config("masterconfig.ini"); Game::config = &config; Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); - + if (argc > 1 && (strcmp(argv[1], "-m") == 0 || strcmp(argv[1], "--migrations") == 0)) { //Connect to the MySQL Database std::string mysql_host = config.GetValue("mysql_host"); @@ -95,23 +95,23 @@ int main(int argc, char** argv) { try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); } catch (sql::SQLException& ex) { - Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s\n", ex.what()); - Game::logger->Log("MigrationRunner", "Migrations not run\n"); + Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s", ex.what()); + Game::logger->Log("MigrationRunner", "Migrations not run"); return EXIT_FAILURE; } MigrationRunner::RunMigrations(); - Game::logger->Log("MigrationRunner", "Finished running migrations\n"); + Game::logger->Log("MigrationRunner", "Finished running migrations"); return EXIT_SUCCESS; - } + } else { //Check CDClient exists const std::string cdclient_path = "./res/CDServer.sqlite"; std::ifstream cdclient_fd(cdclient_path); if (!cdclient_fd.good()) { - Game::logger->Log("WorldServer", "%s could not be opened\n", cdclient_path.c_str()); + Game::logger->Log("WorldServer", "%s could not be opened", cdclient_path.c_str()); return EXIT_FAILURE; } cdclient_fd.close(); @@ -120,9 +120,9 @@ int main(int argc, char** argv) { try { CDClientDatabase::Connect(cdclient_path); } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database\n"); - Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); + Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); + Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); return EXIT_FAILURE; } @@ -130,10 +130,10 @@ int main(int argc, char** argv) { try { CDClientManager::Instance()->Initialize(); } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database\n"); - Game::logger->Log("WorldServer", "May be caused by corrupted file: %s\n", cdclient_path.c_str()); - Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); + Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database"); + Game::logger->Log("WorldServer", "May be caused by corrupted file: %s", cdclient_path.c_str()); + Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); return EXIT_FAILURE; } @@ -146,7 +146,7 @@ int main(int argc, char** argv) { try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); } catch (sql::SQLException& ex) { - Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s\n", ex.what()); + Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s", ex.what()); return EXIT_FAILURE; } } @@ -368,14 +368,14 @@ dLogger* SetupLogger() { void HandlePacket(Packet* packet) { if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION) { - Game::logger->Log("MasterServer", "A server has disconnected\n"); + Game::logger->Log("MasterServer", "A server has disconnected"); //Since this disconnection is intentional, we'll just delete it as //we'll start a new one anyway if needed: Instance* instance = Game::im->GetInstanceBySysAddr(packet->systemAddress); if (instance) { - Game::logger->Log("MasterServer", "Actually disconnected from zone %i clone %i instance %i port %i\n", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); + Game::logger->Log("MasterServer", "Actually disconnected from zone %i clone %i instance %i port %i", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); Game::im->RemoveInstance(instance); //Delete the old } @@ -385,7 +385,7 @@ void HandlePacket(Packet* packet) { } if (packet->data[0] == ID_CONNECTION_LOST) { - Game::logger->Log("MasterServer", "A server has lost the connection\n"); + Game::logger->Log("MasterServer", "A server has lost the connection"); Instance* instance = Game::im->GetInstanceBySysAddr(packet->systemAddress); @@ -403,7 +403,7 @@ void HandlePacket(Packet* packet) { if (packet->data[1] == MASTER) { switch (packet->data[3]) { case MSG_MASTER_REQUEST_PERSISTENT_ID: { - Game::logger->Log("MasterServer", "A persistent ID req\n"); + Game::logger->Log("MasterServer", "A persistent ID req"); RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); uint64_t requestID = 0; @@ -415,7 +415,7 @@ void HandlePacket(Packet* packet) { } case MSG_MASTER_REQUEST_ZONE_TRANSFER: { - Game::logger->Log("MasterServer","Received zone transfer req\n"); + Game::logger->Log("MasterServer","Received zone transfer req"); RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); uint64_t requestID = 0; @@ -431,18 +431,18 @@ void HandlePacket(Packet* packet) { Instance* in = Game::im->GetInstance(zoneID, false, zoneClone); for (auto* instance : Game::im->GetInstances()) { - Game::logger->Log("MasterServer", "Instance: %i/%i/%i -> %i\n",instance->GetMapID(), instance->GetCloneID(),instance->GetInstanceID(), instance == in); + Game::logger->Log("MasterServer", "Instance: %i/%i/%i -> %i",instance->GetMapID(), instance->GetCloneID(),instance->GetInstanceID(), instance == in); } if (!in->GetIsReady()) //Instance not ready, make a pending request { in->GetPendingRequests().push_back({ requestID, static_cast(mythranShift), packet->systemAddress }); - Game::logger->Log("MasterServer", "Server not ready, adding pending request %llu %i %i\n", requestID, zoneID, zoneClone); + Game::logger->Log("MasterServer", "Server not ready, adding pending request %llu %i %i", requestID, zoneID, zoneClone); break; } //Instance is ready, transfer - Game::logger->Log("MasterServer", "Responding to transfer request %llu for zone %i %i\n", requestID, zoneID, zoneClone); + Game::logger->Log("MasterServer", "Responding to transfer request %llu for zone %i %i", requestID, zoneID, zoneClone); Game::im->RequestAffirmation(in, { requestID, static_cast(mythranShift), packet->systemAddress }); break; } @@ -494,7 +494,7 @@ void HandlePacket(Packet* packet) { chatServerMasterPeerSysAddr = copy; } - Game::logger->Log("MasterServer", "Received server info, instance: %i port: %i\n", theirInstanceID, theirPort); + Game::logger->Log("MasterServer", "Received server info, instance: %i port: %i", theirInstanceID, theirPort); break; } @@ -526,7 +526,7 @@ void HandlePacket(Packet* packet) { } activeSessions.insert(std::make_pair(sessionKey, username)); - Game::logger->Log("MasterServer", "Got sessionKey %i for user %s\n", sessionKey, username.c_str()); + Game::logger->Log("MasterServer", "Got sessionKey %i for user %s", sessionKey, username.c_str()); break; } @@ -564,7 +564,7 @@ void HandlePacket(Packet* packet) { instance->AddPlayer(Player()); } else { - printf("Instance missing? What?\n"); + printf("Instance missing? What?"); } break; } @@ -622,7 +622,7 @@ void HandlePacket(Packet* packet) { inStream.Read(requestID); inStream.Read(mythranShift); - + uint32_t len; inStream.Read(len); @@ -633,7 +633,7 @@ void HandlePacket(Packet* packet) { auto* instance = Game::im->FindPrivateInstance(password.c_str()); - Game::logger->Log( "MasterServer", "Join private zone: %llu %d %s %p\n", requestID, mythranShift, password.c_str(), instance); + Game::logger->Log( "MasterServer", "Join private zone: %llu %d %s %p", requestID, mythranShift, password.c_str(), instance); if (instance == nullptr) { return; @@ -656,16 +656,16 @@ void HandlePacket(Packet* packet) { inStream.Read(zoneID); inStream.Read(instanceID); - Game::logger->Log("MasterServer", "Got world ready %i %i\n",zoneID, instanceID); + Game::logger->Log("MasterServer", "Got world ready %i %i",zoneID, instanceID); auto* instance = Game::im->FindInstance(zoneID, instanceID); if (instance == nullptr) { - Game::logger->Log("MasterServer","Failed to find zone to ready\n"); + Game::logger->Log("MasterServer","Failed to find zone to ready"); return; } - Game::logger->Log("MasterServer", "Ready zone %i\n", zoneID); + Game::logger->Log("MasterServer", "Ready zone %i", zoneID); Game::im->ReadyInstance(instance); break; } @@ -677,7 +677,7 @@ void HandlePacket(Packet* packet) { int zoneID; inStream.Read(zoneID); - Game::logger->Log("MasterServer", "Prepping zone %i\n", zoneID); + Game::logger->Log("MasterServer", "Prepping zone %i", zoneID); Game::im->GetInstance(zoneID, false, 0); break; } @@ -690,7 +690,7 @@ void HandlePacket(Packet* packet) { inStream.Read(requestID); - Game::logger->Log("MasterServer","Got affirmation of transfer %llu\n",requestID); + Game::logger->Log("MasterServer","Got affirmation of transfer %llu",requestID); auto* instance =Game::im->GetInstanceBySysAddr(packet->systemAddress); @@ -698,7 +698,7 @@ void HandlePacket(Packet* packet) { return; Game::im->AffirmTransfer(instance, requestID); - Game::logger->Log("MasterServer", "Affirmation complete %llu\n",requestID); + Game::logger->Log("MasterServer", "Affirmation complete %llu",requestID); break; } @@ -712,19 +712,19 @@ void HandlePacket(Packet* packet) { return; } - Game::logger->Log("MasterServer", "Got shutdown response from zone %i clone %i instance %i port %i\n", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); + Game::logger->Log("MasterServer", "Got shutdown response from zone %i clone %i instance %i port %i", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance->GetPort()); instance->SetIsShuttingDown(true); break; } case MSG_MASTER_SHUTDOWN_UNIVERSE: { - Game::logger->Log("MasterServer","Received shutdown universe command, shutting down in 10 minutes.\n"); + Game::logger->Log("MasterServer","Received shutdown universe command, shutting down in 10 minutes."); shouldShutdown = true; break; } default: - Game::logger->Log("MasterServer","Unknown master packet ID from server: %i\n",packet->data[3]); + Game::logger->Log("MasterServer","Unknown master packet ID from server: %i",packet->data[3]); } } } @@ -780,7 +780,7 @@ void ShutdownSequence() { auto* objIdManager = ObjectIDManager::TryInstance(); if (objIdManager != nullptr) { objIdManager->SaveToDatabase(); - Game::logger->Log("MasterServer", "Saved ObjectIDTracker to DB\n"); + Game::logger->Log("MasterServer", "Saved ObjectIDTracker to DB"); } auto t = std::chrono::high_resolution_clock::now(); @@ -790,7 +790,7 @@ void ShutdownSequence() { exit(EXIT_SUCCESS); } - Game::logger->Log("MasterServer", "Attempting to shutdown instances, max 60 seconds...\n"); + Game::logger->Log("MasterServer", "Attempting to shutdown instances, max 60 seconds..."); while (true) { @@ -800,7 +800,7 @@ void ShutdownSequence() { Game::server->DeallocatePacket(packet); packet = nullptr; } - + auto done = true; for (auto* instance : Game::im->GetInstances()) { @@ -814,7 +814,7 @@ void ShutdownSequence() { } if (done) { - Game::logger->Log("MasterServer", "Finished shutting down MasterServer!\n"); + Game::logger->Log("MasterServer", "Finished shutting down MasterServer!"); break; } @@ -824,7 +824,7 @@ void ShutdownSequence() { ticks++; if (ticks == 600 * 6) { - Game::logger->Log("MasterServer", "Finished shutting down by timeout!\n"); + Game::logger->Log("MasterServer", "Finished shutting down by timeout!"); break; } } diff --git a/dMasterServer/ObjectIDManager.cpp b/dMasterServer/ObjectIDManager.cpp index 28a8ea17..160a3859 100644 --- a/dMasterServer/ObjectIDManager.cpp +++ b/dMasterServer/ObjectIDManager.cpp @@ -40,8 +40,8 @@ void ObjectIDManager::Initialize(dLogger *logger) { delete stmt; } catch (sql::SQLException &e) { mLogger->Log("ObjectIDManager", "Unable to fetch max persistent object " - "ID in use. Defaulting to 1.\n"); - mLogger->Log("ObjectIDManager", "SQL error: %s\n", e.what()); + "ID in use. Defaulting to 1."); + mLogger->Log("ObjectIDManager", "SQL error: %s", e.what()); this->currentPersistentID = 1; } } diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index c2aca466..0efce260 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -27,23 +27,23 @@ void AuthPackets::HandleHandshake(dServer* server, Packet* packet) { uint64_t header = inStream.Read(header); uint32_t clientVersion = 0; inStream.Read(clientVersion); - - server->GetLogger()->Log("AuthPackets", "Received client version: %i\n", clientVersion); + + server->GetLogger()->Log("AuthPackets", "Received client version: %i", clientVersion); SendHandshake(server, packet->systemAddress, server->GetIP(), server->GetPort()); } void AuthPackets::SendHandshake(dServer* server, const SystemAddress& sysAddr, const std::string& nextServerIP, uint16_t nextServerPort) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, SERVER, MSG_SERVER_VERSION_CONFIRM); - bitStream.Write(NET_VERSION); + bitStream.Write(NET_VERSION); bitStream.Write(uint32_t(0x93)); - + if (nextServerPort == 1001) bitStream.Write(uint32_t(1)); //Conn: auth else bitStream.Write(uint32_t(4)); //Conn: world - + bitStream.Write(uint32_t(0)); //Server process ID bitStream.Write(nextServerPort); - + server->Send(&bitStream, sysAddr, false); } @@ -55,15 +55,15 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { // Fetch account details sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT password, banned, locked, play_key_id, gm_level FROM accounts WHERE name=? LIMIT 1;"); stmt->setString(1, szUsername); - + sql::ResultSet* res = stmt->executeQuery(); - + if (res->rowsCount() == 0) { - server->GetLogger()->Log("AuthPackets", "No user found!\n"); + server->GetLogger()->Log("AuthPackets", "No user found!"); AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_WRONG_PASS_OR_USER, "", "", 2001, username); return; } - + std::string sqlPass = ""; bool sqlBanned = false; bool sqlLocked = false; @@ -77,7 +77,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { sqlPlayKey = res->getInt(4); sqlGmLevel = res->getInt(5); } - + delete stmt; delete res; @@ -92,7 +92,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { //Check to see if we have a play key: if (sqlPlayKey == 0 && sqlGmLevel == 0) { AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_PERMISSIONS_NOT_HIGH_ENOUGH, "Your account doesn't have a play key associated with it!", "", 2001, username); - server->GetLogger()->Log("AuthPackets", "User %s tried to log in, but they don't have a play key.\n", username.c_str()); + server->GetLogger()->Log("AuthPackets", "User %s tried to log in, but they don't have a play key.", username.c_str()); return; } @@ -101,7 +101,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { keyCheckStmt->setInt(1, sqlPlayKey); auto keyRes = keyCheckStmt->executeQuery(); bool isKeyActive = false; - + if (keyRes->rowsCount() == 0 && sqlGmLevel == 0) { AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_PERMISSIONS_NOT_HIGH_ENOUGH, "Your account doesn't have a play key associated with it!", "", 2001, username); return; @@ -113,13 +113,13 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { if (!isKeyActive && sqlGmLevel == 0) { AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_PERMISSIONS_NOT_HIGH_ENOUGH, "Your play key has been disabled.", "", 2001, username); - server->GetLogger()->Log("AuthPackets", "User %s tried to log in, but their play key was disabled\n", username.c_str()); + server->GetLogger()->Log("AuthPackets", "User %s tried to log in, but their play key was disabled", username.c_str()); return; } } - - if (sqlBanned) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_BANNED, "", "", 2001, username); return; + + if (sqlBanned) { + AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_BANNED, "", "", 2001, username); return; } if (sqlLocked) { @@ -131,7 +131,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { * First attempt bcrypt. * If that fails, fallback to old method and setup bcrypt for new login. */ - + bool loginSuccess = true; int32_t bcryptState = ::bcrypt_checkpw(password.c_str(), sqlPass.c_str()); @@ -162,7 +162,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { assert(bcryptState == 0); sql::PreparedStatement* accountUpdate = Database::CreatePreppedStmt("UPDATE accounts SET password = ? WHERE name = ? LIMIT 1;"); - + accountUpdate->setString(1, std::string(hash, BCRYPT_HASHSIZE).c_str()); accountUpdate->setString(2, szUsername); @@ -176,7 +176,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { if (!loginSuccess) { AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_WRONG_PASS_OR_USER, "", "", 2001, username); - server->GetLogger()->Log("AuthPackets", "Wrong password used\n"); + server->GetLogger()->Log("AuthPackets", "Wrong password used"); } else { SystemAddress system = packet->systemAddress; //Copy the sysAddr before the Packet gets destroyed from main @@ -185,7 +185,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { AuthPackets::SendLoginResponse(server, system, LOGIN_RESPONSE_GENERAL_FAILED, "", "", 0, username); return; } - + ZoneInstanceManager::Instance()->RequestZoneTransfer(server, 0, 0, false, [system, server, username](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string zoneIP, uint16_t zonePort) { AuthPackets::SendLoginResponse(server, system, LOGIN_RESPONSE_SUCCESS, "", zoneIP, zonePort, username); }); @@ -195,11 +195,11 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAddr, eLoginResponse responseCode, const std::string& errorMsg, const std::string& wServerIP, uint16_t wServerPort, std::string username) { RakNet::BitStream packet; PacketUtils::WriteHeader(packet, CLIENT, MSG_CLIENT_LOGIN_RESPONSE); - + packet.Write(static_cast(responseCode)); - + PacketUtils::WritePacketString("Talk_Like_A_Pirate", 33, &packet); - + // 7 unknown strings - perhaps other IP addresses? PacketUtils::WritePacketString("", 33, &packet); PacketUtils::WritePacketString("", 33, &packet); @@ -208,44 +208,44 @@ void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAdd PacketUtils::WritePacketString("", 33, &packet); PacketUtils::WritePacketString("", 33, &packet); PacketUtils::WritePacketString("", 33, &packet); - + packet.Write(static_cast(1)); // Version Major packet.Write(static_cast(10)); // Version Current packet.Write(static_cast(64)); // Version Minor - + // Writes the user key uint32_t sessionKey = rand(); // not mt but whatever std::string userHash = std::to_string(sessionKey); userHash = md5(userHash); PacketUtils::WritePacketWString(userHash, 33, &packet); - + // Write the Character and Chat IPs PacketUtils::WritePacketString(wServerIP, 33, &packet); PacketUtils::WritePacketString("", 33, &packet); - + // Write the Character and Chat Ports packet.Write(static_cast(wServerPort)); packet.Write(static_cast(0)); - + // Write another IP PacketUtils::WritePacketString("", 33, &packet); - + // Write a GUID or something... PacketUtils::WritePacketString("00000000-0000-0000-0000-000000000000", 37, &packet); - + packet.Write(static_cast(0)); // ??? - + // Write the localization PacketUtils::WritePacketString("US", 3, &packet); - + packet.Write(static_cast(false)); // User first logged in? packet.Write(static_cast(false)); // User is F2P? packet.Write(static_cast(0)); // ??? - + // Write custom error message packet.Write(static_cast(errorMsg.length())); PacketUtils::WritePacketWString(errorMsg, static_cast(errorMsg.length()), &packet); - + // Here write auth logs packet.Write(static_cast(20)); for (uint32_t i = 0; i < 20; ++i) { @@ -254,7 +254,7 @@ void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAdd packet.Write(static_cast(14000)); packet.Write(static_cast(0)); } - + server->Send(&packet, sysAddr, false); //Inform the master server that we've created a session for this user: @@ -265,6 +265,6 @@ void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAdd PacketUtils::WriteString(bitStream, username, 66); server->SendToMaster(&bitStream); - server->GetLogger()->Log("AuthPackets", "Set sessionKey: %i for user %s\n", sessionKey, username.c_str()); + server->GetLogger()->Log("AuthPackets", "Set sessionKey: %i for user %s", sessionKey, username.c_str()); } } diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index b9f715ad..00c16133 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -37,7 +37,7 @@ void ClientPackets::HandleChatMessage(const SystemAddress& sysAddr, Packet* packet) { User* user = UserManager::Instance()->GetUser(sysAddr); if (!user) { - Game::logger->Log("ClientPackets", "Unable to get user to parse chat message\n"); + Game::logger->Log("ClientPackets", "Unable to get user to parse chat message"); return; } @@ -71,14 +71,14 @@ void ClientPackets::HandleChatMessage(const SystemAddress& sysAddr, Packet* pack if (!user->GetLastChatMessageApproved() && !isMythran) return; std::string sMessage = GeneralUtils::UTF16ToWTF8(message); - Game::logger->Log("Chat", "%s: %s\n", playerName.c_str(), sMessage.c_str()); + Game::logger->Log("Chat", "%s: %s", playerName.c_str(), sMessage.c_str()); ChatPackets::SendChatMessage(sysAddr, chatChannel, playerName, user->GetLoggedInChar(), isMythran, message); } void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Packet* packet) { User* user = UserManager::Instance()->GetUser(sysAddr); if (!user) { - Game::logger->Log("ClientPackets", "Unable to get user to parse position update\n"); + Game::logger->Log("ClientPackets", "Unable to get user to parse position update"); return; } @@ -240,14 +240,14 @@ void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Pac void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Packet* packet) { User* user = UserManager::Instance()->GetUser(sysAddr); if (!user) { - Game::logger->Log("ClientPackets", "Unable to get user to parse chat moderation request\n"); + Game::logger->Log("ClientPackets", "Unable to get user to parse chat moderation request"); return; } auto* entity = Player::GetPlayer(sysAddr); if (entity == nullptr) { - Game::logger->Log("ClientPackets", "Unable to get player to parse chat moderation request\n"); + Game::logger->Log("ClientPackets", "Unable to get player to parse chat moderation request"); return; } diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index 54c925d6..f7a15c7f 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -18,7 +18,7 @@ void WorldPackets::SendLoadStaticZone(const SystemAddress& sysAddr, float x, float y, float z, uint32_t checksum) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_LOAD_STATIC_ZONE); - + auto zone = dZoneManager::Instance()->GetZone()->GetZoneID(); bitStream.Write(static_cast(zone.GetMapID())); bitStream.Write(static_cast(zone.GetInstanceID())); @@ -33,7 +33,7 @@ void WorldPackets::SendLoadStaticZone(const SystemAddress& sysAddr, float x, flo bitStream.Write(z); bitStream.Write(static_cast(0)); // Change this to eventually use 4 on activity worlds - + SEND_PACKET } @@ -42,23 +42,23 @@ void WorldPackets::SendCharacterList ( const SystemAddress& sysAddr, User* user RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_LIST_RESPONSE); - + std::vector characters = user->GetCharacters(); bitStream.Write(static_cast(characters.size())); bitStream.Write(static_cast(0)); //character index in front, just picking 0 - + for (uint32_t i = 0; i < characters.size(); ++i) { bitStream.Write(characters[i]->GetObjectID()); bitStream.Write(static_cast(0)); - + PacketUtils::WriteWString(bitStream, characters[i]->GetName(), 33); PacketUtils::WriteWString(bitStream, characters[i]->GetUnapprovedName(), 33); - + bitStream.Write(static_cast(characters[i]->GetNameRejected())); bitStream.Write(static_cast(false)); - + PacketUtils::WriteString(bitStream, "", 10); - + bitStream.Write(characters[i]->GetShirtColor()); bitStream.Write(characters[i]->GetShirtStyle()); bitStream.Write(characters[i]->GetPantsColor()); @@ -79,12 +79,12 @@ void WorldPackets::SendCharacterList ( const SystemAddress& sysAddr, User* user const auto& equippedItems = characters[i]->GetEquippedItems(); bitStream.Write(static_cast(equippedItems.size())); - + for (uint32_t j = 0; j < equippedItems.size(); ++j) { bitStream.Write(equippedItems[j]); } } - + SEND_PACKET } @@ -112,11 +112,11 @@ void WorldPackets::SendCharacterDeleteResponse(const SystemAddress& sysAddr, boo void WorldPackets::SendTransferToWorld ( const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift ) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_TRANSFER_TO_WORLD); - + PacketUtils::WriteString(bitStream, serverIP, 33); bitStream.Write(static_cast(serverPort)); bitStream.Write(static_cast(mythranShift)); - + SEND_PACKET } @@ -130,7 +130,7 @@ void WorldPackets::SendServerState ( const SystemAddress& sysAddr ) { void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CREATE_CHARACTER); - + RakNet::BitStream data; data.Write(7); //LDF key count @@ -155,7 +155,7 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent chatmode->WriteToPacket(&data); xmlConfigData->WriteToPacket(&data); reputation->WriteToPacket(&data); - + delete objid; delete lot; delete xmlConfigData; @@ -168,7 +168,7 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent bitStream.Write(data.GetNumberOfBytesUsed() + 1); bitStream.Write(0); bitStream.Write((char*)data.GetData(), data.GetNumberOfBytesUsed()); -#else +#else //Compress the data before sending: const int reservedSize = 5 * 1024 * 1024; uint8_t compressedData[reservedSize]; @@ -185,7 +185,7 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent PacketUtils::SavePacket("chardata.bin", (const char *)bitStream.GetData(), static_cast(bitStream.GetNumberOfBytesUsed())); SEND_PACKET - Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu\n", entity->GetObjectID()); + Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu", entity->GetObjectID()); } void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector> unacceptedItems) { @@ -215,11 +215,11 @@ void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool void WorldPackets::SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel) { CBITSTREAM PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAKE_GM_RESPONSE); - + bitStream.Write(success); bitStream.Write(highestLevel); bitStream.Write(prevLevel); bitStream.Write(newLevel); - + SEND_PACKET } diff --git a/dNet/dServer.cpp b/dNet/dServer.cpp index 27b6df7c..56a73c1f 100644 --- a/dNet/dServer.cpp +++ b/dNet/dServer.cpp @@ -13,7 +13,7 @@ //! Replica Constructor class class ReplicaConstructor : public ReceiveConstructionInterface { -public: +public: ReplicaReturnResult ReceiveConstruction(RakNet::BitStream *inBitStream, RakNetTime timestamp, NetworkID networkID, NetworkIDObject *existingObject, SystemAddress senderId, ReplicaManager *caller) { return REPLICA_PROCESSING_DONE; } @@ -60,11 +60,11 @@ dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnect if (mIsOkay) { if (zoneID == 0) - mLogger->Log("dServer", "Server is listening on %s:%i with encryption: %i\n", ip.c_str(), port, int(useEncryption)); + mLogger->Log("dServer", "Server is listening on %s:%i with encryption: %i", ip.c_str(), port, int(useEncryption)); else - mLogger->Log("dServer", "Server is listening on %s:%i with encryption: %i, running zone %i / %i\n", ip.c_str(), port, int(useEncryption), zoneID, instanceID); + mLogger->Log("dServer", "Server is listening on %s:%i with encryption: %i, running zone %i / %i", ip.c_str(), port, int(useEncryption), zoneID, instanceID); } - else { mLogger->Log("dServer", "FAILED TO START SERVER ON IP/PORT: %s:%i\n", ip.c_str(), port); return; } + else { mLogger->Log("dServer", "FAILED TO START SERVER ON IP/PORT: %s:%i", ip.c_str(), port); return; } mLogger->SetLogToConsole(prevLogSetting); @@ -104,13 +104,13 @@ Packet* dServer::ReceiveFromMaster() { if (packet->length < 1) { mMasterPeer->DeallocatePacket(packet); return nullptr; } if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || packet->data[0] == ID_CONNECTION_LOST) { - mLogger->Log("dServer", "Lost our connection to master, shutting DOWN!\n"); + mLogger->Log("dServer", "Lost our connection to master, shutting DOWN!"); mMasterConnectionActive = false; //ConnectToMaster(); //We'll just shut down now } - + if (packet->data[0] == ID_CONNECTION_REQUEST_ACCEPTED) { - mLogger->Log("dServer", "Established connection to master, zone (%i), instance (%i)\n",this->GetZoneID(), this->GetInstanceID()); + mLogger->Log("dServer", "Established connection to master, zone (%i), instance (%i)",this->GetZoneID(), this->GetInstanceID()); mMasterConnectionActive = true; mMasterSystemAddress = packet->systemAddress; MasterPackets::SendServerInfo(this, packet); diff --git a/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index bb918b23..4caaab40 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -13,7 +13,7 @@ void dpWorld::Initialize(unsigned int zoneID) { phys_sp_tilecount = std::atoi(Game::config->GetValue("phys_sp_tilecount").c_str()); phys_sp_tilesize = std::atoi(Game::config->GetValue("phys_sp_tilesize").c_str()); - //If spatial partitioning is enabled, then we need to create the m_Grid. + //If spatial partitioning is enabled, then we need to create the m_Grid. //if m_Grid exists, then the old method will be used. //SP will NOT be used unless it is added to ShouldUseSP(); if (std::atoi(Game::config->GetValue("phys_spatial_partitioning").c_str()) == 1 @@ -21,11 +21,11 @@ void dpWorld::Initialize(unsigned int zoneID) { m_Grid = new dpGrid(phys_sp_tilecount, phys_sp_tilesize); } - Game::logger->Log("dpWorld", "Physics world initialized!\n"); + Game::logger->Log("dpWorld", "Physics world initialized!"); if (ShouldLoadNavmesh(zoneID)) { - if (LoadNavmeshByZoneID(zoneID)) Game::logger->Log("dpWorld", "Loaded navmesh!\n"); - else Game::logger->Log("dpWorld", "Error(s) occurred during navmesh load.\n"); + if (LoadNavmeshByZoneID(zoneID)) Game::logger->Log("dpWorld", "Loaded navmesh!"); + else Game::logger->Log("dpWorld", "Error(s) occurred during navmesh load."); } } @@ -39,9 +39,9 @@ dpWorld::~dpWorld() { } void dpWorld::StepWorld(float deltaTime) { - if (m_Grid) { - m_Grid->Update(deltaTime); - return; + if (m_Grid) { + m_Grid->Update(deltaTime); + return; } //Pre update: @@ -53,7 +53,7 @@ void dpWorld::StepWorld(float deltaTime) { //Do actual update: for (auto entity : m_DynamicEntites) { if (!entity || entity->GetSleeping()) continue; - + entity->Update(deltaTime); for (auto other : m_StaticEntities) { @@ -135,7 +135,7 @@ bool dpWorld::LoadNavmeshByZoneID(unsigned int zoneID) { dtNavMesh* dpWorld::LoadNavmesh(const char* path) { FILE* fp; - + #ifdef _WIN32 fopen_s(&fp, path, "rb"); #elif __APPLE__ @@ -144,7 +144,7 @@ dtNavMesh* dpWorld::LoadNavmesh(const char* path) { #else fp = fopen64(path, "rb"); #endif - + if (!fp) { return 0; } @@ -272,7 +272,7 @@ std::vector dpWorld::GetPath(const NiPoint3& startPos, const NiPoint3& //how many points to generate between start/end? //note: not actually 100% accurate due to rounding, but worst case it causes them to go a tiny bit faster //than their speed value would normally allow at the end. - int numPoints = startPos.Distance(startPos, endPos) / speed; + int numPoints = startPos.Distance(startPos, endPos) / speed; path.push_back(startPos); //insert the start pos diff --git a/dScripts/ActivityManager.cpp b/dScripts/ActivityManager.cpp index e464b20d..56766482 100644 --- a/dScripts/ActivityManager.cpp +++ b/dScripts/ActivityManager.cpp @@ -51,7 +51,7 @@ float_t ActivityManager::GetActivityValue(Entity *self, const LWOOBJID playerID, void ActivityManager::StopActivity(Entity *self, const LWOOBJID playerID, const uint32_t score, const uint32_t value1, const uint32_t value2, bool quit) { int32_t gameID = 0; - + auto* sac = self->GetComponent(); if (sac == nullptr) { gameID = self->GetLOT(); @@ -125,7 +125,7 @@ void ActivityManager::ActivityTimerStart(Entity *self, const std::string& timerN auto* timer = new ActivityTimer { timerName, updateInterval, stopTime }; activeTimers.push_back(timer); - Game::logger->Log("ActivityManager", "Starting timer '%s', %f, %f\n", timerName.c_str(), updateInterval, stopTime); + Game::logger->Log("ActivityManager", "Starting timer '%s', %f, %f", timerName.c_str(), updateInterval, stopTime); self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); } @@ -147,7 +147,7 @@ float_t ActivityManager::ActivityTimerGetCurrentTime(Entity *self, const std::st int32_t ActivityManager::GetGameID(Entity *self) const { int32_t gameID = 0; - + auto* sac = self->GetComponent(); if (sac == nullptr) { gameID = self->GetLOT(); @@ -208,10 +208,10 @@ void ActivityManager::OnTimerDone(Entity *self, std::string timerName) { activeTimers.erase(std::remove(activeTimers.begin(), activeTimers.end(), timer), activeTimers.end()); delete timer; - Game::logger->Log("ActivityManager", "Executing timer '%s'\n", activityTimerName.c_str()); + Game::logger->Log("ActivityManager", "Executing timer '%s'", activityTimerName.c_str()); OnActivityTimerDone(self, activityTimerName); } else { - Game::logger->Log("ActivityManager", "Updating timer '%s'\n", activityTimerName.c_str()); + Game::logger->Log("ActivityManager", "Updating timer '%s'", activityTimerName.c_str()); OnActivityTimerUpdate(self, timer->name, timer->stopTime - timer->runTime, timer->runTime); self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); } diff --git a/dScripts/AgJetEffectServer.cpp b/dScripts/AgJetEffectServer.cpp index 599f4d01..7336c8b8 100644 --- a/dScripts/AgJetEffectServer.cpp +++ b/dScripts/AgJetEffectServer.cpp @@ -49,20 +49,20 @@ void AgJetEffectServer::OnRebuildComplete(Entity* self, Entity* target) auto* effect = entities[0]; auto groups = self->GetGroups(); - + if (groups.empty()) { return; } builder = target->GetObjectID(); - + const auto group = groups[0]; GameMessages::SendPlayAnimation(effect, u"jetFX"); self->AddTimer("PlayEffect", 2.5f); - + if (group == "Base_Radar") { self->AddTimer("CineDone", 5); @@ -88,7 +88,7 @@ void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) } const auto size = entities.size(); - + if (size == 0) { return; @@ -98,7 +98,7 @@ void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) auto* mortar = entities[selected]; - Game::logger->Log("AgJetEffectServer", "Mortar (%i) (&d)\n", mortar->GetLOT(), mortar->HasComponent(COMPONENT_TYPE_SKILL)); + Game::logger->Log("AgJetEffectServer", "Mortar (%i) (&d)", mortar->GetLOT(), mortar->HasComponent(COMPONENT_TYPE_SKILL)); mortar->SetOwnerOverride(builder); diff --git a/dScripts/BaseRandomServer.cpp b/dScripts/BaseRandomServer.cpp index 7026178c..c2d335c4 100644 --- a/dScripts/BaseRandomServer.cpp +++ b/dScripts/BaseRandomServer.cpp @@ -4,7 +4,7 @@ #include "dLogger.h" #include "Entity.h" -void BaseRandomServer::BaseStartup(Entity* self) +void BaseRandomServer::BaseStartup(Entity* self) { self->SetVar(u"SpawnState", "min"); self->SetVar(u"JustChanged", false); @@ -13,12 +13,12 @@ void BaseRandomServer::BaseStartup(Entity* self) SpawnMapZones(self); } -void BaseRandomServer::CheckEvents(Entity* self) +void BaseRandomServer::CheckEvents(Entity* self) { // TODO: Add events? } -void BaseRandomServer::SpawnMapZones(Entity* self) +void BaseRandomServer::SpawnMapZones(Entity* self) { for (const auto& pair : sectionMultipliers) { @@ -35,13 +35,13 @@ void BaseRandomServer::SpawnMapZones(Entity* self) self->SetVar(u"bInit", true); } -void BaseRandomServer::SpawnSection(Entity* self, const std::string& sectionName, float iMultiplier) +void BaseRandomServer::SpawnSection(Entity* self, const std::string& sectionName, float iMultiplier) { Zone* spawnLoad = GetRandomLoad(self, sectionName); if (spawnLoad == nullptr) { - Game::logger->Log("BaseRandomServer", "Failed to find section: %s\n", sectionName.c_str()); + Game::logger->Log("BaseRandomServer", "Failed to find section: %s", sectionName.c_str()); return; } @@ -60,7 +60,7 @@ void BaseRandomServer::SpawnSection(Entity* self, const std::string& sectionName } } -void BaseRandomServer::SetSpawnerNetwork(Entity* self, const std::string& spawnerName, int32_t spawnNum, LOT spawnLOT) +void BaseRandomServer::SetSpawnerNetwork(Entity* self, const std::string& spawnerName, int32_t spawnNum, LOT spawnLOT) { const auto& spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); @@ -71,7 +71,7 @@ void BaseRandomServer::SetSpawnerNetwork(Entity* self, const std::string& spawne if (spawners.empty()) { - Game::logger->Log("BaseRandomServer", "Failed to find spawner: %s\n", spawnerName.c_str()); + Game::logger->Log("BaseRandomServer", "Failed to find spawner: %s", spawnerName.c_str()); return; } @@ -108,7 +108,7 @@ void BaseRandomServer::SetSpawnerNetwork(Entity* self, const std::string& spawne spawnersWatched.push_back(spawner); } -BaseRandomServer::Zone* BaseRandomServer::GetRandomLoad(Entity* self, const std::string& sectionName) +BaseRandomServer::Zone* BaseRandomServer::GetRandomLoad(Entity* self, const std::string& sectionName) { const auto zoneInfo = GeneralUtils::SplitString(sectionName, '_'); @@ -135,7 +135,7 @@ BaseRandomServer::Zone* BaseRandomServer::GetRandomLoad(Entity* self, const std: return nullptr; } -void BaseRandomServer::NotifySpawnerOfDeath(Entity* self, Spawner* spawner) +void BaseRandomServer::NotifySpawnerOfDeath(Entity* self, Spawner* spawner) { const auto& spawnerName = spawner->GetName(); @@ -164,29 +164,29 @@ void BaseRandomServer::NotifySpawnerOfDeath(Entity* self, Spawner* spawner) self->SetVar(variableName, mobDeathCount); } -void BaseRandomServer::NamedEnemyDeath(Entity* self, Spawner* spawner) +void BaseRandomServer::NamedEnemyDeath(Entity* self, Spawner* spawner) { const auto spawnDelay = GeneralUtils::GenerateRandomNumber(1, 2) * 450; self->AddTimer("SpawnNewEnemy", spawnDelay); } -void BaseRandomServer::SpawnersUp(Entity* self) +void BaseRandomServer::SpawnersUp(Entity* self) { } -void BaseRandomServer::SpawnersDown(Entity* self) +void BaseRandomServer::SpawnersDown(Entity* self) { } -void BaseRandomServer::BaseOnTimerDone(Entity* self, const std::string& timerName) +void BaseRandomServer::BaseOnTimerDone(Entity* self, const std::string& timerName) { NamedTimerDone(self, timerName); } -void BaseRandomServer::SpawnNamedEnemy(Entity* self) +void BaseRandomServer::SpawnNamedEnemy(Entity* self) { const auto enemy = namedMobs[GeneralUtils::GenerateRandomNumber(0, namedMobs.size() - 1)]; diff --git a/dScripts/BossSpiderQueenEnemyServer.cpp b/dScripts/BossSpiderQueenEnemyServer.cpp index dd0b80c8..88f05a4b 100644 --- a/dScripts/BossSpiderQueenEnemyServer.cpp +++ b/dScripts/BossSpiderQueenEnemyServer.cpp @@ -22,7 +22,7 @@ void BossSpiderQueenEnemyServer::OnStartup(Entity* self) { // Make immune to stuns //self:SetStunImmunity{ StateChangeType = "PUSH", bImmuneToStunAttack = true, bImmuneToStunMove = true, bImmuneToStunTurn = true, bImmuneToStunUseItem = true, bImmuneToStunEquip = true, bImmuneToStunInteract = true, bImmuneToStunJump = true } - + // Make immune to knockbacks and pulls //self:SetStatusImmunity{ StateChangeType = "PUSH", bImmuneToPullToPoint = true, bImmuneToKnockback = true, bImmuneToInterrupt = true } @@ -60,7 +60,7 @@ void BossSpiderQueenEnemyServer::OnDie(Entity* self, Entity* killer) { missionComponent->CompleteMission(instanceMissionID); } - Game::logger->Log("BossSpiderQueenEnemyServer", "Starting timer...\n"); + Game::logger->Log("BossSpiderQueenEnemyServer", "Starting timer..."); // There is suppose to be a 0.1 second delay here but that may be admitted? auto* controller = EntityManager::Instance()->GetZoneControlEntity(); @@ -88,15 +88,15 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra //First rotate for anim NiQuaternion rot = NiQuaternion::IDENTITY; - + controllable->SetStatic(false); controllable->SetRotation(rot); - + controllable->SetStatic(true); - + controllable->SetDirtyPosition(true); - + rot = controllable->GetRotation(); EntityManager::Instance()->SerializeEntity(self); @@ -122,10 +122,10 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra } else { controllable->SetStatic(false); - + //Cancel all remaining timers for say idle anims: self->CancelAllTimers(); - + auto* baseCombatAi = self->GetComponent(); baseCombatAi->SetDisabled(false); @@ -133,7 +133,7 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra // Move the Spider to its ground location // preparing its stage attacks, and removing invulnerability //destroyable->SetIsImmune(false); - + // Run the advance animation and prepare a timer for resuming AI float animTime = PlayAnimAndReturnTime(self, spiderAdvanceAnim); animTime += 1.f; @@ -142,19 +142,19 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra destroyable->SetFaction(4); destroyable->SetIsImmune(false); - + //Advance stage m_CurrentBossStage++; //Reset the current wave death counter m_DeathCounter = 0; - + EntityManager::Instance()->SerializeEntity(self); // Prepare a timer for post leap attack self->AddTimer("AdvanceAttack", attackPause); - // Prepare a timer for post leap + // Prepare a timer for post leap self->AddTimer("AdvanceComplete", animTime); } @@ -162,7 +162,7 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra } void BossSpiderQueenEnemyServer::SpawnSpiderWave(Entity* self, int spiderCount) { - // The Spider Queen Boss is withdrawing and requesting the spawn + // The Spider Queen Boss is withdrawing and requesting the spawn // of a hatchling wave /*auto SpiderEggNetworkID = self->GetI64(u"SpiderEggNetworkID"); @@ -176,7 +176,7 @@ void BossSpiderQueenEnemyServer::SpawnSpiderWave(Entity* self, int spiderCount) hatchCounter = spiderCount; hatchList = {}; - Game::logger->Log("SpiderQueen", "Trying to spawn %i spiders\n", hatchCounter); + Game::logger->Log("SpiderQueen", "Trying to spawn %i spiders", hatchCounter); // Run the wave manager @@ -189,19 +189,19 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { // Reset the spider egg spawner network to ensure a maximum number of eggs //SpiderEggNetworkID:SpawnerReset() - + // Obtain a list of all the eggs on the egg spawner network //auto spiderEggList = SpiderEggNetworkID:SpawnerGetAllObjectIDsSpawned().objects; - //if (table.maxn(spiderEggList) <= 0) { + //if (table.maxn(spiderEggList) <= 0) { // self->AddTimer("PollSpiderWaveManager", 1.0f); // return; //} // //// A check for (wave mangement across multiple spawn iterations //if(hatchCounter < spiderWaveCnt) { - // // We have already prepped some objects for (hatching, + // // We have already prepped some objects for (hatching, // // remove them from our list for (random egg pulls // for (i, sVal in ipairs(spiderEggList) { // if(hatchList[sVal:GetID()]) { @@ -220,8 +220,8 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { for (auto spodder : spooders) { spiderEggs.push_back(spodder->GetObjectID()); } - - // Select a number of random spider eggs from the list equal to the + + // Select a number of random spider eggs from the list equal to the // current number needed to complete the current wave for (int i = 0; i < hatchCounter; i++) { // Select a random spider egg @@ -235,7 +235,7 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { randomEgg = spiderEggs[randomEggLoc]; } } - + if (randomEgg) { auto* eggEntity = EntityManager::Instance()->GetEntity(randomEgg); @@ -246,24 +246,24 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { // Prep the selected spider egg //randomEgg:FireEvent{s}erID=self, args="prepEgg"} eggEntity->OnFireEventServerSide(self, "prepEgg"); - Game::logger->Log("SpiderQueen", "Prepping egg %llu\n", eggEntity->GetObjectID()); - + Game::logger->Log("SpiderQueen", "Prepping egg %llu", eggEntity->GetObjectID()); + // Add the prepped egg to our hatchList hatchList.push_back(eggEntity->GetObjectID()); // Decrement the hatchCounter hatchCounter = hatchCounter - 1; } - + // Remove it from our spider egg list //table.remove(spiderEggList, randomEggLoc); spiderEggs[randomEggLoc] = LWOOBJID_EMPTY; - - if (spiderEggs.size() <= 0 || (hatchCounter <= 0)) { + + if (spiderEggs.size() <= 0 || (hatchCounter <= 0)) { break; } } - + if (hatchCounter > 0) { // We still have more eggs to hatch, poll the SpiderWaveManager again self->AddTimer("PollSpiderWaveManager", 1.0f); @@ -280,20 +280,20 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { } eggEntity->OnFireEventServerSide(self, "hatchEgg"); - Game::logger->Log("SpiderQueen", "hatching egg %llu\n", eggEntity->GetObjectID()); + Game::logger->Log("SpiderQueen", "hatching egg %llu", eggEntity->GetObjectID()); auto time = PlayAnimAndReturnTime(self, spiderWithdrawIdle); combat->SetStunImmune(false); combat->Stun(time += 6.0f); combat->SetStunImmune(true); - + //self->AddTimer("disableWaitForIdle", defaultAnimPause); self->AddTimer("checkForSpiders", 6.0f); } hatchList.clear(); - + } } @@ -322,7 +322,7 @@ void BossSpiderQueenEnemyServer::RunRainOfFire(Entity* self) for (const auto& rofGroup : ROFTargetGroupIDTable) { const auto spawners = dZoneManager::Instance()->GetSpawnersInGroup(rofGroup); - + std::vector spawned; for (auto* spawner : spawners) @@ -352,7 +352,7 @@ void BossSpiderQueenEnemyServer::RunRainOfFire(Entity* self) self->AddTimer("StartROF", animTime); } -void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) +void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) { if (!impactList.empty()) { @@ -362,7 +362,7 @@ void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) if (entity == nullptr) { - Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find impact!\n"); + Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find impact!"); return; } @@ -371,8 +371,8 @@ void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) if (skillComponent == nullptr) { - Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find impact skill component!\n"); - + Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find impact skill component!"); + return; } @@ -384,7 +384,7 @@ void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) } ToggleForSpecial(self, false); - + self->AddTimer("ROF", GeneralUtils::GenerateRandomNumber(20, 40)); } @@ -402,7 +402,7 @@ void BossSpiderQueenEnemyServer::RapidFireShooterManager(Entity* self) } const auto target = attackTargetTable[0]; - + auto* skillComponent = self->GetComponent(); skillComponent->CalculateBehavior(1394, 32612, target, true); @@ -412,7 +412,7 @@ void BossSpiderQueenEnemyServer::RapidFireShooterManager(Entity* self) self->AddTimer("PollRFSManager", 0.3f); } -void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) +void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) { /* const auto targets = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER); @@ -429,7 +429,7 @@ void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) if (targets.empty()) { - Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find RFS targets\n"); + Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find RFS targets"); self->AddTimer("RFS", GeneralUtils::GenerateRandomNumber(5, 10)); @@ -452,7 +452,7 @@ void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) PlayAnimAndReturnTime(self, spiderSingleShot); - Game::logger->Log("BossSpiderQueenEnemyServer", "Ran RFS\n"); + Game::logger->Log("BossSpiderQueenEnemyServer", "Ran RFS"); self->AddTimer("RFS", GeneralUtils::GenerateRandomNumber(10, 15)); } @@ -487,7 +487,7 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim //If there are still baby spiders, don't do anyhting either const auto spiders = EntityManager::Instance()->GetEntitiesInGroup("BabySpider"); - if (spiders.size() > 0) + if (spiders.size() > 0) self->AddTimer("checkForSpiders", time); else WithdrawSpider(self, false); @@ -496,30 +496,30 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim //Call the manager again to attempt to initiate an impact on another random location //Run the ROF Manager RainOfFireManager(self); - + } else if ( timerName == "PollRFSManager") { //Call the manager again to attempt to initiate a rapid fire shot at the next sequential target //Run the ROF Manager RapidFireShooterManager(self); - + } else if ( timerName == "StartROF") { //Re-enable Spider Boss //ToggleForSpecial(self, false); - + RainOfFireManager(self); - + } else if ( timerName == "PollSpiderSkillManager") { //Call the skill manager again to attempt to run the current Spider Boss //stage's special attack again //SpiderSkillManager(self, true); PlayAnimAndReturnTime(self, spiderJeerAnim); - + } else if ( timerName == "RFS") { RunRapidFireShooter(self); } else if ( timerName == "ROF") { RunRainOfFire(self); - } else if ( timerName == "RFSTauntComplete") { - //Determine an appropriate random time to check our manager again + } else if ( timerName == "RFSTauntComplete") { + //Determine an appropriate random time to check our manager again // local spiderCooldownDelay = math.random(s1DelayMin, s1DelayMax) //Set a timer based on our random cooldown determination @@ -529,7 +529,7 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim //Re-enable Spider Boss //ToggleForSpecial(self, false); - + } else if ( timerName == "WithdrawComplete") { //Play the Spider Boss' mountain idle anim PlayAnimAndReturnTime(self, spiderWithdrawIdle); @@ -545,19 +545,19 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim if (currentStage > 1) hatchCounter++; SpawnSpiderWave(self, spiderWaveCntTable[currentStage - 1]); - - } else if ( timerName == "AdvanceAttack") { + + } else if ( timerName == "AdvanceAttack") { //TODO: Can we even do knockbacks yet? @Wincent01 // Yes ^ //Fire the melee smash skill to throw players back /*local landingTarget = self:GetVar("LandingTarget") or false - + if((landingTarget) and (landingTarget:Exists())) { local advSmashFlag = landingTarget:CastSkill{skillID = bossLandingSkill} landingTarget:PlayEmbeddedEffectOnAllClientsNearObject{radius = 100, fromObjectID = landingTarget, effectName = "camshake-bridge"} }*/ - + auto landingTarget = self->GetI64(u"LandingTarget"); auto landingEntity = EntityManager::Instance()->GetEntity(landingTarget); @@ -567,7 +567,7 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim { skillComponent->CalculateBehavior(bossLandingSkill, 37739, LWOOBJID_EMPTY); } - + if (landingEntity) { auto* landingSkill = landingEntity->GetComponent(); @@ -578,12 +578,12 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim } GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(self, u"camshake-bridge", self->GetObjectID(), 100.0f); - - } else if ( timerName == "AdvanceComplete") { + + } else if ( timerName == "AdvanceComplete") { //Reset faction and collision /*local SBFactionList = self:GetVar("SBFactionList") local SBCollisionGroup = self:GetVar("SBCollisionGroup") - + for i, fVal in ipairs(SBFactionList) { if(i == 1) { //Our first faction - flush and add @@ -596,18 +596,18 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim /* auto SBCollisionGroup = self->GetI32(u"SBCollisionGroup"); - + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SetColGroup", SBCollisionGroup, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); */ - + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SetColGroup", 11, 0, 0, "", UNASSIGNED_SYSTEM_ADDRESS); //Wind up, telegraphing next round float animTime = PlayAnimAndReturnTime(self, spiderJeerAnim); self->AddTimer("AdvanceTauntComplete", animTime); - + } else if ( timerName == "AdvanceTauntComplete") { - + //Declare a default special Spider Boss skill cooldown int spiderCooldownDelay = 10; @@ -620,11 +620,11 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim //Set a timer based on our random cooldown determination //to pulse the SpiderSkillManager self->AddTimer("PollSpiderSkillManager", spiderCooldownDelay); - + //Remove current status immunity /*self:SetStatusImmunity{ StateChangeType = "POP", bImmuneToSpeed = true, bImmuneToBasicAttack = true, bImmuneToDOT = true} - - self:SetStunned{StateChangeType = "POP", + + self:SetStunned{StateChangeType = "POP", bCantMove = true, bCantJump = true, bCantTurn = true, @@ -638,14 +638,14 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim destroyable->SetFaction(4); EntityManager::Instance()->SerializeEntity(self); - + } else if ( timerName == "Clear") { EntityManager::Instance()->FireEventServerSide(self, "ClearProperty"); self->CancelAllTimers(); } else if ( timerName == "UnlockSpecials") { //We no longer need to lock specials self->SetBoolean(u"bSpecialLock", false); - + //Did we queue a spcial attack? if(self->GetBoolean(u"bSpecialQueued")) { self->SetBoolean(u"bSpecialQueued", false); @@ -723,17 +723,17 @@ float BossSpiderQueenEnemyServer::PlayAnimAndReturnTime(Entity* self, const std: //TODO: Get the actual animation time // Get the anim time - float animTimer = defaultAnimPause; //self:GetAnimationTime{animationID = animID}.time - + float animTimer = defaultAnimPause; //self:GetAnimationTime{animationID = animID}.time + // If we have an animation play it if (animTimer > 0) { GameMessages::SendPlayAnimation(self, animID); } - + // If the anim time is less than the the default time use default if (animTimer < defaultAnimPause) { animTimer = defaultAnimPause; } - + return animTimer; } diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 420394bb..8feb8ae7 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -818,7 +818,7 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = invalidToReturn; else if (script == invalidToReturn) { if (scriptName.length() > 0) - Game::logger->LogDebug("CppScripts", "Attempted to load CppScript for '" + scriptName + "', but returned InvalidScript.\n"); + Game::logger->LogDebug("CppScripts", "Attempted to load CppScript for '" + scriptName + "', but returned InvalidScript."); // information not really needed for sys admins but is for developers script = invalidToReturn; diff --git a/dScripts/FlameJetServer.cpp b/dScripts/FlameJetServer.cpp index 0e6d91cc..936f2a94 100644 --- a/dScripts/FlameJetServer.cpp +++ b/dScripts/FlameJetServer.cpp @@ -2,7 +2,7 @@ #include "SkillComponent.h" #include "GameMessages.h" -void FlameJetServer::OnStartup(Entity* self) +void FlameJetServer::OnStartup(Entity* self) { if (self->GetVar(u"NotActive")) { @@ -12,7 +12,7 @@ void FlameJetServer::OnStartup(Entity* self) self->SetNetworkVar(u"FlameOn", true); } -void FlameJetServer::OnCollisionPhantom(Entity* self, Entity* target) +void FlameJetServer::OnCollisionPhantom(Entity* self, Entity* target) { if (!target->IsPlayer()) { @@ -42,9 +42,9 @@ void FlameJetServer::OnCollisionPhantom(Entity* self, Entity* target) GameMessages::SendKnockback(target->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 1000, dir); } -void FlameJetServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) +void FlameJetServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { - Game::logger->Log("FlameJetServer::OnFireEventServerSide", "Event: %s\n", args.c_str()); + Game::logger->Log("FlameJetServer::OnFireEventServerSide", "Event: %s", args.c_str()); if (args == "OnActivated") { diff --git a/dScripts/FvMaelstromDragon.cpp b/dScripts/FvMaelstromDragon.cpp index afdfa4ae..66e7de85 100644 --- a/dScripts/FvMaelstromDragon.cpp +++ b/dScripts/FvMaelstromDragon.cpp @@ -4,7 +4,7 @@ #include "BaseCombatAIComponent.h" #include "DestroyableComponent.h" -void FvMaelstromDragon::OnStartup(Entity* self) +void FvMaelstromDragon::OnStartup(Entity* self) { self->SetVar(u"weakspot", 0); @@ -16,7 +16,7 @@ void FvMaelstromDragon::OnStartup(Entity* self) } } -void FvMaelstromDragon::OnDie(Entity* self, Entity* killer) +void FvMaelstromDragon::OnDie(Entity* self, Entity* killer) { if (self->GetVar(u"bDied")) { @@ -68,7 +68,7 @@ void FvMaelstromDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_ if (destroyableComponent != nullptr) { - Game::logger->Log("FvMaelstromDragon", "Hit %i\n", destroyableComponent->GetArmor()); + Game::logger->Log("FvMaelstromDragon", "Hit %i", destroyableComponent->GetArmor()); if (destroyableComponent->GetArmor() > 0) return; @@ -76,7 +76,7 @@ void FvMaelstromDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_ if (weakpoint == 0) { - Game::logger->Log("FvMaelstromDragon", "Activating weakpoint\n"); + Game::logger->Log("FvMaelstromDragon", "Activating weakpoint"); self->AddTimer("ReviveTimer", 12); @@ -141,7 +141,7 @@ void FvMaelstromDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_ } } -void FvMaelstromDragon::OnTimerDone(Entity* self, std::string timerName) +void FvMaelstromDragon::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "ReviveHeldTimer") { @@ -187,7 +187,7 @@ FvMaelstromDragon::OnFireEventServerSide(Entity *self, Entity *sender, std::stri int32_t param3) { if (args != "rebuildDone") return; - + self->AddTimer("ExposeWeakSpotTimer", 3.8f); self->CancelTimer("ReviveTimer"); diff --git a/dScripts/NjMonastryBossInstance.cpp b/dScripts/NjMonastryBossInstance.cpp index cd34ea2c..2aa7222e 100644 --- a/dScripts/NjMonastryBossInstance.cpp +++ b/dScripts/NjMonastryBossInstance.cpp @@ -92,7 +92,7 @@ void NjMonastryBossInstance::OnPlayerExit(Entity *self, Entity *player) { UpdatePlayer(self, player->GetObjectID(), true); // Fetch the total players loaded from the vars auto totalPlayersLoaded = self->GetVar >(TotalPlayersLoadedVariable); - + // Find the player to remove auto playerToRemove = std::find(totalPlayersLoaded.begin(), totalPlayersLoaded.end(), player->GetObjectID()); @@ -100,7 +100,7 @@ void NjMonastryBossInstance::OnPlayerExit(Entity *self, Entity *player) { if (playerToRemove != totalPlayersLoaded.end()) { totalPlayersLoaded.erase(playerToRemove); } else { - Game::logger->Log("NjMonastryBossInstance", "Failed to remove player at exit.\n"); + Game::logger->Log("NjMonastryBossInstance", "Failed to remove player at exit."); } // Set the players loaded var back diff --git a/dScripts/SGCannon.cpp b/dScripts/SGCannon.cpp index ab179226..9f270562 100644 --- a/dScripts/SGCannon.cpp +++ b/dScripts/SGCannon.cpp @@ -13,7 +13,7 @@ #include "MissionComponent.h" void SGCannon::OnStartup(Entity *self) { - Game::logger->Log("SGCannon", "OnStartup\n"); + Game::logger->Log("SGCannon", "OnStartup"); m_Waves = GetWaves(); constants = GetConstants(); @@ -59,7 +59,7 @@ void SGCannon::OnStartup(Entity *self) { } void SGCannon::OnPlayerLoaded(Entity *self, Entity *player) { - Game::logger->Log("SGCannon", "Player loaded\n"); + Game::logger->Log("SGCannon", "Player loaded"); self->SetVar(PlayerIDVariable, player->GetObjectID()); } @@ -70,15 +70,15 @@ void SGCannon::OnFireEventServerSide(Entity *self, Entity *sender, std::string a void SGCannon::OnActivityStateChangeRequest(Entity *self, LWOOBJID senderID, int32_t value1, int32_t value2, const std::u16string &stringValue) { - Game::logger->Log("SGCannon", "Got activity state change request: %s\n", GeneralUtils::UTF16ToWTF8(stringValue).c_str()); + Game::logger->Log("SGCannon", "Got activity state change request: %s", GeneralUtils::UTF16ToWTF8(stringValue).c_str()); if (stringValue == u"clientready") { auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); if (player != nullptr) { - Game::logger->Log("SGCannon", "Player is ready\n"); + Game::logger->Log("SGCannon", "Player is ready"); /*GameMessages::SendSetStunned(player->GetObjectID(), PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true);*/ - Game::logger->Log("SGCannon", "Sending ActivityEnter\n"); + Game::logger->Log("SGCannon", "Sending ActivityEnter"); GameMessages::SendActivityEnter(self->GetObjectID(), player->GetSystemAddress()); @@ -87,14 +87,14 @@ void SGCannon::OnActivityStateChangeRequest(Entity *self, LWOOBJID senderID, int if (shootingGalleryComponent != nullptr) { shootingGalleryComponent->SetCurrentPlayerID(player->GetObjectID()); - Game::logger->Log("SGCannon", "Setting player ID\n"); + Game::logger->Log("SGCannon", "Setting player ID"); EntityManager::Instance()->SerializeEntity(self); } else { - Game::logger->Log("SGCannon", "Shooting gallery component is null\n"); + Game::logger->Log("SGCannon", "Shooting gallery component is null"); } - + auto* characterComponent = player->GetComponent(); if (characterComponent != nullptr) { @@ -112,11 +112,11 @@ void SGCannon::OnActivityStateChangeRequest(Entity *self, LWOOBJID senderID, int self->SetNetworkVar(HideScoreBoardVariable, true); self->SetNetworkVar(ReSetSuperChargeVariable, true); self->SetNetworkVar(ShowLoadingUI, true); - + /* GameMessages::SendTeleport( - player->GetObjectID(), - {-292.6415710449219, 230.20237731933594, -3.9090466499328613}, + player->GetObjectID(), + {-292.6415710449219, 230.20237731933594, -3.9090466499328613}, {0.7067984342575073, -6.527870573336259e-05, 0.707414984703064, 0.00021762956748716533}, player->GetSystemAddress(), true ); @@ -125,7 +125,7 @@ void SGCannon::OnActivityStateChangeRequest(Entity *self, LWOOBJID senderID, int //GameMessages::SendRequestActivityEnter(self->GetObjectID(), player->GetSystemAddress(), false, player->GetObjectID()); } else { - Game::logger->Log("SGCannon", "Player not found\n"); + Game::logger->Log("SGCannon", "Player not found"); } } else if (value1 == 1200) { @@ -193,7 +193,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { SpawnObject(self, enemyToSpawn, true); } - Game::logger->Log("SGCannon", "Current wave spawn: %i/%i\n", wave, m_Waves.size()); + Game::logger->Log("SGCannon", "Current wave spawn: %i/%i", wave, m_Waves.size()); // All waves completed const auto timeLimit = (float_t) self->GetVar(TimeLimitVariable); @@ -208,7 +208,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { GameMessages::SendPlayFXEffect(player->GetObjectID(), -1, u"SG-start", ""); GameMessages::SendStartActivityTime(self->GetObjectID(), timeLimit, player->GetSystemAddress()); - Game::logger->Log("SGCannon", "Sending ActivityPause false\n"); + Game::logger->Log("SGCannon", "Sending ActivityPause false"); GameMessages::SendActivityPause(self->GetObjectID(), false, player->GetSystemAddress()); } @@ -229,7 +229,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { self->SetNetworkVar(WaveNumVariable, self->GetVar(ThisWaveVariable) + 1); self->SetNetworkVar(WaveStrVariable, self->GetVar(TimeLimitVariable)); - Game::logger->Log("SGCannon", "Current wave: %i/%i\n", self->GetVar(ThisWaveVariable), m_Waves.size()); + Game::logger->Log("SGCannon", "Current wave: %i/%i", self->GetVar(ThisWaveVariable), m_Waves.size()); if (self->GetVar(ThisWaveVariable) >= m_Waves.size()) { ActivityTimerStart(self, GameOverTimer, 0.1, 0.1); @@ -237,7 +237,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { ActivityTimerStart(self, SpawnWaveTimer, constants.inBetweenWavePause, constants.inBetweenWavePause); } - Game::logger->Log("SGCannon", "Sending ActivityPause true\n"); + Game::logger->Log("SGCannon", "Sending ActivityPause true"); GameMessages::SendActivityPause(self->GetObjectID(), true); if (self->GetVar(SuperChargeActiveVariable) && !self->GetVar(SuperChargePausedVariable)) { @@ -246,7 +246,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { } else if (name == GameOverTimer) { auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); if (player != nullptr) { - Game::logger->Log("SGCannon", "Sending ActivityPause true\n"); + Game::logger->Log("SGCannon", "Sending ActivityPause true"); GameMessages::SendActivityPause(self->GetObjectID(), true, player->GetSystemAddress()); @@ -288,7 +288,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { new LDFData(u"groupID", u"SGEnemy") }; - Game::logger->Log("SGCannon", "Spawning enemy %i on path %s\n", toSpawn.lot, path->pathName.c_str()); + Game::logger->Log("SGCannon", "Spawning enemy %i on path %s", toSpawn.lot, path->pathName.c_str()); auto* enemy = EntityManager::Instance()->CreateEntity(info, nullptr, self); EntityManager::Instance()->ConstructEntity(enemy); @@ -297,7 +297,7 @@ void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { auto* movementAI = new MovementAIComponent(enemy, {}); enemy->AddComponent(COMPONENT_TYPE_MOVEMENT_AI, movementAI); - + movementAI->SetSpeed(toSpawn.initialSpeed); movementAI->SetCurrentSpeed(toSpawn.initialSpeed); movementAI->SetHaltDistance(0.0f); @@ -349,7 +349,7 @@ void SGCannon::StartGame(Entity *self) { auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); if (player != nullptr) { GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self)); - Game::logger->Log("SGCannon", "Sending ActivityStart\n"); + Game::logger->Log("SGCannon", "Sending ActivityStart"); GameMessages::SendActivityStart(self->GetObjectID(), player->GetSystemAddress()); GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"start", ""); @@ -554,7 +554,7 @@ void SGCannon::StopGame(Entity *self, bool cancel) { } auto* missionComponent = player->GetComponent(); - + if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar(TotalScoreVariable), self->GetObjectID(), "performact_score"); missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar(MaxStreakVariable), self->GetObjectID(), "performact_streak"); @@ -602,7 +602,7 @@ void SGCannon::StopGame(Entity *self, bool cancel) { ResetVars(self); } -void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& timerName) +void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& timerName) { const auto& spawnInfo = target->GetVar(u"SpawnData"); @@ -634,7 +634,7 @@ void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& time auto scScore = self->GetVar(TotalScoreVariable) - lastSuperTotal; - Game::logger->Log("SGCannon", "LastSuperTotal: %i, scScore: %i, constants.chargedPoints: %i\n", + Game::logger->Log("SGCannon", "LastSuperTotal: %i, scScore: %i, constants.chargedPoints: %i", lastSuperTotal, scScore, constants.chargedPoints ); @@ -674,7 +674,7 @@ void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& time missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, spawnInfo.lot, self->GetObjectID()); } -void SGCannon::UpdateStreak(Entity* self) +void SGCannon::UpdateStreak(Entity* self) { const auto streakBonus = GetCurrentBonus(self); @@ -705,7 +705,7 @@ void SGCannon::UpdateStreak(Entity* self) if (maxStreak < curStreak) self->SetVar(MaxStreakVariable, curStreak); } -float_t SGCannon::GetCurrentBonus(Entity* self) +float_t SGCannon::GetCurrentBonus(Entity* self) { auto streak = self->GetVar(u"m_curStreak"); @@ -723,7 +723,7 @@ void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); if (player == nullptr) { - Game::logger->Log("SGCannon", "Player not found in toggle super charge\n"); + Game::logger->Log("SGCannon", "Player not found in toggle super charge"); return; } @@ -731,7 +731,7 @@ void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { auto equippedItems = inventoryComponent->GetEquippedItems(); - Game::logger->Log("SGCannon", "Player has %d equipped items\n", equippedItems.size()); + Game::logger->Log("SGCannon", "Player has %d equipped items", equippedItems.size()); auto skillID = constants.cannonSkill; auto coolDown = constants.cannonRefireRate; @@ -739,12 +739,12 @@ void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { auto* selfInventoryComponent = self->GetComponent(); if (inventoryComponent == nullptr) { - Game::logger->Log("SGCannon", "Inventory component not found\n"); + Game::logger->Log("SGCannon", "Inventory component not found"); return; } if (enable) { - Game::logger->Log("SGCannon", "Player is activating super charge\n"); + Game::logger->Log("SGCannon", "Player is activating super charge"); selfInventoryComponent->UpdateSlot("greeble_r", { ObjectIDManager::GenerateRandomObjectID(), 6505, 1, 0 }); selfInventoryComponent->UpdateSlot("greeble_l", { ObjectIDManager::GenerateRandomObjectID(), 6506, 1, 0 }); @@ -754,15 +754,15 @@ void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { } else { selfInventoryComponent->UpdateSlot("greeble_r", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); selfInventoryComponent->UpdateSlot("greeble_l", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); - + self->SetNetworkVar(u"SuperChargeBar", 0); - Game::logger->Log("SGCannon", "Player disables super charge\n"); - + Game::logger->Log("SGCannon", "Player disables super charge"); + // TODO: Unequip items for (const auto& equipped : equippedItems) { if (equipped.first == "special_r" || equipped.first == "special_l") { - Game::logger->Log("SGCannon", "Trying to unequip a weapon, %i\n", equipped.second.lot); + Game::logger->Log("SGCannon", "Trying to unequip a weapon, %i", equipped.second.lot); auto* item = inventoryComponent->FindItemById(equipped.second.id); @@ -770,7 +770,7 @@ void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { inventoryComponent->UnEquipItem(item); } else { - Game::logger->Log("SGCannon", "Item not found, %i\n", equipped.second.lot); + Game::logger->Log("SGCannon", "Item not found, %i", equipped.second.lot); } } } @@ -787,7 +787,7 @@ void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { } DynamicShootingGalleryParams properties = shootingGalleryComponent->GetDynamicParams(); - + properties.cannonFOV = 58.6f; properties.cannonVelocity = 129.0; properties.cannonRefireRate = 800; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 96149ae4..084b465a 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -127,9 +127,9 @@ int main(int argc, char** argv) { if (!Game::logger) return 0; Game::logger->SetLogToConsole(true); //We want this info to always be logged. - Game::logger->Log("WorldServer", "Starting World server...\n"); - Game::logger->Log("WorldServer", "Version: %i.%i\n", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); - Game::logger->Log("WorldServer", "Compiled on: %s\n", __TIMESTAMP__); + Game::logger->Log("WorldServer", "Starting World server..."); + Game::logger->Log("WorldServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); + Game::logger->Log("WorldServer", "Compiled on: %s", __TIMESTAMP__); #ifndef _DEBUG Game::logger->SetLogToConsole(false); //By default, turn it back off if not in debug. @@ -146,9 +146,9 @@ int main(int argc, char** argv) { try { CDClientDatabase::Connect("./res/CDServer.sqlite"); } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database\n"); - Game::logger->Log("WorldServer", "Error: %s\n", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i\n", e.errorCode()); + Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); + Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); return -1; } @@ -170,7 +170,7 @@ int main(int argc, char** argv) { try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); } catch (sql::SQLException& ex) { - Game::logger->Log("WorldServer", "Got an error while connecting to the database: %s\n", ex.what()); + Game::logger->Log("WorldServer", "Got an error while connecting to the database: %s", ex.what()); return 0; } @@ -277,7 +277,7 @@ int main(int argc, char** argv) { delete md5; - Game::logger->Log("WorldServer", "FDB Checksum calculated as: %s\n", databaseChecksum.c_str()); + Game::logger->Log("WorldServer", "FDB Checksum calculated as: %s", databaseChecksum.c_str()); } } @@ -304,7 +304,7 @@ int main(int argc, char** argv) { //Warning if we ran slow if (deltaTime > currentFramerate) { - Game::logger->Log("WorldServer", "We're running behind, dT: %f > %f (framerate)\n", deltaTime, currentFramerate); + Game::logger->Log("WorldServer", "We're running behind, dT: %f > %f (framerate)", deltaTime, currentFramerate); } //Check if we're still connected to master: @@ -313,7 +313,7 @@ int main(int argc, char** argv) { int framesToWaitForMaster = ready ? 10 : 200; if (framesSinceMasterDisconnect >= framesToWaitForMaster && !worldShutdownSequenceStarted) { - Game::logger->Log("WorldServer", "Game loop running but no connection to master for %d frames, shutting down\n", framesToWaitForMaster); + Game::logger->Log("WorldServer", "Game loop running but no connection to master for %d frames, shutting down", framesToWaitForMaster); worldShutdownSequenceStarted = true; } } @@ -470,7 +470,7 @@ int main(int argc, char** argv) { if (framesSinceMasterStatus >= 200) { - Game::logger->Log("WorldServer", "Finished loading world with zone (%i), ready up!\n", Game::server->GetZoneID()); + Game::logger->Log("WorldServer", "Finished loading world with zone (%i), ready up!", Game::server->GetZoneID()); MasterPackets::SendWorldReady(Game::server, Game::server->GetZoneID(), Game::server->GetInstanceID()); @@ -504,13 +504,13 @@ dLogger * SetupLogger(int zoneID, int instanceID) { void HandlePacketChat(Packet* packet) { if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || packet->data[0] == ID_CONNECTION_LOST) { - Game::logger->Log("WorldServer", "Lost our connection to chat, zone(%i), instance(%i)\n", Game::server->GetZoneID(), Game::server->GetInstanceID()); + Game::logger->Log("WorldServer", "Lost our connection to chat, zone(%i), instance(%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); chatConnected = false; } if (packet->data[0] == ID_CONNECTION_REQUEST_ACCEPTED) { - Game::logger->Log("WorldServer", "Established connection to chat, zone(%i), instance (%i)\n",Game::server -> GetZoneID(), Game::server -> GetInstanceID()); + Game::logger->Log("WorldServer", "Established connection to chat, zone(%i), instance (%i)",Game::server -> GetZoneID(), Game::server -> GetInstanceID()); Game::chatSysAddr = packet->systemAddress; chatConnected = true; @@ -556,7 +556,7 @@ void HandlePacketChat(Packet* packet) { inStream.Read(character); title += character; } - + len = 0; inStream.Read(len); for (int i = 0; len > i; i++) { @@ -617,21 +617,21 @@ void HandlePacketChat(Packet* packet) { { TeamManager::Instance()->DeleteTeam(teamID); - Game::logger->Log("WorldServer", "Deleting team (%llu)\n", teamID); + Game::logger->Log("WorldServer", "Deleting team (%llu)", teamID); break; } inStream.Read(lootOption); inStream.Read(memberCount); - Game::logger->Log("WorldServer", "Updating team (%llu), (%i), (%i)\n", teamID, lootOption, memberCount); + Game::logger->Log("WorldServer", "Updating team (%llu), (%i), (%i)", teamID, lootOption, memberCount); for (char i = 0; i < memberCount; i++) { LWOOBJID member = LWOOBJID_EMPTY; inStream.Read(member); members.push_back(member); - Game::logger->Log("WorldServer", "Updating team member (%llu)\n", member); + Game::logger->Log("WorldServer", "Updating team member (%llu)", member); } TeamManager::Instance()->UpdateTeam(teamID, lootOption, members); @@ -640,7 +640,7 @@ void HandlePacketChat(Packet* packet) { } default: - Game::logger->Log("WorldServer", "Received an unknown chat internal: %i\n", int(packet->data[3])); + Game::logger->Log("WorldServer", "Received an unknown chat internal: %i", int(packet->data[3])); } } } @@ -674,7 +674,7 @@ void HandlePacket(Packet* packet) { entity->GetCharacter()->SaveXMLToDatabase(); - Game::logger->Log("WorldServer", "Deleting player %llu\n", entity->GetObjectID()); + Game::logger->Log("WorldServer", "Deleting player %llu", entity->GetObjectID()); EntityManager::Instance()->DestroyEntity(entity); } @@ -741,12 +741,12 @@ void HandlePacket(Packet* packet) { //Verify it: if (userHash != it->second.hash) { - Game::logger->Log("WorldServer", "SOMEONE IS TRYING TO HACK? SESSION KEY MISMATCH: ours: %s != master: %s\n", userHash.c_str(), it->second.hash.c_str()); + Game::logger->Log("WorldServer", "SOMEONE IS TRYING TO HACK? SESSION KEY MISMATCH: ours: %s != master: %s", userHash.c_str(), it->second.hash.c_str()); Game::server->Disconnect(it->second.sysAddr, SERVER_DISCON_INVALID_SESSION_KEY); return; } else { - Game::logger->Log("WorldServer", "User %s authenticated with correct key.\n", username.c_str()); + Game::logger->Log("WorldServer", "User %s authenticated with correct key.", username.c_str()); UserManager::Instance()->DeleteUser(packet->systemAddress); @@ -791,7 +791,7 @@ void HandlePacket(Packet* packet) { case MSG_MASTER_AFFIRM_TRANSFER_REQUEST: { const uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); - Game::logger->Log("MasterServer", "Got affirmation request of transfer %llu\n", requestID); + Game::logger->Log("MasterServer", "Got affirmation request of transfer %llu", requestID); CBITSTREAM @@ -804,7 +804,7 @@ void HandlePacket(Packet* packet) { case MSG_MASTER_SHUTDOWN: { worldShutdownSequenceStarted = true; - Game::logger->Log("WorldServer", "Got shutdown request from master, zone (%i), instance (%i)\n", Game::server->GetZoneID(), Game::server->GetInstanceID()); + Game::logger->Log("WorldServer", "Got shutdown request from master, zone (%i), instance (%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); break; } @@ -814,10 +814,10 @@ void HandlePacket(Packet* packet) { uint32_t sessionKey = inStream.Read(sessionKey); std::string username; - + uint32_t len; inStream.Read(len); - + for (int i = 0; i < len; i++) { char character; inStream.Read(character); username += character; @@ -826,13 +826,13 @@ void HandlePacket(Packet* packet) { //Find them: User* user = UserManager::Instance()->GetUser(username.c_str()); if (!user) { - Game::logger->Log("WorldServer", "Got new session alert for user %s, but they're not logged in.\n", username.c_str()); + Game::logger->Log("WorldServer", "Got new session alert for user %s, but they're not logged in.", username.c_str()); return; } //Check the key: if (sessionKey != std::atoi(user->GetSessionKey().c_str())) { - Game::logger->Log("WorldServer", "Got new session alert for user %s, but the session key is invalid.\n", username.c_str()); + Game::logger->Log("WorldServer", "Got new session alert for user %s, but the session key is invalid.", username.c_str()); Game::server->Disconnect(user->GetSystemAddress(), SERVER_DISCON_INVALID_SESSION_KEY); return; } @@ -840,7 +840,7 @@ void HandlePacket(Packet* packet) { } default: - Game::logger->Log("WorldServer", "Unknown packet ID from master %i\n", int(packet->data[3])); + Game::logger->Log("WorldServer", "Unknown packet ID from master %i", int(packet->data[3])); } return; @@ -873,7 +873,7 @@ void HandlePacket(Packet* packet) { // Developers may skip this check if (gmLevel < 8 && clientDatabaseChecksum != databaseChecksum) { - Game::logger->Log("WorldServer", "Client's database checksum does not match the server's, aborting connection.\n"); + Game::logger->Log("WorldServer", "Client's database checksum does not match the server's, aborting connection."); Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_KICK); return; } @@ -949,7 +949,7 @@ void HandlePacket(Packet* packet) { playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_PERSISTENT); auto user = UserManager::Instance()->GetUser(packet->systemAddress); - + if (user) { auto lastCharacter = user->GetLoggedInChar(); // This means we swapped characters and we need to remove the previous player from the container. @@ -977,7 +977,7 @@ void HandlePacket(Packet* packet) { } case MSG_WORLD_CLIENT_LEVEL_LOAD_COMPLETE: { - Game::logger->Log("WorldServer", "Received level load complete from user.\n"); + Game::logger->Log("WorldServer", "Received level load complete from user."); User* user = UserManager::Instance()->GetUser(packet->systemAddress); if (user) { Character* c = user->GetLastUsedChar(); @@ -1036,7 +1036,7 @@ void HandlePacket(Packet* packet) { auto result = query.execQuery(); if (result.eof() || result.fieldIsNull(0)) { - Game::logger->Log("WorldServer", "No property templates found for zone %d, not sending BBB\n", zoneId); + Game::logger->Log("WorldServer", "No property templates found for zone %d, not sending BBB", zoneId); goto noBBB; } @@ -1064,7 +1064,7 @@ void HandlePacket(Packet* packet) { stmt->setUInt64(1, propertyId); auto res = stmt->executeQuery(); while (res->next()) { - Game::logger->Log("UGC", "Getting lxfml ugcID: " + std::to_string(res->getUInt(1)) + "\n"); + Game::logger->Log("UGC", "Getting lxfml ugcID: " + std::to_string(res->getUInt(1))); //Get lxfml: auto stmtL = Database::CreatePreppedStmt("SELECT lxfml from ugc where id=?"); @@ -1154,11 +1154,11 @@ void HandlePacket(Packet* packet) { } } else { - Game::logger->Log("WorldServer", "Couldn't find character to log in with for user %s (%i)!\n", user->GetUsername().c_str(), user->GetAccountID()); + Game::logger->Log("WorldServer", "Couldn't find character to log in with for user %s (%i)!", user->GetUsername().c_str(), user->GetAccountID()); Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_CHARACTER_NOT_FOUND); } } else { - Game::logger->Log("WorldServer", "Couldn't get user for level load complete!\n"); + Game::logger->Log("WorldServer", "Couldn't get user for level load complete!"); } break; } @@ -1185,7 +1185,7 @@ void HandlePacket(Packet* packet) { inStream.Read(size); if (size > 20000) { - Game::logger->Log("WorldServer", "Tried to route a packet with a read size > 20000, so likely a false packet.\n"); + Game::logger->Log("WorldServer", "Tried to route a packet with a read size > 20000, so likely a false packet."); return; } @@ -1248,38 +1248,36 @@ void HandlePacket(Packet* packet) { } default: - Game::server->GetLogger()->Log("HandlePacket", "Unknown world packet received: %i\n", int(packet->data[3])); + Game::server->GetLogger()->Log("HandlePacket", "Unknown world packet received: %i", int(packet->data[3])); } } void WorldShutdownProcess(uint32_t zoneId) { - Game::logger->Log("WorldServer", "Saving map %i instance %i\n", zoneId, instanceID); + Game::logger->Log("WorldServer", "Saving map %i instance %i", zoneId, instanceID); for (auto i = 0; i < Game::server->GetReplicaManager()->GetParticipantCount(); ++i) { const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(i); auto* entity = Player::GetPlayer(player); - Game::logger->Log("WorldServer", "Saving data!\n"); + Game::logger->Log("WorldServer", "Saving data!"); if (entity != nullptr && entity->GetCharacter() != nullptr) { auto* skillComponent = entity->GetComponent(); if (skillComponent != nullptr) { skillComponent->Reset(); } - std::string message = "Saving character " + entity->GetCharacter()->GetName() + "...\n"; - Game::logger->Log("WorldServer", message); + Game::logger->Log("WorldServer", "Saving character %s...", entity->GetCharacter()->GetName().c_str()); entity->GetCharacter()->SaveXMLToDatabase(); - message = "Character data for " + entity->GetCharacter()->GetName() + " was saved!\n"; - Game::logger->Log("WorldServer", message); + Game::logger->Log("WorldServer", "Character data for %s was saved!", entity->GetCharacter()->GetName().c_str()); } } if (PropertyManagementComponent::Instance() != nullptr) { - Game::logger->Log("WorldServer", "Saving ALL property data for zone %i clone %i!\n", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); + Game::logger->Log("WorldServer", "Saving ALL property data for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); PropertyManagementComponent::Instance()->Save(); - Game::logger->Log("WorldServer", "ALL property data saved for zone %i clone %i!\n", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); + Game::logger->Log("WorldServer", "ALL property data saved for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); } - Game::logger->Log("WorldServer", "ALL DATA HAS BEEN SAVED FOR ZONE %i INSTANCE %i!\n", zoneId, instanceID); + Game::logger->Log("WorldServer", "ALL DATA HAS BEEN SAVED FOR ZONE %i INSTANCE %i!", zoneId, instanceID); while (Game::server->GetReplicaManager()->GetParticipantCount() > 0) { const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(0); @@ -1296,7 +1294,7 @@ void WorldShutdownSequence() { worldShutdownSequenceStarted = true; - Game::logger->Log("WorldServer", "Zone (%i) instance (%i) shutting down outside of main loop!\n", Game::server->GetZoneID(), instanceID); + Game::logger->Log("WorldServer", "Zone (%i) instance (%i) shutting down outside of main loop!", Game::server->GetZoneID(), instanceID); WorldShutdownProcess(Game::server->GetZoneID()); FinalizeShutdown(); } @@ -1306,7 +1304,7 @@ void FinalizeShutdown() { if (Game::physicsWorld) Game::physicsWorld = nullptr; if (Game::zoneManager) delete Game::zoneManager; - Game::logger->Log("WorldServer", "Shutdown complete, zone (%i), instance (%i)\n", Game::server->GetZoneID(), instanceID); + Game::logger->Log("WorldServer", "Shutdown complete, zone (%i), instance (%i)", Game::server->GetZoneID(), instanceID); Metrics::Clear(); Database::Destroy("WorldServer"); diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index b678ed95..afd2413e 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -18,11 +18,10 @@ Level::Level(Zone* parentZone, const std::string& filepath) { m_ParentZone = parentZone; std::ifstream file(filepath, std::ios_base::in | std::ios_base::binary); if (file) { - //printf("Opened %s\n", filepath.c_str()); ReadChunks(file); } else { - Game::logger->Log("Level", "Failed to load %s\n", filepath.c_str()); + Game::logger->Log("Level", "Failed to load %s", filepath.c_str()); } file.close(); @@ -96,7 +95,7 @@ void Level::ReadChunks(std::ifstream & file) { for (uint32_t i = 0; i < s; ++i) { file.ignore(4); //a uint file.ignore(4); //two floats - file.ignore(4); + file.ignore(4); } } } @@ -110,7 +109,7 @@ void Level::ReadChunks(std::ifstream & file) { if (header.chunkVersion >= 36) { file.ignore(3 * 4); } - + if (header.chunkVersion < 42) { file.ignore(3 * 4); @@ -176,7 +175,7 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { BinaryIO::BinaryRead(file, obj.rotation); BinaryIO::BinaryRead(file, obj.scale); - //This is a little bit of a bodge, but because the alpha client (HF) doesn't store the + //This is a little bit of a bodge, but because the alpha client (HF) doesn't store the //spawn position / rotation like the later versions do, we need to check the LOT for the spawn pos & set it. if (obj.lot == LOT_MARKER_PLAYER_START) { dZoneManager::Instance()->GetZone()->SetSpawnPos(obj.position); @@ -186,18 +185,18 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { std::u16string ldfString = u""; uint32_t length = 0; BinaryIO::BinaryRead(file, length); - + for (uint32_t i = 0; i < length; ++i) { uint16_t data; BinaryIO::BinaryRead(file, data); ldfString.push_back(data); } - + std::string sData = GeneralUtils::UTF16ToWTF8(ldfString); std::stringstream ssData(sData); std::string token; char deliminator = '\n'; - + while (std::getline(ssData, token, deliminator)) { LDFBaseData * ldfData = LDFBaseData::DataFromString(token); obj.settings.push_back(ldfData); @@ -260,11 +259,11 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { if (data->GetKey() == u"spawner_active_on_load") { spawnInfo.activeOnLoad = std::stoi(data->GetValueAsString()); } - + if (data->GetKey() == u"active_on_load") { spawnInfo.activeOnLoad = std::stoi(data->GetValueAsString()); } - + if (data->GetKey() == u"respawn") { if (data->GetValueType() == eLDFType::LDF_TYPE_FLOAT) // Floats are in seconds { @@ -350,6 +349,5 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { } } - //printf("Loaded %u objects!\n", objectsCount); header.sceneObjects = chunk; } diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 68adb943..36245df4 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -24,7 +24,7 @@ Zone::Zone(const LWOMAPID & mapID, const LWOINSTANCEID & instanceID, const LWOCL } Zone::~Zone() { - Game::logger->Log("Zone", "Destroying zone %i\n", m_ZoneID.GetMapID()); + Game::logger->Log("Zone", "Destroying zone %i", m_ZoneID.GetMapID()); for (std::map::iterator it = m_Scenes.begin(); it != m_Scenes.end(); ++it) { if (it->second.level != nullptr) delete it->second.level; } @@ -45,12 +45,12 @@ void Zone::LoadZoneIntoMemory() { std::ifstream file(m_ZoneFilePath, std::ios::binary); if (file) { BinaryIO::BinaryRead(file, m_ZoneFileFormatVersion); - + uint32_t mapRevision = 0; if (m_ZoneFileFormatVersion >= Zone::ZoneFileFormatVersion::Alpha) BinaryIO::BinaryRead(file, mapRevision); - + BinaryIO::BinaryRead(file, m_WorldID); - if ((uint16_t)m_WorldID != m_ZoneID.GetMapID()) Game::logger->Log("Zone", "WorldID: %i doesn't match MapID %i! Is this intended?\n", m_WorldID, m_ZoneID.GetMapID()); + if ((uint16_t)m_WorldID != m_ZoneID.GetMapID()) Game::logger->Log("Zone", "WorldID: %i doesn't match MapID %i! Is this intended?", m_WorldID, m_ZoneID.GetMapID()); AddRevision(LWOSCENEID_INVALID, mapRevision); @@ -58,7 +58,7 @@ void Zone::LoadZoneIntoMemory() { BinaryIO::BinaryRead(file, m_Spawnpoint); BinaryIO::BinaryRead(file, m_SpawnpointRotation); } - + if (m_ZoneFileFormatVersion <= Zone::ZoneFileFormatVersion::LateAlpha) { uint8_t sceneCount; BinaryIO::BinaryRead(file, sceneCount); @@ -102,7 +102,7 @@ void Zone::LoadZoneIntoMemory() { for (uint32_t i = 0; i < pathCount; ++i) { LoadPath(file); } - + for (Path path : m_Paths) { if (path.pathType == PathType::Spawner) { SpawnerInfo info = SpawnerInfo(); @@ -150,16 +150,16 @@ void Zone::LoadZoneIntoMemory() { Spawner* spawner = new Spawner(info); dZoneManager::Instance()->AddSpawner(info.spawnerID, spawner); } - + } - + //m_PathData.resize(m_PathDataLength); //file.read((char*)&m_PathData[0], m_PathDataLength); } } else { - Game::logger->Log("Zone", "Failed to open: %s\n", m_ZoneFilePath.c_str()); + Game::logger->Log("Zone", "Failed to open: %s", m_ZoneFilePath.c_str()); } m_ZonePath = m_ZoneFilePath.substr(0, m_ZoneFilePath.rfind('/') + 1); @@ -226,7 +226,7 @@ void Zone::AddRevision(LWOSCENEID sceneID, uint32_t revision) { const void Zone::PrintAllGameObjects() { for (std::pair scene : m_Scenes) { - Game::logger->Log("Zone", "\nIn sceneID: %i\n\n", scene.first.GetSceneID()); + Game::logger->Log("Zone", "In sceneID: %i", scene.first.GetSceneID()); scene.second.level->PrintAllObjects(); } } @@ -242,7 +242,7 @@ void Zone::LoadScene(std::ifstream & file) { std::string luTriggersPath = scene.filename.substr(0, scene.filename.size() - 4) + ".lutriggers"; std::vector triggers = LoadLUTriggers(luTriggersPath, scene.id); - + for (LUTriggers::Trigger* trigger : triggers) { scene.triggers.insert({ trigger->id, trigger }); } @@ -283,13 +283,13 @@ std::vector Zone::LoadLUTriggers(std::string triggerFile, if (!doc) return lvlTriggers; if (doc->Parse(data.str().c_str(), data.str().size()) == 0) { - //Game::logger->Log("Zone", "Loaded LUTriggers from file %s!\n", triggerFile.c_str()); + //Game::logger->Log("Zone", "Loaded LUTriggers from file %s!", triggerFile.c_str()); } else { - Game::logger->Log("Zone", "Failed to load LUTriggers from file %s\n", triggerFile.c_str()); + Game::logger->Log("Zone", "Failed to load LUTriggers from file %s", triggerFile.c_str()); return lvlTriggers; } - + tinyxml2::XMLElement* triggers = doc->FirstChildElement("triggers"); if (!triggers) return lvlTriggers; @@ -323,7 +323,7 @@ std::vector Zone::LoadLUTriggers(std::string triggerFile, currentTrigger = currentTrigger->NextSiblingElement("trigger"); lvlTriggers.push_back(newTrigger); } - + delete doc; return lvlTriggers; @@ -474,8 +474,8 @@ void Zone::LoadPath(std::ifstream & file) { BinaryIO::BinaryRead(file, waypoint.position.x); BinaryIO::BinaryRead(file, waypoint.position.y); BinaryIO::BinaryRead(file, waypoint.position.z); - - + + if (path.pathType == PathType::Spawner || path.pathType == PathType::MovingPlatform || path.pathType == PathType::Race) { BinaryIO::BinaryRead(file, waypoint.rotation.w); BinaryIO::BinaryRead(file, waypoint.rotation.x); @@ -565,7 +565,7 @@ void Zone::LoadPath(std::ifstream & file) { path.pathWaypoints.push_back(waypoint); } - + m_Paths.push_back(path); } diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index 12215378..89f4b6f8 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -15,7 +15,7 @@ dZoneManager* dZoneManager::m_Address = nullptr; void dZoneManager::Initialize(const LWOZONEID& zoneID) { - Game::logger->Log("dZoneManager", "Preparing zone: %i/%i/%i\n", zoneID.GetMapID(), zoneID.GetInstanceID(), zoneID.GetCloneID()); + Game::logger->Log("dZoneManager", "Preparing zone: %i/%i/%i", zoneID.GetMapID(), zoneID.GetInstanceID(), zoneID.GetCloneID()); int64_t startTime = 0; int64_t endTime = 0; @@ -40,7 +40,7 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { } } - Game::logger->Log("dZoneManager", "Creating zone control object %i\n", zoneControlTemplate); + Game::logger->Log("dZoneManager", "Creating zone control object %i", zoneControlTemplate); // Create ZoneControl object EntityInfo info; @@ -53,7 +53,7 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { endTime = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); - Game::logger->Log("dZoneManager", "Zone prepared in: %llu ms\n", (endTime - startTime)); + Game::logger->Log("dZoneManager", "Zone prepared in: %llu ms", (endTime - startTime)); VanityUtilities::SpawnVanity(); } @@ -89,7 +89,7 @@ void dZoneManager::NotifyZone(const dZoneNotifier & notifier, const LWOOBJID& ob case dZoneNotifier::SpawnedChildObjectDestroyed: break; case dZoneNotifier::ReloadZone: - Game::logger->Log("dZoneManager", "Forcing reload of zone %i\n", m_ZoneID.GetMapID()); + Game::logger->Log("dZoneManager", "Forcing reload of zone %i", m_ZoneID.GetMapID()); LoadZone(m_ZoneID); m_pZone->Initalize(); @@ -102,10 +102,10 @@ void dZoneManager::NotifyZone(const dZoneNotifier & notifier, const LWOOBJID& ob m_pZone->PrintAllGameObjects(); break; case dZoneNotifier::InvalidNotifier: - Game::logger->Log("dZoneManager", "Got an invalid zone notifier.\n"); + Game::logger->Log("dZoneManager", "Got an invalid zone notifier."); break; default: - Game::logger->Log("dZoneManager", "Unknown zone notifier: %i\n", int(notifier)); + Game::logger->Log("dZoneManager", "Unknown zone notifier: %i", int(notifier)); } } @@ -188,7 +188,7 @@ void dZoneManager::RemoveSpawner(const LWOOBJID id) auto* spawner = GetSpawner(id); if (spawner == nullptr) { - Game::logger->Log("dZoneManager", "Failed to find spawner (%llu)\n", id); + Game::logger->Log("dZoneManager", "Failed to find spawner (%llu)", id); return; } @@ -199,7 +199,7 @@ void dZoneManager::RemoveSpawner(const LWOOBJID id) } else { - Game::logger->Log("dZoneManager", "Failed to find spawner entity (%llu)\n", id); + Game::logger->Log("dZoneManager", "Failed to find spawner entity (%llu)", id); } for (auto* node : spawner->m_Info.nodes) @@ -218,7 +218,7 @@ void dZoneManager::RemoveSpawner(const LWOOBJID id) spawner->Deactivate(); - Game::logger->Log("dZoneManager", "Destroying spawner (%llu)\n", id); + Game::logger->Log("dZoneManager", "Destroying spawner (%llu)", id); m_Spawners.erase(id); From 9813c3ed2ca60145c5934c73379b8f41b9bb4e4d Mon Sep 17 00:00:00 2001 From: Daniel Seiler Date: Tue, 26 Jul 2022 06:11:30 +0200 Subject: [PATCH 043/322] Better Unicode support in GeneralUtils (#658) * ASCIIToUTF16: output replacement character instead of failing assert * Add GeneralUtils::_NextUTF8Char * Implement GeneralUtils::UTF8ToUTF16 * use string_view everywhere * use string_view::front instead of begin * Add PushUTF16CodePoint --- dCommon/GeneralUtils.cpp | 119 +++++++++++++++++++++++++++++++++++++-- dCommon/GeneralUtils.h | 15 ++++- tests/CMakeLists.txt | 1 + tests/TestEncoding.cpp | 52 +++++++++++++++++ 4 files changed, 179 insertions(+), 8 deletions(-) create mode 100644 tests/TestEncoding.cpp diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index 01306226..eafa6a3b 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -6,7 +6,7 @@ #include template -inline size_t MinSize(size_t size, const std::basic_string& string) { +inline size_t MinSize(size_t size, const std::basic_string_view& string) { if (size == size_t(-1) || size > string.size()) { return string.size(); } else { @@ -24,7 +24,7 @@ inline bool IsTrailSurrogate(char16_t c) { inline void PushUTF8CodePoint(std::string& ret, char32_t cp) { if (cp <= 0x007F) { - ret.push_back(cp); + ret.push_back(static_cast(cp)); } else if (cp <= 0x07FF) { ret.push_back(0xC0 | (cp >> 6)); ret.push_back(0x80 | (cp & 0x3F)); @@ -42,16 +42,123 @@ inline void PushUTF8CodePoint(std::string& ret, char32_t cp) { } } +constexpr const char16_t REPLACEMENT_CHARACTER = 0xFFFD; + +bool _IsSuffixChar(uint8_t c) { + return (c & 0xC0) == 0x80; +} + +bool GeneralUtils::_NextUTF8Char(std::string_view& slice, uint32_t& out) { + size_t rem = slice.length(); + const uint8_t* bytes = (const uint8_t*) &slice.front(); + if (rem > 0) { + uint8_t first = bytes[0]; + if (first < 0x80) { // 1 byte character + out = static_cast(first & 0x7F); + slice.remove_prefix(1); + return true; + } else if (first < 0xC0) { + // middle byte, not valid at start, fall through + } else if (first < 0xE0) { // two byte character + if (rem > 1) { + uint8_t second = bytes[1]; + if (_IsSuffixChar(second)) { + out = (static_cast(first & 0x1F) << 6) + + static_cast(second & 0x3F); + slice.remove_prefix(2); + return true; + } + } + } else if (first < 0xF0) { // three byte character + if (rem > 2) { + uint8_t second = bytes[1]; + uint8_t third = bytes[2]; + if (_IsSuffixChar(second) && _IsSuffixChar(third)) { + out = (static_cast(first & 0x0F) << 12) + + (static_cast(second & 0x3F) << 6) + + static_cast(third & 0x3F); + slice.remove_prefix(3); + return true; + } + } + } else if (first < 0xF8) { // four byte character + if (rem > 3) { + uint8_t second = bytes[1]; + uint8_t third = bytes[2]; + uint8_t fourth = bytes[3]; + if (_IsSuffixChar(second) && _IsSuffixChar(third) && _IsSuffixChar(fourth)) { + out = (static_cast(first & 0x07) << 18) + + (static_cast(second & 0x3F) << 12) + + (static_cast(third & 0x3F) << 6) + + static_cast(fourth & 0x3F); + slice.remove_prefix(4); + return true; + } + } + } + out = static_cast(REPLACEMENT_CHARACTER); + slice.remove_prefix(1); + return true; + } + return false; +} + +/// See +bool PushUTF16CodePoint(std::u16string& output, uint32_t U, size_t size) { + if (output.length() >= size) return false; + if (U < 0x10000) { + // If U < 0x10000, encode U as a 16-bit unsigned integer and terminate. + output.push_back(static_cast(U)); + return true; + } else if (U > 0x10FFFF) { + output.push_back(REPLACEMENT_CHARACTER); + return true; + } else if (output.length() + 1 < size) { + // Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF, + // U' must be less than or equal to 0xFFFFF. That is, U' can be + // represented in 20 bits. + uint32_t Ut = U - 0x10000; + + // Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and + // 0xDC00, respectively. These integers each have 10 bits free to + // encode the character value, for a total of 20 bits. + uint16_t W1 = 0xD800; + uint16_t W2 = 0xDC00; + + // Assign the 10 high-order bits of the 20-bit U' to the 10 low-order + // bits of W1 and the 10 low-order bits of U' to the 10 low-order + // bits of W2. + W1 += static_cast((Ut & 0x3FC00) >> 10); + W2 += static_cast((Ut & 0x3FF) >> 0); + + // Terminate. + output.push_back(W1); // high surrogate + output.push_back(W2); // low surrogate + return true; + } else return false; +} + +std::u16string GeneralUtils::UTF8ToUTF16(const std::string_view& string, size_t size) { + size_t newSize = MinSize(size, string); + std::u16string output; + output.reserve(newSize); + std::string_view iterator = string; + + uint32_t c; + while (_NextUTF8Char(iterator, c) && PushUTF16CodePoint(output, c, size)) {} + return output; +} + //! Converts an std::string (ASCII) to UCS-2 / UTF-16 -std::u16string GeneralUtils::ASCIIToUTF16(const std::string& string, size_t size) { +std::u16string GeneralUtils::ASCIIToUTF16(const std::string_view& string, size_t size) { size_t newSize = MinSize(size, string); std::u16string ret; ret.reserve(newSize); for (size_t i = 0; i < newSize; i++) { char c = string[i]; - assert(c > 0 && c <= 127); - ret.push_back(static_cast(c)); + // Note: both 7-bit ascii characters and REPLACEMENT_CHARACTER fit in one char16_t + ret.push_back((c > 0 && c <= 127) ? static_cast(c) : REPLACEMENT_CHARACTER); } return ret; @@ -59,7 +166,7 @@ std::u16string GeneralUtils::ASCIIToUTF16(const std::string& string, size_t size //! Converts a (potentially-ill-formed) UTF-16 string to UTF-8 //! See: -std::string GeneralUtils::UTF16ToWTF8(const std::u16string& string, size_t size) { +std::string GeneralUtils::UTF16ToWTF8(const std::u16string_view& string, size_t size) { size_t newSize = MinSize(size, string); std::string ret; ret.reserve(newSize); diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index 4973201e..f796839c 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -26,7 +26,18 @@ namespace GeneralUtils { \param size A size to trim the string to. Default is -1 (No trimming) \return An UTF-16 representation of the string */ - std::u16string ASCIIToUTF16(const std::string& string, size_t size = -1); + std::u16string ASCIIToUTF16(const std::string_view& string, size_t size = -1); + + //! Converts a UTF-8 String to a UTF-16 string + /*! + \param string The string to convert + \param size A size to trim the string to. Default is -1 (No trimming) + \return An UTF-16 representation of the string + */ + std::u16string UTF8ToUTF16(const std::string_view& string, size_t size = -1); + + //! Internal, do not use + bool _NextUTF8Char(std::string_view& slice, uint32_t& out); //! Converts a UTF-16 string to a UTF-8 string /*! @@ -34,7 +45,7 @@ namespace GeneralUtils { \param size A size to trim the string to. Default is -1 (No trimming) \return An UTF-8 representation of the string */ - std::string UTF16ToWTF8(const std::u16string& string, size_t size = -1); + std::string UTF16ToWTF8(const std::u16string_view& string, size_t size = -1); /** * Compares two basic strings but does so ignoring case sensitivity diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 9c6e57d3..fb1ed5ac 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -4,6 +4,7 @@ create_test_sourcelist (Tests AMFDeserializeTests.cpp TestNiPoint3.cpp TestLDFFormat.cpp + TestEncoding.cpp ) # add the executable diff --git a/tests/TestEncoding.cpp b/tests/TestEncoding.cpp new file mode 100644 index 00000000..1e676ec3 --- /dev/null +++ b/tests/TestEncoding.cpp @@ -0,0 +1,52 @@ +#include +#include + +#include "GeneralUtils.h" +#include "CommonCxxTests.h" + +int TestEncoding(int argc, char* *const argv) { + std::string x = "Hello World!"; + std::string_view v(x); + + uint32_t out; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'H'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'e'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'o'); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), true); + + x = u8"Frühling"; + v = x; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'F'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'r'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'ü'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'h'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'l'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'i'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'n'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'g'); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); + + x = "中文字"; + v = x; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'中'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'文'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'字'); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); + + x = "👨‍⚖️"; + v = x; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x1F468); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x200D); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x2696); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0xFE0F); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); + + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Hello World!"), u"Hello World!"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Frühling"), u"Frühling"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("中文字"), u"中文字"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("👨‍⚖️"), u"👨‍⚖️"); + + return 0; +} From 9e08bb20d2c122326194b21a83aaf741347cbc24 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Wed, 27 Jul 2022 02:52:04 +0100 Subject: [PATCH 044/322] Implement proper bounds checks across the codebase (#681) * Implement proper bounds checks across the codebase * Implement strnlen_s for cross platform --- dCommon/dLogger.cpp | 7 +++++++ dNet/PacketUtils.cpp | 17 ++++++++++------- dNet/PacketUtils.h | 2 +- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/dCommon/dLogger.cpp b/dCommon/dLogger.cpp index 532a0cee..0beb5a3c 100644 --- a/dCommon/dLogger.cpp +++ b/dCommon/dLogger.cpp @@ -26,6 +26,13 @@ dLogger::~dLogger() { } void dLogger::vLog(const char* format, va_list args) { + const char* tempPtr = format; // strlen_s implementation for Linux and Windows + for (; *tempPtr != '\0'; ++tempPtr) { + size_t size = tempPtr - format; + if (size > 600) { + return; + } + } #ifdef _WIN32 time_t t = time(NULL); struct tm time; diff --git a/dNet/PacketUtils.cpp b/dNet/PacketUtils.cpp index a5d9f0ea..352f54b9 100644 --- a/dNet/PacketUtils.cpp +++ b/dNet/PacketUtils.cpp @@ -46,22 +46,25 @@ int64_t PacketUtils::ReadPacketS64(uint32_t startLoc, Packet * packet) { return *(int64_t*)t.data(); } -std::string PacketUtils::ReadString(uint32_t startLoc, Packet* packet, bool wide) { - std::string readString = ""; - +std::string PacketUtils::ReadString(uint32_t startLoc, Packet* packet, bool wide, uint32_t maxLen) { + std::string readString = ""; + + if (wide) maxLen *= 2; + if (packet->length > startLoc) { uint32_t i = 0; - while (packet->data[startLoc + i] != '\0' && packet->length > (uint32_t)(startLoc + i)) { + while (packet->data[startLoc + i] != '\0' && packet->length > (uint32_t)(startLoc + i) && maxLen > i) { readString.push_back(packet->data[startLoc + i]); - + if (wide) { i += 2; // Wide-char string - } else { + } + else { i++; // Regular string } } } - + return readString; } diff --git a/dNet/PacketUtils.h b/dNet/PacketUtils.h index 3426c3ab..61517ccf 100644 --- a/dNet/PacketUtils.h +++ b/dNet/PacketUtils.h @@ -11,7 +11,7 @@ namespace PacketUtils { uint32_t ReadPacketU32(uint32_t startLoc, Packet * packet); uint64_t ReadPacketU64(uint32_t startLoc, Packet * packet); int64_t ReadPacketS64(uint32_t startLoc, Packet * packet); - std::string ReadString(uint32_t startLoc, Packet * packet, bool wide); + std::string ReadString(uint32_t startLoc, Packet * packet, bool wide, uint32_t maxLen = 33); void WritePacketString(const std::string& string, uint32_t maxSize, RakNet::BitStream * bitStream); void WriteString(RakNet::BitStream& bitStream, const std::string& s, uint32_t maxSize); From a632ef8ccdd87316b27b941da18d051ed0ea32bf Mon Sep 17 00:00:00 2001 From: avery Date: Tue, 26 Jul 2022 23:52:53 -0700 Subject: [PATCH 045/322] Clean up format logs (#682) --- dDatabase/MigrationRunner.cpp | 4 ++-- dGame/dGameMessages/GameMessages.cpp | 6 +++--- dScripts/CppScripts.cpp | 2 +- dWorldServer/WorldServer.cpp | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index 186368fd..a988acac 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -31,7 +31,7 @@ void MigrationRunner::RunMigrations() { delete stmt; if (doExit) continue; - Game::logger->Log("MigrationRunner", "Running migration: " + migration.name + ""); + Game::logger->Log("MigrationRunner", "Running migration: %s", migration.name.c_str()); finalSQL.append(migration.data); finalSQL.append('\n'); @@ -49,7 +49,7 @@ void MigrationRunner::RunMigrations() { delete simpleStatement; } catch (sql::SQLException e) { - Game::logger->Log("MigrationRunner", std::string("Encountered error running migration: ") + e.what() + ""); + Game::logger->Log("MigrationRunner", "Encountered error running migration: %s", e.what()); } } } diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 365485f2..66d71ca1 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -2408,7 +2408,7 @@ void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* LWOOBJID itemID = LWOOBJID_EMPTY; inStream->Read(itemID); - Game::logger->Log("BBB", "Load item request for: " + std::to_string(itemID) + ""); + Game::logger->Log("BBB", "Load item request for: %lld", itemID); CBITSTREAM; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_LOAD_RESPONSE_ITEMID); @@ -3848,7 +3848,7 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* userData.push_back(character); } - Game::logger->Log("HandleMessageBoxResponse", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " identifier: " + GeneralUtils::UTF16ToWTF8(identifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(userData)); + Game::logger->Log("HandleMessageBoxResponse", "Button: %d; LOT: %u identifier: %s; userData: %s", iButton, entity->GetLOT(), GeneralUtils::UTF16ToWTF8(identifier).c_str(), GeneralUtils::UTF16ToWTF8(userData).c_str()); auto* user = UserManager::Instance()->GetUser(sysAddr); @@ -3912,7 +3912,7 @@ void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* e identifier.push_back(character); } - Game::logger->Log("HandleChoiceBoxRespond", "Button: " + std::to_string(iButton) + "; LOT: " + std::to_string(entity->GetLOT()) + " buttonIdentifier: " + GeneralUtils::UTF16ToWTF8(buttonIdentifier) + "; userData: " + GeneralUtils::UTF16ToWTF8(identifier)); + Game::logger->Log("HandleChoiceBoxRespond", "Button: %d; LOT: %u buttonIdentifier: %s; userData: %s", iButton, entity->GetLOT(), GeneralUtils::UTF16ToWTF8(buttonIdentifier).c_str(), GeneralUtils::UTF16ToWTF8(identifier).c_str()); auto* user = UserManager::Instance()->GetUser(sysAddr); diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 8feb8ae7..8569bf9e 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -818,7 +818,7 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = invalidToReturn; else if (script == invalidToReturn) { if (scriptName.length() > 0) - Game::logger->LogDebug("CppScripts", "Attempted to load CppScript for '" + scriptName + "', but returned InvalidScript."); + Game::logger->LogDebug("CppScripts", "Attempted to load CppScript for '%s', but returned InvalidScript.", scriptName.c_str()); // information not really needed for sys admins but is for developers script = invalidToReturn; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 084b465a..6d85b2cd 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -1064,7 +1064,7 @@ void HandlePacket(Packet* packet) { stmt->setUInt64(1, propertyId); auto res = stmt->executeQuery(); while (res->next()) { - Game::logger->Log("UGC", "Getting lxfml ugcID: " + std::to_string(res->getUInt(1))); + Game::logger->Log("UGC", "Getting lxfml ugcID: %u", res->getUInt(1)); //Get lxfml: auto stmtL = Database::CreatePreppedStmt("SELECT lxfml from ugc where id=?"); @@ -1321,4 +1321,4 @@ void SendShutdownMessageToMaster() { CBITSTREAM; PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SHUTDOWN_RESPONSE); Game::server->SendToMaster(&bitStream); -} \ No newline at end of file +} From ffd447708193b38fa35f794e5e54800f7d7413ce Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Wed, 27 Jul 2022 10:08:04 +0100 Subject: [PATCH 046/322] Increment DLU patch version --- CMakeVariables.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeVariables.txt b/CMakeVariables.txt index fb59f455..7a8d6b71 100644 --- a/CMakeVariables.txt +++ b/CMakeVariables.txt @@ -1,6 +1,6 @@ PROJECT_VERSION_MAJOR=1 PROJECT_VERSION_MINOR=0 -PROJECT_VERSION_PATCH=3 +PROJECT_VERSION_PATCH=4 # LICENSE LICENSE=AGPL-3.0 # The network version. @@ -17,4 +17,4 @@ __dynamic=1 # __compile_backtrace__=1 # Set __compile_backtrace__ to 1 to compile the backtrace library instead of using system libraries. __maria_db_connector_compile_jobs__=1 -# Set to the number of jobs (make -j equivalent) to compile the mariadbconn files with. \ No newline at end of file +# Set to the number of jobs (make -j equivalent) to compile the mariadbconn files with. From 4f7aa11067861ef598fcb30797ca140dee6b7036 Mon Sep 17 00:00:00 2001 From: aronwk-aaron Date: Wed, 27 Jul 2022 22:33:36 -0500 Subject: [PATCH 047/322] add editorconfig --- .editorconfig | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..ebdfa7ac --- /dev/null +++ b/.editorconfig @@ -0,0 +1,76 @@ +# top-most EditorConfig file +root=true + +# Unix-style newlines with a newline ending every file +[*] +indent_style=tab +tab_width=4 +charset=utf-8 +trim_trailing_whitespace=true +end_of_line=lf +insert_final_newline=true + +[*.{c++,cc,cpp,cxx,h,h++,hh,hpp,hxx,inl,ipp,tlh,tli}] + +vc_generate_documentation_comments=doxygen_slash_star + +cpp_indent_braces=false +cpp_alignment_tab_fill_style=use_spaces +cpp_indent_multi_line_relative_to=innermost_parenthesis +cpp_indent_within_parentheses=indent +cpp_indent_preserve_within_parentheses=false +cpp_indent_case_labels=false +cpp_indent_case_contents=true +cpp_indent_case_contents_when_block=false +cpp_indent_lambda_braces_when_parameter=true +cpp_indent_goto_labels=one_left +cpp_indent_preprocessor=leftmost_column +cpp_indent_access_specifiers=false +cpp_indent_namespace_contents=true +cpp_indent_preserve_comments=false +cpp_new_line_before_open_brace_namespace=same_line +cpp_new_line_before_open_brace_type=same_line +cpp_new_line_before_open_brace_function=same_line +cpp_new_line_before_open_brace_block=same_line +cpp_new_line_before_open_brace_lambda=same_line +cpp_new_line_scope_braces_on_separate_lines=false +cpp_new_line_close_brace_same_line_empty_type=false +cpp_new_line_close_brace_same_line_empty_function=false +cpp_new_line_before_catch=false +cpp_new_line_before_else=false +cpp_new_line_before_while_in_do_while=false +cpp_space_before_function_open_parenthesis=remove +cpp_space_within_parameter_list_parentheses=false +cpp_space_between_empty_parameter_list_parentheses=false +cpp_space_after_keywords_in_control_flow_statements=true +cpp_space_within_control_flow_statement_parentheses=false +cpp_space_before_lambda_open_parenthesis=false +cpp_space_within_cast_parentheses=false +cpp_space_after_cast_close_parenthesis=false +cpp_space_within_expression_parentheses=false +cpp_space_before_block_open_brace=true +cpp_space_between_empty_braces=false +cpp_space_before_initializer_list_open_brace=false +cpp_space_within_initializer_list_braces=true +cpp_space_preserve_in_initializer_list=true +cpp_space_before_open_square_bracket=false +cpp_space_within_square_brackets=false +cpp_space_before_empty_square_brackets=false +cpp_space_between_empty_square_brackets=false +cpp_space_group_square_brackets=true +cpp_space_within_lambda_brackets=false +cpp_space_between_empty_lambda_brackets=false +cpp_space_before_comma=false +cpp_space_after_comma=true +cpp_space_remove_around_member_operators=true +cpp_space_before_inheritance_colon=true +cpp_space_before_constructor_colon=true +cpp_space_remove_before_semicolon=true +cpp_space_after_semicolon=false +cpp_space_remove_around_unary_operator=true +cpp_space_around_binary_operator=insert +cpp_space_around_assignment_operator=insert +cpp_space_pointer_reference_alignment=left +cpp_space_around_ternary_operator=insert +cpp_wrap_preserve_blocks=one_liners +cpp_indent_comment=fasle From adb6a2c60956bbe8e2f4c225ee943d2315375dba Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 27 Jul 2022 20:54:42 -0700 Subject: [PATCH 048/322] Fix racing lap times (#683) --- dGame/dComponents/RacingControlComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index e157ca5f..770679e5 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -818,7 +818,7 @@ void RacingControlComponent::Update(float deltaTime) { // Reached the start point, lapped if (respawnIndex == 0) { - time_t lapTime = std::time(nullptr) - (player.lap == 1 ? m_StartTime : player.lapTime); + time_t lapTime = std::time(nullptr) - (player.lap == 0 ? m_StartTime : player.lapTime); // Cheating check if (lapTime < 40) { From 19e77a38d837ce781ba0ca6ea8e78b67a6e3b5a5 Mon Sep 17 00:00:00 2001 From: aronwk-aaron Date: Thu, 28 Jul 2022 08:39:57 -0500 Subject: [PATCH 049/322] format codebase --- dAuthServer/AuthServer.cpp | 16 +- dChatFilter/dChatFilter.cpp | 8 +- dChatServer/ChatPacketHandler.cpp | 186 +- dChatServer/ChatServer.cpp | 14 +- dChatServer/PlayerContainer.cpp | 137 +- dChatServer/PlayerContainer.h | 2 +- dCommon/AMFDeserialize.cpp | 106 +- dCommon/AMFDeserialize.h | 112 +- dCommon/AMFFormat.cpp | 122 +- dCommon/AMFFormat.h | 556 +++--- dCommon/AMFFormat_BitStream.cpp | 166 +- dCommon/AMFFormat_BitStream.h | 22 +- dCommon/BinaryIO.cpp | 4 +- dCommon/BinaryIO.h | 6 +- dCommon/Diagnostics.cpp | 254 +-- dCommon/Diagnostics.h | 26 +- dCommon/Game.h | 2 +- dCommon/GeneralUtils.cpp | 450 +++-- dCommon/GeneralUtils.h | 321 ++-- dCommon/LDFFormat.cpp | 212 +-- dCommon/LDFFormat.h | 342 ++-- dCommon/MD5.cpp | 438 +++-- dCommon/MD5.h | 106 +- dCommon/Metrics.cpp | 345 ++-- dCommon/Metrics.hpp | 66 +- dCommon/NiPoint3.cpp | 209 +-- dCommon/NiPoint3.h | 264 +-- dCommon/NiQuaternion.cpp | 179 +- dCommon/NiQuaternion.h | 264 +-- dCommon/PermissionMap.h | 52 +- dCommon/SHA512.cpp | 271 ++- dCommon/SHA512.h | 34 +- dCommon/Type.cpp | 16 +- dCommon/Type.h | 2 +- dCommon/ZCompression.cpp | 124 +- dCommon/ZCompression.h | 3 +- dCommon/dCommonVars.h | 382 ++-- dCommon/dConfig.cpp | 8 +- dCommon/dConfig.h | 2 +- dCommon/dLogger.cpp | 34 +- dCommon/dLogger.h | 10 +- dCommon/dPlatforms.h | 48 +- dCommon/eAninmationFlags.h | 2 +- dCommon/eItemType.h | 2 +- dDatabase/CDClientDatabase.cpp | 8 +- dDatabase/CDClientDatabase.h | 48 +- dDatabase/CDClientManager.cpp | 2 +- dDatabase/CDClientManager.h | 76 +- dDatabase/Database.cpp | 9 +- dDatabase/Database.h | 4 +- dDatabase/MigrationRunner.cpp | 95 +- dDatabase/MigrationRunner.h | 2 +- dDatabase/Tables/CDActivitiesTable.cpp | 2 +- dDatabase/Tables/CDActivityRewardsTable.cpp | 74 +- dDatabase/Tables/CDActivityRewardsTable.h | 70 +- dDatabase/Tables/CDAnimationsTable.cpp | 86 +- dDatabase/Tables/CDAnimationsTable.h | 82 +- dDatabase/Tables/CDBehaviorParameterTable.cpp | 5 +- dDatabase/Tables/CDBehaviorParameterTable.h | 34 +- dDatabase/Tables/CDBehaviorTemplateTable.cpp | 104 +- dDatabase/Tables/CDBehaviorTemplateTable.h | 66 +- dDatabase/Tables/CDBrickIDTableTable.cpp | 6 +- .../Tables/CDComponentsRegistryTable.cpp | 91 +- dDatabase/Tables/CDComponentsRegistryTable.h | 42 +- dDatabase/Tables/CDCurrencyTableTable.cpp | 72 +- dDatabase/Tables/CDCurrencyTableTable.h | 66 +- .../Tables/CDDestructibleComponentTable.cpp | 90 +- .../Tables/CDDestructibleComponentTable.h | 84 +- dDatabase/Tables/CDEmoteTable.cpp | 52 +- dDatabase/Tables/CDEmoteTable.h | 44 +- dDatabase/Tables/CDFeatureGatingTable.cpp | 91 +- dDatabase/Tables/CDFeatureGatingTable.h | 70 +- .../Tables/CDInventoryComponentTable.cpp | 70 +- dDatabase/Tables/CDInventoryComponentTable.h | 64 +- dDatabase/Tables/CDItemComponentTable.cpp | 252 +-- dDatabase/Tables/CDItemComponentTable.h | 124 +- dDatabase/Tables/CDItemSetSkillsTable.cpp | 73 +- dDatabase/Tables/CDItemSetSkillsTable.h | 62 +- dDatabase/Tables/CDItemSetsTable.cpp | 92 +- dDatabase/Tables/CDItemSetsTable.h | 86 +- .../Tables/CDLevelProgressionLookupTable.cpp | 68 +- .../Tables/CDLevelProgressionLookupTable.h | 62 +- dDatabase/Tables/CDLootMatrixTable.cpp | 80 +- dDatabase/Tables/CDLootMatrixTable.h | 74 +- dDatabase/Tables/CDLootTableTable.cpp | 74 +- dDatabase/Tables/CDLootTableTable.h | 66 +- dDatabase/Tables/CDMissionEmailTable.cpp | 66 +- dDatabase/Tables/CDMissionEmailTable.h | 56 +- .../Tables/CDMissionNPCComponentTable.cpp | 72 +- dDatabase/Tables/CDMissionNPCComponentTable.h | 66 +- dDatabase/Tables/CDMissionTasksTable.cpp | 109 +- dDatabase/Tables/CDMissionTasksTable.h | 84 +- dDatabase/Tables/CDMissionsTable.cpp | 206 +- dDatabase/Tables/CDMissionsTable.h | 162 +- .../Tables/CDMovementAIComponentTable.cpp | 6 +- dDatabase/Tables/CDObjectSkillsTable.cpp | 70 +- dDatabase/Tables/CDObjectSkillsTable.h | 64 +- dDatabase/Tables/CDObjectsTable.cpp | 118 +- dDatabase/Tables/CDObjectsTable.h | 60 +- dDatabase/Tables/CDPackageComponentTable.cpp | 8 +- dDatabase/Tables/CDPhysicsComponentTable.cpp | 30 +- dDatabase/Tables/CDPhysicsComponentTable.h | 10 +- .../CDPropertyEntranceComponentTable.cpp | 56 +- .../Tables/CDPropertyEntranceComponentTable.h | 52 +- dDatabase/Tables/CDPropertyTemplateTable.cpp | 54 +- dDatabase/Tables/CDPropertyTemplateTable.h | 22 +- .../CDProximityMonitorComponentTable.cpp | 6 +- dDatabase/Tables/CDRailActivatorComponent.cpp | 90 +- dDatabase/Tables/CDRailActivatorComponent.h | 46 +- dDatabase/Tables/CDRarityTableTable.cpp | 58 +- dDatabase/Tables/CDRarityTableTable.h | 76 +- dDatabase/Tables/CDRebuildComponentTable.cpp | 82 +- dDatabase/Tables/CDRebuildComponentTable.h | 76 +- dDatabase/Tables/CDRewardsTable.cpp | 32 +- dDatabase/Tables/CDRewardsTable.h | 10 +- dDatabase/Tables/CDScriptComponentTable.cpp | 48 +- dDatabase/Tables/CDScriptComponentTable.h | 48 +- dDatabase/Tables/CDSkillBehaviorTable.cpp | 98 +- dDatabase/Tables/CDSkillBehaviorTable.h | 76 +- dDatabase/Tables/CDTable.h | 16 +- dDatabase/Tables/CDVendorComponentTable.cpp | 6 +- dDatabase/Tables/CDZoneTableTable.cpp | 105 +- dDatabase/Tables/CDZoneTableTable.h | 92 +- dGame/Character.cpp | 238 ++- dGame/Character.h | 772 ++++---- dGame/Entity.cpp | 676 +++---- dGame/Entity.h | 257 ++- dGame/EntityManager.cpp | 215 +-- dGame/EntityManager.h | 40 +- dGame/LeaderboardManager.cpp | 573 +++--- dGame/LeaderboardManager.h | 108 +- dGame/Player.cpp | 173 +- dGame/Player.h | 38 +- dGame/TeamManager.cpp | 88 +- dGame/TeamManager.h | 14 +- dGame/TradingManager.cpp | 361 ++-- dGame/TradingManager.h | 72 +- dGame/User.cpp | 81 +- dGame/User.h | 20 +- dGame/UserManager.cpp | 447 +++-- dGame/UserManager.h | 12 +- dGame/dBehaviors/AirMovementBehavior.cpp | 17 +- dGame/dBehaviors/AirMovementBehavior.h | 3 +- dGame/dBehaviors/AndBehavior.cpp | 21 +- dGame/dBehaviors/AndBehavior.h | 7 +- dGame/dBehaviors/ApplyBuffBehavior.cpp | 56 +- dGame/dBehaviors/ApplyBuffBehavior.h | 27 +- dGame/dBehaviors/AreaOfEffectBehavior.cpp | 61 +- dGame/dBehaviors/AreaOfEffectBehavior.h | 9 +- dGame/dBehaviors/AttackDelayBehavior.cpp | 26 +- dGame/dBehaviors/AttackDelayBehavior.h | 7 +- dGame/dBehaviors/BasicAttackBehavior.cpp | 6 +- dGame/dBehaviors/BasicAttackBehavior.h | 7 +- dGame/dBehaviors/Behavior.cpp | 115 +- dGame/dBehaviors/Behavior.h | 18 +- dGame/dBehaviors/BehaviorBranchContext.cpp | 6 +- dGame/dBehaviors/BehaviorBranchContext.h | 6 +- dGame/dBehaviors/BehaviorContext.cpp | 166 +- dGame/dBehaviors/BehaviorContext.h | 18 +- dGame/dBehaviors/BehaviorTemplates.h | 2 +- dGame/dBehaviors/BlockBehavior.cpp | 37 +- dGame/dBehaviors/BlockBehavior.h | 9 +- dGame/dBehaviors/BuffBehavior.cpp | 37 +- dGame/dBehaviors/BuffBehavior.h | 7 +- dGame/dBehaviors/CarBoostBehavior.cpp | 53 +- dGame/dBehaviors/CarBoostBehavior.h | 5 +- dGame/dBehaviors/ChainBehavior.cpp | 18 +- dGame/dBehaviors/ChainBehavior.h | 5 +- .../dBehaviors/ChangeOrientationBehavior.cpp | 58 +- dGame/dBehaviors/ChangeOrientationBehavior.h | 9 +- dGame/dBehaviors/ChargeUpBehavior.cpp | 12 +- dGame/dBehaviors/ChargeUpBehavior.h | 7 +- dGame/dBehaviors/ClearTargetBehavior.cpp | 11 +- dGame/dBehaviors/ClearTargetBehavior.h | 5 +- dGame/dBehaviors/DamageAbsorptionBehavior.cpp | 24 +- dGame/dBehaviors/DamageAbsorptionBehavior.h | 5 +- dGame/dBehaviors/DamageReductionBehavior.cpp | 24 +- dGame/dBehaviors/DamageReductionBehavior.h | 5 +- dGame/dBehaviors/DurationBehavior.cpp | 9 +- dGame/dBehaviors/DurationBehavior.h | 7 +- dGame/dBehaviors/EmptyBehavior.h | 3 +- dGame/dBehaviors/EndBehavior.cpp | 9 +- dGame/dBehaviors/EndBehavior.h | 9 +- dGame/dBehaviors/ForceMovementBehavior.cpp | 102 +- dGame/dBehaviors/ForceMovementBehavior.h | 21 +- dGame/dBehaviors/HealBehavior.cpp | 15 +- dGame/dBehaviors/HealBehavior.h | 5 +- dGame/dBehaviors/ImaginationBehavior.cpp | 15 +- dGame/dBehaviors/ImaginationBehavior.h | 3 +- dGame/dBehaviors/ImmunityBehavior.cpp | 27 +- dGame/dBehaviors/ImmunityBehavior.h | 5 +- dGame/dBehaviors/InterruptBehavior.cpp | 25 +- dGame/dBehaviors/InterruptBehavior.h | 11 +- dGame/dBehaviors/JetPackBehavior.cpp | 20 +- dGame/dBehaviors/JetPackBehavior.h | 2 +- dGame/dBehaviors/KnockbackBehavior.cpp | 15 +- dGame/dBehaviors/KnockbackBehavior.h | 5 +- dGame/dBehaviors/LootBuffBehavior.cpp | 36 +- dGame/dBehaviors/LootBuffBehavior.h | 6 +- dGame/dBehaviors/MovementSwitchBehavior.cpp | 12 +- dGame/dBehaviors/MovementSwitchBehavior.h | 9 +- dGame/dBehaviors/NpcCombatSkillBehavior.cpp | 19 +- dGame/dBehaviors/NpcCombatSkillBehavior.h | 5 +- dGame/dBehaviors/OverTimeBehavior.cpp | 48 +- dGame/dBehaviors/OverTimeBehavior.h | 11 +- dGame/dBehaviors/PlayEffectBehavior.cpp | 9 +- dGame/dBehaviors/PlayEffectBehavior.h | 5 +- dGame/dBehaviors/ProjectileAttackBehavior.cpp | 43 +- dGame/dBehaviors/ProjectileAttackBehavior.h | 3 +- dGame/dBehaviors/PullToPointBehavior.cpp | 19 +- dGame/dBehaviors/PullToPointBehavior.h | 3 +- dGame/dBehaviors/RepairBehavior.cpp | 15 +- dGame/dBehaviors/RepairBehavior.h | 3 +- dGame/dBehaviors/SkillCastFailedBehavior.cpp | 9 +- dGame/dBehaviors/SkillCastFailedBehavior.h | 5 +- dGame/dBehaviors/SkillEventBehavior.cpp | 32 +- dGame/dBehaviors/SkillEventBehavior.h | 8 +- dGame/dBehaviors/SpawnBehavior.cpp | 48 +- dGame/dBehaviors/SpawnBehavior.h | 11 +- dGame/dBehaviors/SpawnQuickbuildBehavior.cpp | 7 +- dGame/dBehaviors/SpawnQuickbuildBehavior.h | 3 +- dGame/dBehaviors/SpeedBehavior.cpp | 117 +- dGame/dBehaviors/SpeedBehavior.h | 13 +- dGame/dBehaviors/StartBehavior.cpp | 11 +- dGame/dBehaviors/StartBehavior.h | 5 +- dGame/dBehaviors/StunBehavior.cpp | 36 +- dGame/dBehaviors/StunBehavior.h | 5 +- dGame/dBehaviors/SwitchBehavior.cpp | 57 +- dGame/dBehaviors/SwitchBehavior.h | 5 +- dGame/dBehaviors/SwitchMultipleBehavior.cpp | 18 +- dGame/dBehaviors/SwitchMultipleBehavior.h | 5 +- dGame/dBehaviors/TacArcBehavior.cpp | 138 +- dGame/dBehaviors/TacArcBehavior.h | 7 +- dGame/dBehaviors/TargetCasterBehavior.cpp | 12 +- dGame/dBehaviors/TargetCasterBehavior.h | 7 +- dGame/dBehaviors/TauntBehavior.cpp | 21 +- dGame/dBehaviors/TauntBehavior.h | 5 +- dGame/dBehaviors/VentureVisionBehavior.cpp | 6 +- dGame/dBehaviors/VentureVisionBehavior.h | 5 +- dGame/dBehaviors/VerifyBehavior.cpp | 32 +- dGame/dBehaviors/VerifyBehavior.h | 5 +- dGame/dComponents/BaseCombatAIComponent.cpp | 178 +- dGame/dComponents/BaseCombatAIComponent.h | 402 ++-- dGame/dComponents/BouncerComponent.cpp | 44 +- dGame/dComponents/BouncerComponent.h | 60 +- dGame/dComponents/BuffComponent.cpp | 172 +- dGame/dComponents/BuffComponent.h | 172 +- dGame/dComponents/BuildBorderComponent.cpp | 12 +- dGame/dComponents/BuildBorderComponent.h | 16 +- dGame/dComponents/CharacterComponent.cpp | 688 ++++--- dGame/dComponents/CharacterComponent.h | 660 +++---- dGame/dComponents/Component.cpp | 52 +- dGame/dComponents/Component.h | 62 +- .../ControllablePhysicsComponent.h | 558 +++--- dGame/dComponents/DestroyableComponent.cpp | 453 ++--- dGame/dComponents/DestroyableComponent.h | 864 ++++----- dGame/dComponents/InventoryComponent.cpp | 715 +++---- dGame/dComponents/InventoryComponent.h | 546 +++--- dGame/dComponents/LUPExhibitComponent.cpp | 51 +- dGame/dComponents/LUPExhibitComponent.h | 50 +- .../dComponents/LevelProgressionComponent.cpp | 18 +- dGame/dComponents/MissionComponent.cpp | 728 ++++---- dGame/dComponents/MissionComponent.h | 296 +-- dGame/dComponents/MissionOfferComponent.cpp | 291 ++- dGame/dComponents/MissionOfferComponent.h | 96 +- dGame/dComponents/ModelComponent.cpp | 19 +- dGame/dComponents/ModuleAssemblyComponent.cpp | 96 +- dGame/dComponents/ModuleAssemblyComponent.h | 92 +- dGame/dComponents/MovementAIComponent.cpp | 258 +-- dGame/dComponents/MovementAIComponent.h | 372 ++-- dGame/dComponents/MovingPlatformComponent.cpp | 459 +++-- dGame/dComponents/MovingPlatformComponent.h | 310 +-- dGame/dComponents/PetComponent.cpp | 1532 +++++++-------- dGame/dComponents/PetComponent.h | 566 +++--- dGame/dComponents/PhantomPhysicsComponent.cpp | 128 +- dGame/dComponents/PhantomPhysicsComponent.h | 296 +-- .../PlayerForcedMovementComponent.cpp | 4 +- .../PlayerForcedMovementComponent.h | 20 +- dGame/dComponents/PossessableComponent.cpp | 6 +- dGame/dComponents/PossessableComponent.h | 162 +- dGame/dComponents/PossessorComponent.h | 100 +- dGame/dComponents/PropertyComponent.cpp | 2 +- .../dComponents/PropertyEntranceComponent.cpp | 443 +++-- dGame/dComponents/PropertyEntranceComponent.h | 126 +- .../PropertyManagementComponent.cpp | 278 ++- .../dComponents/PropertyManagementComponent.h | 294 +-- dGame/dComponents/PropertyVendorComponent.cpp | 15 +- dGame/dComponents/PropertyVendorComponent.h | 34 +- .../dComponents/ProximityMonitorComponent.cpp | 2 +- dGame/dComponents/ProximityMonitorComponent.h | 74 +- dGame/dComponents/RacingControlComponent.cpp | 1344 ++++++------- dGame/dComponents/RacingControlComponent.h | 360 ++-- dGame/dComponents/RailActivatorComponent.cpp | 237 ++- dGame/dComponents/RailActivatorComponent.h | 208 +-- dGame/dComponents/RebuildComponent.cpp | 93 +- dGame/dComponents/RebuildComponent.h | 454 ++--- dGame/dComponents/RenderComponent.cpp | 291 ++- dGame/dComponents/RenderComponent.h | 150 +- .../RigidbodyPhantomPhysicsComponent.cpp | 31 +- .../RigidbodyPhantomPhysicsComponent.h | 84 +- dGame/dComponents/RocketLaunchLupComponent.h | 2 +- .../RocketLaunchpadControlComponent.cpp | 27 +- .../RocketLaunchpadControlComponent.h | 138 +- .../dComponents/ScriptedActivityComponent.cpp | 333 ++-- dGame/dComponents/ScriptedActivityComponent.h | 424 ++--- .../dComponents/ShootingGalleryComponent.cpp | 90 +- dGame/dComponents/ShootingGalleryComponent.h | 180 +- dGame/dComponents/SimplePhysicsComponent.cpp | 95 +- dGame/dComponents/SimplePhysicsComponent.h | 170 +- dGame/dComponents/SkillComponent.cpp | 160 +- dGame/dComponents/SkillComponent.h | 270 +-- dGame/dComponents/SoundTriggerComponent.cpp | 132 +- dGame/dComponents/SoundTriggerComponent.h | 60 +- dGame/dComponents/SwitchComponent.cpp | 70 +- dGame/dComponents/SwitchComponent.h | 4 +- dGame/dComponents/VehiclePhysicsComponent.cpp | 129 +- dGame/dComponents/VehiclePhysicsComponent.h | 160 +- dGame/dComponents/VendorComponent.cpp | 42 +- dGame/dComponents/VendorComponent.h | 28 +- dGame/dEntity/EntityCallbackTimer.cpp | 2 +- dGame/dEntity/EntityCallbackTimer.h | 2 +- dGame/dEntity/EntityInfo.h | 26 +- dGame/dEntity/EntityTimer.cpp | 4 +- dGame/dGameMessages/GameMessageHandler.cpp | 1022 +++++----- dGame/dGameMessages/GameMessageHandler.h | 2 +- dGame/dGameMessages/GameMessages.cpp | 1255 +++++-------- dGame/dGameMessages/GameMessages.h | 1010 +++++----- dGame/dGameMessages/PropertyDataMessage.cpp | 26 +- dGame/dGameMessages/PropertyDataMessage.h | 7 +- .../PropertySelectQueryProperty.cpp | 10 +- .../PropertySelectQueryProperty.h | 28 +- dGame/dInventory/DatabasePet.h | 24 +- dGame/dInventory/EquippedItem.h | 24 +- dGame/dInventory/Inventory.cpp | 149 +- dGame/dInventory/Inventory.h | 220 +-- dGame/dInventory/Item.cpp | 222 +-- dGame/dInventory/Item.h | 325 ++-- dGame/dInventory/ItemSet.cpp | 95 +- dGame/dInventory/ItemSet.h | 126 +- dGame/dInventory/ItemSetPassiveAbility.cpp | 564 +++--- dGame/dInventory/ItemSetPassiveAbility.h | 84 +- dGame/dInventory/ItemSetPassiveAbilityID.h | 100 +- dGame/dMission/Mission.cpp | 712 +++---- dGame/dMission/Mission.h | 326 ++-- dGame/dMission/MissionPrerequisites.cpp | 55 +- dGame/dMission/MissionPrerequisites.h | 44 +- dGame/dMission/MissionState.h | 72 +- dGame/dMission/MissionTask.cpp | 144 +- dGame/dMission/MissionTask.h | 228 +-- dGame/dMission/MissionTaskType.h | 42 +- dGame/dMission/RacingTaskParam.h | 30 +- dGame/dUtilities/BrickDatabase.cpp | 67 +- dGame/dUtilities/BrickDatabase.h | 30 +- dGame/dUtilities/GUID.cpp | 20 +- dGame/dUtilities/GUID.h | 20 +- dGame/dUtilities/GameConfig.cpp | 12 +- dGame/dUtilities/GameConfig.h | 2 +- dGame/dUtilities/Loot.cpp | 514 ++--- dGame/dUtilities/Loot.h | 58 +- dGame/dUtilities/Mail.cpp | 30 +- dGame/dUtilities/Mail.h | 4 +- dGame/dUtilities/Preconditions.cpp | 110 +- dGame/dUtilities/Preconditions.h | 84 +- dGame/dUtilities/SlashCommandHandler.cpp | 662 +++---- dGame/dUtilities/SlashCommandHandler.h | 6 +- dGame/dUtilities/VanityUtilities.cpp | 759 ++++---- dGame/dUtilities/VanityUtilities.h | 68 +- dGame/dUtilities/dLocale.cpp | 86 +- dGame/dUtilities/dLocale.h | 18 +- dMasterServer/InstanceManager.cpp | 176 +- dMasterServer/InstanceManager.h | 12 +- dMasterServer/MasterServer.cpp | 78 +- dMasterServer/ObjectIDManager.cpp | 88 +- dMasterServer/ObjectIDManager.h | 56 +- dNet/AuthPackets.cpp | 117 +- dNet/AuthPackets.h | 4 +- dNet/ChatPackets.cpp | 80 +- dNet/ChatPackets.h | 6 +- dNet/ClientPackets.cpp | 8 +- dNet/ClientPackets.h | 6 +- dNet/MasterPackets.cpp | 61 +- dNet/MasterPackets.h | 12 +- dNet/PacketUtils.cpp | 197 +- dNet/PacketUtils.h | 22 +- dNet/WorldPackets.cpp | 218 +-- dNet/WorldPackets.h | 10 +- dNet/ZoneInstanceManager.cpp | 82 +- dNet/ZoneInstanceManager.h | 76 +- dNet/dMessageIdentifiers.h | 2 +- dNet/dNetCommon.h | 2 +- dNet/dServer.cpp | 54 +- dNet/dServer.h | 4 +- dPhysics/Singleton.h | 2 +- dPhysics/dpCollisionChecks.cpp | 9 +- dPhysics/dpCollisionChecks.h | 2 +- dPhysics/dpCollisionGroups.h | 10 +- dPhysics/dpCommon.h | 2 +- dPhysics/dpEntity.cpp | 3 +- dPhysics/dpEntity.h | 2 +- dPhysics/dpGrid.h | 28 +- dPhysics/dpShapeBase.cpp | 5 +- dPhysics/dpShapeBase.h | 2 +- dPhysics/dpShapeBox.cpp | 9 +- dPhysics/dpShapeBox.h | 2 +- dPhysics/dpShapeSphere.cpp | 3 +- dPhysics/dpShapeSphere.h | 2 +- dPhysics/dpWorld.cpp | 28 +- dPhysics/dpWorld.h | 2 +- dPhysics/main.cpp | 2 +- dScripts/ActMine.cpp | 7 +- dScripts/ActMine.h | 24 +- dScripts/ActNinjaTurret.cpp | 28 +- dScripts/ActNinjaTurret.h | 4 +- dScripts/ActParadoxPipeFix.cpp | 90 +- dScripts/ActParadoxPipeFix.h | 2 +- dScripts/ActPlayerDeathTrigger.cpp | 7 +- dScripts/ActSharkPlayerDeathTrigger.cpp | 4 +- dScripts/ActSharkPlayerDeathTrigger.h | 4 +- dScripts/ActVehicleDeathTrigger.cpp | 70 +- dScripts/ActivityManager.cpp | 295 ++- dScripts/ActivityManager.h | 60 +- dScripts/AgBugsprayer.cpp | 25 +- dScripts/AgBugsprayer.h | 2 +- dScripts/AgBusDoor.cpp | 16 +- dScripts/AgCagedBricksServer.cpp | 5 +- dScripts/AgCagedBricksServer.h | 2 +- dScripts/AgDarkSpiderling.cpp | 10 +- dScripts/AgDarkSpiderling.h | 2 +- dScripts/AgFans.cpp | 13 +- dScripts/AgFans.h | 4 +- dScripts/AgImagSmashable.h | 2 +- dScripts/AgJetEffectServer.cpp | 42 +- dScripts/AgLaserSensorServer.cpp | 11 +- dScripts/AgMonumentBirds.cpp | 2 +- dScripts/AgMonumentLaserServer.cpp | 2 +- dScripts/AgMonumentRaceCancel.cpp | 10 +- dScripts/AgMonumentRaceCancel.h | 2 +- dScripts/AgMonumentRaceGoal.cpp | 17 +- dScripts/AgPicnicBlanket.cpp | 20 +- dScripts/AgPicnicBlanket.h | 2 +- dScripts/AgPropGuard.cpp | 49 +- dScripts/AgPropguards.cpp | 82 +- dScripts/AgPropguards.h | 4 +- dScripts/AgQbElevator.cpp | 14 +- dScripts/AgQbElevator.h | 2 +- dScripts/AgSalutingNpcs.cpp | 6 +- dScripts/AgShipPlayerDeathTrigger.cpp | 2 +- dScripts/AgShipPlayerShockServer.cpp | 6 +- dScripts/AgSpaceStuff.cpp | 12 +- dScripts/AgStagePlatforms.cpp | 18 +- dScripts/AgStagePlatforms.h | 4 +- dScripts/AgStromlingProperty.cpp | 22 +- dScripts/AgStromlingProperty.h | 2 +- dScripts/AgSurvivalBuffStation.cpp | 96 +- dScripts/AgSurvivalBuffStation.h | 90 +- dScripts/AgSurvivalMech.cpp | 14 +- dScripts/AgSurvivalMech.h | 4 +- dScripts/AgSurvivalSpiderling.cpp | 14 +- dScripts/AgSurvivalSpiderling.h | 4 +- dScripts/AgSurvivalStromling.cpp | 2 +- dScripts/AgSurvivalStromling.h | 2 +- dScripts/AgTurret.h | 2 +- dScripts/AmBlueX.cpp | 78 +- dScripts/AmBlueX.h | 26 +- dScripts/AmBridge.cpp | 35 +- dScripts/AmBridge.h | 6 +- dScripts/AmConsoleTeleportServer.cpp | 36 +- dScripts/AmConsoleTeleportServer.h | 24 +- dScripts/AmDarklingDragon.cpp | 211 +-- dScripts/AmDarklingDragon.h | 82 +- dScripts/AmDarklingMech.cpp | 7 +- dScripts/AmDarklingMech.h | 2 +- dScripts/AmDrawBridge.cpp | 168 +- dScripts/AmDrawBridge.h | 14 +- dScripts/AmDropshipComputer.cpp | 118 +- dScripts/AmDropshipComputer.h | 10 +- dScripts/AmScrollReaderServer.cpp | 19 +- dScripts/AmScrollReaderServer.h | 2 +- dScripts/AmShieldGenerator.cpp | 218 +-- dScripts/AmShieldGenerator.h | 14 +- dScripts/AmShieldGeneratorQuickbuild.cpp | 304 ++- dScripts/AmShieldGeneratorQuickbuild.h | 16 +- dScripts/AmSkeletonEngineer.cpp | 31 +- dScripts/AmSkeletonEngineer.h | 2 +- dScripts/AmSkullkinDrill.cpp | 473 +++-- dScripts/AmSkullkinDrill.h | 26 +- dScripts/AmSkullkinDrillStand.cpp | 43 +- dScripts/AmSkullkinDrillStand.h | 6 +- dScripts/AmSkullkinTower.cpp | 365 ++-- dScripts/AmSkullkinTower.h | 12 +- dScripts/AmTeapotServer.cpp | 2 +- dScripts/AmTeapotServer.h | 10 +- dScripts/AmTemplateSkillVolume.cpp | 32 +- dScripts/AmTemplateSkillVolume.h | 2 +- dScripts/AnvilOfArmor.cpp | 18 +- dScripts/AnvilOfArmor.h | 2 +- dScripts/BankInteractServer.cpp | 29 +- dScripts/BankInteractServer.h | 6 +- dScripts/BaseConsoleTeleportServer.cpp | 143 +- dScripts/BaseConsoleTeleportServer.h | 16 +- dScripts/BaseEnemyApe.cpp | 194 +- dScripts/BaseEnemyApe.h | 16 +- dScripts/BaseEnemyMech.cpp | 10 +- dScripts/BaseEnemyMech.h | 2 +- dScripts/BaseFootRaceManager.cpp | 72 +- dScripts/BaseFootRaceManager.h | 6 +- dScripts/BaseInteractDropLootServer.cpp | 37 +- dScripts/BaseInteractDropLootServer.h | 4 +- dScripts/BasePropertyServer.cpp | 510 +++-- dScripts/BasePropertyServer.h | 162 +- dScripts/BaseRandomServer.cpp | 234 +-- dScripts/BaseRandomServer.h | 88 +- dScripts/BaseSurvivalServer.cpp | 844 +++++---- dScripts/BaseSurvivalServer.h | 201 +- dScripts/BaseWavesGenericEnemy.cpp | 14 +- dScripts/BaseWavesGenericEnemy.h | 6 +- dScripts/BaseWavesServer.cpp | 854 ++++----- dScripts/BaseWavesServer.h | 237 +-- dScripts/Binoculars.cpp | 2 +- dScripts/Binoculars.h | 2 +- dScripts/BootyDigServer.cpp | 70 +- dScripts/BootyDigServer.h | 6 +- dScripts/BossSpiderQueenEnemyServer.cpp | 243 ++- dScripts/BossSpiderQueenEnemyServer.h | 14 +- dScripts/BuccaneerValiantShip.cpp | 22 +- dScripts/BuccaneerValiantShip.h | 2 +- dScripts/BurningTile.cpp | 19 +- dScripts/BurningTile.h | 4 +- dScripts/CatapultBaseServer.cpp | 39 +- dScripts/CatapultBaseServer.h | 6 +- dScripts/CatapultBouncerServer.cpp | 16 +- dScripts/CatapultBouncerServer.h | 2 +- dScripts/CauldronOfLife.cpp | 18 +- dScripts/CauldronOfLife.h | 2 +- dScripts/CavePrisonCage.cpp | 322 ++-- dScripts/CavePrisonCage.h | 12 +- dScripts/ChooseYourDestinationNsToNt.cpp | 98 +- dScripts/ChooseYourDestinationNsToNt.h | 6 +- dScripts/ClRing.cpp | 3 +- dScripts/CppScripts.cpp | 236 +-- dScripts/CppScripts.h | 124 +- dScripts/CrabServer.cpp | 56 +- dScripts/CrabServer.h | 6 +- dScripts/DLUVanityNPC.cpp | 68 +- dScripts/DLUVanityNPC.h | 6 +- dScripts/DamagingPets.cpp | 218 +-- dScripts/DamagingPets.h | 22 +- dScripts/Darkitect.cpp | 5 +- dScripts/EnemyNjBuff.cpp | 14 +- dScripts/EnemyRoninSpawner.cpp | 96 +- dScripts/EnemyRoninSpawner.h | 6 +- dScripts/EnemySkeletonSpawner.cpp | 107 +- dScripts/EnemySkeletonSpawner.h | 6 +- dScripts/EnemySpiderSpawner.cpp | 16 +- dScripts/EnemySpiderSpawner.h | 4 +- dScripts/ExplodingAsset.cpp | 41 +- dScripts/ExplodingAsset.h | 2 +- dScripts/FallingTile.cpp | 79 +- dScripts/FallingTile.h | 8 +- dScripts/FireFirstSkillonStartup.cpp | 26 +- dScripts/FireFirstSkillonStartup.h | 4 +- dScripts/FlameJetServer.cpp | 68 +- dScripts/FlameJetServer.h | 6 +- dScripts/ForceVolumeServer.cpp | 27 +- dScripts/FountainOfImagination.cpp | 18 +- dScripts/FountainOfImagination.h | 2 +- dScripts/FvBounceOverWall.cpp | 10 +- dScripts/FvBounceOverWall.h | 32 +- dScripts/FvBrickPuzzleServer.cpp | 100 +- dScripts/FvBrickPuzzleServer.h | 4 +- dScripts/FvCandle.cpp | 12 +- dScripts/FvCandle.h | 4 +- dScripts/FvConsoleLeftQuickbuild.cpp | 75 +- dScripts/FvConsoleLeftQuickbuild.h | 4 +- dScripts/FvConsoleRightQuickbuild.cpp | 75 +- dScripts/FvConsoleRightQuickbuild.h | 4 +- dScripts/FvDragonSmashingGolemQb.cpp | 40 +- dScripts/FvDragonSmashingGolemQb.h | 6 +- dScripts/FvFacilityBrick.cpp | 164 +- dScripts/FvFacilityBrick.h | 10 +- dScripts/FvFlyingCreviceDragon.cpp | 169 +- dScripts/FvFlyingCreviceDragon.h | 6 +- dScripts/FvFong.cpp | 6 +- dScripts/FvFong.h | 4 +- dScripts/FvFreeGfNinjas.cpp | 63 +- dScripts/FvFreeGfNinjas.h | 4 +- dScripts/FvHorsemenTrigger.cpp | 78 +- dScripts/FvHorsemenTrigger.h | 10 +- dScripts/FvMaelstromCavalry.cpp | 45 +- dScripts/FvMaelstromCavalry.h | 2 +- dScripts/FvMaelstromDragon.cpp | 257 ++- dScripts/FvMaelstromDragon.h | 10 +- dScripts/FvNinjaGuard.cpp | 32 +- dScripts/FvPandaServer.cpp | 50 +- dScripts/FvPandaServer.h | 6 +- dScripts/FvPandaSpawnerServer.cpp | 70 +- dScripts/FvPandaSpawnerServer.h | 2 +- dScripts/FvPassThroughWall.cpp | 22 +- dScripts/FvPassThroughWall.h | 56 +- dScripts/FvRaceSmashEggImagineServer.cpp | 50 +- dScripts/FvRaceSmashEggImagineServer.h | 2 +- dScripts/GfApeSmashingQB.cpp | 26 +- dScripts/GfApeSmashingQB.h | 6 +- dScripts/GfBanana.cpp | 33 +- dScripts/GfBanana.h | 4 +- dScripts/GfBananaCluster.cpp | 9 +- dScripts/GfCampfire.cpp | 50 +- dScripts/GfCampfire.h | 10 +- dScripts/GfCaptainsCannon.cpp | 111 +- dScripts/GfCaptainsCannon.h | 6 +- dScripts/GfJailWalls.cpp | 44 +- dScripts/GfJailWalls.h | 6 +- dScripts/GfJailkeepMission.cpp | 58 +- dScripts/GfJailkeepMission.h | 4 +- dScripts/GfOrgan.h | 2 +- dScripts/GfTikiTorch.cpp | 43 +- dScripts/GfTikiTorch.h | 8 +- dScripts/GrowingFlower.cpp | 44 +- dScripts/GrowingFlower.h | 10 +- dScripts/HydrantBroken.cpp | 49 +- dScripts/HydrantBroken.h | 4 +- dScripts/HydrantSmashable.cpp | 23 +- dScripts/HydrantSmashable.h | 2 +- dScripts/ImaginationBackpackHealServer.cpp | 28 +- dScripts/ImaginationBackpackHealServer.h | 2 +- dScripts/ImaginationShrineServer.cpp | 23 +- dScripts/ImaginationShrineServer.h | 2 +- dScripts/ImgBrickConsoleQB.cpp | 385 ++-- dScripts/ImgBrickConsoleQB.h | 24 +- ...nceExitTransferPlayerToLastNonInstance.cpp | 83 +- ...tanceExitTransferPlayerToLastNonInstance.h | 2 +- dScripts/LegoDieRoll.cpp | 84 +- dScripts/LegoDieRoll.h | 2 +- dScripts/Lieutenant.cpp | 66 +- dScripts/Lieutenant.h | 2 +- dScripts/MaestromExtracticatorServer.cpp | 8 +- dScripts/MaestromExtracticatorServer.h | 6 +- dScripts/MailBoxServer.cpp | 4 +- dScripts/MailBoxServer.h | 18 +- dScripts/MastTeleport.cpp | 119 +- dScripts/MastTeleport.h | 4 +- dScripts/MinigameTreasureChestServer.cpp | 86 +- dScripts/MinigameTreasureChestServer.h | 8 +- dScripts/MonCoreNookDoors.cpp | 52 +- dScripts/MonCoreNookDoors.h | 8 +- dScripts/MonCoreSmashableDoors.cpp | 15 +- dScripts/MonCoreSmashableDoors.h | 2 +- dScripts/NPCAddRemoveItem.cpp | 40 +- dScripts/NPCAddRemoveItem.h | 14 +- dScripts/NjColeNPC.cpp | 73 +- dScripts/NjColeNPC.h | 4 +- dScripts/NjDragonEmblemChestServer.cpp | 18 +- dScripts/NjDragonEmblemChestServer.h | 2 +- dScripts/NjEarthDragonPetServer.cpp | 12 +- dScripts/NjEarthDragonPetServer.h | 2 +- dScripts/NjEarthPetServer.cpp | 14 +- dScripts/NjEarthPetServer.h | 4 +- dScripts/NjGarmadonCelebration.cpp | 18 +- dScripts/NjGarmadonCelebration.h | 4 +- dScripts/NjIceRailActivator.cpp | 32 +- dScripts/NjIceRailActivator.h | 10 +- dScripts/NjJayMissionItems.cpp | 14 +- dScripts/NjJayMissionItems.h | 4 +- dScripts/NjMonastryBossInstance.cpp | 802 ++++---- dScripts/NjMonastryBossInstance.h | 252 +-- dScripts/NjNPCMissionSpinjitzuServer.cpp | 32 +- dScripts/NjNPCMissionSpinjitzuServer.h | 20 +- dScripts/NjNyaMissionitems.cpp | 8 +- dScripts/NjNyaMissionitems.h | 2 +- dScripts/NjRailActivatorsServer.cpp | 20 +- dScripts/NjRailActivatorsServer.h | 2 +- dScripts/NjRailPostServer.cpp | 70 +- dScripts/NjRailPostServer.h | 14 +- dScripts/NjRailSwitch.cpp | 16 +- dScripts/NjRailSwitch.h | 2 +- dScripts/NjScrollChestServer.cpp | 20 +- dScripts/NjScrollChestServer.h | 2 +- dScripts/NjWuNPC.cpp | 96 +- dScripts/NjWuNPC.h | 14 +- dScripts/NjhubLavaPlayerDeathTrigger.cpp | 9 +- dScripts/NjhubLavaPlayerDeathTrigger.h | 2 +- dScripts/NpcAgCourseStarter.cpp | 60 +- dScripts/NpcAgCourseStarter.h | 6 +- dScripts/NpcCowboyServer.cpp | 43 +- dScripts/NpcNjAssistantServer.cpp | 7 +- dScripts/NpcNjAssistantServer.h | 2 +- dScripts/NpcNpSpacemanBob.cpp | 8 +- dScripts/NpcPirateServer.cpp | 24 +- dScripts/NpcPirateServer.h | 2 +- dScripts/NpcWispServer.cpp | 38 +- dScripts/NpcWispServer.h | 2 +- dScripts/NsConcertChoiceBuild.cpp | 2 +- dScripts/NsConcertChoiceBuild.h | 4 +- dScripts/NsConcertChoiceBuildManager.cpp | 96 +- dScripts/NsConcertChoiceBuildManager.h | 14 +- dScripts/NsConcertInstrument.cpp | 548 +++--- dScripts/NsConcertInstrument.h | 138 +- dScripts/NsConcertQuickBuild.cpp | 332 ++-- dScripts/NsConcertQuickBuild.h | 34 +- dScripts/NsGetFactionMissionServer.cpp | 12 +- dScripts/NsJohnnyMissionServer.cpp | 20 +- dScripts/NsJohnnyMissionServer.h | 2 +- dScripts/NsLegoClubDoor.cpp | 216 +-- dScripts/NsLegoClubDoor.h | 24 +- dScripts/NsLupTeleport.cpp | 139 +- dScripts/NsLupTeleport.h | 22 +- dScripts/NsQbImaginationStatue.cpp | 53 +- dScripts/NsQbImaginationStatue.h | 6 +- dScripts/NsTokenConsoleServer.cpp | 94 +- dScripts/NsTokenConsoleServer.h | 2 +- dScripts/NtAssemblyTubeServer.cpp | 160 +- dScripts/NtAssemblyTubeServer.h | 12 +- dScripts/NtBeamImaginationCollectors.cpp | 37 +- dScripts/NtBeamImaginationCollectors.h | 14 +- dScripts/NtCombatChallengeDummy.cpp | 38 +- dScripts/NtCombatChallengeDummy.h | 4 +- dScripts/NtCombatChallengeExplodingDummy.cpp | 47 +- dScripts/NtCombatChallengeExplodingDummy.h | 6 +- dScripts/NtCombatChallengeServer.cpp | 292 ++- dScripts/NtCombatChallengeServer.h | 68 +- dScripts/NtConsoleTeleportServer.cpp | 32 +- dScripts/NtConsoleTeleportServer.h | 20 +- dScripts/NtDarkitectRevealServer.cpp | 6 +- dScripts/NtDirtCloudServer.cpp | 65 +- dScripts/NtDirtCloudServer.h | 6 +- dScripts/NtDukeServer.cpp | 50 +- dScripts/NtDukeServer.h | 8 +- dScripts/NtFactionSpyServer.cpp | 136 +- dScripts/NtFactionSpyServer.h | 38 +- dScripts/NtHaelServer.cpp | 26 +- dScripts/NtHaelServer.h | 2 +- dScripts/NtImagBeamBuffer.cpp | 81 +- dScripts/NtImagBeamBuffer.h | 8 +- dScripts/NtOverbuildServer.cpp | 44 +- dScripts/NtOverbuildServer.h | 4 +- dScripts/NtParadoxPanelServer.cpp | 31 +- dScripts/NtParadoxPanelServer.h | 2 +- dScripts/NtParadoxTeleServer.cpp | 158 +- dScripts/NtParadoxTeleServer.h | 10 +- dScripts/NtSentinelWalkwayServer.cpp | 58 +- dScripts/NtSleepingGuard.cpp | 15 +- dScripts/NtVandaServer.cpp | 16 +- dScripts/NtVandaServer.h | 6 +- dScripts/NtVentureCannonServer.cpp | 168 +- dScripts/NtVentureCannonServer.h | 10 +- dScripts/NtVentureSpeedPadServer.cpp | 35 +- dScripts/NtXRayServer.cpp | 16 +- dScripts/PersonalFortress.cpp | 69 +- dScripts/PersonalFortress.h | 4 +- dScripts/PetDigBuild.cpp | 70 +- dScripts/PetDigBuild.h | 4 +- dScripts/PetDigServer.cpp | 319 ++-- dScripts/PetDigServer.h | 32 +- dScripts/PetFromDigServer.cpp | 56 +- dScripts/PetFromDigServer.h | 6 +- dScripts/PetFromObjectServer.cpp | 52 +- dScripts/PetFromObjectServer.h | 6 +- dScripts/PrSeagullFly.cpp | 21 +- dScripts/PrWhistle.cpp | 19 +- dScripts/PrWhistle.h | 4 +- dScripts/PropertyBankInteract.cpp | 52 +- dScripts/PropertyBankInteract.h | 10 +- dScripts/PropertyDeathPlane.cpp | 16 +- dScripts/PropertyDevice.cpp | 32 +- dScripts/PropertyDevice.h | 8 +- dScripts/PropertyFXDamage.cpp | 22 +- dScripts/PropertyFXDamage.h | 2 +- dScripts/PropertyPlatform.cpp | 48 +- dScripts/PropertyPlatform.h | 12 +- dScripts/QbEnemyStunner.cpp | 101 +- dScripts/QbEnemyStunner.h | 4 +- dScripts/RaceImagineCrateServer.cpp | 71 +- dScripts/RaceImagineCrateServer.h | 14 +- dScripts/RaceImaginePowerup.cpp | 45 +- dScripts/RaceImaginePowerup.h | 4 +- dScripts/RaceMaelstromGeiser.cpp | 125 +- dScripts/RaceMaelstromGeiser.h | 4 +- dScripts/RaceSmashServer.cpp | 36 +- dScripts/RaceSmashServer.h | 14 +- dScripts/RainOfArrows.cpp | 113 +- dScripts/RainOfArrows.h | 16 +- dScripts/RandomSpawnerFin.cpp | 40 +- dScripts/RandomSpawnerFin.h | 28 +- dScripts/RandomSpawnerPit.cpp | 30 +- dScripts/RandomSpawnerPit.h | 28 +- dScripts/RandomSpawnerStr.cpp | 28 +- dScripts/RandomSpawnerStr.h | 28 +- dScripts/RandomSpawnerZip.cpp | 26 +- dScripts/RandomSpawnerZip.h | 28 +- dScripts/RockHydrantBroken.cpp | 19 +- dScripts/RockHydrantSmashable.cpp | 7 +- dScripts/SGCannon.cpp | 1661 ++++++++--------- dScripts/SGCannon.h | 270 +-- dScripts/ScriptComponent.cpp | 36 +- dScripts/ScriptComponent.h | 50 +- dScripts/ScriptedPowerupSpawner.cpp | 64 +- dScripts/ScriptedPowerupSpawner.h | 12 +- dScripts/SpawnGryphonServer.cpp | 34 +- dScripts/SpawnGryphonServer.h | 4 +- dScripts/SpawnLionServer.cpp | 12 +- dScripts/SpawnLionServer.h | 2 +- dScripts/SpawnPetBaseServer.cpp | 114 +- dScripts/SpawnPetBaseServer.h | 8 +- dScripts/SpawnSaberCatServer.cpp | 12 +- dScripts/SpawnSaberCatServer.h | 2 +- dScripts/SpawnShrakeServer.cpp | 12 +- dScripts/SpawnShrakeServer.h | 2 +- dScripts/SpawnStegoServer.cpp | 12 +- dScripts/SpawnStegoServer.h | 2 +- dScripts/SpecialImaginePowerupSpawner.cpp | 25 +- dScripts/SsModularBuildServer.cpp | 2 +- dScripts/StinkyFishTarget.cpp | 58 +- dScripts/StinkyFishTarget.h | 6 +- dScripts/StoryBoxInteractServer.cpp | 18 +- dScripts/StoryBoxInteractServer.h | 2 +- dScripts/Sunflower.cpp | 18 +- dScripts/Sunflower.h | 2 +- dScripts/TokenConsoleServer.cpp | 4 +- dScripts/TokenConsoleServer.h | 2 +- dScripts/TouchMissionUpdateServer.cpp | 32 +- dScripts/TreasureChestDragonServer.cpp | 56 +- dScripts/TriggerAmbush.cpp | 17 +- dScripts/TriggerAmbush.h | 4 +- dScripts/VeBricksampleServer.cpp | 24 +- dScripts/VeBricksampleServer.h | 4 +- dScripts/VeEpsilonServer.cpp | 34 +- dScripts/VeEpsilonServer.h | 10 +- dScripts/VeMech.cpp | 6 +- dScripts/VeMech.h | 2 +- dScripts/VeMissionConsole.cpp | 30 +- dScripts/VeMissionConsole.h | 4 +- dScripts/WaveBossApe.cpp | 56 +- dScripts/WaveBossApe.h | 12 +- dScripts/WaveBossHammerling.cpp | 32 +- dScripts/WaveBossHammerling.h | 8 +- dScripts/WaveBossHorsemen.cpp | 32 +- dScripts/WaveBossHorsemen.h | 8 +- dScripts/WaveBossSpiderling.cpp | 34 +- dScripts/WaveBossSpiderling.h | 8 +- dScripts/WhFans.cpp | 7 +- dScripts/WhFans.h | 4 +- dScripts/WildAmbients.cpp | 3 +- dScripts/WishingWellServer.cpp | 57 +- dScripts/WishingWellServer.h | 2 +- dScripts/ZoneAgMedProperty.cpp | 70 +- dScripts/ZoneAgMedProperty.h | 2 +- dScripts/ZoneAgProperty.cpp | 383 ++-- dScripts/ZoneAgProperty.h | 72 +- dScripts/ZoneAgSpiderQueen.cpp | 114 +- dScripts/ZoneAgSpiderQueen.h | 18 +- dScripts/ZoneAgSurvival.cpp | 228 +-- dScripts/ZoneAgSurvival.h | 8 +- dScripts/ZoneFvProperty.cpp | 68 +- dScripts/ZoneFvProperty.h | 2 +- dScripts/ZoneGfProperty.cpp | 68 +- dScripts/ZoneGfProperty.h | 2 +- dScripts/ZoneNsMedProperty.cpp | 68 +- dScripts/ZoneNsMedProperty.h | 2 +- dScripts/ZoneNsProperty.cpp | 70 +- dScripts/ZoneNsProperty.h | 2 +- dScripts/ZoneNsWaves.cpp | 908 ++++----- dScripts/ZoneNsWaves.h | 114 +- dScripts/ZoneSGServer.cpp | 32 +- dScripts/ZoneSGServer.h | 12 +- dWorldServer/ObjectIDManager.cpp | 49 +- dWorldServer/ObjectIDManager.h | 76 +- dWorldServer/PerformanceManager.cpp | 2 +- dWorldServer/WorldServer.cpp | 1135 ++++++----- dZoneManager/Level.cpp | 75 +- dZoneManager/Level.h | 2 +- dZoneManager/Spawner.cpp | 65 +- dZoneManager/Spawner.h | 8 +- dZoneManager/Zone.cpp | 73 +- dZoneManager/Zone.h | 4 +- dZoneManager/dZMCommon.h | 4 +- dZoneManager/dZoneManager.cpp | 71 +- dZoneManager/dZoneManager.h | 14 +- tests/AMFDeserializeTests.cpp | 48 +- tests/TestEncoding.cpp | 78 +- tests/TestLDFFormat.cpp | 8 +- tests/TestNiPoint3.cpp | 4 +- 881 files changed, 34700 insertions(+), 38689 deletions(-) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index f5c85c3f..73cb4212 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -53,15 +53,15 @@ int main(int argc, char** argv) { std::string mysql_username = config.GetValue("mysql_username"); std::string mysql_password = config.GetValue("mysql_password"); - try { - Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); - } catch (sql::SQLException& ex) { + try { + Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); + } catch (sql::SQLException& ex) { Game::logger->Log("AuthServer", "Got an error while connecting to the database: %s", ex.what()); Database::Destroy("AuthServer"); delete Game::server; delete Game::logger; return 0; - } + } //Find out the master's IP: std::string masterIP; @@ -98,8 +98,7 @@ int main(int argc, char** argv) { if (framesSinceMasterDisconnect >= 30) break; //Exit our loop, shut down. - } - else framesSinceMasterDisconnect = 0; + } else framesSinceMasterDisconnect = 0; //In world we'd update our other systems here. @@ -134,8 +133,7 @@ int main(int argc, char** argv) { delete stmt; framesSinceLastSQLPing = 0; - } - else framesSinceLastSQLPing++; + } else framesSinceLastSQLPing++; //Sleep our thread since auth can afford to. t += std::chrono::milliseconds(mediumFramerate); //Auth can run at a lower "fps" @@ -151,7 +149,7 @@ int main(int argc, char** argv) { return EXIT_SUCCESS; } -dLogger * SetupLogger() { +dLogger* SetupLogger() { std::string logPath = "./logs/AuthServer_" + std::to_string(time(nullptr)) + ".log"; bool logToConsole = false; bool logDebugStatements = false; diff --git a/dChatFilter/dChatFilter.cpp b/dChatFilter/dChatFilter.cpp index 6389623e..ea38f8cd 100644 --- a/dChatFilter/dChatFilter.cpp +++ b/dChatFilter/dChatFilter.cpp @@ -21,8 +21,7 @@ dChatFilter::dChatFilter(const std::string& filepath, bool dontGenerateDCF) { if (!BinaryIO::DoesFileExist(filepath + ".dcf") || m_DontGenerateDCF) { ReadWordlistPlaintext(filepath + ".txt", true); if (!m_DontGenerateDCF) ExportWordlistToDCF(filepath + ".dcf", true); - } - else if (!ReadWordlistDCF(filepath + ".dcf", true)) { + } else if (!ReadWordlistDCF(filepath + ".dcf", true)) { ReadWordlistPlaintext(filepath + ".txt", true); ExportWordlistToDCF(filepath + ".dcf", true); } @@ -85,8 +84,7 @@ bool dChatFilter::ReadWordlistDCF(const std::string& filepath, bool whiteList) { } return true; - } - else { + } else { file.close(); return false; } @@ -139,7 +137,7 @@ std::vector> dChatFilter::IsSentenceOkay(const std:: m_UserUnapprovedWordCache.push_back(hash); listOfBadSegments.emplace_back(position, originalSegment.length()); } - + if (std::find(m_DeniedWords.begin(), m_DeniedWords.end(), hash) != m_DeniedWords.end() && !whiteList) { m_UserUnapprovedWordCache.push_back(hash); listOfBadSegments.emplace_back(position, originalSegment.length()); diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index 213e1948..83678525 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -29,8 +29,8 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { std::unique_ptr stmt(Database::CreatePreppedStmt( "SELECT fr.requested_player, best_friend, ci.name FROM " "(SELECT CASE " - "WHEN player_id = ? THEN friend_id " - "WHEN friend_id = ? THEN player_id " + "WHEN player_id = ? THEN friend_id " + "WHEN friend_id = ? THEN player_id " "END AS requested_player, best_friend FROM friends) AS fr " "JOIN charinfo AS ci ON ci.id = fr.requested_player " "WHERE fr.requested_player IS NOT NULL;")); @@ -48,7 +48,7 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { GeneralUtils::SetBit(fd.friendID, static_cast(eObjectBits::OBJECT_BIT_CHARACTER)); fd.isBestFriend = res->getInt(2) == 3; //0 = friends, 1 = left_requested, 2 = right_requested, 3 = both_accepted - are now bffs - if (fd.isBestFriend) player->countOfBestFriends+=1; + if (fd.isBestFriend) player->countOfBestFriends += 1; fd.friendName = res->getString(3); //Now check if they're online: @@ -60,8 +60,7 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { //Since this friend is online, we need to update them on the fact that we've just logged in: SendFriendUpdate(fr, player, 1, fd.isBestFriend); - } - else { + } else { fd.isOnline = false; fd.zoneID = LWOZONEID(); } @@ -209,8 +208,8 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { updateQuery->executeUpdate(); // Sent the best friend update here if the value is 3 if (bestFriendStatus == 3U) { - requestee->countOfBestFriends+=1; - requestor->countOfBestFriends+=1; + requestee->countOfBestFriends += 1; + requestor->countOfBestFriends += 1; if (requestee->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) SendFriendResponse(requestee.get(), requestor, AddFriendResponseType::ACCEPTED, false, true); if (requestor->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) SendFriendResponse(requestor, requestee.get(), AddFriendResponseType::ACCEPTED, false, true); for (auto& friendData : requestor->friends) { @@ -255,18 +254,18 @@ void ChatPacketHandler::HandleFriendResponse(Packet* packet) { uint8_t isAlreadyBestFriends = 0U; // We need to convert this response code to one we can actually send back to the client. switch (clientResponseCode) { - case AddFriendResponseCode::ACCEPTED: - serverResponseCode = AddFriendResponseType::ACCEPTED; - break; - case AddFriendResponseCode::BUSY: - serverResponseCode = AddFriendResponseType::BUSY; - break; - case AddFriendResponseCode::CANCELLED: - serverResponseCode = AddFriendResponseType::CANCELLED; - break; - case AddFriendResponseCode::REJECTED: - serverResponseCode = AddFriendResponseType::DECLINED; - break; + case AddFriendResponseCode::ACCEPTED: + serverResponseCode = AddFriendResponseType::ACCEPTED; + break; + case AddFriendResponseCode::BUSY: + serverResponseCode = AddFriendResponseType::BUSY; + break; + case AddFriendResponseCode::CANCELLED: + serverResponseCode = AddFriendResponseType::CANCELLED; + break; + case AddFriendResponseCode::REJECTED: + serverResponseCode = AddFriendResponseType::DECLINED; + break; } // Now that we have handled the base cases, we need to check the other cases. @@ -371,8 +370,7 @@ void ChatPacketHandler::HandleRemoveFriend(Packet* packet) { SendRemoveFriend(goonB, goonAName, true); } -void ChatPacketHandler::HandleChatMessage(Packet* packet) -{ +void ChatPacketHandler::HandleChatMessage(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -401,8 +399,7 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) if (team == nullptr) return; - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = playerContainer.GetPlayerData(memberId); if (otherMember == nullptr) return; @@ -493,8 +490,7 @@ void ChatPacketHandler::HandlePrivateChatMessage(Packet* packet) { } } -void ChatPacketHandler::HandleTeamInvite(Packet* packet) -{ +void ChatPacketHandler::HandleTeamInvite(Packet* packet) { CINSTREAM; LWOOBJID playerID; inStream.Read(playerID); @@ -503,27 +499,23 @@ void ChatPacketHandler::HandleTeamInvite(Packet* packet) auto* player = playerContainer.GetPlayerData(playerID); - if (player == nullptr) - { + if (player == nullptr) { return; } auto* team = playerContainer.GetTeam(playerID); - if (team == nullptr) - { + if (team == nullptr) { team = playerContainer.CreateTeam(playerID); } auto* other = playerContainer.GetPlayerData(invitedPlayer); - if (other == nullptr) - { + if (other == nullptr) { return; } - if (playerContainer.GetTeam(other->playerID) != nullptr) - { + if (playerContainer.GetTeam(other->playerID) != nullptr) { return; } @@ -539,8 +531,7 @@ void ChatPacketHandler::HandleTeamInvite(Packet* packet) Game::logger->Log("ChatPacketHandler", "Got team invite: %llu -> %s", playerID, invitedPlayer.c_str()); } -void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) -{ +void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -554,22 +545,19 @@ void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) Game::logger->Log("ChatPacketHandler", "Accepted invite: %llu -> %llu (%d)", playerID, leaderID, declined); - if (declined) - { + if (declined) { return; } auto* team = playerContainer.GetTeam(leaderID); - if (team == nullptr) - { + if (team == nullptr) { Game::logger->Log("ChatPacketHandler", "Failed to find team for leader (%llu)", leaderID); team = playerContainer.GetTeam(playerID); } - if (team == nullptr) - { + if (team == nullptr) { Game::logger->Log("ChatPacketHandler", "Failed to find team for player (%llu)", playerID); return; } @@ -577,8 +565,7 @@ void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) playerContainer.AddMember(team, playerID); } -void ChatPacketHandler::HandleTeamLeave(Packet* packet) -{ +void ChatPacketHandler::HandleTeamLeave(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -590,14 +577,12 @@ void ChatPacketHandler::HandleTeamLeave(Packet* packet) Game::logger->Log("ChatPacketHandler", "(%llu) leaving team", playerID); - if (team != nullptr) - { + if (team != nullptr) { playerContainer.RemoveMember(team, playerID, false, false, true); } } -void ChatPacketHandler::HandleTeamKick(Packet* packet) -{ +void ChatPacketHandler::HandleTeamKick(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -611,12 +596,9 @@ void ChatPacketHandler::HandleTeamKick(Packet* packet) LWOOBJID kickedId = LWOOBJID_EMPTY; - if (kicked != nullptr) - { + if (kicked != nullptr) { kickedId = kicked->playerID; - } - else - { + } else { kickedId = playerContainer.GetId(GeneralUtils::ASCIIToUTF16(kickedPlayer)); } @@ -624,16 +606,14 @@ void ChatPacketHandler::HandleTeamKick(Packet* packet) auto* team = playerContainer.GetTeam(playerID); - if (team != nullptr) - { + if (team != nullptr) { if (team->leaderID != playerID || team->leaderID == kickedId) return; playerContainer.RemoveMember(team, kickedId, false, true, false); } } -void ChatPacketHandler::HandleTeamPromote(Packet* packet) -{ +void ChatPacketHandler::HandleTeamPromote(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -649,16 +629,14 @@ void ChatPacketHandler::HandleTeamPromote(Packet* packet) auto* team = playerContainer.GetTeam(playerID); - if (team != nullptr) - { + if (team != nullptr) { if (team->leaderID != playerID) return; playerContainer.PromoteMember(team, promoted->playerID); } } -void ChatPacketHandler::HandleTeamLootOption(Packet* packet) -{ +void ChatPacketHandler::HandleTeamLootOption(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -671,8 +649,7 @@ void ChatPacketHandler::HandleTeamLootOption(Packet* packet) auto* team = playerContainer.GetTeam(playerID); - if (team != nullptr) - { + if (team != nullptr) { if (team->leaderID != playerID) return; team->lootFlag = option; @@ -683,8 +660,7 @@ void ChatPacketHandler::HandleTeamLootOption(Packet* packet) } } -void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) -{ +void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) { CINSTREAM; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); @@ -693,28 +669,22 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) auto* team = playerContainer.GetTeam(playerID); auto* data = playerContainer.GetPlayerData(playerID); - if (team != nullptr && data != nullptr) - { - if (team->local && data->zoneID.GetMapID() != team->zoneId.GetMapID() && data->zoneID.GetCloneID() != team->zoneId.GetCloneID()) - { + if (team != nullptr && data != nullptr) { + if (team->local && data->zoneID.GetMapID() != team->zoneId.GetMapID() && data->zoneID.GetCloneID() != team->zoneId.GetCloneID()) { playerContainer.RemoveMember(team, playerID, false, false, true, true); return; } - if (team->memberIDs.size() <= 1 && !team->local) - { + if (team->memberIDs.size() <= 1 && !team->local) { playerContainer.DisbandTeam(team); return; } - if (!team->local) - { + if (!team->local) { ChatPacketHandler::SendTeamSetLeader(data, team->leaderID); - } - else - { + } else { ChatPacketHandler::SendTeamSetLeader(data, LWOOBJID_EMPTY); } @@ -722,16 +692,14 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(data->playerName.c_str())); - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = playerContainer.GetPlayerData(memberId); if (memberId == playerID) continue; const auto memberName = playerContainer.GetName(memberId); - if (otherMember != nullptr) - { + if (otherMember != nullptr) { ChatPacketHandler::SendTeamSetOffWorldFlag(otherMember, data->playerID, data->zoneID); } ChatPacketHandler::SendTeamAddPlayer(data, false, team->local, false, memberId, memberName, otherMember != nullptr ? otherMember->zoneID : LWOZONEID(0, 0, 0)); @@ -741,8 +709,7 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) } } -void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) -{ +void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -757,8 +724,7 @@ void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) SEND_PACKET; } -void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeaderIsFreeTrial, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, uint8_t ucResponseCode, std::u16string wsLeaderName) -{ +void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeaderIsFreeTrial, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, uint8_t ucResponseCode, std::u16string wsLeaderName) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -766,7 +732,7 @@ void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeader //portion that will get routed: CMSGHEADER - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_INVITE_CONFIRM); bitStream.Write(bLeaderIsFreeTrial); @@ -777,8 +743,7 @@ void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeader bitStream.Write(ucNumOfOtherPlayers); bitStream.Write(ucResponseCode); bitStream.Write(static_cast(wsLeaderName.size())); - for (const auto character : wsLeaderName) - { + for (const auto character : wsLeaderName) { bitStream.Write(character); } @@ -786,8 +751,7 @@ void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeader SEND_PACKET; } -void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, std::u16string wsLeaderName) -{ +void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, std::u16string wsLeaderName) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -795,7 +759,7 @@ void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderI //portion that will get routed: CMSGHEADER - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_GET_STATUS_RESPONSE); bitStream.Write(i64LeaderID); @@ -804,8 +768,7 @@ void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderI bitStream.Write(ucLootFlag); bitStream.Write(ucNumOfOtherPlayers); bitStream.Write(static_cast(wsLeaderName.size())); - for (const auto character : wsLeaderName) - { + for (const auto character : wsLeaderName) { bitStream.Write(character); } @@ -813,8 +776,7 @@ void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderI SEND_PACKET; } -void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64PlayerID) -{ +void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64PlayerID) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -822,7 +784,7 @@ void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64Play //portion that will get routed: CMSGHEADER - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_SET_LEADER); bitStream.Write(i64PlayerID); @@ -831,8 +793,7 @@ void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64Play SEND_PACKET; } -void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTrial, bool bLocal, bool bNoLootOnDeath, LWOOBJID i64PlayerID, std::u16string wsPlayerName, LWOZONEID zoneID) -{ +void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTrial, bool bLocal, bool bNoLootOnDeath, LWOOBJID i64PlayerID, std::u16string wsPlayerName, LWOZONEID zoneID) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -840,7 +801,7 @@ void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTria //portion that will get routed: CMSGHEADER - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_ADD_PLAYER); bitStream.Write(bIsFreeTrial); @@ -848,13 +809,11 @@ void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTria bitStream.Write(bNoLootOnDeath); bitStream.Write(i64PlayerID); bitStream.Write(static_cast(wsPlayerName.size())); - for (const auto character : wsPlayerName) - { + for (const auto character : wsPlayerName) { bitStream.Write(character); } bitStream.Write1(); - if (receiver->zoneID.GetCloneID() == zoneID.GetCloneID()) - { + if (receiver->zoneID.GetCloneID() == zoneID.GetCloneID()) { zoneID = LWOZONEID(zoneID.GetMapID(), zoneID.GetInstanceID(), 0); } bitStream.Write(zoneID); @@ -863,8 +822,7 @@ void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTria SEND_PACKET; } -void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband, bool bIsKicked, bool bIsLeaving, bool bLocal, LWOOBJID i64LeaderID, LWOOBJID i64PlayerID, std::u16string wsPlayerName) -{ +void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband, bool bIsKicked, bool bIsLeaving, bool bLocal, LWOOBJID i64LeaderID, LWOOBJID i64PlayerID, std::u16string wsPlayerName) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -872,7 +830,7 @@ void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband //portion that will get routed: CMSGHEADER - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_REMOVE_PLAYER); bitStream.Write(bDisband); @@ -882,8 +840,7 @@ void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband bitStream.Write(i64LeaderID); bitStream.Write(i64PlayerID); bitStream.Write(static_cast(wsPlayerName.size())); - for (const auto character : wsPlayerName) - { + for (const auto character : wsPlayerName) { bitStream.Write(character); } @@ -891,8 +848,7 @@ void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband SEND_PACKET; } -void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i64PlayerID, LWOZONEID zoneID) -{ +void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i64PlayerID, LWOZONEID zoneID) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); @@ -900,12 +856,11 @@ void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i //portion that will get routed: CMSGHEADER - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_SET_OFF_WORLD_FLAG); bitStream.Write(i64PlayerID); - if (receiver->zoneID.GetCloneID() == zoneID.GetCloneID()) - { + if (receiver->zoneID.GetCloneID() == zoneID.GetCloneID()) { zoneID = LWOZONEID(zoneID.GetMapID(), zoneID.GetInstanceID(), 0); } bitStream.Write(zoneID); @@ -943,12 +898,9 @@ void ChatPacketHandler::SendFriendUpdate(PlayerData* friendData, PlayerData* pla bitStream.Write(playerData->zoneID.GetMapID()); bitStream.Write(playerData->zoneID.GetInstanceID()); - if (playerData->zoneID.GetCloneID() == friendData->zoneID.GetCloneID()) - { + if (playerData->zoneID.GetCloneID() == friendData->zoneID.GetCloneID()) { bitStream.Write(0); - } - else - { + } else { bitStream.Write(playerData->zoneID.GetCloneID()); } @@ -998,7 +950,7 @@ void ChatPacketHandler::SendFriendResponse(PlayerData* receiver, PlayerData* sen // Then write the player name PacketUtils::WritePacketWString(sender->playerName.c_str(), 33, &bitStream); // Then if this is an acceptance code, write the following extra info. - if (responseCode == AddFriendResponseType::ACCEPTED) { + if (responseCode == AddFriendResponseType::ACCEPTED) { bitStream.Write(sender->playerID); bitStream.Write(sender->zoneID); bitStream.Write(isBestFriendRequest); //isBFF diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index 639d7b70..273921eb 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -58,8 +58,7 @@ int main(int argc, char** argv) { try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); - } - catch (sql::SQLException& ex) { + } catch (sql::SQLException& ex) { Game::logger->Log("ChatServer", "Got an error while connecting to the database: %s", ex.what()); Database::Destroy("ChatServer"); delete Game::server; @@ -104,8 +103,7 @@ int main(int argc, char** argv) { if (framesSinceMasterDisconnect >= 30) break; //Exit our loop, shut down. - } - else framesSinceMasterDisconnect = 0; + } else framesSinceMasterDisconnect = 0; //In world we'd update our other systems here. @@ -122,8 +120,7 @@ int main(int argc, char** argv) { if (framesSinceLastFlush >= 900) { Game::logger->Flush(); framesSinceLastFlush = 0; - } - else framesSinceLastFlush++; + } else framesSinceLastFlush++; //Every 10 min we ping our sql server to keep it alive hopefully: if (framesSinceLastSQLPing >= 40000) { @@ -141,8 +138,7 @@ int main(int argc, char** argv) { delete stmt; framesSinceLastSQLPing = 0; - } - else framesSinceLastSQLPing++; + } else framesSinceLastSQLPing++; //Sleep our thread since auth can afford to. t += std::chrono::milliseconds(mediumFramerate); //Chat can run at a lower "fps" @@ -158,7 +154,7 @@ int main(int argc, char** argv) { return EXIT_SUCCESS; } -dLogger * SetupLogger() { +dLogger* SetupLogger() { std::string logPath = "./logs/ChatServer_" + std::to_string(time(nullptr)) + ".log"; bool logToConsole = false; bool logDebugStatements = false; diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index 73a22ba9..d8c2e067 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -70,17 +70,15 @@ void PlayerContainer::RemovePlayer(Packet* packet) { auto* team = GetTeam(playerID); - if (team != nullptr) - { + if (team != nullptr) { const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(player->playerName.c_str())); - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); if (otherMember == nullptr) continue; - ChatPacketHandler::SendTeamSetOffWorldFlag(otherMember, playerID, {0, 0, 0}); + ChatPacketHandler::SendTeamSetOffWorldFlag(otherMember, playerID, { 0, 0, 0 }); } } @@ -97,8 +95,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { insertLog->executeUpdate(); } -void PlayerContainer::MuteUpdate(Packet* packet) -{ +void PlayerContainer::MuteUpdate(Packet* packet) { CINSTREAM; LWOOBJID playerID; inStream.Read(playerID); //skip header @@ -108,8 +105,7 @@ void PlayerContainer::MuteUpdate(Packet* packet) auto* player = this->GetPlayerData(playerID); - if (player == nullptr) - { + if (player == nullptr) { Game::logger->Log("PlayerContainer", "Failed to find user: %llu", playerID); return; @@ -120,8 +116,7 @@ void PlayerContainer::MuteUpdate(Packet* packet) BroadcastMuteUpdate(playerID, expire); } -void PlayerContainer::CreateTeamServer(Packet* packet) -{ +void PlayerContainer::CreateTeamServer(Packet* packet) { CINSTREAM; LWOOBJID playerID; inStream.Read(playerID); //skip header @@ -133,8 +128,7 @@ void PlayerContainer::CreateTeamServer(Packet* packet) members.reserve(membersSize); - for (size_t i = 0; i < membersSize; i++) - { + for (size_t i = 0; i < membersSize; i++) { LWOOBJID member; inStream.Read(member); members.push_back(member); @@ -146,16 +140,14 @@ void PlayerContainer::CreateTeamServer(Packet* packet) auto* team = CreateLocalTeam(members); - if (team != nullptr) - { + if (team != nullptr) { team->zoneId = zoneId; } UpdateTeamsOnWorld(team, false); } -void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) -{ +void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_MUTE_UPDATE); @@ -165,30 +157,23 @@ void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); } -TeamData* PlayerContainer::CreateLocalTeam(std::vector members) -{ - if (members.empty()) - { +TeamData* PlayerContainer::CreateLocalTeam(std::vector members) { + if (members.empty()) { return nullptr; } TeamData* newTeam = nullptr; - for (const auto member : members) - { + for (const auto member : members) { auto* team = GetTeam(member); - if (team != nullptr) - { + if (team != nullptr) { RemoveMember(team, member, false, false, true); } - if (newTeam == nullptr) - { + if (newTeam == nullptr) { newTeam = CreateTeam(member, true); - } - else - { + } else { AddMember(newTeam, member); } } @@ -200,8 +185,7 @@ TeamData* PlayerContainer::CreateLocalTeam(std::vector members) return newTeam; } -TeamData* PlayerContainer::CreateTeam(LWOOBJID leader, bool local) -{ +TeamData* PlayerContainer::CreateTeam(LWOOBJID leader, bool local) { auto* team = new TeamData(); team->teamID = ++mTeamIDCounter; @@ -215,10 +199,8 @@ TeamData* PlayerContainer::CreateTeam(LWOOBJID leader, bool local) return team; } -TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) -{ - for (auto* team : mTeams) - { +TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) { + for (auto* team : mTeams) { if (std::find(team->memberIDs.begin(), team->memberIDs.end(), playerID) == team->memberIDs.end()) continue; return team; @@ -227,8 +209,7 @@ TeamData* PlayerContainer::GetTeam(LWOOBJID playerID) return nullptr; } -void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) -{ +void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) { const auto index = std::find(team->memberIDs.begin(), team->memberIDs.end(), playerID); if (index != team->memberIDs.end()) return; @@ -245,19 +226,15 @@ void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) ChatPacketHandler::SendTeamInviteConfirm(member, false, leader->playerID, leader->zoneID, team->lootFlag, 0, 0, leaderName); - if (!team->local) - { + if (!team->local) { ChatPacketHandler::SendTeamSetLeader(member, leader->playerID); - } - else - { + } else { ChatPacketHandler::SendTeamSetLeader(member, LWOOBJID_EMPTY); } UpdateTeamsOnWorld(team, false); - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); if (otherMember == member) continue; @@ -266,32 +243,27 @@ void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) ChatPacketHandler::SendTeamAddPlayer(member, false, team->local, false, memberId, otherMemberName, otherMember != nullptr ? otherMember->zoneID : LWOZONEID(0, 0, 0)); - if (otherMember != nullptr) - { + if (otherMember != nullptr) { ChatPacketHandler::SendTeamAddPlayer(otherMember, false, team->local, false, member->playerID, memberName, member->zoneID); } } } -void PlayerContainer::RemoveMember(TeamData* team, LWOOBJID playerID, bool disband, bool kicked, bool leaving, bool silent) -{ +void PlayerContainer::RemoveMember(TeamData* team, LWOOBJID playerID, bool disband, bool kicked, bool leaving, bool silent) { const auto index = std::find(team->memberIDs.begin(), team->memberIDs.end(), playerID); if (index == team->memberIDs.end()) return; auto* member = GetPlayerData(playerID); - if (member != nullptr && !silent) - { + if (member != nullptr && !silent) { ChatPacketHandler::SendTeamSetLeader(member, LWOOBJID_EMPTY); } const auto memberName = GetName(playerID); - for (const auto memberId : team->memberIDs) - { - if (silent && memberId == playerID) - { + for (const auto memberId : team->memberIDs) { + if (silent && memberId == playerID) { continue; } @@ -306,25 +278,19 @@ void PlayerContainer::RemoveMember(TeamData* team, LWOOBJID playerID, bool disba UpdateTeamsOnWorld(team, false); - if (team->memberIDs.size() <= 1) - { + if (team->memberIDs.size() <= 1) { DisbandTeam(team); - } - else - { - if (playerID == team->leaderID) - { + } else { + if (playerID == team->leaderID) { PromoteMember(team, team->memberIDs[0]); } } } -void PlayerContainer::PromoteMember(TeamData* team, LWOOBJID newLeader) -{ +void PlayerContainer::PromoteMember(TeamData* team, LWOOBJID newLeader) { team->leaderID = newLeader; - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); if (otherMember == nullptr) continue; @@ -333,14 +299,12 @@ void PlayerContainer::PromoteMember(TeamData* team, LWOOBJID newLeader) } } -void PlayerContainer::DisbandTeam(TeamData* team) -{ +void PlayerContainer::DisbandTeam(TeamData* team) { const auto index = std::find(mTeams.begin(), mTeams.end(), team); if (index == mTeams.end()) return; - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); if (otherMember == nullptr) continue; @@ -358,8 +322,7 @@ void PlayerContainer::DisbandTeam(TeamData* team) delete team; } -void PlayerContainer::TeamStatusUpdate(TeamData* team) -{ +void PlayerContainer::TeamStatusUpdate(TeamData* team) { const auto index = std::find(mTeams.begin(), mTeams.end(), team); if (index == mTeams.end()) return; @@ -370,14 +333,12 @@ void PlayerContainer::TeamStatusUpdate(TeamData* team) const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(leader->playerName.c_str())); - for (const auto memberId : team->memberIDs) - { + for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); if (otherMember == nullptr) continue; - if (!team->local) - { + if (!team->local) { ChatPacketHandler::SendTeamStatus(otherMember, team->leaderID, leader->zoneID, team->lootFlag, 0, leaderName); } } @@ -385,20 +346,17 @@ void PlayerContainer::TeamStatusUpdate(TeamData* team) UpdateTeamsOnWorld(team, false); } -void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) -{ +void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_TEAM_UPDATE); bitStream.Write(team->teamID); bitStream.Write(deleteTeam); - if (!deleteTeam) - { + if (!deleteTeam) { bitStream.Write(team->lootFlag); bitStream.Write(static_cast(team->memberIDs.size())); - for (const auto memberID : team->memberIDs) - { + for (const auto memberID : team->memberIDs) { bitStream.Write(memberID); } } @@ -406,8 +364,7 @@ void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); } -std::u16string PlayerContainer::GetName(LWOOBJID playerID) -{ +std::u16string PlayerContainer::GetName(LWOOBJID playerID) { const auto& pair = mNames.find(playerID); if (pair == mNames.end()) return u""; @@ -415,12 +372,9 @@ std::u16string PlayerContainer::GetName(LWOOBJID playerID) return pair->second; } -LWOOBJID PlayerContainer::GetId(const std::u16string& playerName) -{ - for (const auto& pair : mNames) - { - if (pair.second == playerName) - { +LWOOBJID PlayerContainer::GetId(const std::u16string& playerName) { + for (const auto& pair : mNames) { + if (pair.second == playerName) { return pair.first; } } @@ -428,7 +382,6 @@ LWOOBJID PlayerContainer::GetId(const std::u16string& playerName) return LWOOBJID_EMPTY; } -bool PlayerContainer::GetIsMuted(PlayerData* data) -{ +bool PlayerContainer::GetIsMuted(PlayerData* data) { return data->muteExpire == 1 || data->muteExpire > time(NULL); } diff --git a/dChatServer/PlayerContainer.h b/dChatServer/PlayerContainer.h index 9216a361..0836eb59 100644 --- a/dChatServer/PlayerContainer.h +++ b/dChatServer/PlayerContainer.h @@ -20,7 +20,7 @@ struct PlayerData { struct TeamData { LWOOBJID teamID = LWOOBJID_EMPTY; // Internal use LWOOBJID leaderID = LWOOBJID_EMPTY; - std::vector memberIDs {}; + std::vector memberIDs{}; uint8_t lootFlag = 0; bool local = false; LWOZONEID zoneId = {}; diff --git a/dCommon/AMFDeserialize.cpp b/dCommon/AMFDeserialize.cpp index afe2b61b..df4a7cb6 100644 --- a/dCommon/AMFDeserialize.cpp +++ b/dCommon/AMFDeserialize.cpp @@ -15,64 +15,64 @@ AMFValue* AMFDeserialize::Read(RakNet::BitStream* inStream) { inStream->Read(marker); // Based on the typing, create the value associated with that and return the base value class switch (marker) { - case AMFValueType::AMFUndefined: { - returnValue = new AMFUndefinedValue(); - break; - } + case AMFValueType::AMFUndefined: { + returnValue = new AMFUndefinedValue(); + break; + } - case AMFValueType::AMFNull: { - returnValue = new AMFNullValue(); - break; - } + case AMFValueType::AMFNull: { + returnValue = new AMFNullValue(); + break; + } - case AMFValueType::AMFFalse: { - returnValue = new AMFFalseValue(); - break; - } + case AMFValueType::AMFFalse: { + returnValue = new AMFFalseValue(); + break; + } - case AMFValueType::AMFTrue: { - returnValue = new AMFTrueValue(); - break; - } + case AMFValueType::AMFTrue: { + returnValue = new AMFTrueValue(); + break; + } - case AMFValueType::AMFInteger: { - returnValue = ReadAmfInteger(inStream); - break; - } + case AMFValueType::AMFInteger: { + returnValue = ReadAmfInteger(inStream); + break; + } - case AMFValueType::AMFDouble: { - returnValue = ReadAmfDouble(inStream); - break; - } + case AMFValueType::AMFDouble: { + returnValue = ReadAmfDouble(inStream); + break; + } - case AMFValueType::AMFString: { - returnValue = ReadAmfString(inStream); - break; - } + case AMFValueType::AMFString: { + returnValue = ReadAmfString(inStream); + break; + } - case AMFValueType::AMFArray: { - returnValue = ReadAmfArray(inStream); - break; - } + case AMFValueType::AMFArray: { + returnValue = ReadAmfArray(inStream); + break; + } - // TODO We do not need these values, but if someone wants to implement them - // then please do so and add the corresponding unit tests. - case AMFValueType::AMFXMLDoc: - case AMFValueType::AMFDate: - case AMFValueType::AMFObject: - case AMFValueType::AMFXML: - case AMFValueType::AMFByteArray: - case AMFValueType::AMFVectorInt: - case AMFValueType::AMFVectorUInt: - case AMFValueType::AMFVectorDouble: - case AMFValueType::AMFVectorObject: - case AMFValueType::AMFDictionary: { - throw static_cast(marker); - break; - } - default: - throw static_cast(marker); - break; + // TODO We do not need these values, but if someone wants to implement them + // then please do so and add the corresponding unit tests. + case AMFValueType::AMFXMLDoc: + case AMFValueType::AMFDate: + case AMFValueType::AMFObject: + case AMFValueType::AMFXML: + case AMFValueType::AMFByteArray: + case AMFValueType::AMFVectorInt: + case AMFValueType::AMFVectorUInt: + case AMFValueType::AMFVectorDouble: + case AMFValueType::AMFVectorObject: + case AMFValueType::AMFDictionary: { + throw static_cast(marker); + break; + } + default: + throw static_cast(marker); + break; } return returnValue; } @@ -128,10 +128,10 @@ AMFValue* AMFDeserialize::ReadAmfDouble(RakNet::BitStream* inStream) { AMFValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream* inStream) { auto arrayValue = new AMFArrayValue(); - // Read size of dense array + // Read size of dense array auto sizeOfDenseArray = (ReadU29(inStream) >> 1); - // Then read Key'd portion + // Then read Key'd portion while (true) { auto key = ReadString(inStream); // No more values when we encounter an empty string @@ -139,7 +139,7 @@ AMFValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream* inStream) { arrayValue->InsertValue(key, Read(inStream)); } - // Finally read dense portion + // Finally read dense portion for (uint32_t i = 0; i < sizeOfDenseArray; i++) { arrayValue->PushBackValue(Read(inStream)); } diff --git a/dCommon/AMFDeserialize.h b/dCommon/AMFDeserialize.h index d03c150f..a49cdcd2 100644 --- a/dCommon/AMFDeserialize.h +++ b/dCommon/AMFDeserialize.h @@ -7,65 +7,65 @@ class AMFValue; class AMFDeserialize { - public: - /** - * Read an AMF3 value from a bitstream. - * - * @param inStream inStream to read value from. - * @return Returns an AMFValue with all the information from the bitStream in it. - */ - AMFValue* Read(RakNet::BitStream* inStream); - private: - /** - * @brief Private method to read a U29 integer from a bitstream - * - * @param inStream bitstream to read data from - * @return The number as an unsigned 29 bit integer - */ - uint32_t ReadU29(RakNet::BitStream* inStream); +public: + /** + * Read an AMF3 value from a bitstream. + * + * @param inStream inStream to read value from. + * @return Returns an AMFValue with all the information from the bitStream in it. + */ + AMFValue* Read(RakNet::BitStream* inStream); +private: + /** + * @brief Private method to read a U29 integer from a bitstream + * + * @param inStream bitstream to read data from + * @return The number as an unsigned 29 bit integer + */ + uint32_t ReadU29(RakNet::BitStream* inStream); - /** - * @brief Reads a string from a bitstream - * - * @param inStream bitStream to read data from - * @return The read string - */ - std::string ReadString(RakNet::BitStream* inStream); - - /** - * @brief Read an AMFDouble value from a bitStream - * - * @param inStream bitStream to read data from - * @return Double value represented as an AMFValue - */ - AMFValue* ReadAmfDouble(RakNet::BitStream* inStream); + /** + * @brief Reads a string from a bitstream + * + * @param inStream bitStream to read data from + * @return The read string + */ + std::string ReadString(RakNet::BitStream* inStream); - /** - * @brief Read an AMFArray from a bitStream - * - * @param inStream bitStream to read data from - * @return Array value represented as an AMFValue - */ - AMFValue* ReadAmfArray(RakNet::BitStream* inStream); + /** + * @brief Read an AMFDouble value from a bitStream + * + * @param inStream bitStream to read data from + * @return Double value represented as an AMFValue + */ + AMFValue* ReadAmfDouble(RakNet::BitStream* inStream); - /** - * @brief Read an AMFString from a bitStream - * - * @param inStream bitStream to read data from - * @return String value represented as an AMFValue - */ - AMFValue* ReadAmfString(RakNet::BitStream* inStream); + /** + * @brief Read an AMFArray from a bitStream + * + * @param inStream bitStream to read data from + * @return Array value represented as an AMFValue + */ + AMFValue* ReadAmfArray(RakNet::BitStream* inStream); - /** - * @brief Read an AMFInteger from a bitStream - * - * @param inStream bitStream to read data from - * @return Integer value represented as an AMFValue - */ - AMFValue* ReadAmfInteger(RakNet::BitStream* inStream); + /** + * @brief Read an AMFString from a bitStream + * + * @param inStream bitStream to read data from + * @return String value represented as an AMFValue + */ + AMFValue* ReadAmfString(RakNet::BitStream* inStream); - /** - * List of strings read so far saved to be read by reference. - */ - std::vector accessedElements; + /** + * @brief Read an AMFInteger from a bitStream + * + * @param inStream bitStream to read data from + * @return Integer value represented as an AMFValue + */ + AMFValue* ReadAmfInteger(RakNet::BitStream* inStream); + + /** + * List of strings read so far saved to be read by reference. + */ + std::vector accessedElements; }; diff --git a/dCommon/AMFFormat.cpp b/dCommon/AMFFormat.cpp index 741a8bc4..822f994d 100644 --- a/dCommon/AMFFormat.cpp +++ b/dCommon/AMFFormat.cpp @@ -2,170 +2,170 @@ // AMFInteger void AMFIntegerValue::SetIntegerValue(uint32_t value) { - this->value = value; + this->value = value; } uint32_t AMFIntegerValue::GetIntegerValue() { - return this->value; + return this->value; } // AMFDouble void AMFDoubleValue::SetDoubleValue(double value) { - this->value = value; + this->value = value; } double AMFDoubleValue::GetDoubleValue() { - return this->value; + return this->value; } // AMFString void AMFStringValue::SetStringValue(const std::string& value) { - this->value = value; + this->value = value; } std::string AMFStringValue::GetStringValue() { - return this->value; + return this->value; } // AMFXMLDoc void AMFXMLDocValue::SetXMLDocValue(const std::string& value) { - this->xmlData = value; + this->xmlData = value; } std::string AMFXMLDocValue::GetXMLDocValue() { - return this->xmlData; + return this->xmlData; } // AMFDate void AMFDateValue::SetDateValue(uint64_t value) { - this->millisecondTimestamp = value; + this->millisecondTimestamp = value; } uint64_t AMFDateValue::GetDateValue() { - return this->millisecondTimestamp; + return this->millisecondTimestamp; } // AMFArray Insert Value void AMFArrayValue::InsertValue(const std::string& key, AMFValue* value) { - this->associative.insert(std::make_pair(key, value)); + this->associative.insert(std::make_pair(key, value)); } // AMFArray Remove Value void AMFArrayValue::RemoveValue(const std::string& key) { - _AMFArrayMap_::iterator it = this->associative.find(key); - if (it != this->associative.end()) { - this->associative.erase(it); - } + _AMFArrayMap_::iterator it = this->associative.find(key); + if (it != this->associative.end()) { + this->associative.erase(it); + } } // AMFArray Find Value AMFValue* AMFArrayValue::FindValue(const std::string& key) { - _AMFArrayMap_::iterator it = this->associative.find(key); - if (it != this->associative.end()) { - return it->second; - } - - return nullptr; + _AMFArrayMap_::iterator it = this->associative.find(key); + if (it != this->associative.end()) { + return it->second; + } + + return nullptr; } // AMFArray Get Associative Iterator Begin _AMFArrayMap_::iterator AMFArrayValue::GetAssociativeIteratorValueBegin() { - return this->associative.begin(); + return this->associative.begin(); } // AMFArray Get Associative Iterator End _AMFArrayMap_::iterator AMFArrayValue::GetAssociativeIteratorValueEnd() { - return this->associative.end(); + return this->associative.end(); } // AMFArray Push Back Value void AMFArrayValue::PushBackValue(AMFValue* value) { - this->dense.push_back(value); + this->dense.push_back(value); } // AMFArray Pop Back Value void AMFArrayValue::PopBackValue() { - this->dense.pop_back(); + this->dense.pop_back(); } // AMFArray Get Dense List Size uint32_t AMFArrayValue::GetDenseValueSize() { - return (uint32_t)this->dense.size(); + return (uint32_t)this->dense.size(); } // AMFArray Get value at index in Dense List AMFValue* AMFArrayValue::GetValueAt(uint32_t index) { - return this->dense.at(index); + return this->dense.at(index); } // AMFArray Get Dense Iterator Begin _AMFArrayList_::iterator AMFArrayValue::GetDenseIteratorBegin() { - return this->dense.begin(); + return this->dense.begin(); } // AMFArray Get Dense Iterator End _AMFArrayList_::iterator AMFArrayValue::GetDenseIteratorEnd() { - return this->dense.end(); + return this->dense.end(); } AMFArrayValue::~AMFArrayValue() { - for (auto valueToDelete : GetDenseArray()) { - if (valueToDelete) delete valueToDelete; - } - for (auto valueToDelete : GetAssociativeMap()) { - if (valueToDelete.second) delete valueToDelete.second; - } + for (auto valueToDelete : GetDenseArray()) { + if (valueToDelete) delete valueToDelete; + } + for (auto valueToDelete : GetAssociativeMap()) { + if (valueToDelete.second) delete valueToDelete.second; + } } // AMFObject Constructor AMFObjectValue::AMFObjectValue(std::vector> traits) { - this->traits.reserve(traits.size()); - std::vector>::iterator it = traits.begin(); - while (it != traits.end()) { - this->traits.insert(std::make_pair(it->first, std::make_pair(it->second, new AMFNullValue()))); - it++; - } + this->traits.reserve(traits.size()); + std::vector>::iterator it = traits.begin(); + while (it != traits.end()) { + this->traits.insert(std::make_pair(it->first, std::make_pair(it->second, new AMFNullValue()))); + it++; + } } // AMFObject Set Value void AMFObjectValue::SetTraitValue(const std::string& trait, AMFValue* value) { - if (value) { - _AMFObjectTraits_::iterator it = this->traits.find(trait); - if (it != this->traits.end()) { - if (it->second.first == value->GetValueType()) { - it->second.second = value; - } - } - } + if (value) { + _AMFObjectTraits_::iterator it = this->traits.find(trait); + if (it != this->traits.end()) { + if (it->second.first == value->GetValueType()) { + it->second.second = value; + } + } + } } // AMFObject Get Value AMFValue* AMFObjectValue::GetTraitValue(const std::string& trait) { - _AMFObjectTraits_::iterator it = this->traits.find(trait); - if (it != this->traits.end()) { - return it->second.second; - } - - return nullptr; + _AMFObjectTraits_::iterator it = this->traits.find(trait); + if (it != this->traits.end()) { + return it->second.second; + } + + return nullptr; } // AMFObject Get Trait Iterator Begin _AMFObjectTraits_::iterator AMFObjectValue::GetTraitsIteratorBegin() { - return this->traits.begin(); + return this->traits.begin(); } // AMFObject Get Trait Iterator End _AMFObjectTraits_::iterator AMFObjectValue::GetTraitsIteratorEnd() { - return this->traits.end(); + return this->traits.end(); } // AMFObject Get Trait Size uint32_t AMFObjectValue::GetTraitArrayCount() { - return (uint32_t)this->traits.size(); + return (uint32_t)this->traits.size(); } AMFObjectValue::~AMFObjectValue() { - for (auto valueToDelete = GetTraitsIteratorBegin(); valueToDelete != GetTraitsIteratorEnd(); valueToDelete++) { - if (valueToDelete->second.second) delete valueToDelete->second.second; - } + for (auto valueToDelete = GetTraitsIteratorBegin(); valueToDelete != GetTraitsIteratorEnd(); valueToDelete++) { + if (valueToDelete->second.second) delete valueToDelete->second.second; + } } diff --git a/dCommon/AMFFormat.h b/dCommon/AMFFormat.h index 54a02944..eaa342cd 100644 --- a/dCommon/AMFFormat.h +++ b/dCommon/AMFFormat.h @@ -23,43 +23,43 @@ class AMFValue; // Forward declaration //! An enum for each AMF value type enum AMFValueType : unsigned char { - AMFUndefined = 0x00, //!< An undefined AMF Value - AMFNull = 0x01, //!< A null AMF value - AMFFalse = 0x02, //!< A false AMF value - AMFTrue = 0x03, //!< A true AMF value - AMFInteger = 0x04, //!< An integer AMF value - AMFDouble = 0x05, //!< A double AMF value - AMFString = 0x06, //!< A string AMF value - AMFXMLDoc = 0x07, //!< An XML Doc AMF value - AMFDate = 0x08, //!< A date AMF value - AMFArray = 0x09, //!< An array AMF value - AMFObject = 0x0A, //!< An object AMF value - AMFXML = 0x0B, //!< An XML AMF value - AMFByteArray = 0x0C, //!< A byte array AMF value - AMFVectorInt = 0x0D, //!< An integer vector AMF value - AMFVectorUInt = 0x0E, //!< An unsigned integer AMF value - AMFVectorDouble = 0x0F, //!< A double vector AMF value - AMFVectorObject = 0x10, //!< An object vector AMF value - AMFDictionary = 0x11 //!< A dictionary AMF value + AMFUndefined = 0x00, //!< An undefined AMF Value + AMFNull = 0x01, //!< A null AMF value + AMFFalse = 0x02, //!< A false AMF value + AMFTrue = 0x03, //!< A true AMF value + AMFInteger = 0x04, //!< An integer AMF value + AMFDouble = 0x05, //!< A double AMF value + AMFString = 0x06, //!< A string AMF value + AMFXMLDoc = 0x07, //!< An XML Doc AMF value + AMFDate = 0x08, //!< A date AMF value + AMFArray = 0x09, //!< An array AMF value + AMFObject = 0x0A, //!< An object AMF value + AMFXML = 0x0B, //!< An XML AMF value + AMFByteArray = 0x0C, //!< A byte array AMF value + AMFVectorInt = 0x0D, //!< An integer vector AMF value + AMFVectorUInt = 0x0E, //!< An unsigned integer AMF value + AMFVectorDouble = 0x0F, //!< A double vector AMF value + AMFVectorObject = 0x10, //!< An object vector AMF value + AMFDictionary = 0x11 //!< A dictionary AMF value }; //! An enum for the object value types enum AMFObjectValueType : unsigned char { - AMFObjectAnonymous = 0x01, - AMFObjectTyped = 0x02, - AMFObjectDynamic = 0x03, - AMFObjectExternalizable = 0x04 + AMFObjectAnonymous = 0x01, + AMFObjectTyped = 0x02, + AMFObjectDynamic = 0x03, + AMFObjectExternalizable = 0x04 }; //! The base AMF value class class AMFValue { public: - //! Returns the AMF value type - /*! - \return The AMF value type - */ - virtual AMFValueType GetValueType() = 0; - virtual ~AMFValue() {}; + //! Returns the AMF value type + /*! + \return The AMF value type + */ + virtual AMFValueType GetValueType() = 0; + virtual ~AMFValue() {}; }; //! A typedef for a pointer to an AMF value @@ -71,314 +71,314 @@ typedef AMFValue* NDGFxValue; //! The undefined value AMF type class AMFUndefinedValue : public AMFValue { private: - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFUndefined; } + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFUndefined; } }; //! The null value AMF type class AMFNullValue : public AMFValue { private: - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFNull; } + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFNull; } }; //! The false value AMF type class AMFFalseValue : public AMFValue { private: - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFFalse; } + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFFalse; } }; //! The true value AMF type class AMFTrueValue : public AMFValue { private: - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFTrue; } + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFTrue; } }; //! The integer value AMF type class AMFIntegerValue : public AMFValue { private: - uint32_t value; //!< The value of the AMF type - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFInteger; } - + uint32_t value; //!< The value of the AMF type + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFInteger; } + public: - //! Sets the integer value - /*! - \param value The value to set - */ - void SetIntegerValue(uint32_t value); - - //! Gets the integer value - /*! - \return The integer value - */ - uint32_t GetIntegerValue(); + //! Sets the integer value + /*! + \param value The value to set + */ + void SetIntegerValue(uint32_t value); + + //! Gets the integer value + /*! + \return The integer value + */ + uint32_t GetIntegerValue(); }; //! The double value AMF type class AMFDoubleValue : public AMFValue { private: - double value; //!< The value of the AMF type - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFDouble; } - + double value; //!< The value of the AMF type + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFDouble; } + public: - //! Sets the double value - /*! - \param value The value to set to - */ - void SetDoubleValue(double value); - - //! Gets the double value - /*! - \return The double value - */ - double GetDoubleValue(); + //! Sets the double value + /*! + \param value The value to set to + */ + void SetDoubleValue(double value); + + //! Gets the double value + /*! + \return The double value + */ + double GetDoubleValue(); }; //! The string value AMF type class AMFStringValue : public AMFValue { private: - std::string value; //!< The value of the AMF type - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFString; } - + std::string value; //!< The value of the AMF type + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFString; } + public: - //! Sets the string value - /*! - \param value The string value to set to - */ - void SetStringValue(const std::string& value); - - //! Gets the string value - /*! - \return The string value - */ - std::string GetStringValue(); + //! Sets the string value + /*! + \param value The string value to set to + */ + void SetStringValue(const std::string& value); + + //! Gets the string value + /*! + \return The string value + */ + std::string GetStringValue(); }; //! The XML doc value AMF type class AMFXMLDocValue : public AMFValue { private: - std::string xmlData; //!< The value of the AMF type - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFXMLDoc; } - + std::string xmlData; //!< The value of the AMF type + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFXMLDoc; } + public: - //! Sets the XML Doc value - /*! - \param value The value to set to - */ - void SetXMLDocValue(const std::string& value); - - //! Gets the XML Doc value - /*! - \return The XML Doc value - */ - std::string GetXMLDocValue(); + //! Sets the XML Doc value + /*! + \param value The value to set to + */ + void SetXMLDocValue(const std::string& value); + + //! Gets the XML Doc value + /*! + \return The XML Doc value + */ + std::string GetXMLDocValue(); }; //! The date value AMF type class AMFDateValue : public AMFValue { private: - uint64_t millisecondTimestamp; //!< The time in milliseconds since the ephoch - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFDate; } - + uint64_t millisecondTimestamp; //!< The time in milliseconds since the ephoch + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFDate; } + public: - //! Sets the date time - /*! - \param value The value to set to - */ - void SetDateValue(uint64_t value); - - //! Gets the date value - /*! - \return The date value in milliseconds since the epoch - */ - uint64_t GetDateValue(); + //! Sets the date time + /*! + \param value The value to set to + */ + void SetDateValue(uint64_t value); + + //! Gets the date value + /*! + \return The date value in milliseconds since the epoch + */ + uint64_t GetDateValue(); }; //! The array value AMF type // This object will manage it's own memory map and list. Do not delete its values. class AMFArrayValue : public AMFValue { private: - _AMFArrayMap_ associative; //!< The array map (associative part) - _AMFArrayList_ dense; //!< The array list (dense part) - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFArray; } - + _AMFArrayMap_ associative; //!< The array map (associative part) + _AMFArrayList_ dense; //!< The array list (dense part) + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFArray; } + public: - ~AMFArrayValue() override; - //! Inserts an item into the array map for a specific key - /*! - \param key The key to set - \param value The value to add - */ - void InsertValue(const std::string& key, AMFValue* value); - - //! Removes an item for a specific key - /*! - \param key The key to remove - */ - void RemoveValue(const std::string& key); - - //! Finds an AMF value - /*! - \return The AMF value if found, nullptr otherwise - */ - AMFValue* FindValue(const std::string& key); - - //! Returns where the associative iterator begins - /*! - \return Where the array map iterator begins - */ - _AMFArrayMap_::iterator GetAssociativeIteratorValueBegin(); - - //! Returns where the associative iterator ends - /*! - \return Where the array map iterator ends - */ - _AMFArrayMap_::iterator GetAssociativeIteratorValueEnd(); - - //! Pushes back a value into the array list - /*! - \param value The value to push back - */ - void PushBackValue(AMFValue* value); - - //! Pops back the last value in the array list - void PopBackValue(); - - //! Gets the count of the dense list - /*! - \return The dense list size - */ - uint32_t GetDenseValueSize(); - - //! Gets a specific value from the list for the specified index - /*! - \param index The index to get - */ - AMFValue* GetValueAt(uint32_t index); - - //! Returns where the dense iterator begins - /*! - \return Where the iterator begins - */ - _AMFArrayList_::iterator GetDenseIteratorBegin(); - - //! Returns where the dense iterator ends - /*! - \return Where the iterator ends - */ - _AMFArrayList_::iterator GetDenseIteratorEnd(); + ~AMFArrayValue() override; + //! Inserts an item into the array map for a specific key + /*! + \param key The key to set + \param value The value to add + */ + void InsertValue(const std::string& key, AMFValue* value); - //! Returns the associative map - /*! - \return The associative map - */ - _AMFArrayMap_ GetAssociativeMap() { return this->associative; }; + //! Removes an item for a specific key + /*! + \param key The key to remove + */ + void RemoveValue(const std::string& key); - //! Returns the dense array - /*! - \return The dense array - */ - _AMFArrayList_ GetDenseArray() { return this->dense; }; + //! Finds an AMF value + /*! + \return The AMF value if found, nullptr otherwise + */ + AMFValue* FindValue(const std::string& key); + + //! Returns where the associative iterator begins + /*! + \return Where the array map iterator begins + */ + _AMFArrayMap_::iterator GetAssociativeIteratorValueBegin(); + + //! Returns where the associative iterator ends + /*! + \return Where the array map iterator ends + */ + _AMFArrayMap_::iterator GetAssociativeIteratorValueEnd(); + + //! Pushes back a value into the array list + /*! + \param value The value to push back + */ + void PushBackValue(AMFValue* value); + + //! Pops back the last value in the array list + void PopBackValue(); + + //! Gets the count of the dense list + /*! + \return The dense list size + */ + uint32_t GetDenseValueSize(); + + //! Gets a specific value from the list for the specified index + /*! + \param index The index to get + */ + AMFValue* GetValueAt(uint32_t index); + + //! Returns where the dense iterator begins + /*! + \return Where the iterator begins + */ + _AMFArrayList_::iterator GetDenseIteratorBegin(); + + //! Returns where the dense iterator ends + /*! + \return Where the iterator ends + */ + _AMFArrayList_::iterator GetDenseIteratorEnd(); + + //! Returns the associative map + /*! + \return The associative map + */ + _AMFArrayMap_ GetAssociativeMap() { return this->associative; }; + + //! Returns the dense array + /*! + \return The dense array + */ + _AMFArrayList_ GetDenseArray() { return this->dense; }; }; //! The anonymous object value AMF type class AMFObjectValue : public AMFValue { private: - _AMFObjectTraits_ traits; //!< The object traits - - //! Returns the AMF value type - /*! - \return The AMF value type - */ - AMFValueType GetValueType() { return AMFObject; } - ~AMFObjectValue() override; - + _AMFObjectTraits_ traits; //!< The object traits + + //! Returns the AMF value type + /*! + \return The AMF value type + */ + AMFValueType GetValueType() { return AMFObject; } + ~AMFObjectValue() override; + public: - //! Constructor - /*! - \param traits The traits to set - */ - AMFObjectValue(std::vector> traits); - - //! Gets the object value type - /*! - \return The object value type - */ - virtual AMFObjectValueType GetObjectValueType() { return AMFObjectAnonymous; } - - //! Sets the value of a trait - /*! - \param trait The trait to set the value for - \param value The AMF value to set - */ - void SetTraitValue(const std::string& trait, AMFValue* value); - - //! Gets a trait value - /*! - \param trait The trait to get the value for - \return The trait value - */ - AMFValue* GetTraitValue(const std::string& trait); - - //! Gets the beginning of the object traits iterator - /*! - \return The AMF trait array iterator begin - */ - _AMFObjectTraits_::iterator GetTraitsIteratorBegin(); - - //! Gets the end of the object traits iterator - /*! - \return The AMF trait array iterator begin - */ - _AMFObjectTraits_::iterator GetTraitsIteratorEnd(); - - //! Gets the amount of traits - /*! - \return The amount of traits - */ - uint32_t GetTraitArrayCount(); + //! Constructor + /*! + \param traits The traits to set + */ + AMFObjectValue(std::vector> traits); + + //! Gets the object value type + /*! + \return The object value type + */ + virtual AMFObjectValueType GetObjectValueType() { return AMFObjectAnonymous; } + + //! Sets the value of a trait + /*! + \param trait The trait to set the value for + \param value The AMF value to set + */ + void SetTraitValue(const std::string& trait, AMFValue* value); + + //! Gets a trait value + /*! + \param trait The trait to get the value for + \return The trait value + */ + AMFValue* GetTraitValue(const std::string& trait); + + //! Gets the beginning of the object traits iterator + /*! + \return The AMF trait array iterator begin + */ + _AMFObjectTraits_::iterator GetTraitsIteratorBegin(); + + //! Gets the end of the object traits iterator + /*! + \return The AMF trait array iterator begin + */ + _AMFObjectTraits_::iterator GetTraitsIteratorEnd(); + + //! Gets the amount of traits + /*! + \return The amount of traits + */ + uint32_t GetTraitArrayCount(); }; diff --git a/dCommon/AMFFormat_BitStream.cpp b/dCommon/AMFFormat_BitStream.cpp index 96ccdab3..b603ba31 100644 --- a/dCommon/AMFFormat_BitStream.cpp +++ b/dCommon/AMFFormat_BitStream.cpp @@ -5,73 +5,73 @@ template<> void RakNet::BitStream::Write(AMFValue* value) { if (value != nullptr) { AMFValueType type = value->GetValueType(); - + switch (type) { - case AMFUndefined: { - AMFUndefinedValue* v = (AMFUndefinedValue*)value; - this->Write(*v); - break; - } - - case AMFNull: { - AMFNullValue* v = (AMFNullValue*)value; - this->Write(*v); - break; - } - - case AMFFalse: { - AMFFalseValue* v = (AMFFalseValue*)value; - this->Write(*v); - break; - } - - case AMFTrue: { - AMFTrueValue* v = (AMFTrueValue*)value; - this->Write(*v); - break; - } - - case AMFInteger: { - AMFIntegerValue* v = (AMFIntegerValue*)value; - this->Write(*v); - break; - } + case AMFUndefined: { + AMFUndefinedValue* v = (AMFUndefinedValue*)value; + this->Write(*v); + break; + } - case AMFDouble: { - AMFDoubleValue* v = (AMFDoubleValue*)value; - this->Write(*v); - break; - } + case AMFNull: { + AMFNullValue* v = (AMFNullValue*)value; + this->Write(*v); + break; + } - case AMFString: { - AMFStringValue* v = (AMFStringValue*)value; - this->Write(*v); - break; - } - - case AMFXMLDoc: { - AMFXMLDocValue* v = (AMFXMLDocValue*)value; - this->Write(*v); - break; - } - - case AMFDate: { - AMFDateValue* v = (AMFDateValue*)value; - this->Write(*v); - break; - } - - case AMFArray: { - this->Write((AMFArrayValue*)value); - break; - } + case AMFFalse: { + AMFFalseValue* v = (AMFFalseValue*)value; + this->Write(*v); + break; + } + + case AMFTrue: { + AMFTrueValue* v = (AMFTrueValue*)value; + this->Write(*v); + break; + } + + case AMFInteger: { + AMFIntegerValue* v = (AMFIntegerValue*)value; + this->Write(*v); + break; + } + + case AMFDouble: { + AMFDoubleValue* v = (AMFDoubleValue*)value; + this->Write(*v); + break; + } + + case AMFString: { + AMFStringValue* v = (AMFStringValue*)value; + this->Write(*v); + break; + } + + case AMFXMLDoc: { + AMFXMLDocValue* v = (AMFXMLDocValue*)value; + this->Write(*v); + break; + } + + case AMFDate: { + AMFDateValue* v = (AMFDateValue*)value; + this->Write(*v); + break; + } + + case AMFArray: { + this->Write((AMFArrayValue*)value); + break; + } } } } -/** +/** * A private function to write an value to a RakNet::BitStream - * RakNet writes in the correct byte order - do not reverse this. + * RakNet writes in the correct byte order - do not reverse this. */ void WriteUInt29(RakNet::BitStream* bs, uint32_t v) { unsigned char b4 = (unsigned char)v; @@ -87,70 +87,70 @@ void WriteUInt29(RakNet::BitStream* bs, uint32_t v) { b2 = ((unsigned char)(v)) | 0x80; bs->Write(b2); } - + bs->Write(b3); } } else { unsigned char b1; unsigned char b2; unsigned char b3; - + v = v >> 8; b3 = ((unsigned char)(v)) | 0x80; v = v >> 7; b2 = ((unsigned char)(v)) | 0x80; v = v >> 7; b1 = ((unsigned char)(v)) | 0x80; - + bs->Write(b1); bs->Write(b2); bs->Write(b3); } - + bs->Write(b4); } -/** +/** * Writes a flag number to a RakNet::BitStream - * RakNet writes in the correct byte order - do not reverse this. + * RakNet writes in the correct byte order - do not reverse this. */ void WriteFlagNumber(RakNet::BitStream* bs, uint32_t v) { v = (v << 1) | 0x01; WriteUInt29(bs, v); } -/** +/** * Writes an AMFString to a RakNet::BitStream - * - * RakNet writes in the correct byte order - do not reverse this. + * + * RakNet writes in the correct byte order - do not reverse this. */ void WriteAMFString(RakNet::BitStream* bs, const std::string& str) { WriteFlagNumber(bs, (uint32_t)str.size()); bs->Write(str.c_str(), (uint32_t)str.size()); } -/** +/** * Writes an U16 to a bitstream - * - * RakNet writes in the correct byte order - do not reverse this. + * + * RakNet writes in the correct byte order - do not reverse this. */ void WriteAMFU16(RakNet::BitStream* bs, uint16_t value) { bs->Write(value); } -/** +/** * Writes an U32 to a bitstream - * - * RakNet writes in the correct byte order - do not reverse this. + * + * RakNet writes in the correct byte order - do not reverse this. */ void WriteAMFU32(RakNet::BitStream* bs, uint32_t value) { bs->Write(value); } -/** +/** * Writes an U64 to a bitstream - * - * RakNet writes in the correct byte order - do not reverse this. + * + * RakNet writes in the correct byte order - do not reverse this. */ void WriteAMFU64(RakNet::BitStream* bs, uint64_t value) { bs->Write(value); @@ -193,7 +193,7 @@ template<> void RakNet::BitStream::Write(AMFDoubleValue value) { this->Write(AMFDouble); double d = value.GetDoubleValue(); - WriteAMFU64(this, *((unsigned long long*)&d)); + WriteAMFU64(this, *((unsigned long long*) & d)); } // Writes an AMFStringValue to BitStream @@ -226,22 +226,22 @@ void RakNet::BitStream::Write(AMFArrayValue* value) { this->Write(AMFArray); uint32_t denseSize = value->GetDenseValueSize(); WriteFlagNumber(this, denseSize); - + _AMFArrayMap_::iterator it = value->GetAssociativeIteratorValueBegin(); _AMFArrayMap_::iterator end = value->GetAssociativeIteratorValueEnd(); - + while (it != end) { WriteAMFString(this, it->first); this->Write(it->second); it++; } - + this->Write(AMFNull); - + if (denseSize > 0) { _AMFArrayList_::iterator it2 = value->GetDenseIteratorBegin(); _AMFArrayList_::iterator end2 = value->GetDenseIteratorEnd(); - + while (it2 != end2) { this->Write(*it2); it2++; diff --git a/dCommon/AMFFormat_BitStream.h b/dCommon/AMFFormat_BitStream.h index ff72a180..caa49337 100644 --- a/dCommon/AMFFormat_BitStream.h +++ b/dCommon/AMFFormat_BitStream.h @@ -11,7 +11,7 @@ \brief A class that implements native writing of AMF values to RakNet::BitStream */ -// We are using the RakNet namespace + // We are using the RakNet namespace namespace RakNet { //! Writes an AMFValue pointer to a RakNet::BitStream /*! @@ -19,70 +19,70 @@ namespace RakNet { */ template <> void RakNet::BitStream::Write(AMFValue* value); - + //! Writes an AMFUndefinedValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFUndefinedValue value); - + //! Writes an AMFNullValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFNullValue value); - + //! Writes an AMFFalseValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFFalseValue value); - + //! Writes an AMFTrueValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFTrueValue value); - + //! Writes an AMFIntegerValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFIntegerValue value); - + //! Writes an AMFDoubleValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFDoubleValue value); - + //! Writes an AMFStringValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFStringValue value); - + //! Writes an AMFXMLDocValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFXMLDocValue value); - + //! Writes an AMFDateValue to a RakNet::BitStream /*! \param value The value to write */ template <> void RakNet::BitStream::Write(AMFDateValue value); - + //! Writes an AMFArrayValue to a RakNet::BitStream /*! \param value The value to write diff --git a/dCommon/BinaryIO.cpp b/dCommon/BinaryIO.cpp index 8cad23a6..7cb18331 100644 --- a/dCommon/BinaryIO.cpp +++ b/dCommon/BinaryIO.cpp @@ -10,7 +10,7 @@ void BinaryIO::WriteString(const std::string& stringToWrite, std::ofstream& outs } //For reading null-terminated strings -std::string BinaryIO::ReadString(std::ifstream & instream) { +std::string BinaryIO::ReadString(std::ifstream& instream) { std::string toReturn; char buffer; @@ -37,7 +37,7 @@ std::string BinaryIO::ReadString(std::ifstream& instream, size_t size) { return toReturn; } -std::string BinaryIO::ReadWString(std::ifstream & instream) { +std::string BinaryIO::ReadWString(std::ifstream& instream) { size_t size; BinaryRead(instream, size); //toReturn.resize(size); diff --git a/dCommon/BinaryIO.h b/dCommon/BinaryIO.h index 0c459f02..1f9aaefd 100644 --- a/dCommon/BinaryIO.h +++ b/dCommon/BinaryIO.h @@ -9,15 +9,15 @@ namespace BinaryIO { } template - std::istream & BinaryRead(std::istream& stream, T& value) { - if (!stream.good()) + std::istream& BinaryRead(std::istream& stream, T& value) { + if (!stream.good()) printf("bla"); return stream.read(reinterpret_cast(&value), sizeof(T)); } void WriteString(const std::string& stringToWrite, std::ofstream& outstream); - std::string ReadString(std::ifstream & instream); + std::string ReadString(std::ifstream& instream); std::string ReadString(std::ifstream& instream, size_t size); std::string ReadWString(std::ifstream& instream); diff --git a/dCommon/Diagnostics.cpp b/dCommon/Diagnostics.cpp index 5963400d..bfde2d9a 100644 --- a/dCommon/Diagnostics.cpp +++ b/dCommon/Diagnostics.cpp @@ -10,51 +10,51 @@ #include "dLogger.h" void make_minidump(EXCEPTION_POINTERS* e) { - auto hDbgHelp = LoadLibraryA("dbghelp"); - if (hDbgHelp == nullptr) - return; - auto pMiniDumpWriteDump = (decltype(&MiniDumpWriteDump))GetProcAddress(hDbgHelp, "MiniDumpWriteDump"); - if (pMiniDumpWriteDump == nullptr) - return; + auto hDbgHelp = LoadLibraryA("dbghelp"); + if (hDbgHelp == nullptr) + return; + auto pMiniDumpWriteDump = (decltype(&MiniDumpWriteDump))GetProcAddress(hDbgHelp, "MiniDumpWriteDump"); + if (pMiniDumpWriteDump == nullptr) + return; - char name[MAX_PATH]; - { - auto nameEnd = name + GetModuleFileNameA(GetModuleHandleA(0), name, MAX_PATH); - SYSTEMTIME t; - GetSystemTime(&t); - wsprintfA(nameEnd - strlen(".exe"), - "_%4d%02d%02d_%02d%02d%02d.dmp", - t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond); - } + char name[MAX_PATH]; + { + auto nameEnd = name + GetModuleFileNameA(GetModuleHandleA(0), name, MAX_PATH); + SYSTEMTIME t; + GetSystemTime(&t); + wsprintfA(nameEnd - strlen(".exe"), + "_%4d%02d%02d_%02d%02d%02d.dmp", + t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond); + } - auto hFile = CreateFileA(name, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); - if (hFile == INVALID_HANDLE_VALUE) - return; + auto hFile = CreateFileA(name, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); + if (hFile == INVALID_HANDLE_VALUE) + return; - MINIDUMP_EXCEPTION_INFORMATION exceptionInfo; - exceptionInfo.ThreadId = GetCurrentThreadId(); - exceptionInfo.ExceptionPointers = e; - exceptionInfo.ClientPointers = FALSE; + MINIDUMP_EXCEPTION_INFORMATION exceptionInfo; + exceptionInfo.ThreadId = GetCurrentThreadId(); + exceptionInfo.ExceptionPointers = e; + exceptionInfo.ClientPointers = FALSE; - auto dumped = pMiniDumpWriteDump( - GetCurrentProcess(), - GetCurrentProcessId(), - hFile, - MINIDUMP_TYPE(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory), - e ? &exceptionInfo : nullptr, - nullptr, - nullptr); + auto dumped = pMiniDumpWriteDump( + GetCurrentProcess(), + GetCurrentProcessId(), + hFile, + MINIDUMP_TYPE(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory), + e ? &exceptionInfo : nullptr, + nullptr, + nullptr); - CloseHandle(hFile); + CloseHandle(hFile); - return; + return; } LONG CALLBACK unhandled_handler(EXCEPTION_POINTERS* e) { - make_minidump(e); - if (Game::logger) - Game::logger->Flush(); // Flush our log if we have one, before exiting. - return EXCEPTION_CONTINUE_SEARCH; + make_minidump(e); + if (Game::logger) + Game::logger->Flush(); // Flush our log if we have one, before exiting. + return EXCEPTION_CONTINUE_SEARCH; } #endif @@ -75,146 +75,146 @@ LONG CALLBACK unhandled_handler(EXCEPTION_POINTERS* e) { #include struct bt_ctx { - struct backtrace_state* state; - int error; + struct backtrace_state* state; + int error; }; static inline void Bt(struct backtrace_state* state) { - std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; - FILE* file = fopen(fileName.c_str(), "w+"); - if (file != nullptr) { - backtrace_print(state, 2, file); - fclose(file); - } + std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; + FILE* file = fopen(fileName.c_str(), "w+"); + if (file != nullptr) { + backtrace_print(state, 2, file); + fclose(file); + } - backtrace_print(state, 2, stdout); + backtrace_print(state, 2, stdout); } static void ErrorCallback(void* data, const char* msg, int errnum) { - auto* ctx = (struct bt_ctx*)data; - fprintf(stderr, "ERROR: %s (%d)", msg, errnum); - ctx->error = 1; + auto* ctx = (struct bt_ctx*)data; + fprintf(stderr, "ERROR: %s (%d)", msg, errnum); + ctx->error = 1; - std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; - FILE* file = fopen(fileName.c_str(), "w+"); - if (file != nullptr) { - fprintf(file, "ERROR: %s (%d)", msg, errnum); - fclose(file); - } + std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; + FILE* file = fopen(fileName.c_str(), "w+"); + if (file != nullptr) { + fprintf(file, "ERROR: %s (%d)", msg, errnum); + fclose(file); + } } #endif #include "Type.h" void GenerateDump() { - std::string cmd = "sudo gcore " + std::to_string(getpid()); - system(cmd.c_str()); + std::string cmd = "sudo gcore " + std::to_string(getpid()); + system(cmd.c_str()); } void CatchUnhandled(int sig) { #ifndef __include_backtrace__ - if (Diagnostics::GetProduceMemoryDump()) { - GenerateDump(); - } + if (Diagnostics::GetProduceMemoryDump()) { + GenerateDump(); + } - void* array[10]; - size_t size; + void* array[10]; + size_t size; - // get void*'s for all entries on the stack - size = backtrace(array, 10); + // get void*'s for all entries on the stack + size = backtrace(array, 10); - printf("Fatal error %i\nStacktrace:\n", sig); + printf("Fatal error %i\nStacktrace:\n", sig); #if defined(__GNUG__) and defined(__dynamic) - // Loop through the returned addresses, and get the symbols to be demangled - char** strings = backtrace_symbols(array, size); + // Loop through the returned addresses, and get the symbols to be demangled + char** strings = backtrace_symbols(array, size); - // Print the stack trace - for (size_t i = 0; i < size; i++) { - // Take a string like './WorldServer(_ZN19SlashCommandHandler17HandleChatCommandERKSbIDsSt11char_traitsIDsESaIDsEEP6EntityRK13SystemAddress+0x6187) [0x55869c44ecf7]' and extract the function name - std::string functionName = strings[i]; - std::string::size_type start = functionName.find('('); - std::string::size_type end = functionName.find('+'); - if (start != std::string::npos && end != std::string::npos) { - std::string demangled = functionName.substr(start + 1, end - start - 1); + // Print the stack trace + for (size_t i = 0; i < size; i++) { + // Take a string like './WorldServer(_ZN19SlashCommandHandler17HandleChatCommandERKSbIDsSt11char_traitsIDsESaIDsEEP6EntityRK13SystemAddress+0x6187) [0x55869c44ecf7]' and extract the function name + std::string functionName = strings[i]; + std::string::size_type start = functionName.find('('); + std::string::size_type end = functionName.find('+'); + if (start != std::string::npos && end != std::string::npos) { + std::string demangled = functionName.substr(start + 1, end - start - 1); - demangled = demangle(functionName.c_str()); + demangled = demangle(functionName.c_str()); - if (demangled.empty()) { - printf("[%02d] %s\n", i, demangled.c_str()); - } else { - printf("[%02d] %s\n", i, functionName.c_str()); - } - } else { - printf("[%02d] %s\n", i, functionName.c_str()); - } - } + if (demangled.empty()) { + printf("[%02d] %s\n", i, demangled.c_str()); + } else { + printf("[%02d] %s\n", i, functionName.c_str()); + } + } else { + printf("[%02d] %s\n", i, functionName.c_str()); + } + } #else - backtrace_symbols_fd(array, size, STDOUT_FILENO); + backtrace_symbols_fd(array, size, STDOUT_FILENO); #endif - std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; - FILE* file = fopen(fileName.c_str(), "w+"); - if (file != NULL) { - // print out all the frames to stderr - fprintf(file, "Error: signal %d:\n", sig); - backtrace_symbols_fd(array, size, fileno(file)); - fclose(file); - } + std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; + FILE* file = fopen(fileName.c_str(), "w+"); + if (file != NULL) { + // print out all the frames to stderr + fprintf(file, "Error: signal %d:\n", sig); + backtrace_symbols_fd(array, size, fileno(file)); + fclose(file); + } #else - struct backtrace_state* state = backtrace_create_state( - Diagnostics::GetProcessFileName().c_str(), - BACKTRACE_SUPPORTS_THREADS, - ErrorCallback, - nullptr); + struct backtrace_state* state = backtrace_create_state( + Diagnostics::GetProcessFileName().c_str(), + BACKTRACE_SUPPORTS_THREADS, + ErrorCallback, + nullptr); - struct bt_ctx ctx = {state, 0}; - Bt(state); + struct bt_ctx ctx = { state, 0 }; + Bt(state); #endif - exit(EXIT_FAILURE); + exit(EXIT_FAILURE); } void CritErrHdlr(int sig_num, siginfo_t* info, void* ucontext) { - CatchUnhandled(sig_num); + CatchUnhandled(sig_num); } void OnTerminate() { - CatchUnhandled(-1); + CatchUnhandled(-1); } void MakeBacktrace() { - struct sigaction sigact; + struct sigaction sigact; - sigact.sa_sigaction = CritErrHdlr; - sigact.sa_flags = SA_RESTART | SA_SIGINFO; + sigact.sa_sigaction = CritErrHdlr; + sigact.sa_flags = SA_RESTART | SA_SIGINFO; - if (sigaction(SIGSEGV, &sigact, (struct sigaction*)nullptr) != 0 || - sigaction(SIGFPE, &sigact, (struct sigaction*)nullptr) != 0 || - sigaction(SIGABRT, &sigact, (struct sigaction*)nullptr) != 0 || - sigaction(SIGILL, &sigact, (struct sigaction*)nullptr) != 0) { - fprintf(stderr, "error setting signal handler for %d (%s)\n", - SIGSEGV, - strsignal(SIGSEGV)); + if (sigaction(SIGSEGV, &sigact, (struct sigaction*)nullptr) != 0 || + sigaction(SIGFPE, &sigact, (struct sigaction*)nullptr) != 0 || + sigaction(SIGABRT, &sigact, (struct sigaction*)nullptr) != 0 || + sigaction(SIGILL, &sigact, (struct sigaction*)nullptr) != 0) { + fprintf(stderr, "error setting signal handler for %d (%s)\n", + SIGSEGV, + strsignal(SIGSEGV)); - exit(EXIT_FAILURE); - } + exit(EXIT_FAILURE); + } - std::set_terminate(OnTerminate); + std::set_terminate(OnTerminate); } #endif void Diagnostics::Initialize() { #ifdef _WIN32 - SetUnhandledExceptionFilter(unhandled_handler); + SetUnhandledExceptionFilter(unhandled_handler); #elif defined(__linux__) //&& !defined(__clang__) - MakeBacktrace(); + MakeBacktrace(); #else - fprintf(stderr, "Diagnostics not supported on this platform.\n"); + fprintf(stderr, "Diagnostics not supported on this platform.\n"); #endif } @@ -224,33 +224,33 @@ std::string Diagnostics::m_OutDirectory{}; bool Diagnostics::m_ProduceMemoryDump{}; void Diagnostics::SetProcessName(const std::string& name) { - m_ProcessName = name; + m_ProcessName = name; } void Diagnostics::SetProcessFileName(const std::string& name) { - m_ProcessFileName = name; + m_ProcessFileName = name; } void Diagnostics::SetOutDirectory(const std::string& path) { - m_OutDirectory = path; + m_OutDirectory = path; } void Diagnostics::SetProduceMemoryDump(bool value) { - m_ProduceMemoryDump = value; + m_ProduceMemoryDump = value; } const std::string& Diagnostics::GetProcessName() { - return m_ProcessName; + return m_ProcessName; } const std::string& Diagnostics::GetProcessFileName() { - return m_ProcessFileName; + return m_ProcessFileName; } const std::string& Diagnostics::GetOutDirectory() { - return m_OutDirectory; + return m_OutDirectory; } bool Diagnostics::GetProduceMemoryDump() { - return m_ProduceMemoryDump; + return m_ProduceMemoryDump; } diff --git a/dCommon/Diagnostics.h b/dCommon/Diagnostics.h index 41b7d177..fb6cc1a0 100644 --- a/dCommon/Diagnostics.h +++ b/dCommon/Diagnostics.h @@ -5,27 +5,27 @@ class Diagnostics { public: - static void Initialize(); + static void Initialize(); - static void SetProcessName(const std::string& name); + static void SetProcessName(const std::string& name); - static void SetProcessFileName(const std::string& name); + static void SetProcessFileName(const std::string& name); - static void SetOutDirectory(const std::string& path); + static void SetOutDirectory(const std::string& path); - static void SetProduceMemoryDump(bool value); + static void SetProduceMemoryDump(bool value); - static const std::string& GetProcessName(); + static const std::string& GetProcessName(); - static const std::string& GetProcessFileName(); + static const std::string& GetProcessFileName(); - static const std::string& GetOutDirectory(); + static const std::string& GetOutDirectory(); - static bool GetProduceMemoryDump(); + static bool GetProduceMemoryDump(); private: - static std::string m_ProcessName; - static std::string m_ProcessFileName; - static std::string m_OutDirectory; - static bool m_ProduceMemoryDump; + static std::string m_ProcessName; + static std::string m_ProcessFileName; + static std::string m_OutDirectory; + static bool m_ProduceMemoryDump; }; diff --git a/dCommon/Game.h b/dCommon/Game.h index 912baeb7..f4862602 100644 --- a/dCommon/Game.h +++ b/dCommon/Game.h @@ -23,4 +23,4 @@ namespace Game { extern std::mt19937 randomEngine; extern RakPeerInterface* chatServer; extern SystemAddress chatSysAddr; -} \ No newline at end of file +} diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index eafa6a3b..4a6c4739 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -7,272 +7,265 @@ template inline size_t MinSize(size_t size, const std::basic_string_view& string) { - if (size == size_t(-1) || size > string.size()) { - return string.size(); - } else { - return size; - } + if (size == size_t(-1) || size > string.size()) { + return string.size(); + } else { + return size; + } } inline bool IsLeadSurrogate(char16_t c) { - return (0xD800 <= c) && (c <= 0xDBFF); + return (0xD800 <= c) && (c <= 0xDBFF); } inline bool IsTrailSurrogate(char16_t c) { - return (0xDC00 <= c) && (c <= 0xDFFF); + return (0xDC00 <= c) && (c <= 0xDFFF); } inline void PushUTF8CodePoint(std::string& ret, char32_t cp) { - if (cp <= 0x007F) { - ret.push_back(static_cast(cp)); - } else if (cp <= 0x07FF) { - ret.push_back(0xC0 | (cp >> 6)); - ret.push_back(0x80 | (cp & 0x3F)); - } else if (cp <= 0xFFFF) { - ret.push_back(0xE0 | (cp >> 12)); - ret.push_back(0x80 | ((cp >> 6) & 0x3F)); - ret.push_back(0x80 | (cp & 0x3F)); - } else if (cp <= 0x10FFFF) { - ret.push_back(0xF0 | (cp >> 18)); - ret.push_back(0x80 | ((cp >> 12) & 0x3F)); - ret.push_back(0x80 | ((cp >> 6) & 0x3F)); - ret.push_back(0x80 | (cp & 0x3F)); - } else { - assert(false); - } + if (cp <= 0x007F) { + ret.push_back(static_cast(cp)); + } else if (cp <= 0x07FF) { + ret.push_back(0xC0 | (cp >> 6)); + ret.push_back(0x80 | (cp & 0x3F)); + } else if (cp <= 0xFFFF) { + ret.push_back(0xE0 | (cp >> 12)); + ret.push_back(0x80 | ((cp >> 6) & 0x3F)); + ret.push_back(0x80 | (cp & 0x3F)); + } else if (cp <= 0x10FFFF) { + ret.push_back(0xF0 | (cp >> 18)); + ret.push_back(0x80 | ((cp >> 12) & 0x3F)); + ret.push_back(0x80 | ((cp >> 6) & 0x3F)); + ret.push_back(0x80 | (cp & 0x3F)); + } else { + assert(false); + } } constexpr const char16_t REPLACEMENT_CHARACTER = 0xFFFD; bool _IsSuffixChar(uint8_t c) { - return (c & 0xC0) == 0x80; + return (c & 0xC0) == 0x80; } bool GeneralUtils::_NextUTF8Char(std::string_view& slice, uint32_t& out) { - size_t rem = slice.length(); - const uint8_t* bytes = (const uint8_t*) &slice.front(); - if (rem > 0) { - uint8_t first = bytes[0]; - if (first < 0x80) { // 1 byte character - out = static_cast(first & 0x7F); - slice.remove_prefix(1); - return true; - } else if (first < 0xC0) { - // middle byte, not valid at start, fall through - } else if (first < 0xE0) { // two byte character - if (rem > 1) { - uint8_t second = bytes[1]; - if (_IsSuffixChar(second)) { - out = (static_cast(first & 0x1F) << 6) - + static_cast(second & 0x3F); - slice.remove_prefix(2); - return true; - } - } - } else if (first < 0xF0) { // three byte character - if (rem > 2) { - uint8_t second = bytes[1]; - uint8_t third = bytes[2]; - if (_IsSuffixChar(second) && _IsSuffixChar(third)) { - out = (static_cast(first & 0x0F) << 12) - + (static_cast(second & 0x3F) << 6) - + static_cast(third & 0x3F); - slice.remove_prefix(3); - return true; - } - } - } else if (first < 0xF8) { // four byte character - if (rem > 3) { - uint8_t second = bytes[1]; - uint8_t third = bytes[2]; - uint8_t fourth = bytes[3]; - if (_IsSuffixChar(second) && _IsSuffixChar(third) && _IsSuffixChar(fourth)) { - out = (static_cast(first & 0x07) << 18) - + (static_cast(second & 0x3F) << 12) - + (static_cast(third & 0x3F) << 6) - + static_cast(fourth & 0x3F); - slice.remove_prefix(4); - return true; - } - } - } - out = static_cast(REPLACEMENT_CHARACTER); - slice.remove_prefix(1); - return true; - } - return false; + size_t rem = slice.length(); + const uint8_t* bytes = (const uint8_t*)&slice.front(); + if (rem > 0) { + uint8_t first = bytes[0]; + if (first < 0x80) { // 1 byte character + out = static_cast(first & 0x7F); + slice.remove_prefix(1); + return true; + } else if (first < 0xC0) { + // middle byte, not valid at start, fall through + } else if (first < 0xE0) { // two byte character + if (rem > 1) { + uint8_t second = bytes[1]; + if (_IsSuffixChar(second)) { + out = (static_cast(first & 0x1F) << 6) + + static_cast(second & 0x3F); + slice.remove_prefix(2); + return true; + } + } + } else if (first < 0xF0) { // three byte character + if (rem > 2) { + uint8_t second = bytes[1]; + uint8_t third = bytes[2]; + if (_IsSuffixChar(second) && _IsSuffixChar(third)) { + out = (static_cast(first & 0x0F) << 12) + + (static_cast(second & 0x3F) << 6) + + static_cast(third & 0x3F); + slice.remove_prefix(3); + return true; + } + } + } else if (first < 0xF8) { // four byte character + if (rem > 3) { + uint8_t second = bytes[1]; + uint8_t third = bytes[2]; + uint8_t fourth = bytes[3]; + if (_IsSuffixChar(second) && _IsSuffixChar(third) && _IsSuffixChar(fourth)) { + out = (static_cast(first & 0x07) << 18) + + (static_cast(second & 0x3F) << 12) + + (static_cast(third & 0x3F) << 6) + + static_cast(fourth & 0x3F); + slice.remove_prefix(4); + return true; + } + } + } + out = static_cast(REPLACEMENT_CHARACTER); + slice.remove_prefix(1); + return true; + } + return false; } /// See bool PushUTF16CodePoint(std::u16string& output, uint32_t U, size_t size) { - if (output.length() >= size) return false; - if (U < 0x10000) { - // If U < 0x10000, encode U as a 16-bit unsigned integer and terminate. - output.push_back(static_cast(U)); - return true; - } else if (U > 0x10FFFF) { - output.push_back(REPLACEMENT_CHARACTER); - return true; - } else if (output.length() + 1 < size) { - // Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF, - // U' must be less than or equal to 0xFFFFF. That is, U' can be - // represented in 20 bits. - uint32_t Ut = U - 0x10000; + if (output.length() >= size) return false; + if (U < 0x10000) { + // If U < 0x10000, encode U as a 16-bit unsigned integer and terminate. + output.push_back(static_cast(U)); + return true; + } else if (U > 0x10FFFF) { + output.push_back(REPLACEMENT_CHARACTER); + return true; + } else if (output.length() + 1 < size) { + // Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF, + // U' must be less than or equal to 0xFFFFF. That is, U' can be + // represented in 20 bits. + uint32_t Ut = U - 0x10000; - // Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and - // 0xDC00, respectively. These integers each have 10 bits free to - // encode the character value, for a total of 20 bits. - uint16_t W1 = 0xD800; - uint16_t W2 = 0xDC00; + // Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and + // 0xDC00, respectively. These integers each have 10 bits free to + // encode the character value, for a total of 20 bits. + uint16_t W1 = 0xD800; + uint16_t W2 = 0xDC00; - // Assign the 10 high-order bits of the 20-bit U' to the 10 low-order - // bits of W1 and the 10 low-order bits of U' to the 10 low-order - // bits of W2. - W1 += static_cast((Ut & 0x3FC00) >> 10); - W2 += static_cast((Ut & 0x3FF) >> 0); + // Assign the 10 high-order bits of the 20-bit U' to the 10 low-order + // bits of W1 and the 10 low-order bits of U' to the 10 low-order + // bits of W2. + W1 += static_cast((Ut & 0x3FC00) >> 10); + W2 += static_cast((Ut & 0x3FF) >> 0); - // Terminate. - output.push_back(W1); // high surrogate - output.push_back(W2); // low surrogate - return true; - } else return false; + // Terminate. + output.push_back(W1); // high surrogate + output.push_back(W2); // low surrogate + return true; + } else return false; } std::u16string GeneralUtils::UTF8ToUTF16(const std::string_view& string, size_t size) { - size_t newSize = MinSize(size, string); - std::u16string output; - output.reserve(newSize); - std::string_view iterator = string; + size_t newSize = MinSize(size, string); + std::u16string output; + output.reserve(newSize); + std::string_view iterator = string; - uint32_t c; - while (_NextUTF8Char(iterator, c) && PushUTF16CodePoint(output, c, size)) {} - return output; + uint32_t c; + while (_NextUTF8Char(iterator, c) && PushUTF16CodePoint(output, c, size)) {} + return output; } //! Converts an std::string (ASCII) to UCS-2 / UTF-16 std::u16string GeneralUtils::ASCIIToUTF16(const std::string_view& string, size_t size) { - size_t newSize = MinSize(size, string); - std::u16string ret; - ret.reserve(newSize); + size_t newSize = MinSize(size, string); + std::u16string ret; + ret.reserve(newSize); - for (size_t i = 0; i < newSize; i++) { - char c = string[i]; - // Note: both 7-bit ascii characters and REPLACEMENT_CHARACTER fit in one char16_t - ret.push_back((c > 0 && c <= 127) ? static_cast(c) : REPLACEMENT_CHARACTER); - } + for (size_t i = 0; i < newSize; i++) { + char c = string[i]; + // Note: both 7-bit ascii characters and REPLACEMENT_CHARACTER fit in one char16_t + ret.push_back((c > 0 && c <= 127) ? static_cast(c) : REPLACEMENT_CHARACTER); + } - return ret; + return ret; } //! Converts a (potentially-ill-formed) UTF-16 string to UTF-8 //! See: std::string GeneralUtils::UTF16ToWTF8(const std::u16string_view& string, size_t size) { - size_t newSize = MinSize(size, string); - std::string ret; - ret.reserve(newSize); + size_t newSize = MinSize(size, string); + std::string ret; + ret.reserve(newSize); - for (size_t i = 0; i < newSize; i++) { - char16_t u = string[i]; - if (IsLeadSurrogate(u) && (i + 1) < newSize) { - char16_t next = string[i + 1]; - if (IsTrailSurrogate(next)) { - i += 1; - char32_t cp = 0x10000 - + ((static_cast(u) - 0xD800) << 10) - + (static_cast(next) - 0xDC00); - PushUTF8CodePoint(ret, cp); - } else { - PushUTF8CodePoint(ret, u); - } - } else { - PushUTF8CodePoint(ret, u); - } - } + for (size_t i = 0; i < newSize; i++) { + char16_t u = string[i]; + if (IsLeadSurrogate(u) && (i + 1) < newSize) { + char16_t next = string[i + 1]; + if (IsTrailSurrogate(next)) { + i += 1; + char32_t cp = 0x10000 + + ((static_cast(u) - 0xD800) << 10) + + (static_cast(next) - 0xDC00); + PushUTF8CodePoint(ret, cp); + } else { + PushUTF8CodePoint(ret, u); + } + } else { + PushUTF8CodePoint(ret, u); + } + } - return ret; + return ret; } bool GeneralUtils::CaseInsensitiveStringCompare(const std::string& a, const std::string& b) { - return std::equal(a.begin(), a.end (), b.begin(), b.end(),[](char a, char b) { return tolower(a) == tolower(b); }); + return std::equal(a.begin(), a.end(), b.begin(), b.end(), [](char a, char b) { return tolower(a) == tolower(b); }); } // MARK: Bits //! Sets a specific bit in a signed 64-bit integer int64_t GeneralUtils::SetBit(int64_t value, uint32_t index) { - return value |= 1ULL << index; + return value |= 1ULL << index; } //! Clears a specific bit in a signed 64-bit integer int64_t GeneralUtils::ClearBit(int64_t value, uint32_t index) { - return value &= ~(1ULL << index); + return value &= ~(1ULL << index); } //! Checks a specific bit in a signed 64-bit integer bool GeneralUtils::CheckBit(int64_t value, uint32_t index) { - return value & (1ULL << index); + return value & (1ULL << index); } bool GeneralUtils::ReplaceInString(std::string& str, const std::string& from, const std::string& to) { - size_t start_pos = str.find(from); - if(start_pos == std::string::npos) - return false; - str.replace(start_pos, from.length(), to); - return true; + size_t start_pos = str.find(from); + if (start_pos == std::string::npos) + return false; + str.replace(start_pos, from.length(), to); + return true; } -std::vector GeneralUtils::SplitString(std::wstring& str, wchar_t delimiter) -{ - std::vector vector = std::vector(); - std::wstring current; +std::vector GeneralUtils::SplitString(std::wstring& str, wchar_t delimiter) { + std::vector vector = std::vector(); + std::wstring current; - for (const auto& c : str) { - if (c == delimiter) { - vector.push_back(current); - current = L""; - } else { - current += c; - } - } + for (const auto& c : str) { + if (c == delimiter) { + vector.push_back(current); + current = L""; + } else { + current += c; + } + } - vector.push_back(current); - return vector; + vector.push_back(current); + return vector; } -std::vector GeneralUtils::SplitString(std::u16string& str, char16_t delimiter) -{ - std::vector vector = std::vector(); - std::u16string current; +std::vector GeneralUtils::SplitString(std::u16string& str, char16_t delimiter) { + std::vector vector = std::vector(); + std::u16string current; - for (const auto& c : str) { - if (c == delimiter) { - vector.push_back(current); - current = u""; - } else { - current += c; - } - } + for (const auto& c : str) { + if (c == delimiter) { + vector.push_back(current); + current = u""; + } else { + current += c; + } + } - vector.push_back(current); - return vector; + vector.push_back(current); + return vector; } -std::vector GeneralUtils::SplitString(const std::string& str, char delimiter) -{ +std::vector GeneralUtils::SplitString(const std::string& str, char delimiter) { std::vector vector = std::vector(); std::string current = ""; - for (size_t i = 0; i < str.length(); i++) - { + for (size_t i = 0; i < str.length(); i++) { char c = str[i]; - if (c == delimiter) - { + if (c == delimiter) { vector.push_back(current); current = ""; - } - else - { + } else { current += c; } } @@ -282,39 +275,38 @@ std::vector GeneralUtils::SplitString(const std::string& str, char return vector; } -std::u16string GeneralUtils::ReadWString(RakNet::BitStream *inStream) { - uint32_t length; - inStream->Read(length); +std::u16string GeneralUtils::ReadWString(RakNet::BitStream* inStream) { + uint32_t length; + inStream->Read(length); - std::u16string string; - for (auto i = 0; i < length; i++) { - uint16_t c; - inStream->Read(c); - string.push_back(c); - } + std::u16string string; + for (auto i = 0; i < length; i++) { + uint16_t c; + inStream->Read(c); + string.push_back(c); + } - return string; + return string; } #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include -std::vector GeneralUtils::GetFileNamesFromFolder(const std::string& folder) -{ - std::vector names; - std::string search_path = folder + "/*.*"; - WIN32_FIND_DATA fd; - HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd); - if (hFind != INVALID_HANDLE_VALUE) { - do { - if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { - names.push_back(fd.cFileName); - } - } while (::FindNextFile(hFind, &fd)); - ::FindClose(hFind); - } - return names; +std::vector GeneralUtils::GetFileNamesFromFolder(const std::string& folder) { + std::vector names; + std::string search_path = folder + "/*.*"; + WIN32_FIND_DATA fd; + HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd); + if (hFind != INVALID_HANDLE_VALUE) { + do { + if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { + names.push_back(fd.cFileName); + } + } while (::FindNextFile(hFind, &fd)); + ::FindClose(hFind); + } + return names; } #else #include @@ -325,23 +317,23 @@ std::vector GeneralUtils::GetFileNamesFromFolder(const std::string& #include std::vector GeneralUtils::GetFileNamesFromFolder(const std::string& folder) { - std::vector names; - struct dirent* entry; - DIR* dir = opendir(folder.c_str()); - if (dir == NULL) { - return names; - } + std::vector names; + struct dirent* entry; + DIR* dir = opendir(folder.c_str()); + if (dir == NULL) { + return names; + } - while ((entry = readdir(dir)) != NULL) { - std::string value(entry->d_name, strlen(entry->d_name)); - if (value == "." || value == "..") { - continue; - } - names.push_back(value); - } + while ((entry = readdir(dir)) != NULL) { + std::string value(entry->d_name, strlen(entry->d_name)); + if (value == "." || value == "..") { + continue; + } + names.push_back(value); + } - closedir(dir); + closedir(dir); - return names; + return names; } -#endif \ No newline at end of file +#endif diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index f796839c..898616d2 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -18,120 +18,119 @@ \brief A namespace containing general utility functions */ -//! The general utils namespace + //! The general utils namespace namespace GeneralUtils { - //! Converts a plain ASCII string to a UTF-16 string - /*! - \param string The string to convert - \param size A size to trim the string to. Default is -1 (No trimming) - \return An UTF-16 representation of the string - */ - std::u16string ASCIIToUTF16(const std::string_view& string, size_t size = -1); + //! Converts a plain ASCII string to a UTF-16 string + /*! + \param string The string to convert + \param size A size to trim the string to. Default is -1 (No trimming) + \return An UTF-16 representation of the string + */ + std::u16string ASCIIToUTF16(const std::string_view& string, size_t size = -1); - //! Converts a UTF-8 String to a UTF-16 string - /*! - \param string The string to convert - \param size A size to trim the string to. Default is -1 (No trimming) - \return An UTF-16 representation of the string - */ - std::u16string UTF8ToUTF16(const std::string_view& string, size_t size = -1); + //! Converts a UTF-8 String to a UTF-16 string + /*! + \param string The string to convert + \param size A size to trim the string to. Default is -1 (No trimming) + \return An UTF-16 representation of the string + */ + std::u16string UTF8ToUTF16(const std::string_view& string, size_t size = -1); - //! Internal, do not use - bool _NextUTF8Char(std::string_view& slice, uint32_t& out); + //! Internal, do not use + bool _NextUTF8Char(std::string_view& slice, uint32_t& out); - //! Converts a UTF-16 string to a UTF-8 string - /*! - \param string The string to convert - \param size A size to trim the string to. Default is -1 (No trimming) - \return An UTF-8 representation of the string - */ - std::string UTF16ToWTF8(const std::u16string_view& string, size_t size = -1); + //! Converts a UTF-16 string to a UTF-8 string + /*! + \param string The string to convert + \param size A size to trim the string to. Default is -1 (No trimming) + \return An UTF-8 representation of the string + */ + std::string UTF16ToWTF8(const std::u16string_view& string, size_t size = -1); - /** - * Compares two basic strings but does so ignoring case sensitivity - * \param a the first string to compare against the second string - * \param b the second string to compare against the first string - * @return if the two strings are equal - */ - bool CaseInsensitiveStringCompare(const std::string& a, const std::string& b); + /** + * Compares two basic strings but does so ignoring case sensitivity + * \param a the first string to compare against the second string + * \param b the second string to compare against the first string + * @return if the two strings are equal + */ + bool CaseInsensitiveStringCompare(const std::string& a, const std::string& b); - // MARK: Bits + // MARK: Bits - // MARK: Bits + // MARK: Bits - //! Sets a bit on a numerical value - template - void SetBit(T& value, size_t index) { - static_assert(std::is_arithmetic::value, "Not an arithmetic type"); - - if (index > (sizeof(T) * 8) - 1) { - return; - } - - value |= static_cast(1) << index; - } - - //! Clears a bit on a numerical value - template - void ClearBit(T& value, size_t index) { - static_assert(std::is_arithmetic::value, "Not an arithmetic type"); - - if (index > (sizeof(T) * 8 - 1)) { - return; - } - - value &= ~(static_cast(1) << index); - } - - //! Sets a specific bit in a signed 64-bit integer - /*! - \param value The value to set the bit for - \param index The index of the bit - */ - int64_t SetBit(int64_t value, uint32_t index); - - //! Clears a specific bit in a signed 64-bit integer - /*! - \param value The value to clear the bit from - \param index The index of the bit - */ - int64_t ClearBit(int64_t value, uint32_t index); - - //! Checks a specific bit in a signed 64-bit integer - /*! - \parma value The value to check the bit in - \param index The index of the bit - \return Whether or not the bit is set - */ - bool CheckBit(int64_t value, uint32_t index); + //! Sets a bit on a numerical value + template + void SetBit(T& value, size_t index) { + static_assert(std::is_arithmetic::value, "Not an arithmetic type"); - // MARK: Random Number Generation + if (index > (sizeof(T) * 8) - 1) { + return; + } - //! Generates a random number - /*! - \param min The minimum the generate from - \param max The maximum to generate to - */ - template - inline T GenerateRandomNumber(std::size_t min, std::size_t max) { - // Make sure it is a numeric type - static_assert(std::is_arithmetic::value, "Not an arithmetic type"); + value |= static_cast(1) << index; + } - if constexpr (std::is_integral_v) { // constexpr only necessary on first statement - std::uniform_int_distribution distribution(min, max); - return distribution(Game::randomEngine); - } - else if (std::is_floating_point_v) { - std::uniform_real_distribution distribution(min, max); - return distribution(Game::randomEngine); - } + //! Clears a bit on a numerical value + template + void ClearBit(T& value, size_t index) { + static_assert(std::is_arithmetic::value, "Not an arithmetic type"); + + if (index > (sizeof(T) * 8 - 1)) { + return; + } + + value &= ~(static_cast(1) << index); + } + + //! Sets a specific bit in a signed 64-bit integer + /*! + \param value The value to set the bit for + \param index The index of the bit + */ + int64_t SetBit(int64_t value, uint32_t index); + + //! Clears a specific bit in a signed 64-bit integer + /*! + \param value The value to clear the bit from + \param index The index of the bit + */ + int64_t ClearBit(int64_t value, uint32_t index); + + //! Checks a specific bit in a signed 64-bit integer + /*! + \parma value The value to check the bit in + \param index The index of the bit + \return Whether or not the bit is set + */ + bool CheckBit(int64_t value, uint32_t index); + + // MARK: Random Number Generation + + //! Generates a random number + /*! + \param min The minimum the generate from + \param max The maximum to generate to + */ + template + inline T GenerateRandomNumber(std::size_t min, std::size_t max) { + // Make sure it is a numeric type + static_assert(std::is_arithmetic::value, "Not an arithmetic type"); + + if constexpr (std::is_integral_v) { // constexpr only necessary on first statement + std::uniform_int_distribution distribution(min, max); + return distribution(Game::randomEngine); + } else if (std::is_floating_point_v) { + std::uniform_real_distribution distribution(min, max); + return distribution(Game::randomEngine); + } + + return T(); + } - return T(); - } - bool ReplaceInString(std::string& str, const std::string& from, const std::string& to); - std::u16string ReadWString(RakNet::BitStream *inStream); + std::u16string ReadWString(RakNet::BitStream* inStream); std::vector SplitString(std::wstring& str, wchar_t delimiter); @@ -139,85 +138,71 @@ namespace GeneralUtils { std::vector SplitString(const std::string& str, char delimiter); - std::vector GetFileNamesFromFolder(const std::string& folder); + std::vector GetFileNamesFromFolder(const std::string& folder); - template - T Parse(const char* value); + template + T Parse(const char* value); template <> - inline int32_t Parse(const char* value) - { - return std::stoi(value); + 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 int64_t Parse(const char* value) { + return std::stoll(value); + } - template <> - inline float Parse(const char* value) - { - return std::stof(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 uint32_t Parse(const char* value) - { - return std::stoul(value); - } + template <> + inline double Parse(const char* value) { + return std::stod(value); + } - template <> - inline uint64_t Parse(const char* value) - { - return std::stoull(value); - } - - template - bool TryParse(const char* value, T& dst) - { - try - { - dst = Parse(value); + template <> + inline uint32_t Parse(const char* value) { + return std::stoul(value); + } - return true; - } - catch (...) - { - return false; - } - } + template <> + inline uint64_t Parse(const char* value) { + return std::stoull(value); + } - template - T Parse(const std::string& value) - { - return Parse(value.c_str()); - } + template + bool TryParse(const char* value, T& dst) { + try { + dst = Parse(value); - template - bool TryParse(const std::string& value, T& dst) - { - return TryParse(value.c_str(), dst); - } + return true; + } catch (...) { + return false; + } + } - template - std::u16string to_u16string(T value) - { - return GeneralUtils::ASCIIToUTF16(std::to_string(value)); - } + template + T Parse(const std::string& value) { + return Parse(value.c_str()); + } - // From boost::hash_combine - template - void hash_combine(std::size_t& s, const T& v) - { - std::hash h; - s ^= h(v) + 0x9e3779b9 + (s << 6) + (s >> 2); - } + template + bool TryParse(const std::string& value, T& dst) { + return TryParse(value.c_str(), 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) { + std::hash h; + s ^= h(v) + 0x9e3779b9 + (s << 6) + (s >> 2); + } } diff --git a/dCommon/LDFFormat.cpp b/dCommon/LDFFormat.cpp index 8290faec..b6ea21a4 100644 --- a/dCommon/LDFFormat.cpp +++ b/dCommon/LDFFormat.cpp @@ -8,25 +8,25 @@ #include //! Returns a pointer to a LDFData value based on string format -LDFBaseData * LDFBaseData::DataFromString(const std::string& format) { - - // First, check the format - std::istringstream ssFormat(format); - std::string token; - - std::vector keyValueArray; - while (std::getline(ssFormat, token, '=')) { - keyValueArray.push_back(token); - } - - if (keyValueArray.size() == 2) { - std::u16string key = GeneralUtils::ASCIIToUTF16(keyValueArray[0]); - - std::vector dataArray; - std::istringstream ssData(keyValueArray[1]); - while (std::getline(ssData, token, ':')) { - dataArray.push_back(token); - } +LDFBaseData* LDFBaseData::DataFromString(const std::string& format) { + + // First, check the format + std::istringstream ssFormat(format); + std::string token; + + std::vector keyValueArray; + while (std::getline(ssFormat, token, '=')) { + keyValueArray.push_back(token); + } + + if (keyValueArray.size() == 2) { + std::u16string key = GeneralUtils::ASCIIToUTF16(keyValueArray[0]); + + std::vector dataArray; + std::istringstream ssData(keyValueArray[1]); + while (std::getline(ssData, token, ':')) { + dataArray.push_back(token); + } if (dataArray.size() > 2) { // hacky fix for strings with colons in them std::vector newDataArray; @@ -39,96 +39,86 @@ LDFBaseData * LDFBaseData::DataFromString(const std::string& format) { newDataArray.push_back(value); dataArray = newDataArray; } - - if ((dataArray[0] == "0" || dataArray[0] == "13") && dataArray.size() == 1) { - dataArray.push_back(""); - } - - if (dataArray.size() == 2) { - eLDFType type = static_cast(stoi(dataArray[0])); - - switch (type) { - case LDF_TYPE_UTF_16: { - std::u16string data = GeneralUtils::ASCIIToUTF16(dataArray[1]); - return new LDFData(key, data); - } - - case LDF_TYPE_S32: { - int32_t data = static_cast(stoull(dataArray[1])); - return new LDFData(key, data); - } - - case LDF_TYPE_FLOAT: { - float data = static_cast(stof(dataArray[1])); - return new LDFData(key, data); - } - - case LDF_TYPE_DOUBLE: { - double data = static_cast(stod(dataArray[1])); - return new LDFData(key, data); - } - - case LDF_TYPE_U32: - { - uint32_t data; - - if (dataArray[1] == "true") - { - data = 1; - } - else if (dataArray[1] == "false") - { - data = 0; - } - else - { - data = static_cast(stoul(dataArray[1])); - } - - return new LDFData(key, data); - } - - case LDF_TYPE_BOOLEAN: { - bool data; - - if (dataArray[1] == "true") - { - data = true; - } - else if (dataArray[1] == "false") - { - data = false; - } - else - { - data = static_cast(stoi(dataArray[1])); - } - - return new LDFData(key, data); - } - - case LDF_TYPE_U64: { - uint64_t data = static_cast(stoull(dataArray[1])); - return new LDFData(key, data); - } - - case LDF_TYPE_OBJID: { - LWOOBJID data = static_cast(stoll(dataArray[1])); - return new LDFData(key, data); - } - - case LDF_TYPE_UTF_8: { - std::string data = dataArray[1]; - return new LDFData(key, data); - } - - case LDF_TYPE_UNKNOWN: { - return nullptr; - } - } - } - } - - return nullptr; - + + if ((dataArray[0] == "0" || dataArray[0] == "13") && dataArray.size() == 1) { + dataArray.push_back(""); + } + + if (dataArray.size() == 2) { + eLDFType type = static_cast(stoi(dataArray[0])); + + switch (type) { + case LDF_TYPE_UTF_16: { + std::u16string data = GeneralUtils::ASCIIToUTF16(dataArray[1]); + return new LDFData(key, data); + } + + case LDF_TYPE_S32: { + int32_t data = static_cast(stoull(dataArray[1])); + return new LDFData(key, data); + } + + case LDF_TYPE_FLOAT: { + float data = static_cast(stof(dataArray[1])); + return new LDFData(key, data); + } + + case LDF_TYPE_DOUBLE: { + double data = static_cast(stod(dataArray[1])); + return new LDFData(key, data); + } + + case LDF_TYPE_U32: + { + uint32_t data; + + if (dataArray[1] == "true") { + data = 1; + } else if (dataArray[1] == "false") { + data = 0; + } else { + data = static_cast(stoul(dataArray[1])); + } + + return new LDFData(key, data); + } + + case LDF_TYPE_BOOLEAN: { + bool data; + + if (dataArray[1] == "true") { + data = true; + } else if (dataArray[1] == "false") { + data = false; + } else { + data = static_cast(stoi(dataArray[1])); + } + + return new LDFData(key, data); + } + + case LDF_TYPE_U64: { + uint64_t data = static_cast(stoull(dataArray[1])); + return new LDFData(key, data); + } + + case LDF_TYPE_OBJID: { + LWOOBJID data = static_cast(stoll(dataArray[1])); + return new LDFData(key, data); + } + + case LDF_TYPE_UTF_8: { + std::string data = dataArray[1]; + return new LDFData(key, data); + } + + case LDF_TYPE_UNKNOWN: { + return nullptr; + } + } + } + } + + return nullptr; + } diff --git a/dCommon/LDFFormat.h b/dCommon/LDFFormat.h index 0a8a99f3..9b62efa7 100644 --- a/dCommon/LDFFormat.h +++ b/dCommon/LDFFormat.h @@ -17,64 +17,64 @@ \brief A collection of LDF format classes */ -//! An enum for LDF Data Types + //! An enum for LDF Data Types enum eLDFType { - LDF_TYPE_UNKNOWN = -1, //!< Unknown data type - LDF_TYPE_UTF_16 = 0, //!< UTF-16 wstring data type - LDF_TYPE_S32 = 1, //!< Signed 32-bit data type - LDF_TYPE_FLOAT = 3, //!< Float data type - LDF_TYPE_DOUBLE = 4, //!< Double data type - LDF_TYPE_U32 = 5, //!< Unsigned 32-bit data type - LDF_TYPE_BOOLEAN = 7, //!< Boolean data type - LDF_TYPE_U64 = 8, //!< Unsigned 64-bit data type (originally signed, templates won't work with both S64 & OBJID - LDF_TYPE_OBJID = 9, //!< Signed 64-bit data type (reserved for object IDs) - LDF_TYPE_UTF_8 = 13, //!< UTF-8 string data type + LDF_TYPE_UNKNOWN = -1, //!< Unknown data type + LDF_TYPE_UTF_16 = 0, //!< UTF-16 wstring data type + LDF_TYPE_S32 = 1, //!< Signed 32-bit data type + LDF_TYPE_FLOAT = 3, //!< Float data type + LDF_TYPE_DOUBLE = 4, //!< Double data type + LDF_TYPE_U32 = 5, //!< Unsigned 32-bit data type + LDF_TYPE_BOOLEAN = 7, //!< Boolean data type + LDF_TYPE_U64 = 8, //!< Unsigned 64-bit data type (originally signed, templates won't work with both S64 & OBJID + LDF_TYPE_OBJID = 9, //!< Signed 64-bit data type (reserved for object IDs) + LDF_TYPE_UTF_8 = 13, //!< UTF-8 string data type }; //! A base class for the LDF data class LDFBaseData { public: - - //! Destructor - virtual ~LDFBaseData(void) { } - - //! Writes the data to a packet - /*! - \param packet The packet - */ - virtual void WriteToPacket(RakNet::BitStream * packet) = 0; - - //! Gets the key - /*! - \return The key - */ - virtual const std::u16string& GetKey(void) = 0; - - //! Gets the value type - /*! - \return The value type - */ - virtual eLDFType GetValueType(void) = 0; - - //! Gets a string from the key/value pair - /*! - \param includeKey Whether or not to include the key in the data - \param includeTypeId Whether or not to include the type id in the data - \return The string representation of the data - */ - virtual std::string GetString(bool includeKey = true, bool includeTypeId = true) = 0; - - virtual std::string GetValueAsString() = 0; - virtual LDFBaseData * Copy() = 0; - - // MARK: Functions - - //! Returns a pointer to a LDFData value based on string format - /*! - \param format The format - */ - static LDFBaseData * DataFromString(const std::string& format); + //! Destructor + virtual ~LDFBaseData(void) {} + + //! Writes the data to a packet + /*! + \param packet The packet + */ + virtual void WriteToPacket(RakNet::BitStream* packet) = 0; + + //! Gets the key + /*! + \return The key + */ + virtual const std::u16string& GetKey(void) = 0; + + //! Gets the value type + /*! + \return The value type + */ + virtual eLDFType GetValueType(void) = 0; + + //! Gets a string from the key/value pair + /*! + \param includeKey Whether or not to include the key in the data + \param includeTypeId Whether or not to include the type id in the data + \return The string representation of the data + */ + virtual std::string GetString(bool includeKey = true, bool includeTypeId = true) = 0; + + virtual std::string GetValueAsString() = 0; + + virtual LDFBaseData* Copy() = 0; + + // MARK: Functions + + //! Returns a pointer to a LDFData value based on string format + /*! + \param format The format + */ + static LDFBaseData* DataFromString(const std::string& format); }; @@ -82,115 +82,115 @@ public: template class LDFData : public LDFBaseData { private: - std::u16string key; - T value; - - //! Writes the key to the packet - void WriteKey(RakNet::BitStream * packet) { - packet->Write(static_cast(this->key.length() * sizeof(uint16_t))); - for (uint32_t i = 0; i < this->key.length(); ++i) { - packet->Write(static_cast(this->key[i])); - } - } - - //! Writes the value to the packet - void WriteValue(RakNet::BitStream * packet) { - packet->Write(static_cast(this->GetValueType())); - packet->Write(this->value); - } + std::u16string key; + T value; + + //! Writes the key to the packet + void WriteKey(RakNet::BitStream* packet) { + packet->Write(static_cast(this->key.length() * sizeof(uint16_t))); + for (uint32_t i = 0; i < this->key.length(); ++i) { + packet->Write(static_cast(this->key[i])); + } + } + + //! Writes the value to the packet + void WriteValue(RakNet::BitStream* packet) { + packet->Write(static_cast(this->GetValueType())); + packet->Write(this->value); + } public: - - //! Initializer - LDFData(const std::u16string& key, const T& value) { - this->key = key; - this->value = value; - } - - //! Destructor - ~LDFData(void) override { } - - //! Gets the value - /*! - \return The value - */ - const T& GetValue(void) { return this->value; } - - //! Sets the value - /*! - \param value The value to set to - */ - void SetValue(T value) { this->value = value; }; - //! Gets the value string - /*! - \return The value string - */ - std::string GetValueString(void) { return ""; } - - //! Writes the data to a packet - /*! - \param packet The packet - */ - void WriteToPacket(RakNet::BitStream * packet) override { - this->WriteKey(packet); - this->WriteValue(packet); - } - - //! Gets the key - /*! - \return The key - */ - const std::u16string& GetKey(void) override { return this->key; } - - //! Gets the LDF Type - /*! - \return The LDF value type - */ - eLDFType GetValueType(void) override { return LDF_TYPE_UNKNOWN; } - - //! Gets the string data - /*! - \param includeKey Whether or not to include the key in the data - \param includeTypeId Whether or not to include the type id in the data - \return The string representation of the data - */ - std::string GetString(const bool includeKey = true, const bool includeTypeId = true) override { - if (GetValueType() == -1) { - return GeneralUtils::UTF16ToWTF8(this->key) + "=-1:"; - } + //! Initializer + LDFData(const std::u16string& key, const T& value) { + this->key = key; + this->value = value; + } - std::stringstream stream; + //! Destructor + ~LDFData(void) override {} - if (includeKey) { - const std::string& sKey = GeneralUtils::UTF16ToWTF8(this->key, this->key.size()); - - stream << sKey << "="; - } + //! Gets the value + /*! + \return The value + */ + const T& GetValue(void) { return this->value; } - if (includeTypeId) { - const std::string& sType = std::to_string(this->GetValueType()); + //! Sets the value + /*! + \param value The value to set to + */ + void SetValue(T value) { this->value = value; }; - - stream << sType << ":"; - } + //! Gets the value string + /*! + \return The value string + */ + std::string GetValueString(void) { return ""; } - const std::string& sData = this->GetValueString(); - - stream << sData; + //! Writes the data to a packet + /*! + \param packet The packet + */ + void WriteToPacket(RakNet::BitStream* packet) override { + this->WriteKey(packet); + this->WriteValue(packet); + } - return stream.str(); - } - - std::string GetValueAsString() override { - return this->GetValueString(); - } - - LDFBaseData * Copy() override { - return new LDFData(key, value); - } - - inline static T Default = {}; + //! Gets the key + /*! + \return The key + */ + const std::u16string& GetKey(void) override { return this->key; } + + //! Gets the LDF Type + /*! + \return The LDF value type + */ + eLDFType GetValueType(void) override { return LDF_TYPE_UNKNOWN; } + + //! Gets the string data + /*! + \param includeKey Whether or not to include the key in the data + \param includeTypeId Whether or not to include the type id in the data + \return The string representation of the data + */ + std::string GetString(const bool includeKey = true, const bool includeTypeId = true) override { + if (GetValueType() == -1) { + return GeneralUtils::UTF16ToWTF8(this->key) + "=-1:"; + } + + std::stringstream stream; + + if (includeKey) { + const std::string& sKey = GeneralUtils::UTF16ToWTF8(this->key, this->key.size()); + + stream << sKey << "="; + } + + if (includeTypeId) { + const std::string& sType = std::to_string(this->GetValueType()); + + + stream << sType << ":"; + } + + const std::string& sData = this->GetValueString(); + + stream << sData; + + return stream.str(); + } + + std::string GetValueAsString() override { + return this->GetValueString(); + } + + LDFBaseData* Copy() override { + return new LDFData(key, value); + } + + inline static T Default = {}; }; // LDF Types @@ -206,38 +206,38 @@ template<> inline eLDFType LDFData::GetValueType(void) { return LDF // The specialized version for std::u16string (UTF-16) template<> -inline void LDFData::WriteValue(RakNet::BitStream * packet) { - packet->Write(static_cast(this->GetValueType())); - - packet->Write(static_cast(this->value.length())); - for (uint32_t i = 0; i < this->value.length(); ++i) { - packet->Write(static_cast(this->value[i])); - } +inline void LDFData::WriteValue(RakNet::BitStream* packet) { + packet->Write(static_cast(this->GetValueType())); + + packet->Write(static_cast(this->value.length())); + for (uint32_t i = 0; i < this->value.length(); ++i) { + packet->Write(static_cast(this->value[i])); + } } // The specialized version for bool template<> -inline void LDFData::WriteValue(RakNet::BitStream * packet) { - packet->Write(static_cast(this->GetValueType())); - - packet->Write(static_cast(this->value)); +inline void LDFData::WriteValue(RakNet::BitStream* packet) { + packet->Write(static_cast(this->GetValueType())); + + packet->Write(static_cast(this->value)); } // The specialized version for std::string (UTF-8) template<> -inline void LDFData::WriteValue(RakNet::BitStream * packet) { - packet->Write(static_cast(this->GetValueType())); - - packet->Write(static_cast(this->value.length())); - for (uint32_t i = 0; i < this->value.length(); ++i) { - packet->Write(static_cast(this->value[i])); - } +inline void LDFData::WriteValue(RakNet::BitStream* packet) { + packet->Write(static_cast(this->GetValueType())); + + packet->Write(static_cast(this->value.length())); + for (uint32_t i = 0; i < this->value.length(); ++i) { + packet->Write(static_cast(this->value[i])); + } } // MARK: String Data template<> inline std::string LDFData::GetValueString(void) { - //std::string toReturn(this->value.begin(), this->value.end()); - //return toReturn; + //std::string toReturn(this->value.begin(), this->value.end()); + //return toReturn; return GeneralUtils::UTF16ToWTF8(this->value, this->value.size()); } diff --git a/dCommon/MD5.cpp b/dCommon/MD5.cpp index 36c0d2cf..d02b540d 100644 --- a/dCommon/MD5.cpp +++ b/dCommon/MD5.cpp @@ -1,36 +1,36 @@ /* MD5 converted to C++ class by Frank Thilo (thilo@unix-ag.org) for bzflag (http://www.bzflag.org) - + based on: - + md5.h and md5.c reference implemantion of RFC 1321 - + Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved. - + License to copy and use this software is granted provided that it is identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing this software or this function. - + License is also granted to make and use derivative works provided that such works are identified as "derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing the derived work. - + RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided "as is" without express or implied warranty of any kind. - + These notices must be retained in any copies of any part of this documentation and/or software. - + */ -/* interface header */ + /* interface header */ #include "MD5.h" /* system implementation headers */ @@ -59,304 +59,290 @@ // F, G, H and I are basic MD5 functions. inline MD5::uint4 MD5::F(uint4 x, uint4 y, uint4 z) { - return x&y | ~x&z; + return x & y | ~x & z; } inline MD5::uint4 MD5::G(uint4 x, uint4 y, uint4 z) { - return x&z | y&~z; + return x & z | y & ~z; } inline MD5::uint4 MD5::H(uint4 x, uint4 y, uint4 z) { - return x^y^z; + return x ^ y ^ z; } inline MD5::uint4 MD5::I(uint4 x, uint4 y, uint4 z) { - return y ^ (x | ~z); + return y ^ (x | ~z); } // rotate_left rotates x left n bits. inline MD5::uint4 MD5::rotate_left(uint4 x, int n) { - return (x << n) | (x >> (32 - n)); + return (x << n) | (x >> (32 - n)); } // FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. // Rotation is separate from addition to prevent recomputation. -inline void MD5::FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + F(b, c, d) + x + ac, s) + b; +inline void MD5::FF(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { + a = rotate_left(a + F(b, c, d) + x + ac, s) + b; } -inline void MD5::GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + G(b, c, d) + x + ac, s) + b; +inline void MD5::GG(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { + a = rotate_left(a + G(b, c, d) + x + ac, s) + b; } -inline void MD5::HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + H(b, c, d) + x + ac, s) + b; +inline void MD5::HH(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { + a = rotate_left(a + H(b, c, d) + x + ac, s) + b; } -inline void MD5::II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { - a = rotate_left(a + I(b, c, d) + x + ac, s) + b; +inline void MD5::II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) { + a = rotate_left(a + I(b, c, d) + x + ac, s) + b; } ////////////////////////////////////////////// // default ctor, just initailize -MD5::MD5() -{ - init(); +MD5::MD5() { + init(); } ////////////////////////////////////////////// // nifty shortcut ctor, compute MD5 for string and finalize it right away -MD5::MD5(const std::string &text) -{ - init(); - update(text.c_str(), text.length()); - finalize(); +MD5::MD5(const std::string& text) { + init(); + update(text.c_str(), text.length()); + finalize(); } ////////////////////////////// -void MD5::init() -{ - finalized = false; - - count[0] = 0; - count[1] = 0; - - // load magic initialization constants. - state[0] = 0x67452301; - state[1] = 0xefcdab89; - state[2] = 0x98badcfe; - state[3] = 0x10325476; +void MD5::init() { + finalized = false; + + count[0] = 0; + count[1] = 0; + + // load magic initialization constants. + state[0] = 0x67452301; + state[1] = 0xefcdab89; + state[2] = 0x98badcfe; + state[3] = 0x10325476; } ////////////////////////////// // decodes input (unsigned char) into output (uint4). Assumes len is a multiple of 4. -void MD5::decode(uint4 output[], const uint1 input[], size_type len) -{ - for (unsigned int i = 0, j = 0; j < len; i++, j += 4) - output[i] = ((uint4)input[j]) | (((uint4)input[j + 1]) << 8) | - (((uint4)input[j + 2]) << 16) | (((uint4)input[j + 3]) << 24); +void MD5::decode(uint4 output[], const uint1 input[], size_type len) { + for (unsigned int i = 0, j = 0; j < len; i++, j += 4) + output[i] = ((uint4)input[j]) | (((uint4)input[j + 1]) << 8) | + (((uint4)input[j + 2]) << 16) | (((uint4)input[j + 3]) << 24); } ////////////////////////////// // encodes input (uint4) into output (unsigned char). Assumes len is // a multiple of 4. -void MD5::encode(uint1 output[], const uint4 input[], size_type len) -{ - for (size_type i = 0, j = 0; j < len; i++, j += 4) { - output[j] = input[i] & 0xff; - output[j + 1] = (input[i] >> 8) & 0xff; - output[j + 2] = (input[i] >> 16) & 0xff; - output[j + 3] = (input[i] >> 24) & 0xff; - } +void MD5::encode(uint1 output[], const uint4 input[], size_type len) { + for (size_type i = 0, j = 0; j < len; i++, j += 4) { + output[j] = input[i] & 0xff; + output[j + 1] = (input[i] >> 8) & 0xff; + output[j + 2] = (input[i] >> 16) & 0xff; + output[j + 3] = (input[i] >> 24) & 0xff; + } } ////////////////////////////// // apply MD5 algo on a block -void MD5::transform(const uint1 block[blocksize]) -{ - uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; - decode(x, block, blocksize); - - /* Round 1 */ - FF(a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */ - FF(d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */ - FF(c, d, a, b, x[2], S13, 0x242070db); /* 3 */ - FF(b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */ - FF(a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */ - FF(d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */ - FF(c, d, a, b, x[6], S13, 0xa8304613); /* 7 */ - FF(b, c, d, a, x[7], S14, 0xfd469501); /* 8 */ - FF(a, b, c, d, x[8], S11, 0x698098d8); /* 9 */ - FF(d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */ - FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ - FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ - FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ - FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ - FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ - FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ - - /* Round 2 */ - GG(a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */ - GG(d, a, b, c, x[6], S22, 0xc040b340); /* 18 */ - GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ - GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */ - GG(a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */ - GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */ - GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ - GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */ - GG(a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */ - GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ - GG(c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */ - GG(b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */ - GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ - GG(d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */ - GG(c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */ - GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ - - /* Round 3 */ - HH(a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */ - HH(d, a, b, c, x[8], S32, 0x8771f681); /* 34 */ - HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ - HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ - HH(a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */ - HH(d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */ - HH(c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */ - HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ - HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ - HH(d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */ - HH(c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */ - HH(b, c, d, a, x[6], S34, 0x4881d05); /* 44 */ - HH(a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */ - HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ - HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ - HH(b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */ - - /* Round 4 */ - II(a, b, c, d, x[0], S41, 0xf4292244); /* 49 */ - II(d, a, b, c, x[7], S42, 0x432aff97); /* 50 */ - II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ - II(b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */ - II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ - II(d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */ - II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ - II(b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */ - II(a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */ - II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ - II(c, d, a, b, x[6], S43, 0xa3014314); /* 59 */ - II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ - II(a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */ - II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ - II(c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */ - II(b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */ - - state[0] += a; - state[1] += b; - state[2] += c; - state[3] += d; - - // Zeroize sensitive information. - memset(x, 0, sizeof x); +void MD5::transform(const uint1 block[blocksize]) { + uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16]; + decode(x, block, blocksize); + + /* Round 1 */ + FF(a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */ + FF(d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */ + FF(c, d, a, b, x[2], S13, 0x242070db); /* 3 */ + FF(b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */ + FF(a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */ + FF(d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */ + FF(c, d, a, b, x[6], S13, 0xa8304613); /* 7 */ + FF(b, c, d, a, x[7], S14, 0xfd469501); /* 8 */ + FF(a, b, c, d, x[8], S11, 0x698098d8); /* 9 */ + FF(d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */ + FF(c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */ + FF(b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */ + FF(a, b, c, d, x[12], S11, 0x6b901122); /* 13 */ + FF(d, a, b, c, x[13], S12, 0xfd987193); /* 14 */ + FF(c, d, a, b, x[14], S13, 0xa679438e); /* 15 */ + FF(b, c, d, a, x[15], S14, 0x49b40821); /* 16 */ + + /* Round 2 */ + GG(a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */ + GG(d, a, b, c, x[6], S22, 0xc040b340); /* 18 */ + GG(c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */ + GG(b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */ + GG(a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */ + GG(d, a, b, c, x[10], S22, 0x2441453); /* 22 */ + GG(c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */ + GG(b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */ + GG(a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */ + GG(d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */ + GG(c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */ + GG(b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */ + GG(a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */ + GG(d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */ + GG(c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */ + GG(b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */ + + /* Round 3 */ + HH(a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */ + HH(d, a, b, c, x[8], S32, 0x8771f681); /* 34 */ + HH(c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */ + HH(b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */ + HH(a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */ + HH(d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */ + HH(c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */ + HH(b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */ + HH(a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */ + HH(d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */ + HH(c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */ + HH(b, c, d, a, x[6], S34, 0x4881d05); /* 44 */ + HH(a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */ + HH(d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */ + HH(c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */ + HH(b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */ + + /* Round 4 */ + II(a, b, c, d, x[0], S41, 0xf4292244); /* 49 */ + II(d, a, b, c, x[7], S42, 0x432aff97); /* 50 */ + II(c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */ + II(b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */ + II(a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */ + II(d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */ + II(c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */ + II(b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */ + II(a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */ + II(d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */ + II(c, d, a, b, x[6], S43, 0xa3014314); /* 59 */ + II(b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */ + II(a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */ + II(d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */ + II(c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */ + II(b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */ + + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + + // Zeroize sensitive information. + memset(x, 0, sizeof x); } ////////////////////////////// // MD5 block update operation. Continues an MD5 message-digest // operation, processing another message block -void MD5::update(const unsigned char input[], size_type length) -{ - // compute number of bytes mod 64 - size_type index = count[0] / 8 % blocksize; - - // Update number of bits - if ((count[0] += (length << 3)) < (length << 3)) - count[1]++; - count[1] += (length >> 29); - - // number of bytes we need to fill in buffer - size_type firstpart = 64 - index; - - size_type i; - - // transform as many times as possible. - if (length >= firstpart) - { - // fill buffer first, transform - memcpy(&buffer[index], input, firstpart); - transform(buffer); - - // transform chunks of blocksize (64 bytes) - for (i = firstpart; i + blocksize <= length; i += blocksize) - transform(&input[i]); - - index = 0; - } - else - i = 0; - - // buffer remaining input - memcpy(&buffer[index], &input[i], length - i); +void MD5::update(const unsigned char input[], size_type length) { + // compute number of bytes mod 64 + size_type index = count[0] / 8 % blocksize; + + // Update number of bits + if ((count[0] += (length << 3)) < (length << 3)) + count[1]++; + count[1] += (length >> 29); + + // number of bytes we need to fill in buffer + size_type firstpart = 64 - index; + + size_type i; + + // transform as many times as possible. + if (length >= firstpart) { + // fill buffer first, transform + memcpy(&buffer[index], input, firstpart); + transform(buffer); + + // transform chunks of blocksize (64 bytes) + for (i = firstpart; i + blocksize <= length; i += blocksize) + transform(&input[i]); + + index = 0; + } else + i = 0; + + // buffer remaining input + memcpy(&buffer[index], &input[i], length - i); } ////////////////////////////// // for convenience provide a verson with signed char -void MD5::update(const char input[], size_type length) -{ - update((const unsigned char*)input, length); +void MD5::update(const char input[], size_type length) { + update((const unsigned char*)input, length); } ////////////////////////////// // MD5 finalization. Ends an MD5 message-digest operation, writing the // the message digest and zeroizing the context. -MD5& MD5::finalize() -{ - static unsigned char padding[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - - if (!finalized) { - // Save number of bits - unsigned char bits[8]; - encode(bits, count, 8); - - // pad out to 56 mod 64. - size_type index = count[0] / 8 % 64; - size_type padLen = (index < 56) ? (56 - index) : (120 - index); - update(padding, padLen); - - // Append length (before padding) - update(bits, 8); - - // Store state in digest - encode(digest, state, 16); - - // Zeroize sensitive information. - memset(buffer, 0, sizeof buffer); - memset(count, 0, sizeof count); - - finalized = true; - } - - return *this; +MD5& MD5::finalize() { + static unsigned char padding[64] = { + 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + + if (!finalized) { + // Save number of bits + unsigned char bits[8]; + encode(bits, count, 8); + + // pad out to 56 mod 64. + size_type index = count[0] / 8 % 64; + size_type padLen = (index < 56) ? (56 - index) : (120 - index); + update(padding, padLen); + + // Append length (before padding) + update(bits, 8); + + // Store state in digest + encode(digest, state, 16); + + // Zeroize sensitive information. + memset(buffer, 0, sizeof buffer); + memset(count, 0, sizeof count); + + finalized = true; + } + + return *this; } ////////////////////////////// // return hex representation of digest as string -std::string MD5::hexdigest() const -{ - if (!finalized) - return ""; - - char buf[33]; - for (int i = 0; i<16; i++) - sprintf(buf + i * 2, "%02x", digest[i]); - buf[32] = 0; - - return std::string(buf); +std::string MD5::hexdigest() const { + if (!finalized) + return ""; + + char buf[33]; + for (int i = 0; i < 16; i++) + sprintf(buf + i * 2, "%02x", digest[i]); + buf[32] = 0; + + return std::string(buf); } ////////////////////////////// -std::ostream& operator<<(std::ostream& out, MD5 md5) -{ - return out << md5.hexdigest(); +std::ostream& operator<<(std::ostream& out, MD5 md5) { + return out << md5.hexdigest(); } ////////////////////////////// -std::string md5(const std::string str) -{ - MD5 md5 = MD5(str); - - return md5.hexdigest(); +std::string md5(const std::string str) { + MD5 md5 = MD5(str); + + return md5.hexdigest(); } diff --git a/dCommon/MD5.h b/dCommon/MD5.h index 1ada98a5..30d178e1 100644 --- a/dCommon/MD5.h +++ b/dCommon/MD5.h @@ -1,33 +1,33 @@ /* MD5 converted to C++ class by Frank Thilo (thilo@unix-ag.org) for bzflag (http://www.bzflag.org) - + based on: - + md5.h and md5.c reference implementation of RFC 1321 - + Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved. - + License to copy and use this software is granted provided that it is identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing this software or this function. - + License is also granted to make and use derivative works provided that such works are identified as "derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing the derived work. - + RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided "as is" without express or implied warranty of any kind. - + These notices must be retained in any copies of any part of this documentation and/or software. - + */ #ifndef BZF_MD5_H @@ -37,55 +37,55 @@ #include -// a small class for calculating MD5 hashes of strings or byte arrays -// it is not meant to be fast or secure -// -// usage: 1) feed it blocks of uchars with update() -// 2) finalize() -// 3) get hexdigest() string -// or -// MD5(std::string).hexdigest() -// -// assumes that char is 8 bit and int is 32 bit + // a small class for calculating MD5 hashes of strings or byte arrays + // it is not meant to be fast or secure + // + // usage: 1) feed it blocks of uchars with update() + // 2) finalize() + // 3) get hexdigest() string + // or + // MD5(std::string).hexdigest() + // + // assumes that char is 8 bit and int is 32 bit class MD5 { public: - typedef unsigned int size_type; // must be 32bit - - MD5(); - MD5(const std::string& text); - void update(const unsigned char *buf, size_type length); - void update(const char *buf, size_type length); - MD5& finalize(); - std::string hexdigest() const; - friend std::ostream& operator<<(std::ostream&, MD5 md5); - + typedef unsigned int size_type; // must be 32bit + + MD5(); + MD5(const std::string& text); + void update(const unsigned char* buf, size_type length); + void update(const char* buf, size_type length); + MD5& finalize(); + std::string hexdigest() const; + friend std::ostream& operator<<(std::ostream&, MD5 md5); + private: - void init(); - typedef unsigned char uint1; // 8bit - typedef unsigned int uint4; // 32bit - enum { blocksize = 64 }; // VC6 won't eat a const static int here - - void transform(const uint1 block[blocksize]); - static void decode(uint4 output[], const uint1 input[], size_type len); - static void encode(uint1 output[], const uint4 input[], size_type len); - - bool finalized; - uint1 buffer[blocksize]; // bytes that didn't fit in last 64 byte chunk - uint4 count[2]; // 64bit counter for number of bits (lo, hi) - uint4 state[4]; // digest so far - uint1 digest[16]; // the result - - // low level logic operations - static inline uint4 F(uint4 x, uint4 y, uint4 z); - static inline uint4 G(uint4 x, uint4 y, uint4 z); - static inline uint4 H(uint4 x, uint4 y, uint4 z); - static inline uint4 I(uint4 x, uint4 y, uint4 z); - static inline uint4 rotate_left(uint4 x, int n); - static inline void FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); - static inline void II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); + void init(); + typedef unsigned char uint1; // 8bit + typedef unsigned int uint4; // 32bit + enum { blocksize = 64 }; // VC6 won't eat a const static int here + + void transform(const uint1 block[blocksize]); + static void decode(uint4 output[], const uint1 input[], size_type len); + static void encode(uint1 output[], const uint4 input[], size_type len); + + bool finalized; + uint1 buffer[blocksize]; // bytes that didn't fit in last 64 byte chunk + uint4 count[2]; // 64bit counter for number of bits (lo, hi) + uint4 state[4]; // digest so far + uint1 digest[16]; // the result + + // low level logic operations + static inline uint4 F(uint4 x, uint4 y, uint4 z); + static inline uint4 G(uint4 x, uint4 y, uint4 z); + static inline uint4 H(uint4 x, uint4 y, uint4 z); + static inline uint4 I(uint4 x, uint4 y, uint4 z); + static inline uint4 rotate_left(uint4 x, int n); + static inline void FF(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); + static inline void GG(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); + static inline void HH(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); + static inline void II(uint4& a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac); }; std::string md5(const std::string str); diff --git a/dCommon/Metrics.cpp b/dCommon/Metrics.cpp index a7adb998..b97b5435 100644 --- a/dCommon/Metrics.cpp +++ b/dCommon/Metrics.cpp @@ -4,174 +4,150 @@ std::unordered_map Metrics::m_Metrics = {}; std::vector Metrics::m_Variables = { - MetricVariable::GameLoop, - MetricVariable::PacketHandling, - MetricVariable::UpdateEntities, - MetricVariable::UpdateSpawners, - MetricVariable::Physics, - MetricVariable::UpdateReplica, - MetricVariable::Ghosting, - MetricVariable::CPUTime, - MetricVariable::Sleep, - MetricVariable::Frame, + MetricVariable::GameLoop, + MetricVariable::PacketHandling, + MetricVariable::UpdateEntities, + MetricVariable::UpdateSpawners, + MetricVariable::Physics, + MetricVariable::UpdateReplica, + MetricVariable::Ghosting, + MetricVariable::CPUTime, + MetricVariable::Sleep, + MetricVariable::Frame, }; -void Metrics::AddMeasurement(MetricVariable variable, int64_t value) -{ - const auto& iter = m_Metrics.find(variable); +void Metrics::AddMeasurement(MetricVariable variable, int64_t value) { + const auto& iter = m_Metrics.find(variable); - Metric* metric; + Metric* metric; - if (iter == m_Metrics.end()) - { - metric = new Metric(); + if (iter == m_Metrics.end()) { + metric = new Metric(); - m_Metrics[variable] = metric; - } - else - { - metric = iter->second; - } + m_Metrics[variable] = metric; + } else { + metric = iter->second; + } - AddMeasurement(metric, value); + AddMeasurement(metric, value); } -void Metrics::AddMeasurement(Metric* metric, int64_t value) -{ - const auto index = metric->measurementIndex; +void Metrics::AddMeasurement(Metric* metric, int64_t value) { + const auto index = metric->measurementIndex; - metric->measurements[index] = value; + metric->measurements[index] = value; - if (metric->max == -1 || value > metric->max) - { - metric->max = value; - } - else if (metric->min == -1 || metric->min > value) - { - metric->min = value; - } + if (metric->max == -1 || value > metric->max) { + metric->max = value; + } else if (metric->min == -1 || metric->min > value) { + metric->min = value; + } - if (metric->measurementSize < MAX_MEASURMENT_POINTS) - { - metric->measurementSize++; - } + if (metric->measurementSize < MAX_MEASURMENT_POINTS) { + metric->measurementSize++; + } - metric->measurementIndex = (index + 1) % MAX_MEASURMENT_POINTS; + metric->measurementIndex = (index + 1) % MAX_MEASURMENT_POINTS; } -const Metric* Metrics::GetMetric(MetricVariable variable) -{ - const auto& iter = m_Metrics.find(variable); +const Metric* Metrics::GetMetric(MetricVariable variable) { + const auto& iter = m_Metrics.find(variable); - if (iter == m_Metrics.end()) - { - return nullptr; - } + if (iter == m_Metrics.end()) { + return nullptr; + } - Metric* metric = iter->second; + Metric* metric = iter->second; - int64_t average = 0; + int64_t average = 0; - for (size_t i = 0; i < metric->measurementSize; i++) - { - average += metric->measurements[i]; - } + for (size_t i = 0; i < metric->measurementSize; i++) { + average += metric->measurements[i]; + } - average /= metric->measurementSize; + average /= metric->measurementSize; - metric->average = average; - - return metric; + metric->average = average; + + return metric; } -void Metrics::StartMeasurement(MetricVariable variable) -{ - const auto& iter = m_Metrics.find(variable); +void Metrics::StartMeasurement(MetricVariable variable) { + const auto& iter = m_Metrics.find(variable); - Metric* metric; + Metric* metric; - if (iter == m_Metrics.end()) - { - metric = new Metric(); + if (iter == m_Metrics.end()) { + metric = new Metric(); - m_Metrics[variable] = metric; - } - else - { - metric = iter->second; - } + m_Metrics[variable] = metric; + } else { + metric = iter->second; + } - metric->activeMeasurement = std::chrono::high_resolution_clock::now(); + metric->activeMeasurement = std::chrono::high_resolution_clock::now(); } -void Metrics::EndMeasurement(MetricVariable variable) -{ - const auto end = std::chrono::high_resolution_clock::now(); +void Metrics::EndMeasurement(MetricVariable variable) { + const auto end = std::chrono::high_resolution_clock::now(); - const auto& iter = m_Metrics.find(variable); + const auto& iter = m_Metrics.find(variable); - if (iter == m_Metrics.end()) - { - return; - } + if (iter == m_Metrics.end()) { + return; + } - Metric* metric = iter->second; + Metric* metric = iter->second; - const auto elapsed = end - metric->activeMeasurement; + const auto elapsed = end - metric->activeMeasurement; - const auto nanoseconds = std::chrono::duration_cast(elapsed).count(); + const auto nanoseconds = std::chrono::duration_cast(elapsed).count(); - AddMeasurement(metric, nanoseconds); + AddMeasurement(metric, nanoseconds); } -float Metrics::ToMiliseconds(int64_t nanoseconds) -{ - return (float) nanoseconds / 1e6; +float Metrics::ToMiliseconds(int64_t nanoseconds) { + return (float)nanoseconds / 1e6; } -std::string Metrics::MetricVariableToString(MetricVariable variable) -{ - switch (variable) - { - case MetricVariable::GameLoop: - return "GameLoop"; - case MetricVariable::PacketHandling: - return "PacketHandling"; - case MetricVariable::UpdateEntities: - return "UpdateEntities"; - case MetricVariable::UpdateSpawners: - return "UpdateSpawners"; - case MetricVariable::Physics: - return "Physics"; - case MetricVariable::UpdateReplica: - return "UpdateReplica"; - case MetricVariable::Sleep: - return "Sleep"; - case MetricVariable::CPUTime: - return "CPUTime"; - case MetricVariable::Frame: - return "Frame"; - case MetricVariable::Ghosting: - return "Ghosting"; - - default: - return "Invalid"; - } +std::string Metrics::MetricVariableToString(MetricVariable variable) { + switch (variable) { + case MetricVariable::GameLoop: + return "GameLoop"; + case MetricVariable::PacketHandling: + return "PacketHandling"; + case MetricVariable::UpdateEntities: + return "UpdateEntities"; + case MetricVariable::UpdateSpawners: + return "UpdateSpawners"; + case MetricVariable::Physics: + return "Physics"; + case MetricVariable::UpdateReplica: + return "UpdateReplica"; + case MetricVariable::Sleep: + return "Sleep"; + case MetricVariable::CPUTime: + return "CPUTime"; + case MetricVariable::Frame: + return "Frame"; + case MetricVariable::Ghosting: + return "Ghosting"; + + default: + return "Invalid"; + } } -const std::vector& Metrics::GetAllMetrics() -{ - return m_Variables; +const std::vector& Metrics::GetAllMetrics() { + return m_Variables; } -void Metrics::Clear() -{ - for (const auto& pair : m_Metrics) - { - delete pair.second; - } - - m_Metrics.clear(); +void Metrics::Clear() { + for (const auto& pair : m_Metrics) { + delete pair.second; + } + + m_Metrics.clear(); } /* RSS Memory utilities @@ -207,46 +183,44 @@ void Metrics::Clear() #error "Cannot define getPeakRSS( ) or getCurrentRSS( ) for an unknown OS." #endif -/** - * Returns the peak (maximum so far) resident set size (physical - * memory use) measured in bytes, or zero if the value cannot be - * determined on this OS. - */ -size_t Metrics::GetPeakRSS() -{ + /** + * Returns the peak (maximum so far) resident set size (physical + * memory use) measured in bytes, or zero if the value cannot be + * determined on this OS. + */ +size_t Metrics::GetPeakRSS() { #if defined(_WIN32) - /* Windows -------------------------------------------------- */ - PROCESS_MEMORY_COUNTERS info; - GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); - return (size_t)info.PeakWorkingSetSize; + /* Windows -------------------------------------------------- */ + PROCESS_MEMORY_COUNTERS info; + GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info)); + return (size_t)info.PeakWorkingSetSize; #elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) - /* AIX and Solaris ------------------------------------------ */ - struct psinfo psinfo; - int fd = -1; - if ( (fd = open( "/proc/self/psinfo", O_RDONLY )) == -1 ) - return (size_t)0L; /* Can't open? */ - if ( read( fd, &psinfo, sizeof(psinfo) ) != sizeof(psinfo) ) - { - close( fd ); - return (size_t)0L; /* Can't read? */ - } - close( fd ); - return (size_t)(psinfo.pr_rssize * 1024L); + /* AIX and Solaris ------------------------------------------ */ + struct psinfo psinfo; + int fd = -1; + if ((fd = open("/proc/self/psinfo", O_RDONLY)) == -1) + return (size_t)0L; /* Can't open? */ + if (read(fd, &psinfo, sizeof(psinfo)) != sizeof(psinfo)) { + close(fd); + return (size_t)0L; /* Can't read? */ + } + close(fd); + return (size_t)(psinfo.pr_rssize * 1024L); #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) - /* BSD, Linux, and OSX -------------------------------------- */ - struct rusage rusage; - getrusage( RUSAGE_SELF, &rusage ); + /* BSD, Linux, and OSX -------------------------------------- */ + struct rusage rusage; + getrusage(RUSAGE_SELF, &rusage); #if defined(__APPLE__) && defined(__MACH__) - return (size_t)rusage.ru_maxrss; + return (size_t)rusage.ru_maxrss; #else - return (size_t)(rusage.ru_maxrss * 1024L); + return (size_t)(rusage.ru_maxrss * 1024L); #endif #else - /* Unknown OS ----------------------------------------------- */ - return (size_t)0L; /* Unsupported. */ + /* Unknown OS ----------------------------------------------- */ + return (size_t)0L; /* Unsupported. */ #endif } @@ -255,49 +229,46 @@ size_t Metrics::GetPeakRSS() * Returns the current resident set size (physical memory use) measured * in bytes, or zero if the value cannot be determined on this OS. */ -size_t Metrics::GetCurrentRSS() -{ +size_t Metrics::GetCurrentRSS() { #if defined(_WIN32) - /* Windows -------------------------------------------------- */ - PROCESS_MEMORY_COUNTERS info; - GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); - return (size_t)info.WorkingSetSize; + /* Windows -------------------------------------------------- */ + PROCESS_MEMORY_COUNTERS info; + GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info)); + return (size_t)info.WorkingSetSize; #elif defined(__APPLE__) && defined(__MACH__) - /* OSX ------------------------------------------------------ */ - struct mach_task_basic_info info; - mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; - if ( task_info( mach_task_self( ), MACH_TASK_BASIC_INFO, - (task_info_t)&info, &infoCount ) != KERN_SUCCESS ) - return (size_t)0L; /* Can't access? */ - return (size_t)info.resident_size; + /* OSX ------------------------------------------------------ */ + struct mach_task_basic_info info; + mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; + if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, + (task_info_t)&info, &infoCount) != KERN_SUCCESS) + return (size_t)0L; /* Can't access? */ + return (size_t)info.resident_size; #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) - /* Linux ---------------------------------------------------- */ - long rss = 0L; - FILE* fp = NULL; - if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL ) - return (size_t)0L; /* Can't open? */ - if ( fscanf( fp, "%*s%ld", &rss ) != 1 ) - { - fclose( fp ); - return (size_t)0L; /* Can't read? */ - } - fclose( fp ); - return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE); + /* Linux ---------------------------------------------------- */ + long rss = 0L; + FILE* fp = NULL; + if ((fp = fopen("/proc/self/statm", "r")) == NULL) + return (size_t)0L; /* Can't open? */ + if (fscanf(fp, "%*s%ld", &rss) != 1) { + fclose(fp); + return (size_t)0L; /* Can't read? */ + } + fclose(fp); + return (size_t)rss * (size_t)sysconf(_SC_PAGESIZE); #else - /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ - return (size_t)0L; /* Unsupported. */ + /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ + return (size_t)0L; /* Unsupported. */ #endif } -size_t Metrics::GetProcessID() -{ +size_t Metrics::GetProcessID() { #if defined(_WIN32) - return GetCurrentProcessId(); + return GetCurrentProcessId(); #else - return getpid(); + return getpid(); #endif } diff --git a/dCommon/Metrics.hpp b/dCommon/Metrics.hpp index b22632d2..c03c914f 100644 --- a/dCommon/Metrics.hpp +++ b/dCommon/Metrics.hpp @@ -10,52 +10,52 @@ enum class MetricVariable : int32_t { - GameLoop, - PacketHandling, - UpdateEntities, - UpdateSpawners, - Physics, - UpdateReplica, - Ghosting, - CPUTime, - Sleep, - Frame, + GameLoop, + PacketHandling, + UpdateEntities, + UpdateSpawners, + Physics, + UpdateReplica, + Ghosting, + CPUTime, + Sleep, + Frame, }; struct Metric { - int64_t measurements[MAX_MEASURMENT_POINTS] = {}; - size_t measurementIndex = 0; - size_t measurementSize = 0; - int64_t max = -1; - int64_t min = -1; - int64_t average = 0; - std::chrono::time_point activeMeasurement; + int64_t measurements[MAX_MEASURMENT_POINTS] = {}; + size_t measurementIndex = 0; + size_t measurementSize = 0; + int64_t max = -1; + int64_t min = -1; + int64_t average = 0; + std::chrono::time_point activeMeasurement; }; class Metrics { public: - ~Metrics(); + ~Metrics(); - static void AddMeasurement(MetricVariable variable, int64_t value); - static void AddMeasurement(Metric* metric, int64_t value); - static const Metric* GetMetric(MetricVariable variable); - static void StartMeasurement(MetricVariable variable); - static void EndMeasurement(MetricVariable variable); - static float ToMiliseconds(int64_t nanoseconds); - static std::string MetricVariableToString(MetricVariable variable); - static const std::vector& GetAllMetrics(); + static void AddMeasurement(MetricVariable variable, int64_t value); + static void AddMeasurement(Metric* metric, int64_t value); + static const Metric* GetMetric(MetricVariable variable); + static void StartMeasurement(MetricVariable variable); + static void EndMeasurement(MetricVariable variable); + static float ToMiliseconds(int64_t nanoseconds); + static std::string MetricVariableToString(MetricVariable variable); + static const std::vector& GetAllMetrics(); - static size_t GetPeakRSS(); - static size_t GetCurrentRSS(); - static size_t GetProcessID(); + static size_t GetPeakRSS(); + static size_t GetCurrentRSS(); + static size_t GetProcessID(); - static void Clear(); + static void Clear(); private: - Metrics(); + Metrics(); - static std::unordered_map m_Metrics; - static std::vector m_Variables; + static std::unordered_map m_Metrics; + static std::vector m_Variables; }; diff --git a/dCommon/NiPoint3.cpp b/dCommon/NiPoint3.cpp index 4baefa13..a539c4df 100644 --- a/dCommon/NiPoint3.cpp +++ b/dCommon/NiPoint3.cpp @@ -13,23 +13,23 @@ const NiPoint3 NiPoint3::UNIT_ALL(1.0f, 1.0f, 1.0f); //! Initializer NiPoint3::NiPoint3(void) { - this->x = 0; - this->y = 0; - this->z = 0; + 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; + 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; + this->x = point.x; + this->y = point.y; + this->z = point.z; } //! Destructor @@ -39,63 +39,63 @@ NiPoint3::~NiPoint3(void) {} //! Gets the X coordinate float NiPoint3::GetX(void) const { - return this->x; + return this->x; } //! Sets the X coordinate void NiPoint3::SetX(float x) { - this->x = x; + this->x = x; } //! Gets the Y coordinate float NiPoint3::GetY(void) const { - return this->y; + return this->y; } //! Sets the Y coordinate void NiPoint3::SetY(float y) { - this->y = y; + this->y = y; } //! Gets the Z coordinate float NiPoint3::GetZ(void) const { - return this->z; + return this->z; } //! Sets the Z coordinate void NiPoint3::SetZ(float z) { - this->z = z; + this->z = z; } // MARK: Functions //! Gets the length of the vector float NiPoint3::Length(void) const { - return sqrt(x*x + y*y + z*z); + 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); + 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)); + 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))); + 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))); } //! Unitize the vector NiPoint3 NiPoint3::Unitize(void) const { - float length = this->Length(); - - return length != 0 ? *this / length : NiPoint3::ZERO; + float length = this->Length(); + + return length != 0 ? *this / length : NiPoint3::ZERO; } @@ -103,57 +103,57 @@ NiPoint3 NiPoint3::Unitize(void) const { //! 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; + 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); + return !(*this == point); } //! Operator for subscripting float& NiPoint3::operator[](int i) { - float * base = &x; - return (float&)base[i]; + float* base = &x; + return (float&)base[i]; } //! Operator for subscripting const float& NiPoint3::operator[](int i) const { - const float * base = &x; - return (float&)base[i]; + const float* base = &x; + return (float&)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); + return NiPoint3(this->x + point.x, this->y + point.y, this->z + point.z); } //! 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); + 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); + 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); + 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); + 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); + 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); } @@ -161,96 +161,91 @@ NiPoint3 NiPoint3::operator/(float fScalar) const { //! 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; + 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); + 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)); + 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; +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 pa = p - a; + const auto ab = b - a; - const auto t = pa.DotProduct(ab) / ab.SquaredLength(); + const auto t = pa.DotProduct(ab) / ab.SquaredLength(); - if (t <= 0.0f) return a; - - if (t >= 1.0f) return b; - - return a + ab * t; + 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(); - const auto lenB = a.SquaredLength(); - return acos(dot / sqrt(lenA * lenB)); +float NiPoint3::Angle(const NiPoint3& a, const NiPoint3& b) { + const auto dot = a.DotProduct(b); + const auto lenA = a.SquaredLength(); + const auto lenB = a.SquaredLength(); + return acos(dot / sqrt(lenA * lenB)); } -float NiPoint3::Distance(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; +float NiPoint3::Distance(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 std::sqrt(dx * dx + dy * dy + dz * dz); + 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; +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; + return dx * dx + dy * dy + dz * dz; } -NiPoint3 NiPoint3::MoveTowards(const NiPoint3& current, const NiPoint3& target, float maxDistanceDelta) -{ - float dx = target.x - current.x; - float dy = target.y - current.y; - float dz = target.z - current.z; - float lengthSquared = (float) ((double) dx * (double) dx + (double) dy * (double) dy + (double) dz * (double) dz); - if ((double) lengthSquared == 0.0 || (double) maxDistanceDelta >= 0.0 && (double) lengthSquared <= (double) maxDistanceDelta * (double) maxDistanceDelta) - return target; - float length = (float) std::sqrt((double) lengthSquared); - return NiPoint3(current.x + dx / length * maxDistanceDelta, current.y + dy / length * maxDistanceDelta, current.z + dz / length * maxDistanceDelta); +NiPoint3 NiPoint3::MoveTowards(const NiPoint3& current, const NiPoint3& target, float maxDistanceDelta) { + float dx = target.x - current.x; + float dy = target.y - current.y; + float dz = target.z - current.z; + float lengthSquared = (float)((double)dx * (double)dx + (double)dy * (double)dy + (double)dz * (double)dz); + if ((double)lengthSquared == 0.0 || (double)maxDistanceDelta >= 0.0 && (double)lengthSquared <= (double)maxDistanceDelta * (double)maxDistanceDelta) + return target; + float length = (float)std::sqrt((double)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; + 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; -} \ No newline at end of file + 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 24e4e617..6c0b9d3d 100644 --- a/dCommon/NiPoint3.h +++ b/dCommon/NiPoint3.h @@ -12,177 +12,177 @@ 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; //!< The x position + float y; //!< The y position + float z; //!< The z position - //! Initializer - NiPoint3(void); + //! Initializer + NiPoint3(void); - //! Initializer - /*! - \param x The x coordinate - \param y The y coordinate - \param z The z coordinate - */ - NiPoint3(float x, float y, float z); + //! Initializer + /*! + \param x The x coordinate + \param y The y coordinate + \param z The z coordinate + */ + NiPoint3(float x, float y, float z); - //! Copy Constructor - /*! - \param point The point to copy - */ - NiPoint3(const NiPoint3& point); + //! Copy Constructor + /*! + \param point The point to copy + */ + NiPoint3(const NiPoint3& point); - //! Destructor - ~NiPoint3(void); + //! 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) + // 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) - // MARK: Getters / Setters + // MARK: Getters / Setters - //! Gets the X coordinate - /*! - \return The x coordinate - */ - float GetX(void) const; + //! Gets the X coordinate + /*! + \return The x coordinate + */ + float GetX(void) const; - //! Sets the X coordinate - /*! - \param x The x coordinate - */ - void SetX(float x); + //! Sets the X coordinate + /*! + \param x The x coordinate + */ + void SetX(float x); - //! Gets the Y coordinate - /*! - \return The y coordinate - */ - float GetY(void) const; + //! Gets the Y coordinate + /*! + \return The y coordinate + */ + float GetY(void) const; - //! Sets the Y coordinate - /*! - \param y The y coordinate - */ - void SetY(float y); + //! Sets the Y coordinate + /*! + \param y The y coordinate + */ + void SetY(float y); - //! Gets the Z coordinate - /*! - \return The z coordinate - */ - float GetZ(void) const; + //! Gets the Z coordinate + /*! + \return The z coordinate + */ + float GetZ(void) const; - //! Sets the Z coordinate - /*! - \param z The z coordinate - */ - void SetZ(float z); + //! Sets the Z coordinate + /*! + \param z The z coordinate + */ + void SetZ(float z); - // MARK: Member Functions + // MARK: Member Functions - //! Gets the length of the vector - /*! - \return The scalar length of the vector - */ - float Length(void) const; + //! Gets the length of the vector + /*! + \return The scalar length of the vector + */ + float Length(void) const; - //! Gets the squared length of a vector - /*! - \return The squared length of a vector - */ - float SquaredLength(void) const; + //! Gets the squared length of a vector + /*! + \return The squared length of a vector + */ + float SquaredLength(void) const; - //! 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; + //! 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; - //! 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; + //! 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; - //! Unitize the vector - /*! - \returns The current vector - */ - NiPoint3 Unitize(void) const; + //! Unitize the vector + /*! + \returns The current vector + */ + NiPoint3 Unitize(void) const; - // MARK: Operators + // MARK: Operators - //! Operator to check for equality - bool operator==(const NiPoint3& point) const; + //! Operator to check for equality + bool operator==(const NiPoint3& point) const; - //! Operator to check for inequality - bool operator!=(const NiPoint3& point) const; + //! Operator to check for inequality + bool operator!=(const NiPoint3& point) const; - //! Operator for subscripting - float& operator[](int i); + //! Operator for subscripting + float& operator[](int i); - //! Operator for subscripting - const float& operator[](int i) const; + //! Operator for subscripting + const float& operator[](int i) const; - //! Operator for addition of vectors - NiPoint3 operator+(const NiPoint3& point) const; + //! Operator for addition of vectors + NiPoint3 operator+(const NiPoint3& point) const; - //! Operator for subtraction of vectors - NiPoint3 operator-(const NiPoint3& point) const; + //! Operator for subtraction of vectors + NiPoint3 operator-(const NiPoint3& point) const; - //! Operator for addition of a scalar on all vector components - NiPoint3 operator+(float fScalar) const; + //! Operator for addition of a scalar on all vector components + NiPoint3 operator+(float fScalar) const; - //! Operator for subtraction of a scalar on all vector components - NiPoint3 operator-(float fScalar) const; + //! Operator for subtraction of a scalar on all vector components + NiPoint3 operator-(float fScalar) const; - //! Operator for scalar multiplication of a vector - NiPoint3 operator*(float fScalar) const; + //! Operator for scalar multiplication of a vector + NiPoint3 operator*(float fScalar) const; - //! Operator for scalar division of a vector - NiPoint3 operator/(float fScalar) const; + //! Operator for scalar division of a vector + NiPoint3 operator/(float fScalar) const; - // MARK: Helper Functions + // MARK: Helper Functions - //! Checks to see if the point (or vector) is with an Axis-Aligned Bounding Box - /*! - \param minPoint The minimum point of the bounding box - \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); + //! Checks to see if the point (or vector) is with an Axis-Aligned Bounding Box + /*! + \param minPoint The minimum point of the bounding box + \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); - //! 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); + //! 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); - /*! - \param a Start of line - \param b End of line - \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); + /*! + \param a Start of line + \param b End of line + \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); - static float Angle(const NiPoint3& a, const NiPoint3& b); + static float Angle(const NiPoint3& a, const NiPoint3& b); - static float Distance(const NiPoint3& a, const NiPoint3& b); - - static float DistanceSquared(const NiPoint3& a, const NiPoint3& b); + static float Distance(const NiPoint3& a, const NiPoint3& b); - static NiPoint3 MoveTowards(const NiPoint3& current, const NiPoint3& target, float maxDistanceDelta); + static float DistanceSquared(const NiPoint3& a, const NiPoint3& b); - NiPoint3 RotateByQuaternion(const NiQuaternion& rotation); + static NiPoint3 MoveTowards(const NiPoint3& current, const NiPoint3& target, float maxDistanceDelta); + + NiPoint3 RotateByQuaternion(const NiQuaternion& rotation); }; diff --git a/dCommon/NiQuaternion.cpp b/dCommon/NiQuaternion.cpp index a8aa1dc8..33c5c976 100644 --- a/dCommon/NiQuaternion.cpp +++ b/dCommon/NiQuaternion.cpp @@ -8,18 +8,18 @@ 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; + 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; + this->w = w; + this->x = x; + this->y = y; + this->z = z; } //! Destructor @@ -30,42 +30,42 @@ NiQuaternion::~NiQuaternion(void) {} //! Gets the W coordinate float NiQuaternion::GetW(void) const { - return this->w; + return this->w; } //! Sets the W coordinate void NiQuaternion::SetW(float w) { - this->w = w; + this->w = w; } //! Gets the X coordinate float NiQuaternion::GetX(void) const { - return this->x; + return this->x; } //! Sets the X coordinate void NiQuaternion::SetX(float x) { - this->x = x; + this->x = x; } //! Gets the Y coordinate float NiQuaternion::GetY(void) const { - return this->y; + return this->y; } //! Sets the Y coordinate void NiQuaternion::SetY(float y) { - this->y = y; + this->y = y; } //! Gets the Z coordinate float NiQuaternion::GetZ(void) const { - return this->z; + return this->z; } //! Sets the Z coordinate void NiQuaternion::SetZ(float z) { - this->z = z; + this->z = z; } @@ -73,55 +73,54 @@ void NiQuaternion::SetZ(float z) { //! 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)); + 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)); + 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)); + return Vector3(1 - 2 * (y * y + z * z), 2 * (x * y + w * z), 2 * (x * z - w * y)); } Vector3 NiQuaternion::GetEulerAngles() const { - Vector3 angles; + Vector3 angles; - // roll (x-axis rotation) - const float sinr_cosp = 2 * (w * x + y * z); - const float cosr_cosp = 1 - 2 * (x * x + y * y); - angles.x = std::atan2(sinr_cosp, cosr_cosp); + // roll (x-axis rotation) + const float sinr_cosp = 2 * (w * x + y * z); + const float cosr_cosp = 1 - 2 * (x * x + y * y); + angles.x = std::atan2(sinr_cosp, cosr_cosp); - // pitch (y-axis rotation) - const float sinp = 2 * (w * y - z * x); - - if (std::abs(sinp) >= 1) { - angles.y = std::copysign(3.14 / 2, sinp); // use 90 degrees if out of range - } - else { - angles.y = std::asin(sinp); - } + // pitch (y-axis rotation) + const float sinp = 2 * (w * y - z * x); - // yaw (z-axis rotation) - const float siny_cosp = 2 * (w * z + x * y); - const float cosy_cosp = 1 - 2 * (y * y + z * z); - angles.z = std::atan2(siny_cosp, cosy_cosp); + if (std::abs(sinp) >= 1) { + angles.y = std::copysign(3.14 / 2, sinp); // use 90 degrees if out of range + } else { + angles.y = std::asin(sinp); + } - return angles; + // yaw (z-axis rotation) + const float siny_cosp = 2 * (w * z + x * y); + const float cosy_cosp = 1 - 2 * (y * y + z * z); + angles.z = std::atan2(siny_cosp, cosy_cosp); + + 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; + 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); + return !(*this == rot); } @@ -135,65 +134,63 @@ NiQuaternion NiQuaternion::LookAt(const NiPoint3& sourcePoint, const NiPoint3& d source.y = 0.0f; dest.y = 0.0f; - NiPoint3 forwardVector = NiPoint3(dest - source).Unitize(); - - NiPoint3 posZ = NiPoint3::UNIT_Z; - NiPoint3 vecA = posZ.CrossProduct(forwardVector).Unitize(); - - float dot = posZ.DotProduct(forwardVector); - float rotAngle = static_cast(acos(dot)); - - NiPoint3 vecB = vecA.CrossProduct(posZ); - - if (vecB.DotProduct(forwardVector) < 0) rotAngle = -rotAngle; - return NiQuaternion::CreateFromAxisAngle(vecA, rotAngle); + NiPoint3 forwardVector = NiPoint3(dest - source).Unitize(); + + NiPoint3 posZ = NiPoint3::UNIT_Z; + NiPoint3 vecA = posZ.CrossProduct(forwardVector).Unitize(); + + float dot = posZ.DotProduct(forwardVector); + float rotAngle = static_cast(acos(dot)); + + NiPoint3 vecB = vecA.CrossProduct(posZ); + + if (vecB.DotProduct(forwardVector) < 0) rotAngle = -rotAngle; + return NiQuaternion::CreateFromAxisAngle(vecA, rotAngle); } -NiQuaternion NiQuaternion::LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint) -{ - NiPoint3 forwardVector = NiPoint3(destPoint - sourcePoint).Unitize(); - - NiPoint3 posZ = NiPoint3::UNIT_Z; - NiPoint3 vecA = posZ.CrossProduct(forwardVector).Unitize(); - - float dot = posZ.DotProduct(forwardVector); - float rotAngle = static_cast(acos(dot)); - - NiPoint3 vecB = vecA.CrossProduct(posZ); - - if (vecB.DotProduct(forwardVector) < 0) rotAngle = -rotAngle; - return NiQuaternion::CreateFromAxisAngle(vecA, rotAngle); +NiQuaternion NiQuaternion::LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint) { + NiPoint3 forwardVector = NiPoint3(destPoint - sourcePoint).Unitize(); + + NiPoint3 posZ = NiPoint3::UNIT_Z; + NiPoint3 vecA = posZ.CrossProduct(forwardVector).Unitize(); + + float dot = posZ.DotProduct(forwardVector); + float rotAngle = static_cast(acos(dot)); + + NiPoint3 vecB = vecA.CrossProduct(posZ); + + if (vecB.DotProduct(forwardVector) < 0) rotAngle = -rotAngle; + return NiQuaternion::CreateFromAxisAngle(vecA, rotAngle); } //! Creates a Quaternion from a specific axis and angle relative to that axis NiQuaternion NiQuaternion::CreateFromAxisAngle(const Vector3& axis, float angle) { - float halfAngle = angle * 0.5f; - float s = static_cast(sin(halfAngle)); - - NiQuaternion q; - q.x = axis.GetX() * s; - q.y = axis.GetY() * s; - q.z = axis.GetZ() * s; - q.w = static_cast(cos(halfAngle)); - - return q; + float halfAngle = angle * 0.5f; + float s = static_cast(sin(halfAngle)); + + NiQuaternion q; + q.x = axis.GetX() * s; + q.y = axis.GetY() * s; + q.z = axis.GetZ() * s; + q.w = static_cast(cos(halfAngle)); + + return q; } -NiQuaternion NiQuaternion::FromEulerAngles(const NiPoint3& eulerAngles) -{ - // Abbreviations for the various angular functions - float cy = cos(eulerAngles.z * 0.5); - float sy = sin(eulerAngles.z * 0.5); - float cp = cos(eulerAngles.y * 0.5); - float sp = sin(eulerAngles.y * 0.5); - float cr = cos(eulerAngles.x * 0.5); - float sr = sin(eulerAngles.x * 0.5); +NiQuaternion NiQuaternion::FromEulerAngles(const NiPoint3& eulerAngles) { + // Abbreviations for the various angular functions + float cy = cos(eulerAngles.z * 0.5); + float sy = sin(eulerAngles.z * 0.5); + float cp = cos(eulerAngles.y * 0.5); + float sp = sin(eulerAngles.y * 0.5); + float cr = cos(eulerAngles.x * 0.5); + float sr = sin(eulerAngles.x * 0.5); - NiQuaternion q; - q.w = cr * cp * cy + sr * sp * sy; - q.x = sr * cp * cy - cr * sp * sy; - q.y = cr * sp * cy + sr * cp * sy; - q.z = cr * cp * sy - sr * sp * cy; + NiQuaternion q; + q.w = cr * cp * cy + sr * sp * sy; + q.x = sr * cp * cy - cr * sp * sy; + q.y = cr * sp * cy + sr * cp * sy; + q.z = cr * cp * sy - sr * sp * cy; - return q; + return q; } diff --git a/dCommon/NiQuaternion.h b/dCommon/NiQuaternion.h index f479501a..b7d60f4e 100644 --- a/dCommon/NiQuaternion.h +++ b/dCommon/NiQuaternion.h @@ -14,138 +14,138 @@ 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 - - - //! The initializer - NiQuaternion(void); - - //! The initializer - /*! - \param w The w coordinate - \param x The x coordinate - \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) - - // MARK: Setters / Getters - - //! Gets the W coordinate - /*! - \return The w coordinate - */ - float GetW(void) const; - - //! Sets the W coordinate - /*! - \param w The w coordinate - */ - void SetW(float w); - - //! Gets the X coordinate - /*! - \return The x coordinate - */ - float GetX(void) const; - - //! Sets the X coordinate - /*! - \param x The x coordinate - */ - void SetX(float x); - - //! Gets the Y coordinate - /*! - \return The y coordinate - */ - float GetY(void) const; - - //! Sets the Y coordinate - /*! - \param y The y coordinate - */ - void SetY(float y); - - //! Gets the Z coordinate - /*! - \return The z coordinate - */ - float GetZ(void) const; - - //! Sets the Z coordinate - /*! - \param z The z coordinate - */ - void SetZ(float z); - - - // MARK: Member Functions - - //! Returns the forward vector from the quaternion - /*! - \return The forward vector of the quaternion - */ - Vector3 GetForwardVector(void) const; - - //! Returns the up vector from the quaternion - /*! - \return The up vector fo the quaternion - */ - Vector3 GetUpVector(void) const; - - //! Returns the right vector from the quaternion - /*! - \return The right vector of the quaternion - */ - Vector3 GetRightVector(void) const; + float w; //!< The w coordinate + float x; //!< The x coordinate + float y; //!< The y coordinate + float z; //!< The z coordinate - Vector3 GetEulerAngles() const; - - - // MARK: Operators - - //! Operator to check for equality - bool operator==(const NiQuaternion& rot) const; - - //! Operator to check for inequality - bool operator!=(const NiQuaternion& rot) const; - - - // MARK: Helper Functions - - //! Look from a specific point in space to another point in space (Y-locked) - /*! - \param sourcePoint The source location - \param destPoint The destination location - \return The Quaternion with the rotation towards the destination - */ - static NiQuaternion LookAt(const NiPoint3& sourcePoint, const NiPoint3& destPoint); - - //! Look from a specific point in space to another point in space - /*! - \param sourcePoint The source location - \param destPoint The destination location - \return The Quaternion with the rotation towards the destination - */ - static NiQuaternion LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint); - - //! Creates a Quaternion from a specific axis and angle relative to that axis - /*! - \param axis The axis that is used - \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); - static NiQuaternion FromEulerAngles(const NiPoint3& eulerAngles); + //! The initializer + NiQuaternion(void); + + //! The initializer + /*! + \param w The w coordinate + \param x The x coordinate + \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) + + // MARK: Setters / Getters + + //! Gets the W coordinate + /*! + \return The w coordinate + */ + float GetW(void) const; + + //! Sets the W coordinate + /*! + \param w The w coordinate + */ + void SetW(float w); + + //! Gets the X coordinate + /*! + \return The x coordinate + */ + float GetX(void) const; + + //! Sets the X coordinate + /*! + \param x The x coordinate + */ + void SetX(float x); + + //! Gets the Y coordinate + /*! + \return The y coordinate + */ + float GetY(void) const; + + //! Sets the Y coordinate + /*! + \param y The y coordinate + */ + void SetY(float y); + + //! Gets the Z coordinate + /*! + \return The z coordinate + */ + float GetZ(void) const; + + //! Sets the Z coordinate + /*! + \param z The z coordinate + */ + void SetZ(float z); + + + // MARK: Member Functions + + //! Returns the forward vector from the quaternion + /*! + \return The forward vector of the quaternion + */ + Vector3 GetForwardVector(void) const; + + //! Returns the up vector from the quaternion + /*! + \return The up vector fo the quaternion + */ + Vector3 GetUpVector(void) const; + + //! Returns the right vector from the quaternion + /*! + \return The right vector of the quaternion + */ + Vector3 GetRightVector(void) const; + + Vector3 GetEulerAngles() const; + + + // MARK: Operators + + //! Operator to check for equality + bool operator==(const NiQuaternion& rot) const; + + //! Operator to check for inequality + bool operator!=(const NiQuaternion& rot) const; + + + // MARK: Helper Functions + + //! Look from a specific point in space to another point in space (Y-locked) + /*! + \param sourcePoint The source location + \param destPoint The destination location + \return The Quaternion with the rotation towards the destination + */ + static NiQuaternion LookAt(const NiPoint3& sourcePoint, const NiPoint3& destPoint); + + //! Look from a specific point in space to another point in space + /*! + \param sourcePoint The source location + \param destPoint The destination location + \return The Quaternion with the rotation towards the destination + */ + static NiQuaternion LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint); + + //! Creates a Quaternion from a specific axis and angle relative to that axis + /*! + \param axis The axis that is used + \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); + + static NiQuaternion FromEulerAngles(const NiPoint3& eulerAngles); }; diff --git a/dCommon/PermissionMap.h b/dCommon/PermissionMap.h index 177f4884..8c271f17 100644 --- a/dCommon/PermissionMap.h +++ b/dCommon/PermissionMap.h @@ -7,36 +7,36 @@ */ enum class PermissionMap : uint64_t { - /** - * Reserved for future use, bit 0-3. - */ + /** + * Reserved for future use, bit 0-3. + */ - /** - * The character has restricted trade acccess, bit 4. - */ - RestrictedTradeAccess = 0x1 << 4, + /** + * The character has restricted trade acccess, bit 4. + */ + RestrictedTradeAccess = 0x1 << 4, - /** - * The character has restricted mail access, bit 5. - */ - RestrictedMailAccess = 0x1 << 5, + /** + * The character has restricted mail access, bit 5. + */ + RestrictedMailAccess = 0x1 << 5, - /** - * The character has restricted chat access, bit 6. - */ - RestrictedChatAccess = 0x1 << 6, + /** + * The character has restricted chat access, bit 6. + */ + RestrictedChatAccess = 0x1 << 6, - // - // Combined permissions - // + // + // Combined permissions + // - /** - * The character is marked as 'old', restricted from trade and mail. - */ - Old = RestrictedTradeAccess | RestrictedMailAccess, + /** + * The character is marked as 'old', restricted from trade and mail. + */ + Old = RestrictedTradeAccess | RestrictedMailAccess, - /** - * The character is soft banned, restricted from trade, mail, and chat. - */ - SoftBanned = RestrictedTradeAccess | RestrictedMailAccess | RestrictedChatAccess, + /** + * The character is soft banned, restricted from trade, mail, and chat. + */ + SoftBanned = RestrictedTradeAccess | RestrictedMailAccess | RestrictedChatAccess, }; diff --git a/dCommon/SHA512.cpp b/dCommon/SHA512.cpp index 6daf44f6..f5a71d99 100644 --- a/dCommon/SHA512.cpp +++ b/dCommon/SHA512.cpp @@ -5,153 +5,148 @@ 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 }; + 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::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::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::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]); - } +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); +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]); + 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); + return std::string(buf); } diff --git a/dCommon/SHA512.h b/dCommon/SHA512.h index aba80432..512fa645 100644 --- a/dCommon/SHA512.h +++ b/dCommon/SHA512.h @@ -5,25 +5,25 @@ 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); - + 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); - + 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]; + 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); diff --git a/dCommon/Type.cpp b/dCommon/Type.cpp index f89d090e..5cce9d66 100644 --- a/dCommon/Type.cpp +++ b/dCommon/Type.cpp @@ -6,22 +6,22 @@ std::string demangle(const char* name) { - int status = -4; // some arbitrary value to eliminate the compiler warning + int status = -4; // some arbitrary value to eliminate the compiler warning - // enable c++11 by passing the flag -std=c++11 to g++ - std::unique_ptr res { - abi::__cxa_demangle(name, NULL, NULL, &status), - std::free - }; + // enable c++11 by passing the flag -std=c++11 to g++ + std::unique_ptr res{ + abi::__cxa_demangle(name, NULL, NULL, &status), + std::free + }; - return (status==0) ? res.get() : name ; + return (status == 0) ? res.get() : name; } #else // does nothing if not g++ std::string demangle(const char* name) { - return name; + return name; } #endif diff --git a/dCommon/Type.h b/dCommon/Type.h index ea26d2ce..552bb09f 100644 --- a/dCommon/Type.h +++ b/dCommon/Type.h @@ -8,5 +8,5 @@ std::string demangle(const char* name); template std::string type(const T& t) { - return demangle(typeid(t).name()); + return demangle(typeid(t).name()); } diff --git a/dCommon/ZCompression.cpp b/dCommon/ZCompression.cpp index 28588bb8..a82dc3c9 100644 --- a/dCommon/ZCompression.cpp +++ b/dCommon/ZCompression.cpp @@ -1,77 +1,73 @@ #include "ZCompression.h" -#ifndef _WIN32 +#ifndef _WIN32 #include -namespace ZCompression -{ - int32_t GetMaxCompressedLength(int32_t nLenSrc) - { - int32_t n16kBlocks = (nLenSrc + 16383) / 16384; // round up any fraction of a block - return (nLenSrc + 6 + (n16kBlocks * 5)); - } +namespace ZCompression { + int32_t GetMaxCompressedLength(int32_t nLenSrc) { + int32_t n16kBlocks = (nLenSrc + 16383) / 16384; // round up any fraction of a block + return (nLenSrc + 6 + (n16kBlocks * 5)); + } - int32_t Compress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst) - { - z_stream zInfo = { 0 }; - zInfo.total_in = zInfo.avail_in = nLenSrc; - zInfo.total_out = zInfo.avail_out = nLenDst; - zInfo.next_in = const_cast(abSrc); - zInfo.next_out = abDst; + int32_t Compress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst) { + z_stream zInfo = { 0 }; + zInfo.total_in = zInfo.avail_in = nLenSrc; + zInfo.total_out = zInfo.avail_out = nLenDst; + zInfo.next_in = const_cast(abSrc); + zInfo.next_out = abDst; - int nErr, nRet = -1; - nErr = deflateInit(&zInfo, Z_DEFAULT_COMPRESSION); // zlib function - if (nErr == Z_OK) { - nErr = deflate(&zInfo, Z_FINISH); // zlib function - if (nErr == Z_STREAM_END) { - nRet = zInfo.total_out; - } - } - deflateEnd(&zInfo); // zlib function - return(nRet); + int nErr, nRet = -1; + nErr = deflateInit(&zInfo, Z_DEFAULT_COMPRESSION); // zlib function + if (nErr == Z_OK) { + nErr = deflate(&zInfo, Z_FINISH); // zlib function + if (nErr == Z_STREAM_END) { + nRet = zInfo.total_out; + } + } + deflateEnd(&zInfo); // zlib function + return(nRet); - } + } - int32_t Decompress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst, int32_t& nErr) - { - // Get the size of the decompressed data - z_stream zInfo = { 0 }; - zInfo.total_in = zInfo.avail_in = nLenSrc; - zInfo.total_out = zInfo.avail_out = nLenDst; - zInfo.next_in = const_cast(abSrc); - zInfo.next_out = abDst; + int32_t Decompress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst, int32_t& nErr) { + // Get the size of the decompressed data + z_stream zInfo = { 0 }; + zInfo.total_in = zInfo.avail_in = nLenSrc; + zInfo.total_out = zInfo.avail_out = nLenDst; + zInfo.next_in = const_cast(abSrc); + zInfo.next_out = abDst; - int nRet = -1; - nErr = inflateInit(&zInfo); // zlib function - if (nErr == Z_OK) { - nErr = inflate(&zInfo, Z_FINISH); // zlib function - if (nErr == Z_STREAM_END) { - nRet = zInfo.total_out; - } - } - inflateEnd(&zInfo); // zlib function - return(nRet); - - /* - z_stream zInfo = { 0 }; - zInfo.total_in = zInfo.avail_in = nLenSrc; - zInfo.total_out = zInfo.avail_out = nLenDst; - zInfo.next_in = const_cast(abSrc); - zInfo.next_out = const_cast(abDst); + int nRet = -1; + nErr = inflateInit(&zInfo); // zlib function + if (nErr == Z_OK) { + nErr = inflate(&zInfo, Z_FINISH); // zlib function + if (nErr == Z_STREAM_END) { + nRet = zInfo.total_out; + } + } + inflateEnd(&zInfo); // zlib function + return(nRet); - int nRet = -1; - nErr = inflateInit(&zInfo); // zlib function - if (nErr == Z_OK) { - nErr = inflate(&zInfo, Z_FINISH); // zlib function - if (nErr == Z_STREAM_END) { - nRet = zInfo.total_out; - } - } - inflateEnd(&zInfo); // zlib function - return(nRet); // -1 or len of output - */ - } + /* + z_stream zInfo = { 0 }; + zInfo.total_in = zInfo.avail_in = nLenSrc; + zInfo.total_out = zInfo.avail_out = nLenDst; + zInfo.next_in = const_cast(abSrc); + zInfo.next_out = const_cast(abDst); + + int nRet = -1; + nErr = inflateInit(&zInfo); // zlib function + if (nErr == Z_OK) { + nErr = inflate(&zInfo, Z_FINISH); // zlib function + if (nErr == Z_STREAM_END) { + nRet = zInfo.total_out; + } + } + inflateEnd(&zInfo); // zlib function + return(nRet); // -1 or len of output + */ + } } -#endif \ No newline at end of file +#endif diff --git a/dCommon/ZCompression.h b/dCommon/ZCompression.h index 6db2a600..a4ac9193 100644 --- a/dCommon/ZCompression.h +++ b/dCommon/ZCompression.h @@ -6,8 +6,7 @@ #ifndef DARKFLAME_PLATFORM_WIN32 -namespace ZCompression -{ +namespace ZCompression { int32_t GetMaxCompressedLength(int32_t nLenSrc); int32_t Compress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst); diff --git a/dCommon/dCommonVars.h b/dCommon/dCommonVars.h index 9f62eaa4..986f1c18 100644 --- a/dCommon/dCommonVars.h +++ b/dCommon/dCommonVars.h @@ -103,61 +103,61 @@ private: const LWOSCENEID LWOSCENEID_INVALID = -1; struct LWONameValue { - uint32_t length = 0; //!< The length of the name - std::u16string name; //!< The name - - LWONameValue(void) {} - - LWONameValue(const std::u16string& name) { - this->name = name; - this->length = static_cast(name.length()); - } - - ~LWONameValue(void) {} + uint32_t length = 0; //!< The length of the name + std::u16string name; //!< The name + + LWONameValue(void) {} + + LWONameValue(const std::u16string& name) { + this->name = name; + this->length = static_cast(name.length()); + } + + ~LWONameValue(void) {} }; struct FriendData { public: - bool isOnline = false; - bool isBestFriend = false; - bool isFTP = false; - LWOZONEID zoneID; - LWOOBJID friendID; - std::string friendName; + bool isOnline = false; + bool isBestFriend = false; + bool isFTP = false; + LWOZONEID zoneID; + LWOOBJID friendID; + std::string friendName; - void Serialize(RakNet::BitStream& bitStream) { - bitStream.Write(isOnline); - bitStream.Write(isBestFriend); - bitStream.Write(isFTP); - bitStream.Write(0); //??? - bitStream.Write(0); //??? - bitStream.Write(zoneID.GetMapID()); - bitStream.Write(zoneID.GetInstanceID()); - bitStream.Write(zoneID.GetCloneID()); - bitStream.Write(friendID); - - uint32_t maxSize = 33; - uint32_t size = static_cast(friendName.length()); - uint32_t remSize = static_cast(maxSize - size); + void Serialize(RakNet::BitStream& bitStream) { + bitStream.Write(isOnline); + bitStream.Write(isBestFriend); + bitStream.Write(isFTP); + bitStream.Write(0); //??? + bitStream.Write(0); //??? + bitStream.Write(zoneID.GetMapID()); + bitStream.Write(zoneID.GetInstanceID()); + bitStream.Write(zoneID.GetCloneID()); + bitStream.Write(friendID); - if (size > maxSize) size = maxSize; + uint32_t maxSize = 33; + uint32_t size = static_cast(friendName.length()); + uint32_t remSize = static_cast(maxSize - size); - for (uint32_t i = 0; i < size; ++i) { - bitStream.Write(static_cast(friendName[i])); - } + if (size > maxSize) size = maxSize; - for (uint32_t j = 0; j < remSize; ++j) { - bitStream.Write(static_cast(0)); - } + for (uint32_t i = 0; i < size; ++i) { + bitStream.Write(static_cast(friendName[i])); + } - bitStream.Write(0); //??? - bitStream.Write(0); //??? - } + for (uint32_t j = 0; j < remSize; ++j) { + bitStream.Write(static_cast(0)); + } + + bitStream.Write(0); //??? + bitStream.Write(0); //??? + } }; struct Brick { - uint32_t designerID; - uint32_t materialID; + uint32_t designerID; + uint32_t materialID; }; //This union is used by the behavior system @@ -169,26 +169,26 @@ union suchar { //=========== DLU ENUMS ============ enum eGameMasterLevel : int32_t { - GAME_MASTER_LEVEL_CIVILIAN = 0, // Normal player. - GAME_MASTER_LEVEL_FORUM_MODERATOR = 1, // No permissions on live servers. - GAME_MASTER_LEVEL_JUNIOR_MODERATOR = 2, // Can kick/mute and pull chat logs. - GAME_MASTER_LEVEL_MODERATOR = 3, // Can return lost items. - GAME_MASTER_LEVEL_SENIOR_MODERATOR = 4, // Can ban. - GAME_MASTER_LEVEL_LEAD_MODERATOR = 5, // Can approve properties. - GAME_MASTER_LEVEL_JUNIOR_DEVELOPER = 6, // Junior developer & future content team. Civilan on live. - GAME_MASTER_LEVEL_INACTIVE_DEVELOPER = 7, // Inactive developer, limited permissions. - GAME_MASTER_LEVEL_DEVELOPER = 8, // Active developer, full permissions on live. - GAME_MASTER_LEVEL_OPERATOR = 9 // Can shutdown server for restarts & updates. + GAME_MASTER_LEVEL_CIVILIAN = 0, // Normal player. + GAME_MASTER_LEVEL_FORUM_MODERATOR = 1, // No permissions on live servers. + GAME_MASTER_LEVEL_JUNIOR_MODERATOR = 2, // Can kick/mute and pull chat logs. + GAME_MASTER_LEVEL_MODERATOR = 3, // Can return lost items. + GAME_MASTER_LEVEL_SENIOR_MODERATOR = 4, // Can ban. + GAME_MASTER_LEVEL_LEAD_MODERATOR = 5, // Can approve properties. + GAME_MASTER_LEVEL_JUNIOR_DEVELOPER = 6, // Junior developer & future content team. Civilan on live. + GAME_MASTER_LEVEL_INACTIVE_DEVELOPER = 7, // Inactive developer, limited permissions. + GAME_MASTER_LEVEL_DEVELOPER = 8, // Active developer, full permissions on live. + GAME_MASTER_LEVEL_OPERATOR = 9 // Can shutdown server for restarts & updates. }; //=========== LU ENUMS ============ //! An enum for object ID bits enum eObjectBits : int32_t { - OBJECT_BIT_PERSISTENT = 32, //!< The 32 bit index - OBJECT_BIT_CLIENT = 46, //!< The 46 bit index - OBJECT_BIT_SPAWNED = 58, //!< The 58 bit index - OBJECT_BIT_CHARACTER = 60 //!< The 60 bit index + OBJECT_BIT_PERSISTENT = 32, //!< The 32 bit index + OBJECT_BIT_CLIENT = 46, //!< The 46 bit index + OBJECT_BIT_SPAWNED = 58, //!< The 58 bit index + OBJECT_BIT_CHARACTER = 60 //!< The 60 bit index }; //! An enum for MatchUpdate types @@ -208,18 +208,18 @@ enum eCyclingMode : uint32_t { }; enum eCinematicEvent : uint32_t { - STARTED, - WAYPOINT, - ENDED, + STARTED, + WAYPOINT, + ENDED, }; //! An enum for character creation responses enum eCreationResponse : uint8_t { - CREATION_RESPONSE_SUCCESS = 0, //!< The creation was successful - CREATION_RESPONSE_OBJECT_ID_UNAVAILABLE, //!< The Object ID can't be used - CREATION_RESPONSE_NAME_NOT_ALLOWED, //!< The name is not allowed - CREATION_RESPONSE_PREDEFINED_NAME_IN_USE, //!< The predefined name is already in use - CREATION_RESPONSE_CUSTOM_NAME_IN_USE //!< The custom name is already in use + CREATION_RESPONSE_SUCCESS = 0, //!< The creation was successful + CREATION_RESPONSE_OBJECT_ID_UNAVAILABLE, //!< The Object ID can't be used + CREATION_RESPONSE_NAME_NOT_ALLOWED, //!< The name is not allowed + CREATION_RESPONSE_PREDEFINED_NAME_IN_USE, //!< The predefined name is already in use + CREATION_RESPONSE_CUSTOM_NAME_IN_USE //!< The custom name is already in use }; //! An enum for login responses @@ -234,21 +234,21 @@ enum eLoginResponse : uint8_t { //! An enum for character rename responses enum eRenameResponse : uint8_t { - RENAME_RESPONSE_SUCCESS = 0, //!< The renaming was successful - RENAME_RESPONSE_UNKNOWN_ERROR, //!< There was an unknown error - RENAME_RESPONSE_NAME_UNAVAILABLE, //!< The name is unavailable - RENAME_RESPONSE_NAME_IN_USE //!< The name is already in use + RENAME_RESPONSE_SUCCESS = 0, //!< The renaming was successful + RENAME_RESPONSE_UNKNOWN_ERROR, //!< There was an unknown error + RENAME_RESPONSE_NAME_UNAVAILABLE, //!< The name is unavailable + RENAME_RESPONSE_NAME_IN_USE //!< The name is already in use }; //! A replica packet type enum eReplicaPacketType { - PACKET_TYPE_CONSTRUCTION, //!< A construction packet - PACKET_TYPE_SERIALIZATION, //!< A serialization packet - PACKET_TYPE_DESTRUCTION //!< A destruction packet + PACKET_TYPE_CONSTRUCTION, //!< A construction packet + PACKET_TYPE_SERIALIZATION, //!< A serialization packet + PACKET_TYPE_DESTRUCTION //!< A destruction packet }; enum ServerDisconnectIdentifiers { - SERVER_DISCON_UNKNOWN_SERVER_ERROR = 0, //!< Unknown server error + SERVER_DISCON_UNKNOWN_SERVER_ERROR = 0, //!< Unknown server error SERVER_DISCON_DUPLICATE_LOGIN = 4, //!< Used when another user with the same username is logged in (duplicate login) SERVER_DISCON_SERVER_SHUTDOWN = 5, //!< Used when the server is shutdown SERVER_DISCON_SERVER_MAP_LOAD_FAILURE = 6, //!< Used when the server cannot load a map @@ -263,80 +263,80 @@ enum ServerDisconnectIdentifiers { //! The Behavior Types for use with the AI system enum eCombatBehaviorTypes : uint32_t { - PASSIVE = 0, //!< The object is passive - AGGRESSIVE = 1, //!< The object is aggressive - PASSIVE_TURRET = 2, //!< The object is a passive turret - AGGRESSIVE_TURRET = 3 //!< The object is an aggressive turret + PASSIVE = 0, //!< The object is passive + AGGRESSIVE = 1, //!< The object is aggressive + PASSIVE_TURRET = 2, //!< The object is a passive turret + AGGRESSIVE_TURRET = 3 //!< The object is an aggressive turret }; //! The Combat Role Type for use with the AI system enum eCombatRoleType : uint32_t { - MELEE = 0, //!< Used for melee attacks - RANGED = 1, //!< Used for range attacks - SUPPORT = 2 //!< Used for support + MELEE = 0, //!< Used for melee attacks + RANGED = 1, //!< Used for range attacks + SUPPORT = 2 //!< Used for support }; //! The kill types for the Die packet enum eKillType : uint32_t { - VIOLENT, - SILENT + VIOLENT, + SILENT }; //! The various world states used throughout the server enum eObjectWorldState { - WORLDSTATE_INWORLD, //!< Probably used when the object is in the world - WORLDSTATE_ATTACHED, //!< Probably used when the object is attached to another object - WORLDSTATE_INVENTORY //!< Probably used when the object is in an inventory + WORLDSTATE_INWORLD, //!< Probably used when the object is in the world + WORLDSTATE_ATTACHED, //!< Probably used when the object is attached to another object + WORLDSTATE_INVENTORY //!< Probably used when the object is in an inventory }; //! The trigger stats (???) enum eTriggerStat { - INVALID_STAT, //!< ??? - HEALTH, //!< Probably used for health - ARMOR, //!< Probably used for armor - IMAGINATION //!< Probably used for imagination + INVALID_STAT, //!< ??? + HEALTH, //!< Probably used for health + ARMOR, //!< Probably used for armor + IMAGINATION //!< Probably used for imagination }; //! The trigger operations (???) enum eTriggerOperator { - INVALID_OPER, //!< ??? - EQUAL, //!< ??? - NOT_EQUAL, //!< ??? - GREATER, //!< ??? - GREATER_EQUAL, //!< ??? - LESS, //!< ??? - LESS_EQUAL //!< ??? + INVALID_OPER, //!< ??? + EQUAL, //!< ??? + NOT_EQUAL, //!< ??? + GREATER, //!< ??? + GREATER_EQUAL, //!< ??? + LESS, //!< ??? + LESS_EQUAL //!< ??? }; //! The various build types enum eBuildType { - BUILD_NOWHERE, //!< Used if something can't be built anywhere - BUILD_IN_WORLD, //!< Used if something can be built in the world - BUILD_ON_PROPERTY //!< Used if something can be build on a property + BUILD_NOWHERE, //!< Used if something can't be built anywhere + BUILD_IN_WORLD, //!< Used if something can be built in the world + BUILD_ON_PROPERTY //!< Used if something can be build on a property }; //! Quickbuild fail reasons enum eFailReason : uint32_t { - REASON_NOT_GIVEN, - REASON_OUT_OF_IMAGINATION, - REASON_CANCELED_EARLY, - REASON_BUILD_ENDED + REASON_NOT_GIVEN, + REASON_OUT_OF_IMAGINATION, + REASON_CANCELED_EARLY, + REASON_BUILD_ENDED }; //! Terminate interaction type enum eTerminateType : uint32_t { - RANGE, - USER, - FROM_INTERACTION + RANGE, + USER, + FROM_INTERACTION }; //! The combat state enum eCombatState { - IDLE, //!< The AI is in an idle state - AGGRO, //!< The AI is in an aggressive state - TETHER, //!< The AI is being redrawn back to tether point - SPAWN, //!< The AI is spawning - DEAD //!< The AI is dead + IDLE, //!< The AI is in an idle state + AGGRO, //!< The AI is in an aggressive state + TETHER, //!< The AI is being redrawn back to tether point + SPAWN, //!< The AI is spawning + DEAD //!< The AI is dead }; enum eControlSceme { @@ -348,7 +348,7 @@ enum eControlSceme { SCHEME_DRIVING, SCHEME_TAMING, SCHEME_MODULAR_BUILD, - SCHEME_WEAR_A_ROBOT //== freecam? + SCHEME_WEAR_A_ROBOT //== freecam? }; enum eStunState { @@ -357,86 +357,86 @@ enum eStunState { }; enum eNotifyType { - NOTIFY_TYPE_SUCCESS, - NOTIFY_TYPE_QUIT, - NOTIFY_TYPE_FAILED, - NOTIFY_TYPE_BEGIN, - NOTIFY_TYPE_READY, - NOTIFY_TYPE_NAMINGPET + NOTIFY_TYPE_SUCCESS, + NOTIFY_TYPE_QUIT, + NOTIFY_TYPE_FAILED, + NOTIFY_TYPE_BEGIN, + NOTIFY_TYPE_READY, + NOTIFY_TYPE_NAMINGPET }; enum eReplicaComponentType : int32_t { - COMPONENT_TYPE_CONTROLLABLE_PHYSICS = 1, //!< The ControllablePhysics Component - COMPONENT_TYPE_RENDER = 2, //!< The Render Component - COMPONENT_TYPE_SIMPLE_PHYSICS = 3, //!< The SimplePhysics Component - COMPONENT_TYPE_CHARACTER = 4, //!< The Character Component - COMPONENT_TYPE_SCRIPT = 5, //!< The Script Component - COMPONENT_TYPE_BOUNCER = 6, //!< The Bouncer Component - COMPONENT_TYPE_BUFF = 7, //!< The Buff Component - COMPONENT_TYPE_SKILL = 9, //!< The Skill Component - COMPONENT_TYPE_ITEM = 11, //!< The Item Component - COMPONENT_TYPE_VENDOR = 16, //!< The Vendor Component - COMPONENT_TYPE_INVENTORY = 17, //!< The Inventory Component - COMPONENT_TYPE_SHOOTING_GALLERY = 19, //!< The Shooting Gallery Component - COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS = 20, //!< The RigidBodyPhantomPhysics Component - COMPONENT_TYPE_COLLECTIBLE = 23, //!< The Collectible Component - COMPONENT_TYPE_MOVING_PLATFORM = 25, //!< The MovingPlatform Component - COMPONENT_TYPE_PET = 26, //!< The Pet Component - COMPONENT_TYPE_VEHICLE_PHYSICS = 30, //!< The VehiclePhysics Component - COMPONENT_TYPE_MOVEMENT_AI = 31, //!< The MovementAI Component - COMPONENT_TYPE_PROPERTY = 36, //!< The Property Component - COMPONENT_TYPE_SCRIPTED_ACTIVITY = 39, //!< The ScriptedActivity Component - COMPONENT_TYPE_PHANTOM_PHYSICS = 40, //!< The PhantomPhysics Component - COMPONENT_TYPE_MODEL = 42, //!< The Model Component - COMPONENT_TYPE_PROPERTY_ENTRANCE = 43, //!< The PhantomPhysics Component - COMPONENT_TYPE_PROPERTY_MANAGEMENT = 45, //!< The PropertyManagement Component - COMPONENT_TYPE_REBUILD = 48, //!< The Rebuild Component - COMPONENT_TYPE_SWITCH = 49, //!< The Switch Component - COMPONENT_TYPE_ZONE_CONTROL = 50, //!< The ZoneControl Component - COMPONENT_TYPE_PACKAGE = 53, //!< The Package Component - COMPONENT_TYPE_PLAYER_FLAG = 58, //!< The PlayerFlag Component - COMPONENT_TYPE_BASE_COMBAT_AI = 60, //!< The BaseCombatAI Component - COMPONENT_TYPE_MODULE_ASSEMBLY = 61, //!< The ModuleAssembly Component - COMPONENT_TYPE_PROPERTY_VENDOR = 65, //!< The PropertyVendor Component - COMPONENT_TYPE_ROCKET_LAUNCH = 67, //!< The RocketLaunch Component - COMPONENT_TYPE_RACING_CONTROL = 71, //!< The RacingControl Component - COMPONENT_TYPE_MISSION_OFFER = 73, //!< The MissionOffer Component - COMPONENT_TYPE_EXHIBIT = 75, //!< The Exhibit Component - COMPONENT_TYPE_RACING_STATS = 74, //!< The Racing Stats Component - COMPONENT_TYPE_SOUND_TRIGGER = 77, //!< The Sound Trigger Component - COMPONENT_TYPE_PROXIMITY_MONITOR = 78, //!< The Proximity Monitor Component - COMPONENT_TYPE_MISSION = 84, //!< The Mission Component - COMPONENT_TYPE_ROCKET_LAUNCH_LUP = 97, //!< The LUP Launchpad Componen - COMPONENT_TYPE_RAIL_ACTIVATOR = 104, //!< The Rail Activator Component - COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT = 106, //!< The Player Forced Movement Component - COMPONENT_TYPE_POSSESSABLE = 108, //!< The Possessable Component - COMPONENT_TYPE_LEVEL_PROGRESSION = 109, //!< The Level Progression Component - COMPONENT_TYPE_POSSESSOR = 110, //!< The Possessor Component - COMPONENT_TYPE_BUILD_BORDER = 114, //!< The Build Border Component - COMPONENT_TYPE_DESTROYABLE = 1000, //!< The Destroyable Component + COMPONENT_TYPE_CONTROLLABLE_PHYSICS = 1, //!< The ControllablePhysics Component + COMPONENT_TYPE_RENDER = 2, //!< The Render Component + COMPONENT_TYPE_SIMPLE_PHYSICS = 3, //!< The SimplePhysics Component + COMPONENT_TYPE_CHARACTER = 4, //!< The Character Component + COMPONENT_TYPE_SCRIPT = 5, //!< The Script Component + COMPONENT_TYPE_BOUNCER = 6, //!< The Bouncer Component + COMPONENT_TYPE_BUFF = 7, //!< The Buff Component + COMPONENT_TYPE_SKILL = 9, //!< The Skill Component + COMPONENT_TYPE_ITEM = 11, //!< The Item Component + COMPONENT_TYPE_VENDOR = 16, //!< The Vendor Component + COMPONENT_TYPE_INVENTORY = 17, //!< The Inventory Component + COMPONENT_TYPE_SHOOTING_GALLERY = 19, //!< The Shooting Gallery Component + COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS = 20, //!< The RigidBodyPhantomPhysics Component + COMPONENT_TYPE_COLLECTIBLE = 23, //!< The Collectible Component + COMPONENT_TYPE_MOVING_PLATFORM = 25, //!< The MovingPlatform Component + COMPONENT_TYPE_PET = 26, //!< The Pet Component + COMPONENT_TYPE_VEHICLE_PHYSICS = 30, //!< The VehiclePhysics Component + COMPONENT_TYPE_MOVEMENT_AI = 31, //!< The MovementAI Component + COMPONENT_TYPE_PROPERTY = 36, //!< The Property Component + COMPONENT_TYPE_SCRIPTED_ACTIVITY = 39, //!< The ScriptedActivity Component + COMPONENT_TYPE_PHANTOM_PHYSICS = 40, //!< The PhantomPhysics Component + COMPONENT_TYPE_MODEL = 42, //!< The Model Component + COMPONENT_TYPE_PROPERTY_ENTRANCE = 43, //!< The PhantomPhysics Component + COMPONENT_TYPE_PROPERTY_MANAGEMENT = 45, //!< The PropertyManagement Component + COMPONENT_TYPE_REBUILD = 48, //!< The Rebuild Component + COMPONENT_TYPE_SWITCH = 49, //!< The Switch Component + COMPONENT_TYPE_ZONE_CONTROL = 50, //!< The ZoneControl Component + COMPONENT_TYPE_PACKAGE = 53, //!< The Package Component + COMPONENT_TYPE_PLAYER_FLAG = 58, //!< The PlayerFlag Component + COMPONENT_TYPE_BASE_COMBAT_AI = 60, //!< The BaseCombatAI Component + COMPONENT_TYPE_MODULE_ASSEMBLY = 61, //!< The ModuleAssembly Component + COMPONENT_TYPE_PROPERTY_VENDOR = 65, //!< The PropertyVendor Component + COMPONENT_TYPE_ROCKET_LAUNCH = 67, //!< The RocketLaunch Component + COMPONENT_TYPE_RACING_CONTROL = 71, //!< The RacingControl Component + COMPONENT_TYPE_MISSION_OFFER = 73, //!< The MissionOffer Component + COMPONENT_TYPE_EXHIBIT = 75, //!< The Exhibit Component + COMPONENT_TYPE_RACING_STATS = 74, //!< The Racing Stats Component + COMPONENT_TYPE_SOUND_TRIGGER = 77, //!< The Sound Trigger Component + COMPONENT_TYPE_PROXIMITY_MONITOR = 78, //!< The Proximity Monitor Component + COMPONENT_TYPE_MISSION = 84, //!< The Mission Component + COMPONENT_TYPE_ROCKET_LAUNCH_LUP = 97, //!< The LUP Launchpad Componen + COMPONENT_TYPE_RAIL_ACTIVATOR = 104, //!< The Rail Activator Component + COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT = 106, //!< The Player Forced Movement Component + COMPONENT_TYPE_POSSESSABLE = 108, //!< The Possessable Component + COMPONENT_TYPE_LEVEL_PROGRESSION = 109, //!< The Level Progression Component + COMPONENT_TYPE_POSSESSOR = 110, //!< The Possessor Component + COMPONENT_TYPE_BUILD_BORDER = 114, //!< The Build Border Component + COMPONENT_TYPE_DESTROYABLE = 1000, //!< The Destroyable Component }; enum class UseItemResponse : uint32_t { - NoImaginationForPet = 1, - FailedPrecondition, - MountsNotAllowed + NoImaginationForPet = 1, + FailedPrecondition, + MountsNotAllowed }; /** * Represents the different types of inventories an entity may have */ enum eInventoryType : uint32_t { - ITEMS = 0, - VAULT_ITEMS, - BRICKS, - TEMP_ITEMS = 4, - MODELS, - TEMP_MODELS, - BEHAVIORS, - PROPERTY_DEEDS, + ITEMS = 0, + VAULT_ITEMS, + BRICKS, + TEMP_ITEMS = 4, + MODELS, + TEMP_MODELS, + BEHAVIORS, + PROPERTY_DEEDS, VENDOR_BUYBACK = 11, - HIDDEN = 12, //Used for missional items - VAULT_MODELS = 14, + HIDDEN = 12, //Used for missional items + VAULT_MODELS = 14, ITEM_SETS, //internal INVALID // made up, for internal use!!! }; @@ -450,7 +450,7 @@ enum eRebuildState : uint32_t { }; /** - * The loot source's type. + * The loot source's type. */ enum eLootSourceType : int32_t { LOOT_SOURCE_NONE = 0, @@ -542,7 +542,7 @@ enum ePlayerFlags { TOOLTIP_TALK_TO_SKYLAND_TO_GET_HAT = 52, MODULAR_BUILD_PLAYER_PLACES_FIRST_MODEL_IN_SCRATCH = 53, MODULAR_BUILD_FIRST_ARROW_DISPLAY_FOR_MODULE = 54, - AG_BEACON_QB,_SO_THE_PLAYER_CAN_ALWAYS_BUILD_THEM = 55, + AG_BEACON_QB_SO_THE_PLAYER_CAN_ALWAYS_BUILD_THEM = 55, GF_PET_DIG_FLAG_1 = 56, GF_PET_DIG_FLAG_2 = 57, GF_PET_DIG_FLAG_3 = 58, @@ -554,7 +554,7 @@ enum ePlayerFlags { ENTER_BBB_FROM_PROPERTY_EDIT_CONFIRMATION_DIALOG = 64, AG_FIRST_COMBAT_COMPLETE = 65, AG_COMPLETE_BOB_MISSION = 66, - NJ_GARMADON_CINEMATIC_SEEN = 125, + NJ_GARMADON_CINEMATIC_SEEN = 125, ELEPHANT_PET_3050 = 801, CAT_PET_3054 = 802, TRICERATOPS_PET_3195 = 803, @@ -631,19 +631,19 @@ enum ePlayerFlags { NT_FACTION_SPY_DUKE = 1974, NT_FACTION_SPY_OVERBUILD = 1976, NT_FACTION_SPY_HAEL = 1977, - NJ_EARTH_SPINJITZU = 2030, - NJ_LIGHTNING_SPINJITZU = 2031, - NJ_ICE_SPINJITZU = 2032, - NJ_FIRE_SPINJITZU = 2033, - NJ_WU_SHOW_DAILY_CHEST = 2099 + NJ_EARTH_SPINJITZU = 2030, + NJ_LIGHTNING_SPINJITZU = 2031, + NJ_ICE_SPINJITZU = 2032, + NJ_FIRE_SPINJITZU = 2033, + NJ_WU_SHOW_DAILY_CHEST = 2099 }; //======== FUNC =========== template inline T const& clamp(const T& val, const T& low, const T& high) { - if (val < low) return low; - else if (val > high) return high; - - return val; + if (val < low) return low; + else if (val > high) return high; + + return val; } diff --git a/dCommon/dConfig.cpp b/dCommon/dConfig.cpp index b53b7166..9750238a 100644 --- a/dCommon/dConfig.cpp +++ b/dCommon/dConfig.cpp @@ -12,7 +12,7 @@ dConfig::dConfig(const std::string& filepath) { if (line[0] != '#') ProcessLine(line); } } -} +} dConfig::~dConfig(void) { } @@ -31,15 +31,15 @@ void dConfig::ProcessLine(const std::string& line) { std::vector seglist; while (std::getline(ss, segment, '=')) { - seglist.push_back(segment); + seglist.push_back(segment); } if (seglist.size() != 2) return; //Make sure that on Linux, we remove special characters: if (!seglist[1].empty() && seglist[1][seglist[1].size() - 1] == '\r') - seglist[1].erase(seglist[1].size() - 1); + seglist[1].erase(seglist[1].size() - 1); m_Keys.push_back(seglist[0]); m_Values.push_back(seglist[1]); -} \ No newline at end of file +} diff --git a/dCommon/dConfig.h b/dCommon/dConfig.h index 0e712499..7764fa54 100644 --- a/dCommon/dConfig.h +++ b/dCommon/dConfig.h @@ -17,4 +17,4 @@ private: std::vector m_Keys; std::vector m_Values; std::string m_EmptyString; -}; \ No newline at end of file +}; diff --git a/dCommon/dLogger.cpp b/dCommon/dLogger.cpp index 0beb5a3c..3a91e31d 100644 --- a/dCommon/dLogger.cpp +++ b/dCommon/dLogger.cpp @@ -10,7 +10,7 @@ dLogger::dLogger(const std::string& outpath, bool logToConsole, bool logDebugSta if (!mFile) { printf("Couldn't open %s for writing!\n", outpath.c_str()); } #else fp = fopen(outpath.c_str(), "wt"); - if (fp == NULL) { printf("Couldn't open %s for writing!\n", outpath.c_str()); } + if (fp == NULL) { printf("Couldn't open %s for writing!\n", outpath.c_str()); } #endif } @@ -46,42 +46,42 @@ void dLogger::vLog(const char* format, va_list args) { mFile << "[" << timeStr << "] " << message; #else time_t t = time(NULL); - struct tm * time = localtime(&t); - char timeStr[70]; - strftime(timeStr, sizeof(timeStr), "%d-%m-%y %H:%M:%S", time); + struct tm* time = localtime(&t); + char timeStr[70]; + strftime(timeStr, sizeof(timeStr), "%d-%m-%y %H:%M:%S", time); char message[2048]; - vsprintf(message, format, args); + vsprintf(message, format, args); - if (m_logToConsole) { + if (m_logToConsole) { fputs("[", stdout); fputs(timeStr, stdout); fputs("] ", stdout); fputs(message, stdout); - } + } - if (fp != nullptr) { + if (fp != nullptr) { fputs("[", fp); fputs(timeStr, fp); fputs("] ", fp); fputs(message, fp); - } else { - printf("Logger not initialized!\n"); - } + } else { + printf("Logger not initialized!\n"); + } #endif } -void dLogger::LogBasic(const char * format, ...) { +void dLogger::LogBasic(const char* format, ...) { va_list args; va_start(args, format); vLog(format, args); va_end(args); } -void dLogger::LogBasic(const std::string & message) { +void dLogger::LogBasic(const std::string& message) { LogBasic(message.c_str()); } -void dLogger::Log(const char * className, const char * format, ...) { +void dLogger::Log(const char* className, const char* format, ...) { va_list args; std::string log = "[" + std::string(className) + "] " + std::string(format) + "\n"; va_start(args, format); @@ -89,11 +89,11 @@ void dLogger::Log(const char * className, const char * format, ...) { va_end(args); } -void dLogger::Log(const std::string & className, const std::string & message) { +void dLogger::Log(const std::string& className, const std::string& message) { Log(className.c_str(), message.c_str()); } -void dLogger::LogDebug(const char * className, const char * format, ...) { +void dLogger::LogDebug(const char* className, const char* format, ...) { if (!m_logDebugStatements) return; va_list args; std::string log = "[" + std::string(className) + "] " + std::string(format); @@ -102,7 +102,7 @@ void dLogger::LogDebug(const char * className, const char * format, ...) { va_end(args); } -void dLogger::LogDebug(const std::string & className, const std::string & message) { +void dLogger::LogDebug(const std::string& className, const std::string& message) { LogDebug(className.c_str(), message.c_str()); } diff --git a/dCommon/dLogger.h b/dCommon/dLogger.h index 7448237e..6726c6f1 100644 --- a/dCommon/dLogger.h +++ b/dCommon/dLogger.h @@ -31,8 +31,8 @@ private: std::string m_outpath; std::ofstream mFile; - #ifndef _WIN32 - //Glorious linux can run with SPEED: - FILE* fp = nullptr; - #endif -}; \ No newline at end of file +#ifndef _WIN32 + //Glorious linux can run with SPEED: + FILE* fp = nullptr; +#endif +}; diff --git a/dCommon/dPlatforms.h b/dCommon/dPlatforms.h index d19e8121..bca7f9e0 100644 --- a/dCommon/dPlatforms.h +++ b/dCommon/dPlatforms.h @@ -1,29 +1,29 @@ #pragma once #if defined(_WIN32) - #define DARKFLAME_PLATFORM_WIN32 +#define DARKFLAME_PLATFORM_WIN32 #elif defined(__APPLE__) && defined(__MACH__) - #include - #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR - #define DARKFLAME_PLATFORM_IOS - #elif TARGET_OS_MAC - #define DARKFLAME_PLATFORM_MACOS - #else - #error unknown Apple operating system - #endif -#elif defined(__unix__) - #define DARKFLAME_PLATFORM_UNIX - #if defined(__ANDROID__) - #define DARKFLAME_PLATFORM_ANDROID - #elif defined(__linux__) - #define DARKFLAME_PLATFORM_LINUX - #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) - #define DARKFLAME_PLATFORM_FREEBSD - #elif defined(__CYGWIN__) - #define DARKFLAME_PLATFORM_CYGWIN - #else - #error unknown unix operating system - #endif +#include +#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR +#define DARKFLAME_PLATFORM_IOS +#elif TARGET_OS_MAC +#define DARKFLAME_PLATFORM_MACOS #else - #error unknown operating system -#endif \ No newline at end of file +#error unknown Apple operating system +#endif +#elif defined(__unix__) +#define DARKFLAME_PLATFORM_UNIX +#if defined(__ANDROID__) +#define DARKFLAME_PLATFORM_ANDROID +#elif defined(__linux__) +#define DARKFLAME_PLATFORM_LINUX +#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) +#define DARKFLAME_PLATFORM_FREEBSD +#elif defined(__CYGWIN__) +#define DARKFLAME_PLATFORM_CYGWIN +#else +#error unknown unix operating system +#endif +#else +#error unknown operating system +#endif diff --git a/dCommon/eAninmationFlags.h b/dCommon/eAninmationFlags.h index 09cfde22..9b2ea3fb 100644 --- a/dCommon/eAninmationFlags.h +++ b/dCommon/eAninmationFlags.h @@ -41,4 +41,4 @@ enum class eAnimationFlags : uint32_t { IDLE_MISC12 }; -#endif //!__EANINMATIONFLAGS__H__ \ No newline at end of file +#endif //!__EANINMATIONFLAGS__H__ diff --git a/dCommon/eItemType.h b/dCommon/eItemType.h index 453e8737..e68ce695 100644 --- a/dCommon/eItemType.h +++ b/dCommon/eItemType.h @@ -33,4 +33,4 @@ enum class eItemType : int32_t { ITEM_TYPE_MOUNT = 24 //!< A Mount }; -#endif //!__EITEMTYPE__H__ \ No newline at end of file +#endif //!__EITEMTYPE__H__ diff --git a/dDatabase/CDClientDatabase.cpp b/dDatabase/CDClientDatabase.cpp index d09b2daa..bf8485d6 100644 --- a/dDatabase/CDClientDatabase.cpp +++ b/dDatabase/CDClientDatabase.cpp @@ -2,19 +2,19 @@ #include "CDComponentsRegistryTable.h" // Static Variables -static CppSQLite3DB * conn = new CppSQLite3DB(); +static CppSQLite3DB* conn = new CppSQLite3DB(); //! Opens a connection with the CDClient void CDClientDatabase::Connect(const std::string& filename) { - conn->open(filename.c_str()); + conn->open(filename.c_str()); } //! Queries the CDClient CppSQLite3Query CDClientDatabase::ExecuteQuery(const std::string& query) { - return conn->execQuery(query.c_str()); + return conn->execQuery(query.c_str()); } //! Makes prepared statements CppSQLite3Statement CDClientDatabase::CreatePreppedStmt(const std::string& query) { - return conn->compileStatement(query.c_str()); + return conn->compileStatement(query.c_str()); } diff --git a/dDatabase/CDClientDatabase.h b/dDatabase/CDClientDatabase.h index 91e9ee10..6b254ebb 100644 --- a/dDatabase/CDClientDatabase.h +++ b/dDatabase/CDClientDatabase.h @@ -13,10 +13,10 @@ #include #include -// Enable this to cache all entries in each table for fast access, comes with more memory cost -//#define CDCLIENT_CACHE_ALL + // Enable this to cache all entries in each table for fast access, comes with more memory cost + //#define CDCLIENT_CACHE_ALL -// Enable this to skip some unused columns in some tables + // Enable this to skip some unused columns in some tables #define UNUSED(v) /*! @@ -24,26 +24,26 @@ \brief An interface between the CDClient.sqlite file and the server */ -//! The CDClient Database namespace + //! The CDClient Database namespace namespace CDClientDatabase { - - //! Opens a connection with the CDClient - /*! - \param filename The filename - */ - void Connect(const std::string& filename); - - //! Queries the CDClient - /*! - \param query The query - \return The results of the query - */ - CppSQLite3Query ExecuteQuery(const std::string& query); - - //! Queries the CDClient and parses arguments - /*! - \param query The query with formatted arguments - \return prepared SQLite Statement - */ - CppSQLite3Statement CreatePreppedStmt(const std::string& query); + + //! Opens a connection with the CDClient + /*! + \param filename The filename + */ + void Connect(const std::string& filename); + + //! Queries the CDClient + /*! + \param query The query + \return The results of the query + */ + CppSQLite3Query ExecuteQuery(const std::string& query); + + //! Queries the CDClient and parses arguments + /*! + \param query The query with formatted arguments + \return prepared SQLite Statement + */ + CppSQLite3Statement CreatePreppedStmt(const std::string& query); }; diff --git a/dDatabase/CDClientManager.cpp b/dDatabase/CDClientManager.cpp index 75ada1ea..4b32e749 100644 --- a/dDatabase/CDClientManager.cpp +++ b/dDatabase/CDClientManager.cpp @@ -1,7 +1,7 @@ #include "CDClientManager.h" // Static Variables -CDClientManager * CDClientManager::m_Address = nullptr; +CDClientManager* CDClientManager::m_Address = nullptr; //! Initializes the manager void CDClientManager::Initialize(void) { diff --git a/dDatabase/CDClientManager.h b/dDatabase/CDClientManager.h index f4530f90..ea24a373 100644 --- a/dDatabase/CDClientManager.h +++ b/dDatabase/CDClientManager.h @@ -52,45 +52,45 @@ \brief A manager for the CDClient tables */ -//! Manages all data from the CDClient + //! Manages all data from the CDClient class CDClientManager { private: - static CDClientManager * m_Address; //!< The singleton address - - std::unordered_map tables; //!< The tables - + static CDClientManager* m_Address; //!< The singleton address + + std::unordered_map tables; //!< The tables + public: - - //! The singleton method - static CDClientManager * Instance() { - if (m_Address == 0) { - m_Address = new CDClientManager; - } - - return m_Address; - } - - //! Initializes the manager - void Initialize(void); - - //! Fetches a CDClient table - /*! - This function uses typename T which must be a subclass of CDTable. - It returns the class that conforms to the class name - - \param tableName The table name - \return The class or nullptr - */ - template - T * GetTable(const std::string& tableName) { - static_assert(std::is_base_of::value, "T should inherit from CDTable!"); - - for (auto itr = this->tables.begin(); itr != this->tables.end(); ++itr) { - if (itr->first == tableName) { - return dynamic_cast(itr->second); - } - } - - return nullptr; - } + + //! The singleton method + static CDClientManager* Instance() { + if (m_Address == 0) { + m_Address = new CDClientManager; + } + + return m_Address; + } + + //! Initializes the manager + void Initialize(void); + + //! Fetches a CDClient table + /*! + This function uses typename T which must be a subclass of CDTable. + It returns the class that conforms to the class name + + \param tableName The table name + \return The class or nullptr + */ + template + T* GetTable(const std::string& tableName) { + static_assert(std::is_base_of::value, "T should inherit from CDTable!"); + + for (auto itr = this->tables.begin(); itr != this->tables.end(); ++itr) { + if (itr->first == tableName) { + return dynamic_cast(itr->second); + } + } + + return nullptr; + } }; diff --git a/dDatabase/Database.cpp b/dDatabase/Database.cpp index 7ab7b752..f955bd43 100644 --- a/dDatabase/Database.cpp +++ b/dDatabase/Database.cpp @@ -6,8 +6,8 @@ using namespace std; #pragma warning (disable:4251) //Disables SQL warnings -sql::Driver * Database::driver; -sql::Connection * Database::con; +sql::Driver* Database::driver; +sql::Connection* Database::con; sql::Properties Database::props; std::string Database::database; @@ -66,8 +66,7 @@ sql::PreparedStatement* Database::CreatePreppedStmt(const std::string& query) { Game::logger->Log("Database", "Trying to reconnect to MySQL"); } - if (!con->isValid() || con->isClosed()) - { + if (!con->isValid() || con->isClosed()) { delete con; con = nullptr; @@ -83,4 +82,4 @@ sql::PreparedStatement* Database::CreatePreppedStmt(const std::string& query) { void Database::Commit() { Database::con->commit(); -} \ No newline at end of file +} diff --git a/dDatabase/Database.h b/dDatabase/Database.h index ece62a95..a15ba856 100644 --- a/dDatabase/Database.h +++ b/dDatabase/Database.h @@ -11,8 +11,8 @@ public: class Database { private: - static sql::Driver *driver; - static sql::Connection *con; + static sql::Driver* driver; + static sql::Connection* con; static sql::Properties props; static std::string database; public: diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index a988acac..30a63896 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -9,70 +9,69 @@ void MigrationRunner::RunMigrations() { auto stmt = Database::CreatePreppedStmt("CREATE TABLE IF NOT EXISTS migration_history (name TEXT NOT NULL, date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP());"); stmt->executeQuery(); - delete stmt; + delete stmt; - sql::SQLString finalSQL = ""; - Migration checkMigration{}; + sql::SQLString finalSQL = ""; + Migration checkMigration{}; - for (const auto& entry : GeneralUtils::GetFileNamesFromFolder("./migrations/")) { - auto migration = LoadMigration(entry); + for (const auto& entry : GeneralUtils::GetFileNamesFromFolder("./migrations/")) { + auto migration = LoadMigration(entry); - if (migration.data.empty()) { - continue; - } + if (migration.data.empty()) { + continue; + } - checkMigration = migration; + checkMigration = migration; - stmt = Database::CreatePreppedStmt("SELECT name FROM migration_history WHERE name = ?;"); - stmt->setString(1, migration.name); - auto res = stmt->executeQuery(); - bool doExit = res->next(); - delete res; - delete stmt; - if (doExit) continue; + stmt = Database::CreatePreppedStmt("SELECT name FROM migration_history WHERE name = ?;"); + stmt->setString(1, migration.name); + auto res = stmt->executeQuery(); + bool doExit = res->next(); + delete res; + delete stmt; + if (doExit) continue; - Game::logger->Log("MigrationRunner", "Running migration: %s", migration.name.c_str()); + Game::logger->Log("MigrationRunner", "Running migration: %s", migration.name.c_str()); - finalSQL.append(migration.data); - finalSQL.append('\n'); + finalSQL.append(migration.data); + finalSQL.append('\n'); - stmt = Database::CreatePreppedStmt("INSERT INTO migration_history (name) VALUES (?);"); - stmt->setString(1, entry); - stmt->execute(); - delete stmt; - } + stmt = Database::CreatePreppedStmt("INSERT INTO migration_history (name) VALUES (?);"); + stmt->setString(1, entry); + stmt->execute(); + delete stmt; + } - if (!finalSQL.empty()) { - try { - auto simpleStatement = Database::CreateStmt(); - simpleStatement->execute(finalSQL); - delete simpleStatement; - } - catch (sql::SQLException e) { - Game::logger->Log("MigrationRunner", "Encountered error running migration: %s", e.what()); - } - } + if (!finalSQL.empty()) { + try { + auto simpleStatement = Database::CreateStmt(); + simpleStatement->execute(finalSQL); + delete simpleStatement; + } catch (sql::SQLException e) { + Game::logger->Log("MigrationRunner", "Encountered error running migration: %s", e.what()); + } + } } Migration MigrationRunner::LoadMigration(std::string path) { - Migration migration{}; - std::ifstream file("./migrations/" + path); + Migration migration{}; + std::ifstream file("./migrations/" + path); - if (file.is_open()) { - std::hash hash; + if (file.is_open()) { + std::hash hash; - std::string line; - std::string total = ""; + std::string line; + std::string total = ""; - while (std::getline(file, line)) { - total += line; - } + while (std::getline(file, line)) { + total += line; + } - file.close(); + file.close(); - migration.name = path; - migration.data = total; - } + migration.name = path; + migration.data = total; + } - return migration; + return migration; } diff --git a/dDatabase/MigrationRunner.h b/dDatabase/MigrationRunner.h index 343b252d..f5d1325a 100644 --- a/dDatabase/MigrationRunner.h +++ b/dDatabase/MigrationRunner.h @@ -16,4 +16,4 @@ class MigrationRunner { public: static void RunMigrations(); static Migration LoadMigration(std::string path); -}; \ No newline at end of file +}; diff --git a/dDatabase/Tables/CDActivitiesTable.cpp b/dDatabase/Tables/CDActivitiesTable.cpp index daa07b52..835ca3d2 100644 --- a/dDatabase/Tables/CDActivitiesTable.cpp +++ b/dDatabase/Tables/CDActivitiesTable.cpp @@ -49,7 +49,7 @@ CDActivitiesTable::CDActivitiesTable(void) { } //! Destructor -CDActivitiesTable::~CDActivitiesTable(void) { } +CDActivitiesTable::~CDActivitiesTable(void) {} //! Returns the table's name std::string CDActivitiesTable::GetName(void) const { diff --git a/dDatabase/Tables/CDActivityRewardsTable.cpp b/dDatabase/Tables/CDActivityRewardsTable.cpp index 03424de3..f1719204 100644 --- a/dDatabase/Tables/CDActivityRewardsTable.cpp +++ b/dDatabase/Tables/CDActivityRewardsTable.cpp @@ -2,59 +2,59 @@ //! Constructor CDActivityRewardsTable::CDActivityRewardsTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ActivityRewards"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ActivityRewards"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ActivityRewards"); - while (!tableData.eof()) { - CDActivityRewards entry; - entry.objectTemplate = tableData.getIntField(0, -1); - entry.ActivityRewardIndex = tableData.getIntField(1, -1); - entry.activityRating = tableData.getIntField(2, -1); - entry.LootMatrixIndex = tableData.getIntField(3, -1); - entry.CurrencyIndex = tableData.getIntField(4, -1); - entry.ChallengeRating = tableData.getIntField(5, -1); - entry.description = tableData.getStringField(6, ""); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ActivityRewards"); + while (!tableData.eof()) { + CDActivityRewards entry; + entry.objectTemplate = tableData.getIntField(0, -1); + entry.ActivityRewardIndex = tableData.getIntField(1, -1); + entry.activityRating = tableData.getIntField(2, -1); + entry.LootMatrixIndex = tableData.getIntField(3, -1); + entry.CurrencyIndex = tableData.getIntField(4, -1); + entry.ChallengeRating = tableData.getIntField(5, -1); + entry.description = tableData.getStringField(6, ""); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDActivityRewardsTable::~CDActivityRewardsTable(void) { } +CDActivityRewardsTable::~CDActivityRewardsTable(void) {} //! Returns the table's name std::string CDActivityRewardsTable::GetName(void) const { - return "ActivityRewards"; + return "ActivityRewards"; } //! Queries the table with a custom "where" clause std::vector CDActivityRewardsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDActivityRewardsTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDActivityRewardsTable.h b/dDatabase/Tables/CDActivityRewardsTable.h index fb3a5b09..7f1e81a0 100644 --- a/dDatabase/Tables/CDActivityRewardsTable.h +++ b/dDatabase/Tables/CDActivityRewardsTable.h @@ -8,47 +8,47 @@ \brief Contains data for the ActivityRewards table */ -//! ActivityRewards Entry Struct + //! ActivityRewards Entry Struct struct CDActivityRewards { - unsigned int objectTemplate; //!< The object template (?) - unsigned int ActivityRewardIndex; //!< The activity reward index - int activityRating; //!< The activity rating - unsigned int LootMatrixIndex; //!< The loot matrix index - unsigned int CurrencyIndex; //!< The currency index - unsigned int ChallengeRating; //!< The challenge rating - std::string description; //!< The description + unsigned int objectTemplate; //!< The object template (?) + unsigned int ActivityRewardIndex; //!< The activity reward index + int activityRating; //!< The activity rating + unsigned int LootMatrixIndex; //!< The loot matrix index + unsigned int CurrencyIndex; //!< The currency index + unsigned int ChallengeRating; //!< The challenge rating + std::string description; //!< The description }; //! ActivityRewards table class CDActivityRewardsTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDActivityRewardsTable(void); - - //! Destructor - ~CDActivityRewardsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDActivityRewardsTable(void); + + //! Destructor + ~CDActivityRewardsTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDAnimationsTable.cpp b/dDatabase/Tables/CDAnimationsTable.cpp index 7056f710..399804f8 100644 --- a/dDatabase/Tables/CDAnimationsTable.cpp +++ b/dDatabase/Tables/CDAnimationsTable.cpp @@ -2,65 +2,65 @@ //! Constructor CDAnimationsTable::CDAnimationsTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Animations"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Animations"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Animations"); - while (!tableData.eof()) { - CDAnimations entry; - entry.animationGroupID = tableData.getIntField(0, -1); - entry.animation_type = tableData.getStringField(1, ""); - entry.animation_name = tableData.getStringField(2, ""); - entry.chance_to_play = tableData.getFloatField(3, -1.0f); - entry.min_loops = tableData.getIntField(4, -1); - entry.max_loops = tableData.getIntField(5, -1); - entry.animation_length = tableData.getFloatField(6, -1.0f); - entry.hideEquip = tableData.getIntField(7, -1) == 1 ? true : false; - entry.ignoreUpperBody = tableData.getIntField(8, -1) == 1 ? true : false; - entry.restartable = tableData.getIntField(9, -1) == 1 ? true : false; - entry.face_animation_name = tableData.getStringField(10, ""); - entry.priority = tableData.getFloatField(11, -1.0f); - entry.blendTime = tableData.getFloatField(12, -1.0f); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Animations"); + while (!tableData.eof()) { + CDAnimations entry; + entry.animationGroupID = tableData.getIntField(0, -1); + entry.animation_type = tableData.getStringField(1, ""); + entry.animation_name = tableData.getStringField(2, ""); + entry.chance_to_play = tableData.getFloatField(3, -1.0f); + entry.min_loops = tableData.getIntField(4, -1); + entry.max_loops = tableData.getIntField(5, -1); + entry.animation_length = tableData.getFloatField(6, -1.0f); + entry.hideEquip = tableData.getIntField(7, -1) == 1 ? true : false; + entry.ignoreUpperBody = tableData.getIntField(8, -1) == 1 ? true : false; + entry.restartable = tableData.getIntField(9, -1) == 1 ? true : false; + entry.face_animation_name = tableData.getStringField(10, ""); + entry.priority = tableData.getFloatField(11, -1.0f); + entry.blendTime = tableData.getFloatField(12, -1.0f); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDAnimationsTable::~CDAnimationsTable(void) { } +CDAnimationsTable::~CDAnimationsTable(void) {} //! Returns the table's name std::string CDAnimationsTable::GetName(void) const { - return "Animations"; + return "Animations"; } //! Queries the table with a custom "where" clause std::vector CDAnimationsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDAnimationsTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDAnimationsTable.h b/dDatabase/Tables/CDAnimationsTable.h index 61638f74..24112985 100644 --- a/dDatabase/Tables/CDAnimationsTable.h +++ b/dDatabase/Tables/CDAnimationsTable.h @@ -8,53 +8,53 @@ \brief Contains data for the Animations table */ -//! Animations Entry Struct + //! Animations Entry Struct struct CDAnimations { - unsigned int animationGroupID; //!< The animation group ID - std::string animation_type; //!< The animation type - std::string animation_name; //!< The animation name - float chance_to_play; //!< The chance to play the animation - unsigned int min_loops; //!< The minimum number of loops - unsigned int max_loops; //!< The maximum number of loops - float animation_length; //!< The animation length - bool hideEquip; //!< Whether or not to hide the equip - bool ignoreUpperBody; //!< Whether or not to ignore the upper body - bool restartable; //!< Whether or not the animation is restartable - std::string face_animation_name; //!< The face animation name - float priority; //!< The priority - float blendTime; //!< The blend time + unsigned int animationGroupID; //!< The animation group ID + std::string animation_type; //!< The animation type + std::string animation_name; //!< The animation name + float chance_to_play; //!< The chance to play the animation + unsigned int min_loops; //!< The minimum number of loops + unsigned int max_loops; //!< The maximum number of loops + float animation_length; //!< The animation length + bool hideEquip; //!< Whether or not to hide the equip + bool ignoreUpperBody; //!< Whether or not to ignore the upper body + bool restartable; //!< Whether or not the animation is restartable + std::string face_animation_name; //!< The face animation name + float priority; //!< The priority + float blendTime; //!< The blend time }; //! Animations table class CDAnimationsTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDAnimationsTable(void); - - //! Destructor - ~CDAnimationsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDAnimationsTable(void); + + //! Destructor + ~CDAnimationsTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDBehaviorParameterTable.cpp b/dDatabase/Tables/CDBehaviorParameterTable.cpp index 05f39016..96015896 100644 --- a/dDatabase/Tables/CDBehaviorParameterTable.cpp +++ b/dDatabase/Tables/CDBehaviorParameterTable.cpp @@ -31,15 +31,14 @@ CDBehaviorParameterTable::CDBehaviorParameterTable(void) { } //! Destructor -CDBehaviorParameterTable::~CDBehaviorParameterTable(void) { } +CDBehaviorParameterTable::~CDBehaviorParameterTable(void) {} //! Returns the table's name std::string CDBehaviorParameterTable::GetName(void) const { return "BehaviorParameter"; } -CDBehaviorParameter CDBehaviorParameterTable::GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue) -{ +CDBehaviorParameter CDBehaviorParameterTable::GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue) { CDBehaviorParameter returnValue; returnValue.behaviorID = 0; returnValue.parameterID = m_ParametersList.end(); diff --git a/dDatabase/Tables/CDBehaviorParameterTable.h b/dDatabase/Tables/CDBehaviorParameterTable.h index c45d287b..f067e7d2 100644 --- a/dDatabase/Tables/CDBehaviorParameterTable.h +++ b/dDatabase/Tables/CDBehaviorParameterTable.h @@ -10,11 +10,11 @@ \brief Contains data for the BehaviorParameter table */ -//! BehaviorParameter Entry Struct + //! BehaviorParameter Entry Struct struct CDBehaviorParameter { - unsigned int behaviorID; //!< The Behavior ID - std::unordered_set::iterator parameterID; //!< The Parameter ID - float value; //!< The value of the behavior template + unsigned int behaviorID; //!< The Behavior ID + std::unordered_set::iterator parameterID; //!< The Parameter ID + float value; //!< The value of the behavior template }; //! BehaviorParameter table @@ -23,19 +23,19 @@ private: std::unordered_map m_Entries; std::unordered_set m_ParametersList; public: - - //! Constructor - CDBehaviorParameterTable(void); - - //! Destructor - ~CDBehaviorParameterTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - + + //! Constructor + CDBehaviorParameterTable(void); + + //! Destructor + ~CDBehaviorParameterTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + CDBehaviorParameter GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue = 0); std::map GetParametersByBehaviorID(uint32_t behaviorID); diff --git a/dDatabase/Tables/CDBehaviorTemplateTable.cpp b/dDatabase/Tables/CDBehaviorTemplateTable.cpp index b832400d..1628756f 100644 --- a/dDatabase/Tables/CDBehaviorTemplateTable.cpp +++ b/dDatabase/Tables/CDBehaviorTemplateTable.cpp @@ -2,76 +2,76 @@ //! Constructor CDBehaviorTemplateTable::CDBehaviorTemplateTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM BehaviorTemplate"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - - tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorTemplate"); - while (!tableData.eof()) { - CDBehaviorTemplate entry; - entry.behaviorID = tableData.getIntField(0, -1); - entry.templateID = tableData.getIntField(1, -1); - entry.effectID = tableData.getIntField(2, -1); - auto candidateToAdd = tableData.getStringField(3, ""); - auto parameter = m_EffectHandles.find(candidateToAdd); - if (parameter != m_EffectHandles.end()) { - entry.effectHandle = parameter; - } else { - entry.effectHandle = m_EffectHandles.insert(candidateToAdd).first; - } - - this->entries.push_back(entry); - this->entriesMappedByBehaviorID.insert(std::make_pair(entry.behaviorID, entry)); - tableData.nextRow(); - } + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM BehaviorTemplate"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + + tableSize.finalize(); + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorTemplate"); + while (!tableData.eof()) { + CDBehaviorTemplate entry; + entry.behaviorID = tableData.getIntField(0, -1); + entry.templateID = tableData.getIntField(1, -1); + entry.effectID = tableData.getIntField(2, -1); + auto candidateToAdd = tableData.getStringField(3, ""); + auto parameter = m_EffectHandles.find(candidateToAdd); + if (parameter != m_EffectHandles.end()) { + entry.effectHandle = parameter; + } else { + entry.effectHandle = m_EffectHandles.insert(candidateToAdd).first; + } + + this->entries.push_back(entry); + this->entriesMappedByBehaviorID.insert(std::make_pair(entry.behaviorID, entry)); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDBehaviorTemplateTable::~CDBehaviorTemplateTable(void) { } +CDBehaviorTemplateTable::~CDBehaviorTemplateTable(void) {} //! Returns the table's name std::string CDBehaviorTemplateTable::GetName(void) const { - return "BehaviorTemplate"; + return "BehaviorTemplate"; } //! Queries the table with a custom "where" clause std::vector CDBehaviorTemplateTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDBehaviorTemplateTable::GetEntries(void) const { - return this->entries; + return this->entries; } const CDBehaviorTemplate CDBehaviorTemplateTable::GetByBehaviorID(uint32_t behaviorID) { - auto entry = this->entriesMappedByBehaviorID.find(behaviorID); - if (entry == this->entriesMappedByBehaviorID.end()) { - CDBehaviorTemplate entryToReturn; - entryToReturn.behaviorID = 0; - entryToReturn.effectHandle = m_EffectHandles.end(); - entryToReturn.effectID = 0; - return entryToReturn; - } else { - return entry->second; - } + auto entry = this->entriesMappedByBehaviorID.find(behaviorID); + if (entry == this->entriesMappedByBehaviorID.end()) { + CDBehaviorTemplate entryToReturn; + entryToReturn.behaviorID = 0; + entryToReturn.effectHandle = m_EffectHandles.end(); + entryToReturn.effectID = 0; + return entryToReturn; + } else { + return entry->second; + } } diff --git a/dDatabase/Tables/CDBehaviorTemplateTable.h b/dDatabase/Tables/CDBehaviorTemplateTable.h index 170da854..b2bd2521 100644 --- a/dDatabase/Tables/CDBehaviorTemplateTable.h +++ b/dDatabase/Tables/CDBehaviorTemplateTable.h @@ -10,46 +10,46 @@ \brief Contains data for the BehaviorTemplate table */ -//! BehaviorTemplate Entry Struct + //! BehaviorTemplate Entry Struct struct CDBehaviorTemplate { - unsigned int behaviorID; //!< The Behavior ID - unsigned int templateID; //!< The Template ID (LOT) - unsigned int effectID; //!< The Effect ID attached - std::unordered_set::iterator effectHandle; //!< The effect handle + unsigned int behaviorID; //!< The Behavior ID + unsigned int templateID; //!< The Template ID (LOT) + unsigned int effectID; //!< The Effect ID attached + std::unordered_set::iterator effectHandle; //!< The effect handle }; //! BehaviorTemplate table class CDBehaviorTemplateTable : public CDTable { private: - std::vector entries; - std::unordered_map entriesMappedByBehaviorID; - std::unordered_set m_EffectHandles; + std::vector entries; + std::unordered_map entriesMappedByBehaviorID; + std::unordered_set m_EffectHandles; public: - - //! Constructor - CDBehaviorTemplateTable(void); - - //! Destructor - ~CDBehaviorTemplateTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - const CDBehaviorTemplate GetByBehaviorID(uint32_t behaviorID); + //! Constructor + CDBehaviorTemplateTable(void); + + //! Destructor + ~CDBehaviorTemplateTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + + const CDBehaviorTemplate GetByBehaviorID(uint32_t behaviorID); }; diff --git a/dDatabase/Tables/CDBrickIDTableTable.cpp b/dDatabase/Tables/CDBrickIDTableTable.cpp index a3fc860e..9dbdf2c0 100644 --- a/dDatabase/Tables/CDBrickIDTableTable.cpp +++ b/dDatabase/Tables/CDBrickIDTableTable.cpp @@ -11,9 +11,9 @@ CDBrickIDTableTable::CDBrickIDTableTable(void) { tableSize.nextRow(); } - + tableSize.finalize(); - + // Reserve the size this->entries.reserve(size); @@ -32,7 +32,7 @@ CDBrickIDTableTable::CDBrickIDTableTable(void) { } //! Destructor -CDBrickIDTableTable::~CDBrickIDTableTable(void) { } +CDBrickIDTableTable::~CDBrickIDTableTable(void) {} //! Returns the table's name std::string CDBrickIDTableTable::GetName(void) const { diff --git a/dDatabase/Tables/CDComponentsRegistryTable.cpp b/dDatabase/Tables/CDComponentsRegistryTable.cpp index 7e746fb0..8e5ae108 100644 --- a/dDatabase/Tables/CDComponentsRegistryTable.cpp +++ b/dDatabase/Tables/CDComponentsRegistryTable.cpp @@ -4,33 +4,33 @@ //! Constructor CDComponentsRegistryTable::CDComponentsRegistryTable(void) { - -#ifdef CDCLIENT_CACHE_ALL - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ComponentsRegistry"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - - tableSize.finalize(); - - // Reserve the size - //this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ComponentsRegistry"); - while (!tableData.eof()) { - CDComponentsRegistry entry; - entry.id = tableData.getIntField(0, -1); - entry.component_type = tableData.getIntField(1, -1); - entry.component_id = tableData.getIntField(2, -1); - this->mappedEntries.insert_or_assign(((uint64_t) entry.component_type) << 32 | ((uint64_t) entry.id), entry.component_id); - - //this->entries.push_back(entry); +#ifdef CDCLIENT_CACHE_ALL + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ComponentsRegistry"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + + tableSize.finalize(); + + // Reserve the size + //this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ComponentsRegistry"); + while (!tableData.eof()) { + CDComponentsRegistry entry; + entry.id = tableData.getIntField(0, -1); + entry.component_type = tableData.getIntField(1, -1); + entry.component_id = tableData.getIntField(2, -1); + + this->mappedEntries.insert_or_assign(((uint64_t)entry.component_type) << 32 | ((uint64_t)entry.id), entry.component_id); + + //this->entries.push_back(entry); /* //Darwin's stuff: @@ -48,27 +48,25 @@ CDComponentsRegistryTable::CDComponentsRegistryTable(void) { } */ - tableData.nextRow(); - } + tableData.nextRow(); + } tableData.finalize(); #endif } //! Destructor -CDComponentsRegistryTable::~CDComponentsRegistryTable(void) { } +CDComponentsRegistryTable::~CDComponentsRegistryTable(void) {} //! Returns the table's name std::string CDComponentsRegistryTable::GetName(void) const { - return "ComponentsRegistry"; + return "ComponentsRegistry"; } -int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, uint32_t componentType, int32_t defaultValue) -{ - const auto& iter = this->mappedEntries.find(((uint64_t) componentType) << 32 | ((uint64_t) id)); +int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, uint32_t componentType, int32_t defaultValue) { + const auto& iter = this->mappedEntries.find(((uint64_t)componentType) << 32 | ((uint64_t)id)); - if (iter == this->mappedEntries.end()) - { + if (iter == this->mappedEntries.end()) { return defaultValue; } @@ -85,19 +83,19 @@ int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, uint32_t componen */ #ifndef CDCLIENT_CACHE_ALL - // Now get the data + // Now get the data std::stringstream query; query << "SELECT * FROM ComponentsRegistry WHERE id = " << std::to_string(id); auto tableData = CDClientDatabase::ExecuteQuery(query.str()); - while (!tableData.eof()) { - CDComponentsRegistry entry; - entry.id = tableData.getIntField(0, -1); - entry.component_type = tableData.getIntField(1, -1); - entry.component_id = tableData.getIntField(2, -1); - - //this->entries.push_back(entry); + while (!tableData.eof()) { + CDComponentsRegistry entry; + entry.id = tableData.getIntField(0, -1); + entry.component_type = tableData.getIntField(1, -1); + entry.component_id = tableData.getIntField(2, -1); + + //this->entries.push_back(entry); //Darwin's stuff: const auto& it = this->mappedEntries.find(entry.id); @@ -106,15 +104,14 @@ int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, uint32_t componen if (iter == it->second.end()) { it->second.insert(std::make_pair(entry.component_type, entry.component_id)); } - } - else { + } else { std::map map; map.insert(std::make_pair(entry.component_type, entry.component_id)); this->mappedEntries.insert(std::make_pair(entry.id, map)); } - tableData.nextRow(); - } + tableData.nextRow(); + } tableData.finalize(); diff --git a/dDatabase/Tables/CDComponentsRegistryTable.h b/dDatabase/Tables/CDComponentsRegistryTable.h index 4a02bf94..c3eb0ed2 100644 --- a/dDatabase/Tables/CDComponentsRegistryTable.h +++ b/dDatabase/Tables/CDComponentsRegistryTable.h @@ -8,33 +8,33 @@ \brief Contains data for the ComponentsRegistry table */ -//! ComponentsRegistry Entry Struct + //! ComponentsRegistry Entry Struct struct CDComponentsRegistry { - unsigned int id; //!< The LOT is used as the ID - unsigned int component_type; //!< See ComponentTypes enum for values - unsigned int component_id; //!< The ID used within the component's table (0 may either mean it's non-networked, or that the ID is actually 0 + unsigned int id; //!< The LOT is used as the ID + unsigned int component_type; //!< See ComponentTypes enum for values + unsigned int component_id; //!< The ID used within the component's table (0 may either mean it's non-networked, or that the ID is actually 0 }; //! ComponentsRegistry table class CDComponentsRegistryTable : public CDTable { private: - //std::vector entries; - std::map mappedEntries; //id, component_type, component_id - -public: - - //! Constructor - CDComponentsRegistryTable(void); - - //! Destructor - ~CDComponentsRegistryTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; + //std::vector entries; + std::map mappedEntries; //id, component_type, component_id - int32_t GetByIDAndType(uint32_t id, uint32_t componentType, int32_t defaultValue = 0); +public: + + //! Constructor + CDComponentsRegistryTable(void); + + //! Destructor + ~CDComponentsRegistryTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + int32_t GetByIDAndType(uint32_t id, uint32_t componentType, int32_t defaultValue = 0); }; diff --git a/dDatabase/Tables/CDCurrencyTableTable.cpp b/dDatabase/Tables/CDCurrencyTableTable.cpp index cfe26e73..a1923a73 100644 --- a/dDatabase/Tables/CDCurrencyTableTable.cpp +++ b/dDatabase/Tables/CDCurrencyTableTable.cpp @@ -2,57 +2,57 @@ //! Constructor CDCurrencyTableTable::CDCurrencyTableTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM CurrencyTable"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM CurrencyTable"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM CurrencyTable"); - while (!tableData.eof()) { - CDCurrencyTable entry; - entry.currencyIndex = tableData.getIntField(0, -1); - entry.npcminlevel = tableData.getIntField(1, -1); - entry.minvalue = tableData.getIntField(2, -1); - entry.maxvalue = tableData.getIntField(3, -1); - entry.id = tableData.getIntField(4, -1); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM CurrencyTable"); + while (!tableData.eof()) { + CDCurrencyTable entry; + entry.currencyIndex = tableData.getIntField(0, -1); + entry.npcminlevel = tableData.getIntField(1, -1); + entry.minvalue = tableData.getIntField(2, -1); + entry.maxvalue = tableData.getIntField(3, -1); + entry.id = tableData.getIntField(4, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDCurrencyTableTable::~CDCurrencyTableTable(void) { } +CDCurrencyTableTable::~CDCurrencyTableTable(void) {} //! Returns the table's name std::string CDCurrencyTableTable::GetName(void) const { - return "CurrencyTable"; + return "CurrencyTable"; } //! Queries the table with a custom "where" clause std::vector CDCurrencyTableTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDCurrencyTableTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDCurrencyTableTable.h b/dDatabase/Tables/CDCurrencyTableTable.h index b980a18a..5a856395 100644 --- a/dDatabase/Tables/CDCurrencyTableTable.h +++ b/dDatabase/Tables/CDCurrencyTableTable.h @@ -8,44 +8,44 @@ \brief Contains data for the CurrencyTable table */ -//! CurrencyTable Struct + //! CurrencyTable Struct struct CDCurrencyTable { - unsigned int currencyIndex; //!< The Currency Index - unsigned int npcminlevel; //!< The minimum level of the npc - unsigned int minvalue; //!< The minimum currency - unsigned int maxvalue; //!< The maximum currency - unsigned int id; //!< The ID of the currency index + unsigned int currencyIndex; //!< The Currency Index + unsigned int npcminlevel; //!< The minimum level of the npc + unsigned int minvalue; //!< The minimum currency + unsigned int maxvalue; //!< The maximum currency + unsigned int id; //!< The ID of the currency index }; //! CurrencyTable table class CDCurrencyTableTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDCurrencyTableTable(void); - - //! Destructor - ~CDCurrencyTableTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDCurrencyTableTable(void); + + //! Destructor + ~CDCurrencyTableTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDDestructibleComponentTable.cpp b/dDatabase/Tables/CDDestructibleComponentTable.cpp index 6eb64e7f..d7438fc7 100644 --- a/dDatabase/Tables/CDDestructibleComponentTable.cpp +++ b/dDatabase/Tables/CDDestructibleComponentTable.cpp @@ -2,66 +2,66 @@ //! Constructor CDDestructibleComponentTable::CDDestructibleComponentTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM DestructibleComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM DestructibleComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM DestructibleComponent"); - while (!tableData.eof()) { - CDDestructibleComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.faction = tableData.getIntField(1, -1); - entry.factionList = tableData.getStringField(2, ""); - entry.life = tableData.getIntField(3, -1); - entry.imagination = tableData.getIntField(4, -1); - entry.LootMatrixIndex = tableData.getIntField(5, -1); - entry.CurrencyIndex = tableData.getIntField(6, -1); - entry.level = tableData.getIntField(7, -1); - entry.armor = tableData.getFloatField(8, -1.0f); - entry.death_behavior = tableData.getIntField(9, -1); - entry.isnpc = tableData.getIntField(10, -1) == 1 ? true : false; - entry.attack_priority = tableData.getIntField(11, -1); - entry.isSmashable = tableData.getIntField(12, -1) == 1 ? true : false; - entry.difficultyLevel = tableData.getIntField(13, -1); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM DestructibleComponent"); + while (!tableData.eof()) { + CDDestructibleComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.faction = tableData.getIntField(1, -1); + entry.factionList = tableData.getStringField(2, ""); + entry.life = tableData.getIntField(3, -1); + entry.imagination = tableData.getIntField(4, -1); + entry.LootMatrixIndex = tableData.getIntField(5, -1); + entry.CurrencyIndex = tableData.getIntField(6, -1); + entry.level = tableData.getIntField(7, -1); + entry.armor = tableData.getFloatField(8, -1.0f); + entry.death_behavior = tableData.getIntField(9, -1); + entry.isnpc = tableData.getIntField(10, -1) == 1 ? true : false; + entry.attack_priority = tableData.getIntField(11, -1); + entry.isSmashable = tableData.getIntField(12, -1) == 1 ? true : false; + entry.difficultyLevel = tableData.getIntField(13, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDDestructibleComponentTable::~CDDestructibleComponentTable(void) { } +CDDestructibleComponentTable::~CDDestructibleComponentTable(void) {} //! Returns the table's name std::string CDDestructibleComponentTable::GetName(void) const { - return "DestructibleComponent"; + return "DestructibleComponent"; } //! Queries the table with a custom "where" clause std::vector CDDestructibleComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDDestructibleComponentTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDDestructibleComponentTable.h b/dDatabase/Tables/CDDestructibleComponentTable.h index 9768b6df..e89bbff8 100644 --- a/dDatabase/Tables/CDDestructibleComponentTable.h +++ b/dDatabase/Tables/CDDestructibleComponentTable.h @@ -8,53 +8,53 @@ \brief Contains data for the DestructibleComponent table */ -//! ItemComponent Struct + //! ItemComponent Struct struct CDDestructibleComponent { - unsigned int id; //!< The component ID from the ComponentsRegistry Table - int faction; //!< The Faction ID of the object - std::string factionList; //!< A list of the faction IDs - int life; //!< The amount of life of the object - unsigned int imagination; //!< The amount of imagination of the object - int LootMatrixIndex; //!< The Loot Matrix Index - int CurrencyIndex; //!< The Currency Index - unsigned int level; //!< ??? - float armor; //!< The amount of armor of the object - unsigned int death_behavior; //!< The behavior ID of the death behavior - bool isnpc; //!< Whether or not the object is an NPC - unsigned int attack_priority; //!< ??? - bool isSmashable; //!< Whether or not the object is smashable - int difficultyLevel; //!< ??? + unsigned int id; //!< The component ID from the ComponentsRegistry Table + int faction; //!< The Faction ID of the object + std::string factionList; //!< A list of the faction IDs + int life; //!< The amount of life of the object + unsigned int imagination; //!< The amount of imagination of the object + int LootMatrixIndex; //!< The Loot Matrix Index + int CurrencyIndex; //!< The Currency Index + unsigned int level; //!< ??? + float armor; //!< The amount of armor of the object + unsigned int death_behavior; //!< The behavior ID of the death behavior + bool isnpc; //!< Whether or not the object is an NPC + unsigned int attack_priority; //!< ??? + bool isSmashable; //!< Whether or not the object is smashable + int difficultyLevel; //!< ??? }; //! ItemComponent table class CDDestructibleComponentTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDDestructibleComponentTable(void); - - //! Destructor - ~CDDestructibleComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDDestructibleComponentTable(void); + + //! Destructor + ~CDDestructibleComponentTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDEmoteTable.cpp b/dDatabase/Tables/CDEmoteTable.cpp index 63e985ee..e3898422 100644 --- a/dDatabase/Tables/CDEmoteTable.cpp +++ b/dDatabase/Tables/CDEmoteTable.cpp @@ -2,43 +2,43 @@ //! Constructor CDEmoteTableTable::CDEmoteTableTable(void) { - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Emotes"); - while (!tableData.eof()) { - CDEmoteTable* entry = new CDEmoteTable(); - entry->ID = tableData.getIntField(0, -1); - entry->animationName = tableData.getStringField(1, ""); - entry->iconFilename = tableData.getStringField(2, ""); - entry->channel = tableData.getIntField(3, -1); - entry->locked = tableData.getIntField(5, -1) != 0; - entry->localize = tableData.getIntField(6, -1) != 0; - entry->locState = tableData.getIntField(7, -1); - entry->gateVersion = tableData.getIntField(8, -1); + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Emotes"); + while (!tableData.eof()) { + CDEmoteTable* entry = new CDEmoteTable(); + entry->ID = tableData.getIntField(0, -1); + entry->animationName = tableData.getStringField(1, ""); + entry->iconFilename = tableData.getStringField(2, ""); + entry->channel = tableData.getIntField(3, -1); + entry->locked = tableData.getIntField(5, -1) != 0; + entry->localize = tableData.getIntField(6, -1) != 0; + entry->locState = tableData.getIntField(7, -1); + entry->gateVersion = tableData.getIntField(8, -1); - entries.insert(std::make_pair(entry->ID, entry)); - tableData.nextRow(); - } + entries.insert(std::make_pair(entry->ID, entry)); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor CDEmoteTableTable::~CDEmoteTableTable(void) { - for (auto e : entries) { - if (e.second) delete e.second; - } - - entries.clear(); + for (auto e : entries) { + if (e.second) delete e.second; + } + + entries.clear(); } //! Returns the table's name std::string CDEmoteTableTable::GetName(void) const { - return "Emotes"; + return "Emotes"; } -CDEmoteTable * CDEmoteTableTable::GetEmote(int id) { - for (auto e : entries) { - if (e.first == id) return e.second; - } - - return nullptr; +CDEmoteTable* CDEmoteTableTable::GetEmote(int id) { + for (auto e : entries) { + if (e.first == id) return e.second; + } + + return nullptr; } diff --git a/dDatabase/Tables/CDEmoteTable.h b/dDatabase/Tables/CDEmoteTable.h index 9fd19991..a22ae23e 100644 --- a/dDatabase/Tables/CDEmoteTable.h +++ b/dDatabase/Tables/CDEmoteTable.h @@ -9,7 +9,7 @@ \brief Contains data for the CDEmoteTable table */ -//! CDEmoteEntry Struct + //! CDEmoteEntry Struct struct CDEmoteTable { CDEmoteTable() { ID = -1; @@ -22,35 +22,35 @@ struct CDEmoteTable { gateVersion = -1; } - int ID; - std::string animationName; - std::string iconFilename; - int locState; - int channel; - bool locked; - bool localize; - int gateVersion; + int ID; + std::string animationName; + std::string iconFilename; + int locState; + int channel; + bool locked; + bool localize; + int gateVersion; }; //! CDEmoteTable table class CDEmoteTableTable : public CDTable { private: - std::map entries; + std::map entries; public: - //! Constructor - CDEmoteTableTable(void); + //! Constructor + CDEmoteTableTable(void); - //! Destructor - ~CDEmoteTableTable(void); + //! Destructor + ~CDEmoteTableTable(void); - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Returns an emote by ID - CDEmoteTable* GetEmote(int id); + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Returns an emote by ID + CDEmoteTable* GetEmote(int id); }; diff --git a/dDatabase/Tables/CDFeatureGatingTable.cpp b/dDatabase/Tables/CDFeatureGatingTable.cpp index 6a370e8b..dfc65387 100644 --- a/dDatabase/Tables/CDFeatureGatingTable.cpp +++ b/dDatabase/Tables/CDFeatureGatingTable.cpp @@ -2,70 +2,67 @@ //! Constructor CDFeatureGatingTable::CDFeatureGatingTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM FeatureGating"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM FeatureGating"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM FeatureGating"); - while (!tableData.eof()) { - CDFeatureGating entry; - entry.featureName = tableData.getStringField(0, ""); - entry.major = tableData.getIntField(1, -1); - entry.current = tableData.getIntField(2, -1); - entry.minor = tableData.getIntField(3, -1); - entry.description = tableData.getStringField(4, ""); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM FeatureGating"); + while (!tableData.eof()) { + CDFeatureGating entry; + entry.featureName = tableData.getStringField(0, ""); + entry.major = tableData.getIntField(1, -1); + entry.current = tableData.getIntField(2, -1); + entry.minor = tableData.getIntField(3, -1); + entry.description = tableData.getStringField(4, ""); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDFeatureGatingTable::~CDFeatureGatingTable(void) { } +CDFeatureGatingTable::~CDFeatureGatingTable(void) {} //! Returns the table's name std::string CDFeatureGatingTable::GetName(void) const { - return "FeatureGating"; + return "FeatureGating"; } //! Queries the table with a custom "where" clause std::vector CDFeatureGatingTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } -bool CDFeatureGatingTable::FeatureUnlocked(const std::string& feature) const -{ - for (const auto& entry : entries) - { - if (entry.featureName == feature) - { - return true; - } - } - - return false; +bool CDFeatureGatingTable::FeatureUnlocked(const std::string& feature) const { + for (const auto& entry : entries) { + if (entry.featureName == feature) { + return true; + } + } + + return false; } //! Gets all the entries in the table std::vector CDFeatureGatingTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDFeatureGatingTable.h b/dDatabase/Tables/CDFeatureGatingTable.h index 11c25e67..54e6d21b 100644 --- a/dDatabase/Tables/CDFeatureGatingTable.h +++ b/dDatabase/Tables/CDFeatureGatingTable.h @@ -7,46 +7,46 @@ \file CDFeatureGatingTable.hpp */ -//! ItemComponent Struct + //! ItemComponent Struct struct CDFeatureGating { - std::string featureName; - int32_t major; - int32_t current; - int32_t minor; - std::string description; + std::string featureName; + int32_t major; + int32_t current; + int32_t minor; + std::string description; }; //! ItemComponent table class CDFeatureGatingTable : public CDTable { private: - std::vector entries; - -public: - - //! Constructor - CDFeatureGatingTable(void); - - //! Destructor - ~CDFeatureGatingTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); + std::vector entries; + +public: + + //! Constructor + CDFeatureGatingTable(void); + + //! Destructor + ~CDFeatureGatingTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + bool FeatureUnlocked(const std::string& feature) const; + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; - bool FeatureUnlocked(const std::string& feature) const; - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDInventoryComponentTable.cpp b/dDatabase/Tables/CDInventoryComponentTable.cpp index b0849a45..65f09c9b 100644 --- a/dDatabase/Tables/CDInventoryComponentTable.cpp +++ b/dDatabase/Tables/CDInventoryComponentTable.cpp @@ -2,56 +2,56 @@ //! Constructor CDInventoryComponentTable::CDInventoryComponentTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM InventoryComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM InventoryComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM InventoryComponent"); - while (!tableData.eof()) { - CDInventoryComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.itemid = tableData.getIntField(1, -1); - entry.count = tableData.getIntField(2, -1); - entry.equip = tableData.getIntField(3, -1) == 1 ? true : false; - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM InventoryComponent"); + while (!tableData.eof()) { + CDInventoryComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.itemid = tableData.getIntField(1, -1); + entry.count = tableData.getIntField(2, -1); + entry.equip = tableData.getIntField(3, -1) == 1 ? true : false; + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDInventoryComponentTable::~CDInventoryComponentTable(void) { } +CDInventoryComponentTable::~CDInventoryComponentTable(void) {} //! Returns the table's name std::string CDInventoryComponentTable::GetName(void) const { - return "InventoryComponent"; + return "InventoryComponent"; } //! Queries the table with a custom "where" clause std::vector CDInventoryComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDInventoryComponentTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDInventoryComponentTable.h b/dDatabase/Tables/CDInventoryComponentTable.h index 3bce41f9..c6117907 100644 --- a/dDatabase/Tables/CDInventoryComponentTable.h +++ b/dDatabase/Tables/CDInventoryComponentTable.h @@ -8,43 +8,43 @@ \brief Contains data for the InventoryComponent table */ -//! ItemComponent Struct + //! ItemComponent Struct struct CDInventoryComponent { - unsigned int id; //!< The component ID for this object - unsigned int itemid; //!< The LOT of the object - unsigned int count; //!< The count of the items the object has - bool equip; //!< Whether or not to equip the item + unsigned int id; //!< The component ID for this object + unsigned int itemid; //!< The LOT of the object + unsigned int count; //!< The count of the items the object has + bool equip; //!< Whether or not to equip the item }; //! ItemComponent table class CDInventoryComponentTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDInventoryComponentTable(void); - - //! Destructor - ~CDInventoryComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDInventoryComponentTable(void); + + //! Destructor + ~CDInventoryComponentTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDItemComponentTable.cpp b/dDatabase/Tables/CDItemComponentTable.cpp index 698f72a4..703497ff 100644 --- a/dDatabase/Tables/CDItemComponentTable.cpp +++ b/dDatabase/Tables/CDItemComponentTable.cpp @@ -5,84 +5,84 @@ CDItemComponent CDItemComponentTable::Default = {}; //! Constructor CDItemComponentTable::CDItemComponentTable(void) { - Default = CDItemComponent(); - + Default = CDItemComponent(); + #ifdef CDCLIENT_CACHE_ALL - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ItemComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ItemComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemComponent"); - while (!tableData.eof()) { - CDItemComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.equipLocation = tableData.getStringField(1, ""); - entry.baseValue = tableData.getIntField(2, -1); - entry.isKitPiece = tableData.getIntField(3, -1) == 1 ? true : false; - entry.rarity = tableData.getIntField(4, 0); - entry.itemType = tableData.getIntField(5, -1); - entry.itemInfo = tableData.getInt64Field(6, -1); - entry.inLootTable = tableData.getIntField(7, -1) == 1 ? true : false; - entry.inVendor = tableData.getIntField(8, -1) == 1 ? true : false; - entry.isUnique = tableData.getIntField(9, -1) == 1 ? true : false; - entry.isBOP = tableData.getIntField(10, -1) == 1 ? true : false; - entry.isBOE = tableData.getIntField(11, -1) == 1 ? true : false; - entry.reqFlagID = tableData.getIntField(12, -1); - entry.reqSpecialtyID = tableData.getIntField(13, -1); - entry.reqSpecRank = tableData.getIntField(14, -1); - entry.reqAchievementID = tableData.getIntField(15, -1); - entry.stackSize = tableData.getIntField(16, -1); - entry.color1 = tableData.getIntField(17, -1); - entry.decal = tableData.getIntField(18, -1); - entry.offsetGroupID = tableData.getIntField(19, -1); - entry.buildTypes = tableData.getIntField(20, -1); - entry.reqPrecondition = tableData.getStringField(21, ""); - entry.animationFlag = tableData.getIntField(22, -1); - entry.equipEffects = tableData.getIntField(23, -1); - entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; - entry.itemRating = tableData.getIntField(25, -1); - entry.isTwoHanded = tableData.getIntField(26, -1) == 1 ? true : false; - entry.minNumRequired = tableData.getIntField(27, -1); - entry.delResIndex = tableData.getIntField(28, -1); - entry.currencyLOT = tableData.getIntField(29, -1); - entry.altCurrencyCost = tableData.getIntField(30, -1); - entry.subItems = tableData.getStringField(31, ""); - entry.audioEventUse = tableData.getStringField(32, ""); - entry.noEquipAnimation = tableData.getIntField(33, -1) == 1 ? true : false; - entry.commendationLOT = tableData.getIntField(34, -1); - entry.commendationCost = tableData.getIntField(35, -1); - entry.audioEquipMetaEventSet = tableData.getStringField(36, ""); - entry.currencyCosts = tableData.getStringField(37, ""); - entry.ingredientInfo = tableData.getStringField(38, ""); - entry.locStatus = tableData.getIntField(39, -1); - entry.forgeType = tableData.getIntField(40, -1); - entry.SellMultiplier = tableData.getFloatField(41, -1.0f); - + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemComponent"); + while (!tableData.eof()) { + CDItemComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.equipLocation = tableData.getStringField(1, ""); + entry.baseValue = tableData.getIntField(2, -1); + entry.isKitPiece = tableData.getIntField(3, -1) == 1 ? true : false; + entry.rarity = tableData.getIntField(4, 0); + entry.itemType = tableData.getIntField(5, -1); + entry.itemInfo = tableData.getInt64Field(6, -1); + entry.inLootTable = tableData.getIntField(7, -1) == 1 ? true : false; + entry.inVendor = tableData.getIntField(8, -1) == 1 ? true : false; + entry.isUnique = tableData.getIntField(9, -1) == 1 ? true : false; + entry.isBOP = tableData.getIntField(10, -1) == 1 ? true : false; + entry.isBOE = tableData.getIntField(11, -1) == 1 ? true : false; + entry.reqFlagID = tableData.getIntField(12, -1); + entry.reqSpecialtyID = tableData.getIntField(13, -1); + entry.reqSpecRank = tableData.getIntField(14, -1); + entry.reqAchievementID = tableData.getIntField(15, -1); + entry.stackSize = tableData.getIntField(16, -1); + entry.color1 = tableData.getIntField(17, -1); + entry.decal = tableData.getIntField(18, -1); + entry.offsetGroupID = tableData.getIntField(19, -1); + entry.buildTypes = tableData.getIntField(20, -1); + entry.reqPrecondition = tableData.getStringField(21, ""); + entry.animationFlag = tableData.getIntField(22, -1); + entry.equipEffects = tableData.getIntField(23, -1); + entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; + entry.itemRating = tableData.getIntField(25, -1); + entry.isTwoHanded = tableData.getIntField(26, -1) == 1 ? true : false; + entry.minNumRequired = tableData.getIntField(27, -1); + entry.delResIndex = tableData.getIntField(28, -1); + entry.currencyLOT = tableData.getIntField(29, -1); + entry.altCurrencyCost = tableData.getIntField(30, -1); + entry.subItems = tableData.getStringField(31, ""); + entry.audioEventUse = tableData.getStringField(32, ""); + entry.noEquipAnimation = tableData.getIntField(33, -1) == 1 ? true : false; + entry.commendationLOT = tableData.getIntField(34, -1); + entry.commendationCost = tableData.getIntField(35, -1); + entry.audioEquipMetaEventSet = tableData.getStringField(36, ""); + entry.currencyCosts = tableData.getStringField(37, ""); + entry.ingredientInfo = tableData.getStringField(38, ""); + entry.locStatus = tableData.getIntField(39, -1); + entry.forgeType = tableData.getIntField(40, -1); + entry.SellMultiplier = tableData.getFloatField(41, -1.0f); + this->entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); - } + } tableData.finalize(); #endif } //! Destructor -CDItemComponentTable::~CDItemComponentTable(void) { } +CDItemComponentTable::~CDItemComponentTable(void) {} //! Returns the table's name std::string CDItemComponentTable::GetName(void) const { - return "ItemComponent"; + return "ItemComponent"; } -const CDItemComponent & CDItemComponentTable::GetItemComponentByID(unsigned int skillID) { +const CDItemComponent& CDItemComponentTable::GetItemComponentByID(unsigned int skillID) { const auto& it = this->entries.find(skillID); if (it != this->entries.end()) { return it->second; @@ -94,59 +94,59 @@ const CDItemComponent & CDItemComponentTable::GetItemComponentByID(unsigned int query << "SELECT * FROM ItemComponent WHERE id = " << std::to_string(skillID); auto tableData = CDClientDatabase::ExecuteQuery(query.str()); - if (tableData.eof()) { + if (tableData.eof()) { entries.insert(std::make_pair(skillID, Default)); return Default; } - while (!tableData.eof()) { - CDItemComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.equipLocation = tableData.getStringField(1, ""); - entry.baseValue = tableData.getIntField(2, -1); - entry.isKitPiece = tableData.getIntField(3, -1) == 1 ? true : false; - entry.rarity = tableData.getIntField(4, 0); - entry.itemType = tableData.getIntField(5, -1); - entry.itemInfo = tableData.getInt64Field(6, -1); - entry.inLootTable = tableData.getIntField(7, -1) == 1 ? true : false; - entry.inVendor = tableData.getIntField(8, -1) == 1 ? true : false; - entry.isUnique = tableData.getIntField(9, -1) == 1 ? true : false; - entry.isBOP = tableData.getIntField(10, -1) == 1 ? true : false; - entry.isBOE = tableData.getIntField(11, -1) == 1 ? true : false; - entry.reqFlagID = tableData.getIntField(12, -1); - entry.reqSpecialtyID = tableData.getIntField(13, -1); - entry.reqSpecRank = tableData.getIntField(14, -1); - entry.reqAchievementID = tableData.getIntField(15, -1); - entry.stackSize = tableData.getIntField(16, -1); - entry.color1 = tableData.getIntField(17, -1); - entry.decal = tableData.getIntField(18, -1); - entry.offsetGroupID = tableData.getIntField(19, -1); - entry.buildTypes = tableData.getIntField(20, -1); - entry.reqPrecondition = tableData.getStringField(21, ""); - entry.animationFlag = tableData.getIntField(22, -1); - entry.equipEffects = tableData.getIntField(23, -1); - entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; - entry.itemRating = tableData.getIntField(25, -1); - entry.isTwoHanded = tableData.getIntField(26, -1) == 1 ? true : false; - entry.minNumRequired = tableData.getIntField(27, -1); - entry.delResIndex = tableData.getIntField(28, -1); - entry.currencyLOT = tableData.getIntField(29, -1); - entry.altCurrencyCost = tableData.getIntField(30, -1); - entry.subItems = tableData.getStringField(31, ""); - UNUSED(entry.audioEventUse = tableData.getStringField(32, "")); - entry.noEquipAnimation = tableData.getIntField(33, -1) == 1 ? true : false; - entry.commendationLOT = tableData.getIntField(34, -1); - entry.commendationCost = tableData.getIntField(35, -1); - UNUSED(entry.audioEquipMetaEventSet = tableData.getStringField(36, "")); - entry.currencyCosts = tableData.getStringField(37, ""); - UNUSED(entry.ingredientInfo = tableData.getStringField(38, "")); - entry.locStatus = tableData.getIntField(39, -1); - entry.forgeType = tableData.getIntField(40, -1); - entry.SellMultiplier = tableData.getFloatField(41, -1.0f); - + while (!tableData.eof()) { + CDItemComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.equipLocation = tableData.getStringField(1, ""); + entry.baseValue = tableData.getIntField(2, -1); + entry.isKitPiece = tableData.getIntField(3, -1) == 1 ? true : false; + entry.rarity = tableData.getIntField(4, 0); + entry.itemType = tableData.getIntField(5, -1); + entry.itemInfo = tableData.getInt64Field(6, -1); + entry.inLootTable = tableData.getIntField(7, -1) == 1 ? true : false; + entry.inVendor = tableData.getIntField(8, -1) == 1 ? true : false; + entry.isUnique = tableData.getIntField(9, -1) == 1 ? true : false; + entry.isBOP = tableData.getIntField(10, -1) == 1 ? true : false; + entry.isBOE = tableData.getIntField(11, -1) == 1 ? true : false; + entry.reqFlagID = tableData.getIntField(12, -1); + entry.reqSpecialtyID = tableData.getIntField(13, -1); + entry.reqSpecRank = tableData.getIntField(14, -1); + entry.reqAchievementID = tableData.getIntField(15, -1); + entry.stackSize = tableData.getIntField(16, -1); + entry.color1 = tableData.getIntField(17, -1); + entry.decal = tableData.getIntField(18, -1); + entry.offsetGroupID = tableData.getIntField(19, -1); + entry.buildTypes = tableData.getIntField(20, -1); + entry.reqPrecondition = tableData.getStringField(21, ""); + entry.animationFlag = tableData.getIntField(22, -1); + entry.equipEffects = tableData.getIntField(23, -1); + entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; + entry.itemRating = tableData.getIntField(25, -1); + entry.isTwoHanded = tableData.getIntField(26, -1) == 1 ? true : false; + entry.minNumRequired = tableData.getIntField(27, -1); + entry.delResIndex = tableData.getIntField(28, -1); + entry.currencyLOT = tableData.getIntField(29, -1); + entry.altCurrencyCost = tableData.getIntField(30, -1); + entry.subItems = tableData.getStringField(31, ""); + UNUSED(entry.audioEventUse = tableData.getStringField(32, "")); + entry.noEquipAnimation = tableData.getIntField(33, -1) == 1 ? true : false; + entry.commendationLOT = tableData.getIntField(34, -1); + entry.commendationCost = tableData.getIntField(35, -1); + UNUSED(entry.audioEquipMetaEventSet = tableData.getStringField(36, "")); + entry.currencyCosts = tableData.getStringField(37, ""); + UNUSED(entry.ingredientInfo = tableData.getStringField(38, "")); + entry.locStatus = tableData.getIntField(39, -1); + entry.forgeType = tableData.getIntField(40, -1); + entry.SellMultiplier = tableData.getFloatField(41, -1.0f); + this->entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); - } + } const auto& it2 = this->entries.find(skillID); if (it2 != this->entries.end()) { @@ -154,26 +154,26 @@ const CDItemComponent & CDItemComponentTable::GetItemComponentByID(unsigned int } #endif - return Default; + return Default; } std::map CDItemComponentTable::ParseCraftingCurrencies(const CDItemComponent& itemComponent) { - std::map currencies = {}; + std::map currencies = {}; - if (!itemComponent.currencyCosts.empty()) { - auto currencySplit = GeneralUtils::SplitString(itemComponent.currencyCosts, ','); - for (const auto& currencyAmount : currencySplit) { - auto amountSplit = GeneralUtils::SplitString(currencyAmount, ':'); + if (!itemComponent.currencyCosts.empty()) { + auto currencySplit = GeneralUtils::SplitString(itemComponent.currencyCosts, ','); + for (const auto& currencyAmount : currencySplit) { + auto amountSplit = GeneralUtils::SplitString(currencyAmount, ':'); - // Checking for 2 here, not sure what to do when there's more stuff than expected - if (amountSplit.size() == 2) { - currencies.insert({ - std::stoull(amountSplit[0]), - std::stoi(amountSplit[1]) - }); - } - } - } + // Checking for 2 here, not sure what to do when there's more stuff than expected + if (amountSplit.size() == 2) { + currencies.insert({ + std::stoull(amountSplit[0]), + std::stoi(amountSplit[1]) + }); + } + } + } - return currencies; + return currencies; } diff --git a/dDatabase/Tables/CDItemComponentTable.h b/dDatabase/Tables/CDItemComponentTable.h index 83b66f91..b3a2a5f4 100644 --- a/dDatabase/Tables/CDItemComponentTable.h +++ b/dDatabase/Tables/CDItemComponentTable.h @@ -9,75 +9,75 @@ \brief Contains data for the ItemComponent table */ -//! ItemComponent Struct + //! ItemComponent Struct struct CDItemComponent { - unsigned int id; //!< The Component ID - std::string equipLocation; //!< The equip location - unsigned int baseValue; //!< The monetary base value of the item - bool isKitPiece; //!< Whether or not the item belongs to a kit - unsigned int rarity; //!< The rarity of the item - unsigned int itemType; //!< The item type - int64_t itemInfo; //!< The item info - bool inLootTable; //!< Whether or not the item is in a loot table - bool inVendor; //!< Whether or not the item is in a vendor inventory - bool isUnique; //!< ??? - bool isBOP; //!< ??? - bool isBOE; //!< ??? - unsigned int reqFlagID; //!< User must have completed this flag to get the item - unsigned int reqSpecialtyID; //!< ??? - unsigned int reqSpecRank; //!< ??? - unsigned int reqAchievementID; //!< The required achievement must be completed - unsigned int stackSize; //!< The stack size of the item - unsigned int color1; //!< Something to do with item color... - unsigned int decal; //!< The decal of the item - unsigned int offsetGroupID; //!< Something to do with group IDs - unsigned int buildTypes; //!< Something to do with building - std::string reqPrecondition; //!< The required precondition - unsigned int animationFlag; //!< The Animation Flag - unsigned int equipEffects; //!< The effect played when the item is equipped - bool readyForQA; //!< ??? - unsigned int itemRating; //!< ??? - bool isTwoHanded; //!< Whether or not the item is double handed - unsigned int minNumRequired; //!< Maybe the minimum number required for a mission, or to own this object? - unsigned int delResIndex; //!< ??? - unsigned int currencyLOT; //!< ??? - unsigned int altCurrencyCost; //!< ??? - std::string subItems; //!< A comma seperate string of sub items (maybe for multi-itemed things like faction test gear set) - UNUSED(std::string audioEventUse); //!< ??? - bool noEquipAnimation; //!< Whether or not there is an equip animation - unsigned int commendationLOT; //!< The commendation LOT - unsigned int commendationCost; //!< The commendation cost - UNUSED(std::string audioEquipMetaEventSet); //!< ??? - std::string currencyCosts; //!< Used for crafting - UNUSED(std::string ingredientInfo); //!< Unused - unsigned int locStatus; //!< ??? - unsigned int forgeType; //!< Forge Type - float SellMultiplier; //!< Something to do with early vendors perhaps (but replaced) + unsigned int id; //!< The Component ID + std::string equipLocation; //!< The equip location + unsigned int baseValue; //!< The monetary base value of the item + bool isKitPiece; //!< Whether or not the item belongs to a kit + unsigned int rarity; //!< The rarity of the item + unsigned int itemType; //!< The item type + int64_t itemInfo; //!< The item info + bool inLootTable; //!< Whether or not the item is in a loot table + bool inVendor; //!< Whether or not the item is in a vendor inventory + bool isUnique; //!< ??? + bool isBOP; //!< ??? + bool isBOE; //!< ??? + unsigned int reqFlagID; //!< User must have completed this flag to get the item + unsigned int reqSpecialtyID; //!< ??? + unsigned int reqSpecRank; //!< ??? + unsigned int reqAchievementID; //!< The required achievement must be completed + unsigned int stackSize; //!< The stack size of the item + unsigned int color1; //!< Something to do with item color... + unsigned int decal; //!< The decal of the item + unsigned int offsetGroupID; //!< Something to do with group IDs + unsigned int buildTypes; //!< Something to do with building + std::string reqPrecondition; //!< The required precondition + unsigned int animationFlag; //!< The Animation Flag + unsigned int equipEffects; //!< The effect played when the item is equipped + bool readyForQA; //!< ??? + unsigned int itemRating; //!< ??? + bool isTwoHanded; //!< Whether or not the item is double handed + unsigned int minNumRequired; //!< Maybe the minimum number required for a mission, or to own this object? + unsigned int delResIndex; //!< ??? + unsigned int currencyLOT; //!< ??? + unsigned int altCurrencyCost; //!< ??? + std::string subItems; //!< A comma seperate string of sub items (maybe for multi-itemed things like faction test gear set) + UNUSED(std::string audioEventUse); //!< ??? + bool noEquipAnimation; //!< Whether or not there is an equip animation + unsigned int commendationLOT; //!< The commendation LOT + unsigned int commendationCost; //!< The commendation cost + UNUSED(std::string audioEquipMetaEventSet); //!< ??? + std::string currencyCosts; //!< Used for crafting + UNUSED(std::string ingredientInfo); //!< Unused + unsigned int locStatus; //!< ??? + unsigned int forgeType; //!< Forge Type + float SellMultiplier; //!< Something to do with early vendors perhaps (but replaced) }; //! ItemComponent table class CDItemComponentTable : public CDTable { private: - std::map entries; - -public: - - //! Constructor - CDItemComponentTable(void); - - //! Destructor - ~CDItemComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; + std::map entries; + +public: + + //! Constructor + CDItemComponentTable(void); + + //! Destructor + ~CDItemComponentTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + static std::map ParseCraftingCurrencies(const CDItemComponent& itemComponent); - static std::map ParseCraftingCurrencies(const CDItemComponent& itemComponent); - //! Gets an entry by ID const CDItemComponent& GetItemComponentByID(unsigned int skillID); - - static CDItemComponent Default; + + static CDItemComponent Default; }; diff --git a/dDatabase/Tables/CDItemSetSkillsTable.cpp b/dDatabase/Tables/CDItemSetSkillsTable.cpp index b20fd1cb..e94cf527 100644 --- a/dDatabase/Tables/CDItemSetSkillsTable.cpp +++ b/dDatabase/Tables/CDItemSetSkillsTable.cpp @@ -2,63 +2,62 @@ //! Constructor CDItemSetSkillsTable::CDItemSetSkillsTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ItemSetSkills"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ItemSetSkills"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSetSkills"); - while (!tableData.eof()) { - CDItemSetSkills entry; - entry.SkillSetID = tableData.getIntField(0, -1); - entry.SkillID = tableData.getIntField(1, -1); - entry.SkillCastType = tableData.getIntField(2, -1); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSetSkills"); + while (!tableData.eof()) { + CDItemSetSkills entry; + entry.SkillSetID = tableData.getIntField(0, -1); + entry.SkillID = tableData.getIntField(1, -1); + entry.SkillCastType = tableData.getIntField(2, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDItemSetSkillsTable::~CDItemSetSkillsTable(void) { } +CDItemSetSkillsTable::~CDItemSetSkillsTable(void) {} //! Returns the table's name std::string CDItemSetSkillsTable::GetName(void) const { - return "ItemSetSkills"; + return "ItemSetSkills"; } //! Queries the table with a custom "where" clause std::vector CDItemSetSkillsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDItemSetSkillsTable::GetEntries(void) const { - return this->entries; + return this->entries; } -std::vector CDItemSetSkillsTable::GetBySkillID(unsigned int SkillSetID) -{ +std::vector CDItemSetSkillsTable::GetBySkillID(unsigned int SkillSetID) { std::vector toReturn; - + for (CDItemSetSkills entry : this->entries) { 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/Tables/CDItemSetSkillsTable.h b/dDatabase/Tables/CDItemSetSkillsTable.h index 78ce83ab..bf05eea9 100644 --- a/dDatabase/Tables/CDItemSetSkillsTable.h +++ b/dDatabase/Tables/CDItemSetSkillsTable.h @@ -8,45 +8,45 @@ \brief Contains data for the ItemSetSkills table */ -//! ZoneTable Struct + //! ZoneTable Struct struct CDItemSetSkills { - unsigned int SkillSetID; //!< The skill set ID - unsigned int SkillID; //!< The skill ID - unsigned int SkillCastType; //!< The skill cast type + unsigned int SkillSetID; //!< The skill set ID + unsigned int SkillID; //!< The skill ID + unsigned int SkillCastType; //!< The skill cast type }; //! ItemSets table class CDItemSetSkillsTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDItemSetSkillsTable(void); - - //! Destructor - ~CDItemSetSkillsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; + + //! Constructor + CDItemSetSkillsTable(void); + + //! Destructor + ~CDItemSetSkillsTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; std::vector GetBySkillID(unsigned int SkillSetID); - + }; diff --git a/dDatabase/Tables/CDItemSetsTable.cpp b/dDatabase/Tables/CDItemSetsTable.cpp index ad78ee3b..606e0cf9 100644 --- a/dDatabase/Tables/CDItemSetsTable.cpp +++ b/dDatabase/Tables/CDItemSetsTable.cpp @@ -2,67 +2,67 @@ //! Constructor CDItemSetsTable::CDItemSetsTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ItemSets"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ItemSets"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSets"); - while (!tableData.eof()) { - CDItemSets entry; - entry.setID = tableData.getIntField(0, -1); - entry.locStatus = tableData.getIntField(1, -1); - entry.itemIDs = tableData.getStringField(2, ""); - entry.kitType = tableData.getIntField(3, -1); - entry.kitRank = tableData.getIntField(4, -1); - entry.kitImage = tableData.getIntField(5, -1); - entry.skillSetWith2 = tableData.getIntField(6, -1); - entry.skillSetWith3 = tableData.getIntField(7, -1); - entry.skillSetWith4 = tableData.getIntField(8, -1); - entry.skillSetWith5 = tableData.getIntField(9, -1); - entry.skillSetWith6 = tableData.getIntField(10, -1); - entry.localize = tableData.getIntField(11, -1) == 1 ? true : false; - entry.gate_version = tableData.getStringField(12, ""); - entry.kitID = tableData.getIntField(13, -1); - entry.priority = tableData.getFloatField(14, -1.0f); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSets"); + while (!tableData.eof()) { + CDItemSets entry; + entry.setID = tableData.getIntField(0, -1); + entry.locStatus = tableData.getIntField(1, -1); + entry.itemIDs = tableData.getStringField(2, ""); + entry.kitType = tableData.getIntField(3, -1); + entry.kitRank = tableData.getIntField(4, -1); + entry.kitImage = tableData.getIntField(5, -1); + entry.skillSetWith2 = tableData.getIntField(6, -1); + entry.skillSetWith3 = tableData.getIntField(7, -1); + entry.skillSetWith4 = tableData.getIntField(8, -1); + entry.skillSetWith5 = tableData.getIntField(9, -1); + entry.skillSetWith6 = tableData.getIntField(10, -1); + entry.localize = tableData.getIntField(11, -1) == 1 ? true : false; + entry.gate_version = tableData.getStringField(12, ""); + entry.kitID = tableData.getIntField(13, -1); + entry.priority = tableData.getFloatField(14, -1.0f); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDItemSetsTable::~CDItemSetsTable(void) { } +CDItemSetsTable::~CDItemSetsTable(void) {} //! Returns the table's name std::string CDItemSetsTable::GetName(void) const { - return "ItemSets"; + return "ItemSets"; } //! Queries the table with a custom "where" clause std::vector CDItemSetsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDItemSetsTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDItemSetsTable.h b/dDatabase/Tables/CDItemSetsTable.h index 9e8b85e8..ef12c7b4 100644 --- a/dDatabase/Tables/CDItemSetsTable.h +++ b/dDatabase/Tables/CDItemSetsTable.h @@ -8,55 +8,55 @@ \brief Contains data for the ItemSets table */ -//! ZoneTable Struct + //! ZoneTable Struct struct CDItemSets { - unsigned int setID; //!< The item set ID - unsigned int locStatus; //!< The loc status - std::string itemIDs; //!< THe item IDs - unsigned int kitType; //!< The item kit type - unsigned int kitRank; //!< The item kit rank - unsigned int kitImage; //!< The item kit image - unsigned int skillSetWith2; //!< The skill set with 2 - unsigned int skillSetWith3; //!< The skill set with 3 - unsigned int skillSetWith4; //!< The skill set with 4 - unsigned int skillSetWith5; //!< The skill set with 5 - unsigned int skillSetWith6; //!< The skill set with 6 - bool localize; //!< Whether or localize - std::string gate_version; //!< The gate version - unsigned int kitID; //!< The kit ID - float priority; //!< The priority + unsigned int setID; //!< The item set ID + unsigned int locStatus; //!< The loc status + std::string itemIDs; //!< THe item IDs + unsigned int kitType; //!< The item kit type + unsigned int kitRank; //!< The item kit rank + unsigned int kitImage; //!< The item kit image + unsigned int skillSetWith2; //!< The skill set with 2 + unsigned int skillSetWith3; //!< The skill set with 3 + unsigned int skillSetWith4; //!< The skill set with 4 + unsigned int skillSetWith5; //!< The skill set with 5 + unsigned int skillSetWith6; //!< The skill set with 6 + bool localize; //!< Whether or localize + std::string gate_version; //!< The gate version + unsigned int kitID; //!< The kit ID + float priority; //!< The priority }; //! ItemSets table class CDItemSetsTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDItemSetsTable(void); - - //! Destructor - ~CDItemSetsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDItemSetsTable(void); + + //! Destructor + ~CDItemSetsTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDLevelProgressionLookupTable.cpp b/dDatabase/Tables/CDLevelProgressionLookupTable.cpp index 0070e787..121c9f62 100644 --- a/dDatabase/Tables/CDLevelProgressionLookupTable.cpp +++ b/dDatabase/Tables/CDLevelProgressionLookupTable.cpp @@ -2,55 +2,55 @@ //! Constructor CDLevelProgressionLookupTable::CDLevelProgressionLookupTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM LevelProgressionLookup"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM LevelProgressionLookup"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LevelProgressionLookup"); - while (!tableData.eof()) { - CDLevelProgressionLookup entry; - entry.id = tableData.getIntField(0, -1); - entry.requiredUScore = tableData.getIntField(1, -1); - entry.BehaviorEffect = tableData.getStringField(2, ""); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LevelProgressionLookup"); + while (!tableData.eof()) { + CDLevelProgressionLookup entry; + entry.id = tableData.getIntField(0, -1); + entry.requiredUScore = tableData.getIntField(1, -1); + entry.BehaviorEffect = tableData.getStringField(2, ""); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDLevelProgressionLookupTable::~CDLevelProgressionLookupTable(void) { } +CDLevelProgressionLookupTable::~CDLevelProgressionLookupTable(void) {} //! Returns the table's name std::string CDLevelProgressionLookupTable::GetName(void) const { - return "LevelProgressionLookup"; + return "LevelProgressionLookup"; } //! Queries the table with a custom "where" clause std::vector CDLevelProgressionLookupTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDLevelProgressionLookupTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDLevelProgressionLookupTable.h b/dDatabase/Tables/CDLevelProgressionLookupTable.h index 4174cdff..391c9b37 100644 --- a/dDatabase/Tables/CDLevelProgressionLookupTable.h +++ b/dDatabase/Tables/CDLevelProgressionLookupTable.h @@ -8,42 +8,42 @@ \brief Contains data for the LevelProgressionLookup table */ -//! LevelProgressionLookup Entry Struct + //! LevelProgressionLookup Entry Struct struct CDLevelProgressionLookup { - unsigned int id; //!< The Level ID - unsigned int requiredUScore; //!< The required LEGO Score - std::string BehaviorEffect; //!< The behavior effect attached to this + unsigned int id; //!< The Level ID + unsigned int requiredUScore; //!< The required LEGO Score + std::string BehaviorEffect; //!< The behavior effect attached to this }; //! LevelProgressionLookup table class CDLevelProgressionLookupTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDLevelProgressionLookupTable(void); - - //! Destructor - ~CDLevelProgressionLookupTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDLevelProgressionLookupTable(void); + + //! Destructor + ~CDLevelProgressionLookupTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDLootMatrixTable.cpp b/dDatabase/Tables/CDLootMatrixTable.cpp index 17fd8313..d47c081b 100644 --- a/dDatabase/Tables/CDLootMatrixTable.cpp +++ b/dDatabase/Tables/CDLootMatrixTable.cpp @@ -2,61 +2,61 @@ //! Constructor CDLootMatrixTable::CDLootMatrixTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM LootMatrix"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM LootMatrix"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootMatrix"); - while (!tableData.eof()) { - CDLootMatrix entry; - entry.LootMatrixIndex = tableData.getIntField(0, -1); - entry.LootTableIndex = tableData.getIntField(1, -1); - entry.RarityTableIndex = tableData.getIntField(2, -1); - entry.percent = tableData.getFloatField(3, -1.0f); - entry.minToDrop = tableData.getIntField(4, -1); - entry.maxToDrop = tableData.getIntField(5, -1); - entry.id = tableData.getIntField(6, -1); - entry.flagID = tableData.getIntField(7, -1); - UNUSED(entry.gate_version = tableData.getStringField(8, "")); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootMatrix"); + while (!tableData.eof()) { + CDLootMatrix entry; + entry.LootMatrixIndex = tableData.getIntField(0, -1); + entry.LootTableIndex = tableData.getIntField(1, -1); + entry.RarityTableIndex = tableData.getIntField(2, -1); + entry.percent = tableData.getFloatField(3, -1.0f); + entry.minToDrop = tableData.getIntField(4, -1); + entry.maxToDrop = tableData.getIntField(5, -1); + entry.id = tableData.getIntField(6, -1); + entry.flagID = tableData.getIntField(7, -1); + UNUSED(entry.gate_version = tableData.getStringField(8, "")); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDLootMatrixTable::~CDLootMatrixTable(void) { } +CDLootMatrixTable::~CDLootMatrixTable(void) {} //! Returns the table's name std::string CDLootMatrixTable::GetName(void) const { - return "LootMatrix"; + return "LootMatrix"; } //! Queries the table with a custom "where" clause std::vector CDLootMatrixTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table const std::vector& CDLootMatrixTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDLootMatrixTable.h b/dDatabase/Tables/CDLootMatrixTable.h index f306324f..7d311b3b 100644 --- a/dDatabase/Tables/CDLootMatrixTable.h +++ b/dDatabase/Tables/CDLootMatrixTable.h @@ -8,49 +8,49 @@ \brief Contains data for the ObjectSkills table */ -//! LootMatrix Struct + //! LootMatrix Struct struct CDLootMatrix { - unsigned int LootMatrixIndex; //!< The Loot Matrix Index - unsigned int LootTableIndex; //!< The Loot Table Index - unsigned int RarityTableIndex; //!< The Rarity Table Index - float percent; //!< The percent that this matrix is used? - unsigned int minToDrop; //!< The minimum amount of loot from this matrix to drop - unsigned int maxToDrop; //!< The maximum amount of loot from this matrix to drop - unsigned int id; //!< The ID of the Loot Matrix - unsigned int flagID; //!< ??? - UNUSED(std::string gate_version); //!< The Gate Version + unsigned int LootMatrixIndex; //!< The Loot Matrix Index + unsigned int LootTableIndex; //!< The Loot Table Index + unsigned int RarityTableIndex; //!< The Rarity Table Index + float percent; //!< The percent that this matrix is used? + unsigned int minToDrop; //!< The minimum amount of loot from this matrix to drop + unsigned int maxToDrop; //!< The maximum amount of loot from this matrix to drop + unsigned int id; //!< The ID of the Loot Matrix + unsigned int flagID; //!< ??? + UNUSED(std::string gate_version); //!< The Gate Version }; //! MissionNPCComponent table class CDLootMatrixTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDLootMatrixTable(void); - - //! Destructor - ~CDLootMatrixTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - const std::vector& GetEntries(void) const; - + + //! Constructor + CDLootMatrixTable(void); + + //! Destructor + ~CDLootMatrixTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + const std::vector& GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDLootTableTable.cpp b/dDatabase/Tables/CDLootTableTable.cpp index 62727ade..da8c824b 100644 --- a/dDatabase/Tables/CDLootTableTable.cpp +++ b/dDatabase/Tables/CDLootTableTable.cpp @@ -2,58 +2,58 @@ //! Constructor CDLootTableTable::CDLootTableTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM LootTable"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM LootTable"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootTable"); - while (!tableData.eof()) { - CDLootTable entry; - entry.id = tableData.getIntField(0, -1); - entry.itemid = tableData.getIntField(0, -1); - entry.LootTableIndex = tableData.getIntField(1, -1); - entry.id = tableData.getIntField(2, -1); - entry.MissionDrop = tableData.getIntField(3, -1) == 1 ? true : false; - entry.sortPriority = tableData.getIntField(4, -1); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootTable"); + while (!tableData.eof()) { + CDLootTable entry; + entry.id = tableData.getIntField(0, -1); + entry.itemid = tableData.getIntField(0, -1); + entry.LootTableIndex = tableData.getIntField(1, -1); + entry.id = tableData.getIntField(2, -1); + entry.MissionDrop = tableData.getIntField(3, -1) == 1 ? true : false; + entry.sortPriority = tableData.getIntField(4, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDLootTableTable::~CDLootTableTable(void) { } +CDLootTableTable::~CDLootTableTable(void) {} //! Returns the table's name std::string CDLootTableTable::GetName(void) const { - return "LootTable"; + return "LootTable"; } //! Queries the table with a custom "where" clause std::vector CDLootTableTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table const std::vector& CDLootTableTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDLootTableTable.h b/dDatabase/Tables/CDLootTableTable.h index 750adcb4..3f1baf60 100644 --- a/dDatabase/Tables/CDLootTableTable.h +++ b/dDatabase/Tables/CDLootTableTable.h @@ -8,45 +8,45 @@ \brief Contains data for the LootTable table */ -//! LootTable Struct + //! LootTable Struct struct CDLootTable { - unsigned int itemid; //!< The LOT of the item - unsigned int LootTableIndex; //!< The Loot Table Index - unsigned int id; //!< The ID - bool MissionDrop; //!< Whether or not this loot table is a mission drop - unsigned int sortPriority; //!< The sorting priority + unsigned int itemid; //!< The LOT of the item + unsigned int LootTableIndex; //!< The Loot Table Index + unsigned int id; //!< The ID + bool MissionDrop; //!< Whether or not this loot table is a mission drop + unsigned int sortPriority; //!< The sorting priority }; //! LootTable table class CDLootTableTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDLootTableTable(void); - - //! Destructor - ~CDLootTableTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - const std::vector& GetEntries(void) const; - + + //! Constructor + CDLootTableTable(void); + + //! Destructor + ~CDLootTableTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + const std::vector& GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDMissionEmailTable.cpp b/dDatabase/Tables/CDMissionEmailTable.cpp index 2c5fc56a..a8beb95b 100644 --- a/dDatabase/Tables/CDMissionEmailTable.cpp +++ b/dDatabase/Tables/CDMissionEmailTable.cpp @@ -3,59 +3,59 @@ //! Constructor CDMissionEmailTable::CDMissionEmailTable(void) { - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionEmail"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionEmail"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } - tableSize.nextRow(); - } - tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionEmail"); - while (!tableData.eof()) { - CDMissionEmail entry; - entry.ID = tableData.getIntField(0, -1); - entry.messageType = tableData.getIntField(1, -1); - entry.notificationGroup = tableData.getIntField(2, -1); - entry.missionID = tableData.getIntField(3, -1); - entry.attachmentLOT = tableData.getIntField(4, 0); - entry.localize = (bool)tableData.getIntField(5, -1); - entry.locStatus = tableData.getIntField(6, -1); - entry.gate_version = tableData.getStringField(7, ""); + // Reserve the size + this->entries.reserve(size); - this->entries.push_back(entry); - tableData.nextRow(); - } + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionEmail"); + while (!tableData.eof()) { + CDMissionEmail entry; + entry.ID = tableData.getIntField(0, -1); + entry.messageType = tableData.getIntField(1, -1); + entry.notificationGroup = tableData.getIntField(2, -1); + entry.missionID = tableData.getIntField(3, -1); + entry.attachmentLOT = tableData.getIntField(4, 0); + entry.localize = (bool)tableData.getIntField(5, -1); + entry.locStatus = tableData.getIntField(6, -1); + entry.gate_version = tableData.getStringField(7, ""); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDMissionEmailTable::~CDMissionEmailTable(void) { } +CDMissionEmailTable::~CDMissionEmailTable(void) {} //! Returns the table's name std::string CDMissionEmailTable::GetName(void) const { - return "MissionEmail"; + return "MissionEmail"; } //! Queries the table with a custom "where" clause std::vector CDMissionEmailTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); - return data; + return data; } //! Gets all the entries in the table std::vector CDMissionEmailTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDMissionEmailTable.h b/dDatabase/Tables/CDMissionEmailTable.h index cd0a1285..81a7a793 100644 --- a/dDatabase/Tables/CDMissionEmailTable.h +++ b/dDatabase/Tables/CDMissionEmailTable.h @@ -10,46 +10,46 @@ //! MissionEmail Entry Struct struct CDMissionEmail { - unsigned int ID; - unsigned int messageType; - unsigned int notificationGroup; - unsigned int missionID; - unsigned int attachmentLOT; - bool localize; - unsigned int locStatus; - std::string gate_version; + unsigned int ID; + unsigned int messageType; + unsigned int notificationGroup; + unsigned int missionID; + unsigned int attachmentLOT; + bool localize; + unsigned int locStatus; + std::string gate_version; }; //! MissionEmail table class CDMissionEmailTable : public CDTable { private: - std::vector entries; + std::vector entries; public: - //! Constructor - CDMissionEmailTable(void); + //! Constructor + CDMissionEmailTable(void); - //! Destructor - ~CDMissionEmailTable(void); + //! Destructor + ~CDMissionEmailTable(void); - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; }; diff --git a/dDatabase/Tables/CDMissionNPCComponentTable.cpp b/dDatabase/Tables/CDMissionNPCComponentTable.cpp index 9014585b..e2589890 100644 --- a/dDatabase/Tables/CDMissionNPCComponentTable.cpp +++ b/dDatabase/Tables/CDMissionNPCComponentTable.cpp @@ -2,57 +2,57 @@ //! Constructor CDMissionNPCComponentTable::CDMissionNPCComponentTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionNPCComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionNPCComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionNPCComponent"); - while (!tableData.eof()) { - CDMissionNPCComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.missionID = tableData.getIntField(1, -1); - entry.offersMission = tableData.getIntField(2, -1) == 1 ? true : false; - entry.acceptsMission = tableData.getIntField(3, -1) == 1 ? true : false; - entry.gate_version = tableData.getStringField(4, ""); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionNPCComponent"); + while (!tableData.eof()) { + CDMissionNPCComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.missionID = tableData.getIntField(1, -1); + entry.offersMission = tableData.getIntField(2, -1) == 1 ? true : false; + entry.acceptsMission = tableData.getIntField(3, -1) == 1 ? true : false; + entry.gate_version = tableData.getStringField(4, ""); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDMissionNPCComponentTable::~CDMissionNPCComponentTable(void) { } +CDMissionNPCComponentTable::~CDMissionNPCComponentTable(void) {} //! Returns the table's name std::string CDMissionNPCComponentTable::GetName(void) const { - return "MissionNPCComponent"; + return "MissionNPCComponent"; } //! Queries the table with a custom "where" clause std::vector CDMissionNPCComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDMissionNPCComponentTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDMissionNPCComponentTable.h b/dDatabase/Tables/CDMissionNPCComponentTable.h index a31ba170..68c94ef0 100644 --- a/dDatabase/Tables/CDMissionNPCComponentTable.h +++ b/dDatabase/Tables/CDMissionNPCComponentTable.h @@ -8,45 +8,45 @@ \brief Contains data for the ObjectSkills table */ -//! MissionNPCComponent Struct + //! MissionNPCComponent Struct struct CDMissionNPCComponent { - unsigned int id; //!< The ID - unsigned int missionID; //!< The Mission ID - bool offersMission; //!< Whether or not this NPC offers a mission - bool acceptsMission; //!< Whether or not this NPC accepts a mission - std::string gate_version; //!< The gate version + unsigned int id; //!< The ID + unsigned int missionID; //!< The Mission ID + bool offersMission; //!< Whether or not this NPC offers a mission + bool acceptsMission; //!< Whether or not this NPC accepts a mission + std::string gate_version; //!< The gate version }; //! MissionNPCComponent table class CDMissionNPCComponentTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDMissionNPCComponentTable(void); - - //! Destructor - ~CDMissionNPCComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDMissionNPCComponentTable(void); + + //! Destructor + ~CDMissionNPCComponentTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDMissionTasksTable.cpp b/dDatabase/Tables/CDMissionTasksTable.cpp index e79e6d02..81de2088 100644 --- a/dDatabase/Tables/CDMissionTasksTable.cpp +++ b/dDatabase/Tables/CDMissionTasksTable.cpp @@ -2,82 +2,79 @@ //! Constructor CDMissionTasksTable::CDMissionTasksTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionTasks"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionTasks"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionTasks"); - while (!tableData.eof()) { - CDMissionTasks entry; - entry.id = tableData.getIntField(0, -1); - UNUSED(entry.locStatus = tableData.getIntField(1, -1)); - entry.taskType = tableData.getIntField(2, -1); - entry.target = tableData.getIntField(3, -1); - entry.targetGroup = tableData.getStringField(4, ""); - entry.targetValue = tableData.getIntField(5, -1); - entry.taskParam1 = tableData.getStringField(6, ""); - UNUSED(entry.largeTaskIcon = tableData.getStringField(7, "")); - UNUSED(entry.IconID = tableData.getIntField(8, -1)); - entry.uid = tableData.getIntField(9, -1); - UNUSED(entry.largeTaskIconID = tableData.getIntField(10, -1)); - UNUSED(entry.localize = tableData.getIntField(11, -1) == 1 ? true : false); - UNUSED(entry.gate_version = tableData.getStringField(12, "")); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionTasks"); + while (!tableData.eof()) { + CDMissionTasks entry; + entry.id = tableData.getIntField(0, -1); + UNUSED(entry.locStatus = tableData.getIntField(1, -1)); + entry.taskType = tableData.getIntField(2, -1); + entry.target = tableData.getIntField(3, -1); + entry.targetGroup = tableData.getStringField(4, ""); + entry.targetValue = tableData.getIntField(5, -1); + entry.taskParam1 = tableData.getStringField(6, ""); + UNUSED(entry.largeTaskIcon = tableData.getStringField(7, "")); + UNUSED(entry.IconID = tableData.getIntField(8, -1)); + entry.uid = tableData.getIntField(9, -1); + UNUSED(entry.largeTaskIconID = tableData.getIntField(10, -1)); + UNUSED(entry.localize = tableData.getIntField(11, -1) == 1 ? true : false); + UNUSED(entry.gate_version = tableData.getStringField(12, "")); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDMissionTasksTable::~CDMissionTasksTable(void) { } +CDMissionTasksTable::~CDMissionTasksTable(void) {} //! Returns the table's name std::string CDMissionTasksTable::GetName(void) const { - return "MissionTasks"; + return "MissionTasks"; } //! Queries the table with a custom "where" clause std::vector CDMissionTasksTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } -std::vector CDMissionTasksTable::GetByMissionID(uint32_t missionID) -{ - std::vector tasks; +std::vector CDMissionTasksTable::GetByMissionID(uint32_t missionID) { + std::vector tasks; - for (auto& entry : this->entries) - { - if (entry.id == missionID) - { - CDMissionTasks* task = const_cast(&entry); + for (auto& entry : this->entries) { + if (entry.id == missionID) { + CDMissionTasks* task = const_cast(&entry); - tasks.push_back(task); - } - } + tasks.push_back(task); + } + } - return tasks; + return tasks; } //! Gets all the entries in the table const std::vector& CDMissionTasksTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDMissionTasksTable.h b/dDatabase/Tables/CDMissionTasksTable.h index af84663e..1a4bd361 100644 --- a/dDatabase/Tables/CDMissionTasksTable.h +++ b/dDatabase/Tables/CDMissionTasksTable.h @@ -8,54 +8,54 @@ \brief Contains data for the MissionTasks table */ -//! ObjectSkills Struct + //! ObjectSkills Struct struct CDMissionTasks { - unsigned int id; //!< The Mission ID that the task belongs to - UNUSED(unsigned int locStatus); //!< ??? - unsigned int taskType; //!< The task type - unsigned int target; //!< The mission target - std::string targetGroup; //!< The mission target group - int targetValue; //!< The target value - std::string taskParam1; //!< The task param 1 - UNUSED(std::string largeTaskIcon); //!< ??? - UNUSED(unsigned int IconID); //!< ??? - unsigned int uid; //!< ??? - UNUSED(unsigned int largeTaskIconID); //!< ??? - UNUSED(bool localize); //!< Whether or not the task should be localized - UNUSED(std::string gate_version); //!< ??? + unsigned int id; //!< The Mission ID that the task belongs to + UNUSED(unsigned int locStatus); //!< ??? + unsigned int taskType; //!< The task type + unsigned int target; //!< The mission target + std::string targetGroup; //!< The mission target group + int targetValue; //!< The target value + std::string taskParam1; //!< The task param 1 + UNUSED(std::string largeTaskIcon); //!< ??? + UNUSED(unsigned int IconID); //!< ??? + unsigned int uid; //!< ??? + UNUSED(unsigned int largeTaskIconID); //!< ??? + UNUSED(bool localize); //!< Whether or not the task should be localized + UNUSED(std::string gate_version); //!< ??? }; //! ObjectSkills table class CDMissionTasksTable : public CDTable { private: - std::vector entries; - -public: - - //! Constructor - CDMissionTasksTable(void); - - //! Destructor - ~CDMissionTasksTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); + std::vector entries; - std::vector GetByMissionID(uint32_t missionID); - - //! Gets all the entries in the table - /*! - \return The entries - */ - const std::vector& GetEntries(void) const; +public: + + //! Constructor + CDMissionTasksTable(void); + + //! Destructor + ~CDMissionTasksTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + std::vector GetByMissionID(uint32_t missionID); + + //! Gets all the entries in the table + /*! + \return The entries + */ + const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/Tables/CDMissionsTable.cpp b/dDatabase/Tables/CDMissionsTable.cpp index 58243bd8..7e59657d 100644 --- a/dDatabase/Tables/CDMissionsTable.cpp +++ b/dDatabase/Tables/CDMissionsTable.cpp @@ -4,136 +4,130 @@ CDMissions CDMissionsTable::Default = {}; //! Constructor CDMissionsTable::CDMissionsTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Missions"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Missions"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions"); - while (!tableData.eof()) { - CDMissions entry; - entry.id = tableData.getIntField(0, -1); - entry.defined_type = tableData.getStringField(1, ""); - entry.defined_subtype = tableData.getStringField(2, ""); - entry.UISortOrder = tableData.getIntField(3, -1); - entry.offer_objectID = tableData.getIntField(4, -1); - entry.target_objectID = tableData.getIntField(5, -1); - entry.reward_currency = tableData.getInt64Field(6, -1); - entry.LegoScore = tableData.getIntField(7, -1); - entry.reward_reputation = tableData.getIntField(8, -1); - entry.isChoiceReward = tableData.getIntField(9, -1) == 1 ? true : false; - entry.reward_item1 = tableData.getIntField(10, 0); - entry.reward_item1_count = tableData.getIntField(11, 0); - entry.reward_item2 = tableData.getIntField(12, 0); - entry.reward_item2_count = tableData.getIntField(13, 0); - entry.reward_item3 = tableData.getIntField(14, 0); - entry.reward_item3_count = tableData.getIntField(15, 0); - entry.reward_item4 = tableData.getIntField(16, 0); - entry.reward_item4_count = tableData.getIntField(17, 0); - entry.reward_emote = tableData.getIntField(18, -1); - entry.reward_emote2 = tableData.getIntField(19, -1); - entry.reward_emote3 = tableData.getIntField(20, -1); - entry.reward_emote4 = tableData.getIntField(21, -1); - entry.reward_maximagination = tableData.getIntField(22, -1); - entry.reward_maxhealth = tableData.getIntField(23, -1); - entry.reward_maxinventory = tableData.getIntField(24, -1); - entry.reward_maxmodel = tableData.getIntField(25, -1); - entry.reward_maxwidget = tableData.getIntField(26, -1); - entry.reward_maxwallet = tableData.getIntField(27, -1); - entry.repeatable = tableData.getIntField(28, -1) == 1 ? true : false; - entry.reward_currency_repeatable = tableData.getIntField(29, -1); - entry.reward_item1_repeatable = tableData.getIntField(30, -1); - entry.reward_item1_repeat_count = tableData.getIntField(31, -1); - entry.reward_item2_repeatable = tableData.getIntField(32, -1); - entry.reward_item2_repeat_count = tableData.getIntField(33, -1); - entry.reward_item3_repeatable = tableData.getIntField(34, -1); - entry.reward_item3_repeat_count = tableData.getIntField(35, -1); - entry.reward_item4_repeatable = tableData.getIntField(36, -1); - entry.reward_item4_repeat_count = tableData.getIntField(37, -1); - entry.time_limit = tableData.getIntField(38, -1); - entry.isMission = tableData.getIntField(39, -1) ? true : false; - entry.missionIconID = tableData.getIntField(40, -1); - entry.prereqMissionID = tableData.getStringField(41, ""); - entry.localize = tableData.getIntField(42, -1) == 1 ? true : false; - entry.inMOTD = tableData.getIntField(43, -1) == 1 ? true : false; - entry.cooldownTime = tableData.getInt64Field(44, -1); - entry.isRandom = tableData.getIntField(45, -1) == 1 ? true : false; - entry.randomPool = tableData.getStringField(46, ""); - entry.UIPrereqID = tableData.getIntField(47, -1); - UNUSED(entry.gate_version = tableData.getStringField(48, "")); - UNUSED(entry.HUDStates = tableData.getStringField(49, "")); - UNUSED(entry.locStatus = tableData.getIntField(50, -1)); - entry.reward_bankinventory = tableData.getIntField(51, -1); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions"); + while (!tableData.eof()) { + CDMissions entry; + entry.id = tableData.getIntField(0, -1); + entry.defined_type = tableData.getStringField(1, ""); + entry.defined_subtype = tableData.getStringField(2, ""); + entry.UISortOrder = tableData.getIntField(3, -1); + entry.offer_objectID = tableData.getIntField(4, -1); + entry.target_objectID = tableData.getIntField(5, -1); + entry.reward_currency = tableData.getInt64Field(6, -1); + entry.LegoScore = tableData.getIntField(7, -1); + entry.reward_reputation = tableData.getIntField(8, -1); + entry.isChoiceReward = tableData.getIntField(9, -1) == 1 ? true : false; + entry.reward_item1 = tableData.getIntField(10, 0); + entry.reward_item1_count = tableData.getIntField(11, 0); + entry.reward_item2 = tableData.getIntField(12, 0); + entry.reward_item2_count = tableData.getIntField(13, 0); + entry.reward_item3 = tableData.getIntField(14, 0); + entry.reward_item3_count = tableData.getIntField(15, 0); + entry.reward_item4 = tableData.getIntField(16, 0); + entry.reward_item4_count = tableData.getIntField(17, 0); + entry.reward_emote = tableData.getIntField(18, -1); + entry.reward_emote2 = tableData.getIntField(19, -1); + entry.reward_emote3 = tableData.getIntField(20, -1); + entry.reward_emote4 = tableData.getIntField(21, -1); + entry.reward_maximagination = tableData.getIntField(22, -1); + entry.reward_maxhealth = tableData.getIntField(23, -1); + entry.reward_maxinventory = tableData.getIntField(24, -1); + entry.reward_maxmodel = tableData.getIntField(25, -1); + entry.reward_maxwidget = tableData.getIntField(26, -1); + entry.reward_maxwallet = tableData.getIntField(27, -1); + entry.repeatable = tableData.getIntField(28, -1) == 1 ? true : false; + entry.reward_currency_repeatable = tableData.getIntField(29, -1); + entry.reward_item1_repeatable = tableData.getIntField(30, -1); + entry.reward_item1_repeat_count = tableData.getIntField(31, -1); + entry.reward_item2_repeatable = tableData.getIntField(32, -1); + entry.reward_item2_repeat_count = tableData.getIntField(33, -1); + entry.reward_item3_repeatable = tableData.getIntField(34, -1); + entry.reward_item3_repeat_count = tableData.getIntField(35, -1); + entry.reward_item4_repeatable = tableData.getIntField(36, -1); + entry.reward_item4_repeat_count = tableData.getIntField(37, -1); + entry.time_limit = tableData.getIntField(38, -1); + entry.isMission = tableData.getIntField(39, -1) ? true : false; + entry.missionIconID = tableData.getIntField(40, -1); + entry.prereqMissionID = tableData.getStringField(41, ""); + entry.localize = tableData.getIntField(42, -1) == 1 ? true : false; + entry.inMOTD = tableData.getIntField(43, -1) == 1 ? true : false; + entry.cooldownTime = tableData.getInt64Field(44, -1); + entry.isRandom = tableData.getIntField(45, -1) == 1 ? true : false; + entry.randomPool = tableData.getStringField(46, ""); + entry.UIPrereqID = tableData.getIntField(47, -1); + UNUSED(entry.gate_version = tableData.getStringField(48, "")); + UNUSED(entry.HUDStates = tableData.getStringField(49, "")); + UNUSED(entry.locStatus = tableData.getIntField(50, -1)); + entry.reward_bankinventory = tableData.getIntField(51, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); - Default.id = -1; + Default.id = -1; } //! Destructor -CDMissionsTable::~CDMissionsTable(void) { } +CDMissionsTable::~CDMissionsTable(void) {} //! Returns the table's name std::string CDMissionsTable::GetName(void) const { - return "Missions"; + return "Missions"; } //! Queries the table with a custom "where" clause std::vector CDMissionsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table const std::vector& CDMissionsTable::GetEntries(void) const { - return this->entries; + return this->entries; } -const CDMissions* CDMissionsTable::GetPtrByMissionID(uint32_t missionID) const -{ - for (const auto& entry : entries) - { - if (entry.id == missionID) - { - return const_cast(&entry); - } - } +const CDMissions* CDMissionsTable::GetPtrByMissionID(uint32_t missionID) const { + for (const auto& entry : entries) { + if (entry.id == missionID) { + return const_cast(&entry); + } + } - return &Default; + return &Default; } -const CDMissions& CDMissionsTable::GetByMissionID(uint32_t missionID, bool& found) const -{ - for (const auto& entry : entries) - { - if (entry.id == missionID) - { - found = true; +const CDMissions& CDMissionsTable::GetByMissionID(uint32_t missionID, bool& found) const { + for (const auto& entry : entries) { + if (entry.id == missionID) { + found = true; - return entry; - } - } + return entry; + } + } - found = false; + found = false; - return Default; + return Default; } diff --git a/dDatabase/Tables/CDMissionsTable.h b/dDatabase/Tables/CDMissionsTable.h index c961bb80..6d1c4a8f 100644 --- a/dDatabase/Tables/CDMissionsTable.h +++ b/dDatabase/Tables/CDMissionsTable.h @@ -10,97 +10,97 @@ \brief Contains data for the Missions table */ -//! Missions Struct + //! Missions Struct struct CDMissions { - int id; //!< The Mission ID - std::string defined_type; //!< The type of mission - std::string defined_subtype; //!< The subtype of the mission - int UISortOrder; //!< The UI Sort Order for the mission - int offer_objectID; //!< The LOT of the mission giver - int target_objectID; //!< The LOT of the mission's target - int64_t reward_currency; //!< The amount of currency to reward the player - int LegoScore; //!< The amount of LEGO Score to reward the player - int64_t reward_reputation; //!< The reputation to award the player - bool isChoiceReward; //!< Whether or not the user has the option to choose their loot - int reward_item1; //!< The first rewarded item - int reward_item1_count; //!< The count of the first item to be rewarded - int reward_item2; //!< The second rewarded item - int reward_item2_count; //!< The count of the second item to be rewarded - int reward_item3; //!< The third rewarded item - int reward_item3_count; //!< The count of the third item to be rewarded - int reward_item4; //!< The fourth rewarded item - int reward_item4_count; //!< The count of the fourth item to be rewarded - int reward_emote; //!< The first emote to be rewarded - int reward_emote2; //!< The second emote to be rewarded - int reward_emote3; //!< The third emote to be rewarded - int reward_emote4; //!< The fourth emote to be rewarded - int reward_maximagination; //!< The amount of max imagination to reward - int reward_maxhealth; //!< The amount of max health to reward - int reward_maxinventory; //!< The amount of max inventory to reward - int reward_maxmodel; //!< ??? - int reward_maxwidget; //!< ??? - int reward_maxwallet; //!< ??? - bool repeatable; //!< Whether or not this mission can be repeated (for instance, is it a daily mission) - int64_t reward_currency_repeatable; //!< The repeatable reward - int reward_item1_repeatable; //!< The first rewarded item - int reward_item1_repeat_count; //!< The count of the first item to be rewarded - int reward_item2_repeatable; //!< The second rewarded item - int reward_item2_repeat_count; //!< The count of the second item to be rewarded - int reward_item3_repeatable; //!< The third rewarded item - int reward_item3_repeat_count; //!< The count of the third item to be rewarded - int reward_item4_repeatable; //!< The fourth rewarded item - int reward_item4_repeat_count; //!< The count of the fourth item to be rewarded - int time_limit; //!< The time limit of the mission - bool isMission; //!< Maybe to differentiate between missions and achievements? - int missionIconID; //!< The mission icon ID - std::string prereqMissionID; //!< A '|' seperated list of prerequisite missions - bool localize; //!< Whether or not to localize the mission - bool inMOTD; //!< In Match of the Day(?) - int64_t cooldownTime; //!< The mission cooldown time - bool isRandom; //!< ??? - std::string randomPool; //!< ??? - int UIPrereqID; //!< ??? - UNUSED(std::string gate_version); //!< The gate version - UNUSED(std::string HUDStates); //!< ??? - UNUSED(int locStatus); //!< ??? - int reward_bankinventory; //!< The amount of bank space this mission rewards + int id; //!< The Mission ID + std::string defined_type; //!< The type of mission + std::string defined_subtype; //!< The subtype of the mission + int UISortOrder; //!< The UI Sort Order for the mission + int offer_objectID; //!< The LOT of the mission giver + int target_objectID; //!< The LOT of the mission's target + int64_t reward_currency; //!< The amount of currency to reward the player + int LegoScore; //!< The amount of LEGO Score to reward the player + int64_t reward_reputation; //!< The reputation to award the player + bool isChoiceReward; //!< Whether or not the user has the option to choose their loot + int reward_item1; //!< The first rewarded item + int reward_item1_count; //!< The count of the first item to be rewarded + int reward_item2; //!< The second rewarded item + int reward_item2_count; //!< The count of the second item to be rewarded + int reward_item3; //!< The third rewarded item + int reward_item3_count; //!< The count of the third item to be rewarded + int reward_item4; //!< The fourth rewarded item + int reward_item4_count; //!< The count of the fourth item to be rewarded + int reward_emote; //!< The first emote to be rewarded + int reward_emote2; //!< The second emote to be rewarded + int reward_emote3; //!< The third emote to be rewarded + int reward_emote4; //!< The fourth emote to be rewarded + int reward_maximagination; //!< The amount of max imagination to reward + int reward_maxhealth; //!< The amount of max health to reward + int reward_maxinventory; //!< The amount of max inventory to reward + int reward_maxmodel; //!< ??? + int reward_maxwidget; //!< ??? + int reward_maxwallet; //!< ??? + bool repeatable; //!< Whether or not this mission can be repeated (for instance, is it a daily mission) + int64_t reward_currency_repeatable; //!< The repeatable reward + int reward_item1_repeatable; //!< The first rewarded item + int reward_item1_repeat_count; //!< The count of the first item to be rewarded + int reward_item2_repeatable; //!< The second rewarded item + int reward_item2_repeat_count; //!< The count of the second item to be rewarded + int reward_item3_repeatable; //!< The third rewarded item + int reward_item3_repeat_count; //!< The count of the third item to be rewarded + int reward_item4_repeatable; //!< The fourth rewarded item + int reward_item4_repeat_count; //!< The count of the fourth item to be rewarded + int time_limit; //!< The time limit of the mission + bool isMission; //!< Maybe to differentiate between missions and achievements? + int missionIconID; //!< The mission icon ID + std::string prereqMissionID; //!< A '|' seperated list of prerequisite missions + bool localize; //!< Whether or not to localize the mission + bool inMOTD; //!< In Match of the Day(?) + int64_t cooldownTime; //!< The mission cooldown time + bool isRandom; //!< ??? + std::string randomPool; //!< ??? + int UIPrereqID; //!< ??? + UNUSED(std::string gate_version); //!< The gate version + UNUSED(std::string HUDStates); //!< ??? + UNUSED(int locStatus); //!< ??? + int reward_bankinventory; //!< The amount of bank space this mission rewards }; //! Missions table class CDMissionsTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDMissionsTable(void); - - //! Destructor - ~CDMissionsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ - const std::vector& GetEntries(void) const; + //! Constructor + CDMissionsTable(void); - const CDMissions* GetPtrByMissionID(uint32_t missionID) const; + //! Destructor + ~CDMissionsTable(void); - const CDMissions& GetByMissionID(uint32_t missionID, bool& found) const; + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; - static CDMissions Default; + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + const std::vector& GetEntries(void) const; + + const CDMissions* GetPtrByMissionID(uint32_t missionID) const; + + const CDMissions& GetByMissionID(uint32_t missionID, bool& found) const; + + static CDMissions Default; }; diff --git a/dDatabase/Tables/CDMovementAIComponentTable.cpp b/dDatabase/Tables/CDMovementAIComponentTable.cpp index d4fe4881..a98be8ba 100644 --- a/dDatabase/Tables/CDMovementAIComponentTable.cpp +++ b/dDatabase/Tables/CDMovementAIComponentTable.cpp @@ -11,9 +11,9 @@ CDMovementAIComponentTable::CDMovementAIComponentTable(void) { tableSize.nextRow(); } - + tableSize.finalize(); - + // Reserve the size this->entries.reserve(size); @@ -38,7 +38,7 @@ CDMovementAIComponentTable::CDMovementAIComponentTable(void) { } //! Destructor -CDMovementAIComponentTable::~CDMovementAIComponentTable(void) { } +CDMovementAIComponentTable::~CDMovementAIComponentTable(void) {} //! Returns the table's name std::string CDMovementAIComponentTable::GetName(void) const { diff --git a/dDatabase/Tables/CDObjectSkillsTable.cpp b/dDatabase/Tables/CDObjectSkillsTable.cpp index 4b133df8..1a5c4790 100644 --- a/dDatabase/Tables/CDObjectSkillsTable.cpp +++ b/dDatabase/Tables/CDObjectSkillsTable.cpp @@ -2,56 +2,56 @@ //! Constructor CDObjectSkillsTable::CDObjectSkillsTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ObjectSkills"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ObjectSkills"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ObjectSkills"); - while (!tableData.eof()) { - CDObjectSkills entry; - entry.objectTemplate = tableData.getIntField(0, -1); - entry.skillID = tableData.getIntField(1, -1); - entry.castOnType = tableData.getIntField(2, -1); - entry.AICombatWeight = tableData.getIntField(3, -1); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ObjectSkills"); + while (!tableData.eof()) { + CDObjectSkills entry; + entry.objectTemplate = tableData.getIntField(0, -1); + entry.skillID = tableData.getIntField(1, -1); + entry.castOnType = tableData.getIntField(2, -1); + entry.AICombatWeight = tableData.getIntField(3, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDObjectSkillsTable::~CDObjectSkillsTable(void) { } +CDObjectSkillsTable::~CDObjectSkillsTable(void) {} //! Returns the table's name std::string CDObjectSkillsTable::GetName(void) const { - return "ObjectSkills"; + return "ObjectSkills"; } //! Queries the table with a custom "where" clause std::vector CDObjectSkillsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDObjectSkillsTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDObjectSkillsTable.h b/dDatabase/Tables/CDObjectSkillsTable.h index 986d95d4..c2caf71b 100644 --- a/dDatabase/Tables/CDObjectSkillsTable.h +++ b/dDatabase/Tables/CDObjectSkillsTable.h @@ -8,44 +8,44 @@ \brief Contains data for the ObjectSkills table */ -//! ObjectSkills Struct + //! ObjectSkills Struct struct CDObjectSkills { - unsigned int objectTemplate; //!< The LOT of the item - unsigned int skillID; //!< The Skill ID of the object - unsigned int castOnType; //!< ??? - unsigned int AICombatWeight; //!< ??? + unsigned int objectTemplate; //!< The LOT of the item + unsigned int skillID; //!< The Skill ID of the object + unsigned int castOnType; //!< ??? + unsigned int AICombatWeight; //!< ??? }; //! ObjectSkills table class CDObjectSkillsTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDObjectSkillsTable(void); - - //! Destructor - ~CDObjectSkillsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDObjectSkillsTable(void); + + //! Destructor + ~CDObjectSkillsTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDObjectsTable.cpp b/dDatabase/Tables/CDObjectsTable.cpp index 5106f96a..03979af2 100644 --- a/dDatabase/Tables/CDObjectsTable.cpp +++ b/dDatabase/Tables/CDObjectsTable.cpp @@ -3,39 +3,39 @@ //! Constructor CDObjectsTable::CDObjectsTable(void) { #ifdef CDCLIENT_CACHE_ALL - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Objects"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Objects"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Objects"); - while (!tableData.eof()) { - CDObjects entry; - entry.id = tableData.getIntField(0, -1); - entry.name = tableData.getStringField(1, ""); - entry.placeable = tableData.getIntField(2, -1); - entry.type = tableData.getStringField(3, ""); - entry.description = tableData.getStringField(4, ""); - entry.localize = tableData.getIntField(5, -1); - entry.npcTemplateID = tableData.getIntField(6, -1); - entry.displayName = tableData.getStringField(7, ""); - entry.interactionDistance = tableData.getFloatField(8, -1.0f); - entry.nametag = tableData.getIntField(9, -1); - entry._internalNotes = tableData.getStringField(10, ""); - entry.locStatus = tableData.getIntField(11, -1); - entry.gate_version = tableData.getStringField(12, ""); - entry.HQ_valid = tableData.getIntField(13, -1); - - this->entries.insert(std::make_pair(entry.id, entry)); - tableData.nextRow(); - } + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Objects"); + while (!tableData.eof()) { + CDObjects entry; + entry.id = tableData.getIntField(0, -1); + entry.name = tableData.getStringField(1, ""); + entry.placeable = tableData.getIntField(2, -1); + entry.type = tableData.getStringField(3, ""); + entry.description = tableData.getStringField(4, ""); + entry.localize = tableData.getIntField(5, -1); + entry.npcTemplateID = tableData.getIntField(6, -1); + entry.displayName = tableData.getStringField(7, ""); + entry.interactionDistance = tableData.getFloatField(8, -1.0f); + entry.nametag = tableData.getIntField(9, -1); + entry._internalNotes = tableData.getStringField(10, ""); + entry.locStatus = tableData.getIntField(11, -1); + entry.gate_version = tableData.getStringField(12, ""); + entry.HQ_valid = tableData.getIntField(13, -1); + + this->entries.insert(std::make_pair(entry.id, entry)); + tableData.nextRow(); + } tableData.finalize(); #endif @@ -44,14 +44,14 @@ CDObjectsTable::CDObjectsTable(void) { } //! Destructor -CDObjectsTable::~CDObjectsTable(void) { } +CDObjectsTable::~CDObjectsTable(void) {} //! Returns the table's name std::string CDObjectsTable::GetName(void) const { - return "Objects"; + return "Objects"; } -const CDObjects & CDObjectsTable::GetByID(unsigned int LOT) { +const CDObjects& CDObjectsTable::GetByID(unsigned int LOT) { const auto& it = this->entries.find(LOT); if (it != this->entries.end()) { return it->second; @@ -63,32 +63,32 @@ const CDObjects & CDObjectsTable::GetByID(unsigned int LOT) { query << "SELECT * FROM Objects WHERE id = " << std::to_string(LOT); auto tableData = CDClientDatabase::ExecuteQuery(query.str()); - if (tableData.eof()) { - this->entries.insert(std::make_pair(LOT, m_default)); + if (tableData.eof()) { + this->entries.insert(std::make_pair(LOT, m_default)); return m_default; } - // Now get the data - while (!tableData.eof()) { - CDObjects entry; - entry.id = tableData.getIntField(0, -1); - entry.name = tableData.getStringField(1, ""); - UNUSED(entry.placeable = tableData.getIntField(2, -1)); - entry.type = tableData.getStringField(3, ""); - UNUSED(ntry.description = tableData.getStringField(4, "")); - UNUSED(entry.localize = tableData.getIntField(5, -1)); - UNUSED(entry.npcTemplateID = tableData.getIntField(6, -1)); - UNUSED(entry.displayName = tableData.getStringField(7, "")); - entry.interactionDistance = tableData.getFloatField(8, -1.0f); - UNUSED(entry.nametag = tableData.getIntField(9, -1)); - UNUSED(entry._internalNotes = tableData.getStringField(10, "")); - UNUSED(entry.locStatus = tableData.getIntField(11, -1)); - UNUSED(entry.gate_version = tableData.getStringField(12, "")); - UNUSED(entry.HQ_valid = tableData.getIntField(13, -1)); - - this->entries.insert(std::make_pair(entry.id, entry)); - tableData.nextRow(); - } + // Now get the data + while (!tableData.eof()) { + CDObjects entry; + entry.id = tableData.getIntField(0, -1); + entry.name = tableData.getStringField(1, ""); + UNUSED(entry.placeable = tableData.getIntField(2, -1)); + entry.type = tableData.getStringField(3, ""); + UNUSED(ntry.description = tableData.getStringField(4, "")); + UNUSED(entry.localize = tableData.getIntField(5, -1)); + UNUSED(entry.npcTemplateID = tableData.getIntField(6, -1)); + UNUSED(entry.displayName = tableData.getStringField(7, "")); + entry.interactionDistance = tableData.getFloatField(8, -1.0f); + UNUSED(entry.nametag = tableData.getIntField(9, -1)); + UNUSED(entry._internalNotes = tableData.getStringField(10, "")); + UNUSED(entry.locStatus = tableData.getIntField(11, -1)); + UNUSED(entry.gate_version = tableData.getStringField(12, "")); + UNUSED(entry.HQ_valid = tableData.getIntField(13, -1)); + + this->entries.insert(std::make_pair(entry.id, entry)); + tableData.nextRow(); + } tableData.finalize(); @@ -99,4 +99,4 @@ const CDObjects & CDObjectsTable::GetByID(unsigned int LOT) { #endif return m_default; -} \ No newline at end of file +} diff --git a/dDatabase/Tables/CDObjectsTable.h b/dDatabase/Tables/CDObjectsTable.h index c6dbc662..333477bd 100644 --- a/dDatabase/Tables/CDObjectsTable.h +++ b/dDatabase/Tables/CDObjectsTable.h @@ -8,45 +8,45 @@ \brief Contains data for the Objects table */ -//! RebuildComponent Struct + //! RebuildComponent Struct struct CDObjects { - unsigned int id; //!< The LOT of the object - std::string name; //!< The internal name of the object - UNUSED(unsigned int placeable); //!< Whether or not the object is placable - std::string type; //!< The object type - UNUSED(std::string description); //!< An internal description of the object - UNUSED(unsigned int localize); //!< Whether or not the object should localize - UNUSED(unsigned int npcTemplateID); //!< Something related to NPCs... - UNUSED(std::string displayName); //!< The display name of the object - float interactionDistance; //!< The interaction distance of the object - UNUSED(unsigned int nametag); //!< ??? - UNUSED(std::string _internalNotes); //!< Some internal notes (rarely used) - UNUSED(unsigned int locStatus); //!< ??? - UNUSED(std::string gate_version); //!< The gate version for the object - UNUSED(unsigned int HQ_valid); //!< Probably used for the Nexus HQ database on LEGOUniverse.com + unsigned int id; //!< The LOT of the object + std::string name; //!< The internal name of the object + UNUSED(unsigned int placeable); //!< Whether or not the object is placable + std::string type; //!< The object type + UNUSED(std::string description); //!< An internal description of the object + UNUSED(unsigned int localize); //!< Whether or not the object should localize + UNUSED(unsigned int npcTemplateID); //!< Something related to NPCs... + UNUSED(std::string displayName); //!< The display name of the object + float interactionDistance; //!< The interaction distance of the object + UNUSED(unsigned int nametag); //!< ??? + UNUSED(std::string _internalNotes); //!< Some internal notes (rarely used) + UNUSED(unsigned int locStatus); //!< ??? + UNUSED(std::string gate_version); //!< The gate version for the object + UNUSED(unsigned int HQ_valid); //!< Probably used for the Nexus HQ database on LEGOUniverse.com }; //! ObjectSkills table class CDObjectsTable : public CDTable { private: - //std::vector entries; + //std::vector entries; std::map entries; CDObjects m_default; - + public: - - //! Constructor - CDObjectsTable(void); - - //! Destructor - ~CDObjectsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - + + //! Constructor + CDObjectsTable(void); + + //! Destructor + ~CDObjectsTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + //! Gets an entry by ID const CDObjects& GetByID(unsigned int LOT); diff --git a/dDatabase/Tables/CDPackageComponentTable.cpp b/dDatabase/Tables/CDPackageComponentTable.cpp index 23af5e38..83673c6f 100644 --- a/dDatabase/Tables/CDPackageComponentTable.cpp +++ b/dDatabase/Tables/CDPackageComponentTable.cpp @@ -11,9 +11,9 @@ CDPackageComponentTable::CDPackageComponentTable(void) { tableSize.nextRow(); } - + tableSize.finalize(); - + // Reserve the size this->entries.reserve(size); @@ -33,7 +33,7 @@ CDPackageComponentTable::CDPackageComponentTable(void) { } //! Destructor -CDPackageComponentTable::~CDPackageComponentTable(void) { } +CDPackageComponentTable::~CDPackageComponentTable(void) {} //! Returns the table's name std::string CDPackageComponentTable::GetName(void) const { @@ -53,4 +53,4 @@ std::vector CDPackageComponentTable::Query(std::function CDPackageComponentTable::GetEntries(void) const { return this->entries; -} \ No newline at end of file +} diff --git a/dDatabase/Tables/CDPhysicsComponentTable.cpp b/dDatabase/Tables/CDPhysicsComponentTable.cpp index b4b836ae..8cb7a3b0 100644 --- a/dDatabase/Tables/CDPhysicsComponentTable.cpp +++ b/dDatabase/Tables/CDPhysicsComponentTable.cpp @@ -1,10 +1,10 @@ #include "CDPhysicsComponentTable.h" CDPhysicsComponentTable::CDPhysicsComponentTable(void) { - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PhysicsComponent"); - while (!tableData.eof()) { + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PhysicsComponent"); + while (!tableData.eof()) { CDPhysicsComponent* entry = new CDPhysicsComponent(); - entry->id = tableData.getIntField(0, -1); + entry->id = tableData.getIntField(0, -1); entry->bStatic = tableData.getIntField(1, -1) != 0; entry->physicsAsset = tableData.getStringField(2, ""); UNUSED(entry->jump = tableData.getIntField(3, -1) != 0); @@ -22,28 +22,28 @@ CDPhysicsComponentTable::CDPhysicsComponentTable(void) { UNUSED(entry->gravityVolumeAsset = tableData.getStringField(15)); m_entries.insert(std::make_pair(entry->id, entry)); - tableData.nextRow(); - } + tableData.nextRow(); + } tableData.finalize(); } CDPhysicsComponentTable::~CDPhysicsComponentTable(void) { - for (auto e : m_entries) { - if (e.second) delete e.second; - } - - m_entries.clear(); + for (auto e : m_entries) { + if (e.second) delete e.second; + } + + m_entries.clear(); } std::string CDPhysicsComponentTable::GetName(void) const { - return "PhysicsComponent"; + return "PhysicsComponent"; } CDPhysicsComponent* CDPhysicsComponentTable::GetByID(unsigned int componentID) { - for (auto e : m_entries) { + for (auto e : m_entries) { if (e.first == componentID) return e.second; - } - - return nullptr; + } + + return nullptr; } diff --git a/dDatabase/Tables/CDPhysicsComponentTable.h b/dDatabase/Tables/CDPhysicsComponentTable.h index aa19757f..c5805da3 100644 --- a/dDatabase/Tables/CDPhysicsComponentTable.h +++ b/dDatabase/Tables/CDPhysicsComponentTable.h @@ -23,12 +23,12 @@ struct CDPhysicsComponent { class CDPhysicsComponentTable : public CDTable { public: - CDPhysicsComponentTable(void); - ~CDPhysicsComponentTable(void); - - std::string GetName(void) const override; + CDPhysicsComponentTable(void); + ~CDPhysicsComponentTable(void); + + std::string GetName(void) const override; CDPhysicsComponent* GetByID(unsigned int componentID); private: std::map m_entries; -}; \ No newline at end of file +}; diff --git a/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp b/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp index 500ef659..01a2ae37 100644 --- a/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp +++ b/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp @@ -3,31 +3,31 @@ CDPropertyEntranceComponentTable::CDPropertyEntranceComponentTable() { - // First, get the size of the table - size_t size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM PropertyEntranceComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - tableSize.nextRow(); - } - + // First, get the size of the table + size_t size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM PropertyEntranceComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + tableSize.nextRow(); + } + tableSize.finalize(); - - this->entries.reserve(size); - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyEntranceComponent;"); - while (!tableData.eof()) { - auto entry = CDPropertyEntranceComponent { - static_cast(tableData.getIntField(0, -1)), - static_cast(tableData.getIntField(1, -1)), - tableData.getStringField(2, ""), - static_cast(tableData.getIntField(3, false)), - tableData.getStringField(4, "") - }; + this->entries.reserve(size); - this->entries.push_back(entry); - tableData.nextRow(); - } + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyEntranceComponent;"); + while (!tableData.eof()) { + auto entry = CDPropertyEntranceComponent{ + static_cast(tableData.getIntField(0, -1)), + static_cast(tableData.getIntField(1, -1)), + tableData.getStringField(2, ""), + static_cast(tableData.getIntField(3, false)), + tableData.getStringField(4, "") + }; + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } @@ -35,14 +35,14 @@ CDPropertyEntranceComponentTable::CDPropertyEntranceComponentTable() { CDPropertyEntranceComponentTable::~CDPropertyEntranceComponentTable(void) = default; std::string CDPropertyEntranceComponentTable::GetName() const { - return "PropertyEntranceComponent"; + return "PropertyEntranceComponent"; } CDPropertyEntranceComponent CDPropertyEntranceComponentTable::GetByID(uint32_t id) { - for (const auto& entry : entries) { - if (entry.id == id) - return entry; - } + for (const auto& entry : entries) { + if (entry.id == id) + return entry; + } - return defaultEntry; + return defaultEntry; } diff --git a/dDatabase/Tables/CDPropertyEntranceComponentTable.h b/dDatabase/Tables/CDPropertyEntranceComponentTable.h index 8cecd941..fa0603c0 100644 --- a/dDatabase/Tables/CDPropertyEntranceComponentTable.h +++ b/dDatabase/Tables/CDPropertyEntranceComponentTable.h @@ -2,40 +2,40 @@ #include "CDTable.h" struct CDPropertyEntranceComponent { - uint32_t id; - uint32_t mapID; - std::string propertyName; - bool isOnProperty; - std::string groupType; + uint32_t id; + uint32_t mapID; + std::string propertyName; + bool isOnProperty; + std::string groupType; }; class CDPropertyEntranceComponentTable : public CDTable { public: - //! Constructor - CDPropertyEntranceComponentTable(); + //! Constructor + CDPropertyEntranceComponentTable(); - //! Destructor - ~CDPropertyEntranceComponentTable(); + //! Destructor + ~CDPropertyEntranceComponentTable(); - //! Returns the table's name - /*! - \return The table name - */ - [[nodiscard]] std::string GetName() const override; + //! Returns the table's name + /*! + \return The table name + */ + [[nodiscard]] std::string GetName() const override; - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - CDPropertyEntranceComponent GetByID(uint32_t id); + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + CDPropertyEntranceComponent GetByID(uint32_t id); - //! Gets all the entries in the table - /*! - \return The entries - */ - [[nodiscard]] std::vector GetEntries() const { return entries; } + //! Gets all the entries in the table + /*! + \return The entries + */ + [[nodiscard]] std::vector GetEntries() const { return entries; } private: - std::vector entries {}; - CDPropertyEntranceComponent defaultEntry {}; + std::vector entries{}; + CDPropertyEntranceComponent defaultEntry{}; }; diff --git a/dDatabase/Tables/CDPropertyTemplateTable.cpp b/dDatabase/Tables/CDPropertyTemplateTable.cpp index 11ba9378..7dd118eb 100644 --- a/dDatabase/Tables/CDPropertyTemplateTable.cpp +++ b/dDatabase/Tables/CDPropertyTemplateTable.cpp @@ -2,30 +2,30 @@ CDPropertyTemplateTable::CDPropertyTemplateTable() { - // First, get the size of the table - size_t size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM PropertyTemplate;"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - tableSize.nextRow(); - } - + // First, get the size of the table + size_t size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM PropertyTemplate;"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + tableSize.nextRow(); + } + tableSize.finalize(); - - this->entries.reserve(size); - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyTemplate;"); - while (!tableData.eof()) { - auto entry = CDPropertyTemplate { - static_cast(tableData.getIntField(0, -1)), - static_cast(tableData.getIntField(1, -1)), - static_cast(tableData.getIntField(2, -1)), - tableData.getStringField(3, "") - }; + this->entries.reserve(size); - this->entries.push_back(entry); - tableData.nextRow(); - } + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyTemplate;"); + while (!tableData.eof()) { + auto entry = CDPropertyTemplate{ + static_cast(tableData.getIntField(0, -1)), + static_cast(tableData.getIntField(1, -1)), + static_cast(tableData.getIntField(2, -1)), + tableData.getStringField(3, "") + }; + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } @@ -33,14 +33,14 @@ CDPropertyTemplateTable::CDPropertyTemplateTable() { CDPropertyTemplateTable::~CDPropertyTemplateTable() = default; std::string CDPropertyTemplateTable::GetName() const { - return "PropertyTemplate"; + return "PropertyTemplate"; } CDPropertyTemplate CDPropertyTemplateTable::GetByMapID(uint32_t mapID) { - for (const auto& entry : entries) { - if (entry.mapID == mapID) - return entry; - } + for (const auto& entry : entries) { + if (entry.mapID == mapID) + return entry; + } - return defaultEntry; + return defaultEntry; } diff --git a/dDatabase/Tables/CDPropertyTemplateTable.h b/dDatabase/Tables/CDPropertyTemplateTable.h index 24e6a739..a266932b 100644 --- a/dDatabase/Tables/CDPropertyTemplateTable.h +++ b/dDatabase/Tables/CDPropertyTemplateTable.h @@ -2,20 +2,20 @@ #include "CDTable.h" struct CDPropertyTemplate { - uint32_t id; - uint32_t mapID; - uint32_t vendorMapID; - std::string spawnName; + uint32_t id; + uint32_t mapID; + uint32_t vendorMapID; + std::string spawnName; }; class CDPropertyTemplateTable : public CDTable { public: - CDPropertyTemplateTable(); - ~CDPropertyTemplateTable(); + CDPropertyTemplateTable(); + ~CDPropertyTemplateTable(); - [[nodiscard]] std::string GetName() const override; - CDPropertyTemplate GetByMapID(uint32_t mapID); + [[nodiscard]] std::string GetName() const override; + CDPropertyTemplate GetByMapID(uint32_t mapID); private: - std::vector entries {}; - CDPropertyTemplate defaultEntry {}; -}; \ No newline at end of file + std::vector entries{}; + CDPropertyTemplate defaultEntry{}; +}; diff --git a/dDatabase/Tables/CDProximityMonitorComponentTable.cpp b/dDatabase/Tables/CDProximityMonitorComponentTable.cpp index d4195f0c..092f3ca1 100644 --- a/dDatabase/Tables/CDProximityMonitorComponentTable.cpp +++ b/dDatabase/Tables/CDProximityMonitorComponentTable.cpp @@ -11,9 +11,9 @@ CDProximityMonitorComponentTable::CDProximityMonitorComponentTable(void) { tableSize.nextRow(); } - + tableSize.finalize(); - + // Reserve the size this->entries.reserve(size); @@ -34,7 +34,7 @@ CDProximityMonitorComponentTable::CDProximityMonitorComponentTable(void) { } //! Destructor -CDProximityMonitorComponentTable::~CDProximityMonitorComponentTable(void) { } +CDProximityMonitorComponentTable::~CDProximityMonitorComponentTable(void) {} //! Returns the table's name std::string CDProximityMonitorComponentTable::GetName(void) const { diff --git a/dDatabase/Tables/CDRailActivatorComponent.cpp b/dDatabase/Tables/CDRailActivatorComponent.cpp index e3a2f8b8..ef72859b 100644 --- a/dDatabase/Tables/CDRailActivatorComponent.cpp +++ b/dDatabase/Tables/CDRailActivatorComponent.cpp @@ -2,82 +2,82 @@ #include "GeneralUtils.h" CDRailActivatorComponentTable::CDRailActivatorComponentTable() { - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RailActivatorComponent;"); - while (!tableData.eof()) { - CDRailActivatorComponent entry; + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RailActivatorComponent;"); + while (!tableData.eof()) { + CDRailActivatorComponent entry; - entry.id = tableData.getIntField(0); + entry.id = tableData.getIntField(0); - std::string startAnimation(tableData.getStringField(1, "")); - entry.startAnimation = GeneralUtils::ASCIIToUTF16(startAnimation); + std::string startAnimation(tableData.getStringField(1, "")); + entry.startAnimation = GeneralUtils::ASCIIToUTF16(startAnimation); - std::string loopAnimation(tableData.getStringField(2, "")); - entry.loopAnimation = GeneralUtils::ASCIIToUTF16(loopAnimation); + std::string loopAnimation(tableData.getStringField(2, "")); + entry.loopAnimation = GeneralUtils::ASCIIToUTF16(loopAnimation); - std::string stopAnimation(tableData.getStringField(3, "")); - entry.stopAnimation = GeneralUtils::ASCIIToUTF16(stopAnimation); + std::string stopAnimation(tableData.getStringField(3, "")); + entry.stopAnimation = GeneralUtils::ASCIIToUTF16(stopAnimation); - std::string startSound(tableData.getStringField(4, "")); - entry.startSound = GeneralUtils::ASCIIToUTF16(startSound); + std::string startSound(tableData.getStringField(4, "")); + entry.startSound = GeneralUtils::ASCIIToUTF16(startSound); - std::string loopSound(tableData.getStringField(5, "")); - entry.loopSound = GeneralUtils::ASCIIToUTF16(loopSound); + std::string loopSound(tableData.getStringField(5, "")); + entry.loopSound = GeneralUtils::ASCIIToUTF16(loopSound); - std::string stopSound(tableData.getStringField(6, "")); - entry.stopSound = GeneralUtils::ASCIIToUTF16(stopSound); + std::string stopSound(tableData.getStringField(6, "")); + entry.stopSound = GeneralUtils::ASCIIToUTF16(stopSound); - std::string loopEffectString(tableData.getStringField(7, "")); - entry.loopEffectID = EffectPairFromString(loopEffectString); + std::string loopEffectString(tableData.getStringField(7, "")); + entry.loopEffectID = EffectPairFromString(loopEffectString); - entry.preconditions = tableData.getStringField(8, "-1"); + entry.preconditions = tableData.getStringField(8, "-1"); - entry.playerCollision = tableData.getIntField(9, 0); + entry.playerCollision = tableData.getIntField(9, 0); - entry.cameraLocked = tableData.getIntField(10, 0); + entry.cameraLocked = tableData.getIntField(10, 0); - std::string startEffectString(tableData.getStringField(11, "")); - entry.startEffectID = EffectPairFromString(startEffectString); + std::string startEffectString(tableData.getStringField(11, "")); + entry.startEffectID = EffectPairFromString(startEffectString); - std::string stopEffectString(tableData.getStringField(12, "")); - entry.stopEffectID = EffectPairFromString(stopEffectString); + std::string stopEffectString(tableData.getStringField(12, "")); + entry.stopEffectID = EffectPairFromString(stopEffectString); - entry.damageImmune = tableData.getIntField(13, 0); + entry.damageImmune = tableData.getIntField(13, 0); - entry.noAggro = tableData.getIntField(14, 0); + entry.noAggro = tableData.getIntField(14, 0); - entry.showNameBillboard = tableData.getIntField(15, 0); + entry.showNameBillboard = tableData.getIntField(15, 0); - m_Entries.push_back(entry); - tableData.nextRow(); - } + m_Entries.push_back(entry); + tableData.nextRow(); + } - tableData.finalize(); + tableData.finalize(); } CDRailActivatorComponentTable::~CDRailActivatorComponentTable() = default; std::string CDRailActivatorComponentTable::GetName() const { - return "RailActivatorComponent"; + return "RailActivatorComponent"; } CDRailActivatorComponent CDRailActivatorComponentTable::GetEntryByID(int32_t id) const { - for (const auto& entry : m_Entries) { - if (entry.id == id) - return entry; - } + for (const auto& entry : m_Entries) { + if (entry.id == id) + return entry; + } - return {}; + return {}; } std::vector CDRailActivatorComponentTable::GetEntries() const { - return m_Entries; + return m_Entries; } -std::pair CDRailActivatorComponentTable::EffectPairFromString(std::string &str) { - const auto split = GeneralUtils::SplitString(str, ':'); - if (split.size() == 2) { - return { std::stoi(split.at(0)), GeneralUtils::ASCIIToUTF16(split.at(1)) }; - } +std::pair CDRailActivatorComponentTable::EffectPairFromString(std::string& str) { + const auto split = GeneralUtils::SplitString(str, ':'); + if (split.size() == 2) { + return { std::stoi(split.at(0)), GeneralUtils::ASCIIToUTF16(split.at(1)) }; + } - return {}; + return {}; } diff --git a/dDatabase/Tables/CDRailActivatorComponent.h b/dDatabase/Tables/CDRailActivatorComponent.h index 4f06ff5f..b8313e96 100644 --- a/dDatabase/Tables/CDRailActivatorComponent.h +++ b/dDatabase/Tables/CDRailActivatorComponent.h @@ -2,33 +2,33 @@ #include "CDTable.h" struct CDRailActivatorComponent { - int32_t id; - std::u16string startAnimation; - std::u16string loopAnimation; - std::u16string stopAnimation; - std::u16string startSound; - std::u16string loopSound; - std::u16string stopSound; - std::pair startEffectID; - std::pair loopEffectID; - std::pair stopEffectID; - std::string preconditions; - bool playerCollision; - bool cameraLocked; - bool damageImmune; - bool noAggro; - bool showNameBillboard; + int32_t id; + std::u16string startAnimation; + std::u16string loopAnimation; + std::u16string stopAnimation; + std::u16string startSound; + std::u16string loopSound; + std::u16string stopSound; + std::pair startEffectID; + std::pair loopEffectID; + std::pair stopEffectID; + std::string preconditions; + bool playerCollision; + bool cameraLocked; + bool damageImmune; + bool noAggro; + bool showNameBillboard; }; class CDRailActivatorComponentTable : public CDTable { public: - CDRailActivatorComponentTable(); - ~CDRailActivatorComponentTable(); + CDRailActivatorComponentTable(); + ~CDRailActivatorComponentTable(); - std::string GetName() const override; - [[nodiscard]] CDRailActivatorComponent GetEntryByID(int32_t id) const; - [[nodiscard]] std::vector GetEntries() const; + std::string GetName() const override; + [[nodiscard]] CDRailActivatorComponent GetEntryByID(int32_t id) const; + [[nodiscard]] std::vector GetEntries() const; private: - static std::pair EffectPairFromString(std::string& str); - std::vector m_Entries {}; + static std::pair EffectPairFromString(std::string& str); + std::vector m_Entries{}; }; diff --git a/dDatabase/Tables/CDRarityTableTable.cpp b/dDatabase/Tables/CDRarityTableTable.cpp index da41e3f3..67878cd2 100644 --- a/dDatabase/Tables/CDRarityTableTable.cpp +++ b/dDatabase/Tables/CDRarityTableTable.cpp @@ -3,55 +3,55 @@ //! Constructor CDRarityTableTable::CDRarityTableTable(void) { - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM RarityTable"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM RarityTable"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } - tableSize.nextRow(); - } - tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RarityTable"); - while (!tableData.eof()) { - CDRarityTable entry; - entry.id = tableData.getIntField(0, -1); - entry.randmax = tableData.getFloatField(1, -1); - entry.rarity = tableData.getIntField(2, -1); - entry.RarityTableIndex = tableData.getIntField(3, -1); + // Reserve the size + this->entries.reserve(size); - this->entries.push_back(entry); - tableData.nextRow(); - } + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RarityTable"); + while (!tableData.eof()) { + CDRarityTable entry; + entry.id = tableData.getIntField(0, -1); + entry.randmax = tableData.getFloatField(1, -1); + entry.rarity = tableData.getIntField(2, -1); + entry.RarityTableIndex = tableData.getIntField(3, -1); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDRarityTableTable::~CDRarityTableTable(void) { } +CDRarityTableTable::~CDRarityTableTable(void) {} //! Returns the table's name std::string CDRarityTableTable::GetName(void) const { - return "RarityTable"; + return "RarityTable"; } //! Queries the table with a custom "where" clause std::vector CDRarityTableTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); - return data; + return data; } //! Gets all the entries in the table const std::vector& CDRarityTableTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDRarityTableTable.h b/dDatabase/Tables/CDRarityTableTable.h index 0a57e903..55cfec4b 100644 --- a/dDatabase/Tables/CDRarityTableTable.h +++ b/dDatabase/Tables/CDRarityTableTable.h @@ -10,63 +10,59 @@ //! RarityTable Entry Struct struct CDRarityTable { - unsigned int id; - float randmax; - unsigned int rarity; - unsigned int RarityTableIndex; + unsigned int id; + float randmax; + unsigned int rarity; + unsigned int RarityTableIndex; - friend bool operator> (const CDRarityTable& c1, const CDRarityTable& c2) - { - return c1.rarity > c2.rarity; - } + friend bool operator> (const CDRarityTable& c1, const CDRarityTable& c2) { + return c1.rarity > c2.rarity; + } - friend bool operator>= (const CDRarityTable& c1, const CDRarityTable& c2) - { - return c1.rarity >= c2.rarity; - } + friend bool operator>= (const CDRarityTable& c1, const CDRarityTable& c2) { + return c1.rarity >= c2.rarity; + } - friend bool operator< (const CDRarityTable& c1, const CDRarityTable& c2) - { - return c1.rarity < c2.rarity; - } + friend bool operator< (const CDRarityTable& c1, const CDRarityTable& c2) { + return c1.rarity < c2.rarity; + } - friend bool operator<= (const CDRarityTable& c1, const CDRarityTable& c2) - { - return c1.rarity <= c2.rarity; - } + friend bool operator<= (const CDRarityTable& c1, const CDRarityTable& c2) { + return c1.rarity <= c2.rarity; + } }; //! RarityTable table class CDRarityTableTable : public CDTable { private: - std::vector entries; + std::vector entries; public: - //! Constructor - CDRarityTableTable(void); + //! Constructor + CDRarityTableTable(void); - //! Destructor - ~CDRarityTableTable(void); + //! Destructor + ~CDRarityTableTable(void); - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ - const std::vector& GetEntries(void) const; + //! Gets all the entries in the table + /*! + \return The entries + */ + const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/Tables/CDRebuildComponentTable.cpp b/dDatabase/Tables/CDRebuildComponentTable.cpp index a1b5646c..c4299b98 100644 --- a/dDatabase/Tables/CDRebuildComponentTable.cpp +++ b/dDatabase/Tables/CDRebuildComponentTable.cpp @@ -2,62 +2,62 @@ //! Constructor CDRebuildComponentTable::CDRebuildComponentTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM RebuildComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM RebuildComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Reserve the size - this->entries.reserve(size); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RebuildComponent"); - while (!tableData.eof()) { - CDRebuildComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.reset_time = tableData.getFloatField(1, -1.0f); - entry.complete_time = tableData.getFloatField(2, -1.0f); - entry.take_imagination = tableData.getIntField(3, -1); - entry.interruptible = tableData.getIntField(4, -1) == 1 ? true : false; - entry.self_activator = tableData.getIntField(5, -1) == 1 ? true : false; - entry.custom_modules = tableData.getStringField(6, ""); - entry.activityID = tableData.getIntField(7, -1); - entry.post_imagination_cost = tableData.getIntField(8, -1); - entry.time_before_smash = tableData.getFloatField(9, -1.0f); - - this->entries.push_back(entry); - tableData.nextRow(); - } + + // Reserve the size + this->entries.reserve(size); + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RebuildComponent"); + while (!tableData.eof()) { + CDRebuildComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.reset_time = tableData.getFloatField(1, -1.0f); + entry.complete_time = tableData.getFloatField(2, -1.0f); + entry.take_imagination = tableData.getIntField(3, -1); + entry.interruptible = tableData.getIntField(4, -1) == 1 ? true : false; + entry.self_activator = tableData.getIntField(5, -1) == 1 ? true : false; + entry.custom_modules = tableData.getStringField(6, ""); + entry.activityID = tableData.getIntField(7, -1); + entry.post_imagination_cost = tableData.getIntField(8, -1); + entry.time_before_smash = tableData.getFloatField(9, -1.0f); + + this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDRebuildComponentTable::~CDRebuildComponentTable(void) { } +CDRebuildComponentTable::~CDRebuildComponentTable(void) {} //! Returns the table's name std::string CDRebuildComponentTable::GetName(void) const { - return "RebuildComponent"; + return "RebuildComponent"; } //! Queries the table with a custom "where" clause std::vector CDRebuildComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; + + std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); + + return data; } //! Gets all the entries in the table std::vector CDRebuildComponentTable::GetEntries(void) const { - return this->entries; + return this->entries; } diff --git a/dDatabase/Tables/CDRebuildComponentTable.h b/dDatabase/Tables/CDRebuildComponentTable.h index 49d2e44f..bdc2da8a 100644 --- a/dDatabase/Tables/CDRebuildComponentTable.h +++ b/dDatabase/Tables/CDRebuildComponentTable.h @@ -8,50 +8,50 @@ \brief Contains data for the RebuildComponent table */ -//! RebuildComponent Struct + //! RebuildComponent Struct struct CDRebuildComponent { - unsigned int id; //!< The component Id - float reset_time; //!< The reset time - float complete_time; //!< The complete time - unsigned int take_imagination; //!< The amount of imagination it costs - bool interruptible; //!< Whether or not the rebuild is interruptible - bool self_activator; //!< Whether or not the rebuild is a rebuild activator itself - std::string custom_modules; //!< The custom modules - unsigned int activityID; //!< The activity ID - unsigned int post_imagination_cost; //!< The post imagination cost - float time_before_smash; //!< The time before smash + unsigned int id; //!< The component Id + float reset_time; //!< The reset time + float complete_time; //!< The complete time + unsigned int take_imagination; //!< The amount of imagination it costs + bool interruptible; //!< Whether or not the rebuild is interruptible + bool self_activator; //!< Whether or not the rebuild is a rebuild activator itself + std::string custom_modules; //!< The custom modules + unsigned int activityID; //!< The activity ID + unsigned int post_imagination_cost; //!< The post imagination cost + float time_before_smash; //!< The time before smash }; //! ObjectSkills table class CDRebuildComponentTable : public CDTable { private: - std::vector entries; - + std::vector entries; + public: - - //! Constructor - CDRebuildComponentTable(void); - - //! Destructor - ~CDRebuildComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); - - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector GetEntries(void) const; - + + //! Constructor + CDRebuildComponentTable(void); + + //! Destructor + ~CDRebuildComponentTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); + + //! Gets all the entries in the table + /*! + \return The entries + */ + std::vector GetEntries(void) const; + }; diff --git a/dDatabase/Tables/CDRewardsTable.cpp b/dDatabase/Tables/CDRewardsTable.cpp index 2f7d1778..99d56f26 100644 --- a/dDatabase/Tables/CDRewardsTable.cpp +++ b/dDatabase/Tables/CDRewardsTable.cpp @@ -1,10 +1,10 @@ #include "CDRewardsTable.h" CDRewardsTable::CDRewardsTable(void) { - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Rewards"); - while (!tableData.eof()) { + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Rewards"); + while (!tableData.eof()) { CDRewards* entry = new CDRewards(); - entry->id = tableData.getIntField(0, -1); + entry->id = tableData.getIntField(0, -1); entry->levelID = tableData.getIntField(1, -1); entry->missionID = tableData.getIntField(2, -1); entry->rewardType = tableData.getIntField(3, -1); @@ -12,29 +12,29 @@ CDRewardsTable::CDRewardsTable(void) { entry->count = tableData.getIntField(5, -1); m_entries.insert(std::make_pair(entry->id, entry)); - tableData.nextRow(); - } + tableData.nextRow(); + } tableData.finalize(); } CDRewardsTable::~CDRewardsTable(void) { - for (auto e : m_entries) { - if (e.second) delete e.second; - } - - m_entries.clear(); + for (auto e : m_entries) { + if (e.second) delete e.second; + } + + m_entries.clear(); } std::string CDRewardsTable::GetName(void) const { - return "Rewards"; + return "Rewards"; } std::vector CDRewardsTable::GetByLevelID(uint32_t levelID) { - std::vector result {}; - for (const auto& e : m_entries) { + std::vector result{}; + for (const auto& e : m_entries) { if (e.second->levelID == levelID) result.push_back(e.second); - } - - return result; + } + + return result; } diff --git a/dDatabase/Tables/CDRewardsTable.h b/dDatabase/Tables/CDRewardsTable.h index c4f9fb70..2edfd2b3 100644 --- a/dDatabase/Tables/CDRewardsTable.h +++ b/dDatabase/Tables/CDRewardsTable.h @@ -13,12 +13,12 @@ struct CDRewards { class CDRewardsTable : public CDTable { public: - CDRewardsTable(void); - ~CDRewardsTable(void); - - std::string GetName(void) const override; + CDRewardsTable(void); + ~CDRewardsTable(void); + + std::string GetName(void) const override; std::vector GetByLevelID(uint32_t levelID); private: std::map m_entries; -}; \ No newline at end of file +}; diff --git a/dDatabase/Tables/CDScriptComponentTable.cpp b/dDatabase/Tables/CDScriptComponentTable.cpp index 11ab75ee..b34f96f1 100644 --- a/dDatabase/Tables/CDScriptComponentTable.cpp +++ b/dDatabase/Tables/CDScriptComponentTable.cpp @@ -2,39 +2,39 @@ //! Constructor CDScriptComponentTable::CDScriptComponentTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ScriptComponent"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ScriptComponent"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ScriptComponent"); - while (!tableData.eof()) { - CDScriptComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.script_name = tableData.getStringField(1, ""); - entry.client_script_name = tableData.getStringField(2, ""); - + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ScriptComponent"); + while (!tableData.eof()) { + CDScriptComponent entry; + entry.id = tableData.getIntField(0, -1); + entry.script_name = tableData.getStringField(1, ""); + entry.client_script_name = tableData.getStringField(2, ""); + this->entries.insert(std::make_pair(entry.id, entry)); - tableData.nextRow(); - } + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDScriptComponentTable::~CDScriptComponentTable(void) { } +CDScriptComponentTable::~CDScriptComponentTable(void) {} //! Returns the table's name std::string CDScriptComponentTable::GetName(void) const { - return "ScriptComponent"; + return "ScriptComponent"; } const CDScriptComponent& CDScriptComponentTable::GetByID(unsigned int id) { @@ -44,4 +44,4 @@ const CDScriptComponent& CDScriptComponentTable::GetByID(unsigned int id) { } return m_ToReturnWhenNoneFound; -} \ No newline at end of file +} diff --git a/dDatabase/Tables/CDScriptComponentTable.h b/dDatabase/Tables/CDScriptComponentTable.h index 7fc802fa..92534cc0 100644 --- a/dDatabase/Tables/CDScriptComponentTable.h +++ b/dDatabase/Tables/CDScriptComponentTable.h @@ -8,39 +8,39 @@ \brief Contains data for the ScriptComponent table */ -//! ScriptComponent Struct + //! ScriptComponent Struct struct CDScriptComponent { - unsigned int id; //!< The component ID - std::string script_name; //!< The script name - std::string client_script_name; //!< The client script name + unsigned int id; //!< The component ID + std::string script_name; //!< The script name + std::string client_script_name; //!< The client script name }; //! ObjectSkills table class CDScriptComponentTable : public CDTable { private: - std::map entries; + std::map entries; CDScriptComponent m_ToReturnWhenNoneFound; - + public: //! Gets an entry by ID const CDScriptComponent& GetByID(unsigned int id); - - //! Constructor - CDScriptComponentTable(void); - - //! Destructor - ~CDScriptComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - + + //! Constructor + CDScriptComponentTable(void); + + //! Destructor + ~CDScriptComponentTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + }; diff --git a/dDatabase/Tables/CDSkillBehaviorTable.cpp b/dDatabase/Tables/CDSkillBehaviorTable.cpp index 88124161..e3986578 100644 --- a/dDatabase/Tables/CDSkillBehaviorTable.cpp +++ b/dDatabase/Tables/CDSkillBehaviorTable.cpp @@ -3,82 +3,82 @@ //! Constructor CDSkillBehaviorTable::CDSkillBehaviorTable(void) { - m_empty = CDSkillBehavior(); + m_empty = CDSkillBehavior(); - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM SkillBehavior"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM SkillBehavior"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); - tableSize.nextRow(); - } + tableSize.nextRow(); + } tableSize.finalize(); - // Reserve the size - //this->entries.reserve(size); + // Reserve the size + //this->entries.reserve(size); - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM SkillBehavior"); - while (!tableData.eof()) { - CDSkillBehavior entry; - entry.skillID = tableData.getIntField(0, -1); - UNUSED(entry.locStatus = tableData.getIntField(1, -1)); - entry.behaviorID = tableData.getIntField(2, -1); - entry.imaginationcost = tableData.getIntField(3, -1); - entry.cooldowngroup = tableData.getIntField(4, -1); - entry.cooldown = tableData.getFloatField(5, -1.0f); - UNUSED(entry.isNpcEditor = tableData.getIntField(6, -1) == 1 ? true : false); - UNUSED(entry.skillIcon = tableData.getIntField(7, -1)); - UNUSED(entry.oomSkillID = tableData.getStringField(8, "")); - UNUSED(entry.oomBehaviorEffectID = tableData.getIntField(9, -1)); - UNUSED(entry.castTypeDesc = tableData.getIntField(10, -1)); - UNUSED(entry.imBonusUI = tableData.getIntField(11, -1)); - UNUSED(entry.lifeBonusUI = tableData.getIntField(12, -1)); - UNUSED(entry.armorBonusUI = tableData.getIntField(13, -1)); - UNUSED(entry.damageUI = tableData.getIntField(14, -1)); - UNUSED(entry.hideIcon = tableData.getIntField(15, -1) == 1 ? true : false); - UNUSED(entry.localize = tableData.getIntField(16, -1) == 1 ? true : false); - UNUSED(entry.gate_version = tableData.getStringField(17, "")); - UNUSED(entry.cancelType = tableData.getIntField(18, -1)); + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM SkillBehavior"); + while (!tableData.eof()) { + CDSkillBehavior entry; + entry.skillID = tableData.getIntField(0, -1); + UNUSED(entry.locStatus = tableData.getIntField(1, -1)); + entry.behaviorID = tableData.getIntField(2, -1); + entry.imaginationcost = tableData.getIntField(3, -1); + entry.cooldowngroup = tableData.getIntField(4, -1); + entry.cooldown = tableData.getFloatField(5, -1.0f); + UNUSED(entry.isNpcEditor = tableData.getIntField(6, -1) == 1 ? true : false); + UNUSED(entry.skillIcon = tableData.getIntField(7, -1)); + UNUSED(entry.oomSkillID = tableData.getStringField(8, "")); + UNUSED(entry.oomBehaviorEffectID = tableData.getIntField(9, -1)); + UNUSED(entry.castTypeDesc = tableData.getIntField(10, -1)); + UNUSED(entry.imBonusUI = tableData.getIntField(11, -1)); + UNUSED(entry.lifeBonusUI = tableData.getIntField(12, -1)); + UNUSED(entry.armorBonusUI = tableData.getIntField(13, -1)); + UNUSED(entry.damageUI = tableData.getIntField(14, -1)); + UNUSED(entry.hideIcon = tableData.getIntField(15, -1) == 1 ? true : false); + UNUSED(entry.localize = tableData.getIntField(16, -1) == 1 ? true : false); + UNUSED(entry.gate_version = tableData.getStringField(17, "")); + UNUSED(entry.cancelType = tableData.getIntField(18, -1)); - this->entries.insert(std::make_pair(entry.skillID, entry)); - //this->entries.push_back(entry); - tableData.nextRow(); - } + this->entries.insert(std::make_pair(entry.skillID, entry)); + //this->entries.push_back(entry); + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDSkillBehaviorTable::~CDSkillBehaviorTable(void) { } +CDSkillBehaviorTable::~CDSkillBehaviorTable(void) {} //! Returns the table's name std::string CDSkillBehaviorTable::GetName(void) const { - return "SkillBehavior"; + return "SkillBehavior"; } //! Queries the table with a custom "where" clause std::vector CDSkillBehaviorTable::Query(std::function predicate) { - /*std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); + /*std::vector data = cpplinq::from(this->entries) + >> cpplinq::where(predicate) + >> cpplinq::to_vector(); - return data;*/ + return data;*/ - //Logger::LogDebug("CDSkillBehaviorTable", "The 'Query' function is no longer working! Please use GetSkillByID instead!"); + //Logger::LogDebug("CDSkillBehaviorTable", "The 'Query' function is no longer working! Please use GetSkillByID instead!"); std::vector data; //So MSVC shuts up return data; } //! Gets an entry by ID const CDSkillBehavior& CDSkillBehaviorTable::GetSkillByID(unsigned int skillID) { - std::map::iterator it = this->entries.find(skillID); - if (it != this->entries.end()) { - return it->second; - } + std::map::iterator it = this->entries.find(skillID); + if (it != this->entries.end()) { + return it->second; + } - return m_empty; + return m_empty; } diff --git a/dDatabase/Tables/CDSkillBehaviorTable.h b/dDatabase/Tables/CDSkillBehaviorTable.h index d70dca56..da8676db 100644 --- a/dDatabase/Tables/CDSkillBehaviorTable.h +++ b/dDatabase/Tables/CDSkillBehaviorTable.h @@ -8,56 +8,56 @@ \brief Contains data for the SkillBehavior table */ -//! ZoneTable Struct + //! ZoneTable Struct struct CDSkillBehavior { - unsigned int skillID; //!< The Skill ID of the skill - UNUSED(unsigned int locStatus); //!< ?? - unsigned int behaviorID; //!< The Behavior ID of the skill - unsigned int imaginationcost; //!< The imagination cost of the skill - unsigned int cooldowngroup; //!< The cooldown group ID of the skill - float cooldown; //!< The cooldown time of the skill - UNUSED(bool isNpcEditor); //!< ??? - UNUSED(unsigned int skillIcon); //!< The Skill Icon ID - UNUSED(std::string oomSkillID); //!< ??? - UNUSED(unsigned int oomBehaviorEffectID); //!< ??? - UNUSED(unsigned int castTypeDesc); //!< The cast type description(?) - UNUSED(unsigned int imBonusUI); //!< The imagination bonus of the skill - UNUSED(nsigned int lifeBonusUI); //!< The life bonus of the skill - UNUSED(unsigned int armorBonusUI); //!< The armor bonus of the skill - UNUSED(unsigned int damageUI); //!< ??? - UNUSED(bool hideIcon); //!< Whether or not to show the icon - UNUSED(bool localize); //!< ??? - UNUSED(std::string gate_version); //!< ??? - UNUSED(unsigned int cancelType); //!< The cancel type (?) + unsigned int skillID; //!< The Skill ID of the skill + UNUSED(unsigned int locStatus); //!< ?? + unsigned int behaviorID; //!< The Behavior ID of the skill + unsigned int imaginationcost; //!< The imagination cost of the skill + unsigned int cooldowngroup; //!< The cooldown group ID of the skill + float cooldown; //!< The cooldown time of the skill + UNUSED(bool isNpcEditor); //!< ??? + UNUSED(unsigned int skillIcon); //!< The Skill Icon ID + UNUSED(std::string oomSkillID); //!< ??? + UNUSED(unsigned int oomBehaviorEffectID); //!< ??? + UNUSED(unsigned int castTypeDesc); //!< The cast type description(?) + UNUSED(unsigned int imBonusUI); //!< The imagination bonus of the skill + UNUSED(nsigned int lifeBonusUI); //!< The life bonus of the skill + UNUSED(unsigned int armorBonusUI); //!< The armor bonus of the skill + UNUSED(unsigned int damageUI); //!< ??? + UNUSED(bool hideIcon); //!< Whether or not to show the icon + UNUSED(bool localize); //!< ??? + UNUSED(std::string gate_version); //!< ??? + UNUSED(unsigned int cancelType); //!< The cancel type (?) }; //! SkillBehavior table class CDSkillBehaviorTable : public CDTable { private: - std::map entries; - CDSkillBehavior m_empty; + std::map entries; + CDSkillBehavior m_empty; public: - //! Constructor - CDSkillBehaviorTable(void); + //! Constructor + CDSkillBehaviorTable(void); - //! Destructor - ~CDSkillBehaviorTable(void); + //! Destructor + ~CDSkillBehaviorTable(void); - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - std::vector Query(std::function predicate); + //! Queries the table with a custom "where" clause + /*! + \param predicate The predicate + */ + std::vector Query(std::function predicate); - //! Gets an entry by ID - const CDSkillBehavior& GetSkillByID(unsigned int skillID); + //! Gets an entry by ID + const CDSkillBehavior& GetSkillByID(unsigned int skillID); }; diff --git a/dDatabase/Tables/CDTable.h b/dDatabase/Tables/CDTable.h index ec056e8e..cd05782d 100644 --- a/dDatabase/Tables/CDTable.h +++ b/dDatabase/Tables/CDTable.h @@ -13,7 +13,7 @@ #ifdef _WIN32 #define NOMINMAX // windows.h has min and max macros that breaks cpplinq -#endif +#endif #include "cpplinq.hpp" #pragma warning (disable : 4244) //Disable double to float conversion warnings @@ -29,13 +29,13 @@ typedef __int64_t __int64; \brief A virtual class for CDClient Tables */ -//! The base class for all CD tables + //! The base class for all CD tables class CDTable { public: - - //! Returns the table's name - /*! - \return The table name - */ - virtual std::string GetName() const = 0; + + //! Returns the table's name + /*! + \return The table name + */ + virtual std::string GetName() const = 0; }; diff --git a/dDatabase/Tables/CDVendorComponentTable.cpp b/dDatabase/Tables/CDVendorComponentTable.cpp index e096e85a..f1dd96db 100644 --- a/dDatabase/Tables/CDVendorComponentTable.cpp +++ b/dDatabase/Tables/CDVendorComponentTable.cpp @@ -11,9 +11,9 @@ CDVendorComponentTable::CDVendorComponentTable(void) { tableSize.nextRow(); } - + tableSize.finalize(); - + // Reserve the size this->entries.reserve(size); @@ -35,7 +35,7 @@ CDVendorComponentTable::CDVendorComponentTable(void) { } //! Destructor -CDVendorComponentTable::~CDVendorComponentTable(void) { } +CDVendorComponentTable::~CDVendorComponentTable(void) {} //! Returns the table's name std::string CDVendorComponentTable::GetName(void) const { diff --git a/dDatabase/Tables/CDZoneTableTable.cpp b/dDatabase/Tables/CDZoneTableTable.cpp index 7cd8d0d8..e172f79a 100644 --- a/dDatabase/Tables/CDZoneTableTable.cpp +++ b/dDatabase/Tables/CDZoneTableTable.cpp @@ -2,73 +2,72 @@ //! Constructor CDZoneTableTable::CDZoneTableTable(void) { - - // First, get the size of the table - unsigned int size = 0; - auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ZoneTable"); - while (!tableSize.eof()) { - size = tableSize.getIntField(0, 0); - - tableSize.nextRow(); - } - + + // First, get the size of the table + unsigned int size = 0; + auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM ZoneTable"); + while (!tableSize.eof()) { + size = tableSize.getIntField(0, 0); + + tableSize.nextRow(); + } + tableSize.finalize(); - - // Now get the data - auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ZoneTable"); - while (!tableData.eof()) { - CDZoneTable entry; - entry.zoneID = tableData.getIntField(0, -1); - entry.locStatus = tableData.getIntField(1, -1); - entry.zoneName = tableData.getStringField(2, ""); - entry.scriptID = tableData.getIntField(3, -1); - entry.ghostdistance_min = tableData.getFloatField(4, -1.0f); - entry.ghostdistance = tableData.getFloatField(5, -1.0f); - entry.population_soft_cap = tableData.getIntField(6, -1); - entry.population_hard_cap = tableData.getIntField(7, -1); - UNUSED(entry.DisplayDescription = tableData.getStringField(8, "")); - UNUSED(entry.mapFolder = tableData.getStringField(9, "")); - entry.smashableMinDistance = tableData.getFloatField(10, -1.0f); - entry.smashableMaxDistance = tableData.getFloatField(11, -1.0f); - UNUSED(entry.mixerProgram = tableData.getStringField(12, "")); - UNUSED(entry.clientPhysicsFramerate = tableData.getStringField(13, "")); - UNUSED(entry.serverPhysicsFramerate = tableData.getStringField(14, "")); - entry.zoneControlTemplate = tableData.getIntField(15, -1); - entry.widthInChunks = tableData.getIntField(16, -1); - entry.heightInChunks = tableData.getIntField(17, -1); - entry.petsAllowed = tableData.getIntField(18, -1) == 1 ? true : false; - entry.localize = tableData.getIntField(19, -1) == 1 ? true : false; - entry.fZoneWeight = tableData.getFloatField(20, -1.0f); - UNUSED(entry.thumbnail = tableData.getStringField(21, "")); - entry.PlayerLoseCoinsOnDeath = tableData.getIntField(22, -1) == 1 ? true : false; - UNUSED(entry.disableSaveLoc = tableData.getIntField(23, -1) == 1 ? true : false); - entry.teamRadius = tableData.getFloatField(24, -1.0f); - UNUSED(entry.gate_version = tableData.getStringField(25, "")); - UNUSED(entry.mountsAllowed = tableData.getIntField(26, -1) == 1 ? true : false); - + + // Now get the data + auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ZoneTable"); + while (!tableData.eof()) { + CDZoneTable entry; + entry.zoneID = tableData.getIntField(0, -1); + entry.locStatus = tableData.getIntField(1, -1); + entry.zoneName = tableData.getStringField(2, ""); + entry.scriptID = tableData.getIntField(3, -1); + entry.ghostdistance_min = tableData.getFloatField(4, -1.0f); + entry.ghostdistance = tableData.getFloatField(5, -1.0f); + entry.population_soft_cap = tableData.getIntField(6, -1); + entry.population_hard_cap = tableData.getIntField(7, -1); + UNUSED(entry.DisplayDescription = tableData.getStringField(8, "")); + UNUSED(entry.mapFolder = tableData.getStringField(9, "")); + entry.smashableMinDistance = tableData.getFloatField(10, -1.0f); + entry.smashableMaxDistance = tableData.getFloatField(11, -1.0f); + UNUSED(entry.mixerProgram = tableData.getStringField(12, "")); + UNUSED(entry.clientPhysicsFramerate = tableData.getStringField(13, "")); + UNUSED(entry.serverPhysicsFramerate = tableData.getStringField(14, "")); + entry.zoneControlTemplate = tableData.getIntField(15, -1); + entry.widthInChunks = tableData.getIntField(16, -1); + entry.heightInChunks = tableData.getIntField(17, -1); + entry.petsAllowed = tableData.getIntField(18, -1) == 1 ? true : false; + entry.localize = tableData.getIntField(19, -1) == 1 ? true : false; + entry.fZoneWeight = tableData.getFloatField(20, -1.0f); + UNUSED(entry.thumbnail = tableData.getStringField(21, "")); + entry.PlayerLoseCoinsOnDeath = tableData.getIntField(22, -1) == 1 ? true : false; + UNUSED(entry.disableSaveLoc = tableData.getIntField(23, -1) == 1 ? true : false); + entry.teamRadius = tableData.getFloatField(24, -1.0f); + UNUSED(entry.gate_version = tableData.getStringField(25, "")); + UNUSED(entry.mountsAllowed = tableData.getIntField(26, -1) == 1 ? true : false); + this->m_Entries.insert(std::make_pair(entry.zoneID, entry)); - tableData.nextRow(); - } + tableData.nextRow(); + } tableData.finalize(); } //! Destructor -CDZoneTableTable::~CDZoneTableTable(void) { } +CDZoneTableTable::~CDZoneTableTable(void) {} //! Returns the table's name std::string CDZoneTableTable::GetName(void) const { - return "ZoneTable"; + return "ZoneTable"; } //! Queries the table with a zoneID to find. const CDZoneTable* CDZoneTableTable::Query(unsigned int zoneID) { - const auto& iter = m_Entries.find(zoneID); + const auto& iter = m_Entries.find(zoneID); - if (iter != m_Entries.end()) - { - return &iter->second; - } + if (iter != m_Entries.end()) { + return &iter->second; + } return nullptr; -} \ No newline at end of file +} diff --git a/dDatabase/Tables/CDZoneTableTable.h b/dDatabase/Tables/CDZoneTableTable.h index f99febc8..c115a38a 100644 --- a/dDatabase/Tables/CDZoneTableTable.h +++ b/dDatabase/Tables/CDZoneTableTable.h @@ -8,59 +8,59 @@ \brief Contains data for the ZoneTable table */ -//! ZoneTable Struct + //! ZoneTable Struct struct CDZoneTable { - unsigned int zoneID; //!< The Zone ID of the object - unsigned int locStatus; //!< The Locale Status(?) - std::string zoneName; //!< The name of the zone - unsigned int scriptID; //!< The Script ID of the zone (ScriptsTable) - float ghostdistance_min; //!< The minimum ghosting distance - float ghostdistance; //!< The ghosting distance - unsigned int population_soft_cap; //!< The "soft cap" on the world population - unsigned int population_hard_cap; //!< The "hard cap" on the world population - UNUSED(std::string DisplayDescription); //!< The display description of the world - UNUSED(std::string mapFolder); //!< ??? - float smashableMinDistance; //!< The minimum smashable distance? - float smashableMaxDistance; //!< The maximum smashable distance? - UNUSED(std::string mixerProgram); //!< ??? - UNUSED(std::string clientPhysicsFramerate); //!< The client physics framerate - UNUSED(std::string serverPhysicsFramerate); //!< The server physics framerate - unsigned int zoneControlTemplate; //!< The Zone Control template - unsigned int widthInChunks; //!< The width of the world in chunks - unsigned int heightInChunks; //!< The height of the world in chunks - bool petsAllowed; //!< Whether or not pets are allowed in the world + unsigned int zoneID; //!< The Zone ID of the object + unsigned int locStatus; //!< The Locale Status(?) + std::string zoneName; //!< The name of the zone + unsigned int scriptID; //!< The Script ID of the zone (ScriptsTable) + float ghostdistance_min; //!< The minimum ghosting distance + float ghostdistance; //!< The ghosting distance + unsigned int population_soft_cap; //!< The "soft cap" on the world population + unsigned int population_hard_cap; //!< The "hard cap" on the world population + UNUSED(std::string DisplayDescription); //!< The display description of the world + UNUSED(std::string mapFolder); //!< ??? + float smashableMinDistance; //!< The minimum smashable distance? + float smashableMaxDistance; //!< The maximum smashable distance? + UNUSED(std::string mixerProgram); //!< ??? + UNUSED(std::string clientPhysicsFramerate); //!< The client physics framerate + UNUSED(std::string serverPhysicsFramerate); //!< The server physics framerate + unsigned int zoneControlTemplate; //!< The Zone Control template + unsigned int widthInChunks; //!< The width of the world in chunks + unsigned int heightInChunks; //!< The height of the world in chunks + bool petsAllowed; //!< Whether or not pets are allowed in the world bool localize; //!< Whether or not the world should be localized - float fZoneWeight; //!< ??? - UNUSED(std::string thumbnail); //!< The thumbnail of the world - bool PlayerLoseCoinsOnDeath; //!< Whether or not the user loses coins on death - UNUSED(bool disableSaveLoc); //!< Disables the saving location? + float fZoneWeight; //!< ??? + UNUSED(std::string thumbnail); //!< The thumbnail of the world + bool PlayerLoseCoinsOnDeath; //!< Whether or not the user loses coins on death + UNUSED(bool disableSaveLoc); //!< Disables the saving location? float teamRadius; //!< ??? - UNUSED(std::string gate_version); //!< The gate version - UNUSED(bool mountsAllowed); //!< Whether or not mounts are allowed + UNUSED(std::string gate_version); //!< The gate version + UNUSED(bool mountsAllowed); //!< Whether or not mounts are allowed }; //! ZoneTable table class CDZoneTableTable : public CDTable { private: std::map m_Entries; - + public: - - //! Constructor - CDZoneTableTable(void); - - //! Destructor - ~CDZoneTableTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a zoneID to find. - /*! - \param id The zoneID - */ - const CDZoneTable* Query(unsigned int zoneID); -}; \ No newline at end of file + + //! Constructor + CDZoneTableTable(void); + + //! Destructor + ~CDZoneTableTable(void); + + //! Returns the table's name + /*! + \return The table name + */ + std::string GetName(void) const override; + + //! Queries the table with a zoneID to find. + /*! + \param id The zoneID + */ + const CDZoneTable* Query(unsigned int zoneID); +}; diff --git a/dGame/Character.cpp b/dGame/Character.cpp index d92f8345..0b92f0aa 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -18,7 +18,7 @@ Character::Character(uint32_t id, User* parentUser) { //First load the name, etc: - m_ID = id; + m_ID = id; sql::PreparedStatement* stmt = Database::CreatePreppedStmt( "SELECT name, pending_name, needs_rename, prop_clone_id, permission_map FROM charinfo WHERE id=? LIMIT 1;" @@ -65,21 +65,20 @@ Character::Character(uint32_t id, User* parentUser) { //Set our objectID: m_ObjectID = m_ID; - m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); - m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); + m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); + m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); - m_ParentUser = parentUser; + m_ParentUser = parentUser; m_OurEntity = nullptr; m_BuildMode = false; } Character::~Character() { delete m_Doc; - m_Doc = nullptr; + m_Doc = nullptr; } -void Character::UpdateFromDatabase() -{ +void Character::UpdateFromDatabase() { sql::PreparedStatement* stmt = Database::CreatePreppedStmt( "SELECT name, pending_name, needs_rename, prop_clone_id, permission_map FROM charinfo WHERE id=? LIMIT 1;" ); @@ -125,8 +124,8 @@ void Character::UpdateFromDatabase() //Set our objectID: m_ObjectID = m_ID; - m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); - m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); + m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); + m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); m_OurEntity = nullptr; m_BuildMode = false; @@ -136,14 +135,14 @@ void Character::DoQuickXMLDataParse() { if (m_XMLData.size() == 0) return; delete m_Doc; - m_Doc = new tinyxml2::XMLDocument(); - if (!m_Doc) return; + m_Doc = new tinyxml2::XMLDocument(); + if (!m_Doc) return; if (m_Doc->Parse(m_XMLData.c_str(), m_XMLData.size()) == 0) { Game::logger->Log("Character", "Loaded xmlData for character %s (%i)!", m_Name.c_str(), m_ID); } else { Game::logger->Log("Character", "Failed to load xmlData!"); - //Server::rakServer->CloseConnection(m_ParentUser->GetSystemAddress(), true); + //Server::rakServer->CloseConnection(m_ParentUser->GetSystemAddress(), true); return; } @@ -179,8 +178,7 @@ void Character::DoQuickXMLDataParse() { return; } - while (bag != nullptr) - { + while (bag != nullptr) { auto* sib = bag->FirstChildElement(); while (sib != nullptr) { @@ -201,9 +199,9 @@ void Character::DoQuickXMLDataParse() { tinyxml2::XMLElement* character = m_Doc->FirstChildElement("obj")->FirstChildElement("char"); - if (character) { + if (character) { character->QueryAttribute("cc", &m_Coins); - character->QueryAttribute("gm", &m_GMLevel); + character->QueryAttribute("gm", &m_GMLevel); uint64_t lzidConcat = 0; if (character->FindAttribute("lzid")) { @@ -221,9 +219,9 @@ void Character::DoQuickXMLDataParse() { } if (character->FindAttribute("lnzid")) { - uint32_t lastNonInstanceZoneID = 0; - character->QueryAttribute("lnzid", &lastNonInstanceZoneID); - m_LastNonInstanceZoneID = lastNonInstanceZoneID; + uint32_t lastNonInstanceZoneID = 0; + character->QueryAttribute("lnzid", &lastNonInstanceZoneID); + m_LastNonInstanceZoneID = lastNonInstanceZoneID; } if (character->FindAttribute("tscene")) { @@ -260,33 +258,31 @@ void Character::DoQuickXMLDataParse() { character->QueryAttribute("lzry", &m_OriginalRotation.y); character->QueryAttribute("lzrz", &m_OriginalRotation.z); character->QueryAttribute("lzrw", &m_OriginalRotation.w); - } + } - auto* flags = m_Doc->FirstChildElement("obj")->FirstChildElement("flag"); - if (flags) { - auto* currentChild = flags->FirstChildElement(); - while (currentChild) { - uint32_t index = 0; - uint64_t value = 0; - const auto* temp = currentChild->Attribute("v"); + auto* flags = m_Doc->FirstChildElement("obj")->FirstChildElement("flag"); + if (flags) { + auto* currentChild = flags->FirstChildElement(); + while (currentChild) { + uint32_t index = 0; + uint64_t value = 0; + const auto* temp = currentChild->Attribute("v"); index = std::stoul(currentChild->Attribute("id")); - value = std::stoull(temp); + value = std::stoull(temp); - m_PlayerFlags.insert(std::make_pair(index, value)); - currentChild = currentChild->NextSiblingElement(); - } - } + m_PlayerFlags.insert(std::make_pair(index, value)); + currentChild = currentChild->NextSiblingElement(); + } + } } -void Character::UnlockEmote(int emoteID) -{ +void Character::UnlockEmote(int emoteID) { m_UnlockedEmotes.push_back(emoteID); GameMessages::SendSetEmoteLockState(EntityManager::Instance()->GetEntity(m_ObjectID), false, emoteID); } -void Character::SetBuildMode(bool buildMode) -{ +void Character::SetBuildMode(bool buildMode) { m_BuildMode = buildMode; auto* controller = dZoneManager::Instance()->GetZoneControlObject(); @@ -295,14 +291,14 @@ void Character::SetBuildMode(bool buildMode) } void Character::SaveXMLToDatabase() { - if (!m_Doc) return; + if (!m_Doc) return; - //For metrics, we'll record the time it took to save: - auto start = std::chrono::system_clock::now(); + //For metrics, we'll record the time it took to save: + auto start = std::chrono::system_clock::now(); - tinyxml2::XMLElement* character = m_Doc->FirstChildElement("obj")->FirstChildElement("char"); - if (character) { - character->SetAttribute("gm", m_GMLevel); + tinyxml2::XMLElement* character = m_Doc->FirstChildElement("obj")->FirstChildElement("char"); + if (character) { + character->SetAttribute("gm", m_GMLevel); character->SetAttribute("cc", m_Coins); // lzid garbage, binary concat of zoneID, zoneInstance and zoneClone @@ -333,31 +329,31 @@ void Character::SaveXMLToDatabase() { } character->LinkEndChild(emotes); - } + } - //Export our flags: - auto* flags = m_Doc->FirstChildElement("obj")->FirstChildElement("flag"); + //Export our flags: + auto* flags = m_Doc->FirstChildElement("obj")->FirstChildElement("flag"); if (!flags) { flags = m_Doc->NewElement("flag"); //Create a flags tag if we don't have one m_Doc->FirstChildElement("obj")->LinkEndChild(flags); //Link it to the obj tag so we can find next time } - flags->DeleteChildren(); //Clear it if we have anything, so that we can fill it up again without dupes - for (std::pair flag : m_PlayerFlags) { - auto* f = m_Doc->NewElement("f"); - f->SetAttribute("id", flag.first); + flags->DeleteChildren(); //Clear it if we have anything, so that we can fill it up again without dupes + for (std::pair flag : m_PlayerFlags) { + auto* f = m_Doc->NewElement("f"); + f->SetAttribute("id", flag.first); - //Because of the joy that is tinyxml2, it doesn't offer a function to set a uint64 as an attribute. - //Only signed 64-bits ints would work. - std::string v = std::to_string(flag.second); - f->SetAttribute("v", v.c_str()); + //Because of the joy that is tinyxml2, it doesn't offer a function to set a uint64 as an attribute. + //Only signed 64-bits ints would work. + std::string v = std::to_string(flag.second); + f->SetAttribute("v", v.c_str()); flags->LinkEndChild(f); } SaveXmlRespawnCheckpoints(); - //Call upon the entity to update our xmlDoc: + //Call upon the entity to update our xmlDoc: if (!m_OurEntity) { Game::logger->Log("Character", "We didn't have an entity set while saving! CHARACTER WILL NOT BE SAVED!"); return; @@ -365,22 +361,22 @@ void Character::SaveXMLToDatabase() { m_OurEntity->UpdateXMLDoc(m_Doc); - //Dump our xml into m_XMLData: - auto* printer = new tinyxml2::XMLPrinter(0, true, 0); - m_Doc->Print(printer); - m_XMLData = printer->CStr(); + //Dump our xml into m_XMLData: + auto* printer = new tinyxml2::XMLPrinter(0, true, 0); + m_Doc->Print(printer); + m_XMLData = printer->CStr(); - //Finally, save to db: + //Finally, save to db: sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charxml SET xml_data=? WHERE id=?"); - stmt->setString(1, m_XMLData.c_str()); - stmt->setUInt(2, m_ID); - stmt->execute(); - delete stmt; + stmt->setString(1, m_XMLData.c_str()); + stmt->setUInt(2, m_ID); + stmt->execute(); + delete stmt; - //For metrics, log the time it took to save: - auto end = std::chrono::system_clock::now(); - std::chrono::duration elapsed = end - start; - Game::logger->Log("Character", "Saved character to Database in: %fs", elapsed.count()); + //For metrics, log the time it took to save: + auto end = std::chrono::system_clock::now(); + std::chrono::duration elapsed = end - start; + Game::logger->Log("Character", "Saved character to Database in: %fs", elapsed.count()); delete printer; } @@ -389,51 +385,47 @@ void Character::SetPlayerFlag(const uint32_t flagId, const bool value) { // If the flag is already set, we don't have to recalculate it if (GetPlayerFlag(flagId) == value) return; - if (value) - { + if (value) { // Update the mission component: auto* player = EntityManager::Instance()->GetEntity(m_ObjectID); - if (player != nullptr) - { + if (player != nullptr) { auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { + if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_PLAYER_FLAG, flagId); } } } - // Calculate the index first - auto flagIndex = uint32_t(std::floor(flagId / 64)); + // Calculate the index first + auto flagIndex = uint32_t(std::floor(flagId / 64)); - const auto shiftedValue = 1ULL << flagId % 64; + const auto shiftedValue = 1ULL << flagId % 64; - auto it = m_PlayerFlags.find(flagIndex); + auto it = m_PlayerFlags.find(flagIndex); // Check if flag index exists - if (it != m_PlayerFlags.end()) - { - // Update the value - if (value) { - it->second |= shiftedValue; - } else { - it->second &= ~shiftedValue; - } - } else { - if (value) { - // Otherwise, insert the value - uint64_t flagValue = 0; + if (it != m_PlayerFlags.end()) { + // Update the value + if (value) { + it->second |= shiftedValue; + } else { + it->second &= ~shiftedValue; + } + } else { + if (value) { + // Otherwise, insert the value + uint64_t flagValue = 0; flagValue |= shiftedValue; - m_PlayerFlags.insert(std::make_pair(flagIndex, flagValue)); - } - } + m_PlayerFlags.insert(std::make_pair(flagIndex, flagValue)); + } + } - // Notify the client that a flag has changed server-side - GameMessages::SendNotifyClientFlagChange(m_ObjectID, flagId, value, m_ParentUser->GetSystemAddress()); + // Notify the client that a flag has changed server-side + GameMessages::SendNotifyClientFlagChange(m_ObjectID, flagId, value, m_ParentUser->GetSystemAddress()); } bool Character::GetPlayerFlag(const uint32_t flagId) const { @@ -458,40 +450,37 @@ void Character::SetRetroactiveFlags() { } } -void Character::SaveXmlRespawnCheckpoints() -{ - //Export our respawn points: - auto* points = m_Doc->FirstChildElement("obj")->FirstChildElement("res"); +void Character::SaveXmlRespawnCheckpoints() { + //Export our respawn points: + auto* points = m_Doc->FirstChildElement("obj")->FirstChildElement("res"); if (!points) { points = m_Doc->NewElement("res"); m_Doc->FirstChildElement("obj")->LinkEndChild(points); } - points->DeleteChildren(); - for (const auto& point : m_WorldRespawnCheckpoints) { - auto* r = m_Doc->NewElement("r"); - r->SetAttribute("w", point.first); + points->DeleteChildren(); + for (const auto& point : m_WorldRespawnCheckpoints) { + auto* r = m_Doc->NewElement("r"); + r->SetAttribute("w", point.first); - r->SetAttribute("x", point.second.x); - r->SetAttribute("y", point.second.y); - r->SetAttribute("z", point.second.z); + r->SetAttribute("x", point.second.x); + r->SetAttribute("y", point.second.y); + r->SetAttribute("z", point.second.z); points->LinkEndChild(r); } } -void Character::LoadXmlRespawnCheckpoints() -{ +void Character::LoadXmlRespawnCheckpoints() { m_WorldRespawnCheckpoints.clear(); - auto* points = m_Doc->FirstChildElement("obj")->FirstChildElement("res"); + auto* points = m_Doc->FirstChildElement("obj")->FirstChildElement("res"); if (!points) { return; } auto* r = points->FirstChildElement("r"); - while (r != nullptr) - { + while (r != nullptr) { int32_t map = 0; NiPoint3 point = NiPoint3::ZERO; @@ -507,8 +496,7 @@ void Character::LoadXmlRespawnCheckpoints() } -void Character::OnZoneLoad() -{ +void Character::OnZoneLoad() { if (m_OurEntity == nullptr) { return; } @@ -550,23 +538,19 @@ void Character::OnZoneLoad() } } -PermissionMap Character::GetPermissionMap() const -{ +PermissionMap Character::GetPermissionMap() const { return m_PermissionMap; } -bool Character::HasPermission(PermissionMap permission) const -{ +bool Character::HasPermission(PermissionMap permission) const { return (static_cast(m_PermissionMap) & static_cast(permission)) != 0; } -void Character::SetRespawnPoint(LWOMAPID map, const NiPoint3& point) -{ +void Character::SetRespawnPoint(LWOMAPID map, const NiPoint3& point) { m_WorldRespawnCheckpoints[map] = point; } -const NiPoint3& Character::GetRespawnPoint(LWOMAPID map) const -{ +const NiPoint3& Character::GetRespawnPoint(LWOMAPID map) const { const auto& pair = m_WorldRespawnCheckpoints.find(map); if (pair == m_WorldRespawnCheckpoints.end()) return NiPoint3::ZERO; @@ -575,8 +559,7 @@ const NiPoint3& Character::GetRespawnPoint(LWOMAPID map) const } void Character::SetCoins(int64_t newCoins, eLootSourceType lootSource) { - if (newCoins < 0) - { + if (newCoins < 0) { newCoins = 0; } @@ -585,22 +568,19 @@ void Character::SetCoins(int64_t newCoins, eLootSourceType lootSource) { GameMessages::SendSetCurrency(EntityManager::Instance()->GetEntity(m_ObjectID), m_Coins, 0, 0, 0, 0, true, lootSource); } -bool Character::HasBeenToWorld(LWOMAPID mapID) const -{ +bool Character::HasBeenToWorld(LWOMAPID mapID) const { return m_WorldRespawnCheckpoints.find(mapID) != m_WorldRespawnCheckpoints.end(); } -void Character::SendMuteNotice() const -{ +void Character::SendMuteNotice() const { if (!m_ParentUser->GetIsMuted()) return; time_t expire = m_ParentUser->GetMuteExpire(); char buffer[32] = "brought up for review.\0"; - if (expire != 1) - { - std::tm * ptm = std::localtime(&expire); + if (expire != 1) { + std::tm* ptm = std::localtime(&expire); // Format: Mo, 15.06.2009 20:20:00 std::strftime(buffer, 32, "%a, %d.%m.%Y %H:%M:%S", ptm); } diff --git a/dGame/Character.h b/dGame/Character.h index 9678eb3d..1a1d4cd0 100644 --- a/dGame/Character.h +++ b/dGame/Character.h @@ -23,344 +23,344 @@ public: Character(uint32_t id, User* parentUser); ~Character(); - void SaveXMLToDatabase(); - void UpdateFromDatabase(); + void SaveXMLToDatabase(); + void UpdateFromDatabase(); - void SaveXmlRespawnCheckpoints(); - void LoadXmlRespawnCheckpoints(); + void SaveXmlRespawnCheckpoints(); + void LoadXmlRespawnCheckpoints(); - const std::string& GetXMLData() const { return m_XMLData; } - tinyxml2::XMLDocument* GetXMLDoc() const { return m_Doc; } + const std::string& GetXMLData() const { return m_XMLData; } + tinyxml2::XMLDocument* GetXMLDoc() const { return m_Doc; } - /** - * Gets the database ID of the character - * @return the database ID of the character - */ + /** + * Gets the database ID of the character + * @return the database ID of the character + */ uint32_t GetID() const { return m_ID; } - /** - * Gets the (custom) name of the character - * @return the name of the character - */ + /** + * Gets the (custom) name of the character + * @return the name of the character + */ const std::string& GetName() const { return m_Name; } - /** - * Gets the generated name of the character - * @return the generated name - */ + /** + * Gets the generated name of the character + * @return the generated name + */ const std::string& GetUnapprovedName() const { return m_UnapprovedName; } - /** - * Gets whether or not the custom name for this character was rejected - * @return whether the custom name for this character was rejected - */ + /** + * Gets whether or not the custom name for this character was rejected + * @return whether the custom name for this character was rejected + */ bool GetNameRejected() const { return m_NameRejected; } - /** - * Gets the object ID of the entity this character belongs to - * @return the object ID of the entity this character belongs to - */ + /** + * Gets the object ID of the entity this character belongs to + * @return the object ID of the entity this character belongs to + */ LWOOBJID GetObjectID() const { return m_ObjectID; } - /** - * Gets the identifier for the properties of this character - * @return The identifier for the properties of this character - */ + /** + * Gets the identifier for the properties of this character + * @return The identifier for the properties of this character + */ uint32_t GetPropertyCloneID() const { return m_PropertyCloneID; } - /** - * Gets the last login of this character in MS - * @return the last login of this character - */ + /** + * Gets the last login of this character in MS + * @return the last login of this character + */ uint64_t GetLastLogin() const { return m_LastLogin; } - - /** - * Gets the default shirt color for this character - * @return the default shirt color ID - */ - uint32_t GetShirtColor() const { return m_ShirtColor; } - /** - * Gets the default hair style for this character - * @return the default hair style ID - */ - uint32_t GetShirtStyle() const { return m_ShirtStyle; } + /** + * Gets the default shirt color for this character + * @return the default shirt color ID + */ + uint32_t GetShirtColor() const { return m_ShirtColor; } - /** - * Gets the default pants color for this character - * @return the default pants color ID - */ - uint32_t GetPantsColor() const { return m_PantsColor; } + /** + * Gets the default hair style for this character + * @return the default hair style ID + */ + uint32_t GetShirtStyle() const { return m_ShirtStyle; } - /** - * Gets the default hair color for this character - * @return the default hair color ID - */ - uint32_t GetHairColor() const { return m_HairColor; } + /** + * Gets the default pants color for this character + * @return the default pants color ID + */ + uint32_t GetPantsColor() const { return m_PantsColor; } - /** - * Gets the default hair style of this character - * @return the default hair style ID - */ - uint32_t GetHairStyle() const { return m_HairStyle; } + /** + * Gets the default hair color for this character + * @return the default hair color ID + */ + uint32_t GetHairColor() const { return m_HairColor; } - /** - * Gets the eyes config for this character - * @return the eyes config ID - */ - uint32_t GetEyes() const { return m_Eyes; } + /** + * Gets the default hair style of this character + * @return the default hair style ID + */ + uint32_t GetHairStyle() const { return m_HairStyle; } - /** - * Gets the eyebrows config for this character - * @return the eyebrow config ID - */ - uint32_t GetEyebrows() const { return m_Eyebrows; } + /** + * Gets the eyes config for this character + * @return the eyes config ID + */ + uint32_t GetEyes() const { return m_Eyes; } - /** - * Get the mouth of this character - * @return the mouth ID - */ - uint32_t GetMouth() const { return m_Mouth; } + /** + * Gets the eyebrows config for this character + * @return the eyebrow config ID + */ + uint32_t GetEyebrows() const { return m_Eyebrows; } - /** - * Gets the left hand color of this character - * @return the left hand color ID - */ - uint32_t GetLeftHand() const { return m_LeftHand; } + /** + * Get the mouth of this character + * @return the mouth ID + */ + uint32_t GetMouth() const { return m_Mouth; } - /** - * Gets the right hand color of this character - * @return the right hand color ID - */ - uint32_t GetRightHand() const { return m_RightHand; } + /** + * Gets the left hand color of this character + * @return the left hand color ID + */ + uint32_t GetLeftHand() const { return m_LeftHand; } - /** - * Sets the default shirt color for this character - * @param color the shirt color ID to set - */ - void SetShirtColor(uint32_t color) { m_ShirtColor = color; } + /** + * Gets the right hand color of this character + * @return the right hand color ID + */ + uint32_t GetRightHand() const { return m_RightHand; } - /** - * Sets the default shirt style for this character - * @param style the shirt style ID to set - */ - void SetShirtStyle(uint32_t style) { m_ShirtStyle = style; } + /** + * Sets the default shirt color for this character + * @param color the shirt color ID to set + */ + void SetShirtColor(uint32_t color) { m_ShirtColor = color; } - /** - * Sets the default pants color for this character - * @param color the pants color ID to set - */ - void SetPantsColor(uint32_t color) { m_PantsColor = color; } + /** + * Sets the default shirt style for this character + * @param style the shirt style ID to set + */ + void SetShirtStyle(uint32_t style) { m_ShirtStyle = style; } - /** - * Sets the default hair color for this character - * @param color the hair color ID to set - */ - void SetHairColor(uint32_t color) { m_HairColor = color; } + /** + * Sets the default pants color for this character + * @param color the pants color ID to set + */ + void SetPantsColor(uint32_t color) { m_PantsColor = color; } - /** - * Sets the default hair style for this character - * @param style the hair style ID to set - */ - void SetHairStyle(uint32_t style) { m_HairStyle = style; } + /** + * Sets the default hair color for this character + * @param color the hair color ID to set + */ + void SetHairColor(uint32_t color) { m_HairColor = color; } - /** - * Sets the eyes config for this character - * @param eyes the eyes config ID to set - */ - void SetEyes(uint32_t eyes) { m_Eyes = eyes; } + /** + * Sets the default hair style for this character + * @param style the hair style ID to set + */ + void SetHairStyle(uint32_t style) { m_HairStyle = style; } - /** - * Sets the eyebrows config for this character - * @param eyebrows the eyebrows config ID to set - */ - void SetEyebrows(uint32_t eyebrows) { m_Eyebrows = eyebrows; } + /** + * Sets the eyes config for this character + * @param eyes the eyes config ID to set + */ + void SetEyes(uint32_t eyes) { m_Eyes = eyes; } - /** - * Sets the mouth config for this character - * @param mouth the mouth config ID to set - */ - void SetMouth(uint32_t mouth) { m_Mouth = mouth; } + /** + * Sets the eyebrows config for this character + * @param eyebrows the eyebrows config ID to set + */ + void SetEyebrows(uint32_t eyebrows) { m_Eyebrows = eyebrows; } - /** - * Sets the left hand color for this character - * @param color the left hand color ID to set - */ - void SetLeftHand(uint32_t leftHand) { m_LeftHand = leftHand; } + /** + * Sets the mouth config for this character + * @param mouth the mouth config ID to set + */ + void SetMouth(uint32_t mouth) { m_Mouth = mouth; } - /** - * Sets the right hand color for this character - * @param color the right hand color ID to set - */ - void SetRightHand(uint32_t rightHand) { m_RightHand = rightHand; } + /** + * Sets the left hand color for this character + * @param color the left hand color ID to set + */ + void SetLeftHand(uint32_t leftHand) { m_LeftHand = leftHand; } + + /** + * Sets the right hand color for this character + * @param color the right hand color ID to set + */ + void SetRightHand(uint32_t rightHand) { m_RightHand = rightHand; } - /** - * Whether this character has visited a certain zone - * @param mapID the ID of the zone to check for - * @return Whether the character has visited the provided zone - */ + /** + * Whether this character has visited a certain zone + * @param mapID the ID of the zone to check for + * @return Whether the character has visited the provided zone + */ bool HasBeenToWorld(LWOMAPID mapID) const; - /** - * Gets the zone ID the character is currently in - * @return the zone ID the character is currently in - */ + /** + * Gets the zone ID the character is currently in + * @return the zone ID the character is currently in + */ uint32_t GetZoneID() const { return m_ZoneID; } - /** - * Sets the zone ID the character is currently in - * @param id the zone ID to set - */ - void SetZoneID(uint32_t id) { m_ZoneID = id; } + /** + * Sets the zone ID the character is currently in + * @param id the zone ID to set + */ + void SetZoneID(uint32_t id) { m_ZoneID = id; } - /** - * Gets the instance ID of the zone the character is currently in, for boss battles - * @return the instance ID of the zone the character is in - */ + /** + * Gets the instance ID of the zone the character is currently in, for boss battles + * @return the instance ID of the zone the character is in + */ uint32_t GetZoneInstance() const { return m_ZoneInstanceID; } - /** - * Sets the zone instance ID the character is currently in - * @param instance the instance ID of the zone - */ - void SetZoneInstance(uint32_t instance) { m_ZoneInstanceID = instance; } + /** + * Sets the zone instance ID the character is currently in + * @param instance the instance ID of the zone + */ + void SetZoneInstance(uint32_t instance) { m_ZoneInstanceID = instance; } - /** - * Gets the clone ID of the zone the character is currently in, for properties - * @return the clone ID of the zone the character is in - */ + /** + * Gets the clone ID of the zone the character is currently in, for properties + * @return the clone ID of the zone the character is in + */ uint32_t GetZoneClone() const { return m_ZoneCloneID; } - /** - * Sets the clone ID of the zone the character is currently in - * @param clone the clone ID of the zone - */ - void SetZoneClone(uint32_t clone) { m_ZoneCloneID = clone; } + /** + * Sets the clone ID of the zone the character is currently in + * @param clone the clone ID of the zone + */ + void SetZoneClone(uint32_t clone) { m_ZoneCloneID = clone; } - /** - * Gets the last zone the character was in, that was not an instance (=boss battle), to be able to send them back - * @return the zone ID of the last non-instance zone this character was in - */ + /** + * Gets the last zone the character was in, that was not an instance (=boss battle), to be able to send them back + * @return the zone ID of the last non-instance zone this character was in + */ uint32_t GetLastNonInstanceZoneID() const { return m_LastNonInstanceZoneID; } - /** - * Sets the last non instance zone ID for the character - * @param id the zone ID - */ - void SetLastNonInstanceZoneID(uint32_t id) { m_LastNonInstanceZoneID = id; } + /** + * Sets the last non instance zone ID for the character + * @param id the zone ID + */ + void SetLastNonInstanceZoneID(uint32_t id) { m_LastNonInstanceZoneID = id; } - /** - * Gets the name of the scene that will play when the character lands in the next zone - * @return the name of the landing scene - */ + /** + * Gets the name of the scene that will play when the character lands in the next zone + * @return the name of the landing scene + */ const std::string& GetTargetScene() const { return m_TargetScene; } - /** - * Sets the name of the landing scene that will play when the player lands in the new zone - * NOTE: Generally set by launch pads before heading off to the next zone - * @param value the name of the landing scene to set - */ - void SetTargetScene(const std::string& value) { m_TargetScene = value; } + /** + * Sets the name of the landing scene that will play when the player lands in the new zone + * NOTE: Generally set by launch pads before heading off to the next zone + * @param value the name of the landing scene to set + */ + void SetTargetScene(const std::string& value) { m_TargetScene = value; } - /** - * Gets the starting position of the character (at spawn) - * @return the starting position of the character - */ + /** + * Gets the starting position of the character (at spawn) + * @return the starting position of the character + */ const NiPoint3& GetOriginalPos() const { return m_OriginalPosition; } - /** - * Gets the starting rotation of the character (at spawn) - * @return the starting rotation of the character - */ + /** + * Gets the starting rotation of the character (at spawn) + * @return the starting rotation of the character + */ const NiQuaternion& GetOriginalRot() const { return m_OriginalRotation; } - /** - * Gets the respawn point of the the character for a certain map - * @param map the map ID to get the respawn point for - * @return the respawn point of the character on the given map - */ - const NiPoint3& GetRespawnPoint(LWOMAPID map) const; + /** + * Gets the respawn point of the the character for a certain map + * @param map the map ID to get the respawn point for + * @return the respawn point of the character on the given map + */ + const NiPoint3& GetRespawnPoint(LWOMAPID map) const; - /** - * Sets the respawn point of this character for a given map - * @param map the map to set the respawn point for - * @param point the point to set as respawn point on the given map - */ + /** + * Sets the respawn point of this character for a given map + * @param map the map to set the respawn point for + * @param point the point to set as respawn point on the given map + */ void SetRespawnPoint(LWOMAPID map, const NiPoint3& point); - /** - * Gets the GM level of the character - * @return the GM level - */ + /** + * Gets the GM level of the character + * @return the GM level + */ int32_t GetGMLevel() const { return m_GMLevel; } - /** - * Sets the GM level of the character - * @param value the GM level to set - */ - void SetGMLevel(uint8_t value) { m_GMLevel = value; } + /** + * Sets the GM level of the character + * @param value the GM level to set + */ + void SetGMLevel(uint8_t value) { m_GMLevel = value; } - /** - * Gets the current amount of coins of the character - * @return the current amount of coins - */ + /** + * Gets the current amount of coins of the character + * @return the current amount of coins + */ const int64_t GetCoins() const { return m_Coins; } - /** - * Updates the current amount of coins of the character by a specified amount - * @param newCoins the amount of coins to update by - * @param coinSource The source of the loot - */ - void SetCoins(int64_t newCoins, eLootSourceType coinSource); + /** + * Updates the current amount of coins of the character by a specified amount + * @param newCoins the amount of coins to update by + * @param coinSource The source of the loot + */ + void SetCoins(int64_t newCoins, eLootSourceType coinSource); - /** - * Get the entity this character belongs to - * @return the entity this character belongs to - */ + /** + * Get the entity this character belongs to + * @return the entity this character belongs to + */ Entity* GetEntity() const { return m_OurEntity; } - /** - * Sets the entity this character belongs to - * @param entity the entity this character belongs to - */ + /** + * Sets the entity this character belongs to + * @param entity the entity this character belongs to + */ void SetEntity(Entity* entity) { m_OurEntity = entity; } - /** - * Gets the current build mode of the character (on or off) - * @return the current build mode of the character - */ + /** + * Gets the current build mode of the character (on or off) + * @return the current build mode of the character + */ bool GetBuildMode() const { return m_BuildMode; } - /** - * Sets the current build mode for the character (either on or off) - * @param buildMode the build mode to set - */ + /** + * Sets the current build mode for the character (either on or off) + * @param buildMode the build mode to set + */ void SetBuildMode(bool buildMode); - /** - * Gets the title of an announcement that a character made (reserved for GMs) - * @return the title of the announcement a character made - */ + /** + * Gets the title of an announcement that a character made (reserved for GMs) + * @return the title of the announcement a character made + */ const std::string& GetAnnouncementTitle() const { return m_AnnouncementTitle; } - /** - * Sets the title of an announcement a character will make (reserved for GMs) - * @param value the title to set - */ + /** + * Sets the title of an announcement a character will make (reserved for GMs) + * @param value the title to set + */ void SetAnnouncementTitle(const std::string& value) { m_AnnouncementTitle = value; } - /** - * Gets the body of an announcement a character made (reserved for GMs) - * @return the body of the announcement - */ + /** + * Gets the body of an announcement a character made (reserved for GMs) + * @return the body of the announcement + */ const std::string& GetAnnouncementMessage() const { return m_AnnouncementMessage; } - /** - * Sets the body of an annoucement to make (reserved for GMs) - * @param value the body of the announcement - */ + /** + * Sets the body of an annoucement to make (reserved for GMs) + * @param value the body of the announcement + */ void SetAnnouncementMessage(const std::string& value) { m_AnnouncementMessage = value; } /** @@ -368,29 +368,29 @@ public: */ void OnZoneLoad(); - /** - * Gets the permissions of the character, determining what actions a character may do - * @return the permissions for this character - */ + /** + * Gets the permissions of the character, determining what actions a character may do + * @return the permissions for this character + */ PermissionMap GetPermissionMap() const; - /** - * Check if this character has a certain permission - * @param permission the ID of the permission to check for - * @return whether the character has the specified permission - */ + /** + * Check if this character has a certain permission + * @param permission the ID of the permission to check for + * @return whether the character has the specified permission + */ bool HasPermission(PermissionMap permission) const; - /** - * Gets all the emotes this character has unlocked so far - * @return the emotes this character has unlocked - */ + /** + * Gets all the emotes this character has unlocked so far + * @return the emotes this character has unlocked + */ const std::vector& GetUnlockedEmotes() const { return m_UnlockedEmotes; } - /** - * Unlocks an emote, adding it to the unlocked list, also updates the state for the client - * @param emoteID the ID of the emote to unlock - */ + /** + * Unlocks an emote, adding it to the unlocked list, also updates the state for the client + * @param emoteID the ID of the emote to unlock + */ void UnlockEmote(int emoteID); /** @@ -399,13 +399,13 @@ public: * @param flagId the ID of the flag to set * @param value the value to set for the flag */ - void SetPlayerFlag(uint32_t flagId, bool value); + void SetPlayerFlag(uint32_t flagId, bool value); - /** - * Gets the value for a certain character flag - * @param flagId the ID of the flag to get a value for - * @return the value of the flag given the ID (the default is false, obviously) - */ + /** + * Gets the value for a certain character flag + * @param flagId the ID of the flag to get a value for + * @return the value of the flag given the ID (the default is false, obviously) + */ bool GetPlayerFlag(uint32_t flagId) const; /** @@ -413,18 +413,18 @@ public: */ void SendMuteNotice() const; - /** - * Sets any flags that are meant to have been set that may not have been set due to them being - * missing in a previous patch. - */ - void SetRetroactiveFlags(); - - /** - * Get the equipped items for this character, only used for character creation - * @return the equipped items for this character on world load - */ + /** + * Sets any flags that are meant to have been set that may not have been set due to them being + * missing in a previous patch. + */ + void SetRetroactiveFlags(); + + /** + * Get the equipped items for this character, only used for character creation + * @return the equipped items for this character on world load + */ const std::vector& GetEquippedItems() const { return m_EquippedItems; } - + private: /** * The ID of this character. First 32 bits of the ObjectID. @@ -448,7 +448,7 @@ private: /** * 0-9, the Game Master level of this character. - * + * * @see eGameMasterLevel */ int32_t m_GMLevel; @@ -458,34 +458,34 @@ private: */ PermissionMap m_PermissionMap; - /** - * The default name of this character - */ + /** + * The default name of this character + */ std::string m_Name; - /** - * The custom name of the character - */ + /** + * The custom name of the character + */ std::string m_UnapprovedName; - /** - * Whether the custom name of this character is rejected - */ + /** + * Whether the custom name of this character is rejected + */ bool m_NameRejected; - /** - * The current amount of coins of this character - */ + /** + * The current amount of coins of this character + */ int64_t m_Coins; - /** - * Whether the character is building - */ + /** + * Whether the character is building + */ bool m_BuildMode; - /** - * The items equipped by the character on world load - */ + /** + * The items equipped by the character on world load + */ std::vector m_EquippedItems; /** @@ -493,126 +493,126 @@ private: */ uint32_t m_ShirtColor = 0; - /** - * The default shirt style of the character - */ + /** + * The default shirt style of the character + */ uint32_t m_ShirtStyle = 0; - /** - * The default pants color of the character - */ + /** + * The default pants color of the character + */ uint32_t m_PantsColor = 1; - /** - * The default hair color of the character - */ + /** + * The default hair color of the character + */ uint32_t m_HairColor = 0; - /** - * The default hair style of the character - */ + /** + * The default hair style of the character + */ uint32_t m_HairStyle = 0; - /** - * The eyes style of the character - */ + /** + * The eyes style of the character + */ uint32_t m_Eyes = 1; - /** - * The eyebrow style of the character - */ + /** + * The eyebrow style of the character + */ uint32_t m_Eyebrows = 33; - /** - * The mouth style of the character - */ + /** + * The mouth style of the character + */ uint32_t m_Mouth = 8; - /* - * The left hand ID of the character - * NOTE: This might just be client stack garbage. - */ + /* + * The left hand ID of the character + * NOTE: This might just be client stack garbage. + */ uint32_t m_LeftHand = 23571472; - /** - * The right hand ID of the character - * NOTE: This might just be client stack garbage. - */ + /** + * The right hand ID of the character + * NOTE: This might just be client stack garbage. + */ uint32_t m_RightHand = 23124164; - /** - * The emotes unlocked by this character - */ + /** + * The emotes unlocked by this character + */ std::vector m_UnlockedEmotes; - /** - * The ID of the properties of this character - */ + /** + * The ID of the properties of this character + */ uint32_t m_PropertyCloneID; - /** - * The XML data for this character, stored as string - */ + /** + * The XML data for this character, stored as string + */ std::string m_XMLData; - /** - * The last zone visited by the character that was not an instance zone - */ + /** + * The last zone visited by the character that was not an instance zone + */ uint32_t m_LastNonInstanceZoneID = 0; - /** - * The ID of the zone the character is currently in - */ + /** + * The ID of the zone the character is currently in + */ uint32_t m_ZoneID = 0; - /** - * The instance ID of the zone the character is currently in (for boss battles) - */ + /** + * The instance ID of the zone the character is currently in (for boss battles) + */ uint32_t m_ZoneInstanceID = 0; - /** - * The clone ID of the zone the character is currently in (for properties) - */ + /** + * The clone ID of the zone the character is currently in (for properties) + */ uint32_t m_ZoneCloneID = 0; - /** - * The last time this character logged in - */ + /** + * The last time this character logged in + */ uint64_t m_LastLogin; - /** - * The gameplay flags this character has (not just true values) - */ - std::unordered_map m_PlayerFlags; + /** + * The gameplay flags this character has (not just true values) + */ + std::unordered_map m_PlayerFlags; - /** - * The character XML belonging to this character - */ - tinyxml2::XMLDocument* m_Doc; + /** + * The character XML belonging to this character + */ + tinyxml2::XMLDocument* m_Doc; - /** - * Title of an announcement this character made (reserved for GMs) - */ + /** + * Title of an announcement this character made (reserved for GMs) + */ std::string m_AnnouncementTitle; - /** - * The body of an announcement this character made (reserved for GMs) - */ + /** + * The body of an announcement this character made (reserved for GMs) + */ std::string m_AnnouncementMessage; - /** - * The spawn position of this character when loading in - */ + /** + * The spawn position of this character when loading in + */ NiPoint3 m_OriginalPosition; - /** - * The spawn rotation of this character when loading in - */ + /** + * The spawn rotation of this character when loading in + */ NiQuaternion m_OriginalRotation; - /** - * The respawn points of this character, per world - */ + /** + * The respawn points of this character, per world + */ std::map m_WorldRespawnCheckpoints; /** @@ -620,7 +620,7 @@ private: * Set by the launchpad the player used to get to the current world. */ std::string m_TargetScene; - + /** * Queries the character XML and updates all the fields of this object * NOTE: quick as there's no DB lookups diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index fbb61437..89289004 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -90,8 +90,8 @@ Entity::Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity) m_Scale = info.scale; m_Spawner = info.spawner; m_SpawnerID = info.spawnerID; - m_HasSpawnerNodeID = info.hasSpawnerNodeID; - m_SpawnerNodeID = info.spawnerNodeID; + m_HasSpawnerNodeID = info.hasSpawnerNodeID; + m_SpawnerNodeID = info.spawnerNodeID; if (info.lot != 1) m_PlayerIsReadyForUpdates = true; } @@ -105,7 +105,7 @@ Entity::~Entity() { CancelCallbackTimers(); const auto components = m_Components; - + for (const auto& pair : components) { delete pair.second; @@ -121,8 +121,7 @@ Entity::~Entity() { } } -void Entity::Initialize() -{ +void Entity::Initialize() { /** * Setup trigger */ @@ -197,12 +196,12 @@ void Entity::Initialize() destroyableComponent->SetIsSmashable(true); m_Components.insert(std::make_pair(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)); // We have all our components. - return; + return; } /** * Go through all the components and check if this entity has them. - * + * * Not all components are implemented. Some are represented by a nullptr, as they hold no data. */ @@ -245,7 +244,7 @@ void Entity::Initialize() const auto propertyEntranceComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY_ENTRANCE); if (propertyEntranceComponentID > 0) { m_Components.insert(std::make_pair(COMPONENT_TYPE_PROPERTY_ENTRANCE, - new PropertyEntranceComponent(propertyEntranceComponentID, this))); + new PropertyEntranceComponent(propertyEntranceComponentID, this))); } if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_CONTROLLABLE_PHYSICS) > 0) { @@ -267,21 +266,18 @@ void Entity::Initialize() if (m_Character->HasBeenToWorld(mapID) && targetSceneName.empty()) { pos = m_Character->GetRespawnPoint(mapID); rot = dZoneManager::Instance()->GetZone()->GetSpawnRot(); - } - else if (targetScene != nullptr) { + } else if (targetScene != nullptr) { pos = targetScene->GetPosition(); rot = targetScene->GetRotation(); - } - else { - pos = dZoneManager::Instance()->GetZone()->GetSpawnPos(); - rot = dZoneManager::Instance()->GetZone()->GetSpawnRot(); + } else { + pos = dZoneManager::Instance()->GetZone()->GetSpawnPos(); + rot = dZoneManager::Instance()->GetZone()->GetSpawnRot(); } controllablePhysics->SetPosition(pos); controllablePhysics->SetRotation(rot); } - } - else { + } else { controllablePhysics->SetPosition(m_DefaultPosition); controllablePhysics->SetRotation(m_DefaultRotation); } @@ -315,10 +311,10 @@ void Entity::Initialize() vehiclePhysicsComponent->SetPosition(m_DefaultPosition); vehiclePhysicsComponent->SetRotation(m_DefaultRotation); } - + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SOUND_TRIGGER, -1) != -1) { - auto* comp = new SoundTriggerComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_SOUND_TRIGGER, comp)); + auto* comp = new SoundTriggerComponent(this); + m_Components.insert(std::make_pair(COMPONENT_TYPE_SOUND_TRIGGER, comp)); } //Check to see if we have a moving platform component: @@ -340,7 +336,7 @@ void Entity::Initialize() int collectibleComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_COLLECTIBLE); - if (collectibleComponentID > 0){ + if (collectibleComponentID > 0) { m_Components.insert(std::make_pair(COMPONENT_TYPE_COLLECTIBLE, nullptr)); } @@ -363,14 +359,12 @@ void Entity::Initialize() DestroyableComponent* comp = new DestroyableComponent(this); if (m_Character) { comp->LoadFromXml(m_Character->GetXMLDoc()); - } - else { + } else { if (componentID > 0) { std::vector destCompData = destCompTable->Query([=](CDDestructibleComponent entry) { return (entry.id == componentID); }); if (destCompData.size() > 0) { - if (HasComponent(COMPONENT_TYPE_RACING_STATS)) - { + if (HasComponent(COMPONENT_TYPE_RACING_STATS)) { destCompData[0].imagination = 60; } @@ -402,8 +396,7 @@ void Entity::Initialize() // extraInfo overrides comp->SetIsSmashable(GetVarAs(u"is_smashable") != 0); } - } - else { + } else { comp->SetHealth(1); comp->SetArmor(0); @@ -480,18 +473,15 @@ void Entity::Initialize() CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); scriptName = scriptCompData.script_name; clientScriptName = scriptCompData.client_script_name; - } - else { + } else { scriptName = ""; } if (scriptName != "" || (scriptName == "" && m_Character)) { - - } - else if (clientScriptName != "") { + + } else if (clientScriptName != "") { client = true; - } - else if (!m_Character) { + } else if (!m_Character) { client = true; } } @@ -525,8 +515,7 @@ void Entity::Initialize() const auto zoneID = dZoneManager::Instance()->GetZoneID(); const CDZoneTable* zoneData = zoneTable->Query(zoneID.GetMapID()); - if (zoneData != nullptr) - { + if (zoneData != nullptr) { int zoneScriptID = zoneData->scriptID; CDScriptComponent zoneScriptData = scriptCompTable->GetByID(zoneScriptID); @@ -598,14 +587,12 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_VENDOR, comp)); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY_VENDOR, -1) != -1) - { + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY_VENDOR, -1) != -1) { auto* component = new PropertyVendorComponent(this); m_Components.insert_or_assign(COMPONENT_TYPE_PROPERTY_VENDOR, component); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY_MANAGEMENT, -1) != -1) - { + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY_MANAGEMENT, -1) != -1) { auto* component = new PropertyManagementComponent(this); m_Components.insert_or_assign(COMPONENT_TYPE_PROPERTY_MANAGEMENT, component); } @@ -634,8 +621,8 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_SCRIPTED_ACTIVITY, new ScriptedActivityComponent(this, scriptedActivityID))); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MODEL, -1) != -1 && !GetComponent()) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_MODEL, new ModelComponent(this))); + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MODEL, -1) != -1 && !GetComponent()) { + m_Components.insert(std::make_pair(COMPONENT_TYPE_MODEL, new ModelComponent(this))); if (m_Components.find(COMPONENT_TYPE_DESTROYABLE) == m_Components.end()) { auto destroyableComponent = new DestroyableComponent(this); destroyableComponent->SetHealth(1); @@ -644,7 +631,7 @@ void Entity::Initialize() destroyableComponent->SetIsSmashable(true); m_Components.insert(std::make_pair(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)); } - } + } PetComponent* petComponent; if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_ITEM) > 0 && !TryGetComponent(COMPONENT_TYPE_PET, petComponent) && !HasComponent(COMPONENT_TYPE_MODEL)) { @@ -652,9 +639,9 @@ void Entity::Initialize() } // Shooting gallery component - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SHOOTING_GALLERY) > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_SHOOTING_GALLERY, new ShootingGalleryComponent(this))); - } + if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SHOOTING_GALLERY) > 0) { + m_Components.insert(std::make_pair(COMPONENT_TYPE_SHOOTING_GALLERY, new ShootingGalleryComponent(this))); + } if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY, -1) != -1) { m_Components.insert(std::make_pair(COMPONENT_TYPE_PROPERTY, new PropertyComponent(this))); @@ -667,7 +654,7 @@ void Entity::Initialize() const int32_t railComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_RAIL_ACTIVATOR); if (railComponentID > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_RAIL_ACTIVATOR, new RailActivatorComponent(this, railComponentID))); + m_Components.insert(std::make_pair(COMPONENT_TYPE_RAIL_ACTIVATOR, new RailActivatorComponent(this, railComponentID))); } int movementAIID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MOVEMENT_AI); @@ -697,9 +684,7 @@ void Entity::Initialize() m_Components.insert(std::make_pair(COMPONENT_TYPE_MOVEMENT_AI, new MovementAIComponent(this, moveInfo))); } - } - else if (petComponentId > 0 || combatAiId > 0 && GetComponent()->GetTetherSpeed() > 0) - { + } else if (petComponentId > 0 || combatAiId > 0 && GetComponent()->GetTetherSpeed() > 0) { MovementAIInfo moveInfo = MovementAIInfo(); moveInfo.movementType = ""; moveInfo.wanderChance = 0; @@ -727,49 +712,45 @@ void Entity::Initialize() for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnStartup(this); } - }); + }); - if (!m_Character && EntityManager::Instance()->GetGhostingEnabled()) - { + if (!m_Character && EntityManager::Instance()->GetGhostingEnabled()) { // Don't ghost what is likely large scene elements - if (m_Components.size() == 2 && HasComponent(COMPONENT_TYPE_SIMPLE_PHYSICS) && HasComponent(COMPONENT_TYPE_RENDER)) - { + if (m_Components.size() == 2 && HasComponent(COMPONENT_TYPE_SIMPLE_PHYSICS) && HasComponent(COMPONENT_TYPE_RENDER)) { goto no_ghosting; } /* Filter for ghosting candidates. - * + * * Don't ghost moving platforms, until we've got proper syncing for those. * Don't ghost big phantom physics triggers, as putting those to sleep might prevent interactions. * Don't ghost property related objects, as the client expects those to always be loaded. */ if ( !EntityManager::IsExcludedFromGhosting(GetLOT()) && - !HasComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY) && - !HasComponent(COMPONENT_TYPE_MOVING_PLATFORM) && - !HasComponent(COMPONENT_TYPE_PHANTOM_PHYSICS) && - !HasComponent(COMPONENT_TYPE_PROPERTY) && - !HasComponent(COMPONENT_TYPE_RACING_CONTROL) && + !HasComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY) && + !HasComponent(COMPONENT_TYPE_MOVING_PLATFORM) && + !HasComponent(COMPONENT_TYPE_PHANTOM_PHYSICS) && + !HasComponent(COMPONENT_TYPE_PROPERTY) && + !HasComponent(COMPONENT_TYPE_RACING_CONTROL) && !HasComponent(COMPONENT_TYPE_VEHICLE_PHYSICS) - ) - //if (HasComponent(COMPONENT_TYPE_BASE_COMBAT_AI)) + ) + //if (HasComponent(COMPONENT_TYPE_BASE_COMBAT_AI)) { m_IsGhostingCandidate = true; } - if (GetLOT() == 6368) - { + if (GetLOT() == 6368) { m_IsGhostingCandidate = true; } // Special case for collectibles in Ninjago - if (HasComponent(COMPONENT_TYPE_COLLECTIBLE) && Game::server->GetZoneID() == 2000) - { + if (HasComponent(COMPONENT_TYPE_COLLECTIBLE) && Game::server->GetZoneID() == 2000) { m_IsGhostingCandidate = true; } } - no_ghosting: +no_ghosting: TriggerEvent("OnCreate"); @@ -791,10 +772,8 @@ bool Entity::operator!=(const Entity& other) const { return other.m_ObjectID != m_ObjectID; } -User* Entity::GetParentUser() const -{ - if (!IsPlayer()) - { +User* Entity::GetParentUser() const { + if (!IsPlayer()) { return nullptr; } @@ -804,23 +783,19 @@ User* Entity::GetParentUser() const Component* Entity::GetComponent(int32_t componentID) const { const auto& index = m_Components.find(componentID); - if (index == m_Components.end()) - { + if (index == m_Components.end()) { return nullptr; } - + return index->second; } -bool Entity::HasComponent(const int32_t componentId) const -{ +bool Entity::HasComponent(const int32_t componentId) const { return m_Components.find(componentId) != m_Components.end(); } -void Entity::AddComponent(const int32_t componentId, Component* component) -{ - if (HasComponent(componentId)) - { +void Entity::AddComponent(const int32_t componentId, Component* component) { + if (HasComponent(componentId)) { return; } @@ -834,7 +809,7 @@ std::vector Entity::GetScriptComponents() { comps.push_back(static_cast(p.second)); } } - + return comps; } @@ -884,8 +859,7 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke for (size_t i = 0; i < name.size(); ++i) { outBitStream->Write(name[i]); } - } - else { + } else { const auto& name = GetVar(u"npcName"); outBitStream->Write(uint8_t(name.size())); @@ -901,7 +875,7 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke // Only sync for models. if (m_Settings.size() > 0 && (GetComponent() && !GetComponent())) { outBitStream->Write1(); //ldf data - + RakNet::BitStream settingStream; settingStream.Write(m_Settings.size()); @@ -914,8 +888,7 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke outBitStream->Write(settingStream.GetNumberOfBytesUsed() + 1); outBitStream->Write(0); //no compression used outBitStream->Write(settingStream); - } - else if (!syncLDF.empty()) { + } else if (!syncLDF.empty()) { std::vector ldfData; for (const auto& data : syncLDF) { @@ -936,15 +909,13 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke outBitStream->Write(settingStream.GetNumberOfBytesUsed() + 1); outBitStream->Write(0); //no compression used outBitStream->Write(settingStream); - } - else { - outBitStream->Write0(); //No ldf data + } else { + outBitStream->Write0(); //No ldf data } if (m_Trigger != nullptr && m_Trigger->events.size() > 0) { outBitStream->Write1(); - } - else { + } else { outBitStream->Write0(); } @@ -953,8 +924,7 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke if (m_ParentEntity != nullptr) outBitStream->Write(GeneralUtils::SetBit(m_ParentEntity->GetObjectID(), OBJECT_BIT_CLIENT)); else if (m_Spawner != nullptr && m_Spawner->m_Info.isNetwork) outBitStream->Write(m_SpawnerID); else outBitStream->Write(GeneralUtils::SetBit(m_SpawnerID, OBJECT_BIT_CLIENT)); - } - else outBitStream->Write0(); + } else outBitStream->Write0(); outBitStream->Write(m_HasSpawnerNodeID); if (m_HasSpawnerNodeID) outBitStream->Write(m_SpawnerNodeID); @@ -972,10 +942,9 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke if (m_GMLevel != 0) { outBitStream->Write1(); outBitStream->Write(m_GMLevel); - } - else outBitStream->Write0(); //No GM Level + } else outBitStream->Write0(); //No GM Level } - + // Only serialize parent / child info should the info be dirty (changed) or if this is the construction of the entity. outBitStream->Write(m_IsParentChildDirty || packetType == PACKET_TYPE_CONSTRUCTION); if (m_IsParentChildDirty || packetType == PACKET_TYPE_CONSTRUCTION) { @@ -1007,60 +976,51 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType unsigned int flags = 0; PossessableComponent* possessableComponent; - if (TryGetComponent(COMPONENT_TYPE_POSSESSABLE, possessableComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_POSSESSABLE, possessableComponent)) { possessableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } ModuleAssemblyComponent* moduleAssemblyComponent; - if (TryGetComponent(COMPONENT_TYPE_MODULE_ASSEMBLY, moduleAssemblyComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_MODULE_ASSEMBLY, moduleAssemblyComponent)) { moduleAssemblyComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } - + ControllablePhysicsComponent* controllablePhysicsComponent; - if (TryGetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS, controllablePhysicsComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS, controllablePhysicsComponent)) { controllablePhysicsComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } SimplePhysicsComponent* simplePhysicsComponent; - if (TryGetComponent(COMPONENT_TYPE_SIMPLE_PHYSICS, simplePhysicsComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_SIMPLE_PHYSICS, simplePhysicsComponent)) { simplePhysicsComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } RigidbodyPhantomPhysicsComponent* rigidbodyPhantomPhysics; - if (TryGetComponent(COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS, rigidbodyPhantomPhysics)) - { + if (TryGetComponent(COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS, rigidbodyPhantomPhysics)) { rigidbodyPhantomPhysics->Serialize(outBitStream, bIsInitialUpdate, flags); } VehiclePhysicsComponent* vehiclePhysicsComponent; - if (TryGetComponent(COMPONENT_TYPE_VEHICLE_PHYSICS, vehiclePhysicsComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_VEHICLE_PHYSICS, vehiclePhysicsComponent)) { vehiclePhysicsComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } PhantomPhysicsComponent* phantomPhysicsComponent; - if (TryGetComponent(COMPONENT_TYPE_PHANTOM_PHYSICS, phantomPhysicsComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_PHANTOM_PHYSICS, phantomPhysicsComponent)) { phantomPhysicsComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } SoundTriggerComponent* soundTriggerComponent; if (TryGetComponent(COMPONENT_TYPE_SOUND_TRIGGER, soundTriggerComponent)) { - soundTriggerComponent->Serialize(outBitStream, bIsInitialUpdate, flags); + soundTriggerComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } BuffComponent* buffComponent; - if (TryGetComponent(COMPONENT_TYPE_BUFF, buffComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_BUFF, buffComponent)) { buffComponent->Serialize(outBitStream, bIsInitialUpdate, flags); DestroyableComponent* destroyableComponent; - if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) { destroyableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } destroyableSerialized = true; @@ -1068,8 +1028,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType if (HasComponent(COMPONENT_TYPE_COLLECTIBLE)) { DestroyableComponent* destroyableComponent; - if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent) && !destroyableSerialized) - { + if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent) && !destroyableSerialized) { destroyableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } destroyableSerialized = true; @@ -1077,8 +1036,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } PetComponent* petComponent; - if (TryGetComponent(COMPONENT_TYPE_PET, petComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_PET, petComponent)) { petComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } @@ -1112,41 +1070,34 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType characterComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } - if (HasComponent(COMPONENT_TYPE_ITEM)) - { + if (HasComponent(COMPONENT_TYPE_ITEM)) { outBitStream->Write0(); } InventoryComponent* inventoryComponent; - if (TryGetComponent(COMPONENT_TYPE_INVENTORY, inventoryComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_INVENTORY, inventoryComponent)) { inventoryComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } ScriptComponent* scriptComponent; - if (TryGetComponent(COMPONENT_TYPE_SCRIPT, scriptComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_SCRIPT, scriptComponent)) { scriptComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } SkillComponent* skillComponent; - if (TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) { skillComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } BaseCombatAIComponent* baseCombatAiComponent; - if (TryGetComponent(COMPONENT_TYPE_BASE_COMBAT_AI, baseCombatAiComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_BASE_COMBAT_AI, baseCombatAiComponent)) { baseCombatAiComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } RebuildComponent* rebuildComponent; - if (TryGetComponent(COMPONENT_TYPE_REBUILD, rebuildComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_REBUILD, rebuildComponent)) { DestroyableComponent* destroyableComponent; - if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent) && !destroyableSerialized) - { + if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent) && !destroyableSerialized) { destroyableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } destroyableSerialized = true; @@ -1154,8 +1105,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } MovingPlatformComponent* movingPlatformComponent; - if (TryGetComponent(COMPONENT_TYPE_MOVING_PLATFORM, movingPlatformComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_MOVING_PLATFORM, movingPlatformComponent)) { movingPlatformComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } @@ -1165,14 +1115,12 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } VendorComponent* vendorComponent; - if (TryGetComponent(COMPONENT_TYPE_VENDOR, vendorComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_VENDOR, vendorComponent)) { vendorComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } BouncerComponent* bouncerComponent; - if (TryGetComponent(COMPONENT_TYPE_BOUNCER, bouncerComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_BOUNCER, bouncerComponent)) { bouncerComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } @@ -1181,20 +1129,18 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType scriptedActivityComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } - ShootingGalleryComponent* shootingGalleryComponent; - if (TryGetComponent(COMPONENT_TYPE_SHOOTING_GALLERY, shootingGalleryComponent)) { - shootingGalleryComponent->Serialize(outBitStream, bIsInitialUpdate, flags); - } + ShootingGalleryComponent* shootingGalleryComponent; + if (TryGetComponent(COMPONENT_TYPE_SHOOTING_GALLERY, shootingGalleryComponent)) { + shootingGalleryComponent->Serialize(outBitStream, bIsInitialUpdate, flags); + } RacingControlComponent* racingControlComponent; - if (TryGetComponent(COMPONENT_TYPE_RACING_CONTROL, racingControlComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_RACING_CONTROL, racingControlComponent)) { racingControlComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } LUPExhibitComponent* lupExhibitComponent; - if (TryGetComponent(COMPONENT_TYPE_EXHIBIT, lupExhibitComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_EXHIBIT, lupExhibitComponent)) { lupExhibitComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } @@ -1204,8 +1150,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } RenderComponent* renderComponent; - if (TryGetComponent(COMPONENT_TYPE_RENDER, renderComponent)) - { + if (TryGetComponent(COMPONENT_TYPE_RENDER, renderComponent)) { renderComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } @@ -1217,8 +1162,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } } - if (HasComponent(COMPONENT_TYPE_ZONE_CONTROL)) - { + if (HasComponent(COMPONENT_TYPE_ZONE_CONTROL)) { outBitStream->Write(0x40000000); } @@ -1236,8 +1180,7 @@ void Entity::UpdateXMLDoc(tinyxml2::XMLDocument* doc) { //This function should only ever be called from within Character, meaning doc should always exist when this is called. //Naturally, we don't include any non-player components in this update function. - for (const auto& pair : m_Components) - { + for (const auto& pair : m_Components) { if (pair.second == nullptr) continue; pair.second->UpdateXml(doc); @@ -1271,7 +1214,7 @@ void Entity::Update(const float deltaTime) { m_CallbackTimers.erase(m_CallbackTimers.begin() + i); } } - + // Add pending timers to the list of timers so they start next tick. if (m_PendingTimers.size() > 0) { for (auto namedTimer : m_PendingTimers) { @@ -1280,14 +1223,11 @@ void Entity::Update(const float deltaTime) { m_PendingTimers.clear(); } - if (IsSleeping()) - { + if (IsSleeping()) { Sleep(); return; - } - else - { + } else { Wake(); } @@ -1295,8 +1235,7 @@ void Entity::Update(const float deltaTime) { script->OnUpdate(this); } - for (const auto& pair : m_Components) - { + for (const auto& pair : m_Components) { if (pair.second == nullptr) continue; pair.second->Update(deltaTime); @@ -1329,8 +1268,8 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) { script->OnCollisionPhantom(this, other); } - for (const auto& callback: m_PhantomCollisionCallbacks) { - callback(other); + for (const auto& callback : m_PhantomCollisionCallbacks) { + callback(other); } SwitchComponent* switchComp = GetComponent(); @@ -1345,19 +1284,16 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) { if (!poi.empty()) { auto* missionComponent = other->GetComponent(); - - if (missionComponent != nullptr) - { + + if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_LOCATION, 0, 0, GeneralUtils::UTF16ToWTF8(poi)); } } - if (!other->GetIsDead()) - { + if (!other->GetIsDead()) { auto* combat = GetComponent(); - - if (combat != nullptr) - { + + if (combat != nullptr) { const auto index = std::find(m_TargetsInPhantom.begin(), m_TargetsInPhantom.end(), otherEntity); if (index != m_TargetsInPhantom.end()) return; @@ -1371,8 +1307,7 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) { } } -void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) -{ +void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) { auto* other = EntityManager::Instance()->GetEntity(otherEntity); if (!other) return; @@ -1384,44 +1319,41 @@ void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) } const auto index = std::find(m_TargetsInPhantom.begin(), m_TargetsInPhantom.end(), otherEntity); - + if (index == m_TargetsInPhantom.end()) return; m_TargetsInPhantom.erase(index); } void Entity::OnFireEventServerSide(Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnFireEventServerSide(this, sender, args, param1, param2, param3); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { + script->OnFireEventServerSide(this, sender, args, param1, param2, param3); } } void Entity::OnActivityStateChangeRequest(LWOOBJID senderID, int32_t value1, int32_t value2, const std::u16string& stringValue) { - for (CppScripts::Script *script : CppScripts::GetEntityScripts(this)) { - script->OnActivityStateChangeRequest(this, senderID, value1, value2, stringValue); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { + script->OnActivityStateChangeRequest(this, senderID, value1, value2, stringValue); } } -void Entity::OnCinematicUpdate(Entity *self, Entity *sender, eCinematicEvent event, const std::u16string &pathName, - float_t pathTime, float_t totalTime, int32_t waypoint) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnCinematicUpdate(self, sender, event, pathName, pathTime, totalTime, waypoint); - } +void Entity::OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, + float_t pathTime, float_t totalTime, int32_t waypoint) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { + script->OnCinematicUpdate(self, sender, event, pathName, pathTime, totalTime, waypoint); + } } -void Entity::NotifyObject(Entity* sender, const std::string& name, int32_t param1, int32_t param2) -{ +void Entity::NotifyObject(Entity* sender, const std::string& name, int32_t param1, int32_t param2) { GameMessages::SendNotifyObject(GetObjectID(), sender->GetObjectID(), GeneralUtils::ASCIIToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnNotifyObject(this, sender, name, param1, param2); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { + script->OnNotifyObject(this, sender, name, param1, param2); } } -void Entity::OnEmoteReceived(const int32_t emote, Entity* target) -{ - for (auto* script : CppScripts::GetEntityScripts(this)) - { +void Entity::OnEmoteReceived(const int32_t emote, Entity* target) { + for (auto* script : CppScripts::GetEntityScripts(this)) { script->OnEmoteReceived(this, emote, target); } } @@ -1434,9 +1366,8 @@ void Entity::OnUse(Entity* originator) { } // component base class when - - for (const auto& pair : m_Components) - { + + for (const auto& pair : m_Components) { if (pair.second == nullptr) continue; pair.second->OnUse(originator); @@ -1455,83 +1386,71 @@ void Entity::OnHit(Entity* attacker) { } } -void Entity::OnZonePropertyEditBegin() -{ +void Entity::OnZonePropertyEditBegin() { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyEditBegin(this); } } -void Entity::OnZonePropertyEditEnd() -{ +void Entity::OnZonePropertyEditEnd() { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyEditEnd(this); } } -void Entity::OnZonePropertyModelEquipped() -{ +void Entity::OnZonePropertyModelEquipped() { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyModelEquipped(this); } } -void Entity::OnZonePropertyModelPlaced(Entity* player) -{ +void Entity::OnZonePropertyModelPlaced(Entity* player) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyModelPlaced(this, player); } } -void Entity::OnZonePropertyModelPickedUp(Entity* player) -{ +void Entity::OnZonePropertyModelPickedUp(Entity* player) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyModelPickedUp(this, player); } } -void Entity::OnZonePropertyModelRemoved(Entity* player) -{ +void Entity::OnZonePropertyModelRemoved(Entity* player) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyModelRemoved(this, player); } } -void Entity::OnZonePropertyModelRemovedWhileEquipped(Entity* player) -{ +void Entity::OnZonePropertyModelRemovedWhileEquipped(Entity* player) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyModelRemovedWhileEquipped(this, player); } } -void Entity::OnZonePropertyModelRotated(Entity* player) -{ +void Entity::OnZonePropertyModelRotated(Entity* player) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnZonePropertyModelRotated(this, player); } } -void Entity::OnMessageBoxResponse(Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ +void Entity::OnMessageBoxResponse(Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnMessageBoxResponse(this, sender, button, identifier, userData); } } -void Entity::OnChoiceBoxResponse(Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) -{ +void Entity::OnChoiceBoxResponse(Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnChoiceBoxResponse(this, sender, button, buttonIdentifier, identifier); } } -void Entity::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType) -{ +void Entity::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType) { if (!m_PlayerIsReadyForUpdates) return; auto* destroyableComponent = GetComponent(); - if (destroyableComponent == nullptr) - { + if (destroyableComponent == nullptr) { Kill(EntityManager::Instance()->GetEntity(source)); return; } @@ -1550,62 +1469,53 @@ void Entity::Kill(Entity* murderer) { //OMAI WA MOU, SHINDERIU - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) - { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnDie(this, murderer); } - if (m_Spawner != nullptr) - { + if (m_Spawner != nullptr) { m_Spawner->NotifyOfEntityDeath(m_ObjectID); } - if (!IsPlayer()) - { + if (!IsPlayer()) { EntityManager::Instance()->DestroyEntity(this); } - + const auto& grpNameQBShowBricks = GetVar(u"grpNameQBShowBricks"); - if (!grpNameQBShowBricks.empty()) - { + if (!grpNameQBShowBricks.empty()) { auto spawners = dZoneManager::Instance()->GetSpawnersByName(grpNameQBShowBricks); Spawner* spawner = nullptr; - if (!spawners.empty()) - { + if (!spawners.empty()) { spawner = spawners[0]; - } - else - { + } else { spawners = dZoneManager::Instance()->GetSpawnersInGroup(grpNameQBShowBricks); - if (!spawners.empty()) - { + if (!spawners.empty()) { spawner = spawners[0]; } } - if (spawner != nullptr) - { + if (spawner != nullptr) { spawner->Spawn(); } } - // Track a player being smashed - auto* characterComponent = GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(TimesSmashed); - } + // Track a player being smashed + auto* characterComponent = GetComponent(); + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(TimesSmashed); + } - // Track a player smashing something else - if (murderer != nullptr) { - auto* murdererCharacterComponent = murderer->GetComponent(); - if (murdererCharacterComponent != nullptr) { - murdererCharacterComponent->UpdatePlayerStatistic(SmashablesSmashed); - } - } + // Track a player smashing something else + if (murderer != nullptr) { + auto* murdererCharacterComponent = murderer->GetComponent(); + if (murdererCharacterComponent != nullptr) { + murdererCharacterComponent->UpdatePlayerStatistic(SmashablesSmashed); + } + } } void Entity::AddDieCallback(const std::function& callback) { @@ -1613,14 +1523,14 @@ void Entity::AddDieCallback(const std::function& callback) { } void Entity::AddCollisionPhantomCallback(const std::function& callback) { - m_PhantomCollisionCallbacks.push_back(callback); + m_PhantomCollisionCallbacks.push_back(callback); } -void Entity::AddRebuildCompleteCallback(const std::function &callback) const { - auto* rebuildComponent = GetComponent(); - if (rebuildComponent != nullptr) { - rebuildComponent->AddRebuildCompleteCallback(callback); - } +void Entity::AddRebuildCompleteCallback(const std::function& callback) const { + auto* rebuildComponent = GetComponent(); + if (rebuildComponent != nullptr) { + rebuildComponent->AddRebuildCompleteCallback(callback); + } } bool Entity::GetIsDead() const { @@ -1642,15 +1552,15 @@ void Entity::PickupItem(const LWOOBJID& objectID) { if (!inv) return; CDObjectsTable* objectsTable = CDClientManager::Instance()->GetTable("Objects"); - + auto& droppedLoot = static_cast(this)->GetDroppedLoot(); for (const auto& p : droppedLoot) { if (p.first == objectID) { - auto* characterComponent = GetComponent(); - if (characterComponent != nullptr) { - characterComponent->TrackLOTCollection(p.second.lot); - } + auto* characterComponent = GetComponent(); + if (characterComponent != nullptr) { + characterComponent->TrackLOTCollection(p.second.lot); + } const CDObjects& object = objectsTable->GetByID(p.second.lot); if (object.id != 0 && object.type == "Powerup") { @@ -1664,13 +1574,11 @@ void Entity::PickupItem(const LWOOBJID& objectID) { auto* missionComponent = GetComponent(); - if (missionComponent != nullptr) - { + if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_POWERUP, skill.skillID); } } - } - else { + } else { inv->AddItem(p.second.lot, p.second.count, eLootSourceType::LOOT_SOURCE_PICKUP, eInventoryType::INVALID, {}, LWOOBJID_EMPTY, true, false, LWOOBJID_EMPTY, eInventoryType::INVALID, 1); } } @@ -1683,7 +1591,7 @@ bool Entity::CanPickupCoins(uint64_t count) { if (!IsPlayer()) return false; auto* player = static_cast(this); auto droppedCoins = player->GetDroppedCoins(); - if (count > droppedCoins) { + if (count > droppedCoins) { return false; } else { player->SetDroppedCoins(droppedCoins - count); @@ -1731,12 +1639,9 @@ void Entity::AddCallbackTimer(float time, std::function callback) { m_CallbackTimers.push_back(timer); } -bool Entity::HasTimer(const std::string& name) -{ - for (auto* timer : m_Timers) - { - if (timer->GetName() == name) - { +bool Entity::HasTimer(const std::string& name) { + for (auto* timer : m_Timers) { + if (timer->GetName() == name) { return true; } } @@ -1744,13 +1649,11 @@ bool Entity::HasTimer(const std::string& name) return false; } -void Entity::CancelCallbackTimers() -{ - for (auto* callback : m_CallbackTimers) - { +void Entity::CancelCallbackTimers() { + for (auto* callback : m_CallbackTimers) { delete callback; } - + m_CallbackTimers.clear(); } @@ -1762,13 +1665,13 @@ void Entity::ScheduleKillAfterUpdate(Entity* murderer) { } void Entity::CancelTimer(const std::string& name) { - for (int i = 0; i < m_Timers.size(); i++) { - if (m_Timers[i]->GetName() == name) { - delete m_Timers[i]; - m_Timers.erase(m_Timers.begin() + i); - return; - } - } + for (int i = 0; i < m_Timers.size(); i++) { + if (m_Timers[i]->GetName() == name) { + delete m_Timers[i]; + m_Timers.erase(m_Timers.begin() + i); + return; + } + } } void Entity::CancelAllTimers() { @@ -1776,8 +1679,7 @@ void Entity::CancelAllTimers() { if (timer) delete timer; }*/ - for (auto* timer : m_Timers) - { + for (auto* timer : m_Timers) { delete timer; } @@ -1859,17 +1761,16 @@ void Entity::HandleTriggerCommand(std::string id, std::string target, std::strin if (target == "self") { EntityManager::Instance()->ConstructEntity(this); } - } - else if (id == "updateMission") { + } else if (id == "updateMission") { CDMissionTasksTable* missionTasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); std::vector missionTasks = missionTasksTable->Query([=](CDMissionTasks entry) { std::string lowerTargetGroup; for (char character : entry.targetGroup) { lowerTargetGroup.push_back(std::tolower(character)); // make lowercase to ensure it works } - + return (lowerTargetGroup == argArray[4]); - }); + }); for (const CDMissionTasks& task : missionTasks) { MissionComponent* missionComponent = targetEntity->GetComponent(); @@ -1877,23 +1778,19 @@ void Entity::HandleTriggerCommand(std::string id, std::string target, std::strin missionComponent->ForceProgress(task.id, task.uid, std::stoi(argArray[2])); } - } - else if (id == "fireEvent") { + } else if (id == "fireEvent") { for (CppScripts::Script* script : CppScripts::GetEntityScripts(targetEntity)) { - script->OnFireEventServerSide(targetEntity, this, args, 0, 0, 0); + script->OnFireEventServerSide(targetEntity, this, args, 0, 0, 0); } } } } -Entity* Entity::GetOwner() const -{ - if (m_OwnerOverride != LWOOBJID_EMPTY) - { +Entity* Entity::GetOwner() const { + if (m_OwnerOverride != LWOOBJID_EMPTY) { auto* other = EntityManager::Instance()->GetEntity(m_OwnerOverride); - if (other != nullptr) - { + if (other != nullptr) { return other->GetOwner(); } } @@ -1901,272 +1798,225 @@ Entity* Entity::GetOwner() const return const_cast(this); } -const NiPoint3& Entity::GetDefaultPosition() const -{ +const NiPoint3& Entity::GetDefaultPosition() const { return m_DefaultPosition; } -const NiQuaternion& Entity::GetDefaultRotation() const -{ +const NiQuaternion& Entity::GetDefaultRotation() const { return m_DefaultRotation; } -float Entity::GetDefaultScale() const -{ +float Entity::GetDefaultScale() const { return m_Scale; } -void Entity::SetOwnerOverride(const LWOOBJID value) -{ +void Entity::SetOwnerOverride(const LWOOBJID value) { m_OwnerOverride = value; } -bool Entity::GetIsGhostingCandidate() const -{ +bool Entity::GetIsGhostingCandidate() const { return m_IsGhostingCandidate; } -int8_t Entity::GetObservers() const -{ +int8_t Entity::GetObservers() const { return m_Observers; } -void Entity::SetObservers(int8_t value) -{ - if (value < 0) - { +void Entity::SetObservers(int8_t value) { + if (value < 0) { value = 0; } m_Observers = value; } -void Entity::Sleep() -{ +void Entity::Sleep() { auto* baseCombatAIComponent = GetComponent(); - - if (baseCombatAIComponent != nullptr) - { + + if (baseCombatAIComponent != nullptr) { baseCombatAIComponent->Sleep(); - } + } } -void Entity::Wake() -{ +void Entity::Wake() { auto* baseCombatAIComponent = GetComponent(); - - if (baseCombatAIComponent != nullptr) - { + + if (baseCombatAIComponent != nullptr) { baseCombatAIComponent->Wake(); } } -bool Entity::IsSleeping() const -{ +bool Entity::IsSleeping() const { return m_IsGhostingCandidate && m_Observers == 0; } -const NiPoint3& Entity::GetPosition() const -{ +const NiPoint3& Entity::GetPosition() const { if (!this) return NiPoint3::ZERO; auto* controllable = GetComponent(); - if (controllable != nullptr) - { + if (controllable != nullptr) { return controllable->GetPosition(); } auto* phantom = GetComponent(); - if (phantom != nullptr) - { + if (phantom != nullptr) { return phantom->GetPosition(); } auto* simple = GetComponent(); - if (simple != nullptr) - { + if (simple != nullptr) { return simple->GetPosition(); } auto* vehicel = GetComponent(); - if (vehicel != nullptr) - { + if (vehicel != nullptr) { return vehicel->GetPosition(); } return NiPoint3::ZERO; } -const NiQuaternion& Entity::GetRotation() const -{ +const NiQuaternion& Entity::GetRotation() const { auto* controllable = GetComponent(); - if (controllable != nullptr) - { + if (controllable != nullptr) { return controllable->GetRotation(); } auto* phantom = GetComponent(); - if (phantom != nullptr) - { + if (phantom != nullptr) { return phantom->GetRotation(); } auto* simple = GetComponent(); - if (simple != nullptr) - { + if (simple != nullptr) { return simple->GetRotation(); } - + auto* vehicel = GetComponent(); - if (vehicel != nullptr) - { + if (vehicel != nullptr) { return vehicel->GetRotation(); } return NiQuaternion::IDENTITY; } -void Entity::SetPosition(NiPoint3 position) -{ +void Entity::SetPosition(NiPoint3 position) { auto* controllable = GetComponent(); - if (controllable != nullptr) - { + if (controllable != nullptr) { controllable->SetPosition(position); } auto* phantom = GetComponent(); - if (phantom != nullptr) - { + if (phantom != nullptr) { phantom->SetPosition(position); } auto* simple = GetComponent(); - if (simple != nullptr) - { + if (simple != nullptr) { simple->SetPosition(position); } auto* vehicel = GetComponent(); - if (vehicel != nullptr) - { + if (vehicel != nullptr) { vehicel->SetPosition(position); } EntityManager::Instance()->SerializeEntity(this); } -void Entity::SetRotation(NiQuaternion rotation) -{ +void Entity::SetRotation(NiQuaternion rotation) { auto* controllable = GetComponent(); - if (controllable != nullptr) - { + if (controllable != nullptr) { controllable->SetRotation(rotation); } auto* phantom = GetComponent(); - if (phantom != nullptr) - { + if (phantom != nullptr) { phantom->SetRotation(rotation); } auto* simple = GetComponent(); - if (simple != nullptr) - { + if (simple != nullptr) { simple->SetRotation(rotation); } auto* vehicel = GetComponent(); - if (vehicel != nullptr) - { + if (vehicel != nullptr) { vehicel->SetRotation(rotation); } EntityManager::Instance()->SerializeEntity(this); } -bool Entity::GetBoolean(const std::u16string& name) const -{ +bool Entity::GetBoolean(const std::u16string& name) const { return GetVar(name); } -int32_t Entity::GetI32(const std::u16string& name) const -{ +int32_t Entity::GetI32(const std::u16string& name) const { return GetVar(name); } -int64_t Entity::GetI64(const std::u16string& name) const -{ +int64_t Entity::GetI64(const std::u16string& name) const { return GetVar(name); } -void Entity::SetBoolean(const std::u16string& name, const bool value) -{ +void Entity::SetBoolean(const std::u16string& name, const bool value) { SetVar(name, value); } -void Entity::SetI32(const std::u16string& name, const int32_t value) -{ +void Entity::SetI32(const std::u16string& name, const int32_t value) { SetVar(name, value); } -void Entity::SetI64(const std::u16string& name, const int64_t value) -{ +void Entity::SetI64(const std::u16string& name, const int64_t value) { SetVar(name, value); } -bool Entity::HasVar(const std::u16string& name) const -{ - for (auto* data : m_Settings) - { - if (data->GetKey() == name) - { +bool Entity::HasVar(const std::u16string& name) const { + for (auto* data : m_Settings) { + if (data->GetKey() == name) { return true; } } - + return false; } -uint16_t Entity::GetNetworkId() const -{ +uint16_t Entity::GetNetworkId() const { return m_NetworkID; } -void Entity::SetNetworkId(const uint16_t id) -{ +void Entity::SetNetworkId(const uint16_t id) { m_NetworkID = id; } -std::vector& Entity::GetTargetsInPhantom() -{ +std::vector& Entity::GetTargetsInPhantom() { std::vector valid; // Clean up invalid targets, like disconnected players - for (auto i = 0u; i < m_TargetsInPhantom.size(); ++i) - { + for (auto i = 0u; i < m_TargetsInPhantom.size(); ++i) { const auto id = m_TargetsInPhantom.at(i); auto* entity = EntityManager::Instance()->GetEntity(id); - if (entity == nullptr) - { + if (entity == nullptr) { continue; } @@ -2179,20 +2029,16 @@ std::vector& Entity::GetTargetsInPhantom() } void Entity::SendNetworkVar(const std::string& data, const SystemAddress& sysAddr) { - GameMessages::SendSetNetworkScriptVar(this, sysAddr, data); + GameMessages::SendSetNetworkScriptVar(this, sysAddr, data); } -LDFBaseData* Entity::GetVarData(const std::u16string& name) const -{ - for (auto* data : m_Settings) - { - if (data == nullptr) - { +LDFBaseData* Entity::GetVarData(const std::u16string& name) const { + for (auto* data : m_Settings) { + if (data == nullptr) { continue; } - if (data->GetKey() != name) - { + if (data->GetKey() != name) { continue; } @@ -2202,12 +2048,10 @@ LDFBaseData* Entity::GetVarData(const std::u16string& name) const return nullptr; } -std::string Entity::GetVarAsString(const std::u16string& name) const -{ +std::string Entity::GetVarAsString(const std::u16string& name) const { auto* data = GetVarData(name); - if (data == nullptr) - { + if (data == nullptr) { return ""; } @@ -2215,15 +2059,15 @@ std::string Entity::GetVarAsString(const std::u16string& name) const } void Entity::Resurrect() { - if (IsPlayer()) { - GameMessages::SendResurrect(this); - } + if (IsPlayer()) { + GameMessages::SendResurrect(this); + } } void Entity::AddToGroup(const std::string& group) { - if (std::find(m_Groups.begin(), m_Groups.end(), group) == m_Groups.end()) { - m_Groups.push_back(group); - } + if (std::find(m_Groups.begin(), m_Groups.end(), group) == m_Groups.end()) { + m_Groups.push_back(group); + } } void Entity::RetroactiveVaultSize() { diff --git a/dGame/Entity.h b/dGame/Entity.h index 85f992e8..6c0968f8 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -33,27 +33,27 @@ class Character; */ class Entity { public: - explicit Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity = nullptr); - virtual ~Entity(); + explicit Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity = nullptr); + virtual ~Entity(); virtual void Initialize(); - - bool operator==(const Entity& other) const; - bool operator!=(const Entity& other) const; + + bool operator==(const Entity& other) const; + bool operator!=(const Entity& other) const; /** * Getters */ - - const LWOOBJID& GetObjectID() const { return m_ObjectID; } - const LOT GetLOT() const { return m_TemplateID; } + const LWOOBJID& GetObjectID() const { return m_ObjectID; } - Character* GetCharacter() const { return m_Character; } + const LOT GetLOT() const { return m_TemplateID; } - uint8_t GetGMLevel() const { return m_GMLevel; } + Character* GetCharacter() const { return m_Character; } - uint8_t GetCollectibleID() const { return uint8_t(m_CollectibleID); } + uint8_t GetGMLevel() const { return m_GMLevel; } + + uint8_t GetCollectibleID() const { return uint8_t(m_CollectibleID); } Entity* GetParentEntity() const { return m_ParentEntity; } @@ -62,7 +62,7 @@ public: std::vector& GetGroups() { return m_Groups; }; Spawner* GetSpawner() const { return m_Spawner; } - + LWOOBJID GetSpawnerID() const { return m_SpawnerID; } const std::vector& GetSettings() const { return m_Settings; } @@ -71,7 +71,7 @@ public: bool GetIsDead() const; - bool GetPlayerReadyForUpdates() const { return m_PlayerIsReadyForUpdates;} + bool GetPlayerReadyForUpdates() const { return m_PlayerIsReadyForUpdates; } bool GetIsGhostingCandidate() const; @@ -86,7 +86,7 @@ public: const NiQuaternion& GetDefaultRotation() const; float GetDefaultScale() const; - + const NiPoint3& GetPosition() const; const NiQuaternion& GetRotation() const; @@ -99,9 +99,9 @@ public: * Setters */ - void SetCharacter(Character* value) { m_Character = value; } - - void SetGMLevel(uint8_t value); + void SetCharacter(Character* value) { m_Character = value; } + + void SetGMLevel(uint8_t value); void SetOwnerOverride(LWOOBJID value); @@ -118,14 +118,14 @@ public: virtual void SetRespawnPos(NiPoint3 position) {} virtual void SetRespawnRot(NiQuaternion rotation) {} - + virtual void SetSystemAddress(const SystemAddress& value) {}; /** * Component management */ - Component* GetComponent(int32_t componentID) const; + Component* GetComponent(int32_t componentID) const; template T* GetComponent() const; @@ -152,32 +152,32 @@ public: void CancelAllTimers(); void CancelTimer(const std::string& name); - void AddToGroup(const std::string& group); + void AddToGroup(const std::string& group); bool IsPlayer() const; std::unordered_map& GetComponents() { return m_Components; } // TODO: Remove - + void WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacketType packetType); void WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType packetType); - void ResetFlags(); - void UpdateXMLDoc(tinyxml2::XMLDocument* doc); + void ResetFlags(); + void UpdateXMLDoc(tinyxml2::XMLDocument* doc); void Update(float deltaTime); // Events void OnCollisionProximity(LWOOBJID otherEntity, const std::string& proxName, const std::string& status); void OnCollisionPhantom(LWOOBJID otherEntity); - void OnCollisionLeavePhantom(LWOOBJID otherEntity); + void OnCollisionLeavePhantom(LWOOBJID otherEntity); - void OnFireEventServerSide(Entity* sender, std::string args, int32_t param1 = -1, int32_t param2 = -1, int32_t param3 = -1); - void OnActivityStateChangeRequest(const LWOOBJID senderID, const int32_t value1, const int32_t value2, - const std::u16string& stringValue); - void OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, - float_t pathTime, float_t totalTime, int32_t waypoint); + void OnFireEventServerSide(Entity* sender, std::string args, int32_t param1 = -1, int32_t param2 = -1, int32_t param3 = -1); + void OnActivityStateChangeRequest(const LWOOBJID senderID, const int32_t value1, const int32_t value2, + const std::u16string& stringValue); + void OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, + float_t pathTime, float_t totalTime, int32_t waypoint); void NotifyObject(Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0); void OnEmoteReceived(int32_t emote, Entity* target); - - void OnUse(Entity* originator); + + void OnUse(Entity* originator); void OnHitOrHealResult(Entity* attacker, int32_t damage); void OnHit(Entity* attacker); @@ -196,7 +196,7 @@ public: void Smash(const LWOOBJID source = LWOOBJID_EMPTY, const eKillType killType = eKillType::VIOLENT, const std::u16string& deathType = u""); void Kill(Entity* murderer = nullptr); - void AddRebuildCompleteCallback(const std::function& callback) const; + void AddRebuildCompleteCallback(const std::function& callback) const; void AddCollisionPhantomCallback(const std::function& callback); void AddDieCallback(const std::function& callback); void Resurrect(); @@ -222,15 +222,15 @@ public: /* * Utility */ - /** - * Retroactively corrects the model vault size due to incorrect initialization in a previous patch. - * - */ + /** + * Retroactively corrects the model vault size due to incorrect initialization in a previous patch. + * + */ void RetroactiveVaultSize(); bool GetBoolean(const std::u16string& name) const; int32_t GetI32(const std::u16string& name) const; int64_t GetI64(const std::u16string& name) const; - + void SetBoolean(const std::u16string& name, bool value); void SetI32(const std::u16string& name, int32_t value); void SetI64(const std::u16string& name, int64_t value); @@ -248,11 +248,11 @@ public: template void SetNetworkVar(const std::u16string& name, T value, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); - template - void SetNetworkVar(const std::u16string& name, std::vector value, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); + template + void SetNetworkVar(const std::u16string& name, std::vector value, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); - template - T GetNetworkVar(const std::u16string& name); + template + T GetNetworkVar(const std::u16string& name); /** * Get the LDF value and cast it as T. @@ -278,37 +278,37 @@ public: Entity* GetScheduledKiller() { return m_ScheduleKiller; } protected: - LWOOBJID m_ObjectID; - - LOT m_TemplateID; - - std::vector m_Settings; - std::vector m_NetworkSettings; + LWOOBJID m_ObjectID; - NiPoint3 m_DefaultPosition; - NiQuaternion m_DefaultRotation; + LOT m_TemplateID; + + std::vector m_Settings; + std::vector m_NetworkSettings; + + NiPoint3 m_DefaultPosition; + NiQuaternion m_DefaultRotation; float m_Scale; Spawner* m_Spawner; - LWOOBJID m_SpawnerID; - - bool m_HasSpawnerNodeID; - uint32_t m_SpawnerNodeID; - + LWOOBJID m_SpawnerID; + + bool m_HasSpawnerNodeID; + uint32_t m_SpawnerNodeID; + LUTriggers::Trigger* m_Trigger; Character* m_Character; - - Entity* m_ParentEntity; //For spawners and the like + + Entity* m_ParentEntity; //For spawners and the like std::vector m_ChildEntities; - uint8_t m_GMLevel; - uint16_t m_CollectibleID; + uint8_t m_GMLevel; + uint16_t m_CollectibleID; std::vector m_Groups; uint16_t m_NetworkID; std::vector> m_DieCallbacks; - std::vector> m_PhantomCollisionCallbacks; - - std::unordered_map m_Components; //The int is the ID of the component + std::vector> m_PhantomCollisionCallbacks; + + std::unordered_map m_Components; //The int is the ID of the component std::vector m_Timers; std::vector m_PendingTimers; std::vector m_CallbackTimers; @@ -338,12 +338,10 @@ protected: */ template -bool Entity::TryGetComponent(const int32_t componentId, T*& component) const -{ +bool Entity::TryGetComponent(const int32_t componentId, T*& component) const { const auto& index = m_Components.find(componentId); - if (index == m_Components.end()) - { + if (index == m_Components.end()) { component = nullptr; return false; @@ -355,26 +353,22 @@ bool Entity::TryGetComponent(const int32_t componentId, T*& component) const } template -T* Entity::GetComponent() const -{ +T* Entity::GetComponent() const { return dynamic_cast(GetComponent(T::ComponentType)); } template -const T& Entity::GetVar(const std::u16string& name) const -{ +const T& Entity::GetVar(const std::u16string& name) const { auto* data = GetVarData(name); - if (data == nullptr) - { + if (data == nullptr) { return LDFData::Default; } auto* typed = dynamic_cast*>(data); - if (typed == nullptr) - { + if (typed == nullptr) { return LDFData::Default; } @@ -382,14 +376,12 @@ const T& Entity::GetVar(const std::u16string& name) const } template -T Entity::GetVarAs(const std::u16string& name) const -{ +T Entity::GetVarAs(const std::u16string& name) const { const auto data = GetVarAsString(name); T value; - if (!GeneralUtils::TryParse(data, value)) - { + if (!GeneralUtils::TryParse(data, value)) { return LDFData::Default; } @@ -397,12 +389,10 @@ T Entity::GetVarAs(const std::u16string& name) const } template -void Entity::SetVar(const std::u16string& name, T value) -{ +void Entity::SetVar(const std::u16string& name, T value) { auto* data = GetVarData(name); - if (data == nullptr) - { + if (data == nullptr) { auto* data = new LDFData(name, value); m_Settings.push_back(data); @@ -412,8 +402,7 @@ void Entity::SetVar(const std::u16string& name, T value) auto* typed = dynamic_cast*>(data); - if (typed == nullptr) - { + if (typed == nullptr) { return; } @@ -422,81 +411,81 @@ void Entity::SetVar(const std::u16string& name, T value) template void Entity::SetNetworkVar(const std::u16string& name, T value, const SystemAddress& sysAddr) { - LDFData* newData = nullptr; + LDFData* newData = nullptr; - for (auto* data :m_NetworkSettings) { - if (data->GetKey() != name) - continue; + for (auto* data : m_NetworkSettings) { + if (data->GetKey() != name) + continue; - newData = dynamic_cast*>(data); - if (newData != nullptr) { - newData->SetValue(value); - } else { // If we're changing types - m_NetworkSettings.erase( + newData = dynamic_cast*>(data); + if (newData != nullptr) { + newData->SetValue(value); + } else { // If we're changing types + m_NetworkSettings.erase( std::remove(m_NetworkSettings.begin(), m_NetworkSettings.end(), data), m_NetworkSettings.end() ); - delete data; - } + delete data; + } - break; - } + break; + } - if (newData == nullptr) { - newData = new LDFData(name, value); - } + if (newData == nullptr) { + newData = new LDFData(name, value); + } - m_NetworkSettings.push_back(newData); - SendNetworkVar(newData->GetString(true), sysAddr); + m_NetworkSettings.push_back(newData); + SendNetworkVar(newData->GetString(true), sysAddr); } template void Entity::SetNetworkVar(const std::u16string& name, std::vector values, const SystemAddress& sysAddr) { - std::stringstream updates; - auto index = 1; + std::stringstream updates; + auto index = 1; - for (const auto& value : values) { - LDFData* newData = nullptr; - const auto& indexedName = name + u"." + GeneralUtils::to_u16string(index); + for (const auto& value : values) { + LDFData* newData = nullptr; + const auto& indexedName = name + u"." + GeneralUtils::to_u16string(index); - for (auto* data : m_NetworkSettings) { - if (data->GetKey() != indexedName) - continue; + for (auto* data : m_NetworkSettings) { + if (data->GetKey() != indexedName) + continue; - newData = dynamic_cast*>(data); - newData->SetValue(value); - break; - } + newData = dynamic_cast*>(data); + newData->SetValue(value); + break; + } - if (newData == nullptr) { - newData = new LDFData(indexedName, value); - } + if (newData == nullptr) { + newData = new LDFData(indexedName, value); + } - m_NetworkSettings.push_back(newData); + m_NetworkSettings.push_back(newData); - if (index == values.size()) { - updates << newData->GetString(true); - } else { - updates << newData->GetString(true) << "\n"; - } + if (index == values.size()) { + updates << newData->GetString(true); + } else { + updates << newData->GetString(true) << "\n"; + } - index++; - } + index++; + } - SendNetworkVar(updates.str(), sysAddr); + SendNetworkVar(updates.str(), sysAddr); } template T Entity::GetNetworkVar(const std::u16string& name) { - for (auto* data : m_NetworkSettings) { - if (data == nullptr || data->GetKey() != name) - continue; + for (auto* data : m_NetworkSettings) { + if (data == nullptr || data->GetKey() != name) + continue; - auto* typed = dynamic_cast*>(data); - if (typed == nullptr) - continue; + auto* typed = dynamic_cast*>(data); + if (typed == nullptr) + continue; - return typed->GetValue(); - } + return typed->GetValue(); + } - return LDFData::Default; + return LDFData::Default; } diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index d6e6256f..02b8b59e 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -65,7 +65,7 @@ EntityManager::~EntityManager() { Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentEntity, const bool controller, const LWOOBJID explicitId) { // Determine the objectID for the new entity - LWOOBJID id; + LWOOBJID id; // If an explicit ID was provided, use it if (explicitId != LWOOBJID_EMPTY) { @@ -76,17 +76,17 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE else if (user == nullptr || info.lot != 1) { // Entities with no ID already set, often spawned entities, we'll generate a new sequencial ID - if (info.id == 0) { + if (info.id == 0) { id = ObjectIDManager::Instance()->GenerateObjectID(); } // Entities with an ID already set, often level entities, we'll use that ID as a base - else { + else { id = info.id; } // Exclude the zone control object from any flags - if(!controller && info.lot != 14) { + if (!controller && info.lot != 14) { // The client flags means the client should render the entity id = GeneralUtils::SetBit(id, OBJECT_BIT_CLIENT); @@ -96,22 +96,21 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE id = GeneralUtils::SetBit(id, OBJECT_BIT_SPAWNED); } } - } + } // For players, we'll use the persistent ID for that character else { id = user->GetLastUsedChar()->GetObjectID(); } - info.id = id; + 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 { + } else { entity = new Entity(id, info, parentEntity); } @@ -133,7 +132,7 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE m_SpawnPoints.insert_or_assign(GeneralUtils::UTF16ToWTF8(spawnName), entity->GetObjectID()); } - return entity; + return entity; } void EntityManager::DestroyEntity(const LWOOBJID& objectID) { @@ -229,11 +228,10 @@ void EntityManager::UpdateEntities(const float deltaTime) { m_EntitiesToDelete.clear(); } -Entity * EntityManager::GetEntity(const LWOOBJID& objectId) const { +Entity* EntityManager::GetEntity(const LWOOBJID& objectId) const { const auto& index = m_Entities.find(objectId); - if (index == m_Entities.end()) - { + if (index == m_Entities.end()) { return nullptr; } @@ -263,29 +261,26 @@ std::vector EntityManager::GetEntitiesByComponent(const int componentTy return withComp; } -std::vector EntityManager::GetEntitiesByLOT(const LOT &lot) const { - std::vector entities; +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 (const auto& entity : m_Entities) { + if (entity.second->GetLOT() == lot) + entities.push_back(entity.second); + } - return entities; + return entities; } -Entity* EntityManager::GetZoneControlEntity() const -{ +Entity* EntityManager::GetZoneControlEntity() const { return m_ZoneControlEntity; } -Entity* EntityManager::GetSpawnPointEntity(const std::string& spawnName) const -{ +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()) - { + if (spawnPoint == m_SpawnPoints.end()) { return nullptr; } @@ -293,23 +288,18 @@ Entity* EntityManager::GetSpawnPointEntity(const std::string& spawnName) const return GetEntity(spawnPoint->second); } -const std::unordered_map& EntityManager::GetSpawnPointEntities() const -{ +const std::unordered_map& EntityManager::GetSpawnPointEntities() const { return m_SpawnPoints; } void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr, const bool skipChecks) { - if (entity->GetNetworkId() == 0) - { + if (entity->GetNetworkId() == 0) { uint16_t networkId; - if (!m_LostNetworkIds.empty()) - { + if (!m_LostNetworkIds.empty()) { networkId = m_LostNetworkIds.top(); m_LostNetworkIds.pop(); - } - else - { + } else { networkId = ++m_NetworkIdCounter; } @@ -318,18 +308,15 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr const auto checkGhosting = entity->GetIsGhostingCandidate(); - if (checkGhosting) - { + if (checkGhosting) { const auto& iter = std::find(m_EntitiesToGhost.begin(), m_EntitiesToGhost.end(), entity); - if (iter == m_EntitiesToGhost.end()) - { + if (iter == m_EntitiesToGhost.end()) { m_EntitiesToGhost.push_back(entity); } } - if (checkGhosting && sysAddr == UNASSIGNED_SYSTEM_ADDRESS) - { + if (checkGhosting && sysAddr == UNASSIGNED_SYSTEM_ADDRESS) { CheckGhosting(entity); return; @@ -346,38 +333,26 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr entity->WriteBaseReplicaData(&stream, PACKET_TYPE_CONSTRUCTION); entity->WriteComponents(&stream, PACKET_TYPE_CONSTRUCTION); - if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) - { - if (skipChecks) - { + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) { + if (skipChecks) { Game::server->Send(&stream, UNASSIGNED_SYSTEM_ADDRESS, true); - } - else - { - for (auto* player : Player::GetAllPlayers()) - { - if (player->GetPlayerReadyForUpdates()) - { + } else { + for (auto* player : Player::GetAllPlayers()) { + if (player->GetPlayerReadyForUpdates()) { Game::server->Send(&stream, player->GetSystemAddress(), false); - } - else - { + } else { player->AddLimboConstruction(entity->GetObjectID()); } } } - } - else - { + } else { Game::server->Send(&stream, sysAddr, false); } // PacketUtils::SavePacket("[24]_"+std::to_string(entity->GetObjectID()) + "_" + std::to_string(m_SerializationCounter) + ".bin", (char*)stream.GetData(), stream.GetNumberOfBytesUsed()); - if (entity->IsPlayer()) - { - if (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN) - { + if (entity->IsPlayer()) { + if (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), true, sysAddr); } } @@ -387,18 +362,17 @@ void EntityManager::ConstructAllEntities(const SystemAddress& sysAddr) { //ZoneControl is special: ConstructEntity(m_ZoneControlEntity, sysAddr); - for (const auto& e : m_Entities) { + for (const auto& e : m_Entities) { if (e.second && (e.second->GetSpawnerID() != 0 || e.second->GetLOT() == 1) && !e.second->GetIsGhostingCandidate()) { ConstructEntity(e.second, sysAddr); } - } + } UpdateGhosting(Player::GetPlayer(sysAddr)); } void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr) { - if (entity->GetNetworkId() == 0) - { + if (entity->GetNetworkId() == 0) { return; } @@ -409,23 +383,19 @@ void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr) Game::server->Send(&stream, sysAddr, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); - for (auto* player : Player::GetAllPlayers()) - { - if (!player->GetPlayerReadyForUpdates()) - { + for (auto* player : Player::GetAllPlayers()) { + if (!player->GetPlayerReadyForUpdates()) { player->RemoveLimboConstruction(entity->GetObjectID()); } } } void EntityManager::SerializeEntity(Entity* entity) { - if (entity->GetNetworkId() == 0) - { + if (entity->GetNetworkId() == 0) { return; } - if (std::find(m_EntitiesToSerialize.begin(), m_EntitiesToSerialize.end(), entity->GetObjectID()) == m_EntitiesToSerialize.end()) - { + if (std::find(m_EntitiesToSerialize.begin(), m_EntitiesToSerialize.end(), entity->GetObjectID()) == m_EntitiesToSerialize.end()) { m_EntitiesToSerialize.push_back(entity->GetObjectID()); } @@ -433,49 +403,40 @@ void EntityManager::SerializeEntity(Entity* entity) { } void EntityManager::DestructAllEntities(const SystemAddress& sysAddr) { - for (const auto& e : m_Entities) { + for (const auto& e : m_Entities) { DestructEntity(e.second, sysAddr); - } + } } -void EntityManager::SetGhostDistanceMax(float value) -{ +void EntityManager::SetGhostDistanceMax(float value) { m_GhostDistanceMaxSquared = value * value; } -float EntityManager::GetGhostDistanceMax() const -{ +float EntityManager::GetGhostDistanceMax() const { return std::sqrt(m_GhostDistanceMaxSquared); } -void EntityManager::SetGhostDistanceMin(float value) -{ +void EntityManager::SetGhostDistanceMin(float value) { m_GhostDistanceMinSqaured = value * value; } -float EntityManager::GetGhostDistanceMin() const -{ +float EntityManager::GetGhostDistanceMin() const { return std::sqrt(m_GhostDistanceMinSqaured); } -void EntityManager::QueueGhostUpdate(LWOOBJID playerID) -{ +void EntityManager::QueueGhostUpdate(LWOOBJID playerID) { const auto& iter = std::find(m_PlayersToUpdateGhosting.begin(), m_PlayersToUpdateGhosting.end(), playerID); - if (iter == m_PlayersToUpdateGhosting.end()) - { + if (iter == m_PlayersToUpdateGhosting.end()) { m_PlayersToUpdateGhosting.push_back(playerID); } } -void EntityManager::UpdateGhosting() -{ - for (const auto playerID : m_PlayersToUpdateGhosting) - { +void EntityManager::UpdateGhosting() { + for (const auto playerID : m_PlayersToUpdateGhosting) { auto* player = Player::GetPlayer(playerID); - if (player == nullptr) - { + if (player == nullptr) { continue; } @@ -485,25 +446,21 @@ void EntityManager::UpdateGhosting() m_PlayersToUpdateGhosting.clear(); } -void EntityManager::UpdateGhosting(Player* player) -{ - if (player == nullptr) - { +void EntityManager::UpdateGhosting(Player* player) { + if (player == nullptr) { return; } auto* missionComponent = player->GetComponent(); - if (missionComponent == nullptr) - { + if (missionComponent == nullptr) { return; } const auto& referencePoint = player->GetGhostReferencePoint(); const auto isOverride = player->GetGhostOverride(); - for (auto* entity : m_EntitiesToGhost) - { + for (auto* entity : m_EntitiesToGhost) { const auto isAudioEmitter = entity->GetLOT() == 6368; const auto& entityPoint = entity->GetPosition(); @@ -517,30 +474,24 @@ void EntityManager::UpdateGhosting(Player* player) auto ghostingDistanceMax = m_GhostDistanceMaxSquared; auto ghostingDistanceMin = m_GhostDistanceMinSqaured; - if (isAudioEmitter) - { + if (isAudioEmitter) { ghostingDistanceMax = ghostingDistanceMin; } - if (observed && distance > ghostingDistanceMax && !isOverride) - { + if (observed && distance > ghostingDistanceMax && !isOverride) { player->GhostEntity(id); DestructEntity(entity, player->GetSystemAddress()); entity->SetObservers(entity->GetObservers() - 1); - } - else if (!observed && ghostingDistanceMin > distance) - { + } else if (!observed && ghostingDistanceMin > distance) { // Check collectables, don't construct if it has been collected uint32_t collectionId = entity->GetCollectibleID(); - if (collectionId != 0) - { + if (collectionId != 0) { collectionId = static_cast(collectionId) + static_cast(Game::server->GetZoneID() << 8); - if (missionComponent->HasCollectible(collectionId)) - { + if (missionComponent->HasCollectible(collectionId)) { continue; } } @@ -554,10 +505,8 @@ void EntityManager::UpdateGhosting(Player* player) } } -void EntityManager::CheckGhosting(Entity* entity) -{ - if (entity == nullptr) - { +void EntityManager::CheckGhosting(Entity* entity) { + if (entity == nullptr) { return; } @@ -568,8 +517,7 @@ void EntityManager::CheckGhosting(Entity* entity) const auto isAudioEmitter = entity->GetLOT() == 6368; - for (auto* player : Player::GetAllPlayers()) - { + for (auto* player : Player::GetAllPlayers()) { const auto& entityPoint = player->GetGhostReferencePoint(); const int32_t id = entity->GetObjectID(); @@ -578,16 +526,13 @@ void EntityManager::CheckGhosting(Entity* entity) const auto distance = NiPoint3::DistanceSquared(referencePoint, entityPoint); - if (observed && distance > ghostingDistanceMax) - { + if (observed && distance > ghostingDistanceMax) { player->GhostEntity(id); DestructEntity(entity, player->GetSystemAddress()); entity->SetObservers(entity->GetObservers() - 1); - } - else if (!observed && ghostingDistanceMin > distance) - { + } else if (!observed && ghostingDistanceMin > distance) { player->ObserveEntity(id); ConstructEntity(entity, player->GetSystemAddress()); @@ -597,12 +542,9 @@ void EntityManager::CheckGhosting(Entity* entity) } } -Entity* EntityManager::GetGhostCandidate(int32_t id) -{ - for (auto* entity : m_EntitiesToGhost) - { - if (entity->GetObjectID() == id) - { +Entity* EntityManager::GetGhostCandidate(int32_t id) { + for (auto* entity : m_EntitiesToGhost) { + if (entity->GetObjectID() == id) { return entity; } } @@ -610,8 +552,7 @@ Entity* EntityManager::GetGhostCandidate(int32_t id) return nullptr; } -bool EntityManager::GetGhostingEnabled() const -{ +bool EntityManager::GetGhostingEnabled() const { return m_GhostingEnabled; } @@ -633,18 +574,15 @@ void EntityManager::ScheduleForKill(Entity* entity) { const auto objectId = entity->GetObjectID(); - if (std::count(m_EntitiesToKill.begin(), m_EntitiesToKill.end(), objectId)) - { + if (std::count(m_EntitiesToKill.begin(), m_EntitiesToKill.end(), objectId)) { return; } m_EntitiesToKill.push_back(objectId); } -void EntityManager::ScheduleForDeletion(LWOOBJID entity) -{ - if (std::count(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity)) - { +void EntityManager::ScheduleForDeletion(LWOOBJID entity) { + if (std::count(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity)) { return; } @@ -660,7 +598,6 @@ void EntityManager::FireEventServerSide(Entity* origin, std::string args) { } } -bool EntityManager::IsExcludedFromGhosting(LOT lot) -{ +bool EntityManager::IsExcludedFromGhosting(LOT lot) { return std::find(m_GhostingExcludedLOTs.begin(), m_GhostingExcludedLOTs.end(), lot) != m_GhostingExcludedLOTs.end(); } diff --git a/dGame/EntityManager.h b/dGame/EntityManager.h index 8fb2585c..40a98076 100644 --- a/dGame/EntityManager.h +++ b/dGame/EntityManager.h @@ -14,24 +14,24 @@ class User; class EntityManager { public: - static EntityManager* Instance() { + static EntityManager* Instance() { if (!m_Address) { m_Address = new EntityManager(); m_Address->Initialize(); } - + return m_Address; } - - void Initialize(); - ~EntityManager(); - - void UpdateEntities(float deltaTime); - Entity* CreateEntity(EntityInfo info, User* user = nullptr, Entity* parentEntity = nullptr, bool controller = false, LWOOBJID explicitId = LWOOBJID_EMPTY); - void DestroyEntity(const LWOOBJID& objectID); + void Initialize(); + + ~EntityManager(); + + void UpdateEntities(float deltaTime); + Entity* CreateEntity(EntityInfo info, User* user = nullptr, Entity* parentEntity = nullptr, bool controller = false, LWOOBJID explicitId = LWOOBJID_EMPTY); + void DestroyEntity(const LWOOBJID& objectID); void DestroyEntity(Entity* entity); - Entity* GetEntity(const LWOOBJID& objectId) const; + Entity* GetEntity(const LWOOBJID& objectId) const; std::vector GetEntitiesInGroup(const std::string& group); std::vector GetEntitiesByComponent(int componentType) const; std::vector GetEntitiesByLOT(const LOT& lot) const; @@ -48,12 +48,12 @@ public: const std::unordered_map GetAllEntities() const { return m_Entities; } #endif - void ConstructEntity(Entity * entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, bool skipChecks = false); - void DestructEntity(Entity * entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); + void ConstructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, bool skipChecks = false); + void DestructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void SerializeEntity(Entity* entity); - - void ConstructAllEntities(const SystemAddress& sysAddr); - void DestructAllEntities(const SystemAddress& sysAddr); + + void ConstructAllEntities(const SystemAddress& sysAddr); + void DestructAllEntities(const SystemAddress& sysAddr); void SetGhostDistanceMax(float value); float GetGhostDistanceMax() const; @@ -69,19 +69,19 @@ public: void ResetFlags(); void ScheduleForKill(Entity* entity); - + void ScheduleForDeletion(LWOOBJID entity); void FireEventServerSide(Entity* origin, std::string args); - + static bool IsExcludedFromGhosting(LOT lot); private: - static EntityManager* m_Address; //For singleton method + static EntityManager* m_Address; //For singleton method static std::vector m_GhostingExcludedZones; static std::vector m_GhostingExcludedLOTs; - std::unordered_map m_Entities; + std::unordered_map m_Entities; std::vector m_EntitiesToKill; std::vector m_EntitiesToDelete; std::vector m_EntitiesToSerialize; @@ -95,7 +95,7 @@ private: float m_GhostDistanceMinSqaured = 100 * 100; float m_GhostDistanceMaxSquared = 150 * 150; bool m_GhostingEnabled = true; - + std::stack m_LostNetworkIds; // Map of spawnname to entity object ID diff --git a/dGame/LeaderboardManager.cpp b/dGame/LeaderboardManager.cpp index 793d402c..71a154bd 100644 --- a/dGame/LeaderboardManager.cpp +++ b/dGame/LeaderboardManager.cpp @@ -9,244 +9,243 @@ #include "dConfig.h" Leaderboard::Leaderboard(uint32_t gameID, uint32_t infoType, bool weekly, std::vector entries, - LWOOBJID relatedPlayer, LeaderboardType leaderboardType) { - this->relatedPlayer = relatedPlayer; - this->gameID = gameID; - this->weekly = weekly; - this->infoType = infoType; - this->entries = std::move(entries); - this->leaderboardType = leaderboardType; + LWOOBJID relatedPlayer, LeaderboardType leaderboardType) { + this->relatedPlayer = relatedPlayer; + this->gameID = gameID; + this->weekly = weekly; + this->infoType = infoType; + this->entries = std::move(entries); + this->leaderboardType = leaderboardType; } std::u16string Leaderboard::ToString() const { - std::string leaderboard; + std::string leaderboard; - leaderboard += "ADO.Result=7:1\n"; - leaderboard += "Result.Count=1:1\n"; - leaderboard += "Result[0].Index=0:RowNumber\n"; - leaderboard += "Result[0].RowCount=1:" + std::to_string(entries.size()) + "\n"; + leaderboard += "ADO.Result=7:1\n"; + leaderboard += "Result.Count=1:1\n"; + leaderboard += "Result[0].Index=0:RowNumber\n"; + leaderboard += "Result[0].RowCount=1:" + std::to_string(entries.size()) + "\n"; - auto index = 0; - for (const auto& entry : entries) { - leaderboard += "Result[0].Row[" + std::to_string(index) + "].LastPlayed=8:" + std::to_string(entry.lastPlayed) + "\n"; - leaderboard += "Result[0].Row[" + std::to_string(index) + "].CharacterID=8:" + std::to_string(entry.playerID) + "\n"; - leaderboard += "Result[0].Row[" + std::to_string(index) + "].NumPlayed=1:1\n"; - leaderboard += "Result[0].Row[" + std::to_string(index) + "].RowNumber=8:" + std::to_string(entry.placement) + "\n"; - leaderboard += "Result[0].Row[" + std::to_string(index) + "].Time=1:" + std::to_string(entry.time) + "\n"; + auto index = 0; + for (const auto& entry : entries) { + leaderboard += "Result[0].Row[" + std::to_string(index) + "].LastPlayed=8:" + std::to_string(entry.lastPlayed) + "\n"; + leaderboard += "Result[0].Row[" + std::to_string(index) + "].CharacterID=8:" + std::to_string(entry.playerID) + "\n"; + leaderboard += "Result[0].Row[" + std::to_string(index) + "].NumPlayed=1:1\n"; + leaderboard += "Result[0].Row[" + std::to_string(index) + "].RowNumber=8:" + std::to_string(entry.placement) + "\n"; + leaderboard += "Result[0].Row[" + std::to_string(index) + "].Time=1:" + std::to_string(entry.time) + "\n"; - // Only these minigames have a points system - if (leaderboardType == Survival || leaderboardType == ShootingGallery) { - leaderboard += "Result[0].Row[" + std::to_string(index) + "].Points=1:" + std::to_string(entry.score) + "\n"; - } else if (leaderboardType == SurvivalNS) { - leaderboard += "Result[0].Row[" + std::to_string(index) + "].Wave=1:" + std::to_string(entry.score) + "\n"; - } + // Only these minigames have a points system + if (leaderboardType == Survival || leaderboardType == ShootingGallery) { + leaderboard += "Result[0].Row[" + std::to_string(index) + "].Points=1:" + std::to_string(entry.score) + "\n"; + } else if (leaderboardType == SurvivalNS) { + leaderboard += "Result[0].Row[" + std::to_string(index) + "].Wave=1:" + std::to_string(entry.score) + "\n"; + } - leaderboard += "Result[0].Row[" + std::to_string(index) + "].name=0:" + entry.playerName + "\n"; - index++; - } + leaderboard += "Result[0].Row[" + std::to_string(index) + "].name=0:" + entry.playerName + "\n"; + index++; + } - return GeneralUtils::ASCIIToUTF16(leaderboard); + return GeneralUtils::ASCIIToUTF16(leaderboard); } std::vector Leaderboard::GetEntries() { - return entries; + return entries; } uint32_t Leaderboard::GetGameID() const { - return gameID; + return gameID; } uint32_t Leaderboard::GetInfoType() const { - return infoType; + return infoType; } void Leaderboard::Send(LWOOBJID targetID) const { - auto* player = EntityManager::Instance()->GetEntity(relatedPlayer); - if (player != nullptr) { - GameMessages::SendActivitySummaryLeaderboardData(targetID, this, player->GetSystemAddress()); - } + auto* player = EntityManager::Instance()->GetEntity(relatedPlayer); + if (player != nullptr) { + GameMessages::SendActivitySummaryLeaderboardData(targetID, this, player->GetSystemAddress()); + } } void LeaderboardManager::SaveScore(LWOOBJID playerID, uint32_t gameID, uint32_t score, uint32_t time) { - const auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - return; + const auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + return; - auto* character = player->GetCharacter(); - if (character == nullptr) - return; + auto* character = player->GetCharacter(); + if (character == nullptr) + return; - auto* select = Database::CreatePreppedStmt("SELECT time, score FROM leaderboard WHERE character_id = ? AND game_id = ?;"); + auto* select = Database::CreatePreppedStmt("SELECT time, score FROM leaderboard WHERE character_id = ? AND game_id = ?;"); - select->setUInt64(1, character->GetID()); - select->setInt(2, gameID); + select->setUInt64(1, character->GetID()); + select->setInt(2, gameID); - auto any = false; - auto* result = select->executeQuery(); - auto leaderboardType = GetLeaderboardType(gameID); + auto any = false; + auto* result = select->executeQuery(); + auto leaderboardType = GetLeaderboardType(gameID); - // Check if the new score is a high score - while (result->next()) { - any = true; + // Check if the new score is a high score + while (result->next()) { + any = true; - const auto storedTime = result->getInt(1); - const auto storedScore = result->getInt(2); - auto highscore = true; - bool classicSurvivalScoring = Game::config->GetValue("classic_survival_scoring") == "1"; + const auto storedTime = result->getInt(1); + const auto storedScore = result->getInt(2); + auto highscore = true; + bool classicSurvivalScoring = Game::config->GetValue("classic_survival_scoring") == "1"; - switch (leaderboardType) { - case ShootingGallery: - if (score <= storedScore) - highscore = false; - break; - case Racing: - if (time >= storedTime) - highscore = false; - break; - case MonumentRace: - if (time >= storedTime) - highscore = false; - break; - case FootRace: - if (time <= storedTime) - highscore = false; - break; - case Survival: - if (classicSurvivalScoring) { - if (time <= storedTime) { // Based on time (LU live) - highscore = false; - } - } - else { - if (score <= storedScore) // Based on score (DLU) - highscore = false; - } - break; - case SurvivalNS: - if (!(score > storedScore || (time < storedTime && score >= storedScore))) - highscore = false; - break; - default: - highscore = false; - } + switch (leaderboardType) { + case ShootingGallery: + if (score <= storedScore) + highscore = false; + break; + case Racing: + if (time >= storedTime) + highscore = false; + break; + case MonumentRace: + if (time >= storedTime) + highscore = false; + break; + case FootRace: + if (time <= storedTime) + highscore = false; + break; + case Survival: + if (classicSurvivalScoring) { + if (time <= storedTime) { // Based on time (LU live) + highscore = false; + } + } else { + if (score <= storedScore) // Based on score (DLU) + highscore = false; + } + break; + case SurvivalNS: + if (!(score > storedScore || (time < storedTime && score >= storedScore))) + highscore = false; + break; + default: + highscore = false; + } - if (!highscore) { - delete select; - delete result; - return; - } - } + if (!highscore) { + delete select; + delete result; + return; + } + } - delete select; - delete result; + delete select; + delete result; - if (any) { - auto* statement = Database::CreatePreppedStmt("UPDATE leaderboard SET time = ?, score = ?, last_played=SYSDATE() WHERE character_id = ? AND game_id = ?;"); - statement->setInt(1, time); - statement->setInt(2, score); - statement->setUInt64(3, character->GetID()); - statement->setInt(4, gameID); - statement->execute(); + if (any) { + auto* statement = Database::CreatePreppedStmt("UPDATE leaderboard SET time = ?, score = ?, last_played=SYSDATE() WHERE character_id = ? AND game_id = ?;"); + statement->setInt(1, time); + statement->setInt(2, score); + statement->setUInt64(3, character->GetID()); + statement->setInt(4, gameID); + statement->execute(); - delete statement; - } else { - // Note: last_played will be set to SYSDATE() by default when inserting into leaderboard - auto* statement = Database::CreatePreppedStmt("INSERT INTO leaderboard (character_id, game_id, time, score) VALUES (?, ?, ?, ?);"); - statement->setUInt64(1, character->GetID()); - statement->setInt(2, gameID); - statement->setInt(3, time); - statement->setInt(4, score); - statement->execute(); + delete statement; + } else { + // Note: last_played will be set to SYSDATE() by default when inserting into leaderboard + auto* statement = Database::CreatePreppedStmt("INSERT INTO leaderboard (character_id, game_id, time, score) VALUES (?, ?, ?, ?);"); + statement->setUInt64(1, character->GetID()); + statement->setInt(2, gameID); + statement->setInt(3, time); + statement->setInt(4, score); + statement->execute(); - delete statement; - } + delete statement; + } } -Leaderboard *LeaderboardManager::GetLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID playerID) { - auto leaderboardType = GetLeaderboardType(gameID); +Leaderboard* LeaderboardManager::GetLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID playerID) { + auto leaderboardType = GetLeaderboardType(gameID); - std::string query; - bool classicSurvivalScoring = Game::config->GetValue("classic_survival_scoring") == "1"; - switch (infoType) { - case InfoType::Standings: - switch (leaderboardType) { - case ShootingGallery: - query = standingsScoreQuery; // Shooting gallery is based on the highest score. - break; - case FootRace: - query = standingsTimeQuery; // The higher your time, the better for FootRace. - break; - case Survival: - query = classicSurvivalScoring ? standingsTimeQuery : standingsScoreQuery; - break; - case SurvivalNS: - query = standingsScoreQueryAsc; // BoNS is scored by highest wave (score) first, then time. - break; - default: - query = standingsTimeQueryAsc; // MonumentRace and Racing are based on the shortest time. - } - break; - case InfoType::Friends: - switch (leaderboardType) { - case ShootingGallery: - query = friendsScoreQuery; // Shooting gallery is based on the highest score. - break; - case FootRace: - query = friendsTimeQuery; // The higher your time, the better for FootRace. - break; - case Survival: - query = classicSurvivalScoring ? friendsTimeQuery : friendsScoreQuery; - break; - case SurvivalNS: - query = friendsScoreQueryAsc; // BoNS is scored by highest wave (score) first, then time. - break; - default: - query = friendsTimeQueryAsc; // MonumentRace and Racing are based on the shortest time. - } - break; + std::string query; + bool classicSurvivalScoring = Game::config->GetValue("classic_survival_scoring") == "1"; + switch (infoType) { + case InfoType::Standings: + switch (leaderboardType) { + case ShootingGallery: + query = standingsScoreQuery; // Shooting gallery is based on the highest score. + break; + case FootRace: + query = standingsTimeQuery; // The higher your time, the better for FootRace. + break; + case Survival: + query = classicSurvivalScoring ? standingsTimeQuery : standingsScoreQuery; + break; + case SurvivalNS: + query = standingsScoreQueryAsc; // BoNS is scored by highest wave (score) first, then time. + break; + default: + query = standingsTimeQueryAsc; // MonumentRace and Racing are based on the shortest time. + } + break; + case InfoType::Friends: + switch (leaderboardType) { + case ShootingGallery: + query = friendsScoreQuery; // Shooting gallery is based on the highest score. + break; + case FootRace: + query = friendsTimeQuery; // The higher your time, the better for FootRace. + break; + case Survival: + query = classicSurvivalScoring ? friendsTimeQuery : friendsScoreQuery; + break; + case SurvivalNS: + query = friendsScoreQueryAsc; // BoNS is scored by highest wave (score) first, then time. + break; + default: + query = friendsTimeQueryAsc; // MonumentRace and Racing are based on the shortest time. + } + break; - default: - switch (leaderboardType) { - case ShootingGallery: - query = topPlayersScoreQuery; // Shooting gallery is based on the highest score. - break; - case FootRace: - query = topPlayersTimeQuery; // The higher your time, the better for FootRace. - break; - case Survival: - query = classicSurvivalScoring ? topPlayersTimeQuery : topPlayersScoreQuery; - break; - case SurvivalNS: - query = topPlayersScoreQueryAsc; // BoNS is scored by highest wave (score) first, then time. - break; - default: - query = topPlayersTimeQueryAsc; // MonumentRace and Racing are based on the shortest time. - } - } + default: + switch (leaderboardType) { + case ShootingGallery: + query = topPlayersScoreQuery; // Shooting gallery is based on the highest score. + break; + case FootRace: + query = topPlayersTimeQuery; // The higher your time, the better for FootRace. + break; + case Survival: + query = classicSurvivalScoring ? topPlayersTimeQuery : topPlayersScoreQuery; + break; + case SurvivalNS: + query = topPlayersScoreQueryAsc; // BoNS is scored by highest wave (score) first, then time. + break; + default: + query = topPlayersTimeQueryAsc; // MonumentRace and Racing are based on the shortest time. + } + } - auto* statement = Database::CreatePreppedStmt(query); - statement->setUInt(1, gameID); + auto* statement = Database::CreatePreppedStmt(query); + statement->setUInt(1, gameID); - // Only the standings and friends leaderboards require the character ID to be set - if (infoType == Standings || infoType == Friends) { - auto characterID = 0; + // Only the standings and friends leaderboards require the character ID to be set + if (infoType == Standings || infoType == Friends) { + auto characterID = 0; - const auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - auto* character = player->GetCharacter(); - if (character != nullptr) - characterID = character->GetID(); - } + const auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + auto* character = player->GetCharacter(); + if (character != nullptr) + characterID = character->GetID(); + } - statement->setUInt64(2, characterID); - } + statement->setUInt64(2, characterID); + } - auto* res = statement->executeQuery(); + auto* res = statement->executeQuery(); - std::vector entries {}; + std::vector entries{}; - uint32_t index = 0; - while (res->next()) { + uint32_t index = 0; + while (res->next()) { LeaderboardEntry entry; entry.playerID = res->getUInt64(4); entry.playerName = res->getString(5); @@ -256,124 +255,124 @@ Leaderboard *LeaderboardManager::GetLeaderboard(uint32_t gameID, InfoType infoTy entry.lastPlayed = res->getUInt(6); entries.push_back(entry); - index++; - } + index++; + } - delete res; - delete statement; + delete res; + delete statement; - return new Leaderboard(gameID, infoType, weekly, entries, playerID, leaderboardType); + return new Leaderboard(gameID, infoType, weekly, entries, playerID, leaderboardType); } void LeaderboardManager::SendLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID targetID, - LWOOBJID playerID) { - const auto* leaderboard = LeaderboardManager::GetLeaderboard(gameID, infoType, weekly, playerID); - leaderboard->Send(targetID); - delete leaderboard; + LWOOBJID playerID) { + const auto* leaderboard = LeaderboardManager::GetLeaderboard(gameID, infoType, weekly, playerID); + leaderboard->Send(targetID); + delete leaderboard; } LeaderboardType LeaderboardManager::GetLeaderboardType(uint32_t gameID) { - auto* activitiesTable = CDClientManager::Instance()->GetTable("Activities"); - std::vector activities = activitiesTable->Query([=](const CDActivities& entry) { - return (entry.ActivityID == gameID); - }); + auto* activitiesTable = CDClientManager::Instance()->GetTable("Activities"); + std::vector activities = activitiesTable->Query([=](const CDActivities& entry) { + return (entry.ActivityID == gameID); + }); - for (const auto& activity : activities) { - return static_cast(activity.leaderboardType); - } + for (const auto& activity : activities) { + return static_cast(activity.leaderboardType); + } - return LeaderboardType::None; + return LeaderboardType::None; } const std::string LeaderboardManager::topPlayersScoreQuery = - "WITH leaderboard_vales AS ( " - " SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " - "RANK() OVER ( ORDER BY l.score DESC, l.time DESC, last_played ) leaderboard_rank " - " FROM leaderboard l " - "INNER JOIN charinfo c ON l.character_id = c.id " - "WHERE l.game_id = ? " - "ORDER BY leaderboard_rank) " - "SELECT time, score, leaderboard_rank, id, name, last_played " - "FROM leaderboard_vales LIMIT 11;"; +"WITH leaderboard_vales AS ( " +" SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " +"RANK() OVER ( ORDER BY l.score DESC, l.time DESC, last_played ) leaderboard_rank " +" FROM leaderboard l " +"INNER JOIN charinfo c ON l.character_id = c.id " +"WHERE l.game_id = ? " +"ORDER BY leaderboard_rank) " +"SELECT time, score, leaderboard_rank, id, name, last_played " +"FROM leaderboard_vales LIMIT 11;"; const std::string LeaderboardManager::friendsScoreQuery = - "WITH leaderboard_vales AS ( " - " SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, f.friend_id, f.player_id, " - " RANK() OVER ( ORDER BY l.score DESC, l.time DESC, last_played ) leaderboard_rank " - " FROM leaderboard l " - " INNER JOIN charinfo c ON l.character_id = c.id " - " INNER JOIN friends f ON f.player_id = c.id " - " WHERE l.game_id = ? " - " ORDER BY leaderboard_rank), " - " personal_values AS ( " - " SELECT id as related_player_id, " - " GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " - " GREATEST(leaderboard_rank + 5, 11) AS max_rank " - " FROM leaderboard_vales WHERE leaderboard_vales.id = ? LIMIT 1) " - "SELECT time, score, leaderboard_rank, id, name, last_played " - "FROM leaderboard_vales, personal_values " - "WHERE leaderboard_rank BETWEEN min_rank AND max_rank AND (player_id = related_player_id OR friend_id = related_player_id);"; +"WITH leaderboard_vales AS ( " +" SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, f.friend_id, f.player_id, " +" RANK() OVER ( ORDER BY l.score DESC, l.time DESC, last_played ) leaderboard_rank " +" FROM leaderboard l " +" INNER JOIN charinfo c ON l.character_id = c.id " +" INNER JOIN friends f ON f.player_id = c.id " +" WHERE l.game_id = ? " +" ORDER BY leaderboard_rank), " +" personal_values AS ( " +" SELECT id as related_player_id, " +" GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " +" GREATEST(leaderboard_rank + 5, 11) AS max_rank " +" FROM leaderboard_vales WHERE leaderboard_vales.id = ? LIMIT 1) " +"SELECT time, score, leaderboard_rank, id, name, last_played " +"FROM leaderboard_vales, personal_values " +"WHERE leaderboard_rank BETWEEN min_rank AND max_rank AND (player_id = related_player_id OR friend_id = related_player_id);"; const std::string LeaderboardManager::standingsScoreQuery = - "WITH leaderboard_vales AS ( " - " SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " - " RANK() OVER ( ORDER BY l.score DESC, l.time DESC, last_played ) leaderboard_rank " - " FROM leaderboard l " - " INNER JOIN charinfo c ON l.character_id = c.id " - " WHERE l.game_id = ? " - " ORDER BY leaderboard_rank), " - "personal_values AS ( " - " SELECT GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " - " GREATEST(leaderboard_rank + 5, 11) AS max_rank " - " FROM leaderboard_vales WHERE id = ? LIMIT 1) " - "SELECT time, score, leaderboard_rank, id, name, last_played " - "FROM leaderboard_vales, personal_values " - "WHERE leaderboard_rank BETWEEN min_rank AND max_rank;"; +"WITH leaderboard_vales AS ( " +" SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " +" RANK() OVER ( ORDER BY l.score DESC, l.time DESC, last_played ) leaderboard_rank " +" FROM leaderboard l " +" INNER JOIN charinfo c ON l.character_id = c.id " +" WHERE l.game_id = ? " +" ORDER BY leaderboard_rank), " +"personal_values AS ( " +" SELECT GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " +" GREATEST(leaderboard_rank + 5, 11) AS max_rank " +" FROM leaderboard_vales WHERE id = ? LIMIT 1) " +"SELECT time, score, leaderboard_rank, id, name, last_played " +"FROM leaderboard_vales, personal_values " +"WHERE leaderboard_rank BETWEEN min_rank AND max_rank;"; const std::string LeaderboardManager::topPlayersScoreQueryAsc = - "WITH leaderboard_vales AS ( " - " SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " - "RANK() OVER ( ORDER BY l.score DESC, l.time ASC, last_played ) leaderboard_rank " - " FROM leaderboard l " - "INNER JOIN charinfo c ON l.character_id = c.id " - "WHERE l.game_id = ? " - "ORDER BY leaderboard_rank) " - "SELECT time, score, leaderboard_rank, id, name, last_played " - "FROM leaderboard_vales LIMIT 11;"; +"WITH leaderboard_vales AS ( " +" SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " +"RANK() OVER ( ORDER BY l.score DESC, l.time ASC, last_played ) leaderboard_rank " +" FROM leaderboard l " +"INNER JOIN charinfo c ON l.character_id = c.id " +"WHERE l.game_id = ? " +"ORDER BY leaderboard_rank) " +"SELECT time, score, leaderboard_rank, id, name, last_played " +"FROM leaderboard_vales LIMIT 11;"; const std::string LeaderboardManager::friendsScoreQueryAsc = - "WITH leaderboard_vales AS ( " - " SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, f.friend_id, f.player_id, " - " RANK() OVER ( ORDER BY l.score DESC, l.time ASC, last_played ) leaderboard_rank " - " FROM leaderboard l " - " INNER JOIN charinfo c ON l.character_id = c.id " - " INNER JOIN friends f ON f.player_id = c.id " - " WHERE l.game_id = ? " - " ORDER BY leaderboard_rank), " - " personal_values AS ( " - " SELECT id as related_player_id, " - " GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " - " GREATEST(leaderboard_rank + 5, 11) AS max_rank " - " FROM leaderboard_vales WHERE leaderboard_vales.id = ? LIMIT 1) " - "SELECT time, score, leaderboard_rank, id, name, last_played " - "FROM leaderboard_vales, personal_values " - "WHERE leaderboard_rank BETWEEN min_rank AND max_rank AND (player_id = related_player_id OR friend_id = related_player_id);"; +"WITH leaderboard_vales AS ( " +" SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, f.friend_id, f.player_id, " +" RANK() OVER ( ORDER BY l.score DESC, l.time ASC, last_played ) leaderboard_rank " +" FROM leaderboard l " +" INNER JOIN charinfo c ON l.character_id = c.id " +" INNER JOIN friends f ON f.player_id = c.id " +" WHERE l.game_id = ? " +" ORDER BY leaderboard_rank), " +" personal_values AS ( " +" SELECT id as related_player_id, " +" GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " +" GREATEST(leaderboard_rank + 5, 11) AS max_rank " +" FROM leaderboard_vales WHERE leaderboard_vales.id = ? LIMIT 1) " +"SELECT time, score, leaderboard_rank, id, name, last_played " +"FROM leaderboard_vales, personal_values " +"WHERE leaderboard_rank BETWEEN min_rank AND max_rank AND (player_id = related_player_id OR friend_id = related_player_id);"; const std::string LeaderboardManager::standingsScoreQueryAsc = - "WITH leaderboard_vales AS ( " - " SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " - " RANK() OVER ( ORDER BY l.score DESC, l.time ASC, last_played ) leaderboard_rank " - " FROM leaderboard l " - " INNER JOIN charinfo c ON l.character_id = c.id " - " WHERE l.game_id = ? " - " ORDER BY leaderboard_rank), " - "personal_values AS ( " - " SELECT GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " - " GREATEST(leaderboard_rank + 5, 11) AS max_rank " - " FROM leaderboard_vales WHERE id = ? LIMIT 1) " - "SELECT time, score, leaderboard_rank, id, name, last_played " - "FROM leaderboard_vales, personal_values " - "WHERE leaderboard_rank BETWEEN min_rank AND max_rank;"; +"WITH leaderboard_vales AS ( " +" SELECT l.time, l.score, UNIX_TIMESTAMP(l.last_played) last_played, c.name, c.id, " +" RANK() OVER ( ORDER BY l.score DESC, l.time ASC, last_played ) leaderboard_rank " +" FROM leaderboard l " +" INNER JOIN charinfo c ON l.character_id = c.id " +" WHERE l.game_id = ? " +" ORDER BY leaderboard_rank), " +"personal_values AS ( " +" SELECT GREATEST(CAST(leaderboard_rank AS SIGNED) - 5, 1) AS min_rank, " +" GREATEST(leaderboard_rank + 5, 11) AS max_rank " +" FROM leaderboard_vales WHERE id = ? LIMIT 1) " +"SELECT time, score, leaderboard_rank, id, name, last_played " +"FROM leaderboard_vales, personal_values " +"WHERE leaderboard_rank BETWEEN min_rank AND max_rank;"; const std::string LeaderboardManager::topPlayersTimeQuery = "WITH leaderboard_vales AS ( " diff --git a/dGame/LeaderboardManager.h b/dGame/LeaderboardManager.h index c4479f1a..cabdf2d6 100644 --- a/dGame/LeaderboardManager.h +++ b/dGame/LeaderboardManager.h @@ -4,77 +4,77 @@ #include "dCommonVars.h" struct LeaderboardEntry { - uint64_t playerID; - std::string playerName; - uint32_t time; - uint32_t score; - uint32_t placement; - time_t lastPlayed; + uint64_t playerID; + std::string playerName; + uint32_t time; + uint32_t score; + uint32_t placement; + time_t lastPlayed; }; enum InfoType : uint32_t { - Top, // Top 11 all time players - Standings, // Ranking of the current player - Friends // Ranking between friends + Top, // Top 11 all time players + Standings, // Ranking of the current player + Friends // Ranking between friends }; enum LeaderboardType : uint32_t { - ShootingGallery, - Racing, - MonumentRace, - FootRace, - Survival = 5, - SurvivalNS = 6, - None = UINT_MAX + ShootingGallery, + Racing, + MonumentRace, + FootRace, + Survival = 5, + SurvivalNS = 6, + None = UINT_MAX }; class Leaderboard { public: - Leaderboard(uint32_t gameID, uint32_t infoType, bool weekly, std::vector entries, - LWOOBJID relatedPlayer = LWOOBJID_EMPTY, LeaderboardType = None); - std::vector GetEntries(); - [[nodiscard]] std::u16string ToString() const; - [[nodiscard]] uint32_t GetGameID() const; - [[nodiscard]] uint32_t GetInfoType() const; - void Send(LWOOBJID targetID) const; + Leaderboard(uint32_t gameID, uint32_t infoType, bool weekly, std::vector entries, + LWOOBJID relatedPlayer = LWOOBJID_EMPTY, LeaderboardType = None); + std::vector GetEntries(); + [[nodiscard]] std::u16string ToString() const; + [[nodiscard]] uint32_t GetGameID() const; + [[nodiscard]] uint32_t GetInfoType() const; + void Send(LWOOBJID targetID) const; private: - std::vector entries {}; - LWOOBJID relatedPlayer; - uint32_t gameID; - uint32_t infoType; - LeaderboardType leaderboardType; - bool weekly; + std::vector entries{}; + LWOOBJID relatedPlayer; + uint32_t gameID; + uint32_t infoType; + LeaderboardType leaderboardType; + bool weekly; }; class LeaderboardManager { public: - static LeaderboardManager* Instance() { - if (address == nullptr) - address = new LeaderboardManager; - return address; - } - static void SendLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID targetID, - LWOOBJID playerID = LWOOBJID_EMPTY); - static Leaderboard* GetLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID playerID = LWOOBJID_EMPTY); - static void SaveScore(LWOOBJID playerID, uint32_t gameID, uint32_t score, uint32_t time); - static LeaderboardType GetLeaderboardType(uint32_t gameID); + static LeaderboardManager* Instance() { + if (address == nullptr) + address = new LeaderboardManager; + return address; + } + static void SendLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID targetID, + LWOOBJID playerID = LWOOBJID_EMPTY); + static Leaderboard* GetLeaderboard(uint32_t gameID, InfoType infoType, bool weekly, LWOOBJID playerID = LWOOBJID_EMPTY); + static void SaveScore(LWOOBJID playerID, uint32_t gameID, uint32_t score, uint32_t time); + static LeaderboardType GetLeaderboardType(uint32_t gameID); private: - static LeaderboardManager* address; + static LeaderboardManager* address; - // Modified 12/12/2021: Existing queries were renamed to be more descriptive. - static const std::string topPlayersScoreQuery; - static const std::string friendsScoreQuery; - static const std::string standingsScoreQuery; - static const std::string topPlayersScoreQueryAsc; - static const std::string friendsScoreQueryAsc; - static const std::string standingsScoreQueryAsc; + // Modified 12/12/2021: Existing queries were renamed to be more descriptive. + static const std::string topPlayersScoreQuery; + static const std::string friendsScoreQuery; + static const std::string standingsScoreQuery; + static const std::string topPlayersScoreQueryAsc; + static const std::string friendsScoreQueryAsc; + static const std::string standingsScoreQueryAsc; - // Added 12/12/2021: Queries dictated by time are needed for certain minigames. - static const std::string topPlayersTimeQuery; - static const std::string friendsTimeQuery; - static const std::string standingsTimeQuery; - static const std::string topPlayersTimeQueryAsc; - static const std::string friendsTimeQueryAsc; - static const std::string standingsTimeQueryAsc; + // Added 12/12/2021: Queries dictated by time are needed for certain minigames. + static const std::string topPlayersTimeQuery; + static const std::string friendsTimeQuery; + static const std::string standingsTimeQuery; + static const std::string topPlayersTimeQueryAsc; + static const std::string friendsTimeQueryAsc; + static const std::string standingsTimeQueryAsc; }; diff --git a/dGame/Player.cpp b/dGame/Player.cpp index 56ae5a70..dd269f95 100644 --- a/dGame/Player.cpp +++ b/dGame/Player.cpp @@ -17,8 +17,7 @@ std::vector Player::m_Players = {}; -Player::Player(const LWOOBJID& objectID, const EntityInfo info, User* user, Entity* parentEntity) : Entity(objectID, info, parentEntity) -{ +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); @@ -38,58 +37,48 @@ Player::Player(const LWOOBJID& objectID, const EntityInfo info, User* user, Enti const auto& iter = std::find(m_Players.begin(), m_Players.end(), this); - if (iter != m_Players.end()) - { + if (iter != m_Players.end()) { return; } m_Players.push_back(this); } -User* Player::GetParentUser() const -{ +User* Player::GetParentUser() const { return m_ParentUser; } -SystemAddress Player::GetSystemAddress() const -{ +SystemAddress Player::GetSystemAddress() const { return m_SystemAddress; } -void Player::SetSystemAddress(const SystemAddress& value) -{ +void Player::SetSystemAddress(const SystemAddress& value) { m_SystemAddress = value; } -void Player::SetRespawnPos(const NiPoint3 position) -{ +void Player::SetRespawnPos(const NiPoint3 position) { m_respawnPos = position; m_Character->SetRespawnPoint(dZoneManager::Instance()->GetZone()->GetWorldID(), position); } -void Player::SetRespawnRot(const NiQuaternion rotation) -{ +void Player::SetRespawnRot(const NiQuaternion rotation) { m_respawnRot = rotation; } -NiPoint3 Player::GetRespawnPosition() const -{ +NiPoint3 Player::GetRespawnPosition() const { return m_respawnPos; } -NiQuaternion Player::GetRespawnRotation() const -{ +NiQuaternion Player::GetRespawnRotation() const { return m_respawnRot; } -void Player::SendMail(const LWOOBJID sender, const std::string& senderName, const std::string& subject, const std::string& body, LOT attachment, uint16_t attachmentCount) const -{ +void Player::SendMail(const LWOOBJID sender, const std::string& senderName, const std::string& subject, const std::string& body, LOT attachment, uint16_t attachmentCount) const { Mail::SendMail(sender, senderName, this, subject, body, attachment, attachmentCount); } -void Player::SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId) -{ +void Player::SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId) { const auto objid = GetObjectID(); ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, zoneId, cloneId, false, [objid](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { @@ -118,41 +107,34 @@ void Player::SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId) EntityManager::Instance()->DestructEntity(entity); return; - }); + }); } -void Player::AddLimboConstruction(LWOOBJID objectId) -{ +void Player::AddLimboConstruction(LWOOBJID objectId) { const auto& iter = std::find(m_LimboConstructions.begin(), m_LimboConstructions.end(), objectId); - if (iter != m_LimboConstructions.end()) - { + if (iter != m_LimboConstructions.end()) { return; } m_LimboConstructions.push_back(objectId); } -void Player::RemoveLimboConstruction(LWOOBJID objectId) -{ +void Player::RemoveLimboConstruction(LWOOBJID objectId) { const auto& iter = std::find(m_LimboConstructions.begin(), m_LimboConstructions.end(), objectId); - if (iter == m_LimboConstructions.end()) - { + if (iter == m_LimboConstructions.end()) { return; } m_LimboConstructions.erase(iter); } -void Player::ConstructLimboEntities() -{ - for (const auto objectId : m_LimboConstructions) - { +void Player::ConstructLimboEntities() { + for (const auto objectId : m_LimboConstructions) { auto* entity = EntityManager::Instance()->GetEntity(objectId); - if (entity == nullptr) - { + if (entity == nullptr) { continue; } @@ -162,52 +144,41 @@ void Player::ConstructLimboEntities() m_LimboConstructions.clear(); } -std::map& Player::GetDroppedLoot() -{ +std::map& Player::GetDroppedLoot() { return m_DroppedLoot; } -const NiPoint3& Player::GetGhostReferencePoint() const -{ +const NiPoint3& Player::GetGhostReferencePoint() const { return m_GhostOverride ? m_GhostOverridePoint : m_GhostReferencePoint; } -const NiPoint3& Player::GetOriginGhostReferencePoint() const -{ +const NiPoint3& Player::GetOriginGhostReferencePoint() const { return m_GhostReferencePoint; } -void Player::SetGhostReferencePoint(const NiPoint3& value) -{ +void Player::SetGhostReferencePoint(const NiPoint3& value) { m_GhostReferencePoint = value; } -void Player::SetGhostOverridePoint(const NiPoint3& value) -{ +void Player::SetGhostOverridePoint(const NiPoint3& value) { m_GhostOverridePoint = value; } -const NiPoint3& Player::GetGhostOverridePoint() const -{ +const NiPoint3& Player::GetGhostOverridePoint() const { return m_GhostOverridePoint; } -void Player::SetGhostOverride(bool value) -{ +void Player::SetGhostOverride(bool value) { m_GhostOverride = value; } -bool Player::GetGhostOverride() const -{ +bool Player::GetGhostOverride() const { return m_GhostOverride; } -void Player::ObserveEntity(int32_t id) -{ - for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) - { - if (m_ObservedEntities[i] == 0 || m_ObservedEntities[i] == id) - { +void Player::ObserveEntity(int32_t id) { + for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { + if (m_ObservedEntities[i] == 0 || m_ObservedEntities[i] == id) { m_ObservedEntities[i] = id; return; @@ -216,8 +187,7 @@ void Player::ObserveEntity(int32_t id) const auto index = m_ObservedEntitiesUsed++; - if (m_ObservedEntitiesUsed > m_ObservedEntitiesLength) - { + if (m_ObservedEntitiesUsed > m_ObservedEntitiesLength) { m_ObservedEntities.resize(m_ObservedEntitiesLength + m_ObservedEntitiesLength); m_ObservedEntitiesLength = m_ObservedEntitiesLength + m_ObservedEntitiesLength; @@ -226,12 +196,9 @@ void Player::ObserveEntity(int32_t id) m_ObservedEntities[index] = id; } -bool Player::IsObserved(int32_t id) -{ - for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) - { - if (m_ObservedEntities[i] == id) - { +bool Player::IsObserved(int32_t id) { + for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { + if (m_ObservedEntities[i] == id) { return true; } } @@ -239,34 +206,27 @@ bool Player::IsObserved(int32_t id) return false; } -void Player::GhostEntity(int32_t id) -{ - for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) - { - if (m_ObservedEntities[i] == id) - { +void Player::GhostEntity(int32_t id) { + for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { + if (m_ObservedEntities[i] == id) { m_ObservedEntities[i] = 0; } } } -Player* Player::GetPlayer(const SystemAddress& sysAddr) -{ +Player* Player::GetPlayer(const SystemAddress& sysAddr) { auto* entity = UserManager::Instance()->GetUser(sysAddr)->GetLastUsedChar()->GetEntity(); return static_cast(entity); } -Player* Player::GetPlayer(const std::string& name) -{ +Player* Player::GetPlayer(const std::string& name) { const auto characters = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER); - for (auto* character : characters) - { + for (auto* character : characters) { if (!character->IsPlayer()) continue; - if (character->GetCharacter()->GetName() == name) - { + if (character->GetCharacter()->GetName() == name) { return static_cast(character); } } @@ -274,12 +234,9 @@ Player* Player::GetPlayer(const std::string& name) return nullptr; } -Player* Player::GetPlayer(LWOOBJID playerID) -{ - for (auto* player : m_Players) - { - if (player->GetObjectID() == playerID) - { +Player* Player::GetPlayer(LWOOBJID playerID) { + for (auto* player : m_Players) { + if (player->GetObjectID() == playerID) { return player; } } @@ -287,8 +244,7 @@ Player* Player::GetPlayer(LWOOBJID playerID) return nullptr; } -const std::vector& Player::GetAllPlayers() -{ +const std::vector& Player::GetAllPlayers() { return m_Players; } @@ -300,23 +256,19 @@ void Player::SetDroppedCoins(uint64_t value) { m_DroppedCoins = value; } -Player::~Player() -{ +Player::~Player() { Game::logger->Log("Player", "Deleted player"); - for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) - { + for (int32_t i = 0; i < m_ObservedEntitiesUsed; i++) { const auto id = m_ObservedEntities[i]; - if (id == 0) - { + if (id == 0) { continue; } auto* entity = EntityManager::Instance()->GetGhostCandidate(id); - if (entity != nullptr) - { + if (entity != nullptr) { entity->SetObservers(entity->GetObservers() - 1); } } @@ -325,25 +277,24 @@ Player::~Player() const auto& iter = std::find(m_Players.begin(), m_Players.end(), this); - if (iter == m_Players.end()) - { + if (iter == m_Players.end()) { return; } if (IsPlayer()) { - Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerExit(zoneControl, this); - } + Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { + script->OnPlayerExit(zoneControl, this); + } - std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_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); - } - } - } + std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_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); + } + } + } } m_Players.erase(iter); diff --git a/dGame/Player.h b/dGame/Player.h index bba01363..caad5361 100644 --- a/dGame/Player.h +++ b/dGame/Player.h @@ -4,26 +4,26 @@ /** * 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; - + SystemAddress GetSystemAddress() const override; - + NiPoint3 GetRespawnPosition() const override; - + NiQuaternion GetRespawnRotation() const override; const NiPoint3& GetGhostReferencePoint() const; @@ -41,11 +41,11 @@ public: /** * Setters */ - + void SetSystemAddress(const SystemAddress& value) override; - + void SetRespawnPos(NiPoint3 position) override; - + void SetRespawnRot(NiQuaternion rotation) override; void SetGhostReferencePoint(const NiPoint3& value); @@ -58,7 +58,7 @@ public: /** * Wrapper for sending an in-game mail. - * + * * @param sender id of the sender. LWOOBJID_EMPTY for system mail * @param senderName name of the sender. Max 32 characters. * @param subject mail subject. Max 50 characters. @@ -67,10 +67,10 @@ public: * @param attachmentCount stack size for attachment. */ void SendMail(LWOOBJID sender, const std::string& senderName, const std::string& subject, const std::string& body, LOT attachment, uint16_t attachmentCount) const; - + /** * Wrapper for transfering the player to another instance. - * + * * @param zoneId zoneID for the new instance. * @param cloneId cloneID for the new instance. */ @@ -81,7 +81,7 @@ public: */ void AddLimboConstruction(LWOOBJID objectId); - + void RemoveLimboConstruction(LWOOBJID objectId); void ConstructLimboEntities(); @@ -99,19 +99,19 @@ public: static Player* GetPlayer(const SystemAddress& sysAddr); static Player* GetPlayer(const std::string& name); - + static Player* GetPlayer(LWOOBJID playerID); static const std::vector& GetAllPlayers(); - + ~Player() override; private: SystemAddress m_SystemAddress; - + NiPoint3 m_respawnPos; - + NiQuaternion m_respawnRot; - + User* m_ParentUser; NiPoint3 m_GhostReferencePoint; @@ -121,7 +121,7 @@ private: bool m_GhostOverride; std::vector m_ObservedEntities; - + int32_t m_ObservedEntitiesLength; int32_t m_ObservedEntitiesUsed; diff --git a/dGame/TeamManager.cpp b/dGame/TeamManager.cpp index 8836dd8d..0258ce3e 100644 --- a/dGame/TeamManager.cpp +++ b/dGame/TeamManager.cpp @@ -3,74 +3,60 @@ TeamManager* TeamManager::m_Address = nullptr; //For singleton method -TeamManager::TeamManager() -{ +TeamManager::TeamManager() { } -Team* TeamManager::GetTeam(LWOOBJID member) const -{ - for (const auto& pair : m_Teams) - { - for (const auto memberId : pair.second->members) - { - if (memberId == member) - { - return pair.second; - } - } - } - - return nullptr; +Team* TeamManager::GetTeam(LWOOBJID member) const { + for (const auto& pair : m_Teams) { + for (const auto memberId : pair.second->members) { + if (memberId == member) { + return pair.second; + } + } + } + + return nullptr; } -LWOOBJID TeamManager::GetNextLootOwner(Team* team) const -{ - team->lootRound++; +LWOOBJID TeamManager::GetNextLootOwner(Team* team) const { + team->lootRound++; - if (team->lootRound >= team->members.size()) - { - team->lootRound = 0; - } + if (team->lootRound >= team->members.size()) { + team->lootRound = 0; + } - return team->members[team->lootRound]; + return team->members[team->lootRound]; } -void TeamManager::UpdateTeam(LWOOBJID teamId, char lootOption, const std::vector& members) -{ - const auto& pair = m_Teams.find(teamId); +void TeamManager::UpdateTeam(LWOOBJID teamId, char lootOption, const std::vector& members) { + const auto& pair = m_Teams.find(teamId); - Team* team; + Team* team; - if (pair == m_Teams.end()) - { - if (members.size() <= 1) - { - return; - } + if (pair == m_Teams.end()) { + if (members.size() <= 1) { + return; + } - team = new Team(); - m_Teams[teamId] = team; - } - else - { - team = pair->second; - } + team = new Team(); + m_Teams[teamId] = team; + } else { + team = pair->second; + } - team->members = members; - team->lootOption = lootOption; + team->members = members; + team->lootOption = lootOption; } -void TeamManager::DeleteTeam(LWOOBJID teamId) -{ - const auto& pair = m_Teams.find(teamId); +void TeamManager::DeleteTeam(LWOOBJID teamId) { + const auto& pair = m_Teams.find(teamId); - if (pair == m_Teams.end()) return; + if (pair == m_Teams.end()) return; - delete pair->second; + delete pair->second; - m_Teams.erase(teamId); + m_Teams.erase(teamId); } -TeamManager::~TeamManager() -{ +TeamManager::~TeamManager() { } diff --git a/dGame/TeamManager.h b/dGame/TeamManager.h index ffab3764..eb1b5c5b 100644 --- a/dGame/TeamManager.h +++ b/dGame/TeamManager.h @@ -6,18 +6,18 @@ struct Team { LWOOBJID teamID = LWOOBJID_EMPTY; char lootOption = 0; - std::vector members {}; + std::vector members{}; char lootRound = 0; }; class TeamManager { public: - static TeamManager* Instance() { + static TeamManager* Instance() { if (!m_Address) { m_Address = new TeamManager(); } - + return m_Address; } @@ -26,11 +26,11 @@ public: void UpdateTeam(LWOOBJID teamId, char lootOption, const std::vector& members); void DeleteTeam(LWOOBJID teamId); - explicit TeamManager(); - ~TeamManager(); + explicit TeamManager(); + ~TeamManager(); private: - static TeamManager* m_Address; //For singleton method - std::unordered_map m_Teams {}; + static TeamManager* m_Address; //For singleton method + std::unordered_map m_Teams{}; }; diff --git a/dGame/TradingManager.cpp b/dGame/TradingManager.cpp index 1d23126a..e49cca70 100644 --- a/dGame/TradingManager.cpp +++ b/dGame/TradingManager.cpp @@ -12,297 +12,246 @@ TradingManager* TradingManager::m_Address = nullptr; -Trade::Trade(LWOOBJID tradeId, LWOOBJID participantA, LWOOBJID participantB) -{ - m_TradeId = tradeId; - m_ParticipantA = participantA; - m_ParticipantB = participantB; +Trade::Trade(LWOOBJID tradeId, LWOOBJID participantA, LWOOBJID participantB) { + m_TradeId = tradeId; + m_ParticipantA = participantA; + m_ParticipantB = participantB; } -Trade::~Trade() -{ +Trade::~Trade() { } -LWOOBJID Trade::GetTradeId() const -{ - return m_TradeId; +LWOOBJID Trade::GetTradeId() const { + return m_TradeId; } -bool Trade::IsParticipant(LWOOBJID playerId) const -{ - return m_ParticipantA == playerId || m_ParticipantB == playerId; +bool Trade::IsParticipant(LWOOBJID playerId) const { + return m_ParticipantA == playerId || m_ParticipantB == playerId; } -LWOOBJID Trade::GetParticipantA() const -{ - return m_ParticipantA; +LWOOBJID Trade::GetParticipantA() const { + return m_ParticipantA; } -LWOOBJID Trade::GetParticipantB() const -{ - return m_ParticipantB; +LWOOBJID Trade::GetParticipantB() const { + return m_ParticipantB; } -Entity* Trade::GetParticipantAEntity() const -{ - return EntityManager::Instance()->GetEntity(m_ParticipantA); +Entity* Trade::GetParticipantAEntity() const { + return EntityManager::Instance()->GetEntity(m_ParticipantA); } -Entity* Trade::GetParticipantBEntity() const -{ - return EntityManager::Instance()->GetEntity(m_ParticipantB); +Entity* Trade::GetParticipantBEntity() const { + return EntityManager::Instance()->GetEntity(m_ParticipantB); } -void Trade::SetCoins(LWOOBJID participant, uint64_t coins) -{ - if (participant == m_ParticipantA) - { - m_CoinsA = coins; - } - else if (participant == m_ParticipantB) - { - m_CoinsB = coins; - } +void Trade::SetCoins(LWOOBJID participant, uint64_t coins) { + if (participant == m_ParticipantA) { + m_CoinsA = coins; + } else if (participant == m_ParticipantB) { + m_CoinsB = coins; + } } -void Trade::SetItems(LWOOBJID participant, std::vector items) -{ - if (participant == m_ParticipantA) - { - m_ItemsA = items; - } - else if (participant == m_ParticipantB) - { - m_ItemsB = items; - } +void Trade::SetItems(LWOOBJID participant, std::vector items) { + if (participant == m_ParticipantA) { + m_ItemsA = items; + } else if (participant == m_ParticipantB) { + m_ItemsB = items; + } } -void Trade::SetAccepted(LWOOBJID participant, bool value) -{ - if (participant == m_ParticipantA) - { - m_AcceptedA = !value; +void Trade::SetAccepted(LWOOBJID participant, bool value) { + if (participant == m_ParticipantA) { + m_AcceptedA = !value; - Game::logger->Log("Trade", "Accepted from A (%d), B: (%d)", value, m_AcceptedB); + Game::logger->Log("Trade", "Accepted from A (%d), B: (%d)", value, m_AcceptedB); - auto* entityB = GetParticipantBEntity(); + auto* entityB = GetParticipantBEntity(); - if (entityB != nullptr) - { - GameMessages::SendServerTradeAccept(m_ParticipantB, value, entityB->GetSystemAddress()); - } - } - else if (participant == m_ParticipantB) - { - m_AcceptedB = !value; + if (entityB != nullptr) { + GameMessages::SendServerTradeAccept(m_ParticipantB, value, entityB->GetSystemAddress()); + } + } else if (participant == m_ParticipantB) { + m_AcceptedB = !value; - Game::logger->Log("Trade", "Accepted from B (%d), A: (%d)", value, m_AcceptedA); + Game::logger->Log("Trade", "Accepted from B (%d), A: (%d)", value, m_AcceptedA); - auto* entityA = GetParticipantAEntity(); + auto* entityA = GetParticipantAEntity(); - if (entityA != nullptr) - { - GameMessages::SendServerTradeAccept(m_ParticipantA, value, entityA->GetSystemAddress()); - } - } + if (entityA != nullptr) { + GameMessages::SendServerTradeAccept(m_ParticipantA, value, entityA->GetSystemAddress()); + } + } - if (m_AcceptedA && m_AcceptedB) - { - auto* entityB = GetParticipantBEntity(); + if (m_AcceptedA && m_AcceptedB) { + auto* entityB = GetParticipantBEntity(); - if (entityB != nullptr) - { - GameMessages::SendServerTradeAccept(m_ParticipantB, false, entityB->GetSystemAddress()); - } - else - { - return; - } + if (entityB != nullptr) { + GameMessages::SendServerTradeAccept(m_ParticipantB, false, entityB->GetSystemAddress()); + } else { + return; + } - auto* entityA = GetParticipantAEntity(); + auto* entityA = GetParticipantAEntity(); - if (entityA != nullptr) - { - GameMessages::SendServerTradeAccept(m_ParticipantA, false, entityA->GetSystemAddress()); - } - else - { - return; - } + if (entityA != nullptr) { + GameMessages::SendServerTradeAccept(m_ParticipantA, false, entityA->GetSystemAddress()); + } else { + return; + } - Complete(); - } + Complete(); + } } -void Trade::Complete() -{ - auto* entityA = GetParticipantAEntity(); - auto* entityB = GetParticipantBEntity(); +void Trade::Complete() { + auto* entityA = GetParticipantAEntity(); + auto* entityB = GetParticipantBEntity(); - if (entityA == nullptr || entityB == nullptr) return; + if (entityA == nullptr || entityB == nullptr) return; - auto* inventoryA = entityA->GetComponent(); - auto* inventoryB = entityB->GetComponent(); - auto* missionsA = entityA->GetComponent(); - auto* missionsB = entityB->GetComponent(); - auto* characterA = entityA->GetCharacter(); - auto* characterB = entityB->GetCharacter(); + auto* inventoryA = entityA->GetComponent(); + auto* inventoryB = entityB->GetComponent(); + auto* missionsA = entityA->GetComponent(); + auto* missionsB = entityB->GetComponent(); + auto* characterA = entityA->GetCharacter(); + auto* characterB = entityB->GetCharacter(); - if (inventoryA == nullptr || inventoryB == nullptr || characterA == nullptr || characterB == nullptr || missionsA == nullptr || missionsB == nullptr) return; + if (inventoryA == nullptr || inventoryB == nullptr || characterA == nullptr || characterB == nullptr || missionsA == nullptr || missionsB == nullptr) return; - characterA->SetCoins(characterA->GetCoins() - m_CoinsA + m_CoinsB, eLootSourceType::LOOT_SOURCE_TRADE); - characterB->SetCoins(characterB->GetCoins() - m_CoinsB + m_CoinsA, eLootSourceType::LOOT_SOURCE_TRADE); + characterA->SetCoins(characterA->GetCoins() - m_CoinsA + m_CoinsB, eLootSourceType::LOOT_SOURCE_TRADE); + characterB->SetCoins(characterB->GetCoins() - m_CoinsB + m_CoinsA, eLootSourceType::LOOT_SOURCE_TRADE); - for (const auto& tradeItem : m_ItemsA) - { - inventoryA->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true); + for (const auto& tradeItem : m_ItemsA) { + inventoryA->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true); - missionsA->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); - } + missionsA->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); + } - for (const auto& tradeItem : m_ItemsB) - { - inventoryB->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true); + for (const auto& tradeItem : m_ItemsB) { + inventoryB->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true); - missionsB->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); - } + missionsB->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); + } - for (const auto& tradeItem : m_ItemsA) - { - inventoryB->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); - } + for (const auto& tradeItem : m_ItemsA) { + inventoryB->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); + } - for (const auto& tradeItem : m_ItemsB) - { - inventoryA->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); - } + for (const auto& tradeItem : m_ItemsB) { + inventoryA->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); + } - TradingManager::Instance()->CancelTrade(m_TradeId); + TradingManager::Instance()->CancelTrade(m_TradeId); - characterA->SaveXMLToDatabase(); - characterB->SaveXMLToDatabase(); + characterA->SaveXMLToDatabase(); + characterB->SaveXMLToDatabase(); } -void Trade::Cancel() -{ - auto* entityA = GetParticipantAEntity(); - auto* entityB = GetParticipantBEntity(); +void Trade::Cancel() { + auto* entityA = GetParticipantAEntity(); + auto* entityB = GetParticipantBEntity(); - if (entityA == nullptr || entityB == nullptr) return; + if (entityA == nullptr || entityB == nullptr) return; - GameMessages::SendServerTradeCancel(entityA->GetObjectID(), entityA->GetSystemAddress()); - GameMessages::SendServerTradeCancel(entityB->GetObjectID(), entityB->GetSystemAddress()); + GameMessages::SendServerTradeCancel(entityA->GetObjectID(), entityA->GetSystemAddress()); + GameMessages::SendServerTradeCancel(entityB->GetObjectID(), entityB->GetSystemAddress()); } -void Trade::SendUpdateToOther(LWOOBJID participant) -{ - Entity* other = nullptr; - Entity* self = nullptr; - uint64_t coins; - std::vector itemIds; +void Trade::SendUpdateToOther(LWOOBJID participant) { + Entity* other = nullptr; + Entity* self = nullptr; + uint64_t coins; + std::vector itemIds; - Game::logger->Log("Trade", "Attempting to send trade update"); + Game::logger->Log("Trade", "Attempting to send trade update"); - if (participant == m_ParticipantA) - { - other = GetParticipantBEntity(); - self = GetParticipantAEntity(); - coins = m_CoinsA; - itemIds = m_ItemsA; - } - else if (participant == m_ParticipantB) - { - other = GetParticipantAEntity(); - self = GetParticipantBEntity(); - coins = m_CoinsB; - itemIds = m_ItemsB; - } - else - { - return; - } + if (participant == m_ParticipantA) { + other = GetParticipantBEntity(); + self = GetParticipantAEntity(); + coins = m_CoinsA; + itemIds = m_ItemsA; + } else if (participant == m_ParticipantB) { + other = GetParticipantAEntity(); + self = GetParticipantBEntity(); + coins = m_CoinsB; + itemIds = m_ItemsB; + } else { + return; + } - if (other == nullptr || self == nullptr) return; + if (other == nullptr || self == nullptr) return; - std::vector items {}; + std::vector items{}; - auto* inventoryComponent = self->GetComponent(); + auto* inventoryComponent = self->GetComponent(); - if (inventoryComponent == nullptr) return; + if (inventoryComponent == nullptr) return; - for (const auto tradeItem : itemIds) - { - auto* item = inventoryComponent->FindItemById(tradeItem.itemId); + for (const auto tradeItem : itemIds) { + auto* item = inventoryComponent->FindItemById(tradeItem.itemId); - if (item == nullptr) return; + if (item == nullptr) return; - if (tradeItem.itemCount > item->GetCount()) return; + if (tradeItem.itemCount > item->GetCount()) return; - items.push_back(tradeItem); - } + items.push_back(tradeItem); + } - Game::logger->Log("Trade", "Sending trade update"); + Game::logger->Log("Trade", "Sending trade update"); - GameMessages::SendServerTradeUpdate(other->GetObjectID(), coins, items, other->GetSystemAddress()); + GameMessages::SendServerTradeUpdate(other->GetObjectID(), coins, items, other->GetSystemAddress()); } -TradingManager::TradingManager() -{ +TradingManager::TradingManager() { } -TradingManager::~TradingManager() -{ - for (const auto& pair : trades) - { - delete pair.second; - } +TradingManager::~TradingManager() { + for (const auto& pair : trades) { + delete pair.second; + } - trades.clear(); + trades.clear(); } -Trade* TradingManager::GetTrade(LWOOBJID tradeId) const -{ - const auto& pair = trades.find(tradeId); +Trade* TradingManager::GetTrade(LWOOBJID tradeId) const { + const auto& pair = trades.find(tradeId); - if (pair == trades.end()) return nullptr; + if (pair == trades.end()) return nullptr; - return pair->second; + return pair->second; } -Trade* TradingManager::GetPlayerTrade(LWOOBJID playerId) const -{ - for (const auto& pair : trades) - { - if (pair.second->IsParticipant(playerId)) - { - return pair.second; - } - } +Trade* TradingManager::GetPlayerTrade(LWOOBJID playerId) const { + for (const auto& pair : trades) { + if (pair.second->IsParticipant(playerId)) { + return pair.second; + } + } - return nullptr; + return nullptr; } -void TradingManager::CancelTrade(LWOOBJID tradeId) -{ - auto* trade = GetTrade(tradeId); +void TradingManager::CancelTrade(LWOOBJID tradeId) { + auto* trade = GetTrade(tradeId); - if (trade == nullptr) return; + if (trade == nullptr) return; - delete trade; + delete trade; - trades.erase(tradeId); + trades.erase(tradeId); } -Trade* TradingManager::NewTrade(LWOOBJID participantA, LWOOBJID participantB) -{ - const LWOOBJID tradeId = ObjectIDManager::Instance()->GenerateObjectID(); +Trade* TradingManager::NewTrade(LWOOBJID participantA, LWOOBJID participantB) { + const LWOOBJID tradeId = ObjectIDManager::Instance()->GenerateObjectID(); - auto* trade = new Trade(tradeId, participantA, participantB); + auto* trade = new Trade(tradeId, participantA, participantB); - trades[tradeId] = trade; + trades[tradeId] = trade; - Game::logger->Log("TradingManager", "Created new trade between (%llu) <-> (%llu)", participantA, participantB); + Game::logger->Log("TradingManager", "Created new trade between (%llu) <-> (%llu)", participantA, participantB); - return trade; + return trade; } diff --git a/dGame/TradingManager.h b/dGame/TradingManager.h index 6962acaa..ec0d332f 100644 --- a/dGame/TradingManager.h +++ b/dGame/TradingManager.h @@ -4,73 +4,73 @@ struct TradeItem { - LWOOBJID itemId; - LOT itemLot; - uint32_t itemCount; + LWOOBJID itemId; + LOT itemLot; + uint32_t itemCount; }; class Trade { public: - explicit Trade(LWOOBJID tradeId, LWOOBJID participantA, LWOOBJID participantB); - ~Trade(); + explicit Trade(LWOOBJID tradeId, LWOOBJID participantA, LWOOBJID participantB); + ~Trade(); - LWOOBJID GetTradeId() const; + LWOOBJID GetTradeId() const; - bool IsParticipant(LWOOBJID playerId) const; + bool IsParticipant(LWOOBJID playerId) const; - LWOOBJID GetParticipantA() const; - LWOOBJID GetParticipantB() const; + LWOOBJID GetParticipantA() const; + LWOOBJID GetParticipantB() const; - Entity* GetParticipantAEntity() const; - Entity* GetParticipantBEntity() const; + Entity* GetParticipantAEntity() const; + Entity* GetParticipantBEntity() const; - void SetCoins(LWOOBJID participant, uint64_t coins); - void SetItems(LWOOBJID participant, std::vector items); - void SetAccepted(LWOOBJID participant, bool value); + void SetCoins(LWOOBJID participant, uint64_t coins); + void SetItems(LWOOBJID participant, std::vector items); + void SetAccepted(LWOOBJID participant, bool value); - void Complete(); - void Cancel(); + void Complete(); + void Cancel(); - void SendUpdateToOther(LWOOBJID participant); + void SendUpdateToOther(LWOOBJID participant); private: - LWOOBJID m_TradeId = LWOOBJID_EMPTY; - LWOOBJID m_ParticipantA = LWOOBJID_EMPTY; - LWOOBJID m_ParticipantB = LWOOBJID_EMPTY; + LWOOBJID m_TradeId = LWOOBJID_EMPTY; + LWOOBJID m_ParticipantA = LWOOBJID_EMPTY; + LWOOBJID m_ParticipantB = LWOOBJID_EMPTY; - uint64_t m_CoinsA = 0; - uint64_t m_CoinsB = 0; + uint64_t m_CoinsA = 0; + uint64_t m_CoinsB = 0; - std::vector m_ItemsA {}; - std::vector m_ItemsB {}; + std::vector m_ItemsA{}; + std::vector m_ItemsB{}; - bool m_AcceptedA = false; - bool m_AcceptedB = false; + bool m_AcceptedA = false; + bool m_AcceptedB = false; }; class TradingManager { public: - static TradingManager* Instance() { + static TradingManager* Instance() { if (!m_Address) { m_Address = new TradingManager(); } - + return m_Address; } - explicit TradingManager(); - ~TradingManager(); + explicit TradingManager(); + ~TradingManager(); - Trade* GetTrade(LWOOBJID tradeId) const; - Trade* GetPlayerTrade(LWOOBJID playerId) const; - void CancelTrade(LWOOBJID tradeId); - Trade* NewTrade(LWOOBJID participantA, LWOOBJID participantB); + Trade* GetTrade(LWOOBJID tradeId) const; + Trade* GetPlayerTrade(LWOOBJID playerId) const; + void CancelTrade(LWOOBJID tradeId); + Trade* NewTrade(LWOOBJID participantA, LWOOBJID participantB); private: - static TradingManager* m_Address; //For singleton method + static TradingManager* m_Address; //For singleton method - std::unordered_map trades; + std::unordered_map trades; }; diff --git a/dGame/User.cpp b/dGame/User.cpp index 33329199..20cc3ab4 100644 --- a/dGame/User.cpp +++ b/dGame/User.cpp @@ -17,7 +17,7 @@ User::User(const SystemAddress& sysAddr, const std::string& username, const std: m_SessionKey = sessionKey; m_SystemAddress = sysAddr; m_Username = username; - m_LoggedInCharID = 0; + m_LoggedInCharID = 0; m_IsBestFriendMap = std::unordered_map(); @@ -39,88 +39,85 @@ User::User(const SystemAddress& sysAddr, const std::string& username, const std: delete res; delete stmt; - //If we're loading a zone, we'll load the last used (aka current) character: + //If we're loading a zone, we'll load the last used (aka current) character: if (Game::server->GetZoneID() != 0) { - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE account_id=? ORDER BY last_login DESC LIMIT 1;"); - stmt->setUInt(1, m_AccountID); + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE account_id=? ORDER BY last_login DESC LIMIT 1;"); + stmt->setUInt(1, m_AccountID); - sql::ResultSet* res = stmt->executeQuery(); - if (res->rowsCount() > 0) { - while (res->next()) { - LWOOBJID objID = res->getUInt64(1); - Character* character = new Character(uint32_t(objID), this); - m_Characters.push_back(character); - Game::logger->Log("User", "Loaded %llu as it is the last used char", objID); - } - } + sql::ResultSet* res = stmt->executeQuery(); + if (res->rowsCount() > 0) { + while (res->next()) { + LWOOBJID objID = res->getUInt64(1); + Character* character = new Character(uint32_t(objID), this); + m_Characters.push_back(character); + Game::logger->Log("User", "Loaded %llu as it is the last used char", objID); + } + } - delete res; - delete stmt; - } + delete res; + delete stmt; + } } -User::User ( const User& other ) { +User::User(const User& other) { this->m_AccountID = other.m_AccountID; this->m_LastCharID = other.m_LastCharID; this->m_MaxGMLevel = other.m_MaxGMLevel; this->m_SessionKey = other.m_SessionKey; this->m_SystemAddress = other.m_SystemAddress; this->m_Username = other.m_Username; - this->m_LoggedInCharID = other.m_LoggedInCharID; + this->m_LoggedInCharID = other.m_LoggedInCharID; } User::~User() { for (Character* c : m_Characters) { - if (c) { - delete c; - c = nullptr; - } - } + if (c) { + delete c; + c = nullptr; + } + } } -User& User::operator= ( const User& other ) { +User& User::operator= (const User& other) { this->m_AccountID = other.m_AccountID; this->m_LastCharID = other.m_LastCharID; this->m_MaxGMLevel = other.m_MaxGMLevel; this->m_SessionKey = other.m_SessionKey; this->m_SystemAddress = other.m_SystemAddress; this->m_Username = other.m_Username; - this->m_LoggedInCharID = other.m_LoggedInCharID; + this->m_LoggedInCharID = other.m_LoggedInCharID; return *this; } -bool User::operator== ( const User& other ) const { +bool User::operator== (const User& other) const { if (m_Username == other.m_Username || m_SessionKey == other.m_SessionKey || m_SystemAddress == other.m_SystemAddress) return true; return false; } -Character * User::GetLastUsedChar() { - if (m_Characters.size() == 0) return nullptr; - else if (m_Characters.size() == 1) return m_Characters[0]; - else { - Character* toReturn = m_Characters[0]; - for (size_t i = 0; i < m_Characters.size(); ++i) { - if (m_Characters[i]->GetLastLogin() > toReturn->GetLastLogin()) toReturn = m_Characters[i]; - } +Character* User::GetLastUsedChar() { + if (m_Characters.size() == 0) return nullptr; + else if (m_Characters.size() == 1) return m_Characters[0]; + else { + Character* toReturn = m_Characters[0]; + for (size_t i = 0; i < m_Characters.size(); ++i) { + if (m_Characters[i]->GetLastLogin() > toReturn->GetLastLogin()) toReturn = m_Characters[i]; + } - return toReturn; - } + return toReturn; + } } -bool User::GetIsMuted() const -{ +bool User::GetIsMuted() const { return m_MuteExpire == 1 || m_MuteExpire > time(NULL); } -time_t User::GetMuteExpire() const -{ +time_t User::GetMuteExpire() const { return m_MuteExpire; } -void User::SetMuteExpire(time_t value) -{ +void User::SetMuteExpire(time_t value) { m_MuteExpire = value; } diff --git a/dGame/User.h b/dGame/User.h index 78640b38..59416c4c 100644 --- a/dGame/User.h +++ b/dGame/User.h @@ -10,7 +10,7 @@ class Character; -struct BehaviorParams{ +struct BehaviorParams { uint32_t behavior; LWOOBJID objid; bool followup; @@ -23,21 +23,21 @@ public: ~User(); User& operator=(const User& other); bool operator==(const User& other) const; - + uint32_t GetAccountID() { return m_AccountID; } std::string& GetUsername() { return m_Username; } std::string& GetSessionKey() { return m_SessionKey; } SystemAddress& GetSystemAddress() { return m_SystemAddress; } - + uint32_t GetMaxGMLevel() { return m_MaxGMLevel; } uint32_t GetLastCharID() { return m_LastCharID; } void SetLastCharID(uint32_t newCharID) { m_LastCharID = newCharID; } - + std::vector& GetCharacters() { return m_Characters; } Character* GetLastUsedChar(); - - void SetLoggedInChar(const LWOOBJID& objID) { m_LoggedInCharID = objID; } - LWOOBJID& GetLoggedInChar() { return m_LoggedInCharID; } + + void SetLoggedInChar(const LWOOBJID& objID) { m_LoggedInCharID = objID; } + LWOOBJID& GetLoggedInChar() { return m_LoggedInCharID; } bool GetLastChatMessageApproved() { return m_LastChatMessageApproved; } void SetLastChatMessageApproved(bool approved) { m_LastChatMessageApproved = approved; } @@ -52,7 +52,7 @@ public: // Added for GameMessageHandler std::unordered_map uiBehaviorHandles; - + void UserOutOfSync(); private: @@ -60,11 +60,11 @@ private: std::string m_Username; std::string m_SessionKey; SystemAddress m_SystemAddress; - + uint32_t m_MaxGMLevel; //The max GM level this account can assign to it's characters uint32_t m_LastCharID; std::vector m_Characters; - LWOOBJID m_LoggedInCharID; + LWOOBJID m_LoggedInCharID; std::unordered_map m_IsBestFriendMap; diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index 5a320b51..7da26b9a 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -21,7 +21,7 @@ #include "EntityManager.h" #include "SkillComponent.h" -UserManager * UserManager::m_Address = nullptr; +UserManager* UserManager::m_Address = nullptr; //Local functions as they aren't needed by anything else, leave the implementations at the bottom! uint32_t FindCharShirtID(uint32_t shirtColor, uint32_t shirtStyle); @@ -75,7 +75,7 @@ UserManager::~UserManager() { } -User* UserManager::CreateUser ( const SystemAddress& sysAddr, const std::string& username, const std::string& sessionKey ) { +User* UserManager::CreateUser(const SystemAddress& sysAddr, const std::string& username, const std::string& sessionKey) { User* user = new User(sysAddr, username, sessionKey); if (user && Game::server->IsConnected(sysAddr)) m_Users.insert(std::make_pair(sysAddr, user)); @@ -89,28 +89,27 @@ User* UserManager::CreateUser ( const SystemAddress& sysAddr, const std::string& return user; } -User* UserManager::GetUser ( const SystemAddress& sysAddr ) { +User* UserManager::GetUser(const SystemAddress& sysAddr) { auto it = m_Users.find(sysAddr); if (it != m_Users.end() && it->second) return it->second; - return nullptr; + return nullptr; } -User* UserManager::GetUser ( const std::string& username ) { +User* UserManager::GetUser(const std::string& username) { for (auto p : m_Users) { if (p.second) { if (p.second->GetUsername() == username) return p.second; } } - return nullptr; + return nullptr; } -bool UserManager::DeleteUser ( const SystemAddress& sysAddr ) { +bool UserManager::DeleteUser(const SystemAddress& sysAddr) { const auto& it = m_Users.find(sysAddr); - if (it != m_Users.end()) - { + if (it != m_Users.end()) { if (std::count(m_UsersToDelete.begin(), m_UsersToDelete.end(), it->second)) return false; m_UsersToDelete.push_back(it->second); @@ -123,10 +122,8 @@ bool UserManager::DeleteUser ( const SystemAddress& sysAddr ) { return false; } -void UserManager::DeletePendingRemovals() -{ - for (auto* user : m_UsersToDelete) - { +void UserManager::DeletePendingRemovals() { + for (auto* user : m_UsersToDelete) { Game::logger->Log("UserManager", "Deleted user %i", user->GetAccountID()); delete user; @@ -135,7 +132,7 @@ void UserManager::DeletePendingRemovals() m_UsersToDelete.clear(); } -bool UserManager::IsNameAvailable ( const std::string& requestedName ) { +bool UserManager::IsNameAvailable(const std::string& requestedName) { bool toReturn = false; //To allow for a clean exit sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE name=? OR pending_name=? LIMIT 1;"); stmt->setString(1, requestedName.c_str()); @@ -149,12 +146,12 @@ bool UserManager::IsNameAvailable ( const std::string& requestedName ) { return toReturn; } -std::string UserManager::GetPredefinedName ( uint32_t firstNameIndex, uint32_t middleNameIndex, uint32_t lastNameIndex ) { +std::string UserManager::GetPredefinedName(uint32_t firstNameIndex, uint32_t middleNameIndex, uint32_t lastNameIndex) { if (firstNameIndex > m_FirstNames.size() || middleNameIndex > m_MiddleNames.size() || lastNameIndex > m_LastNames.size()) return std::string("INVALID"); return std::string(m_FirstNames[firstNameIndex] + m_MiddleNames[middleNameIndex] + m_LastNames[lastNameIndex]); } -bool UserManager::IsNamePreapproved ( const std::string& requestedName ) { +bool UserManager::IsNamePreapproved(const std::string& requestedName) { for (std::string& s : m_PreapprovedNames) { if (s == requestedName) return true; } @@ -174,7 +171,7 @@ bool UserManager::IsNamePreapproved ( const std::string& requestedName ) { return false; } -void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { +void UserManager::RequestCharacterList(const SystemAddress& sysAddr) { User* u = GetUser(sysAddr); if (!u) return; @@ -185,8 +182,7 @@ void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { if (res->rowsCount() > 0) { std::vector& chars = u->GetCharacters(); - for (size_t i = 0; i < chars.size(); ++i) - { + for (size_t i = 0; i < chars.size(); ++i) { if (chars[i]->GetEntity() == nullptr) // We don't have entity data to save { delete chars[i]; @@ -196,8 +192,7 @@ void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { auto* skillComponent = chars[i]->GetEntity()->GetComponent(); - if (skillComponent != nullptr) - { + if (skillComponent != nullptr) { skillComponent->Reset(); } @@ -226,166 +221,164 @@ void UserManager::RequestCharacterList ( const SystemAddress& sysAddr ) { } void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) { - User* u = GetUser(sysAddr); - if (!u) return; + User* u = GetUser(sysAddr); + if (!u) return; - std::string name = PacketUtils::ReadString(8, packet, true); + std::string name = PacketUtils::ReadString(8, packet, true); - uint32_t firstNameIndex = PacketUtils::ReadPacketU32(74, packet); - uint32_t middleNameIndex = PacketUtils::ReadPacketU32(78, packet); - uint32_t lastNameIndex = PacketUtils::ReadPacketU32(82, packet); - std::string predefinedName = GetPredefinedName(firstNameIndex, middleNameIndex, lastNameIndex); + uint32_t firstNameIndex = PacketUtils::ReadPacketU32(74, packet); + uint32_t middleNameIndex = PacketUtils::ReadPacketU32(78, packet); + uint32_t lastNameIndex = PacketUtils::ReadPacketU32(82, packet); + std::string predefinedName = GetPredefinedName(firstNameIndex, middleNameIndex, lastNameIndex); - uint32_t shirtColor = PacketUtils::ReadPacketU32(95, packet); - uint32_t shirtStyle = PacketUtils::ReadPacketU32(99, packet); - uint32_t pantsColor = PacketUtils::ReadPacketU32(103, packet); - uint32_t hairStyle = PacketUtils::ReadPacketU32(107, packet); - uint32_t hairColor = PacketUtils::ReadPacketU32(111, packet); - uint32_t lh = PacketUtils::ReadPacketU32(115, packet); - uint32_t rh = PacketUtils::ReadPacketU32(119, packet); - uint32_t eyebrows = PacketUtils::ReadPacketU32(123, packet); - uint32_t eyes = PacketUtils::ReadPacketU32(127, packet); - uint32_t mouth = PacketUtils::ReadPacketU32(131, packet); + uint32_t shirtColor = PacketUtils::ReadPacketU32(95, packet); + uint32_t shirtStyle = PacketUtils::ReadPacketU32(99, packet); + uint32_t pantsColor = PacketUtils::ReadPacketU32(103, packet); + uint32_t hairStyle = PacketUtils::ReadPacketU32(107, packet); + uint32_t hairColor = PacketUtils::ReadPacketU32(111, packet); + uint32_t lh = PacketUtils::ReadPacketU32(115, packet); + uint32_t rh = PacketUtils::ReadPacketU32(119, packet); + uint32_t eyebrows = PacketUtils::ReadPacketU32(123, packet); + uint32_t eyes = PacketUtils::ReadPacketU32(127, packet); + uint32_t mouth = PacketUtils::ReadPacketU32(131, packet); - LOT shirtLOT = FindCharShirtID(shirtColor, shirtStyle); + LOT shirtLOT = FindCharShirtID(shirtColor, shirtStyle); LOT pantsLOT = FindCharPantsID(pantsColor); - if (name != "" && !UserManager::IsNameAvailable(name)) { - Game::logger->Log("UserManager", "AccountID: %i chose unavailable name: %s", u->GetAccountID(), name.c_str()); - WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_CUSTOM_NAME_IN_USE); - return; - } + if (name != "" && !UserManager::IsNameAvailable(name)) { + Game::logger->Log("UserManager", "AccountID: %i chose unavailable name: %s", u->GetAccountID(), name.c_str()); + WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_CUSTOM_NAME_IN_USE); + return; + } - if (!IsNameAvailable(predefinedName)) { - Game::logger->Log("UserManager", "AccountID: %i chose unavailable predefined name: %s", u->GetAccountID(), predefinedName.c_str()); - WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_PREDEFINED_NAME_IN_USE); - return; - } + if (!IsNameAvailable(predefinedName)) { + Game::logger->Log("UserManager", "AccountID: %i chose unavailable predefined name: %s", u->GetAccountID(), predefinedName.c_str()); + WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_PREDEFINED_NAME_IN_USE); + return; + } - if (name == "") { - Game::logger->Log("UserManager", "AccountID: %i is creating a character with predefined name: %s", u->GetAccountID(), predefinedName.c_str()); - } - else { - Game::logger->Log("UserManager", "AccountID: %i is creating a character with name: %s (temporary: %s)", u->GetAccountID(), name.c_str(), predefinedName.c_str()); - } + if (name == "") { + Game::logger->Log("UserManager", "AccountID: %i is creating a character with predefined name: %s", u->GetAccountID(), predefinedName.c_str()); + } else { + Game::logger->Log("UserManager", "AccountID: %i is creating a character with name: %s (temporary: %s)", u->GetAccountID(), name.c_str(), predefinedName.c_str()); + } - //Now that the name is ok, we can get an objectID from Master: - ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t objectID) { + //Now that the name is ok, we can get an objectID from Master: + ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t objectID) { sql::PreparedStatement* overlapStmt = Database::CreatePreppedStmt("SELECT id FROM charinfo WHERE id = ?"); overlapStmt->setUInt(1, objectID); auto* overlapResult = overlapStmt->executeQuery(); - if (overlapResult->next()) { + if (overlapResult->next()) { Game::logger->Log("UserManager", "Character object id unavailable, check objectidtracker!"); WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_OBJECT_ID_UNAVAILABLE); - return; - } + return; + } - std::stringstream xml; - xml << ""; + std::stringstream xml; + xml << ""; - xml << "GetAccountID() << "\" cc=\"0\" gm=\"0\" ft=\"0\" llog=\"" << time(NULL) << "\" "; - xml << "ls=\"0\" lzx=\"-626.5847\" lzy=\"613.3515\" lzz=\"-28.6374\" lzrx=\"0.0\" lzry=\"0.7015\" lzrz=\"0.0\" lzrw=\"0.7126\" "; - xml << "stt=\"0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;\">"; - xml << ""; - xml << ""; - std::string xmlSave1 = xml.str(); + xml << "GetAccountID() << "\" cc=\"0\" gm=\"0\" ft=\"0\" llog=\"" << time(NULL) << "\" "; + xml << "ls=\"0\" lzx=\"-626.5847\" lzy=\"613.3515\" lzz=\"-28.6374\" lzrx=\"0.0\" lzry=\"0.7015\" lzrz=\"0.0\" lzrw=\"0.7126\" "; + xml << "stt=\"0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;\">"; + xml << ""; + xml << ""; + std::string xmlSave1 = xml.str(); - ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t idforshirt) { - std::stringstream xml2; + ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t idforshirt) { + std::stringstream xml2; - LWOOBJID lwoidforshirt = idforshirt; - lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_CHARACTER); - lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_PERSISTENT); - xml2 << xmlSave1 << ""; + LWOOBJID lwoidforshirt = idforshirt; + lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_CHARACTER); + lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_PERSISTENT); + xml2 << xmlSave1 << ""; - std::string xmlSave2 = xml2.str(); + std::string xmlSave2 = xml2.str(); - ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t idforpants) { - LWOOBJID lwoidforpants = idforpants; - lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_CHARACTER); - lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_PERSISTENT); + ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t idforpants) { + LWOOBJID lwoidforpants = idforpants; + lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_CHARACTER); + lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_PERSISTENT); - std::stringstream xml3; - xml3 << xmlSave2 << ""; + std::stringstream xml3; + xml3 << xmlSave2 << ""; - xml3 << ""; + xml3 << ""; - //Check to see if our name was pre-approved: - bool nameOk = IsNamePreapproved(name); - if (!nameOk && u->GetMaxGMLevel() > 1) nameOk = true; + //Check to see if our name was pre-approved: + bool nameOk = IsNamePreapproved(name); + if (!nameOk && u->GetMaxGMLevel() > 1) nameOk = true; - if (name != "") { - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charinfo`(`id`, `account_id`, `name`, `pending_name`, `needs_rename`, `last_login`) VALUES (?,?,?,?,?,?)"); - stmt->setUInt(1, objectID); - stmt->setUInt(2, u->GetAccountID()); - stmt->setString(3, predefinedName.c_str()); - stmt->setString(4, name.c_str()); - stmt->setBoolean(5, false); - stmt->setUInt64(6, time(NULL)); + if (name != "") { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charinfo`(`id`, `account_id`, `name`, `pending_name`, `needs_rename`, `last_login`) VALUES (?,?,?,?,?,?)"); + stmt->setUInt(1, objectID); + stmt->setUInt(2, u->GetAccountID()); + stmt->setString(3, predefinedName.c_str()); + stmt->setString(4, name.c_str()); + stmt->setBoolean(5, false); + stmt->setUInt64(6, time(NULL)); - if (nameOk) { - stmt->setString(3, name.c_str()); - stmt->setString(4, ""); - } + if (nameOk) { + stmt->setString(3, name.c_str()); + stmt->setString(4, ""); + } - stmt->execute(); - delete stmt; - } else { - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charinfo`(`id`, `account_id`, `name`, `pending_name`, `needs_rename`, `last_login`) VALUES (?,?,?,?,?,?)"); - stmt->setUInt(1, objectID); - stmt->setUInt(2, u->GetAccountID()); - stmt->setString(3, predefinedName.c_str()); - stmt->setString(4, ""); - stmt->setBoolean(5, false); - stmt->setUInt64(6, time(NULL)); + stmt->execute(); + delete stmt; + } else { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charinfo`(`id`, `account_id`, `name`, `pending_name`, `needs_rename`, `last_login`) VALUES (?,?,?,?,?,?)"); + stmt->setUInt(1, objectID); + stmt->setUInt(2, u->GetAccountID()); + stmt->setString(3, predefinedName.c_str()); + stmt->setString(4, ""); + stmt->setBoolean(5, false); + stmt->setUInt64(6, time(NULL)); - stmt->execute(); - delete stmt; - } + stmt->execute(); + delete stmt; + } - //Now finally insert our character xml: - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charxml`(`id`, `xml_data`) VALUES (?,?)"); - stmt->setUInt(1, objectID); - stmt->setString(2, xml3.str().c_str()); - stmt->execute(); - delete stmt; + //Now finally insert our character xml: + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charxml`(`id`, `xml_data`) VALUES (?,?)"); + stmt->setUInt(1, objectID); + stmt->setString(2, xml3.str().c_str()); + stmt->execute(); + delete stmt; - WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_SUCCESS); - UserManager::RequestCharacterList(sysAddr); - }); - }); - }); + WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_SUCCESS); + UserManager::RequestCharacterList(sysAddr); + }); + }); + }); } void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) { - User* u = GetUser(sysAddr); - if (!u) { - Game::logger->Log("UserManager", "Couldn't get user to delete character"); - return; - } + User* u = GetUser(sysAddr); + if (!u) { + Game::logger->Log("UserManager", "Couldn't get user to delete character"); + return; + } - LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); + LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); uint32_t charID = static_cast(objectID); - Game::logger->Log("UserManager", "Received char delete req for ID: %llu (%u)", objectID, charID); + Game::logger->Log("UserManager", "Received char delete req for ID: %llu (%u)", objectID, charID); - //Check if this user has this character: - bool hasCharacter = false; - std::vector& characters = u->GetCharacters(); - for (size_t i = 0; i < characters.size(); ++i) { - if (characters[i]->GetID() == charID) { hasCharacter = true; } - } + //Check if this user has this character: + bool hasCharacter = false; + std::vector& characters = u->GetCharacters(); + for (size_t i = 0; i < characters.size(); ++i) { + if (characters[i]->GetID() == charID) { hasCharacter = true; } + } - if (!hasCharacter) { - Game::logger->Log("UserManager", "User %i tried to delete a character that it does not own!", u->GetAccountID()); - WorldPackets::SendCharacterDeleteResponse(sysAddr, false); - } - else { - Game::logger->Log("UserManager", "Deleting character %i", charID); + if (!hasCharacter) { + Game::logger->Log("UserManager", "User %i tried to delete a character that it does not own!", u->GetAccountID()); + WorldPackets::SendCharacterDeleteResponse(sysAddr, false); + } else { + Game::logger->Log("UserManager", "Deleting character %i", charID); { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("DELETE FROM charxml WHERE id=? LIMIT 1;"); stmt->setUInt64(1, charID); @@ -454,115 +447,115 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) delete stmt; } - WorldPackets::SendCharacterDeleteResponse(sysAddr, true); - } + WorldPackets::SendCharacterDeleteResponse(sysAddr, true); + } } void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) { - User* u = GetUser(sysAddr); - if (!u) { - Game::logger->Log("UserManager", "Couldn't get user to delete character"); - return; - } + User* u = GetUser(sysAddr); + if (!u) { + Game::logger->Log("UserManager", "Couldn't get user to delete character"); + return; + } - LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); - objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_CHARACTER); - objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_PERSISTENT); + LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); + objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_CHARACTER); + objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_PERSISTENT); - uint32_t charID = static_cast(objectID); - Game::logger->Log("UserManager", "Received char rename request for ID: %llu (%u)", objectID, charID); + uint32_t charID = static_cast(objectID); + Game::logger->Log("UserManager", "Received char rename request for ID: %llu (%u)", objectID, charID); - std::string newName = PacketUtils::ReadString(16, packet, true); + std::string newName = PacketUtils::ReadString(16, packet, true); - Character* character = nullptr; + Character* character = nullptr; - //Check if this user has this character: - bool hasCharacter = false; - std::vector& characters = u->GetCharacters(); - for (size_t i = 0; i < characters.size(); ++i) { - if (characters[i]->GetID() == charID) { hasCharacter = true; character = characters[i]; } - } + //Check if this user has this character: + bool hasCharacter = false; + std::vector& characters = u->GetCharacters(); + for (size_t i = 0; i < characters.size(); ++i) { + if (characters[i]->GetID() == charID) { hasCharacter = true; character = characters[i]; } + } - if (!hasCharacter || !character) { - Game::logger->Log("UserManager", "User %i tried to rename a character that it does not own!", u->GetAccountID()); - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); - } else if (hasCharacter && character) { - if (newName == character->GetName()) { - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_UNAVAILABLE); - return; - } + if (!hasCharacter || !character) { + Game::logger->Log("UserManager", "User %i tried to rename a character that it does not own!", u->GetAccountID()); + WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); + } else if (hasCharacter && character) { + if (newName == character->GetName()) { + WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_UNAVAILABLE); + return; + } - if (IsNameAvailable(newName)) { - if (IsNamePreapproved(newName)) { - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET name=?, pending_name='', needs_rename=0, last_login=? WHERE id=? LIMIT 1"); - stmt->setString(1, newName); - stmt->setUInt64(2, time(NULL)); - stmt->setUInt(3, character->GetID()); - stmt->execute(); - delete stmt; + if (IsNameAvailable(newName)) { + if (IsNamePreapproved(newName)) { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET name=?, pending_name='', needs_rename=0, last_login=? WHERE id=? LIMIT 1"); + stmt->setString(1, newName); + stmt->setUInt64(2, time(NULL)); + stmt->setUInt(3, character->GetID()); + stmt->execute(); + delete stmt; - Game::logger->Log("UserManager", "Character %s now known as %s", character->GetName().c_str(), newName.c_str()); - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); - UserManager::RequestCharacterList(sysAddr); - } else { - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET pending_name=?, needs_rename=0, last_login=? WHERE id=? LIMIT 1"); - stmt->setString(1, newName); - stmt->setUInt64(2, time(NULL)); - stmt->setUInt(3, character->GetID()); - stmt->execute(); - delete stmt; + Game::logger->Log("UserManager", "Character %s now known as %s", character->GetName().c_str(), newName.c_str()); + WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); + UserManager::RequestCharacterList(sysAddr); + } else { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET pending_name=?, needs_rename=0, last_login=? WHERE id=? LIMIT 1"); + stmt->setString(1, newName); + stmt->setUInt64(2, time(NULL)); + stmt->setUInt(3, character->GetID()); + stmt->execute(); + delete stmt; - Game::logger->Log("UserManager", "Character %s has been renamed to %s and is pending approval by a moderator.", character->GetName().c_str(), newName.c_str()); - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); - UserManager::RequestCharacterList(sysAddr); - } - } else { - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_IN_USE); - } - } else { - Game::logger->Log("UserManager", "Unknown error occurred when renaming character, either hasCharacter or character variable != true."); - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); - } + Game::logger->Log("UserManager", "Character %s has been renamed to %s and is pending approval by a moderator.", character->GetName().c_str(), newName.c_str()); + WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); + UserManager::RequestCharacterList(sysAddr); + } + } else { + WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_IN_USE); + } + } else { + Game::logger->Log("UserManager", "Unknown error occurred when renaming character, either hasCharacter or character variable != true."); + WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); + } } void UserManager::LoginCharacter(const SystemAddress& sysAddr, uint32_t playerID) { - User* u = GetUser(sysAddr); - if (!u) { - Game::logger->Log("UserManager", "Couldn't get user to log in character"); - return; - } + User* u = GetUser(sysAddr); + if (!u) { + Game::logger->Log("UserManager", "Couldn't get user to log in character"); + return; + } - Character* character = nullptr; - bool hasCharacter = false; - std::vector& characters = u->GetCharacters(); + Character* character = nullptr; + bool hasCharacter = false; + std::vector& characters = u->GetCharacters(); - for (size_t i = 0; i < characters.size(); ++i) { - if (characters[i]->GetID() == playerID) { hasCharacter = true; character = characters[i]; } - } + for (size_t i = 0; i < characters.size(); ++i) { + if (characters[i]->GetID() == playerID) { hasCharacter = true; character = characters[i]; } + } - if (hasCharacter && character) { - sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET last_login=? WHERE id=? LIMIT 1"); - stmt->setUInt64(1, time(NULL)); - stmt->setUInt(2, playerID); - stmt->execute(); - delete stmt; + if (hasCharacter && character) { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET last_login=? WHERE id=? LIMIT 1"); + stmt->setUInt64(1, time(NULL)); + stmt->setUInt(2, playerID); + stmt->execute(); + delete stmt; - uint32_t zoneID = character->GetZoneID(); + uint32_t zoneID = character->GetZoneID(); if (zoneID == LWOZONEID_INVALID) zoneID = 1000; //Send char to VE - ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, zoneID, character->GetZoneClone(), false, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, zoneID, character->GetZoneClone(), false, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", character->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); if (character) { character->SetZoneID(zoneID); character->SetZoneInstance(zoneInstance); character->SetZoneClone(zoneClone); } WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); - return; - }); - } else { - Game::logger->Log("UserManager", "Unknown error occurred when logging in a character, either hasCharacter or character variable != true."); - } + return; + }); + } else { + Game::logger->Log("UserManager", "Unknown error occurred when logging in a character, either hasCharacter or character variable != true."); + } } uint32_t FindCharShirtID(uint32_t shirtColor, uint32_t shirtStyle) { @@ -575,8 +568,7 @@ uint32_t FindCharShirtID(uint32_t shirtColor, uint32_t shirtStyle) { auto shirtLOT = tableData.getIntField(0, -1); tableData.finalize(); return shirtLOT; - } - catch (const std::exception&){ + } catch (const std::exception&) { Game::logger->Log("Character Create", "Failed to execute query! Using backup..."); // in case of no shirt found in CDServer, return problematic red vest. return 4069; @@ -591,8 +583,7 @@ uint32_t FindCharPantsID(uint32_t pantsColor) { auto pantsLOT = tableData.getIntField(0, -1); tableData.finalize(); return pantsLOT; - } - catch (const std::exception&){ + } catch (const std::exception&) { Game::logger->Log("Character Create", "Failed to execute query! Using backup..."); // in case of no pants color found in CDServer, return red pants. return 2508; diff --git a/dGame/UserManager.h b/dGame/UserManager.h index a5db6979..bf9985a1 100644 --- a/dGame/UserManager.h +++ b/dGame/UserManager.h @@ -15,23 +15,23 @@ public: if (!m_Address) { m_Address = new UserManager(); } - + return m_Address; } - + void Initialize(); ~UserManager(); - + User* CreateUser(const SystemAddress& sysAddr, const std::string& username, const std::string& sessionKey); User* GetUser(const SystemAddress& sysAddr); User* GetUser(const std::string& username); bool DeleteUser(const SystemAddress& sysAddr); //Returns true on succesful deletion void DeletePendingRemovals(); - + bool IsNameAvailable(const std::string& requestedName); std::string GetPredefinedName(uint32_t firstNameIndex, uint32_t middleNameIndex, uint32_t lastNameIndex); bool IsNamePreapproved(const std::string& requestedName); - + void RequestCharacterList(const SystemAddress& sysAddr); void CreateCharacter(const SystemAddress& sysAddr, Packet* packet); void DeleteCharacter(const SystemAddress& sysAddr, Packet* packet); @@ -46,7 +46,7 @@ private: static UserManager* m_Address; //Singleton std::map m_Users; std::vector m_UsersToDelete; - + std::vector m_FirstNames; std::vector m_MiddleNames; std::vector m_LastNames; diff --git a/dGame/dBehaviors/AirMovementBehavior.cpp b/dGame/dBehaviors/AirMovementBehavior.cpp index ac7bf667..188d743d 100644 --- a/dGame/dBehaviors/AirMovementBehavior.cpp +++ b/dGame/dBehaviors/AirMovementBehavior.cpp @@ -3,8 +3,7 @@ #include "BehaviorContext.h" #include "EntityManager.h" -void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { uint32_t handle; bitStream->Read(handle); @@ -12,15 +11,13 @@ void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi context->RegisterSyncBehavior(handle, this, branch); } -void AirMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void AirMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto handle = context->GetUniqueSkillId(); bitStream->Write(handle); } -void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { uint32_t behaviorId; bit_stream->Read(behaviorId); @@ -31,14 +28,12 @@ void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bit_ auto* behavior = CreateBehavior(behaviorId); - if (EntityManager::Instance()->GetEntity(target) != nullptr) - { + if (EntityManager::Instance()->GetEntity(target) != nullptr) { branch.target = target; } - + behavior->Handle(context, bit_stream, branch); } -void AirMovementBehavior::Load() -{ +void AirMovementBehavior::Load() { } diff --git a/dGame/dBehaviors/AirMovementBehavior.h b/dGame/dBehaviors/AirMovementBehavior.h index 0a9755e6..6c3a2abf 100644 --- a/dGame/dBehaviors/AirMovementBehavior.h +++ b/dGame/dBehaviors/AirMovementBehavior.h @@ -9,8 +9,7 @@ public: * Inherited */ - explicit AirMovementBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit AirMovementBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/AndBehavior.cpp b/dGame/dBehaviors/AndBehavior.cpp index 5fc1e113..d54d9ec5 100644 --- a/dGame/dBehaviors/AndBehavior.cpp +++ b/dGame/dBehaviors/AndBehavior.cpp @@ -3,18 +3,14 @@ #include "Game.h" #include "dLogger.h" -void AndBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ - for (auto* behavior : this->m_behaviors) - { +void AndBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { + for (auto* behavior : this->m_behaviors) { behavior->Handle(context, bitStream, branch); } } -void AndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ - for (auto* behavior : this->m_behaviors) - { +void AndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { + for (auto* behavior : this->m_behaviors) { behavior->Calculate(context, bitStream, branch); } } @@ -25,14 +21,11 @@ void AndBehavior::UnCast(BehaviorContext* context, const BehaviorBranchContext b } } -void AndBehavior::Load() -{ +void AndBehavior::Load() { const auto parameters = GetParameterNames(); - for (const auto& parameter : parameters) - { - if (parameter.first.rfind("behavior", 0) == 0) - { + for (const auto& parameter : parameters) { + if (parameter.first.rfind("behavior", 0) == 0) { auto* action = GetAction(parameter.second); this->m_behaviors.push_back(action); diff --git a/dGame/dBehaviors/AndBehavior.h b/dGame/dBehaviors/AndBehavior.h index 9cbce569..17d1e51e 100644 --- a/dGame/dBehaviors/AndBehavior.h +++ b/dGame/dBehaviors/AndBehavior.h @@ -8,18 +8,17 @@ class AndBehavior final : public Behavior { public: std::vector m_behaviors; - + /* * Inherited */ - explicit AndBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit AndBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/ApplyBuffBehavior.cpp b/dGame/dBehaviors/ApplyBuffBehavior.cpp index 46422aa1..35b0f269 100644 --- a/dGame/dBehaviors/ApplyBuffBehavior.cpp +++ b/dGame/dBehaviors/ApplyBuffBehavior.cpp @@ -5,48 +5,44 @@ #include "BuffComponent.h" -void ApplyBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - auto* entity = EntityManager::Instance()->GetEntity(branch.target == LWOOBJID_EMPTY ? context->originator : branch.target); +void ApplyBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto* entity = EntityManager::Instance()->GetEntity(branch.target == LWOOBJID_EMPTY ? context->originator : branch.target); - if (entity == nullptr) return; + if (entity == nullptr) return; - auto* buffComponent = entity->GetComponent(); + auto* buffComponent = entity->GetComponent(); - if (buffComponent == nullptr) return; + if (buffComponent == nullptr) return; - buffComponent->ApplyBuff(m_BuffId, m_Duration, context->originator, addImmunity, cancelOnDamaged, cancelOnDeath, - cancelOnLogout, cancelonRemoveBuff, cancelOnUi, cancelOnUnequip, cancelOnZone); + buffComponent->ApplyBuff(m_BuffId, m_Duration, context->originator, addImmunity, cancelOnDamaged, cancelOnDeath, + cancelOnLogout, cancelonRemoveBuff, cancelOnUi, cancelOnUnequip, cancelOnZone); } -void ApplyBuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) -{ - auto* entity = EntityManager::Instance()->GetEntity(branch.target); +void ApplyBuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { + auto* entity = EntityManager::Instance()->GetEntity(branch.target); - if (entity == nullptr) return; + if (entity == nullptr) return; - auto* buffComponent = entity->GetComponent(); + auto* buffComponent = entity->GetComponent(); - if (buffComponent == nullptr) return; + if (buffComponent == nullptr) return; - buffComponent->RemoveBuff(m_BuffId); + buffComponent->RemoveBuff(m_BuffId); } -void ApplyBuffBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - Handle(context, bitStream, branch); +void ApplyBuffBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + Handle(context, bitStream, branch); } -void ApplyBuffBehavior::Load() -{ - m_BuffId = GetInt("buff_id"); - m_Duration = GetFloat("duration_secs"); - addImmunity = GetBoolean("add_immunity"); - cancelOnDamaged = GetBoolean("cancel_on_damaged"); - cancelOnDeath = GetBoolean("cancel_on_death"); - cancelOnLogout = GetBoolean("cancel_on_logout"); - cancelonRemoveBuff = GetBoolean("cancel_on_remove_buff"); - cancelOnUi = GetBoolean("cancel_on_ui"); - cancelOnUnequip = GetBoolean("cancel_on_unequip"); - cancelOnZone = GetBoolean("cancel_on_zone"); +void ApplyBuffBehavior::Load() { + m_BuffId = GetInt("buff_id"); + m_Duration = GetFloat("duration_secs"); + addImmunity = GetBoolean("add_immunity"); + cancelOnDamaged = GetBoolean("cancel_on_damaged"); + cancelOnDeath = GetBoolean("cancel_on_death"); + cancelOnLogout = GetBoolean("cancel_on_logout"); + cancelonRemoveBuff = GetBoolean("cancel_on_remove_buff"); + cancelOnUi = GetBoolean("cancel_on_ui"); + cancelOnUnequip = GetBoolean("cancel_on_unequip"); + cancelOnZone = GetBoolean("cancel_on_zone"); } diff --git a/dGame/dBehaviors/ApplyBuffBehavior.h b/dGame/dBehaviors/ApplyBuffBehavior.h index 536d3501..139082df 100644 --- a/dGame/dBehaviors/ApplyBuffBehavior.h +++ b/dGame/dBehaviors/ApplyBuffBehavior.h @@ -7,29 +7,28 @@ class ApplyBuffBehavior final : public Behavior { public: - int32_t m_BuffId; - float m_Duration; - bool addImmunity; - bool cancelOnDamaged; - bool cancelOnDeath; - bool cancelOnLogout; - bool cancelonRemoveBuff; - bool cancelOnUi; - bool cancelOnUnequip; - bool cancelOnZone; + int32_t m_BuffId; + float m_Duration; + bool addImmunity; + bool cancelOnDamaged; + bool cancelOnDeath; + bool cancelOnLogout; + bool cancelonRemoveBuff; + bool cancelOnUi; + bool cancelOnUnequip; + bool cancelOnZone; /* * Inherited */ - explicit ApplyBuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ApplyBuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; + void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.cpp b/dGame/dBehaviors/AreaOfEffectBehavior.cpp index e3f992e7..ba0f69a5 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.cpp +++ b/dGame/dBehaviors/AreaOfEffectBehavior.cpp @@ -10,14 +10,12 @@ #include "RebuildComponent.h" #include "DestroyableComponent.h" -void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { uint32_t targetCount; bitStream->Read(targetCount); - if (targetCount > this->m_maxTargets) - { + if (targetCount > this->m_maxTargets) { return; } @@ -25,8 +23,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b targets.reserve(targetCount); - for (auto i = 0u; i < targetCount; ++i) - { + for (auto i = 0u; i < targetCount; ++i) { LWOOBJID target; bitStream->Read(target); @@ -34,20 +31,17 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b targets.push_back(target); } - for (auto target : targets) - { + for (auto target : targets) { branch.target = target; this->m_action->Handle(context, bitStream, branch); } } -void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* self = EntityManager::Instance()->GetEntity(context->caster); - if (self == nullptr) - { + if (self == nullptr) { Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!", context->originator); return; @@ -59,10 +53,8 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream auto* presetTarget = EntityManager::Instance()->GetEntity(branch.target); - if (presetTarget != nullptr) - { - if (this->m_radius * this->m_radius >= Vector3::DistanceSquared(reference, presetTarget->GetPosition())) - { + if (presetTarget != nullptr) { + if (this->m_radius * this->m_radius >= Vector3::DistanceSquared(reference, presetTarget->GetPosition())) { targets.push_back(presetTarget); } } @@ -75,78 +67,67 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream } // Gets all of the valid targets, passing in if should target enemies and friends - for (auto validTarget : context->GetValidTargets(m_ignoreFaction , includeFaction, m_TargetSelf == 1, m_targetEnemy == 1, m_targetFriend == 1)) - { + for (auto validTarget : context->GetValidTargets(m_ignoreFaction, includeFaction, m_TargetSelf == 1, m_targetEnemy == 1, m_targetFriend == 1)) { auto* entity = EntityManager::Instance()->GetEntity(validTarget); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!", validTarget, context->originator); continue; } - if (std::find(targets.begin(), targets.end(), entity) != targets.end()) - { + if (std::find(targets.begin(), targets.end(), entity) != targets.end()) { continue; } auto* destroyableComponent = entity->GetComponent(); - if (destroyableComponent == nullptr) - { + if (destroyableComponent == nullptr) { continue; } - if (destroyableComponent->HasFaction(m_ignoreFaction)) - { + if (destroyableComponent->HasFaction(m_ignoreFaction)) { continue; } const auto distance = Vector3::DistanceSquared(reference, entity->GetPosition()); - if (this->m_radius * this->m_radius >= distance && (this->m_maxTargets == 0 || targets.size() < this->m_maxTargets)) - { + if (this->m_radius * this->m_radius >= distance && (this->m_maxTargets == 0 || targets.size() < this->m_maxTargets)) { targets.push_back(entity); } } - std::sort(targets.begin(), targets.end(), [reference](Entity* a, Entity* b) - { + std::sort(targets.begin(), targets.end(), [reference](Entity* a, Entity* b) { const auto aDistance = Vector3::DistanceSquared(a->GetPosition(), reference); const auto bDistance = Vector3::DistanceSquared(b->GetPosition(), reference); return aDistance > bDistance; - }); + }); const uint32_t size = targets.size(); bitStream->Write(size); - if (size == 0) - { + if (size == 0) { return; } context->foundTarget = true; - for (auto* target : targets) - { + for (auto* target : targets) { bitStream->Write(target->GetObjectID()); PlayFx(u"cast", context->originator, target->GetObjectID()); } - for (auto* target : targets) - { + for (auto* target : targets) { branch.target = target->GetObjectID(); this->m_action->Calculate(context, bitStream, branch); } } -void AreaOfEffectBehavior::Load() -{ +void AreaOfEffectBehavior::Load() { this->m_action = GetAction("action"); this->m_radius = GetFloat("radius"); @@ -157,7 +138,7 @@ void AreaOfEffectBehavior::Load() this->m_includeFaction = GetInt("include_faction"); - this->m_TargetSelf = GetInt("target_self"); + this->m_TargetSelf = GetInt("target_self"); this->m_targetEnemy = GetInt("target_enemy"); diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.h b/dGame/dBehaviors/AreaOfEffectBehavior.h index 9a8b7290..863ce8f7 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.h +++ b/dGame/dBehaviors/AreaOfEffectBehavior.h @@ -14,21 +14,20 @@ public: int32_t m_includeFaction; - int32_t m_TargetSelf; + int32_t m_TargetSelf; int32_t m_targetEnemy; int32_t m_targetFriend; - + /* * Inherited */ - explicit AreaOfEffectBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit AreaOfEffectBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/AttackDelayBehavior.cpp b/dGame/dBehaviors/AttackDelayBehavior.cpp index c536f925..9d1eb872 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.cpp +++ b/dGame/dBehaviors/AttackDelayBehavior.cpp @@ -4,48 +4,41 @@ #include "Game.h" #include "dLogger.h" -void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { uint32_t handle; bitStream->Read(handle); - - for (auto i = 0u; i < this->m_numIntervals; ++i) - { + + for (auto i = 0u; i < this->m_numIntervals; ++i) { context->RegisterSyncBehavior(handle, this, branch); } } -void AttackDelayBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void AttackDelayBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { const auto handle = context->GetUniqueSkillId(); bitStream->Write(handle); context->foundTarget = true; - for (auto i = 0u; i < this->m_numIntervals; ++i) - { + for (auto i = 0u; i < this->m_numIntervals; ++i) { const auto multiple = static_cast(i + 1); context->SyncCalculation(handle, this->m_delay * multiple, this, branch, m_ignoreInterrupts); } } -void AttackDelayBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void AttackDelayBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { this->m_action->Handle(context, bitStream, branch); } -void AttackDelayBehavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void AttackDelayBehavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { PlayFx(u"cast", context->originator); this->m_action->Calculate(context, bitStream, branch); } -void AttackDelayBehavior::Load() -{ +void AttackDelayBehavior::Load() { this->m_numIntervals = GetInt("num_intervals"); this->m_action = GetAction("action"); @@ -54,8 +47,7 @@ void AttackDelayBehavior::Load() this->m_ignoreInterrupts = GetBoolean("ignore_interrupts"); - if (this->m_numIntervals == 0) - { + if (this->m_numIntervals == 0) { this->m_numIntervals = 1; } } diff --git a/dGame/dBehaviors/AttackDelayBehavior.h b/dGame/dBehaviors/AttackDelayBehavior.h index e798bf87..4223aba4 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.h +++ b/dGame/dBehaviors/AttackDelayBehavior.h @@ -15,9 +15,8 @@ public: /* * Inherited */ - - explicit AttackDelayBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + + explicit AttackDelayBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; @@ -27,6 +26,6 @@ public: void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/BasicAttackBehavior.cpp b/dGame/dBehaviors/BasicAttackBehavior.cpp index 8f0fd287..0c0b0d56 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.cpp +++ b/dGame/dBehaviors/BasicAttackBehavior.cpp @@ -43,7 +43,7 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi uint32_t damageDealt; bitStream->Read(damageDealt); - // A value that's too large may be a cheating attempt, so we set it to MIN too + // A value that's too large may be a cheating attempt, so we set it to MIN too if (damageDealt > this->m_maxDamage || damageDealt < this->m_minDamage) { damageDealt = this->m_minDamage; } @@ -53,7 +53,7 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi bitStream->Read(died); if (entity != nullptr) { - auto* destroyableComponent = entity->GetComponent(); + auto* destroyableComponent = entity->GetComponent(); if (destroyableComponent != nullptr) { PlayFx(u"onhit", entity->GetObjectID()); destroyableComponent->Damage(damageDealt, context->originator, context->skillID); @@ -113,7 +113,7 @@ void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* auto* destroyableComponent = entity->GetComponent(); if (damage != 0 && destroyableComponent != nullptr) { PlayFx(u"onhit", entity->GetObjectID(), 1); - destroyableComponent->Damage(damage, context->originator, context->skillID, false); + destroyableComponent->Damage(damage, context->originator, context->skillID, false); context->ScheduleUpdate(branch.target); } } diff --git a/dGame/dBehaviors/BasicAttackBehavior.h b/dGame/dBehaviors/BasicAttackBehavior.h index fa4dc0e8..9e6874b9 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.h +++ b/dGame/dBehaviors/BasicAttackBehavior.h @@ -9,14 +9,13 @@ public: uint32_t m_maxDamage; Behavior* m_onSuccess; - - explicit BasicAttackBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + + explicit BasicAttackBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index a1b746cd..ed8f2f8c 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -60,7 +60,7 @@ #include "DamageReductionBehavior.h" #include "JetPackBehavior.h" -//CDClient includes + //CDClient includes #include "CDBehaviorParameterTable.h" #include "CDClientDatabase.h" #include "CDClientManager.h" @@ -73,34 +73,28 @@ std::unordered_map Behavior::Cache = {}; CDBehaviorParameterTable* Behavior::BehaviorParameterTable = nullptr; -Behavior* Behavior::GetBehavior(const uint32_t behaviorId) -{ - if (BehaviorParameterTable == nullptr) - { +Behavior* Behavior::GetBehavior(const uint32_t behaviorId) { + if (BehaviorParameterTable == nullptr) { BehaviorParameterTable = CDClientManager::Instance()->GetTable("BehaviorParameter"); } const auto pair = Cache.find(behaviorId); - if (pair == Cache.end()) - { + if (pair == Cache.end()) { return nullptr; } return static_cast(pair->second); } -Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) -{ +Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) { auto* cached = GetBehavior(behaviorId); - if (cached != nullptr) - { + if (cached != nullptr) { return cached; } - if (behaviorId == 0) - { + if (behaviorId == 0) { return new EmptyBehavior(0); } @@ -108,8 +102,7 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) Behavior* behavior = nullptr; - switch (templateId) - { + switch (templateId) { case BehaviorTemplates::BEHAVIOR_EMPTY: break; case BehaviorTemplates::BEHAVIOR_BASIC_ATTACK: behavior = new BasicAttackBehavior(behaviorId); @@ -273,8 +266,7 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) break; } - if (behavior == nullptr) - { + if (behavior == nullptr) { //Game::logger->Log("Behavior", "Failed to load unimplemented template id (%i)!", templateId); behavior = new EmptyBehavior(behaviorId); @@ -305,19 +297,16 @@ BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) { } // For use with enemies, to display the correct damage animations on the players -void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID secondary) -{ +void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID secondary) { auto* targetEntity = EntityManager::Instance()->GetEntity(target); - if (targetEntity == nullptr) - { + if (targetEntity == nullptr) { return; } const auto effectId = this->m_effectId; - if (effectId == 0) - { + if (effectId == 0) { GameMessages::SendPlayFXEffect(targetEntity, -1, type, "", secondary, 1, 1, true); return; @@ -327,23 +316,17 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID const auto typeString = GeneralUtils::UTF16ToWTF8(type); - if (m_effectNames == nullptr) - { + if (m_effectNames == nullptr) { m_effectNames = new std::unordered_map(); - } - else - { + } else { const auto pair = m_effectNames->find(typeString); - if (type.empty()) - { + if (type.empty()) { type = GeneralUtils::ASCIIToUTF16(*m_effectType); } - if (pair != m_effectNames->end()) - { - if (renderComponent == nullptr) - { + if (pair != m_effectNames->end()) { + if (renderComponent == nullptr) { GameMessages::SendPlayFXEffect(targetEntity, effectId, type, pair->second, secondary, 1, 1, true); return; @@ -366,24 +349,22 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID if (!type.empty()) { typeQuery.bind(1, typeString.c_str()); - typeQuery.bind(2, (int) effectId); + typeQuery.bind(2, (int)effectId); result = typeQuery.execQuery(); } else { - idQuery.bind(1, (int) effectId); + idQuery.bind(1, (int)effectId); result = idQuery.execQuery(); } - if (result.eof() || result.fieldIsNull(0)) - { + if (result.eof() || result.fieldIsNull(0)) { return; } const auto name = std::string(result.getStringField(0)); - if (type.empty()) - { + if (type.empty()) { const auto typeResult = result.getStringField(1); type = GeneralUtils::ASCIIToUTF16(typeResult); @@ -395,8 +376,7 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID m_effectNames->insert_or_assign(typeString, name); - if (renderComponent == nullptr) - { + if (renderComponent == nullptr) { GameMessages::SendPlayFXEffect(targetEntity, effectId, type, name, secondary, 1, 1, true); return; @@ -405,8 +385,7 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID renderComponent->PlayEffect(effectId, type, name, secondary); } -Behavior::Behavior(const uint32_t behaviorId) -{ +Behavior::Behavior(const uint32_t behaviorId) { auto behaviorTemplateTable = CDClientManager::Instance()->GetTable("BehaviorTemplate"); CDBehaviorTemplate templateInDatabase{}; @@ -430,8 +409,7 @@ Behavior::Behavior(const uint32_t behaviorId) } // Make sure we do not proceed if we are trying to load an invalid behavior - if (templateInDatabase.behaviorID == 0) - { + if (templateInDatabase.behaviorID == 0) { Game::logger->Log("Behavior", "Failed to load behavior with id (%i)!", behaviorId); this->m_effectId = 0; @@ -449,40 +427,34 @@ Behavior::Behavior(const uint32_t behaviorId) } -float Behavior::GetFloat(const std::string& name, const float defaultValue) const -{ +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("BehaviorParameter"); return BehaviorParameterTable->GetEntry(this->m_behaviorId, name, defaultValue).value; } -bool Behavior::GetBoolean(const std::string& name, const bool defaultValue) const -{ +bool Behavior::GetBoolean(const std::string& name, const bool defaultValue) const { return GetFloat(name, defaultValue) > 0; } -int32_t Behavior::GetInt(const std::string& name, const int defaultValue) const -{ +int32_t Behavior::GetInt(const std::string& name, const int defaultValue) const { return static_cast(GetFloat(name, defaultValue)); } -Behavior* Behavior::GetAction(const std::string& name) const -{ +Behavior* Behavior::GetAction(const std::string& name) const { const auto id = GetInt(name); return CreateBehavior(id); } -Behavior* Behavior::GetAction(float value) const -{ +Behavior* Behavior::GetAction(float value) const { return CreateBehavior(static_cast(value)); } -std::map Behavior::GetParameterNames() const -{ +std::map Behavior::GetParameterNames() const { std::map templatesInDatabase; // Find behavior template by its behavior id. if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance()->GetTable("BehaviorParameter"); @@ -493,40 +465,31 @@ std::map Behavior::GetParameterNames() const return templatesInDatabase; } -void Behavior::Load() -{ +void Behavior::Load() { } -void Behavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void Behavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -void Behavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void Behavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -void Behavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) -{ +void Behavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { } -void Behavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) -{ +void Behavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { } -void Behavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) -{ +void Behavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { } -void Behavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void Behavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -void Behavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void Behavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -Behavior::~Behavior() -{ +Behavior::~Behavior() { delete m_effectNames; delete m_effectType; delete m_effectHandle; diff --git a/dGame/dBehaviors/Behavior.h b/dGame/dBehaviors/Behavior.h index 34ba469b..bf656e1b 100644 --- a/dGame/dBehaviors/Behavior.h +++ b/dGame/dBehaviors/Behavior.h @@ -31,24 +31,24 @@ public: /* * Utilities */ - + void PlayFx(std::u16string type, LWOOBJID target, LWOOBJID secondary = LWOOBJID_EMPTY); /* * Members */ - + uint32_t m_behaviorId; BehaviorTemplates m_templateId; uint32_t m_effectId; std::string* m_effectHandle = nullptr; std::unordered_map* m_effectNames = nullptr; std::string* m_effectType = nullptr; - + /* * Behavior parameters */ - + float GetFloat(const std::string& name, const float defaultValue = 0) const; bool GetBoolean(const std::string& name, const bool defaultValue = false) const; @@ -60,7 +60,7 @@ public: Behavior* GetAction(float value) const; std::map GetParameterNames() const; - + /* * Virtual */ @@ -69,15 +69,15 @@ public: // Player side virtual void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); - + virtual void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); virtual void UnCast(BehaviorContext* context, BehaviorBranchContext branch); virtual void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second); - + virtual void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second); - + // Npc side virtual void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); @@ -86,7 +86,7 @@ public: /* * Creations/destruction */ - + explicit Behavior(uint32_t behaviorId); virtual ~Behavior(); }; diff --git a/dGame/dBehaviors/BehaviorBranchContext.cpp b/dGame/dBehaviors/BehaviorBranchContext.cpp index 91791d89..7793eb54 100644 --- a/dGame/dBehaviors/BehaviorBranchContext.cpp +++ b/dGame/dBehaviors/BehaviorBranchContext.cpp @@ -1,13 +1,11 @@ #include "BehaviorBranchContext.h" -BehaviorBranchContext::BehaviorBranchContext() -{ +BehaviorBranchContext::BehaviorBranchContext() { this->isProjectile = false; } -BehaviorBranchContext::BehaviorBranchContext(const LWOOBJID target, const float duration, const NiPoint3& referencePosition) -{ +BehaviorBranchContext::BehaviorBranchContext(const LWOOBJID target, const float duration, const NiPoint3& referencePosition) { this->target = target; this->duration = duration; this->referencePosition = referencePosition; diff --git a/dGame/dBehaviors/BehaviorBranchContext.h b/dGame/dBehaviors/BehaviorBranchContext.h index bd4e6722..dfd76fad 100644 --- a/dGame/dBehaviors/BehaviorBranchContext.h +++ b/dGame/dBehaviors/BehaviorBranchContext.h @@ -6,9 +6,9 @@ struct BehaviorBranchContext { LWOOBJID target = LWOOBJID_EMPTY; - + float duration = 0; - + NiPoint3 referencePosition = {}; bool isProjectile = false; @@ -16,6 +16,6 @@ struct BehaviorBranchContext uint32_t start = 0; BehaviorBranchContext(); - + BehaviorBranchContext(LWOOBJID target, float duration = 0, const NiPoint3& referencePosition = NiPoint3(0, 0, 0)); }; diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index 87e63a59..54325bac 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -15,24 +15,19 @@ #include "PhantomPhysicsComponent.h" #include "RebuildComponent.h" -BehaviorSyncEntry::BehaviorSyncEntry() -{ +BehaviorSyncEntry::BehaviorSyncEntry() { } -BehaviorTimerEntry::BehaviorTimerEntry() -{ +BehaviorTimerEntry::BehaviorTimerEntry() { } -BehaviorEndEntry::BehaviorEndEntry() -{ +BehaviorEndEntry::BehaviorEndEntry() { } -uint32_t BehaviorContext::GetUniqueSkillId() const -{ +uint32_t BehaviorContext::GetUniqueSkillId() const { auto* entity = EntityManager::Instance()->GetEntity(this->originator); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("BehaviorContext", "Invalid entity for (%llu)!", this->originator); return 0; @@ -40,8 +35,7 @@ uint32_t BehaviorContext::GetUniqueSkillId() const auto* component = entity->GetComponent(); - if (component == nullptr) - { + if (component == nullptr) { Game::logger->Log("BehaviorContext", "No skill component attached to (%llu)!", this->originator);; return 0; @@ -51,8 +45,7 @@ uint32_t BehaviorContext::GetUniqueSkillId() const } -void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext) -{ +void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext) { auto entry = BehaviorSyncEntry(); entry.handle = syncId; @@ -62,8 +55,7 @@ void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* beha this->syncEntries.push_back(entry); } -void BehaviorContext::RegisterTimerBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, const LWOOBJID second) -{ +void BehaviorContext::RegisterTimerBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, const LWOOBJID second) { BehaviorTimerEntry entry; entry.time = branchContext.duration; @@ -74,8 +66,7 @@ void BehaviorContext::RegisterTimerBehavior(Behavior* behavior, const BehaviorBr this->timerEntries.push_back(entry); } -void BehaviorContext::RegisterEndBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, const LWOOBJID second) -{ +void BehaviorContext::RegisterEndBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, const LWOOBJID second) { BehaviorEndEntry entry; entry.behavior = behavior; @@ -86,20 +77,16 @@ void BehaviorContext::RegisterEndBehavior(Behavior* behavior, const BehaviorBran this->endEntries.push_back(entry); } -void BehaviorContext::ScheduleUpdate(const LWOOBJID id) -{ - if (std::find(this->scheduledUpdates.begin(), this->scheduledUpdates.end(), id) != this->scheduledUpdates.end()) - { +void BehaviorContext::ScheduleUpdate(const LWOOBJID id) { + if (std::find(this->scheduledUpdates.begin(), this->scheduledUpdates.end(), id) != this->scheduledUpdates.end()) { return; } this->scheduledUpdates.push_back(id); } -void BehaviorContext::ExecuteUpdates() -{ - for (const auto& id : this->scheduledUpdates) - { +void BehaviorContext::ExecuteUpdates() { + for (const auto& id : this->scheduledUpdates) { auto* entity = EntityManager::Instance()->GetEntity(id); if (entity == nullptr) continue; @@ -110,20 +97,17 @@ void BehaviorContext::ExecuteUpdates() this->scheduledUpdates.clear(); } -void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bitStream) -{ +void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bitStream) { BehaviorSyncEntry entry; auto found = false; /* * There may be more than one of each handle */ - for (auto i = 0u; i < this->syncEntries.size(); ++i) - { + for (auto i = 0u; i < this->syncEntries.size(); ++i) { const auto syncEntry = this->syncEntries.at(i); - if (syncEntry.handle == syncId) - { + if (syncEntry.handle == syncId) { found = true; entry = syncEntry; @@ -133,8 +117,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bit } } - if (!found) - { + if (!found) { Game::logger->Log("BehaviorContext", "Failed to find behavior sync entry with sync id (%i)!", syncId); return; @@ -143,8 +126,7 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bit auto* behavior = entry.behavior; const auto branch = entry.branchContext; - if (behavior == nullptr) - { + if (behavior == nullptr) { Game::logger->Log("BehaviorContext", "Invalid behavior for sync id (%i)!", syncId); return; @@ -154,21 +136,17 @@ void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bit } -void BehaviorContext::Update(const float deltaTime) -{ - for (auto i = 0u; i < this->timerEntries.size(); ++i) - { +void BehaviorContext::Update(const float deltaTime) { + for (auto i = 0u; i < this->timerEntries.size(); ++i) { auto entry = this->timerEntries.at(i); - if (entry.time > 0) - { + if (entry.time > 0) { entry.time -= deltaTime; this->timerEntries[i] = entry; } - if (entry.time > 0) - { + if (entry.time > 0) { continue; } @@ -177,10 +155,8 @@ void BehaviorContext::Update(const float deltaTime) std::vector valid; - for (const auto& entry : this->timerEntries) - { - if (entry.time <= 0) - { + for (const auto& entry : this->timerEntries) { + if (entry.time <= 0) { continue; } @@ -191,8 +167,7 @@ void BehaviorContext::Update(const float deltaTime) } -void BehaviorContext::SyncCalculation(const uint32_t syncId, const float time, Behavior* behavior, const BehaviorBranchContext& branch, const bool ignoreInterrupts) -{ +void BehaviorContext::SyncCalculation(const uint32_t syncId, const float time, Behavior* behavior, const BehaviorBranchContext& branch, const bool ignoreInterrupts) { BehaviorSyncEntry entry; entry.behavior = behavior; @@ -204,14 +179,11 @@ void BehaviorContext::SyncCalculation(const uint32_t syncId, const float time, B this->syncEntries.push_back(entry); } -void BehaviorContext::InvokeEnd(const uint32_t id) -{ +void BehaviorContext::InvokeEnd(const uint32_t id) { std::vector entries; - for (const auto& entry : this->endEntries) - { - if (entry.start == id) - { + for (const auto& entry : this->endEntries) { + if (entry.start == id) { entry.behavior->End(this, entry.branchContext, entry.second); continue; @@ -223,23 +195,19 @@ void BehaviorContext::InvokeEnd(const uint32_t id) this->endEntries = entries; } -bool BehaviorContext::CalculateUpdate(const float deltaTime) -{ +bool BehaviorContext::CalculateUpdate(const float deltaTime) { auto any = false; - for (auto i = 0u; i < this->syncEntries.size(); ++i) - { + for (auto i = 0u; i < this->syncEntries.size(); ++i) { auto entry = this->syncEntries.at(i); - if (entry.time > 0) - { + if (entry.time > 0) { entry.time -= deltaTime; this->syncEntries[i] = entry; } - if (entry.time > 0) - { + if (entry.time > 0) { any = true; continue; @@ -257,9 +225,8 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) // Calculate sync entry.behavior->SyncCalculation(this, bitStream, entry.branchContext); - if (!clientInitalized) - { - echo.sBitStream.assign((char*) bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); + if (!clientInitalized) { + echo.sBitStream.assign((char*)bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); // Write message RakNet::BitStream message; @@ -278,10 +245,8 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) std::vector valid; - for (const auto& entry : this->syncEntries) - { - if (entry.time <= 0) - { + for (const auto& entry : this->syncEntries) { + if (entry.time <= 0) { continue; } @@ -293,12 +258,10 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) return any; } -void BehaviorContext::Interrupt() -{ - std::vector keptSync {}; +void BehaviorContext::Interrupt() { + std::vector keptSync{}; - for (const auto& entry : this->syncEntries) - { + for (const auto& entry : this->syncEntries) { if (!entry.ignoreInterrupts) continue; keptSync.push_back(entry); @@ -307,15 +270,12 @@ void BehaviorContext::Interrupt() this->syncEntries = keptSync; } -void BehaviorContext::Reset() -{ - for (const auto& entry : this->timerEntries) - { +void BehaviorContext::Reset() { + for (const auto& entry : this->timerEntries) { entry.behavior->Timer(this, entry.branchContext, entry.second); } - for (const auto& entry : this->endEntries) - { + for (const auto& entry : this->endEntries) { entry.behavior->End(this, entry.branchContext, entry.second); } @@ -325,27 +285,22 @@ void BehaviorContext::Reset() this->scheduledUpdates.clear(); } -std::vector BehaviorContext::GetValidTargets(int32_t ignoreFaction, int32_t includeFaction, bool targetSelf, bool targetEnemy, bool targetFriend) const -{ +std::vector BehaviorContext::GetValidTargets(int32_t ignoreFaction, int32_t includeFaction, bool targetSelf, bool targetEnemy, bool targetFriend) const { auto* entity = EntityManager::Instance()->GetEntity(this->caster); std::vector targets; - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("BehaviorContext", "Invalid entity for (%llu)!", this->originator); return targets; } - if (!ignoreFaction && !includeFaction) - { - for (auto entry : entity->GetTargetsInPhantom()) - { + if (!ignoreFaction && !includeFaction) { + for (auto entry : entity->GetTargetsInPhantom()) { auto* instance = EntityManager::Instance()->GetEntity(entry); - if (instance == nullptr) - { + if (instance == nullptr) { continue; } @@ -353,21 +308,17 @@ std::vector BehaviorContext::GetValidTargets(int32_t ignoreFaction, in } } - if (ignoreFaction || includeFaction || (!entity->HasComponent(COMPONENT_TYPE_PHANTOM_PHYSICS) && targets.empty())) - { - DestroyableComponent* destroyableComponent; - if (!entity->TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) - { + if (ignoreFaction || includeFaction || (!entity->HasComponent(COMPONENT_TYPE_PHANTOM_PHYSICS) && targets.empty())) { + DestroyableComponent* destroyableComponent; + if (!entity->TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) { return targets; } auto entities = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS); - for (auto* candidate : entities) - { + for (auto* candidate : entities) { const auto id = candidate->GetObjectID(); - if ((id != entity->GetObjectID() || targetSelf) && destroyableComponent->CheckValidity(id, ignoreFaction || includeFaction, targetEnemy, targetFriend)) - { + if ((id != entity->GetObjectID() || targetSelf) && destroyableComponent->CheckValidity(id, ignoreFaction || includeFaction, targetEnemy, targetFriend)) { targets.push_back(id); } } @@ -377,23 +328,18 @@ std::vector BehaviorContext::GetValidTargets(int32_t ignoreFaction, in } -BehaviorContext::BehaviorContext(const LWOOBJID originator, const bool calculation) -{ +BehaviorContext::BehaviorContext(const LWOOBJID originator, const bool calculation) { this->originator = originator; this->syncEntries = {}; this->timerEntries = {}; - if (calculation) - { + if (calculation) { this->skillUId = GetUniqueSkillId(); - } - else - { + } else { this->skillUId = 0; } } -BehaviorContext::~BehaviorContext() -{ +BehaviorContext::~BehaviorContext() { Reset(); } diff --git a/dGame/dBehaviors/BehaviorContext.h b/dGame/dBehaviors/BehaviorContext.h index f27889f1..af8e66b4 100644 --- a/dGame/dBehaviors/BehaviorContext.h +++ b/dGame/dBehaviors/BehaviorContext.h @@ -16,7 +16,7 @@ struct BehaviorSyncEntry float time = 0; bool ignoreInterrupts = false; - + Behavior* behavior = nullptr; BehaviorBranchContext branchContext; @@ -46,7 +46,7 @@ struct BehaviorEndEntry BehaviorBranchContext branchContext; LWOOBJID second = LWOOBJID_EMPTY; - + BehaviorEndEntry(); }; @@ -65,11 +65,11 @@ struct BehaviorContext bool failed = false; bool clientInitalized = false; - + std::vector syncEntries; - + std::vector timerEntries; - + std::vector endEntries; std::vector scheduledUpdates; @@ -89,15 +89,15 @@ struct BehaviorContext void ScheduleUpdate(LWOOBJID id); void ExecuteUpdates(); - + void SyncBehavior(uint32_t syncId, RakNet::BitStream* bitStream); void Update(float deltaTime); - + void SyncCalculation(uint32_t syncId, float time, Behavior* behavior, const BehaviorBranchContext& branch, bool ignoreInterrupts = false); void InvokeEnd(uint32_t id); - + bool CalculateUpdate(float deltaTime); void Interrupt(); @@ -105,7 +105,7 @@ struct BehaviorContext void Reset(); std::vector GetValidTargets(int32_t ignoreFaction = 0, int32_t includeFaction = 0, const bool targetSelf = false, const bool targetEnemy = true, const bool targetFriend = false) const; - + explicit BehaviorContext(LWOOBJID originator, bool calculation = false); ~BehaviorContext(); diff --git a/dGame/dBehaviors/BehaviorTemplates.h b/dGame/dBehaviors/BehaviorTemplates.h index 04c15fc0..af7ab376 100644 --- a/dGame/dBehaviors/BehaviorTemplates.h +++ b/dGame/dBehaviors/BehaviorTemplates.h @@ -67,4 +67,4 @@ enum class BehaviorTemplates : unsigned int { BEHAVIOR_TAKE_PICTURE, BEHAVIOR_MOUNT, BEHAVIOR_SKILL_SET -}; \ No newline at end of file +}; diff --git a/dGame/dBehaviors/BlockBehavior.cpp b/dGame/dBehaviors/BlockBehavior.cpp index 13012f98..25650b2a 100644 --- a/dGame/dBehaviors/BlockBehavior.cpp +++ b/dGame/dBehaviors/BlockBehavior.cpp @@ -7,14 +7,12 @@ #include "dLogger.h" #include "DestroyableComponent.h" -void BlockBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void BlockBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto target = context->originator; auto* entity = EntityManager::Instance()->GetEntity(target); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -22,36 +20,29 @@ void BlockBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea auto* destroyableComponent = entity->GetComponent(); - if (destroyableComponent == nullptr) - { + if (destroyableComponent == nullptr) { return; } destroyableComponent->SetAttacksToBlock(this->m_numAttacksCanBlock); - if (branch.start > 0) - { + if (branch.start > 0) { context->RegisterEndBehavior(this, branch); - } - else if (branch.duration > 0) - { + } else if (branch.duration > 0) { context->RegisterTimerBehavior(this, branch); } } -void BlockBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void BlockBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } -void BlockBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) -{ +void BlockBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { const auto target = context->originator; auto* entity = EntityManager::Instance()->GetEntity(target); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -61,25 +52,21 @@ void BlockBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branc destroyableComponent->SetAttacksToBlock(this->m_numAttacksCanBlock); - if (destroyableComponent == nullptr) - { + if (destroyableComponent == nullptr) { return; } destroyableComponent->SetAttacksToBlock(0); } -void BlockBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) -{ +void BlockBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { UnCast(context, branch); } -void BlockBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) -{ +void BlockBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { UnCast(context, branch); } -void BlockBehavior::Load() -{ +void BlockBehavior::Load() { this->m_numAttacksCanBlock = GetInt("num_attacks_can_block"); } diff --git a/dGame/dBehaviors/BlockBehavior.h b/dGame/dBehaviors/BlockBehavior.h index 5de3d309..139fa0af 100644 --- a/dGame/dBehaviors/BlockBehavior.h +++ b/dGame/dBehaviors/BlockBehavior.h @@ -5,13 +5,12 @@ class BlockBehavior final : public Behavior { public: int32_t m_numAttacksCanBlock; - + /* * Inherited */ - explicit BlockBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit BlockBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; @@ -19,10 +18,10 @@ public: void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; - + void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/BuffBehavior.cpp b/dGame/dBehaviors/BuffBehavior.cpp index 09b70e03..8bd14529 100644 --- a/dGame/dBehaviors/BuffBehavior.cpp +++ b/dGame/dBehaviors/BuffBehavior.cpp @@ -7,14 +7,12 @@ #include "dLogger.h" #include "DestroyableComponent.h" -void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator; auto* entity = EntityManager::Instance()->GetEntity(target); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("BuffBehavior", "Invalid target (%llu)!", target); return; @@ -22,8 +20,7 @@ void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream auto* component = entity->GetComponent(); - if (component == nullptr) - { + if (component == nullptr) { Game::logger->Log("BuffBehavior", "Invalid target, no destroyable component (%llu)!", target); return; @@ -35,27 +32,21 @@ void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream EntityManager::Instance()->SerializeEntity(entity); - if (!context->unmanaged) - { - if (branch.duration > 0) - { + if (!context->unmanaged) { + if (branch.duration > 0) { context->RegisterTimerBehavior(this, branch); - } - else if (branch.start > 0) - { + } else if (branch.start > 0) { context->RegisterEndBehavior(this, branch); } } } -void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) -{ +void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator; auto* entity = EntityManager::Instance()->GetEntity(target); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("BuffBehavior", "Invalid target (%llu)!", target); return; @@ -63,8 +54,7 @@ void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch auto* component = entity->GetComponent(); - if (component == nullptr) - { + if (component == nullptr) { Game::logger->Log("BuffBehavior", "Invalid target, no destroyable component (%llu)!", target); return; @@ -77,18 +67,15 @@ void BuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch EntityManager::Instance()->SerializeEntity(entity); } -void BuffBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext branch, LWOOBJID second) -{ +void BuffBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext branch, LWOOBJID second) { UnCast(context, branch); } -void BuffBehavior::End(BehaviorContext* context, const BehaviorBranchContext branch, LWOOBJID second) -{ +void BuffBehavior::End(BehaviorContext* context, const BehaviorBranchContext branch, LWOOBJID second) { UnCast(context, branch); } -void BuffBehavior::Load() -{ +void BuffBehavior::Load() { this->m_health = GetInt("life"); this->m_armor = GetInt("armor"); diff --git a/dGame/dBehaviors/BuffBehavior.h b/dGame/dBehaviors/BuffBehavior.h index cfb26aef..ffc853fa 100644 --- a/dGame/dBehaviors/BuffBehavior.h +++ b/dGame/dBehaviors/BuffBehavior.h @@ -9,12 +9,11 @@ public: uint32_t m_armor; uint32_t m_imagination; - + /* * Inherited */ - explicit BuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit BuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; @@ -24,6 +23,6 @@ public: void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/CarBoostBehavior.cpp b/dGame/dBehaviors/CarBoostBehavior.cpp index adfae01b..1ab0af95 100644 --- a/dGame/dBehaviors/CarBoostBehavior.cpp +++ b/dGame/dBehaviors/CarBoostBehavior.cpp @@ -8,44 +8,41 @@ #include "dLogger.h" #include "PossessableComponent.h" -void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - GameMessages::SendVehicleAddPassiveBoostAction(branch.target, UNASSIGNED_SYSTEM_ADDRESS); +void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + GameMessages::SendVehicleAddPassiveBoostAction(branch.target, UNASSIGNED_SYSTEM_ADDRESS); - auto* entity = EntityManager::Instance()->GetEntity(context->originator); + auto* entity = EntityManager::Instance()->GetEntity(context->originator); - if (entity == nullptr) - { - return; - } + if (entity == nullptr) { + return; + } - Game::logger->Log("Car boost", "Activating car boost!"); + Game::logger->Log("Car boost", "Activating car boost!"); - auto* possessableComponent = entity->GetComponent(); - if (possessableComponent != nullptr) { + auto* possessableComponent = entity->GetComponent(); + if (possessableComponent != nullptr) { - auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (possessor != nullptr) { + auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); + if (possessor != nullptr) { - auto* characterComponent = possessor->GetComponent(); - if (characterComponent != nullptr) { - Game::logger->Log("Car boost", "Tracking car boost!"); - characterComponent->UpdatePlayerStatistic(RacingCarBoostsActivated); - } - } - } + auto* characterComponent = possessor->GetComponent(); + if (characterComponent != nullptr) { + Game::logger->Log("Car boost", "Tracking car boost!"); + characterComponent->UpdatePlayerStatistic(RacingCarBoostsActivated); + } + } + } - m_Action->Handle(context, bitStream, branch); + m_Action->Handle(context, bitStream, branch); - entity->AddCallbackTimer(m_Time, [entity] () { - GameMessages::SendVehicleRemovePassiveBoostAction(entity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - }); + entity->AddCallbackTimer(m_Time, [entity]() { + GameMessages::SendVehicleRemovePassiveBoostAction(entity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + }); } -void CarBoostBehavior::Load() -{ - m_Action = GetAction("action"); +void CarBoostBehavior::Load() { + m_Action = GetAction("action"); - m_Time = GetFloat("time"); + m_Time = GetFloat("time"); } diff --git a/dGame/dBehaviors/CarBoostBehavior.h b/dGame/dBehaviors/CarBoostBehavior.h index 32eb00c8..3f4265b9 100644 --- a/dGame/dBehaviors/CarBoostBehavior.h +++ b/dGame/dBehaviors/CarBoostBehavior.h @@ -14,10 +14,9 @@ public: * Inherited */ - explicit CarBoostBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit CarBoostBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/ChainBehavior.cpp b/dGame/dBehaviors/ChainBehavior.cpp index 0d49de82..df8b223f 100644 --- a/dGame/dBehaviors/ChainBehavior.cpp +++ b/dGame/dBehaviors/ChainBehavior.cpp @@ -3,35 +3,29 @@ #include "Game.h" #include "dLogger.h" -void ChainBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void ChainBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { uint32_t chain_index; bitStream->Read(chain_index); chain_index--; - if (chain_index < this->m_behaviors.size()) - { + if (chain_index < this->m_behaviors.size()) { this->m_behaviors.at(chain_index)->Handle(context, bitStream, branch); } } -void ChainBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void ChainBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { bitStream->Write(1); this->m_behaviors.at(0)->Calculate(context, bitStream, branch); } -void ChainBehavior::Load() -{ +void ChainBehavior::Load() { const auto parameters = GetParameterNames(); - for (const auto& parameter : parameters) - { - if (parameter.first.rfind("behavior", 0) == 0) - { + for (const auto& parameter : parameters) { + if (parameter.first.rfind("behavior", 0) == 0) { auto* action = GetAction(parameter.second); this->m_behaviors.push_back(action); diff --git a/dGame/dBehaviors/ChainBehavior.h b/dGame/dBehaviors/ChainBehavior.h index 733707dc..626ecbe3 100644 --- a/dGame/dBehaviors/ChainBehavior.h +++ b/dGame/dBehaviors/ChainBehavior.h @@ -13,10 +13,9 @@ public: * Inherited */ - explicit ChainBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ChainBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/ChangeOrientationBehavior.cpp b/dGame/dBehaviors/ChangeOrientationBehavior.cpp index 60dcf2ac..a60be62f 100644 --- a/dGame/dBehaviors/ChangeOrientationBehavior.cpp +++ b/dGame/dBehaviors/ChangeOrientationBehavior.cpp @@ -4,47 +4,41 @@ #include "EntityManager.h" #include "BaseCombatAIComponent.h" -void ChangeOrientationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ChangeOrientationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -void ChangeOrientationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - if (!m_ToTarget) return; // TODO: Add the other arguments to this behavior +void ChangeOrientationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + if (!m_ToTarget) return; // TODO: Add the other arguments to this behavior - auto* self = EntityManager::Instance()->GetEntity(context->originator); - auto* other = EntityManager::Instance()->GetEntity(branch.target); + auto* self = EntityManager::Instance()->GetEntity(context->originator); + auto* other = EntityManager::Instance()->GetEntity(branch.target); - if (self == nullptr || other == nullptr) return; + if (self == nullptr || other == nullptr) return; - const auto source = self->GetPosition(); - const auto destination = self->GetPosition(); + const auto source = self->GetPosition(); + const auto destination = self->GetPosition(); - if (m_OrientCaster) - { - auto* baseCombatAIComponent = self->GetComponent(); + if (m_OrientCaster) { + auto* baseCombatAIComponent = self->GetComponent(); - /*if (baseCombatAIComponent != nullptr) - { - baseCombatAIComponent->LookAt(destination); - } - else*/ - { - self->SetRotation(NiQuaternion::LookAt(source, destination)); - } + /*if (baseCombatAIComponent != nullptr) + { + baseCombatAIComponent->LookAt(destination); + } + else*/ + { + self->SetRotation(NiQuaternion::LookAt(source, destination)); + } - EntityManager::Instance()->SerializeEntity(self); - } - else - { - other->SetRotation(NiQuaternion::LookAt(destination, source)); + EntityManager::Instance()->SerializeEntity(self); + } else { + other->SetRotation(NiQuaternion::LookAt(destination, source)); - EntityManager::Instance()->SerializeEntity(other); - } + EntityManager::Instance()->SerializeEntity(other); + } } -void ChangeOrientationBehavior::Load() -{ - m_OrientCaster = GetBoolean("orient_caster"); - m_ToTarget = GetBoolean("to_target"); +void ChangeOrientationBehavior::Load() { + m_OrientCaster = GetBoolean("orient_caster"); + m_ToTarget = GetBoolean("to_target"); } diff --git a/dGame/dBehaviors/ChangeOrientationBehavior.h b/dGame/dBehaviors/ChangeOrientationBehavior.h index 960ec8ea..eb038ffb 100644 --- a/dGame/dBehaviors/ChangeOrientationBehavior.h +++ b/dGame/dBehaviors/ChangeOrientationBehavior.h @@ -7,17 +7,16 @@ class ChangeOrientationBehavior final : public Behavior { public: - bool m_OrientCaster; - bool m_ToTarget; + bool m_OrientCaster; + bool m_ToTarget; /* * Inherited */ - explicit ChangeOrientationBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ChangeOrientationBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/ChargeUpBehavior.cpp b/dGame/dBehaviors/ChargeUpBehavior.cpp index c9259801..5fc9822e 100644 --- a/dGame/dBehaviors/ChargeUpBehavior.cpp +++ b/dGame/dBehaviors/ChargeUpBehavior.cpp @@ -3,8 +3,7 @@ #include "BehaviorContext.h" #include "dLogger.h" -void ChargeUpBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void ChargeUpBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { uint32_t handle; bitStream->Read(handle); @@ -12,16 +11,13 @@ void ChargeUpBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt context->RegisterSyncBehavior(handle, this, branch); } -void ChargeUpBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ChargeUpBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -void ChargeUpBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void ChargeUpBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { this->m_action->Handle(context, bitStream, branch); } -void ChargeUpBehavior::Load() -{ +void ChargeUpBehavior::Load() { this->m_action = GetAction("action"); } diff --git a/dGame/dBehaviors/ChargeUpBehavior.h b/dGame/dBehaviors/ChargeUpBehavior.h index f9c8d30a..a80026c5 100644 --- a/dGame/dBehaviors/ChargeUpBehavior.h +++ b/dGame/dBehaviors/ChargeUpBehavior.h @@ -5,13 +5,12 @@ class ChargeUpBehavior final : public Behavior { public: Behavior* m_action; - + /* * Inherited */ - explicit ChargeUpBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ChargeUpBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; @@ -19,6 +18,6 @@ public: void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/ClearTargetBehavior.cpp b/dGame/dBehaviors/ClearTargetBehavior.cpp index 3428e754..e37161f3 100644 --- a/dGame/dBehaviors/ClearTargetBehavior.cpp +++ b/dGame/dBehaviors/ClearTargetBehavior.cpp @@ -3,23 +3,20 @@ #include "BehaviorContext.h" -void ClearTargetBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ClearTargetBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { branch.target = LWOOBJID_EMPTY; this->m_action->Handle(context, bitStream, branch); } -void ClearTargetBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ClearTargetBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { branch.target = LWOOBJID_EMPTY; this->m_action->Calculate(context, bitStream, branch); } -void ClearTargetBehavior::Load() -{ +void ClearTargetBehavior::Load() { this->m_action = GetAction("action"); - + this->m_clearIfCaster = GetBoolean("clear_if_caster"); } diff --git a/dGame/dBehaviors/ClearTargetBehavior.h b/dGame/dBehaviors/ClearTargetBehavior.h index ccb631a4..e1235eea 100644 --- a/dGame/dBehaviors/ClearTargetBehavior.h +++ b/dGame/dBehaviors/ClearTargetBehavior.h @@ -7,12 +7,11 @@ public: Behavior* m_action; bool m_clearIfCaster; - + /* * Inherited */ - explicit ClearTargetBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ClearTargetBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp index f02c4eea..4f4e5b81 100644 --- a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp +++ b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp @@ -7,12 +7,10 @@ #include "dLogger.h" #include "DestroyableComponent.h" -void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -20,8 +18,7 @@ void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStrea auto* destroyable = target->GetComponent(); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } @@ -32,17 +29,14 @@ void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStrea context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void DamageAbsorptionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void DamageAbsorptionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } -void DamageAbsorptionBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) -{ +void DamageAbsorptionBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) { auto* target = EntityManager::Instance()->GetEntity(second); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", second); return; @@ -50,8 +44,7 @@ void DamageAbsorptionBehavior::Timer(BehaviorContext* context, BehaviorBranchCon auto* destroyable = target->GetComponent(); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } @@ -62,7 +55,6 @@ void DamageAbsorptionBehavior::Timer(BehaviorContext* context, BehaviorBranchCon destroyable->SetDamageToAbsorb(present - toRemove); } -void DamageAbsorptionBehavior::Load() -{ +void DamageAbsorptionBehavior::Load() { this->m_absorbAmount = GetInt("absorb_amount"); } diff --git a/dGame/dBehaviors/DamageAbsorptionBehavior.h b/dGame/dBehaviors/DamageAbsorptionBehavior.h index 34b564a5..533fe554 100644 --- a/dGame/dBehaviors/DamageAbsorptionBehavior.h +++ b/dGame/dBehaviors/DamageAbsorptionBehavior.h @@ -5,13 +5,12 @@ class DamageAbsorptionBehavior final : public Behavior { public: uint32_t m_absorbAmount; - + /* * Inherited */ - explicit DamageAbsorptionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit DamageAbsorptionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/DamageReductionBehavior.cpp b/dGame/dBehaviors/DamageReductionBehavior.cpp index 45a30975..2b18b7c2 100644 --- a/dGame/dBehaviors/DamageReductionBehavior.cpp +++ b/dGame/dBehaviors/DamageReductionBehavior.cpp @@ -7,12 +7,10 @@ #include "dLogger.h" #include "DestroyableComponent.h" -void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("DamageReductionBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -20,8 +18,7 @@ void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream auto* destroyable = target->GetComponent(); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } @@ -30,17 +27,14 @@ void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void DamageReductionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void DamageReductionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } -void DamageReductionBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) -{ +void DamageReductionBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) { auto* target = EntityManager::Instance()->GetEntity(second); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("DamageReductionBehavior", "Failed to find target (%llu)!", second); return; @@ -48,15 +42,13 @@ void DamageReductionBehavior::Timer(BehaviorContext* context, BehaviorBranchCont auto* destroyable = target->GetComponent(); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } destroyable->SetDamageReduction(0); } -void DamageReductionBehavior::Load() -{ +void DamageReductionBehavior::Load() { this->m_ReductionAmount = GetInt("reduction_amount"); } diff --git a/dGame/dBehaviors/DamageReductionBehavior.h b/dGame/dBehaviors/DamageReductionBehavior.h index 8881b88d..bddd31fb 100644 --- a/dGame/dBehaviors/DamageReductionBehavior.h +++ b/dGame/dBehaviors/DamageReductionBehavior.h @@ -5,13 +5,12 @@ class DamageReductionBehavior final : public Behavior { public: uint32_t m_ReductionAmount; - + /* * Inherited */ - explicit DamageReductionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit DamageReductionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/DurationBehavior.cpp b/dGame/dBehaviors/DurationBehavior.cpp index 1f95d7d4..6fc1b4d9 100644 --- a/dGame/dBehaviors/DurationBehavior.cpp +++ b/dGame/dBehaviors/DurationBehavior.cpp @@ -2,22 +2,19 @@ #include "BehaviorBranchContext.h" #include "BehaviorContext.h" -void DurationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void DurationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { branch.duration = this->m_duration; this->m_action->Handle(context, bitStream, branch); } -void DurationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void DurationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { branch.duration = this->m_duration; this->m_action->Calculate(context, bitStream, branch); } -void DurationBehavior::Load() -{ +void DurationBehavior::Load() { this->m_duration = GetFloat("duration"); this->m_action = GetAction("action"); diff --git a/dGame/dBehaviors/DurationBehavior.h b/dGame/dBehaviors/DurationBehavior.h index 82bc3230..b8533700 100644 --- a/dGame/dBehaviors/DurationBehavior.h +++ b/dGame/dBehaviors/DurationBehavior.h @@ -7,11 +7,10 @@ public: float m_duration; Behavior* m_action; - - explicit DurationBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + + explicit DurationBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/EmptyBehavior.h b/dGame/dBehaviors/EmptyBehavior.h index f3f6a77f..64990ec4 100644 --- a/dGame/dBehaviors/EmptyBehavior.h +++ b/dGame/dBehaviors/EmptyBehavior.h @@ -5,7 +5,6 @@ class EmptyBehavior final : public Behavior { public: - explicit EmptyBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit EmptyBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } }; diff --git a/dGame/dBehaviors/EndBehavior.cpp b/dGame/dBehaviors/EndBehavior.cpp index 4e7b8351..bf35932f 100644 --- a/dGame/dBehaviors/EndBehavior.cpp +++ b/dGame/dBehaviors/EndBehavior.cpp @@ -3,17 +3,14 @@ #include "BehaviorContext.h" #include "BehaviorBranchContext.h" -void EndBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void EndBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { context->InvokeEnd(this->m_startBehavior); } -void EndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void EndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { context->InvokeEnd(this->m_startBehavior); } -void EndBehavior::Load() -{ +void EndBehavior::Load() { this->m_startBehavior = GetInt("start_action"); } diff --git a/dGame/dBehaviors/EndBehavior.h b/dGame/dBehaviors/EndBehavior.h index afa539ce..8503f7ba 100644 --- a/dGame/dBehaviors/EndBehavior.h +++ b/dGame/dBehaviors/EndBehavior.h @@ -5,17 +5,16 @@ class EndBehavior final : public Behavior { public: uint32_t m_startBehavior; - + /* * Inherited */ - explicit EndBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit EndBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/ForceMovementBehavior.cpp b/dGame/dBehaviors/ForceMovementBehavior.cpp index ea8c04a7..8074dbcc 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.cpp +++ b/dGame/dBehaviors/ForceMovementBehavior.cpp @@ -5,77 +5,75 @@ #include "EntityManager.h" void ForceMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { - if (this->m_hitAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitEnemyAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitFactionAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { - return; - } + if (this->m_hitAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitEnemyAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitFactionAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { + return; + } - uint32_t handle; - bitStream->Read(handle); - context->RegisterSyncBehavior(handle, this, branch); + uint32_t handle; + bitStream->Read(handle); + context->RegisterSyncBehavior(handle, this, branch); } -void ForceMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - uint32_t next; - bitStream->Read(next); +void ForceMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + uint32_t next; + bitStream->Read(next); - LWOOBJID target; - bitStream->Read(target); + LWOOBJID target; + bitStream->Read(target); - branch.target = target; - auto* behavior = CreateBehavior(next); - behavior->Handle(context, bitStream, branch); + branch.target = target; + auto* behavior = CreateBehavior(next); + behavior->Handle(context, bitStream, branch); } void ForceMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - if (this->m_hitAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitEnemyAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitFactionAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { - return; - } + if (this->m_hitAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitEnemyAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitFactionAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { + return; + } - auto* casterEntity = EntityManager::Instance()->GetEntity(context->caster); - if (casterEntity != nullptr) { - auto* controllablePhysicsComponent = casterEntity->GetComponent(); - if (controllablePhysicsComponent != nullptr) { + auto* casterEntity = EntityManager::Instance()->GetEntity(context->caster); + if (casterEntity != nullptr) { + auto* controllablePhysicsComponent = casterEntity->GetComponent(); + if (controllablePhysicsComponent != nullptr) { - if (m_Forward == 1) { - controllablePhysicsComponent->SetVelocity(controllablePhysicsComponent->GetRotation().GetForwardVector() * 25); - } + if (m_Forward == 1) { + controllablePhysicsComponent->SetVelocity(controllablePhysicsComponent->GetRotation().GetForwardVector() * 25); + } - EntityManager::Instance()->SerializeEntity(casterEntity); - } - } + EntityManager::Instance()->SerializeEntity(casterEntity); + } + } - const auto skillHandle = context->GetUniqueSkillId(); - bitStream->Write(skillHandle); + const auto skillHandle = context->GetUniqueSkillId(); + bitStream->Write(skillHandle); - context->SyncCalculation(skillHandle, this->m_Duration, this, branch); + context->SyncCalculation(skillHandle, this->m_Duration, this, branch); } -void ForceMovementBehavior::Load() -{ - this->m_hitAction = GetAction("hit_action"); - this->m_hitEnemyAction = GetAction("hit_action_enemy"); - this->m_hitFactionAction = GetAction("hit_action_faction"); - this->m_Duration = GetFloat("duration"); - this->m_Forward = GetFloat("forward"); - this->m_Left = GetFloat("left"); - this->m_Yaw = GetFloat("yaw"); +void ForceMovementBehavior::Load() { + this->m_hitAction = GetAction("hit_action"); + this->m_hitEnemyAction = GetAction("hit_action_enemy"); + this->m_hitFactionAction = GetAction("hit_action_faction"); + this->m_Duration = GetFloat("duration"); + this->m_Forward = GetFloat("forward"); + this->m_Left = GetFloat("left"); + this->m_Yaw = GetFloat("yaw"); } void ForceMovementBehavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - auto* casterEntity = EntityManager::Instance()->GetEntity(context->caster); - if (casterEntity != nullptr) { - auto* controllablePhysicsComponent = casterEntity->GetComponent(); - if (controllablePhysicsComponent != nullptr) { + auto* casterEntity = EntityManager::Instance()->GetEntity(context->caster); + if (casterEntity != nullptr) { + auto* controllablePhysicsComponent = casterEntity->GetComponent(); + if (controllablePhysicsComponent != nullptr) { - controllablePhysicsComponent->SetPosition(controllablePhysicsComponent->GetPosition() + controllablePhysicsComponent->GetVelocity() * m_Duration); - controllablePhysicsComponent->SetVelocity({}); + controllablePhysicsComponent->SetPosition(controllablePhysicsComponent->GetPosition() + controllablePhysicsComponent->GetVelocity() * m_Duration); + controllablePhysicsComponent->SetVelocity({}); - EntityManager::Instance()->SerializeEntity(casterEntity); - } - } + EntityManager::Instance()->SerializeEntity(casterEntity); + } + } - this->m_hitAction->Calculate(context, bitStream, branch); - this->m_hitEnemyAction->Calculate(context, bitStream, branch); - this->m_hitEnemyAction->Calculate(context, bitStream, branch); + this->m_hitAction->Calculate(context, bitStream, branch); + this->m_hitEnemyAction->Calculate(context, bitStream, branch); + this->m_hitEnemyAction->Calculate(context, bitStream, branch); } diff --git a/dGame/dBehaviors/ForceMovementBehavior.h b/dGame/dBehaviors/ForceMovementBehavior.h index 50b0aa26..26b5ce89 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.h +++ b/dGame/dBehaviors/ForceMovementBehavior.h @@ -10,27 +10,26 @@ public: Behavior* m_hitFactionAction; - float_t m_Duration; - float_t m_Forward; - float_t m_Left; - float_t m_Yaw; - + float_t m_Duration; + float_t m_Forward; + float_t m_Left; + float_t m_Yaw; + /* * Inherited */ - explicit ForceMovementBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ForceMovementBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Calculate(BehaviorContext *context, RakNet::BitStream *bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void SyncCalculation(BehaviorContext *context, RakNet::BitStream *bitStream, BehaviorBranchContext branch) override; + void SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; - + }; diff --git a/dGame/dBehaviors/HealBehavior.cpp b/dGame/dBehaviors/HealBehavior.cpp index 41107203..da0d4a3b 100644 --- a/dGame/dBehaviors/HealBehavior.cpp +++ b/dGame/dBehaviors/HealBehavior.cpp @@ -6,12 +6,10 @@ #include "DestroyableComponent.h" -void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) -{ +void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("HealBehavior", "Failed to find entity for (%llu)!", branch.target); return; @@ -19,8 +17,7 @@ void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_strea auto* destroyable = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { Game::logger->Log("HealBehavior", "Failed to find destroyable component for %(llu)!", branch.target); return; @@ -30,13 +27,11 @@ void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_strea } -void HealBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) -{ +void HealBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { Handle(context, bit_stream, branch); } -void HealBehavior::Load() -{ +void HealBehavior::Load() { this->m_health = GetInt("health"); } diff --git a/dGame/dBehaviors/HealBehavior.h b/dGame/dBehaviors/HealBehavior.h index f5568551..0a719b6c 100644 --- a/dGame/dBehaviors/HealBehavior.h +++ b/dGame/dBehaviors/HealBehavior.h @@ -5,13 +5,12 @@ class HealBehavior final : public Behavior { public: uint32_t m_health; - + /* * Inherited */ - explicit HealBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit HealBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/ImaginationBehavior.cpp b/dGame/dBehaviors/ImaginationBehavior.cpp index d2d50fbe..cf2cd757 100644 --- a/dGame/dBehaviors/ImaginationBehavior.cpp +++ b/dGame/dBehaviors/ImaginationBehavior.cpp @@ -6,19 +6,16 @@ #include "dLogger.h" -void ImaginationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) -{ +void ImaginationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); - if (entity == nullptr) - { + if (entity == nullptr) { return; } auto* destroyable = entity->GetComponent(); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } @@ -26,12 +23,10 @@ void ImaginationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi } -void ImaginationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) -{ +void ImaginationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { Handle(context, bit_stream, branch); } -void ImaginationBehavior::Load() -{ +void ImaginationBehavior::Load() { this->m_imagination = GetInt("imagination"); } diff --git a/dGame/dBehaviors/ImaginationBehavior.h b/dGame/dBehaviors/ImaginationBehavior.h index 52a2c1b3..59d864f9 100644 --- a/dGame/dBehaviors/ImaginationBehavior.h +++ b/dGame/dBehaviors/ImaginationBehavior.h @@ -10,8 +10,7 @@ public: * Inherited */ - explicit ImaginationBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit ImaginationBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/ImmunityBehavior.cpp b/dGame/dBehaviors/ImmunityBehavior.cpp index 4e72ba36..93110cde 100644 --- a/dGame/dBehaviors/ImmunityBehavior.cpp +++ b/dGame/dBehaviors/ImmunityBehavior.cpp @@ -7,12 +7,10 @@ #include "dLogger.h" #include "DestroyableComponent.h" -void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -20,13 +18,11 @@ void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt auto* destroyable = static_cast(target->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } - if (!this->m_immuneBasicAttack) - { + if (!this->m_immuneBasicAttack) { return; } @@ -35,17 +31,14 @@ void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void ImmunityBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ImmunityBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } -void ImmunityBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) -{ +void ImmunityBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) { auto* target = EntityManager::Instance()->GetEntity(second); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", second); return; @@ -53,15 +46,13 @@ void ImmunityBehavior::Timer(BehaviorContext* context, BehaviorBranchContext bra auto* destroyable = static_cast(target->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { return; } destroyable->PopImmunity(); } -void ImmunityBehavior::Load() -{ +void ImmunityBehavior::Load() { this->m_immuneBasicAttack = GetBoolean("immune_basic_attack"); } diff --git a/dGame/dBehaviors/ImmunityBehavior.h b/dGame/dBehaviors/ImmunityBehavior.h index 72ea843b..8a66b3d2 100644 --- a/dGame/dBehaviors/ImmunityBehavior.h +++ b/dGame/dBehaviors/ImmunityBehavior.h @@ -5,13 +5,12 @@ class ImmunityBehavior final : public Behavior { public: uint32_t m_immuneBasicAttack; - + /* * Inherited */ - explicit ImmunityBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit ImmunityBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/InterruptBehavior.cpp b/dGame/dBehaviors/InterruptBehavior.cpp index 559a699d..b0695430 100644 --- a/dGame/dBehaviors/InterruptBehavior.cpp +++ b/dGame/dBehaviors/InterruptBehavior.cpp @@ -7,10 +7,8 @@ #include "SkillComponent.h" -void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - if (branch.target != context->originator) - { +void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + if (branch.target != context->originator) { bool unknown = false; bitStream->Read(unknown); @@ -18,8 +16,7 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS if (unknown) return; } - if (!this->m_interruptBlock) - { + if (!this->m_interruptBlock) { bool unknown = false; bitStream->Read(unknown); @@ -48,15 +45,12 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS } -void InterruptBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - if (branch.target != context->originator) - { +void InterruptBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + if (branch.target != context->originator) { bitStream->Write(false); } - if (!this->m_interruptBlock) - { + if (!this->m_interruptBlock) { bitStream->Write(false); } @@ -71,14 +65,13 @@ void InterruptBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* b auto* skillComponent = target->GetComponent(); if (skillComponent == nullptr) return; - + skillComponent->Interrupt(); } -void InterruptBehavior::Load() -{ +void InterruptBehavior::Load() { this->m_target = GetBoolean("target"); - + this->m_interruptBlock = GetBoolean("interrupt_block"); } diff --git a/dGame/dBehaviors/InterruptBehavior.h b/dGame/dBehaviors/InterruptBehavior.h index b5e3b6f6..35a2def9 100644 --- a/dGame/dBehaviors/InterruptBehavior.h +++ b/dGame/dBehaviors/InterruptBehavior.h @@ -5,20 +5,19 @@ class InterruptBehavior final : public Behavior { public: bool m_target; - + bool m_interruptBlock; /* * Inherited */ - explicit InterruptBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit InterruptBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/JetPackBehavior.cpp b/dGame/dBehaviors/JetPackBehavior.cpp index 63c0c6a9..00900735 100644 --- a/dGame/dBehaviors/JetPackBehavior.cpp +++ b/dGame/dBehaviors/JetPackBehavior.cpp @@ -4,26 +4,26 @@ #include "GameMessages.h" void JetPackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { - auto* entity = EntityManager::Instance()->GetEntity(branch.target); - + auto* entity = EntityManager::Instance()->GetEntity(branch.target); + GameMessages::SendSetJetPackMode(entity, true, this->m_BypassChecks, this->m_EnableHover, this->m_effectId, this->m_Airspeed, this->m_MaxAirspeed, this->m_VerticalVelocity, this->m_WarningEffectID); } void JetPackBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { - auto* entity = EntityManager::Instance()->GetEntity(branch.target); + auto* entity = EntityManager::Instance()->GetEntity(branch.target); GameMessages::SendSetJetPackMode(entity, false); } void JetPackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { - Handle(context, bit_stream, branch); + Handle(context, bit_stream, branch); } void JetPackBehavior::Load() { - this->m_WarningEffectID = GetInt("warning_effect_id"); - this->m_Airspeed = GetFloat("airspeed"); - this->m_MaxAirspeed = GetFloat("max_airspeed"); - this->m_VerticalVelocity = GetFloat("vertical_velocity"); - this->m_EnableHover = GetBoolean("enable_hover"); - this->m_BypassChecks = GetBoolean("bypass_checks", true); + this->m_WarningEffectID = GetInt("warning_effect_id"); + this->m_Airspeed = GetFloat("airspeed"); + this->m_MaxAirspeed = GetFloat("max_airspeed"); + this->m_VerticalVelocity = GetFloat("vertical_velocity"); + this->m_EnableHover = GetBoolean("enable_hover"); + this->m_BypassChecks = GetBoolean("bypass_checks", true); } diff --git a/dGame/dBehaviors/JetPackBehavior.h b/dGame/dBehaviors/JetPackBehavior.h index d891bf54..0cc6c399 100644 --- a/dGame/dBehaviors/JetPackBehavior.h +++ b/dGame/dBehaviors/JetPackBehavior.h @@ -1,7 +1,7 @@ #pragma once #include "Behavior.h" -class JetPackBehavior final : public Behavior +class JetPackBehavior final : public Behavior { public: int32_t m_WarningEffectID; diff --git a/dGame/dBehaviors/KnockbackBehavior.cpp b/dGame/dBehaviors/KnockbackBehavior.cpp index 37092536..0b1fc5d7 100644 --- a/dGame/dBehaviors/KnockbackBehavior.cpp +++ b/dGame/dBehaviors/KnockbackBehavior.cpp @@ -7,25 +7,21 @@ #include "GameMessages.h" #include "DestroyableComponent.h" -void KnockbackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void KnockbackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { bool unknown; bitStream->Read(unknown); } -void KnockbackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void KnockbackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { bool blocked = false; auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target != nullptr) - { + if (target != nullptr) { auto* destroyableComponent = target->GetComponent(); - if (destroyableComponent != nullptr) - { + if (destroyableComponent != nullptr) { blocked = destroyableComponent->IsKnockbackImmune(); } } @@ -33,8 +29,7 @@ void KnockbackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* b bitStream->Write(blocked); } -void KnockbackBehavior::Load() -{ +void KnockbackBehavior::Load() { this->m_strength = GetInt("strength"); this->m_angle = GetInt("angle"); this->m_relative = GetBoolean("relative"); diff --git a/dGame/dBehaviors/KnockbackBehavior.h b/dGame/dBehaviors/KnockbackBehavior.h index 0f939acd..4feb592c 100644 --- a/dGame/dBehaviors/KnockbackBehavior.h +++ b/dGame/dBehaviors/KnockbackBehavior.h @@ -12,10 +12,9 @@ public: uint32_t m_angle; bool m_relative; uint32_t m_time; - - explicit KnockbackBehavior(const uint32_t behaviorID) : Behavior(behaviorID) - { + + explicit KnockbackBehavior(const uint32_t behaviorID) : Behavior(behaviorID) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/LootBuffBehavior.cpp b/dGame/dBehaviors/LootBuffBehavior.cpp index fe46f7bb..6e5634fc 100644 --- a/dGame/dBehaviors/LootBuffBehavior.cpp +++ b/dGame/dBehaviors/LootBuffBehavior.cpp @@ -1,38 +1,38 @@ #include "LootBuffBehavior.h" -void LootBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - auto target = EntityManager::Instance()->GetEntity(context->caster); - if (!target) return; +void LootBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto target = EntityManager::Instance()->GetEntity(context->caster); + if (!target) return; - auto controllablePhysicsComponent = target->GetComponent(); - if (!controllablePhysicsComponent) return; + auto controllablePhysicsComponent = target->GetComponent(); + if (!controllablePhysicsComponent) return; - controllablePhysicsComponent->AddPickupRadiusScale(m_Scale); - EntityManager::Instance()->SerializeEntity(target); + controllablePhysicsComponent->AddPickupRadiusScale(m_Scale); + EntityManager::Instance()->SerializeEntity(target); - if (branch.duration > 0) context->RegisterTimerBehavior(this, branch); + if (branch.duration > 0) context->RegisterTimerBehavior(this, branch); } void LootBuffBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - Handle(context, bitStream, branch); + Handle(context, bitStream, branch); } void LootBuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { - auto target = EntityManager::Instance()->GetEntity(context->caster); - if (!target) return; + auto target = EntityManager::Instance()->GetEntity(context->caster); + if (!target) return; - auto controllablePhysicsComponent = target->GetComponent(); - if (!controllablePhysicsComponent) return; + auto controllablePhysicsComponent = target->GetComponent(); + if (!controllablePhysicsComponent) return; - controllablePhysicsComponent->RemovePickupRadiusScale(m_Scale); - EntityManager::Instance()->SerializeEntity(target); + controllablePhysicsComponent->RemovePickupRadiusScale(m_Scale); + EntityManager::Instance()->SerializeEntity(target); } void LootBuffBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { - UnCast(context, branch); + UnCast(context, branch); } void LootBuffBehavior::Load() { - this->m_Scale = GetFloat("scale"); -} \ No newline at end of file + this->m_Scale = GetFloat("scale"); +} diff --git a/dGame/dBehaviors/LootBuffBehavior.h b/dGame/dBehaviors/LootBuffBehavior.h index 0f85b3b0..b6f700ca 100644 --- a/dGame/dBehaviors/LootBuffBehavior.h +++ b/dGame/dBehaviors/LootBuffBehavior.h @@ -6,7 +6,7 @@ /** * @brief This is the behavior class to be used for all Loot Buff behavior nodes in the Behavior tree. - * + * */ class LootBuffBehavior final : public Behavior { @@ -17,13 +17,13 @@ public: /* * Inherited */ - + explicit LootBuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; diff --git a/dGame/dBehaviors/MovementSwitchBehavior.cpp b/dGame/dBehaviors/MovementSwitchBehavior.cpp index 066f6224..de1b0b50 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.cpp +++ b/dGame/dBehaviors/MovementSwitchBehavior.cpp @@ -3,15 +3,13 @@ #include "Game.h" #include "dLogger.h" -void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { if (this->m_groundAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_jumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_fallingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_doubleJumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_airAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && - this->m_jetpackAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) - { + this->m_jetpackAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { return; } @@ -19,8 +17,7 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream->Read(movementType); - switch (movementType) - { + switch (movementType) { case 1: this->m_groundAction->Handle(context, bitStream, branch); break; @@ -45,8 +42,7 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* } } -void MovementSwitchBehavior::Load() -{ +void MovementSwitchBehavior::Load() { this->m_airAction = GetAction("air_action"); this->m_doubleJumpAction = GetAction("double_jump_action"); diff --git a/dGame/dBehaviors/MovementSwitchBehavior.h b/dGame/dBehaviors/MovementSwitchBehavior.h index 59069eff..8a1e83a3 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.h +++ b/dGame/dBehaviors/MovementSwitchBehavior.h @@ -8,7 +8,7 @@ public: * Members */ Behavior* m_airAction; - + Behavior* m_doubleJumpAction; Behavior* m_fallingAction; @@ -18,14 +18,13 @@ public: Behavior* m_jetpackAction; Behavior* m_jumpAction; - + /* * Inherited */ - explicit MovementSwitchBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit MovementSwitchBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/NpcCombatSkillBehavior.cpp b/dGame/dBehaviors/NpcCombatSkillBehavior.cpp index c2aff256..d541033c 100644 --- a/dGame/dBehaviors/NpcCombatSkillBehavior.cpp +++ b/dGame/dBehaviors/NpcCombatSkillBehavior.cpp @@ -3,26 +3,21 @@ #include "BehaviorContext.h" -void NpcCombatSkillBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void NpcCombatSkillBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { context->skillTime = this->m_npcSkillTime; - - for (auto* behavior : this->m_behaviors) - { + + for (auto* behavior : this->m_behaviors) { behavior->Calculate(context, bit_stream, branch); } } -void NpcCombatSkillBehavior::Load() -{ +void NpcCombatSkillBehavior::Load() { this->m_npcSkillTime = GetFloat("npc skill time"); - + const auto parameters = GetParameterNames(); - for (const auto& parameter : parameters) - { - if (parameter.first.rfind("behavior", 0) == 0) - { + for (const auto& parameter : parameters) { + if (parameter.first.rfind("behavior", 0) == 0) { auto* action = GetAction(parameter.second); this->m_behaviors.push_back(action); diff --git a/dGame/dBehaviors/NpcCombatSkillBehavior.h b/dGame/dBehaviors/NpcCombatSkillBehavior.h index a5523acd..f2ed60b9 100644 --- a/dGame/dBehaviors/NpcCombatSkillBehavior.h +++ b/dGame/dBehaviors/NpcCombatSkillBehavior.h @@ -12,10 +12,9 @@ public: * Inherited */ - explicit NpcCombatSkillBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit NpcCombatSkillBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - + void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/OverTimeBehavior.cpp b/dGame/dBehaviors/OverTimeBehavior.cpp index 9e8618df..43ac9bc2 100644 --- a/dGame/dBehaviors/OverTimeBehavior.cpp +++ b/dGame/dBehaviors/OverTimeBehavior.cpp @@ -7,43 +7,39 @@ #include "SkillComponent.h" #include "DestroyableComponent.h" -void OverTimeBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - const auto originator = context->originator; +void OverTimeBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + const auto originator = context->originator; - auto* entity = EntityManager::Instance()->GetEntity(originator); + auto* entity = EntityManager::Instance()->GetEntity(originator); - if (entity == nullptr) return; + if (entity == nullptr) return; - for (size_t i = 0; i < m_NumIntervals; i++) - { - entity->AddCallbackTimer((i + 1) * m_Delay, [originator, branch, this]() { - auto* entity = EntityManager::Instance()->GetEntity(originator); + for (size_t i = 0; i < m_NumIntervals; i++) { + entity->AddCallbackTimer((i + 1) * m_Delay, [originator, branch, this]() { + auto* entity = EntityManager::Instance()->GetEntity(originator); - if (entity == nullptr) return; + if (entity == nullptr) return; - auto* skillComponent = entity->GetComponent(); + auto* skillComponent = entity->GetComponent(); - if (skillComponent == nullptr) return; + if (skillComponent == nullptr) return; - skillComponent->CalculateBehavior(m_Action, m_ActionBehaviorId, branch.target, true, true); - }); - } + skillComponent->CalculateBehavior(m_Action, m_ActionBehaviorId, branch.target, true, true); + }); + } } -void OverTimeBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - +void OverTimeBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + } -void OverTimeBehavior::Load() -{ - m_Action = GetInt("action"); - // Since m_Action is a skillID and not a behavior, get is correlated behaviorID. +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("SkillBehavior"); - m_ActionBehaviorId = skillTable->GetSkillByID(m_Action).behaviorID; + CDSkillBehaviorTable* skillTable = CDClientManager::Instance()->GetTable("SkillBehavior"); + m_ActionBehaviorId = skillTable->GetSkillByID(m_Action).behaviorID; - m_Delay = GetFloat("delay"); - m_NumIntervals = GetInt("num_intervals"); + m_Delay = GetFloat("delay"); + m_NumIntervals = GetInt("num_intervals"); } diff --git a/dGame/dBehaviors/OverTimeBehavior.h b/dGame/dBehaviors/OverTimeBehavior.h index 5c177926..73a07865 100644 --- a/dGame/dBehaviors/OverTimeBehavior.h +++ b/dGame/dBehaviors/OverTimeBehavior.h @@ -4,19 +4,18 @@ class OverTimeBehavior final : public Behavior { public: - uint32_t m_Action; + uint32_t m_Action; uint32_t m_ActionBehaviorId; - float m_Delay; - int32_t m_NumIntervals; + float m_Delay; + int32_t m_NumIntervals; /* * Inherited */ - explicit OverTimeBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit OverTimeBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/PlayEffectBehavior.cpp b/dGame/dBehaviors/PlayEffectBehavior.cpp index 20148132..9793c1db 100644 --- a/dGame/dBehaviors/PlayEffectBehavior.cpp +++ b/dGame/dBehaviors/PlayEffectBehavior.cpp @@ -3,8 +3,7 @@ #include "BehaviorContext.h" #include "BehaviorBranchContext.h" -void PlayEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void PlayEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { // On managed behaviors this is handled by the client if (!context->unmanaged) return; @@ -14,13 +13,11 @@ void PlayEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit PlayFx(u"", target); } -void PlayEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void PlayEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto& target = branch.target == LWOOBJID_EMPTY ? context->originator : branch.target; //PlayFx(u"", target); } -void PlayEffectBehavior::Load() -{ +void PlayEffectBehavior::Load() { } diff --git a/dGame/dBehaviors/PlayEffectBehavior.h b/dGame/dBehaviors/PlayEffectBehavior.h index 3f49f38c..d6069305 100644 --- a/dGame/dBehaviors/PlayEffectBehavior.h +++ b/dGame/dBehaviors/PlayEffectBehavior.h @@ -7,13 +7,12 @@ public: /* * Inherited */ - explicit PlayEffectBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit PlayEffectBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Load() override; }; diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.cpp b/dGame/dBehaviors/ProjectileAttackBehavior.cpp index 5bf8b6a1..861837e7 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.cpp +++ b/dGame/dBehaviors/ProjectileAttackBehavior.cpp @@ -7,16 +7,14 @@ #include "SkillComponent.h" #include "../dWorldServer/ObjectIDManager.h" -void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { LWOOBJID target; bitStream->Read(target); auto* entity = EntityManager::Instance()->GetEntity(context->originator); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("ProjectileAttackBehavior", "Failed to find originator (%llu)!", context->originator); return; @@ -24,23 +22,20 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea auto* skillComponent = entity->GetComponent(); - if (skillComponent == nullptr) - { + if (skillComponent == nullptr) { Game::logger->Log("ProjectileAttackBehavior", "Failed to find skill component for (%llu)!", -context->originator); return; } - if (m_useMouseposit) - { + if (m_useMouseposit) { NiPoint3 targetPosition = NiPoint3::ZERO; bitStream->Read(targetPosition); } auto* targetEntity = EntityManager::Instance()->GetEntity(target); - for (auto i = 0u; i < this->m_projectileCount; ++i) - { + for (auto i = 0u; i < this->m_projectileCount; ++i) { LWOOBJID projectileId; bitStream->Read(projectileId); @@ -53,14 +48,12 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea } } -void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { bitStream->Write(branch.target); auto* entity = EntityManager::Instance()->GetEntity(context->originator); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("ProjectileAttackBehavior", "Failed to find originator (%llu)!", context->originator); return; @@ -68,8 +61,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt auto* skillComponent = entity->GetComponent(); - if (skillComponent == nullptr) - { + if (skillComponent == nullptr) { Game::logger->Log("ProjectileAttackBehavior", "Failed to find skill component for (%llu)!", context->originator); return; @@ -78,8 +70,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt auto* other = EntityManager::Instance()->GetEntity(branch.target); - if (other == nullptr) - { + if (other == nullptr) { Game::logger->Log("ProjectileAttackBehavior", "Invalid projectile target (%llu)!", branch.target); return; @@ -104,8 +95,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt const auto maxTime = this->m_maxDistance / this->m_projectileSpeed; - for (auto i = 0u; i < this->m_projectileCount; ++i) - { + for (auto i = 0u; i < this->m_projectileCount; ++i) { auto id = static_cast(ObjectIDManager::Instance()->GenerateObjectID()); id = GeneralUtils::SetBit(id, OBJECT_BIT_CLIENT); @@ -128,25 +118,20 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt skillComponent->RegisterCalculatedProjectile(id, context, branch, this->m_lot, maxTime, position, direction * this->m_projectileSpeed, this->m_trackTarget, this->m_trackRadius); // No idea how to calculate this properly - if (this->m_projectileCount == 2) - { + if (this->m_projectileCount == 2) { angle += angleDelta; - } - else if (this->m_projectileCount == 3) - { + } else if (this->m_projectileCount == 3) { angle += angleStep; } } } -void ProjectileAttackBehavior::Load() -{ +void ProjectileAttackBehavior::Load() { this->m_lot = GetInt("LOT_ID"); this->m_projectileCount = GetInt("spread_count"); - if (this->m_projectileCount == 0) - { + if (this->m_projectileCount == 0) { this->m_projectileCount = 1; } diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.h b/dGame/dBehaviors/ProjectileAttackBehavior.h index 9d40e97c..0003c2dc 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.h +++ b/dGame/dBehaviors/ProjectileAttackBehavior.h @@ -27,8 +27,7 @@ public: * Inherited */ - explicit ProjectileAttackBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit ProjectileAttackBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/PullToPointBehavior.cpp b/dGame/dBehaviors/PullToPointBehavior.cpp index 8b87cbfb..2cdbaa7e 100644 --- a/dGame/dBehaviors/PullToPointBehavior.cpp +++ b/dGame/dBehaviors/PullToPointBehavior.cpp @@ -5,21 +5,18 @@ #include "EntityManager.h" #include "MovementAIComponent.h" -void PullToPointBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void PullToPointBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(context->originator); - + auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (entity == nullptr || target == nullptr) - { + if (entity == nullptr || target == nullptr) { return; } - + auto* movement = target->GetComponent(); - if (movement == nullptr) - { + if (movement == nullptr) { return; } @@ -28,11 +25,9 @@ void PullToPointBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi movement->PullToPoint(position); } -void PullToPointBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void PullToPointBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } -void PullToPointBehavior::Load() -{ +void PullToPointBehavior::Load() { } diff --git a/dGame/dBehaviors/PullToPointBehavior.h b/dGame/dBehaviors/PullToPointBehavior.h index ecd50bab..09e4310c 100644 --- a/dGame/dBehaviors/PullToPointBehavior.h +++ b/dGame/dBehaviors/PullToPointBehavior.h @@ -9,8 +9,7 @@ public: * Inherited */ - explicit PullToPointBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit PullToPointBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/RepairBehavior.cpp b/dGame/dBehaviors/RepairBehavior.cpp index c3e8a4d3..470fb4d4 100644 --- a/dGame/dBehaviors/RepairBehavior.cpp +++ b/dGame/dBehaviors/RepairBehavior.cpp @@ -6,12 +6,10 @@ #include "dLogger.h" #include "Game.h" -void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) -{ +void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("RepairBehavior", "Failed to find entity for (%llu)!", branch.target); return; @@ -19,8 +17,7 @@ void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_str auto* destroyable = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { Game::logger->Log("RepairBehavior", "Failed to find destroyable component for %(llu)!", branch.target); return; @@ -29,12 +26,10 @@ void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_str destroyable->Repair(this->m_armor); } -void RepairBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) -{ +void RepairBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { Handle(context, bit_stream, branch); } -void RepairBehavior::Load() -{ +void RepairBehavior::Load() { this->m_armor = GetInt("armor"); } diff --git a/dGame/dBehaviors/RepairBehavior.h b/dGame/dBehaviors/RepairBehavior.h index 46ca6bfb..38f97b05 100644 --- a/dGame/dBehaviors/RepairBehavior.h +++ b/dGame/dBehaviors/RepairBehavior.h @@ -10,8 +10,7 @@ public: * Inherited */ - explicit RepairBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit RepairBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/SkillCastFailedBehavior.cpp b/dGame/dBehaviors/SkillCastFailedBehavior.cpp index ef8ba3e1..7a0166f9 100644 --- a/dGame/dBehaviors/SkillCastFailedBehavior.cpp +++ b/dGame/dBehaviors/SkillCastFailedBehavior.cpp @@ -3,16 +3,13 @@ #include "BehaviorContext.h" #include "BehaviorBranchContext.h" -void SkillCastFailedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void SkillCastFailedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { context->failed = true; } -void SkillCastFailedBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void SkillCastFailedBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { context->failed = true; } -void SkillCastFailedBehavior::Load() -{ +void SkillCastFailedBehavior::Load() { } diff --git a/dGame/dBehaviors/SkillCastFailedBehavior.h b/dGame/dBehaviors/SkillCastFailedBehavior.h index cdd2adb4..1f414f90 100644 --- a/dGame/dBehaviors/SkillCastFailedBehavior.h +++ b/dGame/dBehaviors/SkillCastFailedBehavior.h @@ -8,12 +8,11 @@ public: /* * Inherited */ - explicit SkillCastFailedBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit SkillCastFailedBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/SkillEventBehavior.cpp b/dGame/dBehaviors/SkillEventBehavior.cpp index 35a9aa6f..837d70c9 100644 --- a/dGame/dBehaviors/SkillEventBehavior.cpp +++ b/dGame/dBehaviors/SkillEventBehavior.cpp @@ -4,25 +4,25 @@ #include "EntityManager.h" #include "CppScripts.h" -void SkillEventBehavior::Handle(BehaviorContext *context, RakNet::BitStream *bitStream, BehaviorBranchContext branch) { - auto* target = EntityManager::Instance()->GetEntity(branch.target); - auto* caster = EntityManager::Instance()->GetEntity(context->originator); +void SkillEventBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto* target = EntityManager::Instance()->GetEntity(branch.target); + auto* caster = EntityManager::Instance()->GetEntity(context->originator); - if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(target)) { - script->OnSkillEventFired(target, caster, *this->m_effectHandle); - } - } + if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(target)) { + script->OnSkillEventFired(target, caster, *this->m_effectHandle); + } + } } void -SkillEventBehavior::Calculate(BehaviorContext *context, RakNet::BitStream *bitStream, BehaviorBranchContext branch) { - auto* target = EntityManager::Instance()->GetEntity(branch.target); - auto* caster = EntityManager::Instance()->GetEntity(context->originator); +SkillEventBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto* target = EntityManager::Instance()->GetEntity(branch.target); + auto* caster = EntityManager::Instance()->GetEntity(context->originator); - if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(target)) { - script->OnSkillEventFired(target, caster, *this->m_effectHandle); - } - } + if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(target)) { + script->OnSkillEventFired(target, caster, *this->m_effectHandle); + } + } } diff --git a/dGame/dBehaviors/SkillEventBehavior.h b/dGame/dBehaviors/SkillEventBehavior.h index 720cd440..540f6d4a 100644 --- a/dGame/dBehaviors/SkillEventBehavior.h +++ b/dGame/dBehaviors/SkillEventBehavior.h @@ -6,10 +6,10 @@ */ class SkillEventBehavior final : public Behavior { public: - explicit SkillEventBehavior(const uint32_t behaviorID) : Behavior(behaviorID) { - } + explicit SkillEventBehavior(const uint32_t behaviorID) : Behavior(behaviorID) { + } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext *context, RakNet::BitStream *bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; }; diff --git a/dGame/dBehaviors/SpawnBehavior.cpp b/dGame/dBehaviors/SpawnBehavior.cpp index 6d0e7490..592a8a22 100644 --- a/dGame/dBehaviors/SpawnBehavior.cpp +++ b/dGame/dBehaviors/SpawnBehavior.cpp @@ -8,23 +8,19 @@ #include "DestroyableComponent.h" #include "RebuildComponent.h" -void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* origin = EntityManager::Instance()->GetEntity(context->originator); - if (origin == nullptr) - { + if (origin == nullptr) { Game::logger->Log("SpawnBehavior", "Failed to find self entity (%llu)!", context->originator); return; } - if (branch.isProjectile) - { + if (branch.isProjectile) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target != nullptr) - { + if (target != nullptr) { origin = target; } } @@ -42,11 +38,10 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea auto* entity = EntityManager::Instance()->CreateEntity( info, nullptr, - EntityManager::Instance()->GetEntity(context->originator) + EntityManager::Instance()->GetEntity(context->originator) ); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("SpawnBehavior", "Failed to spawn entity (%i)!", this->m_lot); return; @@ -57,39 +52,33 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea // Unset the flag to reposition the player, this makes it harder to glitch out of the map auto* rebuildComponent = entity->GetComponent(); - if (rebuildComponent != nullptr) - { + if (rebuildComponent != nullptr) { rebuildComponent->SetRepositionPlayer(false); } EntityManager::Instance()->ConstructEntity(entity); - if (branch.duration > 0) - { + if (branch.duration > 0) { context->RegisterTimerBehavior(this, branch, entity->GetObjectID()); } - if (branch.start != 0) - { + if (branch.start != 0) { context->RegisterEndBehavior(this, branch, entity->GetObjectID()); } - entity->AddCallbackTimer(60, [entity] () { + entity->AddCallbackTimer(60, [entity]() { entity->Smash(); - }); + }); } -void SpawnBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void SpawnBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } -void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext branch, const LWOOBJID second) -{ +void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext branch, const LWOOBJID second) { auto* entity = EntityManager::Instance()->GetEntity(second); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("SpawnBehavior", "Failed to find spawned entity (%llu)!", second); return; @@ -97,8 +86,7 @@ void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext auto* destroyable = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - if (destroyable == nullptr) - { + if (destroyable == nullptr) { entity->Smash(context->originator); return; @@ -107,14 +95,12 @@ void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext destroyable->Smash(second); } -void SpawnBehavior::End(BehaviorContext* context, const BehaviorBranchContext branch, const LWOOBJID second) -{ +void SpawnBehavior::End(BehaviorContext* context, const BehaviorBranchContext branch, const LWOOBJID second) { Timer(context, branch, second); } -void SpawnBehavior::Load() -{ +void SpawnBehavior::Load() { this->m_lot = GetInt("LOT_ID"); this->m_Distance = GetFloat("distance"); } diff --git a/dGame/dBehaviors/SpawnBehavior.h b/dGame/dBehaviors/SpawnBehavior.h index a4adbcad..0617f781 100644 --- a/dGame/dBehaviors/SpawnBehavior.h +++ b/dGame/dBehaviors/SpawnBehavior.h @@ -6,21 +6,20 @@ class SpawnBehavior final : public Behavior public: LOT m_lot; float m_Distance; - + /* * Inherited */ - explicit SpawnBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit SpawnBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; - + void Load() override; -}; \ No newline at end of file +}; diff --git a/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp b/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp index 3072d53c..2b78f12e 100644 --- a/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp +++ b/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp @@ -3,11 +3,8 @@ #include "BehaviorBranchContext.h" #include "BehaviorContext.h" -void SpawnQuickbuildBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void SpawnQuickbuildBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { } -void SpawnQuickbuildBehavior::Load() -{ +void SpawnQuickbuildBehavior::Load() { } - \ No newline at end of file diff --git a/dGame/dBehaviors/SpawnQuickbuildBehavior.h b/dGame/dBehaviors/SpawnQuickbuildBehavior.h index 2172d25e..d1ed2e53 100644 --- a/dGame/dBehaviors/SpawnQuickbuildBehavior.h +++ b/dGame/dBehaviors/SpawnQuickbuildBehavior.h @@ -8,8 +8,7 @@ public: /* * Inherited */ - explicit SpawnQuickbuildBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit SpawnQuickbuildBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/SpeedBehavior.cpp b/dGame/dBehaviors/SpeedBehavior.cpp index 73bc9029..c7855557 100644 --- a/dGame/dBehaviors/SpeedBehavior.cpp +++ b/dGame/dBehaviors/SpeedBehavior.cpp @@ -6,101 +6,86 @@ #include "dLogger.h" -void SpeedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - if (m_AffectsCaster) - { - branch.target = context->caster; - } +void SpeedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + if (m_AffectsCaster) { + branch.target = context->caster; + } auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { - return; - } + if (target == nullptr) { + return; + } - auto* controllablePhysicsComponent = target->GetComponent(); + auto* controllablePhysicsComponent = target->GetComponent(); - if (controllablePhysicsComponent == nullptr) - { - return; - } + if (controllablePhysicsComponent == nullptr) { + return; + } - const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); + const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); - controllablePhysicsComponent->SetSpeedMultiplier(current + ((m_RunSpeed - 500.0f) / 500.0f)); + controllablePhysicsComponent->SetSpeedMultiplier(current + ((m_RunSpeed - 500.0f) / 500.0f)); - EntityManager::Instance()->SerializeEntity(target); + EntityManager::Instance()->SerializeEntity(target); - if (branch.duration > 0.0f) - { - context->RegisterTimerBehavior(this, branch); - } - else if (branch.start > 0) - { - controllablePhysicsComponent->SetIgnoreMultipliers(true); + if (branch.duration > 0.0f) { + context->RegisterTimerBehavior(this, branch); + } else if (branch.start > 0) { + controllablePhysicsComponent->SetIgnoreMultipliers(true); - context->RegisterEndBehavior(this, branch); - } + context->RegisterEndBehavior(this, branch); + } } -void SpeedBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) -{ - auto* target = EntityManager::Instance()->GetEntity(branch.target); +void SpeedBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { + auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { - return; - } + if (target == nullptr) { + return; + } - auto* controllablePhysicsComponent = target->GetComponent(); + auto* controllablePhysicsComponent = target->GetComponent(); - if (controllablePhysicsComponent == nullptr) - { - return; - } + if (controllablePhysicsComponent == nullptr) { + return; + } - const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); + const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); - controllablePhysicsComponent->SetSpeedMultiplier(current - ((m_RunSpeed - 500.0f) / 500.0f)); + controllablePhysicsComponent->SetSpeedMultiplier(current - ((m_RunSpeed - 500.0f) / 500.0f)); - EntityManager::Instance()->SerializeEntity(target); + EntityManager::Instance()->SerializeEntity(target); } -void SpeedBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) -{ - auto* target = EntityManager::Instance()->GetEntity(branch.target); +void SpeedBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { + auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { - return; - } + if (target == nullptr) { + return; + } - auto* controllablePhysicsComponent = target->GetComponent(); + auto* controllablePhysicsComponent = target->GetComponent(); - if (controllablePhysicsComponent == nullptr) - { - return; - } + if (controllablePhysicsComponent == nullptr) { + return; + } - const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); + const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); - controllablePhysicsComponent->SetIgnoreMultipliers(false); + controllablePhysicsComponent->SetIgnoreMultipliers(false); - controllablePhysicsComponent->SetSpeedMultiplier(current - ((m_RunSpeed - 500.0f) / 500.0f)); + controllablePhysicsComponent->SetSpeedMultiplier(current - ((m_RunSpeed - 500.0f) / 500.0f)); - EntityManager::Instance()->SerializeEntity(target); + EntityManager::Instance()->SerializeEntity(target); } -void SpeedBehavior::Load() -{ - m_RunSpeed = GetFloat("run_speed"); +void SpeedBehavior::Load() { + m_RunSpeed = GetFloat("run_speed"); - if (m_RunSpeed < 500.0f) - { - m_RunSpeed = 500.0f; - } + if (m_RunSpeed < 500.0f) { + m_RunSpeed = 500.0f; + } - m_AffectsCaster = GetBoolean("affects_caster"); + m_AffectsCaster = GetBoolean("affects_caster"); } diff --git a/dGame/dBehaviors/SpeedBehavior.h b/dGame/dBehaviors/SpeedBehavior.h index 9b8aa688..04c0090f 100644 --- a/dGame/dBehaviors/SpeedBehavior.h +++ b/dGame/dBehaviors/SpeedBehavior.h @@ -8,20 +8,19 @@ public: /* * Inherited */ - explicit SpeedBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit SpeedBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - - void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; - void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; + void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; + + void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void Load() override; private: - float m_RunSpeed; + float m_RunSpeed; - bool m_AffectsCaster; + bool m_AffectsCaster; }; diff --git a/dGame/dBehaviors/StartBehavior.cpp b/dGame/dBehaviors/StartBehavior.cpp index af03c333..436984d1 100644 --- a/dGame/dBehaviors/StartBehavior.cpp +++ b/dGame/dBehaviors/StartBehavior.cpp @@ -1,21 +1,18 @@ #include "StartBehavior.h" #include "BehaviorBranchContext.h" -void StartBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void StartBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { branch.start = this->m_behaviorId; - + this->m_action->Handle(context, bit_stream, branch); } -void StartBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void StartBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { branch.start = this->m_behaviorId; this->m_action->Calculate(context, bit_stream, branch); } -void StartBehavior::Load() -{ +void StartBehavior::Load() { this->m_action = GetAction("action"); } diff --git a/dGame/dBehaviors/StartBehavior.h b/dGame/dBehaviors/StartBehavior.h index d93526f6..9ee461fc 100644 --- a/dGame/dBehaviors/StartBehavior.h +++ b/dGame/dBehaviors/StartBehavior.h @@ -5,13 +5,12 @@ class StartBehavior final : public Behavior { public: Behavior* m_action; - + /* * Inherited */ - explicit StartBehavior(const uint32_t behaviorID) : Behavior(behaviorID) - { + explicit StartBehavior(const uint32_t behaviorID) : Behavior(behaviorID) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/StunBehavior.cpp b/dGame/dBehaviors/StunBehavior.cpp index 5c0ea310..3cbfe9c4 100644 --- a/dGame/dBehaviors/StunBehavior.cpp +++ b/dGame/dBehaviors/StunBehavior.cpp @@ -9,8 +9,7 @@ #include "DestroyableComponent.h" -void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { if (this->m_stunCaster || branch.target == context->originator) { return; } @@ -20,8 +19,7 @@ void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("StunBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -33,22 +31,18 @@ void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream auto* combatAiComponent = static_cast(target->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); - if (combatAiComponent == nullptr) - { + if (combatAiComponent == nullptr) { return; } combatAiComponent->Stun(branch.duration); } -void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ - if (this->m_stunCaster || branch.target == context->originator) - { +void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { + if (this->m_stunCaster || branch.target == context->originator) { auto* self = EntityManager::Instance()->GetEntity(context->originator); - if (self == nullptr) - { + if (self == nullptr) { Game::logger->Log("StunBehavior", "Invalid self entity (%llu)!", context->originator); return; @@ -60,8 +54,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr auto* combatAiComponent = static_cast(self->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); - if (combatAiComponent == nullptr) - { + if (combatAiComponent == nullptr) { return; } @@ -74,20 +67,17 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target != nullptr) - { + if (target != nullptr) { auto* destroyableComponent = target->GetComponent(); - if (destroyableComponent != nullptr) - { + if (destroyableComponent != nullptr) { blocked = destroyableComponent->IsKnockbackImmune(); } } bitStream->Write(blocked); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("StunBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -99,15 +89,13 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr auto* combatAiComponent = static_cast(target->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); - if (combatAiComponent == nullptr) - { + if (combatAiComponent == nullptr) { return; } combatAiComponent->Stun(branch.duration); } -void StunBehavior::Load() -{ +void StunBehavior::Load() { this->m_stunCaster = GetBoolean("stun_caster"); } diff --git a/dGame/dBehaviors/StunBehavior.h b/dGame/dBehaviors/StunBehavior.h index 0ec36129..a512528d 100644 --- a/dGame/dBehaviors/StunBehavior.h +++ b/dGame/dBehaviors/StunBehavior.h @@ -9,10 +9,9 @@ public: /* * Inherited */ - explicit StunBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit StunBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/SwitchBehavior.cpp b/dGame/dBehaviors/SwitchBehavior.cpp index 8af8a334..ff3d7baf 100644 --- a/dGame/dBehaviors/SwitchBehavior.cpp +++ b/dGame/dBehaviors/SwitchBehavior.cpp @@ -6,57 +6,46 @@ #include "BehaviorContext.h" #include "BuffComponent.h" -void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) -{ +void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { auto state = true; - if (this->m_imagination > 0 || !this->m_isEnemyFaction) - { + if (this->m_imagination > 0 || !this->m_isEnemyFaction) { bitStream->Read(state); } - auto* entity = EntityManager::Instance()->GetEntity(context->originator); + auto* entity = EntityManager::Instance()->GetEntity(context->originator); - if (entity == nullptr) - { - return; - } - - auto* destroyableComponent = entity->GetComponent(); - - if (destroyableComponent == nullptr) - { + if (entity == nullptr) { return; } - Game::logger->Log("SwitchBehavior", "[%i] State: (%d), imagination: (%i) / (%f)", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination()); + auto* destroyableComponent = entity->GetComponent(); - if (state || (entity->GetLOT() == 8092 && destroyableComponent->GetImagination() >= m_imagination)) - { - this->m_actionTrue->Handle(context, bitStream, branch); + if (destroyableComponent == nullptr) { + return; } - else - { + + Game::logger->Log("SwitchBehavior", "[%i] State: (%d), imagination: (%i) / (%f)", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination()); + + if (state || (entity->GetLOT() == 8092 && destroyableComponent->GetImagination() >= m_imagination)) { + this->m_actionTrue->Handle(context, bitStream, branch); + } else { this->m_actionFalse->Handle(context, bitStream, branch); } } -void SwitchBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void SwitchBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto state = true; - if (this->m_imagination > 0 || !this->m_isEnemyFaction) - { + if (this->m_imagination > 0 || !this->m_isEnemyFaction) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); state = entity != nullptr; - if (state && m_targetHasBuff != 0) - { - auto* buffComponent = entity->GetComponent(); + if (state && m_targetHasBuff != 0) { + auto* buffComponent = entity->GetComponent(); - if (buffComponent != nullptr && !buffComponent->HasBuff(m_targetHasBuff)) - { + if (buffComponent != nullptr && !buffComponent->HasBuff(m_targetHasBuff)) { state = false; } } @@ -64,18 +53,14 @@ void SwitchBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS bitStream->Write(state); } - if (state) - { + if (state) { this->m_actionTrue->Calculate(context, bitStream, branch); - } - else - { + } else { this->m_actionFalse->Calculate(context, bitStream, branch); } } -void SwitchBehavior::Load() -{ +void SwitchBehavior::Load() { this->m_actionTrue = GetAction("action_true"); this->m_actionFalse = GetAction("action_false"); diff --git a/dGame/dBehaviors/SwitchBehavior.h b/dGame/dBehaviors/SwitchBehavior.h index 8dc43e71..675c1a35 100644 --- a/dGame/dBehaviors/SwitchBehavior.h +++ b/dGame/dBehaviors/SwitchBehavior.h @@ -13,13 +13,12 @@ public: bool m_isEnemyFaction; int32_t m_targetHasBuff; - + /* * Inherited */ - explicit SwitchBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit SwitchBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/SwitchMultipleBehavior.cpp b/dGame/dBehaviors/SwitchMultipleBehavior.cpp index 93662060..b34b1144 100644 --- a/dGame/dBehaviors/SwitchMultipleBehavior.cpp +++ b/dGame/dBehaviors/SwitchMultipleBehavior.cpp @@ -9,20 +9,19 @@ #include "EntityManager.h" -void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { float value; bit_stream->Read(value); - + uint32_t trigger = 0; for (unsigned int i = 0; i < this->m_behaviors.size(); i++) { - + const double data = this->m_behaviors.at(i).first; - + if (value <= data) { - + trigger = i; break; @@ -34,8 +33,7 @@ void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* behavior->Handle(context, bit_stream, branch); } -void SwitchMultipleBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void SwitchMultipleBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { // TODO } @@ -45,7 +43,7 @@ void SwitchMultipleBehavior::Load() { "(select bP2.value FROM BehaviorParameter bP2 WHERE bP2.behaviorID = ?1 AND bP2.parameterID LIKE 'value %' " "AND replace(bP1.parameterID, 'behavior ', '') = replace(bP2.parameterID, 'value ', '')) as value " "FROM BehaviorParameter bP1 WHERE bP1.behaviorID = ?1 AND bP1.parameterID LIKE 'behavior %';"); - query.bind(1, (int) this->m_behaviorId); + query.bind(1, (int)this->m_behaviorId); auto result = query.execQuery(); @@ -57,7 +55,7 @@ void SwitchMultipleBehavior::Load() { auto value = result.getFloatField(2); this->m_behaviors.emplace_back(value, behavior); - + result.nextRow(); } } diff --git a/dGame/dBehaviors/SwitchMultipleBehavior.h b/dGame/dBehaviors/SwitchMultipleBehavior.h index c25049ae..c60fcd6d 100644 --- a/dGame/dBehaviors/SwitchMultipleBehavior.h +++ b/dGame/dBehaviors/SwitchMultipleBehavior.h @@ -7,13 +7,12 @@ class SwitchMultipleBehavior final : public Behavior { public: std::vector> m_behaviors; - + /* * Inherited */ - explicit SwitchMultipleBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit SwitchMultipleBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/TacArcBehavior.cpp b/dGame/dBehaviors/TacArcBehavior.cpp index 2d012305..21885624 100644 --- a/dGame/dBehaviors/TacArcBehavior.cpp +++ b/dGame/dBehaviors/TacArcBehavior.cpp @@ -11,10 +11,8 @@ #include -void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - if (this->m_targetEnemy && this->m_usePickedTarget && branch.target > 0) - { +void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + if (this->m_targetEnemy && this->m_usePickedTarget && branch.target > 0) { this->m_action->Handle(context, bitStream, branch); return; @@ -24,35 +22,30 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre bitStream->Read(hit); - if (this->m_checkEnv) - { + if (this->m_checkEnv) { bool blocked = false; bitStream->Read(blocked); - if (blocked) - { + if (blocked) { this->m_blockedAction->Handle(context, bitStream, branch); return; } } - if (hit) - { + if (hit) { uint32_t count = 0; bitStream->Read(count); - if (count > m_maxTargets && m_maxTargets > 0) - { + if (count > m_maxTargets && m_maxTargets > 0) { count = m_maxTargets; } std::vector targets; - for (auto i = 0u; i < count; ++i) - { + for (auto i = 0u; i < count; ++i) { LWOOBJID id; bitStream->Read(id); @@ -60,46 +53,41 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre targets.push_back(id); } - for (auto target : targets) - { + for (auto target : targets) { branch.target = target; this->m_action->Handle(context, bitStream, branch); } - } - else - { + } else { this->m_missAction->Handle(context, bitStream, branch); } } -void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ - auto* self = EntityManager::Instance()->GetEntity(context->originator); - if (self == nullptr) { - Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!", context->originator); - return; - } +void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto* self = EntityManager::Instance()->GetEntity(context->originator); + if (self == nullptr) { + Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!", context->originator); + return; + } - const auto* destroyableComponent = self->GetComponent(); + const auto* destroyableComponent = self->GetComponent(); - if ((this->m_usePickedTarget || context->clientInitalized) && branch.target > 0) { - const auto* target = EntityManager::Instance()->GetEntity(branch.target); + if ((this->m_usePickedTarget || context->clientInitalized) && branch.target > 0) { + const auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { return; } - // If the game is specific about who to target, check that - if (destroyableComponent == nullptr || ((!m_targetFriend && !m_targetEnemy - || m_targetFriend && destroyableComponent->IsFriend(target) - || m_targetEnemy && destroyableComponent->IsEnemy(target)))) { - this->m_action->Calculate(context, bitStream, branch); - } + // If the game is specific about who to target, check that + if (destroyableComponent == nullptr || ((!m_targetFriend && !m_targetEnemy + || m_targetFriend && destroyableComponent->IsFriend(target) + || m_targetEnemy && destroyableComponent->IsEnemy(target)))) { + this->m_action->Calculate(context, bitStream, branch); + } - return; - } + return; + } auto* combatAi = self->GetComponent(); @@ -111,46 +99,40 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS std::vector validTargets; - if (combatAi != nullptr) - { - if (combatAi->GetTarget() != LWOOBJID_EMPTY) - { + if (combatAi != nullptr) { + if (combatAi->GetTarget() != LWOOBJID_EMPTY) { validTargets.push_back(combatAi->GetTarget()); } } // Find all valid targets, based on whether we target enemies or friends for (const auto& contextTarget : context->GetValidTargets()) { - if (destroyableComponent != nullptr) { - const auto* targetEntity = EntityManager::Instance()->GetEntity(contextTarget); + if (destroyableComponent != nullptr) { + const auto* targetEntity = EntityManager::Instance()->GetEntity(contextTarget); - if (m_targetEnemy && destroyableComponent->IsEnemy(targetEntity) - || m_targetFriend && destroyableComponent->IsFriend(targetEntity)) { - validTargets.push_back(contextTarget); - } - } else { - validTargets.push_back(contextTarget); - } + if (m_targetEnemy && destroyableComponent->IsEnemy(targetEntity) + || m_targetFriend && destroyableComponent->IsFriend(targetEntity)) { + validTargets.push_back(contextTarget); + } + } else { + validTargets.push_back(contextTarget); + } } - for (auto validTarget : validTargets) - { - if (targets.size() >= this->m_maxTargets) - { + for (auto validTarget : validTargets) { + if (targets.size() >= this->m_maxTargets) { break; } auto* entity = EntityManager::Instance()->GetEntity(validTarget); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!", validTarget, context->originator); continue; } - if (std::find(targets.begin(), targets.end(), entity) != targets.end()) - { + if (std::find(targets.begin(), targets.end(), entity) != targets.end()) { continue; } @@ -174,12 +156,10 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS const auto distance = Vector3::Distance(reference, otherPosition); - if (m_method == 2) - { + if (m_method == 2) { NiPoint3 rayPoint = casterPosition + forward * distance; - if (m_farWidth > 0 && Vector3::DistanceSquared(rayPoint, otherPosition) > this->m_farWidth * this->m_farWidth) - { + if (m_farWidth > 0 && Vector3::DistanceSquared(rayPoint, otherPosition) > this->m_farWidth * this->m_farWidth) { continue; } } @@ -188,35 +168,30 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS const float degreeAngle = std::abs(Vector3::Angle(forward, normalized) * (180 / 3.14) - 180); - if (distance >= this->m_minDistance && this->m_maxDistance >= distance && degreeAngle <= 2 * this->m_angle) - { + if (distance >= this->m_minDistance && this->m_maxDistance >= distance && degreeAngle <= 2 * this->m_angle) { targets.push_back(entity); } } - std::sort(targets.begin(), targets.end(), [reference](Entity* a, Entity* b) - { + std::sort(targets.begin(), targets.end(), [reference](Entity* a, Entity* b) { const auto aDistance = Vector3::DistanceSquared(reference, a->GetPosition()); const auto bDistance = Vector3::DistanceSquared(reference, b->GetPosition()); return aDistance > bDistance; - }); + }); const auto hit = !targets.empty(); bitStream->Write(hit); - if (this->m_checkEnv) - { + if (this->m_checkEnv) { const auto blocked = false; // TODO bitStream->Write(blocked); } - if (hit) - { - if (combatAi != nullptr) - { + if (hit) { + if (combatAi != nullptr) { combatAi->LookAt(targets[0]->GetPosition()); } @@ -226,26 +201,21 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS bitStream->Write(count); - for (auto* target : targets) - { + for (auto* target : targets) { bitStream->Write(target->GetObjectID()); } - for (auto* target : targets) - { + for (auto* target : targets) { branch.target = target->GetObjectID(); this->m_action->Calculate(context, bitStream, branch); } - } - else - { + } else { this->m_missAction->Calculate(context, bitStream, branch); } } -void TacArcBehavior::Load() -{ +void TacArcBehavior::Load() { this->m_usePickedTarget = GetBoolean("use_picked_target"); this->m_action = GetAction("action"); diff --git a/dGame/dBehaviors/TacArcBehavior.h b/dGame/dBehaviors/TacArcBehavior.h index 774e65a1..211ed6b7 100644 --- a/dGame/dBehaviors/TacArcBehavior.h +++ b/dGame/dBehaviors/TacArcBehavior.h @@ -45,11 +45,10 @@ public: /* * Inherited */ - - explicit TacArcBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + + explicit TacArcBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/TargetCasterBehavior.cpp b/dGame/dBehaviors/TargetCasterBehavior.cpp index 41b5e73a..fb76b90d 100644 --- a/dGame/dBehaviors/TargetCasterBehavior.cpp +++ b/dGame/dBehaviors/TargetCasterBehavior.cpp @@ -3,27 +3,23 @@ #include "BehaviorContext.h" -void TargetCasterBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void TargetCasterBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { branch.target = context->caster; this->m_action->Handle(context, bit_stream, branch); } -void TargetCasterBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) -{ +void TargetCasterBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { this->m_action->UnCast(context, branch); } -void TargetCasterBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) -{ +void TargetCasterBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { branch.target = context->caster; this->m_action->Calculate(context, bit_stream, branch); } -void TargetCasterBehavior::Load() -{ +void TargetCasterBehavior::Load() { this->m_action = GetAction("action"); } diff --git a/dGame/dBehaviors/TargetCasterBehavior.h b/dGame/dBehaviors/TargetCasterBehavior.h index 4054f81d..4f2a0f5f 100644 --- a/dGame/dBehaviors/TargetCasterBehavior.h +++ b/dGame/dBehaviors/TargetCasterBehavior.h @@ -5,18 +5,17 @@ class TargetCasterBehavior final : public Behavior { public: Behavior* m_action; - + /* * Inherited */ - explicit TargetCasterBehavior(const uint32_t behavior_id) : Behavior(behavior_id) - { + explicit TargetCasterBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; - void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; + void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/TauntBehavior.cpp b/dGame/dBehaviors/TauntBehavior.cpp index 8ccc3abc..7ed3b897 100644 --- a/dGame/dBehaviors/TauntBehavior.cpp +++ b/dGame/dBehaviors/TauntBehavior.cpp @@ -6,12 +6,10 @@ #include "dLogger.h" -void TauntBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void TauntBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("TauntBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -19,18 +17,15 @@ void TauntBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea auto* combatComponent = target->GetComponent(); - if (combatComponent != nullptr) - { + if (combatComponent != nullptr) { combatComponent->Taunt(context->originator, m_threatToAdd); } } -void TauntBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void TauntBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) - { + if (target == nullptr) { Game::logger->Log("TauntBehavior", "Failed to find target (%llu)!", branch.target); return; @@ -38,14 +33,12 @@ void TauntBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitSt auto* combatComponent = target->GetComponent(); - if (combatComponent != nullptr) - { + if (combatComponent != nullptr) { combatComponent->Taunt(context->originator, m_threatToAdd); } } -void TauntBehavior::Load() -{ +void TauntBehavior::Load() { this->m_threatToAdd = GetFloat("threat to add"); } diff --git a/dGame/dBehaviors/TauntBehavior.h b/dGame/dBehaviors/TauntBehavior.h index a482d0b5..3ae7db9d 100644 --- a/dGame/dBehaviors/TauntBehavior.h +++ b/dGame/dBehaviors/TauntBehavior.h @@ -6,13 +6,12 @@ class TauntBehavior final : public Behavior { public: float m_threatToAdd; - + /* * Inherited */ - explicit TauntBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit TauntBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/VentureVisionBehavior.cpp b/dGame/dBehaviors/VentureVisionBehavior.cpp index 9061deb7..93feb8e9 100644 --- a/dGame/dBehaviors/VentureVisionBehavior.cpp +++ b/dGame/dBehaviors/VentureVisionBehavior.cpp @@ -2,8 +2,8 @@ #include "BehaviorBranchContext.h" #include "CharacterComponent.h" #include "BehaviorContext.h" - -void VentureVisionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch){ + +void VentureVisionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto targetEntity = EntityManager::Instance()->GetEntity(branch.target); @@ -38,7 +38,7 @@ void VentureVisionBehavior::Timer(BehaviorContext* context, BehaviorBranchContex UnCast(context, branch); } -void VentureVisionBehavior::Load(){ +void VentureVisionBehavior::Load() { this->m_show_pet_digs = GetBoolean("show_pet_digs"); this->m_show_minibosses = GetBoolean("show_minibosses"); diff --git a/dGame/dBehaviors/VentureVisionBehavior.h b/dGame/dBehaviors/VentureVisionBehavior.h index 96b2642b..72758949 100644 --- a/dGame/dBehaviors/VentureVisionBehavior.h +++ b/dGame/dBehaviors/VentureVisionBehavior.h @@ -25,10 +25,9 @@ public: * Inherited */ - explicit VentureVisionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit VentureVisionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/VerifyBehavior.cpp b/dGame/dBehaviors/VerifyBehavior.cpp index 17ba1001..cbc3c6df 100644 --- a/dGame/dBehaviors/VerifyBehavior.cpp +++ b/dGame/dBehaviors/VerifyBehavior.cpp @@ -7,22 +7,17 @@ #include "dLogger.h" -void VerifyBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) -{ +void VerifyBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); auto success = true; - if (entity == nullptr) - { + if (entity == nullptr) { success = false; - } - else if (this->m_rangeCheck) - { + } else if (this->m_rangeCheck) { auto* self = EntityManager::Instance()->GetEntity(context->originator); - if (self == nullptr) - { + if (self == nullptr) { Game::logger->Log("VerifyBehavior", "Invalid self for (%llu)", context->originator); return; @@ -30,38 +25,31 @@ void VerifyBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS const auto distance = Vector3::DistanceSquared(self->GetPosition(), entity->GetPosition()); - if (distance > this->m_range * this->m_range) - { + if (distance > this->m_range * this->m_range) { success = false; } - } - else if (this->m_blockCheck) - { + } else if (this->m_blockCheck) { // TODO } - if (branch.target != LWOOBJID_EMPTY && branch.target != context->originator) - { + if (branch.target != LWOOBJID_EMPTY && branch.target != context->originator) { bitStream->Write(success); - if (success) - { + if (success) { bitStream->Write(1); bitStream->Write0(); bitStream->Write0(); } } - if (!success) - { + if (!success) { branch.target = LWOOBJID_EMPTY; } m_action->Calculate(context, bitStream, branch); } -void VerifyBehavior::Load() -{ +void VerifyBehavior::Load() { this->m_rangeCheck = GetBoolean("check_range"); this->m_blockCheck = GetBoolean("check blocking"); diff --git a/dGame/dBehaviors/VerifyBehavior.h b/dGame/dBehaviors/VerifyBehavior.h index f4f295aa..b38d1953 100644 --- a/dGame/dBehaviors/VerifyBehavior.h +++ b/dGame/dBehaviors/VerifyBehavior.h @@ -16,10 +16,9 @@ public: * Inherited */ - explicit VerifyBehavior(const uint32_t behaviorId) : Behavior(behaviorId) - { + explicit VerifyBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 022b3e6c..2ac2cf04 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -37,12 +37,11 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) //Grab the aggro information from BaseCombatAI: auto componentQuery = CDClientDatabase::CreatePreppedStmt( "SELECT aggroRadius, tetherSpeed, pursuitSpeed, softTetherRadius, hardTetherRadius FROM BaseCombatAIComponent WHERE id = ?;"); - componentQuery.bind(1, (int) id); + componentQuery.bind(1, (int)id); auto componentResult = componentQuery.execQuery(); - if (!componentResult.eof()) - { + if (!componentResult.eof()) { if (!componentResult.fieldIsNull(0)) m_AggroRadius = componentResult.getFloatField(0); @@ -75,7 +74,7 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) */ auto skillQuery = CDClientDatabase::CreatePreppedStmt( "SELECT skillID, cooldown, behaviorID FROM SkillBehavior WHERE skillID IN (SELECT skillID FROM ObjectSkills WHERE objectTemplate = ?);"); - skillQuery.bind(1, (int) parent->GetLOT()); + skillQuery.bind(1, (int)parent->GetLOT()); auto result = skillQuery.execQuery(); @@ -110,11 +109,9 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance()->GetTable("PhysicsComponent"); - if (physicsComponentTable != nullptr) - { + if (physicsComponentTable != nullptr) { auto* info = physicsComponentTable->GetByID(componentID); - if (info != nullptr) - { + if (info != nullptr) { collisionGroup = info->bStatic ? COLLISION_GROUP_NEUTRAL : info->collisionGroup; } } @@ -166,37 +163,32 @@ void BaseCombatAIComponent::Update(const float deltaTime) { if (m_Target != LWOOBJID_EMPTY || (NiPoint3::DistanceSquared( m_StartPosition, m_Parent->GetPosition()) < 20 * 20 && m_TetherTime <= 0) - ) { + ) { GameMessages::SendStopFXEffect(m_Parent, true, "tether"); m_TetherEffectActive = false; } } - if (m_SoftTimer <= 0.0f) - { + if (m_SoftTimer <= 0.0f) { EntityManager::Instance()->SerializeEntity(m_Parent); m_SoftTimer = 5.0f; - } - else - { + } else { m_SoftTimer -= deltaTime; } if (m_Disabled || m_Parent->GetIsDead()) - return; + return; CalculateCombat(deltaTime); // Putting this here for now - if (m_StartPosition == NiPoint3::ZERO) - { + if (m_StartPosition == NiPoint3::ZERO) { m_StartPosition = m_Parent->GetPosition(); } m_MovementAI = m_Parent->GetComponent(); - if (m_MovementAI == nullptr) - { + if (m_MovementAI == nullptr) { return; } @@ -222,7 +214,7 @@ void BaseCombatAIComponent::Update(const float deltaTime) { break; case AiState::aggro: - OnAggro(); + OnAggro(); break; case AiState::tether: @@ -248,8 +240,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { auto* skillComponent = m_Parent->GetComponent(); - if (skillComponent == nullptr) - { + if (skillComponent == nullptr) { return; } @@ -257,8 +248,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { if (m_Disabled) return; - if (m_StunTime > 0.0f) - { + if (m_StunTime > 0.0f) { m_StunTime -= deltaTime; if (m_StunTime > 0.0f) { @@ -278,8 +268,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { if (m_Target != LWOOBJID_EMPTY && newTarget == LWOOBJID_EMPTY) { m_OutOfCombat = true; m_OutOfCombatTime = 1.0f; - } - else if (newTarget != LWOOBJID_EMPTY) { + } else if (newTarget != LWOOBJID_EMPTY) { m_OutOfCombat = false; m_OutOfCombatTime = 0.0f; } @@ -332,8 +321,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { } m_State = AiState::aggro; - } - else { + } else { m_State = AiState::idle; } @@ -359,8 +347,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { return; } - if (m_Target == LWOOBJID_EMPTY) - { + if (m_Target == LWOOBJID_EMPTY) { m_State = AiState::idle; return; @@ -370,13 +357,11 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { auto* target = GetTargetEntity(); - if (target != nullptr) - { + if (target != nullptr) { LookAt(target->GetPosition()); } - for (auto i = 0; i < m_SkillEntries.size(); ++i) - { + for (auto i = 0; i < m_SkillEntries.size(); ++i) { auto entry = m_SkillEntries.at(i); if (entry.cooldown > 0) { @@ -414,12 +399,10 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { auto* target = GetTargetEntity(); - if (target != nullptr && !m_DirtyThreat) - { + if (target != nullptr && !m_DirtyThreat) { const auto targetPosition = target->GetPosition(); - if (Vector3::DistanceSquared(targetPosition, m_StartPosition) < m_HardTetherRadius * m_HardTetherRadius) - { + if (Vector3::DistanceSquared(targetPosition, m_StartPosition) < m_HardTetherRadius * m_HardTetherRadius) { return m_Target; } @@ -428,8 +411,7 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { auto possibleTargets = GetTargetWithinAggroRange(); - if (possibleTargets.empty() && m_ThreatEntries.empty()) - { + if (possibleTargets.empty() && m_ThreatEntries.empty()) { m_DirtyThreat = false; return LWOOBJID_EMPTY; @@ -438,8 +420,7 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { Entity* optimalTarget = nullptr; float biggestThreat = 0; - for (const auto& entry : possibleTargets) - { + for (const auto& entry : possibleTargets) { auto* entity = EntityManager::Instance()->GetEntity(entry); if (entity == nullptr) { @@ -452,53 +433,43 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { const auto maxDistanceSquared = m_HardTetherRadius * m_HardTetherRadius; - if (Vector3::DistanceSquared(targetPosition, m_StartPosition) > maxDistanceSquared) - { - if (threat > 0) - { + if (Vector3::DistanceSquared(targetPosition, m_StartPosition) > maxDistanceSquared) { + if (threat > 0) { SetThreat(entry, 0); } continue; } - if (threat > biggestThreat) - { + if (threat > biggestThreat) { biggestThreat = threat; optimalTarget = entity; continue; } - const auto proximityThreat = - (Vector3::DistanceSquared(targetPosition, reference) - maxDistanceSquared) / 100; // Proximity threat takes last priority + const auto proximityThreat = -(Vector3::DistanceSquared(targetPosition, reference) - maxDistanceSquared) / 100; // Proximity threat takes last priority - if (proximityThreat > biggestThreat) - { + if (proximityThreat > biggestThreat) { biggestThreat = proximityThreat; optimalTarget = entity; } } - if (!m_DirtyThreat) - { - if (optimalTarget == nullptr) - { + if (!m_DirtyThreat) { + if (optimalTarget == nullptr) { return LWOOBJID_EMPTY; - } - else - { + } else { return optimalTarget->GetObjectID(); } } - std::vector deadThreats {}; + std::vector deadThreats{}; - for (const auto& threatTarget : m_ThreatEntries) - { + for (const auto& threatTarget : m_ThreatEntries) { auto* entity = EntityManager::Instance()->GetEntity(threatTarget.first); - if (entity == nullptr) - { + if (entity == nullptr) { deadThreats.push_back(threatTarget.first); continue; @@ -506,33 +477,27 @@ LWOOBJID BaseCombatAIComponent::FindTarget() { const auto targetPosition = entity->GetPosition(); - if (Vector3::DistanceSquared(targetPosition, m_StartPosition) > m_HardTetherRadius * m_HardTetherRadius) - { + if (Vector3::DistanceSquared(targetPosition, m_StartPosition) > m_HardTetherRadius * m_HardTetherRadius) { deadThreats.push_back(threatTarget.first); continue; } - if (threatTarget.second > biggestThreat) - { + if (threatTarget.second > biggestThreat) { optimalTarget = entity; biggestThreat = threatTarget.second; } } - for (const auto& deadThreat : deadThreats) - { + for (const auto& deadThreat : deadThreats) { SetThreat(deadThreat, 0); } m_DirtyThreat = false; - if (optimalTarget == nullptr) - { + if (optimalTarget == nullptr) { return LWOOBJID_EMPTY; - } - else - { + } else { return optimalTarget->GetObjectID(); } } @@ -598,12 +563,10 @@ bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const { auto* quickbuild = entity->GetComponent(); - if (quickbuild != nullptr) - { + if (quickbuild != nullptr) { const auto state = quickbuild->GetState(); - if (state != REBUILD_COMPLETED) - { + if (state != REBUILD_COMPLETED) { return false; } } @@ -630,9 +593,9 @@ Entity* BaseCombatAIComponent::GetTargetEntity() const { } void BaseCombatAIComponent::Taunt(LWOOBJID offender, float threat) { - // Can't taunt self - if (offender == m_Parent->GetObjectID()) - return; + // Can't taunt self + if (offender == m_Parent->GetObjectID()) + return; m_ThreatEntries[offender] += threat; m_DirtyThreat = true; @@ -649,21 +612,18 @@ float BaseCombatAIComponent::GetThreat(LWOOBJID offender) { void BaseCombatAIComponent::SetThreat(LWOOBJID offender, float threat) { if (threat == 0) { m_ThreatEntries.erase(offender); - } - else { + } else { m_ThreatEntries[offender] = threat; } m_DirtyThreat = true; } -const NiPoint3& BaseCombatAIComponent::GetStartPosition() const -{ +const NiPoint3& BaseCombatAIComponent::GetStartPosition() const { return m_StartPosition; } -void BaseCombatAIComponent::ClearThreat() -{ +void BaseCombatAIComponent::ClearThreat() { m_ThreatEntries.clear(); m_DirtyThreat = true; @@ -727,14 +687,12 @@ void BaseCombatAIComponent::OnAggro() { // If the player's position is within range, attack if (Vector3::DistanceSquared(currentPos, targetPos) <= m_AttackRadius * m_AttackRadius) { m_MovementAI->Stop(); - } - else if (Vector3::DistanceSquared(m_StartPosition, targetPos) > m_HardTetherRadius * m_HardTetherRadius) //Return to spawn if we're too far + } else if (Vector3::DistanceSquared(m_StartPosition, targetPos) > m_HardTetherRadius * m_HardTetherRadius) //Return to spawn if we're too far { m_MovementAI->SetSpeed(m_PursuitSpeed); m_MovementAI->SetDestination(m_StartPosition); - } - else //Chase the player's new position + } else //Chase the player's new position { if (IsMech() && Vector3::DistanceSquared(targetPos, currentPos) > m_AttackRadius * m_AttackRadius * 3 * 3) return; @@ -762,16 +720,14 @@ void BaseCombatAIComponent::OnTether() { if (Vector3::DistanceSquared(currentPos, targetPos) <= m_AttackRadius * m_AttackRadius) { m_MovementAI->Stop(); - } - else if (Vector3::DistanceSquared(m_StartPosition, targetPos) > m_HardTetherRadius * m_HardTetherRadius) //Return to spawn if we're too far + } else if (Vector3::DistanceSquared(m_StartPosition, targetPos) > m_HardTetherRadius * m_HardTetherRadius) //Return to spawn if we're too far { m_MovementAI->SetSpeed(m_PursuitSpeed); m_MovementAI->SetDestination(m_StartPosition); m_State = AiState::aggro; - } - else { + } else { if (IsMech() && Vector3::DistanceSquared(targetPos, currentPos) > m_AttackRadius * m_AttackRadius * 3 * 3) return; m_MovementAI->SetSpeed(m_PursuitSpeed); @@ -790,23 +746,19 @@ void BaseCombatAIComponent::SetStunned(const bool value) { m_Stunned = value; } -bool BaseCombatAIComponent::GetStunImmune() const -{ +bool BaseCombatAIComponent::GetStunImmune() const { return m_StunImmune; } -void BaseCombatAIComponent::SetStunImmune(bool value) -{ +void BaseCombatAIComponent::SetStunImmune(bool value) { m_StunImmune = value; } -float BaseCombatAIComponent::GetTetherSpeed() const -{ +float BaseCombatAIComponent::GetTetherSpeed() const { return m_TetherSpeed; } -void BaseCombatAIComponent::SetTetherSpeed(float value) -{ +void BaseCombatAIComponent::SetTetherSpeed(float value) { m_TetherSpeed = value; } @@ -828,34 +780,28 @@ void BaseCombatAIComponent::SetAggroRadius(const float value) { m_AggroRadius = value; } -void BaseCombatAIComponent::LookAt(const NiPoint3& point) -{ - if (m_Stunned) - { +void BaseCombatAIComponent::LookAt(const NiPoint3& point) { + if (m_Stunned) { return; } m_Parent->SetRotation(NiQuaternion::LookAt(m_Parent->GetPosition(), point)); } -void BaseCombatAIComponent::SetDisabled(bool value) -{ +void BaseCombatAIComponent::SetDisabled(bool value) { m_Disabled = value; } -bool BaseCombatAIComponent::GetDistabled() const -{ +bool BaseCombatAIComponent::GetDistabled() const { return m_Disabled; } -void BaseCombatAIComponent::Sleep() -{ +void BaseCombatAIComponent::Sleep() { m_dpEntity->SetSleeping(true); m_dpEntityEnemy->SetSleeping(true); } -void BaseCombatAIComponent::Wake() -{ +void BaseCombatAIComponent::Wake() { m_dpEntity->SetSleeping(false); m_dpEntityEnemy->SetSleeping(false); -} \ No newline at end of file +} diff --git a/dGame/dComponents/BaseCombatAIComponent.h b/dGame/dComponents/BaseCombatAIComponent.h index ff291736..70a88a42 100644 --- a/dGame/dComponents/BaseCombatAIComponent.h +++ b/dGame/dComponents/BaseCombatAIComponent.h @@ -60,318 +60,318 @@ public: */ AiState GetState() const { return m_State; } - /** - * Set the current behavioral state of the enemy - * @param state the state to change to - */ + /** + * Set the current behavioral state of the enemy + * @param state the state to change to + */ void SetState(AiState state) { m_State = state; } - /** - * Checks if the target may be an enemy of this entity - * @param target the target to check for - * @return whether the target is a valid enemy for this entity or not - */ + /** + * Checks if the target may be an enemy of this entity + * @param target the target to check for + * @return whether the target is a valid enemy for this entity or not + */ bool IsEnemy(LWOOBJID target) const; - /** - * Gets the current target ID that this entity will attack - * @return the current target ID of this entity - */ + /** + * Gets the current target ID that this entity will attack + * @return the current target ID of this entity + */ LWOOBJID GetTarget() const { return m_Target; } - /** - * Sets the target that this entity will attack - * @param target the target to set - */ + /** + * Sets the target that this entity will attack + * @param target the target to set + */ void SetTarget(LWOOBJID target); - /** - * Gets the current target entity that this entity will attack - * @return the current target entity of this entity - */ + /** + * Gets the current target entity that this entity will attack + * @return the current target entity of this entity + */ Entity* GetTargetEntity() const; - /** - * Taunts this entity, making it a higher or lower threat for this entity. Increasing or decreasing the chance to - * be attacked. - * @param offender the entity that triggered the taunt - * @param threat how high to increase the threat for the offender - */ + /** + * Taunts this entity, making it a higher or lower threat for this entity. Increasing or decreasing the chance to + * be attacked. + * @param offender the entity that triggered the taunt + * @param threat how high to increase the threat for the offender + */ void Taunt(LWOOBJID offender, float threat); - /** - * Gets the current threat level for an offending entity - * @param offender the entity to get the threat for - * @return the current threat level of the offending entity, 0 if the entity is not a threat - */ + /** + * Gets the current threat level for an offending entity + * @param offender the entity to get the threat for + * @return the current threat level of the offending entity, 0 if the entity is not a threat + */ float GetThreat(LWOOBJID offender); - /** - * Sets the threat level for an entity - * @param offender the entity to set the threat level for - * @param threat the threat level to set - */ + /** + * Sets the threat level for an entity + * @param offender the entity to set the threat level for + * @param threat the threat level to set + */ void SetThreat(LWOOBJID offender, float threat); - /** - * Gets the position where the entity spawned - * @return the position where the entity spawned - */ + /** + * Gets the position where the entity spawned + * @return the position where the entity spawned + */ const NiPoint3& GetStartPosition() const; - /** - * Removes all threats for this entities, and thus chances for it attacking other entities - */ + /** + * Removes all threats for this entities, and thus chances for it attacking other entities + */ void ClearThreat(); - /** - * Makes the entity continue to wander to a random point around it's starting position - */ + /** + * Makes the entity continue to wander to a random point around it's starting position + */ void Wander(); - /** - * Continues a step in the aggro state, making sure that the entity is around its start position, if an entity - * crosses its aggro range this will set the state to tether. - */ + /** + * Continues a step in the aggro state, making sure that the entity is around its start position, if an entity + * crosses its aggro range this will set the state to tether. + */ void OnAggro(); - /** - * Continues a step in the tether state, making the entity run towards its target, if the target is outside of its - * tether range, this will change the state to aggro - */ + /** + * Continues a step in the tether state, making the entity run towards its target, if the target is outside of its + * tether range, this will change the state to aggro + */ void OnTether(); - /** - * Gets whether or not the entity is currently stunned - * @return whether the entity is currently stunned - */ - bool GetStunned() const; + /** + * Gets whether or not the entity is currently stunned + * @return whether the entity is currently stunned + */ + bool GetStunned() const; - /** - * (un)stuns the entity, determining whether it'll be able to attack other entities - * @param value whether the enemy is stunned - */ + /** + * (un)stuns the entity, determining whether it'll be able to attack other entities + * @param value whether the enemy is stunned + */ void SetStunned(bool value); - /** - * Gets if this entity may be stunned - * @return if this entity may be stunned - */ + /** + * Gets if this entity may be stunned + * @return if this entity may be stunned + */ bool GetStunImmune() const; - /** - * Set the stun immune value, determining if the entity may be stunned - * @param value - */ + /** + * Set the stun immune value, determining if the entity may be stunned + * @param value + */ void SetStunImmune(bool value); - /** - * Gets the current speed at which an entity runs when tethering - * @return the current speed at which an entity runs when tethering - */ + /** + * Gets the current speed at which an entity runs when tethering + * @return the current speed at which an entity runs when tethering + */ float GetTetherSpeed() const; - /** - * Sets the speed at which an entity will tether - * @param value the new tether speed - */ + /** + * Sets the speed at which an entity will tether + * @param value the new tether speed + */ void SetTetherSpeed(float value); - /** - * Stuns the entity for a certain amount of time, will not work if the entity is stun immune - * @param time the time to stun the entity, if stunnable - */ + /** + * Stuns the entity for a certain amount of time, will not work if the entity is stun immune + * @param time the time to stun the entity, if stunnable + */ void Stun(float time); - /** - * Gets the radius that will cause this entity to get aggro'd, causing a target chase - * @return the aggro radius of the entity - */ + /** + * Gets the radius that will cause this entity to get aggro'd, causing a target chase + * @return the aggro radius of the entity + */ float GetAggroRadius() const; - /** - * Sets the aggro radius, causing the entity to start chasing enemies in this range - * @param value the aggro radius to set - */ + /** + * Sets the aggro radius, causing the entity to start chasing enemies in this range + * @param value the aggro radius to set + */ void SetAggroRadius(float value); - /** - * Makes the entity look at a certain point in space - * @param point the point to look at - */ + /** + * Makes the entity look at a certain point in space + * @param point the point to look at + */ void LookAt(const NiPoint3& point); - /** - * (dis)ables the AI, causing it to stop/start attacking enemies - * @param value - */ + /** + * (dis)ables the AI, causing it to stop/start attacking enemies + * @param value + */ void SetDisabled(bool value); - /** - * Gets the current state of the AI, whether or not it's looking for enemies to attack - * @return - */ + /** + * Gets the current state of the AI, whether or not it's looking for enemies to attack + * @return + */ bool GetDistabled() const; - /** - * Turns the entity asleep, stopping updates to its physics volumes - */ + /** + * Turns the entity asleep, stopping updates to its physics volumes + */ void Sleep(); - /** - * Wakes the entity, allowing updates to its physics volumes - */ + /** + * Wakes the entity, allowing updates to its physics volumes + */ void Wake(); private: - /** - * Returns the current target or the target that currently is the largest threat to this entity - * @return the current highest priority enemy of this entity - */ + /** + * Returns the current target or the target that currently is the largest threat to this entity + * @return the current highest priority enemy of this entity + */ LWOOBJID FindTarget(); - /** - * Handles anything attack related for the game loop, e.g.: finding targets, sticking with targets and attacking - * them, depending on cooldowns. - * @param deltaTime the time since the last game tick - */ + /** + * Handles anything attack related for the game loop, e.g.: finding targets, sticking with targets and attacking + * them, depending on cooldowns. + * @param deltaTime the time since the last game tick + */ void CalculateCombat(float deltaTime); - /** - * Gets all the targets that are in the aggro collision phantom of this entity - * @return the targets within the aggro range of this entity - */ + /** + * Gets all the targets that are in the aggro collision phantom of this entity + * @return the targets within the aggro range of this entity + */ std::vector GetTargetWithinAggroRange() const; - /** - * The current state of the AI - */ + /** + * The current state of the AI + */ AiState m_State; - /** - * The target this entity is currently trying to attack - */ + /** + * The target this entity is currently trying to attack + */ LWOOBJID m_Target; - /** - * The aggro physics volumes of this entity - */ + /** + * The aggro physics volumes of this entity + */ dpEntity* m_dpEntity; dpEntity* m_dpEntityEnemy; - /** - * The max radius of this entity to an enemy allowing it to be chased - */ + /** + * The max radius of this entity to an enemy allowing it to be chased + */ float m_HardTetherRadius = 100; - /** - * A soft radius for the tether, currently unused - */ + /** + * A soft radius for the tether, currently unused + */ float m_SoftTetherRadius = 25; - /** - * The speed at which this entity chases enemies - */ + /** + * The speed at which this entity chases enemies + */ float m_PursuitSpeed = 2; - /** - * The radius that can cause enemies to aggro this entity - */ + /** + * The radius that can cause enemies to aggro this entity + */ float m_AggroRadius = 25; - /** - * The speed at which an enemy wanders around - */ + /** + * The speed at which an enemy wanders around + */ float m_TetherSpeed = 4; - /** - * How close this entity needs to be to an enemy to allow attacks - */ + /** + * How close this entity needs to be to an enemy to allow attacks + */ float m_AttackRadius = 5.0f; - /** - * Timer before we start attacking others - */ + /** + * Timer before we start attacking others + */ float m_Timer = 0.0f; - /** - * Timer to serializing this entity - */ + /** + * Timer to serializing this entity + */ float m_SoftTimer = 0.0f; - /** - * The skills this entity can cast on enemies - */ + /** + * The skills this entity can cast on enemies + */ std::vector m_SkillEntries; - /** - * The current enemies and their respective threats to this entity - */ + /** + * The current enemies and their respective threats to this entity + */ std::map m_ThreatEntries; - /** - * The component that handles movement AI, also owned by this entity - */ + /** + * The component that handles movement AI, also owned by this entity + */ MovementAIComponent* m_MovementAI; - /** - * The position at which this entity spawned - */ + /** + * The position at which this entity spawned + */ NiPoint3 m_StartPosition; - /** - * For how long this entity has been stunned - */ + /** + * For how long this entity has been stunned + */ float m_StunTime = 0; - /** - * If this entity is stunned - */ + /** + * If this entity is stunned + */ bool m_Stunned = false; - /** - * If this entity is immune to stunds - */ + /** + * If this entity is immune to stunds + */ bool m_StunImmune = false; - /** - * Time taken between actions - */ + /** + * Time taken between actions + */ float m_Downtime = 0; - /** - * How long this entity needs to execute its skill - */ + /** + * How long this entity needs to execute its skill + */ float m_SkillTime = 0; - /** - * If the entity is currently showing the exclamation mark icon above its head - */ + /** + * If the entity is currently showing the exclamation mark icon above its head + */ bool m_TetherEffectActive = false; - /** - * How long the tether effect will remain active - */ + /** + * How long the tether effect will remain active + */ float m_TetherTime = 0; - /** - * How long until we will consider this entity out of combat, resetting its health and armor - */ + /** + * How long until we will consider this entity out of combat, resetting its health and armor + */ float m_OutOfCombatTime = 0; - /** - * If the entity is currently out of combat, resetting its health and armor if it just came out of combat - */ + /** + * If the entity is currently out of combat, resetting its health and armor if it just came out of combat + */ bool m_OutOfCombat = false; - /** - * If the AI is currently disabled - */ + /** + * If the AI is currently disabled + */ bool m_Disabled = false; - /** - * If the threat list should be updated - */ + /** + * If the threat list should be updated + */ bool m_DirtyThreat = false; /** diff --git a/dGame/dComponents/BouncerComponent.cpp b/dGame/dComponents/BouncerComponent.cpp index 2e24b1ed..1f32d6e5 100644 --- a/dGame/dComponents/BouncerComponent.cpp +++ b/dGame/dComponents/BouncerComponent.cpp @@ -13,8 +13,7 @@ BouncerComponent::BouncerComponent(Entity* parent) : Component(parent) { m_PetBouncerEnabled = false; m_PetSwitchLoaded = false; - if (parent->GetLOT() == 7625) - { + if (parent->GetLOT() == 7625) { LookupPetSwitch(); } } @@ -22,68 +21,56 @@ BouncerComponent::BouncerComponent(Entity* parent) : Component(parent) { BouncerComponent::~BouncerComponent() { } -void BouncerComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags){ +void BouncerComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { outBitStream->Write(m_PetEnabled); if (m_PetEnabled) { outBitStream->Write(m_PetBouncerEnabled); } } -Entity* BouncerComponent::GetParentEntity() const -{ +Entity* BouncerComponent::GetParentEntity() const { return m_Parent; } -void BouncerComponent::SetPetEnabled(bool value) -{ +void BouncerComponent::SetPetEnabled(bool value) { m_PetEnabled = value; EntityManager::Instance()->SerializeEntity(m_Parent); } -void BouncerComponent::SetPetBouncerEnabled(bool value) -{ +void BouncerComponent::SetPetBouncerEnabled(bool value) { m_PetBouncerEnabled = value; GameMessages::SendBouncerActiveStatus(m_Parent->GetObjectID(), value, UNASSIGNED_SYSTEM_ADDRESS); EntityManager::Instance()->SerializeEntity(m_Parent); - if (value) - { + if (value) { GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), 1513, u"create", "PetOnSwitch", LWOOBJID_EMPTY, 1, 1, true); - } - else - { + } else { GameMessages::SendStopFXEffect(m_Parent, true, "PetOnSwitch"); } } -bool BouncerComponent::GetPetEnabled() const -{ +bool BouncerComponent::GetPetEnabled() const { return m_PetEnabled; } -bool BouncerComponent::GetPetBouncerEnabled() const -{ +bool BouncerComponent::GetPetBouncerEnabled() const { return m_PetBouncerEnabled; } -void BouncerComponent::LookupPetSwitch() -{ +void BouncerComponent::LookupPetSwitch() { const auto& groups = m_Parent->GetGroups(); - for (const auto& group : groups) - { + for (const auto& group : groups) { const auto& entities = EntityManager::Instance()->GetEntitiesInGroup(group); - for (auto* entity : entities) - { + for (auto* entity : entities) { auto* switchComponent = entity->GetComponent(); - if (switchComponent != nullptr) - { + if (switchComponent != nullptr) { switchComponent->SetPetBouncer(this); m_PetSwitchLoaded = true; @@ -96,12 +83,11 @@ void BouncerComponent::LookupPetSwitch() } } - if (!m_PetSwitchLoaded) - { + if (!m_PetSwitchLoaded) { Game::logger->Log("BouncerComponent", "Failed to load pet bouncer"); m_Parent->AddCallbackTimer(0.5f, [this]() { LookupPetSwitch(); - }); + }); } } diff --git a/dGame/dComponents/BouncerComponent.h b/dGame/dComponents/BouncerComponent.h index 557f737f..f179998b 100644 --- a/dGame/dComponents/BouncerComponent.h +++ b/dGame/dComponents/BouncerComponent.h @@ -12,7 +12,7 @@ class BouncerComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_BOUNCER; - + BouncerComponent(Entity* parentEntity); ~BouncerComponent() override; @@ -20,50 +20,50 @@ public: Entity* GetParentEntity() const; - /** - * Sets whether or not this bouncer needs to be activated by a pet - * @param value whether or not this bouncer needs to be activated by a pet - */ + /** + * Sets whether or not this bouncer needs to be activated by a pet + * @param value whether or not this bouncer needs to be activated by a pet + */ void SetPetEnabled(bool value); - /** - * Sets whether or not this bouncer is currently being activated by a pet, allowing entities to bounce off of it, - * also displays FX accordingly. - * @param value whether or not this bouncer is activated by a pet - */ + /** + * Sets whether or not this bouncer is currently being activated by a pet, allowing entities to bounce off of it, + * also displays FX accordingly. + * @param value whether or not this bouncer is activated by a pet + */ void SetPetBouncerEnabled(bool value); - /** - * Gets whether this bouncer should be enabled using pets - * @return whether this bouncer should be enabled using pets - */ + /** + * Gets whether this bouncer should be enabled using pets + * @return whether this bouncer should be enabled using pets + */ bool GetPetEnabled() const; - /** - * Gets whether this bouncer is currently activated by a pet - * @return whether this bouncer is currently activated by a pet - */ + /** + * Gets whether this bouncer is currently activated by a pet + * @return whether this bouncer is currently activated by a pet + */ bool GetPetBouncerEnabled() const; - /** - * Finds the switch used to activate this bouncer if its pet-enabled and stores this components' state there - */ + /** + * Finds the switch used to activate this bouncer if its pet-enabled and stores this components' state there + */ void LookupPetSwitch(); private: - /** - * Whether this bouncer needs to be activated by a pet - */ + /** + * Whether this bouncer needs to be activated by a pet + */ bool m_PetEnabled; - /** - * Whether this bouncer is currently being activated by a pet - */ + /** + * Whether this bouncer is currently being activated by a pet + */ bool m_PetBouncerEnabled; - /** - * Whether the pet switch for this bouncer has been located - */ + /** + * Whether the pet switch for this bouncer has been located + */ bool m_PetSwitchLoaded; }; diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index 5874f8a6..ecb10017 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -10,28 +10,23 @@ #include "ControllablePhysicsComponent.h" #include "EntityManager.h" -std::unordered_map> BuffComponent::m_Cache {}; +std::unordered_map> BuffComponent::m_Cache{}; -BuffComponent::BuffComponent(Entity* parent) : Component(parent) -{ +BuffComponent::BuffComponent(Entity* parent) : Component(parent) { } BuffComponent::~BuffComponent() { } void BuffComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - if (!bIsInitialUpdate) return; - if (m_Buffs.empty()) - { + if (!bIsInitialUpdate) return; + if (m_Buffs.empty()) { outBitStream->Write0(); - } - else - { + } else { outBitStream->Write1(); outBitStream->Write(m_Buffs.size()); - for (const auto& buff : m_Buffs) - { + for (const auto& buff : m_Buffs) { outBitStream->Write(buff.first); outBitStream->Write0(); outBitStream->Write0(); @@ -53,21 +48,17 @@ void BuffComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUp outBitStream->Write0(); } -void BuffComponent::Update(float deltaTime) -{ +void BuffComponent::Update(float deltaTime) { /** * Loop through all buffs and apply deltaTime to ther time. * If they have expired, remove the buff and break. */ - for (auto& buff : m_Buffs) - { + for (auto& buff : m_Buffs) { // For damage buffs - if (buff.second.tick != 0.0f && buff.second.stacks > 0) - { + if (buff.second.tick != 0.0f && buff.second.stacks > 0) { buff.second.tickTime -= deltaTime; - if (buff.second.tickTime <= 0.0f) - { + if (buff.second.tickTime <= 0.0f) { buff.second.tickTime = buff.second.tick; buff.second.stacks--; @@ -76,15 +67,13 @@ void BuffComponent::Update(float deltaTime) } // These are indefinate buffs, don't update them. - if (buff.second.time == 0.0f) - { + if (buff.second.time == 0.0f) { continue; } buff.second.time -= deltaTime; - if (buff.second.time <= 0.0f) - { + if (buff.second.time <= 0.0f) { RemoveBuff(buff.first); break; @@ -93,28 +82,24 @@ void BuffComponent::Update(float deltaTime) } void BuffComponent::ApplyBuff(const int32_t id, const float duration, const LWOOBJID source, bool addImmunity, - bool cancelOnDamaged, bool cancelOnDeath, bool cancelOnLogout, bool cancelOnRemoveBuff, - bool cancelOnUi, bool cancelOnUnequip, bool cancelOnZone) -{ + bool cancelOnDamaged, bool cancelOnDeath, bool cancelOnLogout, bool cancelOnRemoveBuff, + bool cancelOnUi, bool cancelOnUnequip, bool cancelOnZone) { // Prevent buffs from stacking. - if (HasBuff(id)) - { + if (HasBuff(id)) { return; } - GameMessages::SendAddBuff(const_cast(m_Parent->GetObjectID()), source, (uint32_t) id, - (uint32_t) duration * 1000, addImmunity, cancelOnDamaged, cancelOnDeath, - cancelOnLogout, cancelOnRemoveBuff, cancelOnUi, cancelOnUnequip, cancelOnZone); + GameMessages::SendAddBuff(const_cast(m_Parent->GetObjectID()), source, (uint32_t)id, + (uint32_t)duration * 1000, addImmunity, cancelOnDamaged, cancelOnDeath, + cancelOnLogout, cancelOnRemoveBuff, cancelOnUi, cancelOnUnequip, cancelOnZone); float tick = 0; float stacks = 0; int32_t behaviorID = 0; const auto& parameters = GetBuffParameters(id); - for (const auto& parameter : parameters) - { - if (parameter.name == "overtime") - { + for (const auto& parameter : parameters) { + if (parameter.name == "overtime") { auto* behaviorTemplateTable = CDClientManager::Instance()->GetTable("SkillBehavior"); behaviorID = behaviorTemplateTable->GetSkillByID(parameter.values[0]).behaviorID; @@ -138,12 +123,10 @@ void BuffComponent::ApplyBuff(const int32_t id, const float duration, const LWOO m_Buffs.emplace(id, buff); } -void BuffComponent::RemoveBuff(int32_t id) -{ +void BuffComponent::RemoveBuff(int32_t id) { const auto& iter = m_Buffs.find(id); - if (iter == m_Buffs.end()) - { + if (iter == m_Buffs.end()) { return; } @@ -152,18 +135,14 @@ void BuffComponent::RemoveBuff(int32_t id) RemoveBuffEffect(id); } -bool BuffComponent::HasBuff(int32_t id) -{ +bool BuffComponent::HasBuff(int32_t id) { return m_Buffs.find(id) != m_Buffs.end(); } -void BuffComponent::ApplyBuffEffect(int32_t id) -{ +void BuffComponent::ApplyBuffEffect(int32_t id) { const auto& parameters = GetBuffParameters(id); - for (const auto& parameter : parameters) - { - if (parameter.name == "max_health") - { + for (const auto& parameter : parameters) { + if (parameter.name == "max_health") { const auto maxHealth = parameter.value; auto* destroyable = this->GetParent()->GetComponent(); @@ -171,9 +150,7 @@ void BuffComponent::ApplyBuffEffect(int32_t id) if (destroyable == nullptr) return; destroyable->SetMaxHealth(destroyable->GetMaxHealth() + maxHealth); - } - else if (parameter.name == "max_armor") - { + } else if (parameter.name == "max_armor") { const auto maxArmor = parameter.value; auto* destroyable = this->GetParent()->GetComponent(); @@ -181,9 +158,7 @@ void BuffComponent::ApplyBuffEffect(int32_t id) if (destroyable == nullptr) return; destroyable->SetMaxArmor(destroyable->GetMaxArmor() + maxArmor); - } - else if (parameter.name == "max_imagination") - { + } else if (parameter.name == "max_imagination") { const auto maxImagination = parameter.value; auto* destroyable = this->GetParent()->GetComponent(); @@ -191,9 +166,7 @@ void BuffComponent::ApplyBuffEffect(int32_t id) if (destroyable == nullptr) return; destroyable->SetMaxImagination(destroyable->GetMaxImagination() + maxImagination); - } - else if (parameter.name == "speed") - { + } else if (parameter.name == "speed") { const auto speed = parameter.value; auto* controllablePhysicsComponent = this->GetParent()->GetComponent(); @@ -209,13 +182,10 @@ void BuffComponent::ApplyBuffEffect(int32_t id) } } -void BuffComponent::RemoveBuffEffect(int32_t id) -{ +void BuffComponent::RemoveBuffEffect(int32_t id) { const auto& parameters = GetBuffParameters(id); - for (const auto& parameter : parameters) - { - if (parameter.name == "max_health") - { + for (const auto& parameter : parameters) { + if (parameter.name == "max_health") { const auto maxHealth = parameter.value; auto* destroyable = this->GetParent()->GetComponent(); @@ -223,9 +193,7 @@ void BuffComponent::RemoveBuffEffect(int32_t id) if (destroyable == nullptr) return; destroyable->SetMaxHealth(destroyable->GetMaxHealth() - maxHealth); - } - else if (parameter.name == "max_armor") - { + } else if (parameter.name == "max_armor") { const auto maxArmor = parameter.value; auto* destroyable = this->GetParent()->GetComponent(); @@ -233,9 +201,7 @@ void BuffComponent::RemoveBuffEffect(int32_t id) if (destroyable == nullptr) return; destroyable->SetMaxArmor(destroyable->GetMaxArmor() - maxArmor); - } - else if (parameter.name == "max_imagination") - { + } else if (parameter.name == "max_imagination") { const auto maxImagination = parameter.value; auto* destroyable = this->GetParent()->GetComponent(); @@ -243,9 +209,7 @@ void BuffComponent::RemoveBuffEffect(int32_t id) if (destroyable == nullptr) return; destroyable->SetMaxImagination(destroyable->GetMaxImagination() - maxImagination); - } - else if (parameter.name == "speed") - { + } else if (parameter.name == "speed") { const auto speed = parameter.value; auto* controllablePhysicsComponent = this->GetParent()->GetComponent(); @@ -261,36 +225,29 @@ void BuffComponent::RemoveBuffEffect(int32_t id) } } -void BuffComponent::RemoveAllBuffs() -{ - for (const auto& buff : m_Buffs) - { +void BuffComponent::RemoveAllBuffs() { + for (const auto& buff : m_Buffs) { RemoveBuffEffect(buff.first); } m_Buffs.clear(); } -void BuffComponent::Reset() -{ +void BuffComponent::Reset() { RemoveAllBuffs(); } -void BuffComponent::ReApplyBuffs() -{ - for (const auto& buff : m_Buffs) - { +void BuffComponent::ReApplyBuffs() { + for (const auto& buff : m_Buffs) { ApplyBuffEffect(buff.first); } } -Entity* BuffComponent::GetParent() const -{ +Entity* BuffComponent::GetParent() const { return m_Parent; } -void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) -{ +void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { // Load buffs auto* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); @@ -298,15 +255,13 @@ void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) auto* buffElement = dest->FirstChildElement("buff"); // Old character, no buffs to load - if (buffElement == nullptr) - { + if (buffElement == nullptr) { return; } auto* buffEntry = buffElement->FirstChildElement("b"); - while (buffEntry != nullptr) - { + while (buffEntry != nullptr) { int32_t id = buffEntry->IntAttribute("id"); float t = buffEntry->FloatAttribute("t"); float tk = buffEntry->FloatAttribute("tk"); @@ -328,27 +283,22 @@ void BuffComponent::LoadFromXml(tinyxml2::XMLDocument* doc) } } -void BuffComponent::UpdateXml(tinyxml2::XMLDocument* doc) -{ +void BuffComponent::UpdateXml(tinyxml2::XMLDocument* doc) { // Save buffs auto* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); // Make sure we have a clean buff element. auto* buffElement = dest->FirstChildElement("buff"); - if (buffElement == nullptr) - { + if (buffElement == nullptr) { buffElement = doc->NewElement("buff"); dest->LinkEndChild(buffElement); - } - else - { + } else { buffElement->DeleteChildren(); } - for (const auto& buff : m_Buffs) - { + for (const auto& buff : m_Buffs) { auto* buffEntry = doc->NewElement("b"); buffEntry->SetAttribute("id", buff.first); @@ -362,46 +312,38 @@ void BuffComponent::UpdateXml(tinyxml2::XMLDocument* doc) } } -const std::vector& BuffComponent::GetBuffParameters(int32_t buffId) -{ +const std::vector& BuffComponent::GetBuffParameters(int32_t buffId) { const auto& pair = m_Cache.find(buffId); - if (pair != m_Cache.end()) - { + if (pair != m_Cache.end()) { return pair->second; } auto query = CDClientDatabase::CreatePreppedStmt( "SELECT * FROM BuffParameters WHERE BuffID = ?;"); - query.bind(1, (int) buffId); + query.bind(1, (int)buffId); auto result = query.execQuery(); - std::vector parameters {}; + std::vector parameters{}; - while (!result.eof()) - { + while (!result.eof()) { BuffParameter param; param.buffId = buffId; param.name = result.getStringField(1); param.value = result.getFloatField(2); - if (!result.fieldIsNull(3)) - { + if (!result.fieldIsNull(3)) { std::istringstream stream(result.getStringField(3)); std::string token; - while (std::getline(stream, token, ',')) - { - try - { + while (std::getline(stream, token, ',')) { + try { const auto value = std::stof(token); param.values.push_back(value); - } - catch (std::invalid_argument& exception) - { + } catch (std::invalid_argument& exception) { Game::logger->Log("BuffComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); } } diff --git a/dGame/dComponents/BuffComponent.h b/dGame/dComponents/BuffComponent.h index 49d7fec4..aa669b13 100644 --- a/dGame/dComponents/BuffComponent.h +++ b/dGame/dComponents/BuffComponent.h @@ -15,11 +15,11 @@ class Entity; */ struct BuffParameter { - int32_t buffId; - std::string name; - float value; - std::vector values; - int32_t effectId; + int32_t buffId; + std::string name; + float value; + std::vector values; + int32_t effectId; }; /** @@ -27,13 +27,13 @@ struct BuffParameter */ struct Buff { - int32_t id = 0; - float time = 0; - float tick = 0; - float tickTime = 0; - int32_t stacks = 0; - LWOOBJID source = 0; - int32_t behaviorID = 0; + int32_t id = 0; + float time = 0; + float tick = 0; + float tickTime = 0; + int32_t stacks = 0; + LWOOBJID source = 0; + int32_t behaviorID = 0; }; /** @@ -41,97 +41,97 @@ struct Buff */ class BuffComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_BUFF; - - explicit BuffComponent(Entity* parent); + static const uint32_t ComponentType = COMPONENT_TYPE_BUFF; - ~BuffComponent(); + explicit BuffComponent(Entity* parent); - Entity* GetParent() const; + ~BuffComponent(); - void LoadFromXml(tinyxml2::XMLDocument* doc) override; + Entity* GetParent() const; - void UpdateXml(tinyxml2::XMLDocument* doc) override; - - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; - void Update(float deltaTime) override; + void UpdateXml(tinyxml2::XMLDocument* doc) override; - /** - * Applies a buff to the parent entity - * @param id the id of the buff to apply - * @param duration the duration of the buff in seconds - * @param source an optional source entity that cast the buff - * @param addImmunity client flag - * @param cancelOnDamaged client flag to indicate that the buff should disappear when damaged - * @param cancelOnDeath client flag to indicate that the buff should disappear when dying - * @param cancelOnLogout client flag to indicate that the buff should disappear when logging out - * @param cancelOnRemoveBuff client flag to indicate that the buff should disappear when a concrete GM to do so comes around - * @param cancelOnUi client flag to indicate that the buff should disappear when interacting with UI - * @param cancelOnUnequip client flag to indicate that the buff should disappear when the triggering item is unequipped - * @param cancelOnZone client flag to indicate that the buff should disappear when changing zones - */ - void ApplyBuff(int32_t id, float duration, LWOOBJID source, bool addImmunity = false, bool cancelOnDamaged = false, - bool cancelOnDeath = true, bool cancelOnLogout = false, bool cancelOnRemoveBuff = true, - bool cancelOnUi = false, bool cancelOnUnequip = false, bool cancelOnZone = false); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Removes a buff from the parent entity, reversing its effects - * @param id the id of the buff to remove - */ - void RemoveBuff(int32_t id); + void Update(float deltaTime) override; - /** - * Returns whether or not the entity has a buff identified by `id` - * @param id the id of the buff to find - * @return whether or not the entity has a buff with the specified id active - */ - bool HasBuff(int32_t id); + /** + * Applies a buff to the parent entity + * @param id the id of the buff to apply + * @param duration the duration of the buff in seconds + * @param source an optional source entity that cast the buff + * @param addImmunity client flag + * @param cancelOnDamaged client flag to indicate that the buff should disappear when damaged + * @param cancelOnDeath client flag to indicate that the buff should disappear when dying + * @param cancelOnLogout client flag to indicate that the buff should disappear when logging out + * @param cancelOnRemoveBuff client flag to indicate that the buff should disappear when a concrete GM to do so comes around + * @param cancelOnUi client flag to indicate that the buff should disappear when interacting with UI + * @param cancelOnUnequip client flag to indicate that the buff should disappear when the triggering item is unequipped + * @param cancelOnZone client flag to indicate that the buff should disappear when changing zones + */ + void ApplyBuff(int32_t id, float duration, LWOOBJID source, bool addImmunity = false, bool cancelOnDamaged = false, + bool cancelOnDeath = true, bool cancelOnLogout = false, bool cancelOnRemoveBuff = true, + bool cancelOnUi = false, bool cancelOnUnequip = false, bool cancelOnZone = false); - /** - * Applies the effects of the buffs on the entity, e.g.: changing armor, health, imag, etc. - * @param id the id of the buff effects to apply - */ - void ApplyBuffEffect(int32_t id); + /** + * Removes a buff from the parent entity, reversing its effects + * @param id the id of the buff to remove + */ + void RemoveBuff(int32_t id); - /** - * Reverses the effects of the applied buff - * @param id the id of the buff for which to remove the effects - */ - void RemoveBuffEffect(int32_t id); + /** + * Returns whether or not the entity has a buff identified by `id` + * @param id the id of the buff to find + * @return whether or not the entity has a buff with the specified id active + */ + bool HasBuff(int32_t id); - /** - * Removes all buffs for the entity and reverses all of their effects - */ - void RemoveAllBuffs(); + /** + * Applies the effects of the buffs on the entity, e.g.: changing armor, health, imag, etc. + * @param id the id of the buff effects to apply + */ + void ApplyBuffEffect(int32_t id); - /** - * Removes all buffs for the entity and reverses all of their effects - */ - void Reset(); + /** + * Reverses the effects of the applied buff + * @param id the id of the buff for which to remove the effects + */ + void RemoveBuffEffect(int32_t id); - /** - * Applies all effects for all buffs, active or not, again - */ - void ReApplyBuffs(); + /** + * Removes all buffs for the entity and reverses all of their effects + */ + void RemoveAllBuffs(); - /** - * Gets all the parameters (= effects), for the buffs that belong to this component - * @param buffId - * @return - */ - const std::vector& GetBuffParameters(int32_t buffId); + /** + * Removes all buffs for the entity and reverses all of their effects + */ + void Reset(); + + /** + * Applies all effects for all buffs, active or not, again + */ + void ReApplyBuffs(); + + /** + * Gets all the parameters (= effects), for the buffs that belong to this component + * @param buffId + * @return + */ + const std::vector& GetBuffParameters(int32_t buffId); private: - /** - * The currently active buffs - */ - std::map m_Buffs; + /** + * The currently active buffs + */ + std::map m_Buffs; - /** - * Parameters (=effects) for each buff - */ - static std::unordered_map> m_Cache; + /** + * Parameters (=effects) for each buff + */ + static std::unordered_map> m_Cache; }; #endif // BUFFCOMPONENT_H diff --git a/dGame/dComponents/BuildBorderComponent.cpp b/dGame/dComponents/BuildBorderComponent.cpp index c565af97..f9ead9e4 100644 --- a/dGame/dComponents/BuildBorderComponent.cpp +++ b/dGame/dComponents/BuildBorderComponent.cpp @@ -9,12 +9,10 @@ #include "Item.h" #include "PropertyManagementComponent.h" -BuildBorderComponent::BuildBorderComponent(Entity* parent) : Component(parent) -{ +BuildBorderComponent::BuildBorderComponent(Entity* parent) : Component(parent) { } -BuildBorderComponent::~BuildBorderComponent() -{ +BuildBorderComponent::~BuildBorderComponent() { } void BuildBorderComponent::OnUse(Entity* originator) { @@ -23,8 +21,7 @@ void BuildBorderComponent::OnUse(Entity* originator) { auto buildArea = m_Parent->GetObjectID(); - if (!entities.empty()) - { + if (!entities.empty()) { buildArea = entities[0]->GetObjectID(); Game::logger->Log("BuildBorderComponent", "Using PropertyPlaque"); @@ -62,8 +59,7 @@ void BuildBorderComponent::OnUse(Entity* originator) { NiPoint3::ZERO, 0 ); - } - else { + } else { GameMessages::SendStartArrangingWithItem(originator, originator->GetSystemAddress(), true, buildArea, originator->GetPosition()); } diff --git a/dGame/dComponents/BuildBorderComponent.h b/dGame/dComponents/BuildBorderComponent.h index bd615b48..ba677e37 100644 --- a/dGame/dComponents/BuildBorderComponent.h +++ b/dGame/dComponents/BuildBorderComponent.h @@ -10,20 +10,20 @@ #include "Entity.h" #include "Component.h" -/** - * Component for the build border, allowing the user to start building when interacting with it - */ + /** + * Component for the build border, allowing the user to start building when interacting with it + */ class BuildBorderComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_BUILD_BORDER; - + BuildBorderComponent(Entity* parent); ~BuildBorderComponent() override; - /** - * Causes the originator to start build with this entity as a reference point - * @param originator the entity (probably a player) that triggered the event - */ + /** + * Causes the originator to start build with this entity as a reference point + * @param originator the entity (probably a player) that triggered the event + */ void OnUse(Entity* originator) override; private: }; diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 1f726a79..91666014 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -31,7 +31,7 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C m_EditorEnabled = false; m_EditorLevel = m_GMLevel; - m_Reputation = 0; + m_Reputation = 0; m_CurrentActivity = 0; m_CountryCode = 0; @@ -163,13 +163,11 @@ void CharacterComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInit } } -bool CharacterComponent::GetPvpEnabled() const -{ +bool CharacterComponent::GetPvpEnabled() const { return m_PvpEnabled; } -void CharacterComponent::SetPvpEnabled(const bool value) -{ +void CharacterComponent::SetPvpEnabled(const bool value) { m_DirtyGMInfo = true; m_PvpEnabled = value; @@ -189,66 +187,64 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { Game::logger->Log("CharacterComponent", "Failed to find char tag while loading XML!"); return; } - if (character->QueryAttribute("rpt", &m_Reputation) == tinyxml2::XML_NO_ATTRIBUTE) { - SetReputation(0); - } + if (character->QueryAttribute("rpt", &m_Reputation) == tinyxml2::XML_NO_ATTRIBUTE) { + SetReputation(0); + } character->QueryInt64Attribute("ls", &m_Uscore); // Load the statistics - const auto* statisticsAttribute = character->FindAttribute("stt"); - if (statisticsAttribute) { - InitializeStatisticsFromString(std::string(statisticsAttribute->Value())); - } else { - InitializeEmptyStatistics(); - } + const auto* statisticsAttribute = character->FindAttribute("stt"); + if (statisticsAttribute) { + InitializeStatisticsFromString(std::string(statisticsAttribute->Value())); + } else { + InitializeEmptyStatistics(); + } - // Load the zone statistics - m_ZoneStatistics = {}; - auto zoneStatistics = character->FirstChildElement("zs"); + // Load the zone statistics + m_ZoneStatistics = {}; + auto zoneStatistics = character->FirstChildElement("zs"); - if (zoneStatistics) { - auto child = zoneStatistics->FirstChildElement(); - while (child) { - ZoneStatistics statistics = {}; + if (zoneStatistics) { + auto child = zoneStatistics->FirstChildElement(); + while (child) { + ZoneStatistics statistics = {}; - child->QueryUnsigned64Attribute("ac", &statistics.m_AchievementsCollected); - child->QueryUnsigned64Attribute("bc", &statistics.m_BricksCollected); - child->QueryUnsigned64Attribute("cc", &statistics.m_CoinsCollected); - child->QueryUnsigned64Attribute("es", &statistics.m_EnemiesSmashed); - child->QueryUnsigned64Attribute("qbc", &statistics.m_QuickBuildsCompleted); + child->QueryUnsigned64Attribute("ac", &statistics.m_AchievementsCollected); + child->QueryUnsigned64Attribute("bc", &statistics.m_BricksCollected); + child->QueryUnsigned64Attribute("cc", &statistics.m_CoinsCollected); + child->QueryUnsigned64Attribute("es", &statistics.m_EnemiesSmashed); + child->QueryUnsigned64Attribute("qbc", &statistics.m_QuickBuildsCompleted); - uint32_t mapID; - child->QueryAttribute("map", &mapID); + uint32_t mapID; + child->QueryAttribute("map", &mapID); - m_ZoneStatistics.insert({ (LWOMAPID) mapID, statistics }); + m_ZoneStatistics.insert({ (LWOMAPID)mapID, statistics }); - child = child->NextSiblingElement(); - } - } + child = child->NextSiblingElement(); + } + } - const tinyxml2::XMLAttribute *rocketConfig = character->FindAttribute("lcbp"); + const tinyxml2::XMLAttribute* rocketConfig = character->FindAttribute("lcbp"); if (rocketConfig) { m_LastRocketConfig = GeneralUtils::ASCIIToUTF16(std::string(rocketConfig->Value())); - } - else - { + } else { m_LastRocketConfig = u""; } - // - // Begin custom attributes - // + // + // Begin custom attributes + // - // Load the last rocket item ID - const tinyxml2::XMLAttribute *lastRocketItemID = character->FindAttribute("lrid"); - if (lastRocketItemID) { - m_LastRocketItemID = lastRocketItemID->Int64Value(); - } + // Load the last rocket item ID + const tinyxml2::XMLAttribute* lastRocketItemID = character->FindAttribute("lrid"); + if (lastRocketItemID) { + m_LastRocketItemID = lastRocketItemID->Int64Value(); + } - // - // End custom attributes - // + // + // End custom attributes + // if (m_GMLevel > 0) { m_IsGM = true; @@ -258,7 +254,7 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { } //Annoying guild bs: - const tinyxml2::XMLAttribute *guildName = character->FindAttribute("gn"); + const tinyxml2::XMLAttribute* guildName = character->FindAttribute("gn"); if (guildName) { const char* gn = guildName->Value(); int64_t gid = 0; @@ -272,32 +268,32 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { } if (character->FindAttribute("time")) { - character->QueryUnsigned64Attribute("time", &m_TotalTimePlayed); + character->QueryUnsigned64Attribute("time", &m_TotalTimePlayed); } else { - m_TotalTimePlayed = 0; + m_TotalTimePlayed = 0; } } void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { - tinyxml2::XMLElement* minifig = doc->FirstChildElement("obj")->FirstChildElement("mf"); + tinyxml2::XMLElement* minifig = doc->FirstChildElement("obj")->FirstChildElement("mf"); if (!minifig) { Game::logger->Log("CharacterComponent", "Failed to find mf tag while updating XML!"); return; } - // write minifig information that might have been changed by commands + // write minifig information that might have been changed by commands - minifig->SetAttribute("es", m_Character->GetEyebrows()); - minifig->SetAttribute("ess", m_Character->GetEyes()); - minifig->SetAttribute("hc", m_Character->GetHairColor()); - minifig->SetAttribute("hs", m_Character->GetHairStyle()); - minifig->SetAttribute("l", m_Character->GetPantsColor()); - minifig->SetAttribute("lh", m_Character->GetLeftHand()); - minifig->SetAttribute("ms", m_Character->GetMouth()); - minifig->SetAttribute("rh", m_Character->GetRightHand()); - minifig->SetAttribute("t", m_Character->GetShirtColor()); + minifig->SetAttribute("es", m_Character->GetEyebrows()); + minifig->SetAttribute("ess", m_Character->GetEyes()); + minifig->SetAttribute("hc", m_Character->GetHairColor()); + minifig->SetAttribute("hs", m_Character->GetHairStyle()); + minifig->SetAttribute("l", m_Character->GetPantsColor()); + minifig->SetAttribute("lh", m_Character->GetLeftHand()); + minifig->SetAttribute("ms", m_Character->GetMouth()); + minifig->SetAttribute("rh", m_Character->GetRightHand()); + minifig->SetAttribute("t", m_Character->GetShirtColor()); - // done with minifig + // done with minifig tinyxml2::XMLElement* character = doc->FirstChildElement("obj")->FirstChildElement("char"); if (!character) { @@ -306,8 +302,8 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { } character->SetAttribute("ls", m_Uscore); - // Custom attribute to keep track of reputation. - character->SetAttribute("rpt", GetReputation()); + // Custom attribute to keep track of reputation. + character->SetAttribute("rpt", GetReputation()); character->SetAttribute("stt", StatisticsToString().c_str()); // Set the zone statistics of the form ... @@ -316,16 +312,16 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { zoneStatistics->DeleteChildren(); for (auto pair : m_ZoneStatistics) { - auto zoneStatistic = doc->NewElement("s"); + auto zoneStatistic = doc->NewElement("s"); - zoneStatistic->SetAttribute("map", pair.first); - zoneStatistic->SetAttribute("ac", pair.second.m_AchievementsCollected); - zoneStatistic->SetAttribute("bc", pair.second.m_BricksCollected); - zoneStatistic->SetAttribute("cc", pair.second.m_CoinsCollected); - zoneStatistic->SetAttribute("es", pair.second.m_EnemiesSmashed); - zoneStatistic->SetAttribute("qbc", pair.second.m_QuickBuildsCompleted); + zoneStatistic->SetAttribute("map", pair.first); + zoneStatistic->SetAttribute("ac", pair.second.m_AchievementsCollected); + zoneStatistic->SetAttribute("bc", pair.second.m_BricksCollected); + zoneStatistic->SetAttribute("cc", pair.second.m_CoinsCollected); + zoneStatistic->SetAttribute("es", pair.second.m_EnemiesSmashed); + zoneStatistic->SetAttribute("qbc", pair.second.m_QuickBuildsCompleted); - zoneStatistics->LinkEndChild(zoneStatistic); + zoneStatistics->LinkEndChild(zoneStatistic); } character->LinkEndChild(zoneStatistics); @@ -333,22 +329,20 @@ void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { if (!m_LastRocketConfig.empty()) { std::string config = GeneralUtils::UTF16ToWTF8(m_LastRocketConfig); character->SetAttribute("lcbp", config.c_str()); - } - else - { + } else { character->DeleteAttribute("lcbp"); } - // - // Begin custom attributes - // + // + // Begin custom attributes + // - // Store last rocket item ID - character->SetAttribute("lrid", m_LastRocketItemID); + // Store last rocket item ID + character->SetAttribute("lrid", m_LastRocketItemID); - // - // End custom attributes - // + // + // End custom attributes + // auto newUpdateTimestamp = std::time(nullptr); Game::logger->Log("TotalTimePlayed", "Time since last save: %d", newUpdateTimestamp - m_LastUpdateTimestamp); @@ -372,7 +366,7 @@ Item* CharacterComponent::GetRocket(Entity* player) { if (!inventoryComponent) return rocket; // Select the rocket - if (!rocket){ + if (!rocket) { rocket = inventoryComponent->FindItemById(GetLastRocketItemID()); } @@ -415,325 +409,325 @@ void CharacterComponent::RocketUnEquip(Entity* player) { } void CharacterComponent::TrackMissionCompletion(bool isAchievement) { - UpdatePlayerStatistic(MissionsCompleted); + UpdatePlayerStatistic(MissionsCompleted); - // Achievements are tracked separately for the zone - if (isAchievement) { - const auto mapID = dZoneManager::Instance()->GetZoneID().GetMapID(); - GetZoneStatisticsForMap(mapID).m_AchievementsCollected++; - } + // Achievements are tracked separately for the zone + if (isAchievement) { + const auto mapID = dZoneManager::Instance()->GetZoneID().GetMapID(); + GetZoneStatisticsForMap(mapID).m_AchievementsCollected++; + } } void CharacterComponent::TrackLOTCollection(LOT lot) { - switch (lot) { - // Handle all the imagination powerup lots - case 935: // 1 point - case 4035: // 2 points - case 11910: // 3 points - case 11911: // 5 points - case 11918: // 10 points - UpdatePlayerStatistic(ImaginationPowerUpsCollected); - break; - // Handle all the armor powerup lots - case 6431: // 1 point - case 11912: // 2 points - case 11913: // 3 points - case 11914: // 5 points - case 11919: // 10 points - UpdatePlayerStatistic(ArmorPowerUpsCollected); - break; - // Handle all the life powerup lots - case 177: // 1 point - case 11915: // 2 points - case 11916: // 3 points - case 11917: // 5 points - case 11920: // 10 points - UpdatePlayerStatistic(LifePowerUpsCollected); - break; - default: - break; - } + switch (lot) { + // Handle all the imagination powerup lots + case 935: // 1 point + case 4035: // 2 points + case 11910: // 3 points + case 11911: // 5 points + case 11918: // 10 points + UpdatePlayerStatistic(ImaginationPowerUpsCollected); + break; + // Handle all the armor powerup lots + case 6431: // 1 point + case 11912: // 2 points + case 11913: // 3 points + case 11914: // 5 points + case 11919: // 10 points + UpdatePlayerStatistic(ArmorPowerUpsCollected); + break; + // Handle all the life powerup lots + case 177: // 1 point + case 11915: // 2 points + case 11916: // 3 points + case 11917: // 5 points + case 11920: // 10 points + UpdatePlayerStatistic(LifePowerUpsCollected); + break; + default: + break; + } } void CharacterComponent::TrackHealthDelta(int32_t health) { - if (health > 0) { - UpdatePlayerStatistic(TotalDamageHealed, health); - } else { - UpdatePlayerStatistic(TotalDamageTaken, -health); - } + if (health > 0) { + UpdatePlayerStatistic(TotalDamageHealed, health); + } else { + UpdatePlayerStatistic(TotalDamageTaken, -health); + } } void CharacterComponent::TrackImaginationDelta(int32_t imagination) { - if (imagination > 0) { - UpdatePlayerStatistic(TotalImaginationRestored, imagination); - } else { - UpdatePlayerStatistic(TotalImaginationUsed, -imagination); - } + if (imagination > 0) { + UpdatePlayerStatistic(TotalImaginationRestored, imagination); + } else { + UpdatePlayerStatistic(TotalImaginationUsed, -imagination); + } } void CharacterComponent::TrackArmorDelta(int32_t armor) { - if (armor > 0) { - UpdatePlayerStatistic(TotalArmorRepaired, armor); - } + if (armor > 0) { + UpdatePlayerStatistic(TotalArmorRepaired, armor); + } } void CharacterComponent::TrackRebuildComplete() { - UpdatePlayerStatistic(QuickBuildsCompleted); + UpdatePlayerStatistic(QuickBuildsCompleted); - const auto mapID = dZoneManager::Instance()->GetZoneID().GetMapID(); - GetZoneStatisticsForMap(mapID).m_QuickBuildsCompleted++; + const auto mapID = dZoneManager::Instance()->GetZoneID().GetMapID(); + GetZoneStatisticsForMap(mapID).m_QuickBuildsCompleted++; } void CharacterComponent::TrackRaceCompleted(bool won) { - m_RacesFinished++; - if (won) - m_FirstPlaceRaceFinishes++; + m_RacesFinished++; + if (won) + m_FirstPlaceRaceFinishes++; } void CharacterComponent::TrackPositionUpdate(const NiPoint3& newPosition) { - const auto distance = NiPoint3::Distance(newPosition, m_Parent->GetPosition()); + const auto distance = NiPoint3::Distance(newPosition, m_Parent->GetPosition()); - if (m_IsRacing) { - UpdatePlayerStatistic(DistanceDriven, (uint64_t) distance); - } else { - UpdatePlayerStatistic(MetersTraveled, (uint64_t) distance); - } + if (m_IsRacing) { + UpdatePlayerStatistic(DistanceDriven, (uint64_t)distance); + } else { + UpdatePlayerStatistic(MetersTraveled, (uint64_t)distance); + } } -void CharacterComponent::HandleZoneStatisticsUpdate(LWOMAPID zoneID, const std::u16string &name, int32_t value) { - auto zoneStatistics = &GetZoneStatisticsForMap(zoneID); +void CharacterComponent::HandleZoneStatisticsUpdate(LWOMAPID zoneID, const std::u16string& name, int32_t value) { + auto zoneStatistics = &GetZoneStatisticsForMap(zoneID); - if (name == u"BricksCollected") { - m_BricksCollected += value; - zoneStatistics->m_BricksCollected += value; - } else if (name == u"CoinsCollected") { - m_CurrencyCollected += value; - zoneStatistics->m_CoinsCollected += value; - } else if (name == u"EnemiesSmashed") { - m_EnemiesSmashed += value; - zoneStatistics->m_EnemiesSmashed += value; - } + if (name == u"BricksCollected") { + m_BricksCollected += value; + zoneStatistics->m_BricksCollected += value; + } else if (name == u"CoinsCollected") { + m_CurrencyCollected += value; + zoneStatistics->m_CoinsCollected += value; + } else if (name == u"EnemiesSmashed") { + m_EnemiesSmashed += value; + zoneStatistics->m_EnemiesSmashed += value; + } } void CharacterComponent::UpdatePlayerStatistic(StatisticID updateID, uint64_t updateValue) { - switch (updateID) { - case CurrencyCollected: - m_CurrencyCollected += updateValue; - break; - case BricksCollected: - m_BricksCollected += updateValue; - break; - case SmashablesSmashed: - m_SmashablesSmashed += updateValue; - break; - case QuickBuildsCompleted: - m_QuickBuildsCompleted += updateValue; - break; - case EnemiesSmashed: - m_EnemiesSmashed += updateValue; - break; - case RocketsUsed: - m_RocketsUsed += updateValue; - break; - case MissionsCompleted: - m_MissionsCompleted += updateValue; - break; - case PetsTamed: - m_PetsTamed += updateValue; - break; - case ImaginationPowerUpsCollected: - m_ImaginationPowerUpsCollected += updateValue; - break; - case LifePowerUpsCollected: - m_LifePowerUpsCollected += updateValue; - break; - case ArmorPowerUpsCollected: - m_ArmorPowerUpsCollected += updateValue; - break; - case MetersTraveled: - m_MetersTraveled += updateValue; - break; - case TimesSmashed: - m_TimesSmashed += updateValue; - break; - case TotalDamageTaken: - m_TotalDamageTaken += updateValue; - break; - case TotalDamageHealed: - m_TotalDamageHealed += updateValue; - break; - case TotalArmorRepaired: - m_TotalArmorRepaired += updateValue; - break; - case TotalImaginationRestored: - m_TotalImaginationRestored += updateValue; - break; - case TotalImaginationUsed: - m_TotalImaginationUsed += updateValue; - break; - case DistanceDriven: - m_DistanceDriven += updateValue; - break; - case TimeAirborneInCar: - m_TimeAirborneInCar += updateValue; - break; - case RacingImaginationPowerUpsCollected: - m_RacingImaginationPowerUpsCollected += updateValue; - break; - case RacingImaginationCratesSmashed: - m_RacingImaginationCratesSmashed += updateValue; - break; - case RacingCarBoostsActivated: - m_RacingCarBoostsActivated += updateValue; - break; - case RacingTimesWrecked: - m_RacingTimesWrecked += updateValue; - break; - case RacingSmashablesSmashed: - m_RacingSmashablesSmashed += updateValue; - break; - case RacesFinished: - m_RacesFinished += updateValue; - break; - case FirstPlaceRaceFinishes: - m_FirstPlaceRaceFinishes += updateValue; - break; - default: - break; - } + switch (updateID) { + case CurrencyCollected: + m_CurrencyCollected += updateValue; + break; + case BricksCollected: + m_BricksCollected += updateValue; + break; + case SmashablesSmashed: + m_SmashablesSmashed += updateValue; + break; + case QuickBuildsCompleted: + m_QuickBuildsCompleted += updateValue; + break; + case EnemiesSmashed: + m_EnemiesSmashed += updateValue; + break; + case RocketsUsed: + m_RocketsUsed += updateValue; + break; + case MissionsCompleted: + m_MissionsCompleted += updateValue; + break; + case PetsTamed: + m_PetsTamed += updateValue; + break; + case ImaginationPowerUpsCollected: + m_ImaginationPowerUpsCollected += updateValue; + break; + case LifePowerUpsCollected: + m_LifePowerUpsCollected += updateValue; + break; + case ArmorPowerUpsCollected: + m_ArmorPowerUpsCollected += updateValue; + break; + case MetersTraveled: + m_MetersTraveled += updateValue; + break; + case TimesSmashed: + m_TimesSmashed += updateValue; + break; + case TotalDamageTaken: + m_TotalDamageTaken += updateValue; + break; + case TotalDamageHealed: + m_TotalDamageHealed += updateValue; + break; + case TotalArmorRepaired: + m_TotalArmorRepaired += updateValue; + break; + case TotalImaginationRestored: + m_TotalImaginationRestored += updateValue; + break; + case TotalImaginationUsed: + m_TotalImaginationUsed += updateValue; + break; + case DistanceDriven: + m_DistanceDriven += updateValue; + break; + case TimeAirborneInCar: + m_TimeAirborneInCar += updateValue; + break; + case RacingImaginationPowerUpsCollected: + m_RacingImaginationPowerUpsCollected += updateValue; + break; + case RacingImaginationCratesSmashed: + m_RacingImaginationCratesSmashed += updateValue; + break; + case RacingCarBoostsActivated: + m_RacingCarBoostsActivated += updateValue; + break; + case RacingTimesWrecked: + m_RacingTimesWrecked += updateValue; + break; + case RacingSmashablesSmashed: + m_RacingSmashablesSmashed += updateValue; + break; + case RacesFinished: + m_RacesFinished += updateValue; + break; + case FirstPlaceRaceFinishes: + m_FirstPlaceRaceFinishes += updateValue; + break; + default: + break; + } } -void CharacterComponent::InitializeStatisticsFromString(const std::string &statisticsString) { - auto split = GeneralUtils::SplitString(statisticsString, ';'); +void CharacterComponent::InitializeStatisticsFromString(const std::string& statisticsString) { + auto split = GeneralUtils::SplitString(statisticsString, ';'); - m_CurrencyCollected = GetStatisticFromSplit(split, 0); - m_BricksCollected = GetStatisticFromSplit(split, 1); - m_SmashablesSmashed = GetStatisticFromSplit(split, 2); - m_QuickBuildsCompleted = GetStatisticFromSplit(split, 3); - m_EnemiesSmashed = GetStatisticFromSplit(split, 4); - m_RocketsUsed = GetStatisticFromSplit(split, 5); - m_MissionsCompleted = GetStatisticFromSplit(split, 6); - m_PetsTamed = GetStatisticFromSplit(split, 7); - m_ImaginationPowerUpsCollected = GetStatisticFromSplit(split, 8); - m_LifePowerUpsCollected = GetStatisticFromSplit(split, 9); - m_ArmorPowerUpsCollected = GetStatisticFromSplit(split, 10); - m_MetersTraveled = GetStatisticFromSplit(split, 11); - m_TimesSmashed = GetStatisticFromSplit(split, 12); - m_TotalDamageTaken = GetStatisticFromSplit(split, 13); - m_TotalDamageHealed = GetStatisticFromSplit(split, 14); - m_TotalArmorRepaired = GetStatisticFromSplit(split, 15); - m_TotalImaginationRestored = GetStatisticFromSplit(split, 16); - m_TotalImaginationUsed = GetStatisticFromSplit(split, 17); - m_DistanceDriven = GetStatisticFromSplit(split, 18); - m_TimeAirborneInCar = GetStatisticFromSplit(split, 19); // WONTFIX - m_RacingImaginationPowerUpsCollected = GetStatisticFromSplit(split, 20); - m_RacingImaginationCratesSmashed = GetStatisticFromSplit(split, 21); - m_RacingCarBoostsActivated = GetStatisticFromSplit(split, 22); - m_RacingTimesWrecked = GetStatisticFromSplit(split, 23); - m_RacingSmashablesSmashed = GetStatisticFromSplit(split, 24); - m_RacesFinished = GetStatisticFromSplit(split, 25); - m_FirstPlaceRaceFinishes = GetStatisticFromSplit(split, 26); + m_CurrencyCollected = GetStatisticFromSplit(split, 0); + m_BricksCollected = GetStatisticFromSplit(split, 1); + m_SmashablesSmashed = GetStatisticFromSplit(split, 2); + m_QuickBuildsCompleted = GetStatisticFromSplit(split, 3); + m_EnemiesSmashed = GetStatisticFromSplit(split, 4); + m_RocketsUsed = GetStatisticFromSplit(split, 5); + m_MissionsCompleted = GetStatisticFromSplit(split, 6); + m_PetsTamed = GetStatisticFromSplit(split, 7); + m_ImaginationPowerUpsCollected = GetStatisticFromSplit(split, 8); + m_LifePowerUpsCollected = GetStatisticFromSplit(split, 9); + m_ArmorPowerUpsCollected = GetStatisticFromSplit(split, 10); + m_MetersTraveled = GetStatisticFromSplit(split, 11); + m_TimesSmashed = GetStatisticFromSplit(split, 12); + m_TotalDamageTaken = GetStatisticFromSplit(split, 13); + m_TotalDamageHealed = GetStatisticFromSplit(split, 14); + m_TotalArmorRepaired = GetStatisticFromSplit(split, 15); + m_TotalImaginationRestored = GetStatisticFromSplit(split, 16); + m_TotalImaginationUsed = GetStatisticFromSplit(split, 17); + m_DistanceDriven = GetStatisticFromSplit(split, 18); + m_TimeAirborneInCar = GetStatisticFromSplit(split, 19); // WONTFIX + m_RacingImaginationPowerUpsCollected = GetStatisticFromSplit(split, 20); + m_RacingImaginationCratesSmashed = GetStatisticFromSplit(split, 21); + m_RacingCarBoostsActivated = GetStatisticFromSplit(split, 22); + m_RacingTimesWrecked = GetStatisticFromSplit(split, 23); + m_RacingSmashablesSmashed = GetStatisticFromSplit(split, 24); + m_RacesFinished = GetStatisticFromSplit(split, 25); + m_FirstPlaceRaceFinishes = GetStatisticFromSplit(split, 26); } void CharacterComponent::InitializeEmptyStatistics() { - m_CurrencyCollected = 0; - m_BricksCollected = 0; - m_SmashablesSmashed = 0; - m_QuickBuildsCompleted = 0; - m_EnemiesSmashed = 0; - m_RocketsUsed = 0; - m_MissionsCompleted = 0; - m_PetsTamed = 0; - m_ImaginationPowerUpsCollected = 0; - m_LifePowerUpsCollected = 0; - m_ArmorPowerUpsCollected = 0; - m_MetersTraveled = 0; - m_TimesSmashed = 0; - m_TotalDamageTaken = 0; - m_TotalDamageHealed = 0; - m_TotalArmorRepaired = 0; - m_TotalImaginationRestored = 0; - m_TotalImaginationUsed = 0; - m_DistanceDriven = 0; - m_TimeAirborneInCar = 0; - m_RacingImaginationPowerUpsCollected = 0; - m_RacingImaginationCratesSmashed = 0; - m_RacingCarBoostsActivated = 0; - m_RacingTimesWrecked = 0; - m_RacingSmashablesSmashed = 0; - m_RacesFinished = 0; - m_FirstPlaceRaceFinishes = 0; + m_CurrencyCollected = 0; + m_BricksCollected = 0; + m_SmashablesSmashed = 0; + m_QuickBuildsCompleted = 0; + m_EnemiesSmashed = 0; + m_RocketsUsed = 0; + m_MissionsCompleted = 0; + m_PetsTamed = 0; + m_ImaginationPowerUpsCollected = 0; + m_LifePowerUpsCollected = 0; + m_ArmorPowerUpsCollected = 0; + m_MetersTraveled = 0; + m_TimesSmashed = 0; + m_TotalDamageTaken = 0; + m_TotalDamageHealed = 0; + m_TotalArmorRepaired = 0; + m_TotalImaginationRestored = 0; + m_TotalImaginationUsed = 0; + m_DistanceDriven = 0; + m_TimeAirborneInCar = 0; + m_RacingImaginationPowerUpsCollected = 0; + m_RacingImaginationCratesSmashed = 0; + m_RacingCarBoostsActivated = 0; + m_RacingTimesWrecked = 0; + m_RacingSmashablesSmashed = 0; + m_RacesFinished = 0; + m_FirstPlaceRaceFinishes = 0; } std::string CharacterComponent::StatisticsToString() const { - std::stringstream result; - result << std::to_string(m_CurrencyCollected) << ';' - << std::to_string(m_BricksCollected) << ';' - << std::to_string(m_SmashablesSmashed) << ';' - << std::to_string(m_QuickBuildsCompleted) << ';' - << std::to_string(m_EnemiesSmashed) << ';' - << std::to_string(m_RocketsUsed) << ';' - << std::to_string(m_MissionsCompleted) << ';' - << std::to_string(m_PetsTamed) << ';' - << std::to_string(m_ImaginationPowerUpsCollected) << ';' - << std::to_string(m_LifePowerUpsCollected) << ';' - << std::to_string(m_ArmorPowerUpsCollected) << ';' - << std::to_string(m_MetersTraveled) << ';' - << std::to_string(m_TimesSmashed) << ';' - << std::to_string(m_TotalDamageTaken) << ';' - << std::to_string(m_TotalDamageHealed) << ';' - << std::to_string(m_TotalArmorRepaired) << ';' - << std::to_string(m_TotalImaginationRestored) << ';' - << std::to_string(m_TotalImaginationUsed) << ';' - << std::to_string(m_DistanceDriven) << ';' - << std::to_string(m_TimeAirborneInCar) << ';' - << std::to_string(m_RacingImaginationPowerUpsCollected) << ';' - << std::to_string(m_RacingImaginationCratesSmashed) << ';' - << std::to_string(m_RacingCarBoostsActivated) << ';' - << std::to_string(m_RacingTimesWrecked) << ';' - << std::to_string(m_RacingSmashablesSmashed) << ';' - << std::to_string(m_RacesFinished) << ';' - << std::to_string(m_FirstPlaceRaceFinishes) << ';'; + std::stringstream result; + result << std::to_string(m_CurrencyCollected) << ';' + << std::to_string(m_BricksCollected) << ';' + << std::to_string(m_SmashablesSmashed) << ';' + << std::to_string(m_QuickBuildsCompleted) << ';' + << std::to_string(m_EnemiesSmashed) << ';' + << std::to_string(m_RocketsUsed) << ';' + << std::to_string(m_MissionsCompleted) << ';' + << std::to_string(m_PetsTamed) << ';' + << std::to_string(m_ImaginationPowerUpsCollected) << ';' + << std::to_string(m_LifePowerUpsCollected) << ';' + << std::to_string(m_ArmorPowerUpsCollected) << ';' + << std::to_string(m_MetersTraveled) << ';' + << std::to_string(m_TimesSmashed) << ';' + << std::to_string(m_TotalDamageTaken) << ';' + << std::to_string(m_TotalDamageHealed) << ';' + << std::to_string(m_TotalArmorRepaired) << ';' + << std::to_string(m_TotalImaginationRestored) << ';' + << std::to_string(m_TotalImaginationUsed) << ';' + << std::to_string(m_DistanceDriven) << ';' + << std::to_string(m_TimeAirborneInCar) << ';' + << std::to_string(m_RacingImaginationPowerUpsCollected) << ';' + << std::to_string(m_RacingImaginationCratesSmashed) << ';' + << std::to_string(m_RacingCarBoostsActivated) << ';' + << std::to_string(m_RacingTimesWrecked) << ';' + << std::to_string(m_RacingSmashablesSmashed) << ';' + << std::to_string(m_RacesFinished) << ';' + << std::to_string(m_FirstPlaceRaceFinishes) << ';'; - return result.str(); + return result.str(); } uint64_t CharacterComponent::GetStatisticFromSplit(std::vector split, uint32_t index) { - return split.size() > index ? std::stoul(split.at(index)) : 0; + return split.size() > index ? std::stoul(split.at(index)) : 0; } ZoneStatistics& CharacterComponent::GetZoneStatisticsForMap(LWOMAPID mapID) { - auto stats = m_ZoneStatistics.find(mapID); - if (stats == m_ZoneStatistics.end()) - m_ZoneStatistics.insert({ mapID, {0, 0, 0, 0, 0 } }); - return m_ZoneStatistics.at(mapID); + auto stats = m_ZoneStatistics.find(mapID); + if (stats == m_ZoneStatistics.end()) + m_ZoneStatistics.insert({ mapID, {0, 0, 0, 0, 0 } }); + return m_ZoneStatistics.at(mapID); } void CharacterComponent::AddVentureVisionEffect(std::string ventureVisionType) { - const auto ventureVisionTypeIterator = m_ActiveVentureVisionEffects.find(ventureVisionType); + const auto ventureVisionTypeIterator = m_ActiveVentureVisionEffects.find(ventureVisionType); - if (ventureVisionTypeIterator != m_ActiveVentureVisionEffects.end()) { - ventureVisionTypeIterator->second = ++ventureVisionTypeIterator->second; - } else { - // If the effect it not found, insert it into the active effects. - m_ActiveVentureVisionEffects.insert(std::make_pair(ventureVisionType, 1U)); - } + if (ventureVisionTypeIterator != m_ActiveVentureVisionEffects.end()) { + ventureVisionTypeIterator->second = ++ventureVisionTypeIterator->second; + } else { + // If the effect it not found, insert it into the active effects. + m_ActiveVentureVisionEffects.insert(std::make_pair(ventureVisionType, 1U)); + } - UpdateClientMinimap(true, ventureVisionType); + UpdateClientMinimap(true, ventureVisionType); } void CharacterComponent::RemoveVentureVisionEffect(std::string ventureVisionType) { - const auto ventureVisionTypeIterator = m_ActiveVentureVisionEffects.find(ventureVisionType); + const auto ventureVisionTypeIterator = m_ActiveVentureVisionEffects.find(ventureVisionType); - if (ventureVisionTypeIterator != m_ActiveVentureVisionEffects.end()) { - ventureVisionTypeIterator->second = --ventureVisionTypeIterator->second; - UpdateClientMinimap(ventureVisionTypeIterator->second != 0U, ventureVisionType); - } + if (ventureVisionTypeIterator != m_ActiveVentureVisionEffects.end()) { + ventureVisionTypeIterator->second = --ventureVisionTypeIterator->second; + UpdateClientMinimap(ventureVisionTypeIterator->second != 0U, ventureVisionType); + } } void CharacterComponent::UpdateClientMinimap(bool showFaction, std::string ventureVisionType) const { - if (!m_Parent) return; - AMFArrayValue arrayToSend; - arrayToSend.InsertValue(ventureVisionType, showFaction ? static_cast(new AMFTrueValue()) : static_cast(new AMFFalseValue())); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent ? m_Parent->GetSystemAddress() : UNASSIGNED_SYSTEM_ADDRESS, "SetFactionVisibility", &arrayToSend); + if (!m_Parent) return; + AMFArrayValue arrayToSend; + arrayToSend.InsertValue(ventureVisionType, showFaction ? static_cast(new AMFTrueValue()) : static_cast(new AMFFalseValue())); + GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent ? m_Parent->GetSystemAddress() : UNASSIGNED_SYSTEM_ADDRESS, "SetFactionVisibility", &arrayToSend); } diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index cd5809f0..f6bf1e70 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -14,44 +14,44 @@ * The statistics that can be achieved per zone */ struct ZoneStatistics { - uint64_t m_AchievementsCollected; - uint64_t m_BricksCollected; - uint64_t m_CoinsCollected; - uint64_t m_EnemiesSmashed; - uint64_t m_QuickBuildsCompleted; + uint64_t m_AchievementsCollected; + uint64_t m_BricksCollected; + uint64_t m_CoinsCollected; + uint64_t m_EnemiesSmashed; + uint64_t m_QuickBuildsCompleted; }; /** * The IDs of each of the possible statistics */ enum StatisticID { - CurrencyCollected = 1, - BricksCollected, - SmashablesSmashed, - QuickBuildsCompleted, - EnemiesSmashed, - RocketsUsed, - MissionsCompleted, - PetsTamed, - ImaginationPowerUpsCollected, - LifePowerUpsCollected, - ArmorPowerUpsCollected, - MetersTraveled, - TimesSmashed, - TotalDamageTaken, - TotalDamageHealed, - TotalArmorRepaired, - TotalImaginationRestored, - TotalImaginationUsed, - DistanceDriven, - TimeAirborneInCar, - RacingImaginationPowerUpsCollected, - RacingImaginationCratesSmashed, - RacingCarBoostsActivated, - RacingTimesWrecked, - RacingSmashablesSmashed, - RacesFinished, - FirstPlaceRaceFinishes, + CurrencyCollected = 1, + BricksCollected, + SmashablesSmashed, + QuickBuildsCompleted, + EnemiesSmashed, + RocketsUsed, + MissionsCompleted, + PetsTamed, + ImaginationPowerUpsCollected, + LifePowerUpsCollected, + ArmorPowerUpsCollected, + MetersTraveled, + TimesSmashed, + TotalDamageTaken, + TotalDamageHealed, + TotalArmorRepaired, + TotalImaginationRestored, + TotalImaginationUsed, + DistanceDriven, + TimeAirborneInCar, + RacingImaginationPowerUpsCollected, + RacingImaginationCratesSmashed, + RacingCarBoostsActivated, + RacingTimesWrecked, + RacingSmashablesSmashed, + RacesFinished, + FirstPlaceRaceFinishes, }; /** @@ -60,19 +60,19 @@ enum StatisticID { class CharacterComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_CHARACTER; - - CharacterComponent(Entity* parent, Character* character); - ~CharacterComponent() override; - - void LoadFromXml(tinyxml2::XMLDocument* doc) override; + + CharacterComponent(Entity* parent, Character* character); + ~CharacterComponent() override; + + void LoadFromXml(tinyxml2::XMLDocument* doc) override; void UpdateXml(tinyxml2::XMLDocument* doc) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Updates the rocket configuration using a LOT string separated by commas - * @param config the rocket config to use - */ + /** + * Updates the rocket configuration using a LOT string separated by commas + * @param config the rocket config to use + */ void SetLastRocketConfig(std::u16string config); /** @@ -95,76 +95,76 @@ public: */ void RocketUnEquip(Entity* player); - /** - * Gets the universe score of the entity - * @return the universe score of the entity - */ + /** + * Gets the universe score of the entity + * @return the universe score of the entity + */ const int64_t GetUScore() const { return m_Uscore; } - /** - * Sets the universe score for this entity - * @param uscore the universe score to set - */ + /** + * Sets the universe score for this entity + * @param uscore the universe score to set + */ void SetUScore(int64_t uscore) { m_Uscore = uscore; } - /** - * Gets the current activity that the character is partaking in, see ScriptedActivityComponent for more details - * @return the current activity that the character is partaking in - */ + /** + * Gets the current activity that the character is partaking in, see ScriptedActivityComponent for more details + * @return the current activity that the character is partaking in + */ const uint32_t GetCurrentActivity() const { return m_CurrentActivity; } - /** - * Set the current activity of the character, see ScriptedActivityComponent for more details - * @param currentActivity the activity to set - */ + /** + * Set the current activity of the character, see ScriptedActivityComponent for more details + * @param currentActivity the activity to set + */ void SetCurrentActivity(uint32_t currentActivity) { m_CurrentActivity = currentActivity; m_DirtyCurrentActivity = true; } - /** - * Gets if the entity is currently racing - * @return whether the entity is currently racing - */ + /** + * Gets if the entity is currently racing + * @return whether the entity is currently racing + */ const bool GetIsRacing() const { return m_IsRacing; } - /** - * Sets the state of whether the character is racing - * @param isRacing whether the character is racing - */ + /** + * Sets the state of whether the character is racing + * @param isRacing whether the character is racing + */ void SetIsRacing(bool isRacing) { m_IsRacing = isRacing; } - /** - * Gets whether this character has PvP enabled, allowing combat between players - * @return - */ + /** + * Gets whether this character has PvP enabled, allowing combat between players + * @return + */ bool GetPvpEnabled() const; - /** - * Returns the characters lifetime reputation - * @return The lifetime reputation of this character. - */ - int64_t GetReputation() { return m_Reputation; }; + /** + * Returns the characters lifetime reputation + * @return The lifetime reputation of this character. + */ + int64_t GetReputation() { return m_Reputation; }; - /** - * Sets the lifetime reputation of the character to newValue - * @param newValue the value to set reputation to - */ - void SetReputation(int64_t newValue) { m_Reputation = newValue; }; + /** + * Sets the lifetime reputation of the character to newValue + * @param newValue the value to set reputation to + */ + void SetReputation(int64_t newValue) { m_Reputation = newValue; }; - /** - * Sets the current value of PvP combat being enabled - * @param value whether to enable PvP combat - */ + /** + * Sets the current value of PvP combat being enabled + * @param value whether to enable PvP combat + */ void SetPvpEnabled(bool value); - /** - * Gets the object ID of the rocket that was last used, allowing it to be rendered on launch pads - * @return the object ID of the rocket that was last used, if available - */ + /** + * Gets the object ID of the rocket that was last used, allowing it to be rendered on launch pads + * @return the object ID of the rocket that was last used, if available + */ LWOOBJID GetLastRocketItemID() const { return m_LastRocketItemID; } - /** - * Sets the object ID of the last used rocket - * @param lastRocketItemID the object ID of the last used rocket - */ + /** + * Sets the object ID of the last used rocket + * @param lastRocketItemID the object ID of the last used rocket + */ void SetLastRocketItemID(LWOOBJID lastRocketItemID) { m_LastRocketItemID = lastRocketItemID; } /** @@ -179,40 +179,40 @@ public: */ void SetMountItemID(LWOOBJID mountItemID) { m_MountItemID = mountItemID; } - /** - * Gets the name of this character - * @return the name of this character - */ + /** + * Gets the name of this character + * @return the name of this character + */ std::string GetName() const { return m_Character->GetName(); } - /** - * Sets the GM level of the character, should be called in the entity. Here it's set for serialization - * @param gmlevel the gm level to set - */ + /** + * Sets the GM level of the character, should be called in the entity. Here it's set for serialization + * @param gmlevel the gm level to set + */ void SetGMLevel(int gmlevel); - /** - * Initializes the player statistics from the string stored in the XML - * @param statisticsString the string to parse - */ + /** + * Initializes the player statistics from the string stored in the XML + * @param statisticsString the string to parse + */ void InitializeStatisticsFromString(const std::string& statisticsString); - /** - * Initializes all the statistics with empty stats when there's no stats available up until that point - */ + /** + * Initializes all the statistics with empty stats when there's no stats available up until that point + */ void InitializeEmptyStatistics(); - /** - * Turns character statistics into a stats string - * @return the statistics of the character as a string, in order, split by semicolon (;) - */ + /** + * Turns character statistics into a stats string + * @return the statistics of the character as a string, in order, split by semicolon (;) + */ std::string StatisticsToString() const; /** * Updates the statistics for when a user completes a mission * @param mission the mission info to track */ - void TrackMissionCompletion(bool isAchievement); + void TrackMissionCompletion(bool isAchievement); /** * Handles statistics related to collecting heart flags and imagination bricks @@ -269,301 +269,301 @@ public: */ void UpdatePlayerStatistic(StatisticID updateID, uint64_t updateValue = 1); - /** - * Add a venture vision effect to the player minimap. - */ - void AddVentureVisionEffect(std::string ventureVisionType); + /** + * Add a venture vision effect to the player minimap. + */ + void AddVentureVisionEffect(std::string ventureVisionType); - /** - * Remove a venture vision effect from the player minimap. - * When an effect hits 0 active effects, it is deactivated. - */ - void RemoveVentureVisionEffect(std::string ventureVisionType); + /** + * Remove a venture vision effect from the player minimap. + * When an effect hits 0 active effects, it is deactivated. + */ + void RemoveVentureVisionEffect(std::string ventureVisionType); - /** - * Update the client minimap to reveal the specified factions - */ - void UpdateClientMinimap(bool showFaction, std::string ventureVisionType) const; + /** + * Update the client minimap to reveal the specified factions + */ + void UpdateClientMinimap(bool showFaction, std::string ventureVisionType) const; - /** - * Character info regarding this character, including clothing styles, etc. - */ - Character* m_Character; + /** + * Character info regarding this character, including clothing styles, etc. + */ + Character* m_Character; private: - - /** - * The map of active venture vision effects - */ - std::map m_ActiveVentureVisionEffects; - /** - * Whether this character is racing - */ + /** + * The map of active venture vision effects + */ + std::map m_ActiveVentureVisionEffects; + + /** + * Whether this character is racing + */ bool m_IsRacing; - /** - * Possessible type, used by the shooting gallery - */ + /** + * Possessible type, used by the shooting gallery + */ uint8_t m_PossessableType = 1; - /** - * Universe score of the entity - */ + /** + * Universe score of the entity + */ int64_t m_Uscore; - /** - * The lifetime reputation earned by the entity - */ - int64_t m_Reputation; + /** + * The lifetime reputation earned by the entity + */ + int64_t m_Reputation; - /** - * Whether the character is landing by rocket - */ + /** + * Whether the character is landing by rocket + */ bool m_IsLanding; - /** - * The configuration of the last used rocket, essentially a string of LOTs separated by commas - */ + /** + * The configuration of the last used rocket, essentially a string of LOTs separated by commas + */ std::u16string m_LastRocketConfig; - /** - * Whether the GM info has been changed - */ + /** + * Whether the GM info has been changed + */ bool m_DirtyGMInfo = false; - /** - * Whether PvP is enabled for this entity - */ + /** + * Whether PvP is enabled for this entity + */ bool m_PvpEnabled; - /** - * Whether this entity is a GM - */ + /** + * Whether this entity is a GM + */ bool m_IsGM; - /** - * The current GM level of this character (anything > 0 counts as a GM) - */ + /** + * The current GM level of this character (anything > 0 counts as a GM) + */ unsigned char m_GMLevel; - /** - * Whether the character has HF enabled - */ + /** + * Whether the character has HF enabled + */ bool m_EditorEnabled; - /** - * The level of the character in HF - */ + /** + * The level of the character in HF + */ unsigned char m_EditorLevel; - /** - * Whether the currently active activity has been changed - */ + /** + * Whether the currently active activity has been changed + */ bool m_DirtyCurrentActivity = false; - /** - * The ID of the curently active activity - */ + /** + * The ID of the curently active activity + */ int m_CurrentActivity; - /** - * Whether the social info has been changed - */ + /** + * Whether the social info has been changed + */ bool m_DirtySocialInfo = false; - /** - * The guild this character is in - */ + /** + * The guild this character is in + */ LWOOBJID m_GuildID; - /** - * The name of the guild this character is in - */ + /** + * The name of the guild this character is in + */ std::u16string m_GuildName; - /** - * Whether this character is a lego club member - */ + /** + * Whether this character is a lego club member + */ bool m_IsLEGOClubMember; - /** - * The country code that the character is from - */ + /** + * The country code that the character is from + */ int m_CountryCode; - /** - * Returns whether the landing animation is enabled for a certain zone - * @param zoneID the zone to check for - * @return whether the landing animation is enabled for that zone - */ + /** + * Returns whether the landing animation is enabled for a certain zone + * @param zoneID the zone to check for + * @return whether the landing animation is enabled for that zone + */ bool LandingAnimDisabled(int zoneID); - /** - * Returns the statistics for a certain statistics ID, from a statistics string - * @param split the statistics string to look in - * @param index the statistics ID in the string - * @return the integer value of this statistic, parsed from the string - */ + /** + * Returns the statistics for a certain statistics ID, from a statistics string + * @param split the statistics string to look in + * @param index the statistics ID in the string + * @return the integer value of this statistic, parsed from the string + */ static uint64_t GetStatisticFromSplit(std::vector split, uint32_t index); - /** - * Gets all the statistics for a certain map, if it doesn't exist, it creates empty stats - * @param mapID the ID of the zone to get statistics for - * @return the statistics for the zone - */ + /** + * Gets all the statistics for a certain map, if it doesn't exist, it creates empty stats + * @param mapID the ID of the zone to get statistics for + * @return the statistics for the zone + */ ZoneStatistics& GetZoneStatisticsForMap(const LWOMAPID mapID); - /** - * The last time we saved this character, used to update the total time played - */ - time_t m_LastUpdateTimestamp; + /** + * The last time we saved this character, used to update the total time played + */ + time_t m_LastUpdateTimestamp; - /** - * The total time the character has played, in MS - */ - uint64_t m_TotalTimePlayed; + /** + * The total time the character has played, in MS + */ + uint64_t m_TotalTimePlayed; - /** - * The total amount of currency collected by this character - */ - uint64_t m_CurrencyCollected; + /** + * The total amount of currency collected by this character + */ + uint64_t m_CurrencyCollected; - /** - * The total amount of bricks collected by this character - */ - uint64_t m_BricksCollected; + /** + * The total amount of bricks collected by this character + */ + uint64_t m_BricksCollected; - /** - * The total amount of entities smashed by this character - */ - uint64_t m_SmashablesSmashed; + /** + * The total amount of entities smashed by this character + */ + uint64_t m_SmashablesSmashed; - /** - * The total amount of quickbuilds completed by this character - */ - uint64_t m_QuickBuildsCompleted; + /** + * The total amount of quickbuilds completed by this character + */ + uint64_t m_QuickBuildsCompleted; - /** - * The total amount of enemies killd by this character - */ - uint64_t m_EnemiesSmashed; + /** + * The total amount of enemies killd by this character + */ + uint64_t m_EnemiesSmashed; - /** - * The total amount of rockets used by this character - */ - uint64_t m_RocketsUsed; + /** + * The total amount of rockets used by this character + */ + uint64_t m_RocketsUsed; - /** - * The total amount of missions completed by this character - */ - uint64_t m_MissionsCompleted; + /** + * The total amount of missions completed by this character + */ + uint64_t m_MissionsCompleted; - /** - * The total number of pets tamed by this character - */ - uint64_t m_PetsTamed; + /** + * The total number of pets tamed by this character + */ + uint64_t m_PetsTamed; - /** - * The total amount of imagination powerups collected by this character, this includes the ones in racing - */ - uint64_t m_ImaginationPowerUpsCollected; + /** + * The total amount of imagination powerups collected by this character, this includes the ones in racing + */ + uint64_t m_ImaginationPowerUpsCollected; - /** - * The total amount of life powerups collected (note: not the total amount of life gained) - */ - uint64_t m_LifePowerUpsCollected; + /** + * The total amount of life powerups collected (note: not the total amount of life gained) + */ + uint64_t m_LifePowerUpsCollected; - /** - * The total amount of armor powerups collected (note: not the total amount of armor gained) - */ - uint64_t m_ArmorPowerUpsCollected; + /** + * The total amount of armor powerups collected (note: not the total amount of armor gained) + */ + uint64_t m_ArmorPowerUpsCollected; - /** - * Total amount of meters traveled by this character - */ - uint64_t m_MetersTraveled; + /** + * Total amount of meters traveled by this character + */ + uint64_t m_MetersTraveled; - /** - * Total amount of times this character was smashed, either by other entities or by going out of bounds - */ - uint64_t m_TimesSmashed; + /** + * Total amount of times this character was smashed, either by other entities or by going out of bounds + */ + uint64_t m_TimesSmashed; - /** - * The total amount of damage inflicted on this character - */ - uint64_t m_TotalDamageTaken; + /** + * The total amount of damage inflicted on this character + */ + uint64_t m_TotalDamageTaken; - /** - * The total amount of damage healed by this character (excludes armor polish, etc) - */ - uint64_t m_TotalDamageHealed; + /** + * The total amount of damage healed by this character (excludes armor polish, etc) + */ + uint64_t m_TotalDamageHealed; - /** - * Total amount of armor repaired by this character - */ - uint64_t m_TotalArmorRepaired; + /** + * Total amount of armor repaired by this character + */ + uint64_t m_TotalArmorRepaired; - /** - * Total amount of imagination resored by this character - */ - uint64_t m_TotalImaginationRestored; + /** + * Total amount of imagination resored by this character + */ + uint64_t m_TotalImaginationRestored; - /** - * Total amount of imagination used by this character - */ - uint64_t m_TotalImaginationUsed; + /** + * Total amount of imagination used by this character + */ + uint64_t m_TotalImaginationUsed; - /** - * Amount of distance driven, mutually exclusively tracked to meters travelled based on whether the charcter - * is currently driving - */ - uint64_t m_DistanceDriven; + /** + * Amount of distance driven, mutually exclusively tracked to meters travelled based on whether the charcter + * is currently driving + */ + uint64_t m_DistanceDriven; - /** - * Time airborne in a car, currently untracked. - * Honestly, who even cares about this. - */ - uint64_t m_TimeAirborneInCar; + /** + * Time airborne in a car, currently untracked. + * Honestly, who even cares about this. + */ + uint64_t m_TimeAirborneInCar; - /** - * Amount of imagination powerups found on racing tracks being collected, generally triggered by scripts - */ - uint64_t m_RacingImaginationPowerUpsCollected; + /** + * Amount of imagination powerups found on racing tracks being collected, generally triggered by scripts + */ + uint64_t m_RacingImaginationPowerUpsCollected; - /** - * Total amount of racing imagination crates smashed, generally tracked by scripts - */ - uint64_t m_RacingImaginationCratesSmashed; + /** + * Total amount of racing imagination crates smashed, generally tracked by scripts + */ + uint64_t m_RacingImaginationCratesSmashed; - /** - * The amount of times this character triggered a car boost - */ - uint64_t m_RacingCarBoostsActivated; + /** + * The amount of times this character triggered a car boost + */ + uint64_t m_RacingCarBoostsActivated; - /** - * The amount of times a car of this character was wrecked - */ - uint64_t m_RacingTimesWrecked; + /** + * The amount of times a car of this character was wrecked + */ + uint64_t m_RacingTimesWrecked; - /** - * The amount of entities smashed by the character while driving - */ - uint64_t m_RacingSmashablesSmashed; + /** + * The amount of entities smashed by the character while driving + */ + uint64_t m_RacingSmashablesSmashed; - /** - * The total amount of races completed by this character - */ - uint64_t m_RacesFinished; + /** + * The total amount of races completed by this character + */ + uint64_t m_RacesFinished; - /** - * The total amount of races won by this character - */ - uint64_t m_FirstPlaceRaceFinishes; + /** + * The total amount of races won by this character + */ + uint64_t m_FirstPlaceRaceFinishes; - /** - * Special stats which are tracked per zone - */ - std::map m_ZoneStatistics {}; + /** + * Special stats which are tracked per zone + */ + std::map m_ZoneStatistics{}; /** * ID of the last rocket used diff --git a/dGame/dComponents/Component.cpp b/dGame/dComponents/Component.cpp index 1a38b871..ca018c29 100644 --- a/dGame/dComponents/Component.cpp +++ b/dGame/dComponents/Component.cpp @@ -1,36 +1,30 @@ #include "Component.h" -Component::Component(Entity* parent) -{ - m_Parent = parent; +Component::Component(Entity* parent) { + m_Parent = parent; } -Component::~Component() -{ - -} - -Entity* Component::GetParent() const -{ - return m_Parent; -} - -void Component::Update(float deltaTime) -{ - -} - -void Component::OnUse(Entity* originator) -{ - -} - -void Component::UpdateXml(tinyxml2::XMLDocument* doc) -{ - -} - -void Component::LoadFromXml(tinyxml2::XMLDocument *doc) { +Component::~Component() { + +} + +Entity* Component::GetParent() const { + return m_Parent; +} + +void Component::Update(float deltaTime) { + +} + +void Component::OnUse(Entity* originator) { + +} + +void Component::UpdateXml(tinyxml2::XMLDocument* doc) { + +} + +void Component::LoadFromXml(tinyxml2::XMLDocument* doc) { } diff --git a/dGame/dComponents/Component.h b/dGame/dComponents/Component.h index b84537bc..9b0df9fd 100644 --- a/dGame/dComponents/Component.h +++ b/dGame/dComponents/Component.h @@ -10,43 +10,43 @@ class Entity; class Component { public: - Component(Entity* parent); - virtual ~Component(); + Component(Entity* parent); + virtual ~Component(); - /** - * Gets the owner of this component - * @return the owner of this component - */ - Entity* GetParent() const; + /** + * Gets the owner of this component + * @return the owner of this component + */ + Entity* GetParent() const; - /** - * Updates the component in the game loop - * @param deltaTime time passed since last update - */ - virtual void Update(float deltaTime); + /** + * Updates the component in the game loop + * @param deltaTime time passed since last update + */ + virtual void Update(float deltaTime); - /** - * Event called when this component is being used, e.g. when some entity interacted with it - * @param originator - */ - virtual void OnUse(Entity* originator); + /** + * Event called when this component is being used, e.g. when some entity interacted with it + * @param originator + */ + virtual void OnUse(Entity* originator); - /** - * Save data from this componennt to character XML - * @param doc the document to write data to - */ - virtual void UpdateXml(tinyxml2::XMLDocument* doc); + /** + * Save data from this componennt to character XML + * @param doc the document to write data to + */ + virtual void UpdateXml(tinyxml2::XMLDocument* doc); - /** - * Load base data for this component from character XML - * @param doc the document to read data from - */ - virtual void LoadFromXml(tinyxml2::XMLDocument* doc); + /** + * Load base data for this component from character XML + * @param doc the document to read data from + */ + virtual void LoadFromXml(tinyxml2::XMLDocument* doc); protected: - /** - * The entity that owns this component - */ - Entity* m_Parent; + /** + * The entity that owns this component + */ + Entity* m_Parent; }; diff --git a/dGame/dComponents/ControllablePhysicsComponent.h b/dGame/dComponents/ControllablePhysicsComponent.h index 73b3bb69..bc05657c 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.h +++ b/dGame/dComponents/ControllablePhysicsComponent.h @@ -18,343 +18,343 @@ class dpEntity; */ class ControllablePhysicsComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_CONTROLLABLE_PHYSICS; - - ControllablePhysicsComponent(Entity* entity); - ~ControllablePhysicsComponent() override; - - void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void LoadFromXml(tinyxml2::XMLDocument* doc) override; - void ResetFlags(); - void UpdateXml(tinyxml2::XMLDocument* doc) override; - - /** - * Sets the position of this entity, also ensures this update is serialized next tick. - * If the entity is static, this is a no-op. - * @param pos The position to set - */ - void SetPosition(const NiPoint3& pos); + static const uint32_t ComponentType = COMPONENT_TYPE_CONTROLLABLE_PHYSICS; - /** - * Returns the current position of the entity - * @return The current position of the entity - */ - const NiPoint3& GetPosition() const { return m_Position; } + ControllablePhysicsComponent(Entity* entity); + ~ControllablePhysicsComponent() override; - /** - * Sets the rotation of this entity, ensures this change is serialized next tick. If the entity is static, this is - * a no-op. - * @param rot the rotation to set - */ - void SetRotation(const NiQuaternion& rot); + void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; + void ResetFlags(); + void UpdateXml(tinyxml2::XMLDocument* doc) override; - /** - * Returns the current rotation of this entity - * @return the current rotation of this entity - */ - const NiQuaternion& GetRotation() const { return m_Rotation; } + /** + * Sets the position of this entity, also ensures this update is serialized next tick. + * If the entity is static, this is a no-op. + * @param pos The position to set + */ + void SetPosition(const NiPoint3& pos); - /** - * Sets the current velocity of this entity, ensures that this change is serialized next tick. If the entity is - * marked as static this is a no-op. - * @param vel the velocity to set - */ - void SetVelocity(const NiPoint3& vel); + /** + * Returns the current position of the entity + * @return The current position of the entity + */ + const NiPoint3& GetPosition() const { return m_Position; } - /** - * Returns the current velocity of this entity - * @return the current velocity of this entity - */ - const NiPoint3& GetVelocity() const { return m_Velocity; } + /** + * Sets the rotation of this entity, ensures this change is serialized next tick. If the entity is static, this is + * a no-op. + * @param rot the rotation to set + */ + void SetRotation(const NiQuaternion& rot); - /** - * Sets the angular velocity (e.g. rotational velocity) of this entity and ensures this is serialized next tick. - * If the entity is marked as static this is a no-op. - * @param vel the angular velocity to set. - */ - void SetAngularVelocity(const NiPoint3& vel); + /** + * Returns the current rotation of this entity + * @return the current rotation of this entity + */ + const NiQuaternion& GetRotation() const { return m_Rotation; } - /** - * Returns the current angular velocity of this entity - * @return the current angular velocity of this entity - */ - const NiPoint3& GetAngularVelocity() const { return m_AngularVelocity; } + /** + * Sets the current velocity of this entity, ensures that this change is serialized next tick. If the entity is + * marked as static this is a no-op. + * @param vel the velocity to set + */ + void SetVelocity(const NiPoint3& vel); - /** - * Sets the IsOnGround value, determining whether or not the entity is stuck to the ground. Note that this is mostly - * a client side flag as no server-side entities jump around and therefore this does not have to be updated server - * side. - * @param val whether the entity is on the ground. - */ - void SetIsOnGround(bool val); + /** + * Returns the current velocity of this entity + * @return the current velocity of this entity + */ + const NiPoint3& GetVelocity() const { return m_Velocity; } - /** - * Returns whether or not the entity is currently on the ground - * @return whether the entity is currently on the ground - */ - const bool GetIsOnGround() const { return m_IsOnGround; } + /** + * Sets the angular velocity (e.g. rotational velocity) of this entity and ensures this is serialized next tick. + * If the entity is marked as static this is a no-op. + * @param vel the angular velocity to set. + */ + void SetAngularVelocity(const NiPoint3& vel); - /** - * Sets the on-rail parameter, determining if a player is currently on a rail (e.g. the lamps in Ninjago). - * Also ensures that this change is serialized. - * @param val whether the player is currently on a rail - */ - void SetIsOnRail(bool val); + /** + * Returns the current angular velocity of this entity + * @return the current angular velocity of this entity + */ + const NiPoint3& GetAngularVelocity() const { return m_AngularVelocity; } - /** - * Returns whether or not this entity is currently on a rail. - * @return whether or not this entity is currently on a rail - */ - const bool GetIsOnRail() const { return m_IsOnRail; } + /** + * Sets the IsOnGround value, determining whether or not the entity is stuck to the ground. Note that this is mostly + * a client side flag as no server-side entities jump around and therefore this does not have to be updated server + * side. + * @param val whether the entity is on the ground. + */ + void SetIsOnGround(bool val); - /** - * Mark the position as dirty, forcing a serialization update next tick - * @param val whether or not the position is dirty - */ - void SetDirtyPosition(bool val); + /** + * Returns whether or not the entity is currently on the ground + * @return whether the entity is currently on the ground + */ + const bool GetIsOnGround() const { return m_IsOnGround; } - /** - * Mark the velocity as dirty, forcing a serializtion update next tick - * @param val whether or not the velocity is dirty - */ - void SetDirtyVelocity(bool val); + /** + * Sets the on-rail parameter, determining if a player is currently on a rail (e.g. the lamps in Ninjago). + * Also ensures that this change is serialized. + * @param val whether the player is currently on a rail + */ + void SetIsOnRail(bool val); - /** - * Mark the angular velocity as dirty, forcing a serialization update next tick - * @param val whether or not the angular velocity is dirty - */ - void SetDirtyAngularVelocity(bool val); + /** + * Returns whether or not this entity is currently on a rail. + * @return whether or not this entity is currently on a rail + */ + const bool GetIsOnRail() const { return m_IsOnRail; } - /** - * Sets whether or not the entity is currently wearing a jetpack - * @param val whether or not the entity is currently wearing a jetpack - */ - void SetInJetpackMode(bool val) { m_InJetpackMode = val; } + /** + * Mark the position as dirty, forcing a serialization update next tick + * @param val whether or not the position is dirty + */ + void SetDirtyPosition(bool val); - /** - * Returns whether or not the entity is currently wearing a jetpack - * @return whether or not the entity is currently wearing a jetpack - */ - const bool GetInJetpackMode() const { return m_InJetpackMode; } + /** + * Mark the velocity as dirty, forcing a serializtion update next tick + * @param val whether or not the velocity is dirty + */ + void SetDirtyVelocity(bool val); - /** - * Sets whether or not the entity is currently flying a jetpack - * @param val whether or not the entity is currently flying a jetpack - */ - void SetJetpackFlying(bool val) { m_JetpackFlying = val; } + /** + * Mark the angular velocity as dirty, forcing a serialization update next tick + * @param val whether or not the angular velocity is dirty + */ + void SetDirtyAngularVelocity(bool val); - /** - * Returns whether or not an entity is currently flying a jetpack - * @return whether or not an entity is currently flying a jetpack - */ - const bool GetJetpackFlying() const { return m_JetpackFlying; } + /** + * Sets whether or not the entity is currently wearing a jetpack + * @param val whether or not the entity is currently wearing a jetpack + */ + void SetInJetpackMode(bool val) { m_InJetpackMode = val; } - /** - * UNUSED: necessary for serialization - */ - void SetJetpackBypassChecks(bool val) { m_JetpackBypassChecks = val; } + /** + * Returns whether or not the entity is currently wearing a jetpack + * @return whether or not the entity is currently wearing a jetpack + */ + const bool GetInJetpackMode() const { return m_InJetpackMode; } - /** - * UNUSUED: necessary for serialization - */ - const bool GetJetpackBypassChecks() const { return m_JetpackBypassChecks; } + /** + * Sets whether or not the entity is currently flying a jetpack + * @param val whether or not the entity is currently flying a jetpack + */ + void SetJetpackFlying(bool val) { m_JetpackFlying = val; } - /** - * Set the jetpack effect ID - * @param effectID the effect to play while using the jetpack - */ - void SetJetpackEffectID(int effectID) { m_JetpackEffectID = effectID; } + /** + * Returns whether or not an entity is currently flying a jetpack + * @return whether or not an entity is currently flying a jetpack + */ + const bool GetJetpackFlying() const { return m_JetpackFlying; } - /** - * Returns the current jetpack effect ID - * @return the current jetpack effect ID - */ - const int GetJetpackEffectID() const { return m_JetpackEffectID; } + /** + * UNUSED: necessary for serialization + */ + void SetJetpackBypassChecks(bool val) { m_JetpackBypassChecks = val; } - /** - * Sets a speed multiplier, altering the entities speed - * @param value the multiplier to set - */ - void SetSpeedMultiplier(float value) { m_SpeedMultiplier = value; m_DirtyCheats = true; } + /** + * UNUSUED: necessary for serialization + */ + const bool GetJetpackBypassChecks() const { return m_JetpackBypassChecks; } - /** - * Returns the current speed multiplier - * @return the current speed multiplier - */ - const float GetSpeedMultiplier() const { return m_SpeedMultiplier; } + /** + * Set the jetpack effect ID + * @param effectID the effect to play while using the jetpack + */ + void SetJetpackEffectID(int effectID) { m_JetpackEffectID = effectID; } - /** - * Sets the current gravity scale, allowing the entity to move using altered gravity - * @param value the gravity value to set - */ - void SetGravityScale(float value) { m_GravityScale = value; m_DirtyCheats = true; } + /** + * Returns the current jetpack effect ID + * @return the current jetpack effect ID + */ + const int GetJetpackEffectID() const { return m_JetpackEffectID; } - /** - * Returns the current gravity scale - * @return the current gravity scale - */ - const float GetGravityScale() const { return m_GravityScale; } + /** + * Sets a speed multiplier, altering the entities speed + * @param value the multiplier to set + */ + void SetSpeedMultiplier(float value) { m_SpeedMultiplier = value; m_DirtyCheats = true; } - /** - * Sets the ignore multipliers value, allowing you to skip the serialization of speed and gravity multipliers - * @param value whether or not to ignore multipliers - */ - void SetIgnoreMultipliers(bool value) { m_IgnoreMultipliers = value; } + /** + * Returns the current speed multiplier + * @return the current speed multiplier + */ + const float GetSpeedMultiplier() const { return m_SpeedMultiplier; } - /** - * Returns the current ignore multipliers value - * @return the current ignore multipliers value - */ - const bool GetIgnoreMultipliers() const { return m_IgnoreMultipliers; } + /** + * Sets the current gravity scale, allowing the entity to move using altered gravity + * @param value the gravity value to set + */ + void SetGravityScale(float value) { m_GravityScale = value; m_DirtyCheats = true; } - /** - * Can make an entity static, making it unable to move around - * @param value whether or not the entity is static - */ - void SetStatic(const bool value) { m_Static = value; } + /** + * Returns the current gravity scale + * @return the current gravity scale + */ + const float GetGravityScale() const { return m_GravityScale; } - /** - * Returns whether or not this entity is currently static - * @return whether or not this entity is currently static - */ - bool GetStatic() const { return m_Static; } + /** + * Sets the ignore multipliers value, allowing you to skip the serialization of speed and gravity multipliers + * @param value whether or not to ignore multipliers + */ + void SetIgnoreMultipliers(bool value) { m_IgnoreMultipliers = value; } - /** - * Returns the Physics entity for the component - * @return Physics entity for the component - */ + /** + * Returns the current ignore multipliers value + * @return the current ignore multipliers value + */ + const bool GetIgnoreMultipliers() const { return m_IgnoreMultipliers; } - dpEntity* GetdpEntity() const { return m_dpEntity; } + /** + * Can make an entity static, making it unable to move around + * @param value whether or not the entity is static + */ + void SetStatic(const bool value) { m_Static = value; } - /** - * I store this in a vector because if I have 2 separate pickup radii being applied to the player, I dont know which one is correctly active. - * This method adds the pickup radius to the vector of active radii and if its larger than the current one, is applied as the new pickup radius. - */ - void AddPickupRadiusScale(float value) ; + /** + * Returns whether or not this entity is currently static + * @return whether or not this entity is currently static + */ + bool GetStatic() const { return m_Static; } - /** - * Removes the provided pickup radius scale from our list of buffs - * The recalculates what our pickup radius is. - */ - void RemovePickupRadiusScale(float value) ; + /** + * Returns the Physics entity for the component + * @return Physics entity for the component + */ - /** - * The pickup radii of this component. - * @return All active radii scales for this component. - */ - std::vector GetActivePickupRadiusScales() { return m_ActivePickupRadiusScales; }; + dpEntity* GetdpEntity() const { return m_dpEntity; } + + /** + * I store this in a vector because if I have 2 separate pickup radii being applied to the player, I dont know which one is correctly active. + * This method adds the pickup radius to the vector of active radii and if its larger than the current one, is applied as the new pickup radius. + */ + void AddPickupRadiusScale(float value); + + /** + * Removes the provided pickup radius scale from our list of buffs + * The recalculates what our pickup radius is. + */ + void RemovePickupRadiusScale(float value); + + /** + * The pickup radii of this component. + * @return All active radii scales for this component. + */ + std::vector GetActivePickupRadiusScales() { return m_ActivePickupRadiusScales; }; private: - /** - * The entity that owns this component - */ - dpEntity* m_dpEntity; + /** + * The entity that owns this component + */ + dpEntity* m_dpEntity; - /** - * Whether or not the position is dirty, forcing a serialization update of the position - */ - bool m_DirtyPosition; + /** + * Whether or not the position is dirty, forcing a serialization update of the position + */ + bool m_DirtyPosition; - /** - * The current position of the entity - */ - NiPoint3 m_Position; + /** + * The current position of the entity + */ + NiPoint3 m_Position; - /** - * The current rotation of the entity - */ - NiQuaternion m_Rotation; + /** + * The current rotation of the entity + */ + NiQuaternion m_Rotation; - /** - * Whether or not the velocity is dirty, forcing a serialization of the velocity - */ - bool m_DirtyVelocity; + /** + * Whether or not the velocity is dirty, forcing a serialization of the velocity + */ + bool m_DirtyVelocity; - /** - * The current velocity of the entity - */ - NiPoint3 m_Velocity; + /** + * The current velocity of the entity + */ + NiPoint3 m_Velocity; - /** - * Whether or not the angular velocity is dirty, forcing a serialization - */ - bool m_DirtyAngularVelocity; + /** + * Whether or not the angular velocity is dirty, forcing a serialization + */ + bool m_DirtyAngularVelocity; - /** - * The current angular velocity of the entity - */ - NiPoint3 m_AngularVelocity; + /** + * The current angular velocity of the entity + */ + NiPoint3 m_AngularVelocity; - /** - * Whether or not the entity is on the ground, generally unused - */ - bool m_IsOnGround; + /** + * Whether or not the entity is on the ground, generally unused + */ + bool m_IsOnGround; - /** - * Whether or not the entity is on a rail, e.g. in Ninjago - */ - bool m_IsOnRail; + /** + * Whether or not the entity is on a rail, e.g. in Ninjago + */ + bool m_IsOnRail; - /** - * Whether or not this entity has a jetpack equipped - */ - bool m_InJetpackMode; + /** + * Whether or not this entity has a jetpack equipped + */ + bool m_InJetpackMode; - /** - * Whether or not this entity is currently flying a jetpack - */ - bool m_JetpackFlying; + /** + * Whether or not this entity is currently flying a jetpack + */ + bool m_JetpackFlying; - /** - * Bypass jetpack checks, currently unused - */ - bool m_JetpackBypassChecks; + /** + * Bypass jetpack checks, currently unused + */ + bool m_JetpackBypassChecks; - /** - * The effect that plays while using the jetpack - */ - int32_t m_JetpackEffectID; + /** + * The effect that plays while using the jetpack + */ + int32_t m_JetpackEffectID; - /** - * The current speed multiplier, allowing an entity to run faster - */ - float m_SpeedMultiplier; + /** + * The current speed multiplier, allowing an entity to run faster + */ + float m_SpeedMultiplier; - /** - * The current gravity scale, allowing an entity to move at an altered gravity - */ - float m_GravityScale; + /** + * The current gravity scale, allowing an entity to move at an altered gravity + */ + float m_GravityScale; - /** - * Forces a serialization of the speed multiplier and the gravity scale - */ - bool m_DirtyCheats; + /** + * Forces a serialization of the speed multiplier and the gravity scale + */ + bool m_DirtyCheats; - /** - * Makes it so that the speed multiplier and gravity scale are no longer serialized if false - */ - bool m_IgnoreMultipliers; + /** + * Makes it so that the speed multiplier and gravity scale are no longer serialized if false + */ + bool m_IgnoreMultipliers; - /** - * Whether this entity is static, making it unable to move - */ - bool m_Static; + /** + * Whether this entity is static, making it unable to move + */ + bool m_Static; - /** - * Whether the pickup scale is dirty. - */ - bool m_DirtyPickupRadiusScale; + /** + * Whether the pickup scale is dirty. + */ + bool m_DirtyPickupRadiusScale; - /** - * The list of pickup radius scales for this entity - */ - std::vector m_ActivePickupRadiusScales; + /** + * The list of pickup radius scales for this entity + */ + std::vector m_ActivePickupRadiusScales; - /** - * The active pickup radius for this entity - */ - float m_PickupRadius; + /** + * The active pickup radius for this entity + */ + float m_PickupRadius; }; #endif // CONTROLLABLEPHYSICSCOMPONENT_H diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index c2532f42..1cbf7aad 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -29,21 +29,21 @@ #include "dZoneManager.h" DestroyableComponent::DestroyableComponent(Entity* parent) : Component(parent) { - m_iArmor = 0; - m_fMaxArmor = 0.0f; - m_iImagination = 0; - m_fMaxImagination = 0.0f; - m_FactionIDs = std::vector(); - m_EnemyFactionIDs = std::vector(); - m_IsSmashable = false; - m_IsDead = false; - m_IsSmashed = false; - m_IsGMImmune = false; - m_IsShielded = false; - m_DamageToAbsorb = 0; - m_HasBricks = false; - m_DirtyThreatList = false; - m_HasThreats = false; + m_iArmor = 0; + m_fMaxArmor = 0.0f; + m_iImagination = 0; + m_fMaxImagination = 0.0f; + m_FactionIDs = std::vector(); + m_EnemyFactionIDs = std::vector(); + m_IsSmashable = false; + m_IsDead = false; + m_IsSmashed = false; + m_IsGMImmune = false; + m_IsShielded = false; + m_DamageToAbsorb = 0; + m_HasBricks = false; + m_DirtyThreatList = false; + m_HasThreats = false; m_ExplodeFactor = 1.0f; m_iHealth = 0; m_fMaxHealth = 0; @@ -87,8 +87,7 @@ void DestroyableComponent::Reinitialize(LOT templateID) { SetIsSmashable(destCompData[0].isSmashable); } - } - else { + } else { SetHealth(1); SetImagination(0); SetArmor(0); @@ -102,65 +101,65 @@ void DestroyableComponent::Reinitialize(LOT templateID) { } void DestroyableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags) { - if (bIsInitialUpdate) { - outBitStream->Write0(); //Contains info about immunities this object has, but it's left out for now. - } + if (bIsInitialUpdate) { + outBitStream->Write0(); //Contains info about immunities this object has, but it's left out for now. + } - outBitStream->Write(m_DirtyHealth || bIsInitialUpdate); - if (m_DirtyHealth || bIsInitialUpdate) { - outBitStream->Write(m_iHealth); - outBitStream->Write(m_fMaxHealth); - outBitStream->Write(m_iArmor); - outBitStream->Write(m_fMaxArmor); - outBitStream->Write(m_iImagination); - outBitStream->Write(m_fMaxImagination); + outBitStream->Write(m_DirtyHealth || bIsInitialUpdate); + if (m_DirtyHealth || bIsInitialUpdate) { + outBitStream->Write(m_iHealth); + outBitStream->Write(m_fMaxHealth); + outBitStream->Write(m_iArmor); + outBitStream->Write(m_fMaxArmor); + outBitStream->Write(m_iImagination); + outBitStream->Write(m_fMaxImagination); - outBitStream->Write(m_DamageToAbsorb); - outBitStream->Write(IsImmune()); - outBitStream->Write(m_IsGMImmune); - outBitStream->Write(m_IsShielded); + outBitStream->Write(m_DamageToAbsorb); + outBitStream->Write(IsImmune()); + outBitStream->Write(m_IsGMImmune); + outBitStream->Write(m_IsShielded); - outBitStream->Write(m_fMaxHealth); - outBitStream->Write(m_fMaxArmor); - outBitStream->Write(m_fMaxImagination); + outBitStream->Write(m_fMaxHealth); + outBitStream->Write(m_fMaxArmor); + outBitStream->Write(m_fMaxImagination); outBitStream->Write(uint32_t(m_FactionIDs.size())); for (size_t i = 0; i < m_FactionIDs.size(); ++i) { outBitStream->Write(m_FactionIDs[i]); } - outBitStream->Write(m_IsSmashable); + outBitStream->Write(m_IsSmashable); - if (bIsInitialUpdate) { - outBitStream->Write(m_IsDead); - outBitStream->Write(m_IsSmashed); + if (bIsInitialUpdate) { + outBitStream->Write(m_IsDead); + outBitStream->Write(m_IsSmashed); - if (m_IsSmashable) { - outBitStream->Write(m_HasBricks); + if (m_IsSmashable) { + outBitStream->Write(m_HasBricks); - if (m_ExplodeFactor != 1.0f) { - outBitStream->Write1(); - outBitStream->Write(m_ExplodeFactor); - } else { - outBitStream->Write0(); - } - } - } + if (m_ExplodeFactor != 1.0f) { + outBitStream->Write1(); + outBitStream->Write(m_ExplodeFactor); + } else { + outBitStream->Write0(); + } + } + } m_DirtyHealth = false; - } + } - if (m_DirtyThreatList || bIsInitialUpdate) { - outBitStream->Write1(); - outBitStream->Write(m_HasThreats); + if (m_DirtyThreatList || bIsInitialUpdate) { + outBitStream->Write1(); + outBitStream->Write(m_HasThreats); m_DirtyThreatList = false; - } else { - outBitStream->Write0(); - } + } else { + outBitStream->Write0(); + } } void DestroyableComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { - tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); + tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); if (!dest) { Game::logger->Log("DestroyableComponent", "Failed to find dest tag!"); return; @@ -173,16 +172,16 @@ void DestroyableComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { } dest->QueryAttribute("hc", &m_iHealth); - dest->QueryAttribute("hm", &m_fMaxHealth); - dest->QueryAttribute("im", &m_fMaxImagination); - dest->QueryAttribute("ic", &m_iImagination); - dest->QueryAttribute("ac", &m_iArmor); - dest->QueryAttribute("am", &m_fMaxArmor); - m_DirtyHealth = true; + dest->QueryAttribute("hm", &m_fMaxHealth); + dest->QueryAttribute("im", &m_fMaxImagination); + dest->QueryAttribute("ic", &m_iImagination); + dest->QueryAttribute("ac", &m_iArmor); + dest->QueryAttribute("am", &m_fMaxArmor); + m_DirtyHealth = true; } void DestroyableComponent::UpdateXml(tinyxml2::XMLDocument* doc) { - tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); + tinyxml2::XMLElement* dest = doc->FirstChildElement("obj")->FirstChildElement("dest"); if (!dest) { Game::logger->Log("DestroyableComponent", "Failed to find dest tag!"); return; @@ -195,11 +194,11 @@ void DestroyableComponent::UpdateXml(tinyxml2::XMLDocument* doc) { } dest->SetAttribute("hc", m_iHealth); - dest->SetAttribute("hm", m_fMaxHealth); - dest->SetAttribute("im", m_fMaxImagination); - dest->SetAttribute("ic", m_iImagination); - dest->SetAttribute("ac", m_iArmor); - dest->SetAttribute("am", m_fMaxArmor); + dest->SetAttribute("hm", m_fMaxHealth); + dest->SetAttribute("im", m_fMaxImagination); + dest->SetAttribute("ic", m_iImagination); + dest->SetAttribute("ac", m_iArmor); + dest->SetAttribute("am", m_fMaxArmor); } void DestroyableComponent::SetHealth(int32_t value) { @@ -207,7 +206,7 @@ void DestroyableComponent::SetHealth(int32_t value) { auto* characterComponent = m_Parent->GetComponent(); if (characterComponent != nullptr) { - characterComponent->TrackHealthDelta(value - m_iHealth); + characterComponent->TrackHealthDelta(value - m_iHealth); } m_iHealth = value; @@ -242,17 +241,17 @@ void DestroyableComponent::SetMaxHealth(float value, bool playAnim) { } void DestroyableComponent::SetArmor(int32_t value) { - m_DirtyHealth = true; + m_DirtyHealth = true; // If Destroyable Component already has zero armor do not trigger the passive ability again. bool hadArmor = m_iArmor > 0; - auto* characterComponent = m_Parent->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->TrackArmorDelta(value - m_iArmor); - } + auto* characterComponent = m_Parent->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->TrackArmorDelta(value - m_iArmor); + } - m_iArmor = value; + m_iArmor = value; auto* inventroyComponent = m_Parent->GetComponent(); if (m_iArmor == 0 && inventroyComponent != nullptr && hadArmor) { @@ -261,8 +260,8 @@ void DestroyableComponent::SetArmor(int32_t value) { } void DestroyableComponent::SetMaxArmor(float value, bool playAnim) { - m_DirtyHealth = true; - m_fMaxArmor = value; + m_DirtyHealth = true; + m_fMaxArmor = value; if (m_iArmor > m_fMaxArmor) { m_iArmor = m_fMaxArmor; @@ -287,14 +286,14 @@ void DestroyableComponent::SetMaxArmor(float value, bool playAnim) { } void DestroyableComponent::SetImagination(int32_t value) { - m_DirtyHealth = true; + m_DirtyHealth = true; - auto* characterComponent = m_Parent->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->TrackImaginationDelta(value - m_iImagination); - } + auto* characterComponent = m_Parent->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->TrackImaginationDelta(value - m_iImagination); + } - m_iImagination = value; + m_iImagination = value; auto* inventroyComponent = m_Parent->GetComponent(); if (m_iImagination == 0 && inventroyComponent != nullptr) { @@ -303,10 +302,10 @@ void DestroyableComponent::SetImagination(int32_t value) { } void DestroyableComponent::SetMaxImagination(float value, bool playAnim) { - m_DirtyHealth = true; + m_DirtyHealth = true; // Used for playAnim if opted in for. int32_t difference = static_cast(std::abs(m_fMaxImagination - value)); - m_fMaxImagination = value; + m_fMaxImagination = value; if (m_iImagination > m_fMaxImagination) { m_iImagination = m_fMaxImagination; @@ -329,32 +328,27 @@ void DestroyableComponent::SetMaxImagination(float value, bool playAnim) { EntityManager::Instance()->SerializeEntity(m_Parent); } -void DestroyableComponent::SetDamageToAbsorb(int32_t value) -{ +void DestroyableComponent::SetDamageToAbsorb(int32_t value) { m_DirtyHealth = true; m_DamageToAbsorb = value; } -void DestroyableComponent::SetDamageReduction(int32_t value) -{ +void DestroyableComponent::SetDamageReduction(int32_t value) { m_DirtyHealth = true; m_DamageReduction = value; } -void DestroyableComponent::SetIsImmune(bool value) -{ +void DestroyableComponent::SetIsImmune(bool value) { m_DirtyHealth = true; m_ImmuneStacks = value ? 1 : 0; } -void DestroyableComponent::SetIsGMImmune(bool value) -{ +void DestroyableComponent::SetIsGMImmune(bool value) { m_DirtyHealth = true; m_IsGMImmune = value; } -void DestroyableComponent::SetIsShielded(bool value) -{ +void DestroyableComponent::SetIsShielded(bool value) { m_DirtyHealth = true; m_IsShielded = value; } @@ -365,12 +359,12 @@ void DestroyableComponent::AddFaction(const int32_t factionID, const bool ignore return; } - m_FactionIDs.push_back(factionID); - m_DirtyHealth = true; + m_FactionIDs.push_back(factionID); + m_DirtyHealth = true; auto query = CDClientDatabase::CreatePreppedStmt( "SELECT enemyList FROM Factions WHERE faction = ?;"); - query.bind(1, (int) factionID); + query.bind(1, (int)factionID); auto result = query.execQuery(); @@ -390,13 +384,11 @@ void DestroyableComponent::AddFaction(const int32_t factionID, const bool ignore auto exclude = std::find(m_FactionIDs.begin(), m_FactionIDs.end(), id) != m_FactionIDs.end(); - if (!exclude) - { + if (!exclude) { exclude = std::find(m_EnemyFactionIDs.begin(), m_EnemyFactionIDs.end(), id) != m_EnemyFactionIDs.end(); } - if (exclude) - { + if (exclude) { continue; } @@ -406,60 +398,56 @@ void DestroyableComponent::AddFaction(const int32_t factionID, const bool ignore result.finalize(); } -bool DestroyableComponent::IsEnemy (const Entity* other) const { - const auto* otherDestroyableComponent = other->GetComponent(); - if (otherDestroyableComponent != nullptr) { - for (const auto enemyFaction : m_EnemyFactionIDs) { - for (const auto otherFaction : otherDestroyableComponent->GetFactionIDs()) { - if (enemyFaction == otherFaction) - return true; - } - } - } +bool DestroyableComponent::IsEnemy(const Entity* other) const { + const auto* otherDestroyableComponent = other->GetComponent(); + if (otherDestroyableComponent != nullptr) { + for (const auto enemyFaction : m_EnemyFactionIDs) { + for (const auto otherFaction : otherDestroyableComponent->GetFactionIDs()) { + if (enemyFaction == otherFaction) + return true; + } + } + } - return false; + return false; } -bool DestroyableComponent::IsFriend (const Entity* other) const { - const auto* otherDestroyableComponent = other->GetComponent(); - if (otherDestroyableComponent != nullptr) { - for (const auto enemyFaction : m_EnemyFactionIDs) { - for (const auto otherFaction : otherDestroyableComponent->GetFactionIDs()) { - if (enemyFaction == otherFaction) - return false; - } - } +bool DestroyableComponent::IsFriend(const Entity* other) const { + const auto* otherDestroyableComponent = other->GetComponent(); + if (otherDestroyableComponent != nullptr) { + for (const auto enemyFaction : m_EnemyFactionIDs) { + for (const auto otherFaction : otherDestroyableComponent->GetFactionIDs()) { + if (enemyFaction == otherFaction) + return false; + } + } - return true; - } + return true; + } - return false; + return false; } -void DestroyableComponent::AddEnemyFaction(int32_t factionID) -{ +void DestroyableComponent::AddEnemyFaction(int32_t factionID) { m_EnemyFactionIDs.push_back(factionID); } void DestroyableComponent::SetIsSmashable(bool value) { - m_DirtyHealth = true; - m_IsSmashable = value; - //m_HasBricks = value; + m_DirtyHealth = true; + m_IsSmashable = value; + //m_HasBricks = value; } -void DestroyableComponent::SetAttacksToBlock(const uint32_t value) -{ +void DestroyableComponent::SetAttacksToBlock(const uint32_t value) { m_AttacksToBlock = value; } -bool DestroyableComponent::IsImmune() const -{ +bool DestroyableComponent::IsImmune() const { return m_ImmuneStacks > 0 || m_IsGMImmune; } -bool DestroyableComponent::IsKnockbackImmune() const -{ +bool DestroyableComponent::IsKnockbackImmune() const { auto* characterComponent = m_Parent->GetComponent(); auto* inventoryComponent = m_Parent->GetComponent(); @@ -468,7 +456,7 @@ bool DestroyableComponent::IsKnockbackImmune() const ItemSetPassiveAbilityID::EngineerRank2, ItemSetPassiveAbilityID::EngineerRank3, ItemSetPassiveAbilityID::SummonerRank2, ItemSetPassiveAbilityID::SummonerRank3, ItemSetPassiveAbilityID::InventorRank2, ItemSetPassiveAbilityID::InventorRank3, - }, 5); + }, 5); if (hasPassive) { return true; @@ -478,52 +466,43 @@ bool DestroyableComponent::IsKnockbackImmune() const return IsImmune() || m_IsShielded || m_AttacksToBlock > 0; } -bool DestroyableComponent::HasFaction(int32_t factionID) const -{ +bool DestroyableComponent::HasFaction(int32_t factionID) const { return std::find(m_FactionIDs.begin(), m_FactionIDs.end(), factionID) != m_FactionIDs.end(); } -LWOOBJID DestroyableComponent::GetKillerID() const -{ +LWOOBJID DestroyableComponent::GetKillerID() const { return m_KillerID; } -Entity* DestroyableComponent::GetKiller() const -{ +Entity* DestroyableComponent::GetKiller() const { return EntityManager::Instance()->GetEntity(m_KillerID); } -bool DestroyableComponent::CheckValidity(const LWOOBJID target, const bool ignoreFactions, const bool targetEnemy, const bool targetFriend) const -{ +bool DestroyableComponent::CheckValidity(const LWOOBJID target, const bool ignoreFactions, const bool targetEnemy, const bool targetFriend) const { auto* targetEntity = EntityManager::Instance()->GetEntity(target); - if (targetEntity == nullptr) - { + if (targetEntity == nullptr) { Game::logger->Log("DestroyableComponent", "Invalid entity for checking validity (%llu)!", target); return false; } auto* targetDestroyable = targetEntity->GetComponent(); - if (targetDestroyable == nullptr) - { + if (targetDestroyable == nullptr) { return false; } auto* targetQuickbuild = targetEntity->GetComponent(); - if (targetQuickbuild != nullptr) - { + if (targetQuickbuild != nullptr) { const auto state = targetQuickbuild->GetState(); - if (state != REBUILD_COMPLETED) - { + if (state != REBUILD_COMPLETED) { return false; } } - if (ignoreFactions) - { + if (ignoreFactions) { return true; } @@ -536,8 +515,7 @@ bool DestroyableComponent::CheckValidity(const LWOOBJID target, const bool ignor } -void DestroyableComponent::Heal(const uint32_t health) -{ +void DestroyableComponent::Heal(const uint32_t health) { auto current = static_cast(GetHealth()); const auto max = static_cast(GetMaxHealth()); @@ -551,8 +529,7 @@ void DestroyableComponent::Heal(const uint32_t health) } -void DestroyableComponent::Imagine(const int32_t deltaImagination) -{ +void DestroyableComponent::Imagine(const int32_t deltaImagination) { auto current = static_cast(GetImagination()); const auto max = static_cast(GetMaxImagination()); @@ -560,8 +537,7 @@ void DestroyableComponent::Imagine(const int32_t deltaImagination) current = std::min(current, max); - if (current < 0) - { + if (current < 0) { current = 0; } @@ -571,8 +547,7 @@ void DestroyableComponent::Imagine(const int32_t deltaImagination) } -void DestroyableComponent::Repair(const uint32_t armor) -{ +void DestroyableComponent::Repair(const uint32_t armor) { auto current = static_cast(GetArmor()); const auto max = static_cast(GetMaxArmor()); @@ -586,34 +561,26 @@ void DestroyableComponent::Repair(const uint32_t armor) } -void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32_t skillID, bool echo) -{ - if (GetHealth() <= 0) - { +void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32_t skillID, bool echo) { + if (GetHealth() <= 0) { return; } - if (IsImmune()) - { + if (IsImmune()) { return; } - if (m_AttacksToBlock > 0) - { + if (m_AttacksToBlock > 0) { m_AttacksToBlock--; return; } // If this entity has damage reduction, reduce the damage to a minimum of 1 - if (m_DamageReduction > 0 && damage > 0) - { - if (damage > m_DamageReduction) - { + if (m_DamageReduction > 0 && damage > 0) { + if (damage > m_DamageReduction) { damage -= m_DamageReduction; - } - else - { + } else { damage = 1; } } @@ -641,13 +608,11 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 SetHealth(health); SetIsShielded(absorb > 0); - if (m_Parent->GetLOT() != 1) - { + if (m_Parent->GetLOT() != 1) { echo = true; } - if (echo) - { + if (echo) { EntityManager::Instance()->SerializeEntity(m_Parent); } @@ -656,15 +621,13 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 m_Parent->OnHitOrHealResult(attacker, sourceDamage); for (const auto& cb : m_OnHitCallbacks) { - cb(attacker); + cb(attacker); } - if (health != 0) - { + if (health != 0) { auto* combatComponent = m_Parent->GetComponent(); - if (combatComponent != nullptr) - { + if (combatComponent != nullptr) { combatComponent->Taunt(source, sourceDamage * 10); // * 10 is arbatrary } @@ -673,10 +636,8 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 Smash(source, eKillType::VIOLENT, u"", skillID); } -void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType, uint32_t skillID) -{ - if (m_iHealth > 0) - { +void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType, uint32_t skillID) { + if (m_iHealth > 0) { SetArmor(0); SetHealth(0); @@ -687,8 +648,7 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType auto* owner = EntityManager::Instance()->GetEntity(source); - if (owner != nullptr) - { + if (owner != nullptr) { owner = owner->GetOwner(); // If the owner is overwritten, we collect that here auto* team = TeamManager::Instance()->GetTeam(owner->GetObjectID()); @@ -697,19 +657,15 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType auto* inventoryComponent = owner->GetComponent(); - if (inventoryComponent != nullptr && isEnemy) - { + if (inventoryComponent != nullptr && isEnemy) { inventoryComponent->TriggerPassiveAbility(PassiveAbilityTrigger::EnemySmashed); } auto* missions = owner->GetComponent(); - if (missions != nullptr) - { - if (team != nullptr && isEnemy) - { - for (const auto memberId : team->members) - { + if (missions != nullptr) { + if (team != nullptr && isEnemy) { + for (const auto memberId : team->members) { auto* member = EntityManager::Instance()->GetEntity(memberId); if (member == nullptr) continue; @@ -721,9 +677,7 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType memberMissions->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, m_Parent->GetLOT()); memberMissions->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, m_Parent->GetLOT(), skillID); } - } - else - { + } else { missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, m_Parent->GetLOT()); missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, m_Parent->GetLOT(), skillID); } @@ -735,14 +689,11 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType GameMessages::SendDie(m_Parent, source, source, true, killType, deathType, 0, 0, 0, isPlayer, false, 1); //NANI?! - if (!isPlayer) - { - if (owner != nullptr) - { + if (!isPlayer) { + if (owner != nullptr) { auto* team = TeamManager::Instance()->GetTeam(owner->GetObjectID()); - if (team != nullptr && m_Parent->GetComponent() != nullptr) - { + if (team != nullptr && m_Parent->GetComponent() != nullptr) { LWOOBJID specificOwner = LWOOBJID_EMPTY; auto* scriptedActivityComponent = m_Parent->GetComponent(); uint32_t teamSize = team->members.size(); @@ -757,9 +708,8 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType auto* member = EntityManager::Instance()->GetEntity(specificOwner); - if (member) LootGenerator::Instance().DropLoot(member, m_Parent, lootMatrixId, GetMinCoins(), GetMaxCoins()); - } - else { + if (member) LootGenerator::Instance().DropLoot(member, m_Parent, lootMatrixId, GetMinCoins(), GetMaxCoins()); + } else { for (const auto memberId : team->members) { // Free for all auto* member = EntityManager::Instance()->GetEntity(memberId); @@ -768,32 +718,25 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType LootGenerator::Instance().DropLoot(member, m_Parent, lootMatrixId, GetMinCoins(), GetMaxCoins()); } } - } - else { // drop loot for non team user + } else { // drop loot for non team user LootGenerator::Instance().DropLoot(owner, m_Parent, GetLootMatrixID(), GetMinCoins(), GetMaxCoins()); } } - } - else - { + } else { //Check if this zone allows coin drops - if (dZoneManager::Instance()->GetPlayerLoseCoinOnDeath()) - { + if (dZoneManager::Instance()->GetPlayerLoseCoinOnDeath()) { auto* character = m_Parent->GetCharacter(); uint64_t coinsTotal = character->GetCoins(); - if (coinsTotal > 0) - { + if (coinsTotal > 0) { uint64_t coinsToLoose = 1; - if (coinsTotal >= 200) - { + if (coinsTotal >= 200) { float hundreth = (coinsTotal / 100.0f); coinsToLoose = static_cast(hundreth); } - if (coinsToLoose > 10000) - { + if (coinsToLoose > 10000) { coinsToLoose = 10000; } @@ -804,19 +747,19 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType } } - Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerDied(zoneControl, m_Parent); - } + Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { + script->OnPlayerDied(zoneControl, m_Parent); + } - std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_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->OnPlayerDied(scriptEntity, m_Parent); - } - } - } + std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_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->OnPlayerDied(scriptEntity, m_Parent); + } + } + } } m_Parent->Kill(owner); @@ -829,18 +772,15 @@ void DestroyableComponent::SetFaction(int32_t factionID, bool ignoreChecks) { AddFaction(factionID, ignoreChecks); } -void DestroyableComponent::PushImmunity(int32_t stacks) -{ +void DestroyableComponent::PushImmunity(int32_t stacks) { m_ImmuneStacks += stacks; } -void DestroyableComponent::PopImmunity(int32_t stacks) -{ +void DestroyableComponent::PopImmunity(int32_t stacks) { m_ImmuneStacks -= stacks; } -void DestroyableComponent::FixStats() -{ +void DestroyableComponent::FixStats() { auto* entity = GetParent(); if (entity == nullptr) return; @@ -853,8 +793,7 @@ void DestroyableComponent::FixStats() auto* destroyableComponent = entity->GetComponent(); // If any of the components are nullptr, return - if (skillComponent == nullptr || buffComponent == nullptr || missionComponent == nullptr || inventoryComponent == nullptr || destroyableComponent == nullptr) - { + if (skillComponent == nullptr || buffComponent == nullptr || missionComponent == nullptr || inventoryComponent == nullptr || destroyableComponent == nullptr) { return; } @@ -866,13 +805,11 @@ void DestroyableComponent::FixStats() // Unequip all items auto equipped = inventoryComponent->GetEquippedItems(); - for (auto& equippedItem : equipped) - { + for (auto& equippedItem : equipped) { // Get the item with the item ID auto* item = inventoryComponent->FindItemById(equippedItem.second.id); - if (item == nullptr) - { + if (item == nullptr) { continue; } @@ -886,12 +823,10 @@ void DestroyableComponent::FixStats() int32_t maxImagination = 0; // Go through all completed missions and add the reward stats - for (auto& pair : missionComponent->GetMissions()) - { + for (auto& pair : missionComponent->GetMissions()) { auto* mission = pair.second; - if (!mission->IsComplete()) - { + if (!mission->IsComplete()) { continue; } @@ -911,13 +846,11 @@ void DestroyableComponent::FixStats() buffComponent->ReApplyBuffs(); // Requip all items - for (auto& equippedItem : equipped) - { + for (auto& equippedItem : equipped) { // Get the item with the item ID auto* item = inventoryComponent->FindItemById(equippedItem.second.id); - if (item == nullptr) - { + if (item == nullptr) { continue; } @@ -945,5 +878,5 @@ void DestroyableComponent::FixStats() } void DestroyableComponent::AddOnHitCallback(const std::function& callback) { - m_OnHitCallbacks.push_back(callback); + m_OnHitCallbacks.push_back(callback); } diff --git a/dGame/dComponents/DestroyableComponent.h b/dGame/dComponents/DestroyableComponent.h index 9d2b228f..a403717b 100644 --- a/dGame/dComponents/DestroyableComponent.h +++ b/dGame/dComponents/DestroyableComponent.h @@ -13,542 +13,542 @@ */ class DestroyableComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_DESTROYABLE; - - DestroyableComponent(Entity* parentEntity); - ~DestroyableComponent() override; + static const uint32_t ComponentType = COMPONENT_TYPE_DESTROYABLE; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags); - void LoadFromXml(tinyxml2::XMLDocument* doc) override; - void UpdateXml(tinyxml2::XMLDocument* doc) override; + DestroyableComponent(Entity* parentEntity); + ~DestroyableComponent() override; - /** - * Initializes the component using a different LOT - * @param templateID the ID to use for initialization - */ + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; + void UpdateXml(tinyxml2::XMLDocument* doc) override; + + /** + * Initializes the component using a different LOT + * @param templateID the ID to use for initialization + */ void Reinitialize(LOT templateID); - /** - * Sets the health of this entity. Makes sure this is serialized on the next tick and if this is a character its - * stats will also update. - * @param value the new health value - */ - void SetHealth(int32_t value); + /** + * Sets the health of this entity. Makes sure this is serialized on the next tick and if this is a character its + * stats will also update. + * @param value the new health value + */ + void SetHealth(int32_t value); - /** - * Heals the entity by some delta amount - * @param health the delta amount to heal - */ - void Heal(uint32_t health); + /** + * Heals the entity by some delta amount + * @param health the delta amount to heal + */ + void Heal(uint32_t health); - /** - * Returns the current health of this entity - * @return the current health of this entity - */ - int32_t GetHealth() const { return m_iHealth; } + /** + * Returns the current health of this entity + * @return the current health of this entity + */ + int32_t GetHealth() const { return m_iHealth; } - /** - * Updates the max health this entity has (e.g. what it can heal to), and optionally displays a UI animation indicating that - * @param value the max health value to set - * @param playAnim whether or not to play a UI animation indicating the change in max health - */ - void SetMaxHealth(float value, bool playAnim = false); + /** + * Updates the max health this entity has (e.g. what it can heal to), and optionally displays a UI animation indicating that + * @param value the max health value to set + * @param playAnim whether or not to play a UI animation indicating the change in max health + */ + void SetMaxHealth(float value, bool playAnim = false); - /** - * Returns the curent max health of this entity - * @return the current max health of this entity - */ - float GetMaxHealth() const { return m_fMaxHealth; } + /** + * Returns the curent max health of this entity + * @return the current max health of this entity + */ + float GetMaxHealth() const { return m_fMaxHealth; } - /** - * Sets the armor for this entity. This also makes sure this change is serialized and if this is a character it also - * updates their stats. - * @param value the armor value to set - */ - void SetArmor(int32_t value); + /** + * Sets the armor for this entity. This also makes sure this change is serialized and if this is a character it also + * updates their stats. + * @param value the armor value to set + */ + void SetArmor(int32_t value); - /** - * Repairs armor of this entity, updating it by a delta amount - * @param armor the amount of armor to repair - */ - void Repair(uint32_t armor); + /** + * Repairs armor of this entity, updating it by a delta amount + * @param armor the amount of armor to repair + */ + void Repair(uint32_t armor); - /** - * Returns the current armor value for the entity - * @return the current armor value for the entity - */ - int32_t GetArmor() const { return m_iArmor; } + /** + * Returns the current armor value for the entity + * @return the current armor value for the entity + */ + int32_t GetArmor() const { return m_iArmor; } - /** - * Updates the max armor this entity has (e.g. what it can heal to), and optionally displays a UI animation indicating that - * @param value the max armor value to set - * @param playAnim whether or not to play a UI animation indicating the change in max armor - */ - void SetMaxArmor(float value, bool playAnim = false); + /** + * Updates the max armor this entity has (e.g. what it can heal to), and optionally displays a UI animation indicating that + * @param value the max armor value to set + * @param playAnim whether or not to play a UI animation indicating the change in max armor + */ + void SetMaxArmor(float value, bool playAnim = false); - /** - * Returns the current maximum armor this entity can have - * @return the current maximum armor this entity can have - */ - float GetMaxArmor() const { return m_fMaxArmor; } + /** + * Returns the current maximum armor this entity can have + * @return the current maximum armor this entity can have + */ + float GetMaxArmor() const { return m_fMaxArmor; } - /** - * Sets the imagination value for this entity. Ensures that the change is serialized and if this is a character - * their stats will be updated. Can also trigger the assembly passive ability to restore on 0 imag. - * @param value - */ - void SetImagination(int32_t value); + /** + * Sets the imagination value for this entity. Ensures that the change is serialized and if this is a character + * their stats will be updated. Can also trigger the assembly passive ability to restore on 0 imag. + * @param value + */ + void SetImagination(int32_t value); - /** - * Updates the imagination of this entity by a delta amount - * @param deltaImagination the imagination to update - */ - void Imagine(int32_t deltaImagination); + /** + * Updates the imagination of this entity by a delta amount + * @param deltaImagination the imagination to update + */ + void Imagine(int32_t deltaImagination); - /** - * Returns the current imagination value of this entity - * @return the current imagination value of this entity - */ - int32_t GetImagination() const { return m_iImagination; } + /** + * Returns the current imagination value of this entity + * @return the current imagination value of this entity + */ + int32_t GetImagination() const { return m_iImagination; } - /** - * Updates the max imagination this entity has (e.g. what it can heal to), and optionally displays a UI animation indicating that - * @param value the max imagination value to set - * @param playAnim whether or not to play a UI animation indicating the change in max imagination - */ - void SetMaxImagination(float value, bool playAnim = false); + /** + * Updates the max imagination this entity has (e.g. what it can heal to), and optionally displays a UI animation indicating that + * @param value the max imagination value to set + * @param playAnim whether or not to play a UI animation indicating the change in max imagination + */ + void SetMaxImagination(float value, bool playAnim = false); - /** - * Returns the current max imagination value - * @return the current max imagination value - */ - float GetMaxImagination() const { return m_fMaxImagination; } + /** + * Returns the current max imagination value + * @return the current max imagination value + */ + float GetMaxImagination() const { return m_fMaxImagination; } - /** - * Sets the damage this entity can absorb before getting hurt, also serializes this change. - * @param value the damage to absorb - */ - void SetDamageToAbsorb(int32_t value); + /** + * Sets the damage this entity can absorb before getting hurt, also serializes this change. + * @param value the damage to absorb + */ + void SetDamageToAbsorb(int32_t value); - /** - * Returns the current damage to absorb - * @return the current damage to absorb - */ - int32_t GetDamageToAbsorb() const { return m_DamageToAbsorb; } + /** + * Returns the current damage to absorb + * @return the current damage to absorb + */ + int32_t GetDamageToAbsorb() const { return m_DamageToAbsorb; } - /** - * Sets the reduced damage value for each attack for this entity, also serializes that change. - * @param value the damage to reduce for each attack - */ - void SetDamageReduction(int32_t value); + /** + * Sets the reduced damage value for each attack for this entity, also serializes that change. + * @param value the damage to reduce for each attack + */ + void SetDamageReduction(int32_t value); - /** - * Returns the current damage reduction value - * @return the current damage reduction value - */ - int32_t GetDamageReduction() const { return m_DamageReduction; } + /** + * Returns the current damage reduction value + * @return the current damage reduction value + */ + int32_t GetDamageReduction() const { return m_DamageReduction; } - /** - * Sets whether or not this entity is immune to attacks - * @param value whether or not this entity is immune to attacks - */ - void SetIsImmune(bool value); + /** + * Sets whether or not this entity is immune to attacks + * @param value whether or not this entity is immune to attacks + */ + void SetIsImmune(bool value); - /** - * Returns whether or not this entity is immune to attacks - * @return whether or not this entity is immune to attacks - */ - bool IsImmune() const; + /** + * Returns whether or not this entity is immune to attacks + * @return whether or not this entity is immune to attacks + */ + bool IsImmune() const; - /** - * Sets if this entity has GM immunity, making it not killable - * @param value the GM immunity of this entity - */ - void SetIsGMImmune(bool value); + /** + * Sets if this entity has GM immunity, making it not killable + * @param value the GM immunity of this entity + */ + void SetIsGMImmune(bool value); - /** - * Returns whether or not this entity has GM immunity - * @return whether or not this entity has GM immunity - */ - bool GetIsGMImmune() const { return m_IsGMImmune; } + /** + * Returns whether or not this entity has GM immunity + * @return whether or not this entity has GM immunity + */ + bool GetIsGMImmune() const { return m_IsGMImmune; } - /** - * Sets whether or not this entity is shielded for a certain amount of damage - * @param value whether or not this entity is shielded for a certain amount of damage - */ - void SetIsShielded(bool value); + /** + * Sets whether or not this entity is shielded for a certain amount of damage + * @param value whether or not this entity is shielded for a certain amount of damage + */ + void SetIsShielded(bool value); - /** - * Returns if this entity is currently shielded from damage - * @return if this entity is currently shielded from damage - */ - bool GetIsShielded() const { return m_IsShielded; } + /** + * Returns if this entity is currently shielded from damage + * @return if this entity is currently shielded from damage + */ + bool GetIsShielded() const { return m_IsShielded; } - /** - * Adds a faction to the faction list of this entity, potentially making more factions friendly. Fetches the info - * from the CDClient. - * @param factionID the faction ID to add - * @param ignoreChecks whether or not to allow factionID -1 - */ - void AddFaction(int32_t factionID, bool ignoreChecks = false); + /** + * Adds a faction to the faction list of this entity, potentially making more factions friendly. Fetches the info + * from the CDClient. + * @param factionID the faction ID to add + * @param ignoreChecks whether or not to allow factionID -1 + */ + void AddFaction(int32_t factionID, bool ignoreChecks = false); - /** - * Adds a faction ID to the enemy list - * @param factionID the faction ID to make an enemy - */ - void AddEnemyFaction(int32_t factionID); + /** + * Adds a faction ID to the enemy list + * @param factionID the faction ID to make an enemy + */ + void AddEnemyFaction(int32_t factionID); - /** - * Sets whether or not this entity can be smashed, does not indicate the smashable glow, which is indicated by - * faction ids - * @param value whether or not this entity is smashable - */ - void SetIsSmashable(bool value); + /** + * Sets whether or not this entity can be smashed, does not indicate the smashable glow, which is indicated by + * faction ids + * @param value whether or not this entity is smashable + */ + void SetIsSmashable(bool value); - /** - * Returns whether or not this entity is smashable - * @return whether or not this entity is smashable - */ - bool GetIsSmashable() const { return m_IsSmashable; } + /** + * Returns whether or not this entity is smashable + * @return whether or not this entity is smashable + */ + bool GetIsSmashable() const { return m_IsSmashable; } - /** - * Returns the current is-dead value, this is mostly unused - * @return the current is-dead value, this is mostly unused - */ - bool GetIsDead() const { return m_IsDead; } + /** + * Returns the current is-dead value, this is mostly unused + * @return the current is-dead value, this is mostly unused + */ + bool GetIsDead() const { return m_IsDead; } - /** - * Returns the current is-smashed value, this is mostly unused - * @return the current is-smashed value, this is mostly unused - */ - bool GetIsSmashed() const { return m_IsSmashed; } + /** + * Returns the current is-smashed value, this is mostly unused + * @return the current is-smashed value, this is mostly unused + */ + bool GetIsSmashed() const { return m_IsSmashed; } - /** - * Sets whether or not this entity has bricks flying out when smashed - * @param value whether or not this entity has bricks flying out when smashed - */ - void SetHasBricks(bool value); + /** + * Sets whether or not this entity has bricks flying out when smashed + * @param value whether or not this entity has bricks flying out when smashed + */ + void SetHasBricks(bool value); - /** - * Returns whether or not this entity has bricks flying out when smashed - * @return whether or not this entity has bricks flying out when smashed - */ - bool GetHasBricks() const { return m_HasBricks; } + /** + * Returns whether or not this entity has bricks flying out when smashed + * @return whether or not this entity has bricks flying out when smashed + */ + bool GetHasBricks() const { return m_HasBricks; } - /** - * Sets the multiplier for the explosion that's visible when the bricks fly out when this entity is smashed - * @param value the multiplier for the explosion that's visible when the bricks fly out when this entity is smashed - */ - void SetExplodeFactor(float value); + /** + * Sets the multiplier for the explosion that's visible when the bricks fly out when this entity is smashed + * @param value the multiplier for the explosion that's visible when the bricks fly out when this entity is smashed + */ + void SetExplodeFactor(float value); - /** - * Returns the current multiplier for explosions - * @return the current multiplier for explosions - */ - float GetExplodeFactor() const { return m_ExplodeFactor; } + /** + * Returns the current multiplier for explosions + * @return the current multiplier for explosions + */ + float GetExplodeFactor() const { return m_ExplodeFactor; } - /** - * Sets the amount of attacks this entity can block before being able to be damaged again, useful for example for - * shields. - * @param value the amount of attacks this entity can block before being able to be damaged again - */ - void SetAttacksToBlock(uint32_t value); + /** + * Sets the amount of attacks this entity can block before being able to be damaged again, useful for example for + * shields. + * @param value the amount of attacks this entity can block before being able to be damaged again + */ + void SetAttacksToBlock(uint32_t value); - /** - * Returns the current amount of attacks this entity can block - * @return the current amount of attacks this entity can block - */ - uint32_t GetAttacksToBlock() const { return m_AttacksToBlock; } + /** + * Returns the current amount of attacks this entity can block + * @return the current amount of attacks this entity can block + */ + uint32_t GetAttacksToBlock() const { return m_AttacksToBlock; } - /** - * Sets whether or not this enemy currently has threats, NOTE: only here for serialization, has no use internally - * @param value whether or not this enemy currently has threats - */ - void SetHasThreats(bool value); + /** + * Sets whether or not this enemy currently has threats, NOTE: only here for serialization, has no use internally + * @param value whether or not this enemy currently has threats + */ + void SetHasThreats(bool value); - /** - * Returns whether or not this entity currently has threats, NOTE: unused internally - * @return whether or not this entity currently has threats - */ - bool GetHasThreats() const { return m_HasThreats; } + /** + * Returns whether or not this entity currently has threats, NOTE: unused internally + * @return whether or not this entity currently has threats + */ + bool GetHasThreats() const { return m_HasThreats; } - /** - * Returns whether or not this entity is knockback immune, based on whether it's quickbuilding or has assembly gear - * @return whether or not this entity is knockback immune - */ - bool IsKnockbackImmune() const; + /** + * Returns whether or not this entity is knockback immune, based on whether it's quickbuilding or has assembly gear + * @return whether or not this entity is knockback immune + */ + bool IsKnockbackImmune() const; - /** - * Sets the faction ID of this entity, overriding all previously set entries - * @param factionID the faction ID to set - */ - void SetFaction(int32_t factionID, bool ignoreChecks = false); + /** + * Sets the faction ID of this entity, overriding all previously set entries + * @param factionID the faction ID to set + */ + void SetFaction(int32_t factionID, bool ignoreChecks = false); - /** - * Returns whether or not the provided entity is an enemy of this entity - * @param other the entity to check - * @return whether the provided entity is an enemy of this entity or not - */ - bool IsEnemy(const Entity *other) const; + /** + * Returns whether or not the provided entity is an enemy of this entity + * @param other the entity to check + * @return whether the provided entity is an enemy of this entity or not + */ + bool IsEnemy(const Entity* other) const; - /** - * Returns whether or not the provided entity is a friend of this entity - * @param other the entity to check - * @return whether or not the provided entity is a friend of this entity - */ - bool IsFriend(const Entity *other) const; + /** + * Returns whether or not the provided entity is a friend of this entity + * @param other the entity to check + * @return whether or not the provided entity is a friend of this entity + */ + bool IsFriend(const Entity* other) const; - /** - * Returns all the faction IDs that this entity considers a friend - * @return all the faction IDs that this entity considers a friend - */ - const std::vector& GetFactionIDs() const { return m_FactionIDs; } + /** + * Returns all the faction IDs that this entity considers a friend + * @return all the faction IDs that this entity considers a friend + */ + const std::vector& GetFactionIDs() const { return m_FactionIDs; } - /** - * Returns all the faction IDs that this entity considers an enemy - * @return all the faction IDs that this entity considers an enemy - */ - const std::vector& GetEnemyFactionsIDs() const { return m_EnemyFactionIDs; } + /** + * Returns all the faction IDs that this entity considers an enemy + * @return all the faction IDs that this entity considers an enemy + */ + const std::vector& GetEnemyFactionsIDs() const { return m_EnemyFactionIDs; } - /** - * Returns whether the provided faction is a friendly faction - * @param factionID the faction ID to check - * @return whether the provided faction is a friendly faction - */ - bool HasFaction(int32_t factionID) const; + /** + * Returns whether the provided faction is a friendly faction + * @param factionID the faction ID to check + * @return whether the provided faction is a friendly faction + */ + bool HasFaction(int32_t factionID) const; - /** - * Sets the minimum amount of coins this entity drops when smashed - * @param minCoins the minimum amount of coins this entity drops when smashed - */ + /** + * Sets the minimum amount of coins this entity drops when smashed + * @param minCoins the minimum amount of coins this entity drops when smashed + */ void SetMinCoins(uint32_t minCoins) { m_MinCoins = minCoins; } - /** - * Returns the minimum amount of coins this entity drops when smashed - * @return the minimum amount of coins this entity drops when smashed - */ + /** + * Returns the minimum amount of coins this entity drops when smashed + * @return the minimum amount of coins this entity drops when smashed + */ uint32_t GetMinCoins() const { return m_MinCoins; } - /** - * Sets the maximum amount of coins this entity drops when smashed - * @param maxCoins the maximum amount of coins this entity drops when smashed - */ + /** + * Sets the maximum amount of coins this entity drops when smashed + * @param maxCoins the maximum amount of coins this entity drops when smashed + */ void SetMaxCoins(uint32_t maxCoins) { m_MaxCoins = maxCoins; } - /** - * Returns the maximum amount of coins this entity drops when smashed - * @return the maximum amount of coins this entity drops when smashed - */ + /** + * Returns the maximum amount of coins this entity drops when smashed + * @return the maximum amount of coins this entity drops when smashed + */ uint32_t GetMaxCoins() const { return m_MaxCoins; } - /** - * Sets the loot matrix ID that will be used to determine what items to drop when this entity is smashed - * @param lootMatrixID the loot matrix ID to set - */ + /** + * Sets the loot matrix ID that will be used to determine what items to drop when this entity is smashed + * @param lootMatrixID the loot matrix ID to set + */ void SetLootMatrixID(uint32_t lootMatrixID) { m_LootMatrixID = lootMatrixID; } - /** - * Returns the current loot matrix ID that will be used to determine loot drops when this entity is smashed - * @return the current loot matrix ID - */ + /** + * Returns the current loot matrix ID that will be used to determine loot drops when this entity is smashed + * @return the current loot matrix ID + */ uint32_t GetLootMatrixID() const { return m_LootMatrixID; } - /** - * Returns the ID of the entity that killed this entity, if any - * @return the ID of the entity that killed this entity, if any - */ - LWOOBJID GetKillerID() const; + /** + * Returns the ID of the entity that killed this entity, if any + * @return the ID of the entity that killed this entity, if any + */ + LWOOBJID GetKillerID() const; - /** - * Returns the entity that killed this entity, if any - * @return the entity that killed this entity, if any - */ - Entity* GetKiller() const; + /** + * Returns the entity that killed this entity, if any + * @return the entity that killed this entity, if any + */ + Entity* GetKiller() const; - /** - * Checks if the target ID is a valid enemy of this entity - * @param target the target ID to check for - * @param ignoreFactions whether or not check for the factions, e.g. just return true if the entity cannot be smashed - * @return if the target ID is a valid enemy - */ - bool CheckValidity(LWOOBJID target, bool ignoreFactions = false, bool targetEnemy = true, bool targetFriend = false) const; + /** + * Checks if the target ID is a valid enemy of this entity + * @param target the target ID to check for + * @param ignoreFactions whether or not check for the factions, e.g. just return true if the entity cannot be smashed + * @return if the target ID is a valid enemy + */ + bool CheckValidity(LWOOBJID target, bool ignoreFactions = false, bool targetEnemy = true, bool targetFriend = false) const; - /** - * Attempt to damage this entity, handles everything from health and armor to absorption, immunity and callbacks. - * @param damage the damage to attempt to apply - * @param source the attacker that caused this damage - * @param skillID the skill that damaged this entity - * @param echo whether or not to serialize the damage - */ + /** + * Attempt to damage this entity, handles everything from health and armor to absorption, immunity and callbacks. + * @param damage the damage to attempt to apply + * @param source the attacker that caused this damage + * @param skillID the skill that damaged this entity + * @param echo whether or not to serialize the damage + */ void Damage(uint32_t damage, LWOOBJID source, uint32_t skillID = 0, bool echo = true); - /** - * Smashes this entity, notifying all clients - * @param source the source that smashed this entity - * @param skillID the skill that killed this entity - * @param killType the way this entity was killed, determines if a client animation is played - * @param deathType the animation to play when killed - */ - void Smash(LWOOBJID source, eKillType killType = eKillType::VIOLENT, const std::u16string& deathType = u"", uint32_t skillID = 0); + /** + * Smashes this entity, notifying all clients + * @param source the source that smashed this entity + * @param skillID the skill that killed this entity + * @param killType the way this entity was killed, determines if a client animation is played + * @param deathType the animation to play when killed + */ + void Smash(LWOOBJID source, eKillType killType = eKillType::VIOLENT, const std::u16string& deathType = u"", uint32_t skillID = 0); - /** - * Pushes a layer of immunity to this entity, making it immune for longer - * @param stacks the amount of immunity to add - */ - void PushImmunity(int32_t stacks = 1); + /** + * Pushes a layer of immunity to this entity, making it immune for longer + * @param stacks the amount of immunity to add + */ + void PushImmunity(int32_t stacks = 1); - /** - * Pops layers of immunity, making it immune for less longer - * @param stacks the number of layers of immunity to remove - */ - void PopImmunity(int32_t stacks = 1); + /** + * Pops layers of immunity, making it immune for less longer + * @param stacks the number of layers of immunity to remove + */ + void PopImmunity(int32_t stacks = 1); - /** - * Utility to reset all stats to the default stats based on items and completed missions - */ + /** + * Utility to reset all stats to the default stats based on items and completed missions + */ void FixStats(); - /** - * Adds a callback that is called when this entity is hit by some other entity - * @param callback the callback to add - */ + /** + * Adds a callback that is called when this entity is hit by some other entity + * @param callback the callback to add + */ void AddOnHitCallback(const std::function& callback); private: - /** - * Whether or not the health should be serialized - */ - bool m_DirtyHealth; + /** + * Whether or not the health should be serialized + */ + bool m_DirtyHealth; - /** - * The health of the entity - */ - int32_t m_iHealth; + /** + * The health of the entity + */ + int32_t m_iHealth; - /** - * The max health of the entity - */ - float m_fMaxHealth; + /** + * The max health of the entity + */ + float m_fMaxHealth; - /** - * The armor of the entity - */ - int32_t m_iArmor; + /** + * The armor of the entity + */ + int32_t m_iArmor; - /** - * The max armor of the entity - */ - float m_fMaxArmor; + /** + * The max armor of the entity + */ + float m_fMaxArmor; - /** - * The imagination of the entity - */ - int32_t m_iImagination; + /** + * The imagination of the entity + */ + int32_t m_iImagination; - /** - * The max imagination of the entity - */ - float m_fMaxImagination; + /** + * The max imagination of the entity + */ + float m_fMaxImagination; - /** - * The damage this entity can absord before being able to be damaged again - */ - int32_t m_DamageToAbsorb; + /** + * The damage this entity can absord before being able to be damaged again + */ + int32_t m_DamageToAbsorb; - /** - * Whether this entity currently has GM immunity, making it unsmashable - */ - bool m_IsGMImmune; + /** + * Whether this entity currently has GM immunity, making it unsmashable + */ + bool m_IsGMImmune; - /** - * Whether this entity is currently shielded from other attacks - */ - bool m_IsShielded; + /** + * Whether this entity is currently shielded from other attacks + */ + bool m_IsShielded; - /** - * The number of attacks this entity can block before being able to be attacked again - */ - uint32_t m_AttacksToBlock; + /** + * The number of attacks this entity can block before being able to be attacked again + */ + uint32_t m_AttacksToBlock; - /** - * The layers of immunity this entity has left - */ - int32_t m_ImmuneStacks; + /** + * The layers of immunity this entity has left + */ + int32_t m_ImmuneStacks; - /** - * The amount of damage that should be reduced from every attack - */ - int32_t m_DamageReduction; + /** + * The amount of damage that should be reduced from every attack + */ + int32_t m_DamageReduction; - /** - * The faction IDs this entity considers friendly - */ - std::vector m_FactionIDs; + /** + * The faction IDs this entity considers friendly + */ + std::vector m_FactionIDs; - /** - * The faction IDs this entity considers hostile - */ - std::vector m_EnemyFactionIDs; + /** + * The faction IDs this entity considers hostile + */ + std::vector m_EnemyFactionIDs; - /** - * Whether this entity is smasahble, mostly unused - */ - bool m_IsSmashable; + /** + * Whether this entity is smasahble, mostly unused + */ + bool m_IsSmashable; - /** - * Whether this entity is dead. Unused, here for serialization - */ - bool m_IsDead; + /** + * Whether this entity is dead. Unused, here for serialization + */ + bool m_IsDead; - /** - * Whether this entity is smashed. Unused, here for serialization - */ - bool m_IsSmashed; + /** + * Whether this entity is smashed. Unused, here for serialization + */ + bool m_IsSmashed; - /** - * Whether this entity has bricks flying out when smashed (causes the client to look up the files) - */ - bool m_HasBricks; + /** + * Whether this entity has bricks flying out when smashed (causes the client to look up the files) + */ + bool m_HasBricks; - /** - * The rate at which bricks fly out when smashed - */ - float m_ExplodeFactor; + /** + * The rate at which bricks fly out when smashed + */ + float m_ExplodeFactor; - /** - * Whether the list of potential enemies has changed - */ - bool m_DirtyThreatList; + /** + * Whether the list of potential enemies has changed + */ + bool m_DirtyThreatList; - /** - * Whether the entity has threats. Unused: here for serialization - */ - bool m_HasThreats; + /** + * Whether the entity has threats. Unused: here for serialization + */ + bool m_HasThreats; - /** - * The loot matrix that will be used to drop items when the entity is smashed - */ + /** + * The loot matrix that will be used to drop items when the entity is smashed + */ uint32_t m_LootMatrixID; - /** - * The min amount of coins that will drop when this entity is smashed - */ + /** + * The min amount of coins that will drop when this entity is smashed + */ uint32_t m_MinCoins; - /** - * The max amount of coins that will drop when this entity is smashed - */ + /** + * The max amount of coins that will drop when this entity is smashed + */ uint32_t m_MaxCoins; - /** - * The ID of the entity that smashed this entity, if any - */ - LWOOBJID m_KillerID; + /** + * The ID of the entity that smashed this entity, if any + */ + LWOOBJID m_KillerID; - /** - * The list of callbacks that will be called when this entity gets hit - */ - std::vector> m_OnHitCallbacks; + /** + * The list of callbacks that will be called when this entity gets hit + */ + std::vector> m_OnHitCallbacks; }; #endif // DESTROYABLECOMPONENT_H diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index ea6c8368..a48173bb 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -27,8 +27,7 @@ #include "dConfig.h" #include "eItemType.h" -InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document) : Component(parent) -{ +InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document) : Component(parent) { this->m_Dirty = true; this->m_Equipped = {}; this->m_Pushed = {}; @@ -37,8 +36,7 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do const auto lot = parent->GetLOT(); - if (lot == 1) - { + if (lot == 1) { LoadXml(document); CheckProxyIntegrity(); @@ -54,10 +52,8 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do auto slot = 0u; - for (const auto& item : items) - { - if (!item.equip || !Inventory::IsValidItem(item.itemid)) - { + for (const auto& item : items) { + if (!item.equip || !Inventory::IsValidItem(item.itemid)) { continue; } @@ -69,20 +65,17 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do } } -Inventory* InventoryComponent::GetInventory(const eInventoryType type) -{ +Inventory* InventoryComponent::GetInventory(const eInventoryType type) { const auto index = m_Inventories.find(type); - if (index != m_Inventories.end()) - { + if (index != m_Inventories.end()) { return index->second; } // Create new empty inventory uint32_t size = 240u; - switch (type) - { + switch (type) { case eInventoryType::ITEMS: size = 20u; break; @@ -104,29 +97,24 @@ Inventory* InventoryComponent::GetInventory(const eInventoryType type) return inventory; } -const std::map& InventoryComponent::GetInventories() const -{ +const std::map& InventoryComponent::GetInventories() const { return m_Inventories; } -uint32_t InventoryComponent::GetLotCount(const LOT lot) const -{ +uint32_t InventoryComponent::GetLotCount(const LOT lot) const { uint32_t count = 0; - for (const auto& inventory : m_Inventories) - { + for (const auto& inventory : m_Inventories) { count += inventory.second->GetLotCount(lot); } return count; } -uint32_t InventoryComponent::GetLotCountNonTransfer(LOT lot) const -{ +uint32_t InventoryComponent::GetLotCountNonTransfer(LOT lot) const { uint32_t count = 0; - for (const auto& inventory : m_Inventories) - { + for (const auto& inventory : m_Inventories) { if (IsTransferInventory(inventory.second->GetType())) continue; count += inventory.second->GetLotCount(lot); @@ -135,8 +123,7 @@ uint32_t InventoryComponent::GetLotCountNonTransfer(LOT lot) const return count; } -const EquipmentMap& InventoryComponent::GetEquippedItems() const -{ +const EquipmentMap& InventoryComponent::GetEquippedItems() const { return m_Equipped; } @@ -153,27 +140,22 @@ void InventoryComponent::AddItem( const eInventoryType inventorySourceType, const int32_t sourceType, const bool bound, - int32_t preferredSlot) -{ - if (count == 0) - { + int32_t preferredSlot) { + if (count == 0) { Game::logger->Log("InventoryComponent", "Attempted to add 0 of item (%i) to the inventory!", lot); return; } - if (!Inventory::IsValidItem(lot)) - { - if (lot > 0) - { + if (!Inventory::IsValidItem(lot)) { + if (lot > 0) { Game::logger->Log("InventoryComponent", "Attempted to add invalid item (%i) to the inventory!", lot); } return; } - if (inventoryType == INVALID) - { + if (inventoryType == INVALID) { inventoryType = Inventory::FindInventoryTypeForLot(lot); } @@ -181,12 +163,10 @@ void InventoryComponent::AddItem( auto* inventory = GetInventory(inventoryType); - if (!config.empty() || bound) - { + if (!config.empty() || bound) { const auto slot = preferredSlot != -1 && inventory->IsSlotEmpty(preferredSlot) ? preferredSlot : inventory->FindEmptySlot(); - if (slot == -1) - { + if (slot == -1) { Game::logger->Log("InventoryComponent", "Failed to find empty slot for inventory (%i)!", inventoryType); return; @@ -194,8 +174,7 @@ void InventoryComponent::AddItem( auto* item = new Item(lot, inventory, slot, count, config, parent, showFlyingLoot, isModMoveAndEquip, subKey, bound, lootSourceType); - if (missions != nullptr && !IsTransferInventory(inventoryType)) - { + if (missions != nullptr && !IsTransferInventory(inventoryType)) { missions->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, LWOOBJID_EMPTY, "", count, IsTransferInventory(inventorySourceType)); } @@ -211,72 +190,59 @@ void InventoryComponent::AddItem( auto stack = static_cast(info.stackSize); // info.itemType of 1 is item type brick - if (inventoryType == eInventoryType::BRICKS || (stack == 0 && info.itemType == 1)) - { + if (inventoryType == eInventoryType::BRICKS || (stack == 0 && info.itemType == 1)) { stack = 999; - } - else if (stack == 0) - { + } else if (stack == 0) { stack = 1; } auto* existing = FindItemByLot(lot, inventoryType); - if (existing != nullptr) - { + if (existing != nullptr) { const auto delta = std::min(left, stack - existing->GetCount()); left -= delta; existing->SetCount(existing->GetCount() + delta, false, true, showFlyingLoot, lootSourceType); - if (isModMoveAndEquip) - { + if (isModMoveAndEquip) { existing->Equip(); isModMoveAndEquip = false; } } - while (left > 0) - { + while (left > 0) { const auto size = std::min(left, stack); left -= size; int32_t slot; - if (preferredSlot != -1 && inventory->IsSlotEmpty(preferredSlot)) - { + if (preferredSlot != -1 && inventory->IsSlotEmpty(preferredSlot)) { slot = preferredSlot; preferredSlot = -1; - } - else - { + } else { slot = inventory->FindEmptySlot(); } - if (slot == -1) - { + if (slot == -1) { auto* player = dynamic_cast(GetParent()); - if (player == nullptr) - { + if (player == nullptr) { return; } outOfSpace += size; - switch (sourceType) - { + switch (sourceType) { case 0: player->SendMail(LWOOBJID_EMPTY, "Darkflame Universe", "Lost Reward", "You received an item and didn't have room for it.", lot, size); break; case 1: - for (size_t i = 0; i < size; i++) - { + for (size_t i = 0; i < size; i++) { GameMessages::SendDropClientLoot(this->m_Parent, this->m_Parent->GetObjectID(), lot, 0, this->m_Parent->GetPosition(), 1); } @@ -293,41 +259,34 @@ void InventoryComponent::AddItem( isModMoveAndEquip = false; } - if (missions != nullptr && !IsTransferInventory(inventoryType)) - { + if (missions != nullptr && !IsTransferInventory(inventoryType)) { missions->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, LWOOBJID_EMPTY, "", count - outOfSpace, IsTransferInventory(inventorySourceType)); } } -void InventoryComponent::RemoveItem(const LOT lot, const uint32_t count, eInventoryType inventoryType, const bool ignoreBound) -{ - if (count == 0) - { +void InventoryComponent::RemoveItem(const LOT lot, const uint32_t count, eInventoryType inventoryType, const bool ignoreBound) { + if (count == 0) { Game::logger->Log("InventoryComponent", "Attempted to remove 0 of item (%i) from the inventory!", lot); return; } - if (inventoryType == INVALID) - { + if (inventoryType == INVALID) { inventoryType = Inventory::FindInventoryTypeForLot(lot); } auto* inventory = GetInventory(inventoryType); - if (inventory == nullptr) - { + if (inventory == nullptr) { return; } auto left = std::min(count, inventory->GetLotCount(lot)); - while (left > 0) - { + while (left > 0) { auto* item = FindItemByLot(lot, inventoryType, false, ignoreBound); - if (item == nullptr) - { + if (item == nullptr) { break; } @@ -339,10 +298,8 @@ void InventoryComponent::RemoveItem(const LOT lot, const uint32_t count, eInvent } } -void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType inventory, const uint32_t count, const bool showFlyingLot, bool isModMoveAndEquip, const bool ignoreEquipped, const int32_t preferredSlot) -{ - if (item == nullptr) - { +void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType inventory, const uint32_t count, const bool showFlyingLot, bool isModMoveAndEquip, const bool ignoreEquipped, const int32_t preferredSlot) { + if (item == nullptr) { return; } @@ -350,18 +307,14 @@ void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType in const auto lot = item->GetLot(); - if (item->GetConfig().empty() && !item->GetBound() || (item->GetBound() && item->GetInfo().isBOP)) - { + if (item->GetConfig().empty() && !item->GetBound() || (item->GetBound() && item->GetInfo().isBOP)) { auto left = std::min(count, origin->GetLotCount(lot)); - while (left > 0) - { - if (item == nullptr) - { + while (left > 0) { + if (item == nullptr) { item = origin->FindItemByLot(lot, false); - if (item == nullptr) - { + if (item == nullptr) { break; } } @@ -376,13 +329,10 @@ void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType in isModMoveAndEquip = false; } - } - else - { + } else { std::vector config; - for (auto* const data : item->GetConfig()) - { + for (auto* const data : item->GetConfig()) { config.push_back(data->Copy()); } @@ -395,19 +345,15 @@ void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType in auto* missionComponent = m_Parent->GetComponent(); - if (missionComponent != nullptr) - { - if (IsTransferInventory(inventory)) - { + if (missionComponent != nullptr) { + if (IsTransferInventory(inventory)) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, LWOOBJID_EMPTY, "", -static_cast(count)); } } } -void InventoryComponent::MoveStack(Item* item, const eInventoryType inventory, const uint32_t slot) -{ - if (inventory != INVALID && item->GetInventory()->GetType() != inventory) - { +void InventoryComponent::MoveStack(Item* item, const eInventoryType inventory, const uint32_t slot) { + if (inventory != INVALID && item->GetInventory()->GetType() != inventory) { auto* newInventory = GetInventory(inventory); item->SetInventory(newInventory); @@ -416,14 +362,11 @@ void InventoryComponent::MoveStack(Item* item, const eInventoryType inventory, c item->SetSlot(slot); } -Item* InventoryComponent::FindItemById(const LWOOBJID id) const -{ - for (const auto& inventory : m_Inventories) - { +Item* InventoryComponent::FindItemById(const LWOOBJID id) const { + for (const auto& inventory : m_Inventories) { auto* item = inventory.second->FindItemById(id); - if (item != nullptr) - { + if (item != nullptr) { return item; } } @@ -431,10 +374,8 @@ Item* InventoryComponent::FindItemById(const LWOOBJID id) const return nullptr; } -Item* InventoryComponent::FindItemByLot(const LOT lot, eInventoryType inventoryType, const bool ignoreEquipped, const bool ignoreBound) -{ - if (inventoryType == INVALID) - { +Item* InventoryComponent::FindItemByLot(const LOT lot, eInventoryType inventoryType, const bool ignoreEquipped, const bool ignoreBound) { + if (inventoryType == INVALID) { inventoryType = Inventory::FindInventoryTypeForLot(lot); } @@ -443,47 +384,37 @@ Item* InventoryComponent::FindItemByLot(const LOT lot, eInventoryType inventoryT return inventory->FindItemByLot(lot, ignoreEquipped, ignoreBound); } -Item* InventoryComponent::FindItemBySubKey(LWOOBJID id, eInventoryType inventoryType) -{ - if (inventoryType == INVALID) - { - for (const auto& inventory : m_Inventories) - { +Item* InventoryComponent::FindItemBySubKey(LWOOBJID id, eInventoryType inventoryType) { + if (inventoryType == INVALID) { + for (const auto& inventory : m_Inventories) { auto* item = inventory.second->FindItemBySubKey(id); - if (item != nullptr) - { + if (item != nullptr) { return item; } } return nullptr; - } - else - { + } else { return GetInventory(inventoryType)->FindItemBySubKey(id); } } -bool InventoryComponent::HasSpaceForLoot(const std::unordered_map& loot) -{ - std::unordered_map spaceOffset {}; +bool InventoryComponent::HasSpaceForLoot(const std::unordered_map& loot) { + std::unordered_map spaceOffset{}; uint32_t slotsNeeded = 0; - for (const auto& pair : loot) - { + for (const auto& pair : loot) { const auto inventoryType = Inventory::FindInventoryTypeForLot(pair.first); - if (inventoryType == BRICKS) - { + if (inventoryType == BRICKS) { continue; } auto* inventory = GetInventory(inventoryType); - if (inventory == nullptr) - { + if (inventory == nullptr) { return false; } @@ -495,8 +426,7 @@ bool InventoryComponent::HasSpaceForLoot(const std::unordered_map& auto* partial = inventory->FindItemByLot(pair.first); - if (partial != nullptr && partial->GetCount() < stack) - { + if (partial != nullptr && partial->GetCount() < stack) { left -= stack - partial->GetCount(); } @@ -506,16 +436,14 @@ bool InventoryComponent::HasSpaceForLoot(const std::unordered_map& auto freeSpace = inventory->GetEmptySlots() - (offsetIter == spaceOffset.end() ? 0 : offsetIter->second); - if (requiredSlots > freeSpace) - { + if (requiredSlots > freeSpace) { slotsNeeded += requiredSlots - freeSpace; } spaceOffset[inventoryType] = offsetIter == spaceOffset.end() ? requiredSlots : offsetIter->second + requiredSlots; } - if (slotsNeeded > 0) - { + if (slotsNeeded > 0) { GameMessages::SendNotifyNotEnoughInvSpace(m_Parent->GetObjectID(), slotsNeeded, ITEMS, m_Parent->GetSystemAddress()); return false; @@ -524,14 +452,12 @@ bool InventoryComponent::HasSpaceForLoot(const std::unordered_map& return true; } -void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) -{ +void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) { LoadPetXml(document); auto* inventoryElement = document->FirstChildElement("obj")->FirstChildElement("inv"); - if (inventoryElement == nullptr) - { + if (inventoryElement == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find 'inv' xml element!"); return; @@ -539,8 +465,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) auto* bags = inventoryElement->FirstChildElement("bag"); - if (bags == nullptr) - { + if (bags == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find 'bags' xml element!"); return; @@ -550,8 +475,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) auto* bag = bags->FirstChildElement(); - while (bag != nullptr) - { + while (bag != nullptr) { unsigned int type; unsigned int size; @@ -567,8 +491,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) auto* items = inventoryElement->FirstChildElement("items"); - if (items == nullptr) - { + if (items == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find 'items' xml element!"); return; @@ -576,16 +499,14 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) bag = items->FirstChildElement(); - while (bag != nullptr) - { + while (bag != nullptr) { unsigned int type; bag->QueryAttribute("t", &type); auto* inventory = GetInventory(static_cast(type)); - if (inventory == nullptr) - { + if (inventory == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find inventory (%i)!", type); return; @@ -593,8 +514,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) auto* itemElement = bag->FirstChildElement(); - while (itemElement != nullptr) - { + while (itemElement != nullptr) { LWOOBJID id; LOT lot; bool equipped; @@ -621,8 +541,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) auto* extraInfo = itemElement->FirstChildElement("x"); - if (extraInfo) - { + if (extraInfo) { std::string modInfo = extraInfo->Attribute("ma"); LDFBaseData* moduleAssembly = new LDFData(u"assemblyPartLOTs", GeneralUtils::ASCIIToUTF16(modInfo.substr(2, modInfo.size() - 1))); @@ -632,8 +551,7 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) const auto* item = new Item(id, lot, inventory, slot, count, bound, config, parent, subKey); - if (equipped) - { + if (equipped) { const auto info = Inventory::FindItemComponent(lot); UpdateSlot(info.equipLocation, { item->GetId(), item->GetLot(), item->GetCount(), item->GetSlot() }); @@ -647,25 +565,21 @@ void InventoryComponent::LoadXml(tinyxml2::XMLDocument* document) bag = bag->NextSiblingElement(); } - for (const auto inventory : m_Inventories) - { + for (const auto inventory : m_Inventories) { const auto itemCount = inventory.second->GetItems().size(); - if (inventory.second->GetSize() < itemCount) - { + if (inventory.second->GetSize() < itemCount) { inventory.second->SetSize(itemCount); } } } -void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) -{ +void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) { UpdatePetXml(document); auto* inventoryElement = document->FirstChildElement("obj")->FirstChildElement("inv"); - if (inventoryElement == nullptr) - { + if (inventoryElement == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find 'inv' xml element!"); return; @@ -673,12 +587,10 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) std::vector inventories; - for (const auto& pair : this->m_Inventories) - { + for (const auto& pair : this->m_Inventories) { auto* inventory = pair.second; - if (inventory->GetType() == VENDOR_BUYBACK) - { + if (inventory->GetType() == VENDOR_BUYBACK) { continue; } @@ -689,8 +601,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) auto* bags = inventoryElement->FirstChildElement("bag"); - if (bags == nullptr) - { + if (bags == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find 'bags' xml element!"); return; @@ -698,8 +609,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) bags->DeleteChildren(); - for (const auto* inventory : inventories) - { + for (const auto* inventory : inventories) { auto* bag = document->NewElement("b"); bag->SetAttribute("t", inventory->GetType()); @@ -710,8 +620,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) auto* items = inventoryElement->FirstChildElement("items"); - if (items == nullptr) - { + if (items == nullptr) { Game::logger->Log("InventoryComponent", "Failed to find 'items' xml element!"); return; @@ -719,10 +628,8 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) items->DeleteChildren(); - for (auto* inventory : inventories) - { - if (inventory->GetSize() == 0) - { + for (auto* inventory : inventories) { + if (inventory->GetSize() == 0) { continue; } @@ -730,8 +637,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) bagElement->SetAttribute("t", inventory->GetType()); - for (const auto& pair : inventory->GetItems()) - { + for (const auto& pair : inventory->GetItems()) { auto* item = pair.second; auto* itemElement = document->NewElement("i"); @@ -748,10 +654,8 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) itemElement->SetAttribute("parent", item->GetParent()); // End custom xml - for (auto* data : item->GetConfig()) - { - if (data->GetKey() != u"assemblyPartLOTs") - { + for (auto* data : item->GetConfig()) { + if (data->GetKey() != u"assemblyPartLOTs") { continue; } @@ -769,35 +673,31 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) } } -void InventoryComponent::Serialize(RakNet::BitStream* outBitStream, const bool bIsInitialUpdate, unsigned& flags) -{ - if (bIsInitialUpdate || m_Dirty) - { +void InventoryComponent::Serialize(RakNet::BitStream* outBitStream, const bool bIsInitialUpdate, unsigned& flags) { + if (bIsInitialUpdate || m_Dirty) { outBitStream->Write(true); outBitStream->Write(m_Equipped.size()); - for (const auto& pair : m_Equipped) - { + for (const auto& pair : m_Equipped) { const auto item = pair.second; - if (bIsInitialUpdate) - { + if (bIsInitialUpdate) { AddItemSkills(item.lot); } outBitStream->Write(item.id); - outBitStream->Write(item.lot); + outBitStream->Write(item.lot); - outBitStream->Write0(); + outBitStream->Write0(); - outBitStream->Write(item.count > 0); - if (item.count > 0) outBitStream->Write(item.count); + outBitStream->Write(item.count > 0); + if (item.count > 0) outBitStream->Write(item.count); - outBitStream->Write(item.slot != 0); - if (item.slot != 0) outBitStream->Write(item.slot); + outBitStream->Write(item.slot != 0); + if (item.slot != 0) outBitStream->Write(item.slot); - outBitStream->Write0(); + outBitStream->Write0(); bool flag = !item.config.empty(); outBitStream->Write(flag); @@ -824,34 +724,27 @@ void InventoryComponent::Serialize(RakNet::BitStream* outBitStream, const bool b } m_Dirty = false; - } - else - { + } else { outBitStream->Write(false); } outBitStream->Write(false); } -void InventoryComponent::ResetFlags() -{ +void InventoryComponent::ResetFlags() { m_Dirty = false; } -void InventoryComponent::Update(float deltaTime) -{ - for (auto* set : m_Itemsets) - { +void InventoryComponent::Update(float deltaTime) { + for (auto* set : m_Itemsets) { set->Update(deltaTime); } } -void InventoryComponent::UpdateSlot(const std::string& location, EquippedItem item, bool keepCurrent) -{ +void InventoryComponent::UpdateSlot(const std::string& location, EquippedItem item, bool keepCurrent) { const auto index = m_Equipped.find(location); - if (index != m_Equipped.end()) - { + if (index != m_Equipped.end()) { if (keepCurrent) { m_Equipped.insert_or_assign(location + std::to_string(m_Equipped.size()), item); @@ -862,8 +755,7 @@ void InventoryComponent::UpdateSlot(const std::string& location, EquippedItem it auto* old = FindItemById(index->second.id); - if (old != nullptr) - { + if (old != nullptr) { UnEquipItem(old); } } @@ -873,10 +765,8 @@ void InventoryComponent::UpdateSlot(const std::string& location, EquippedItem it m_Dirty = true; } -void InventoryComponent::RemoveSlot(const std::string& location) -{ - if (m_Equipped.find(location) == m_Equipped.end()) - { +void InventoryComponent::RemoveSlot(const std::string& location) { + if (m_Equipped.find(location) == m_Equipped.end()) { return; } @@ -885,39 +775,33 @@ void InventoryComponent::RemoveSlot(const std::string& location) m_Dirty = true; } -void InventoryComponent::EquipItem(Item* item, const bool skipChecks) -{ - if (!Inventory::IsValidItem(item->GetLot())) - { +void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { + if (!Inventory::IsValidItem(item->GetLot())) { return; } - // Temp items should be equippable but other transfer items shouldn't be (for example the instruments in RB) + // Temp items should be equippable but other transfer items shouldn't be (for example the instruments in RB) if (item->IsEquipped() - || (item->GetInventory()->GetType() != TEMP_ITEMS && IsTransferInventory(item->GetInventory()->GetType())) - || IsPet(item->GetSubKey())) { + || (item->GetInventory()->GetType() != TEMP_ITEMS && IsTransferInventory(item->GetInventory()->GetType())) + || IsPet(item->GetSubKey())) { return; } auto* character = m_Parent->GetCharacter(); - if (character != nullptr && !skipChecks) - { + if (character != nullptr && !skipChecks) { // Hacky proximity rocket - if (item->GetLot() == 6416) - { + if (item->GetLot() == 6416) { const auto rocketLauchPads = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_ROCKET_LAUNCH); const auto position = m_Parent->GetPosition(); - for (auto* lauchPad : rocketLauchPads) - { + for (auto* lauchPad : rocketLauchPads) { if (Vector3::DistanceSquared(lauchPad->GetPosition(), position) > 13 * 13) continue; auto* characterComponent = m_Parent->GetComponent(); - if (characterComponent != nullptr) - { + if (characterComponent != nullptr) { characterComponent->SetLastRocketItemID(item->GetId()); } @@ -933,8 +817,7 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) const auto type = static_cast(item->GetInfo().itemType); - if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == false) - { + if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == false) { auto startPosition = m_Parent->GetPosition(); auto startRotation = NiQuaternion::LookAt(startPosition, startPosition + NiPoint3::UNIT_X); @@ -944,7 +827,7 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) GameMessages::SendTeleport(m_Parent->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); - EntityInfo info {}; + EntityInfo info{}; info.lot = 8092; info.pos = startPosition; info.rot = startRotation; @@ -953,33 +836,29 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) auto* carEntity = EntityManager::Instance()->CreateEntity(info, nullptr, m_Parent); m_Parent->AddChild(carEntity); - auto *destroyableComponent = carEntity->GetComponent(); + auto* destroyableComponent = carEntity->GetComponent(); - // Setup the vehicle stats. - if (destroyableComponent != nullptr) { + // Setup the vehicle stats. + if (destroyableComponent != nullptr) { destroyableComponent->SetIsSmashable(false); destroyableComponent->SetIsImmune(true); - } + } // #108 auto* possessableComponent = carEntity->GetComponent(); - if (possessableComponent != nullptr) - { + if (possessableComponent != nullptr) { previousPossessableID = possessableComponent->GetPossessor(); possessableComponent->SetPossessor(m_Parent->GetObjectID()); } auto* moduleAssemblyComponent = carEntity->GetComponent(); - if (moduleAssemblyComponent != nullptr) - { + if (moduleAssemblyComponent != nullptr) { moduleAssemblyComponent->SetSubKey(item->GetSubKey()); moduleAssemblyComponent->SetUseOptionalParts(false); - for (auto* config : item->GetConfig()) - { - if (config->GetKey() == u"assemblyPartLOTs") - { + for (auto* config : item->GetConfig()) { + if (config->GetKey() == u"assemblyPartLOTs") { moduleAssemblyComponent->SetAssemblyPartsLOTs(GeneralUtils::ASCIIToUTF16(config->GetValueAsString())); } } @@ -1001,14 +880,13 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) GameMessages::SendRacingPlayerLoaded(LWOOBJID_EMPTY, m_Parent->GetObjectID(), carEntity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendVehicleUnlockInput(carEntity->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendTeleport(m_Parent->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); - GameMessages::SendTeleport(carEntity->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); + GameMessages::SendTeleport(carEntity->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); EntityManager::Instance()->SerializeEntity(m_Parent); hasCarEquipped = true; equippedCarEntity = carEntity; return; - } else if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == true) - { + } else if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == true) { GameMessages::SendNotifyRacingClient(LWOOBJID_EMPTY, 3, 0, LWOOBJID_EMPTY, u"", m_Parent->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); auto player = dynamic_cast(m_Parent); player->SendToZone(player->GetCharacter()->GetZoneID()); @@ -1018,23 +896,18 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) return; } - if (!building) - { - if (item->GetLot() == 6086) - { + if (!building) { + if (item->GetLot() == 6086) { return; } - if (type == eItemType::ITEM_TYPE_LOOT_MODEL || type == eItemType::ITEM_TYPE_VEHICLE) - { + if (type == eItemType::ITEM_TYPE_LOOT_MODEL || type == eItemType::ITEM_TYPE_VEHICLE) { return; } } - if (type != eItemType::ITEM_TYPE_LOOT_MODEL && type != eItemType::ITEM_TYPE_MODEL) - { - if (!item->GetBound() && !item->GetPreconditionExpression()->Check(m_Parent)) - { + if (type != eItemType::ITEM_TYPE_LOOT_MODEL && type != eItemType::ITEM_TYPE_MODEL) { + if (!item->GetBound() && !item->GetPreconditionExpression()->Check(m_Parent)) { return; } } @@ -1044,13 +917,11 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) CheckItemSet(lot); - for (auto* set : m_Itemsets) - { + for (auto* set : m_Itemsets) { set->OnEquip(lot); } - if (item->GetInfo().isBOE) - { + if (item->GetInfo().isBOE) { item->SetBound(true); } @@ -1065,24 +936,20 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) EntityManager::Instance()->SerializeEntity(m_Parent); } -void InventoryComponent::UnEquipItem(Item* item) -{ - if (!item->IsEquipped()) - { +void InventoryComponent::UnEquipItem(Item* item) { + if (!item->IsEquipped()) { return; } const auto lot = item->GetLot(); - if (!Inventory::IsValidItem(lot)) - { + if (!Inventory::IsValidItem(lot)) { return; } CheckItemSet(lot); - for (auto* set : m_Itemsets) - { + for (auto* set : m_Itemsets) { set->OnUnEquip(lot); } @@ -1097,62 +964,51 @@ void InventoryComponent::UnEquipItem(Item* item) EntityManager::Instance()->SerializeEntity(m_Parent); // Trigger property event - if (PropertyManagementComponent::Instance() != nullptr && item->GetCount() > 0 && Inventory::FindInventoryTypeForLot(item->GetLot()) == MODELS) - { + if (PropertyManagementComponent::Instance() != nullptr && item->GetCount() > 0 && Inventory::FindInventoryTypeForLot(item->GetLot()) == MODELS) { PropertyManagementComponent::Instance()->GetParent()->OnZonePropertyModelRemovedWhileEquipped(m_Parent); dZoneManager::Instance()->GetZoneControlObject()->OnZonePropertyModelRemovedWhileEquipped(m_Parent); } } -void InventoryComponent::ApplyBuff(Item* item) const -{ +void InventoryComponent::ApplyBuff(Item* item) const { const auto buffs = FindBuffs(item, true); - for (const auto buff : buffs) - { + for (const auto buff : buffs) { SkillComponent::HandleUnmanaged(buff, m_Parent->GetObjectID()); } } -void InventoryComponent::RemoveBuff(Item* item) const -{ +void InventoryComponent::RemoveBuff(Item* item) const { const auto buffs = FindBuffs(item, false); - for (const auto buff : buffs) - { + for (const auto buff : buffs) { SkillComponent::HandleUnCast(buff, m_Parent->GetObjectID()); } } -void InventoryComponent::PushEquippedItems() -{ +void InventoryComponent::PushEquippedItems() { m_Pushed = m_Equipped; m_Dirty = true; } -void InventoryComponent::PopEquippedItems() -{ +void InventoryComponent::PopEquippedItems() { auto current = m_Equipped; - for (const auto& pair : current) - { + for (const auto& pair : current) { auto* const item = FindItemById(pair.second.id); - if (item == nullptr) - { + if (item == nullptr) { continue; } item->UnEquip(); } - for (const auto& pair : m_Pushed) - { + for (const auto& pair : m_Pushed) { auto* const item = FindItemById(pair.second.id); - if (item == nullptr) - { + if (item == nullptr) { continue; } @@ -1175,12 +1031,9 @@ void InventoryComponent::PopEquippedItems() } -bool InventoryComponent::IsEquipped(const LOT lot) const -{ - for (const auto& pair : m_Equipped) - { - if (pair.second.lot == lot) - { +bool InventoryComponent::IsEquipped(const LOT lot) const { + for (const auto& pair : m_Equipped) { + if (pair.second.lot == lot) { return true; } } @@ -1208,17 +1061,14 @@ void InventoryComponent::CheckItemSet(const LOT lot) { bool found = false; // Check if we have the set already - for (auto* itemset : m_Itemsets) - { - if (itemset->GetID() == id) - { + for (auto* itemset : m_Itemsets) { + if (itemset->GetID() == id) { found = true; break; } } - if (!found) - { + if (!found) { auto* set = new ItemSet(id, this); m_Itemsets.push_back(set); @@ -1232,24 +1082,20 @@ void InventoryComponent::CheckItemSet(const LOT lot) { result.finalize(); } -void InventoryComponent::SetConsumable(LOT lot) -{ +void InventoryComponent::SetConsumable(LOT lot) { m_Consumable = lot; } -LOT InventoryComponent::GetConsumable() const -{ +LOT InventoryComponent::GetConsumable() const { return m_Consumable; } -void InventoryComponent::AddItemSkills(const LOT lot) -{ +void InventoryComponent::AddItemSkills(const LOT lot) { const auto info = Inventory::FindItemComponent(lot); const auto slot = FindBehaviorSlot(static_cast(info.itemType)); - if (slot == BehaviorSlot::Invalid) - { + if (slot == BehaviorSlot::Invalid) { return; } @@ -1257,13 +1103,11 @@ void InventoryComponent::AddItemSkills(const LOT lot) const auto skill = FindSkill(lot); - if (skill == 0) - { + if (skill == 0) { return; } - if (index != m_Skills.end()) - { + if (index != m_Skills.end()) { const auto old = index->second; GameMessages::SendRemoveSkill(m_Parent, old); @@ -1274,21 +1118,18 @@ void InventoryComponent::AddItemSkills(const LOT lot) m_Skills.insert_or_assign(slot, skill); } -void InventoryComponent::RemoveItemSkills(const LOT lot) -{ +void InventoryComponent::RemoveItemSkills(const LOT lot) { const auto info = Inventory::FindItemComponent(lot); const auto slot = FindBehaviorSlot(static_cast(info.itemType)); - if (slot == BehaviorSlot::Invalid) - { + if (slot == BehaviorSlot::Invalid) { return; } const auto index = m_Skills.find(slot); - if (index == m_Skills.end()) - { + if (index == m_Skills.end()) { return; } @@ -1298,34 +1139,27 @@ void InventoryComponent::RemoveItemSkills(const LOT lot) m_Skills.erase(slot); - if (slot == BehaviorSlot::Primary) - { + if (slot == BehaviorSlot::Primary) { m_Skills.insert_or_assign(BehaviorSlot::Primary, 1); GameMessages::SendAddSkill(m_Parent, 1, static_cast(BehaviorSlot::Primary)); } } -void InventoryComponent::TriggerPassiveAbility(PassiveAbilityTrigger trigger) -{ - for (auto* set : m_Itemsets) - { +void InventoryComponent::TriggerPassiveAbility(PassiveAbilityTrigger trigger) { + for (auto* set : m_Itemsets) { set->TriggerPassiveAbility(trigger); } } -bool InventoryComponent::HasAnyPassive(const std::vector& passiveIDs, int32_t equipmentRequirement) const -{ - for (auto* set : m_Itemsets) - { - if (set->GetEquippedCount() < equipmentRequirement) - { +bool InventoryComponent::HasAnyPassive(const std::vector& passiveIDs, int32_t equipmentRequirement) const { + for (auto* set : m_Itemsets) { + if (set->GetEquippedCount() < equipmentRequirement) { continue; } // Check if the set has any of the passive abilities - if (std::find(passiveIDs.begin(), passiveIDs.end(), static_cast(set->GetID())) != passiveIDs.end()) - { + if (std::find(passiveIDs.begin(), passiveIDs.end(), static_cast(set->GetID())) != passiveIDs.end()) { return true; } } @@ -1333,26 +1167,21 @@ bool InventoryComponent::HasAnyPassive(const std::vectorGetObjectID()); - if (current != nullptr) - { + if (current != nullptr) { current->Deactivate(); } } -void InventoryComponent::SpawnPet(Item* item) -{ +void InventoryComponent::SpawnPet(Item* item) { auto* current = PetComponent::GetActivePet(m_Parent->GetObjectID()); - if (current != nullptr) - { + if (current != nullptr) { current->Deactivate(); - if (current->GetDatabaseId() == item->GetSubKey()) - { + if (current->GetDatabaseId() == item->GetSubKey()) { return; } } @@ -1365,7 +1194,7 @@ void InventoryComponent::SpawnPet(Item* item) return; } - EntityInfo info {}; + EntityInfo info{}; info.lot = item->GetLot(); info.pos = m_Parent->GetPosition(); info.rot = NiQuaternion::IDENTITY; @@ -1375,21 +1204,18 @@ void InventoryComponent::SpawnPet(Item* item) auto* petComponent = pet->GetComponent(); - if (petComponent != nullptr) - { + if (petComponent != nullptr) { petComponent->Activate(item); } EntityManager::Instance()->ConstructEntity(pet); } -void InventoryComponent::SetDatabasePet(LWOOBJID id, const DatabasePet& data) -{ +void InventoryComponent::SetDatabasePet(LWOOBJID id, const DatabasePet& data) { m_Pets.insert_or_assign(id, data); } -const DatabasePet& InventoryComponent::GetDatabasePet(LWOOBJID id) const -{ +const DatabasePet& InventoryComponent::GetDatabasePet(LWOOBJID id) const { const auto& pair = m_Pets.find(id); if (pair == m_Pets.end()) return DATABASE_PET_INVALID; @@ -1397,20 +1223,17 @@ const DatabasePet& InventoryComponent::GetDatabasePet(LWOOBJID id) const return pair->second; } -bool InventoryComponent::IsPet(LWOOBJID id) const -{ +bool InventoryComponent::IsPet(LWOOBJID id) const { const auto& pair = m_Pets.find(id); return pair != m_Pets.end(); } -void InventoryComponent::RemoveDatabasePet(LWOOBJID id) -{ +void InventoryComponent::RemoveDatabasePet(LWOOBJID id) { m_Pets.erase(id); } -BehaviorSlot InventoryComponent::FindBehaviorSlot(const eItemType type) -{ +BehaviorSlot InventoryComponent::FindBehaviorSlot(const eItemType type) { switch (type) { case eItemType::ITEM_TYPE_HAT: return BehaviorSlot::Head; @@ -1427,24 +1250,19 @@ BehaviorSlot InventoryComponent::FindBehaviorSlot(const eItemType type) } } -bool InventoryComponent::IsTransferInventory(eInventoryType type) -{ +bool InventoryComponent::IsTransferInventory(eInventoryType type) { return type == VENDOR_BUYBACK || type == VAULT_ITEMS || type == VAULT_MODELS || type == TEMP_ITEMS || type == TEMP_MODELS; } -uint32_t InventoryComponent::FindSkill(const LOT lot) -{ +uint32_t InventoryComponent::FindSkill(const LOT lot) { auto* table = CDClientManager::Instance()->GetTable("ObjectSkills"); - const auto results = table->Query([=](const CDObjectSkills& entry) - { + const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast(lot); - }); + }); - for (const auto& result : results) - { - if (result.castOnType == 0) - { + for (const auto& result : results) { + if (result.castOnType == 0) { return result.skillID; } } @@ -1452,35 +1270,29 @@ uint32_t InventoryComponent::FindSkill(const LOT lot) return 0; } -std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip) const -{ +std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip) const { std::vector buffs; if (item == nullptr) return buffs; auto* table = CDClientManager::Instance()->GetTable("ObjectSkills"); auto* behaviors = CDClientManager::Instance()->GetTable("SkillBehavior"); - const auto results = table->Query([=](const CDObjectSkills& entry) - { + const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast(item->GetLot()); - }); + }); auto* missions = static_cast(m_Parent->GetComponent(COMPONENT_TYPE_MISSION)); - for (const auto& result : results) - { - if (result.castOnType == 1) - { + for (const auto& result : results) { + if (result.castOnType == 1) { const auto entry = behaviors->GetSkillByID(result.skillID); - if (entry.skillID == 0) - { + if (entry.skillID == 0) { Game::logger->Log("InventoryComponent", "Failed to find buff behavior for skill (%i)!", result.skillID); continue; } - if (missions != nullptr && castOnEquip) - { + if (missions != nullptr && castOnEquip) { missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, result.skillID); } @@ -1492,14 +1304,12 @@ std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip return buffs; } -void InventoryComponent::SetNPCItems(const std::vector& items) -{ +void InventoryComponent::SetNPCItems(const std::vector& items) { m_Equipped.clear(); auto slot = 0u; - for (const auto& item : items) - { + for (const auto& item : items) { const LWOOBJID id = ObjectIDManager::Instance()->GenerateObjectID(); const auto& info = Inventory::FindItemComponent(item); @@ -1510,17 +1320,14 @@ void InventoryComponent::SetNPCItems(const std::vector& items) EntityManager::Instance()->SerializeEntity(m_Parent); } -InventoryComponent::~InventoryComponent() -{ - for (const auto& inventory : m_Inventories) - { +InventoryComponent::~InventoryComponent() { + for (const auto& inventory : m_Inventories) { delete inventory.second; } m_Inventories.clear(); - for (auto* set : m_Itemsets) - { + for (auto* set : m_Itemsets) { delete set; } @@ -1528,14 +1335,12 @@ InventoryComponent::~InventoryComponent() m_Pets.clear(); } -std::vector InventoryComponent::GenerateProxies(Item* parent) -{ +std::vector InventoryComponent::GenerateProxies(Item* parent) { std::vector proxies; auto subItems = parent->GetInfo().subItems; - if (subItems.empty()) - { + if (subItems.empty()) { return proxies; } @@ -1545,22 +1350,16 @@ std::vector InventoryComponent::GenerateProxies(Item* parent) std::string segment; std::vector lots; - while (std::getline(stream, segment, ',')) - { - try - { + while (std::getline(stream, segment, ',')) { + try { lots.push_back(std::stoi(segment)); - } - catch (std::invalid_argument& exception) - { + } catch (std::invalid_argument& exception) { Game::logger->Log("InventoryComponent", "Failed to parse proxy (%s): (%s)!", segment.c_str(), exception.what()); } } - for (const auto lot : lots) - { - if (!Inventory::IsValidItem(lot)) - { + for (const auto lot : lots) { + if (!Inventory::IsValidItem(lot)) { continue; } @@ -1576,18 +1375,15 @@ std::vector InventoryComponent::GenerateProxies(Item* parent) return proxies; } -std::vector InventoryComponent::FindProxies(const LWOOBJID parent) -{ +std::vector InventoryComponent::FindProxies(const LWOOBJID parent) { auto* inventory = GetInventory(ITEM_SETS); std::vector proxies; - for (const auto& pair : inventory->GetItems()) - { + for (const auto& pair : inventory->GetItems()) { auto* item = pair.second; - if (item->GetParent() == parent) - { + if (item->GetParent() == parent) { proxies.push_back(item); } } @@ -1595,18 +1391,14 @@ std::vector InventoryComponent::FindProxies(const LWOOBJID parent) return proxies; } -bool InventoryComponent::IsValidProxy(const LWOOBJID parent) -{ - for (const auto& pair : m_Inventories) - { +bool InventoryComponent::IsValidProxy(const LWOOBJID parent) { + for (const auto& pair : m_Inventories) { const auto items = pair.second->GetItems(); - for (const auto& candidate : items) - { + for (const auto& candidate : items) { auto* item = candidate.second; - if (item->GetId() == parent) - { + if (item->GetId() == parent) { return true; } } @@ -1615,25 +1407,20 @@ bool InventoryComponent::IsValidProxy(const LWOOBJID parent) return false; } -bool InventoryComponent::IsParentValid(Item* root) -{ - if (root->GetInfo().subItems.empty()) - { +bool InventoryComponent::IsParentValid(Item* root) { + if (root->GetInfo().subItems.empty()) { return true; } const auto id = root->GetId(); - for (const auto& pair : m_Inventories) - { + for (const auto& pair : m_Inventories) { const auto items = pair.second->GetItems(); - for (const auto& candidate : items) - { + for (const auto& candidate : items) { auto* item = candidate.second; - if (item->GetParent() == id) - { + if (item->GetParent() == id) { return true; } } @@ -1642,27 +1429,22 @@ bool InventoryComponent::IsParentValid(Item* root) return false; } -void InventoryComponent::CheckProxyIntegrity() -{ +void InventoryComponent::CheckProxyIntegrity() { std::vector dead; - for (const auto& pair : m_Inventories) - { + for (const auto& pair : m_Inventories) { const auto& items = pair.second->GetItems(); - for (const auto& candidate : items) - { + for (const auto& candidate : items) { auto* item = candidate.second; const auto parent = item->GetParent(); - if (parent == LWOOBJID_EMPTY) - { + if (parent == LWOOBJID_EMPTY) { continue; } - if (IsValidProxy(parent)) - { + if (IsValidProxy(parent)) { continue; } @@ -1670,8 +1452,7 @@ void InventoryComponent::CheckProxyIntegrity() } } - for (auto* item : dead) - { + for (auto* item : dead) { item->RemoveFromInventory(); } @@ -1714,16 +1495,13 @@ void InventoryComponent::CheckProxyIntegrity() */ } -void InventoryComponent::PurgeProxies(Item* item) -{ +void InventoryComponent::PurgeProxies(Item* item) { const auto root = item->GetParent(); - if (root != LWOOBJID_EMPTY) - { + if (root != LWOOBJID_EMPTY) { item = FindItemById(root); - if (item != nullptr) - { + if (item != nullptr) { UnEquipItem(item); } @@ -1732,20 +1510,17 @@ void InventoryComponent::PurgeProxies(Item* item) auto proxies = FindProxies(item->GetId()); - for (auto* proxy : proxies) - { + for (auto* proxy : proxies) { proxy->UnEquip(); proxy->RemoveFromInventory(); } } -void InventoryComponent::LoadPetXml(tinyxml2::XMLDocument* document) -{ +void InventoryComponent::LoadPetXml(tinyxml2::XMLDocument* document) { auto* petInventoryElement = document->FirstChildElement("obj")->FirstChildElement("pet"); - if (petInventoryElement == nullptr) - { + if (petInventoryElement == nullptr) { m_Pets.clear(); return; @@ -1753,8 +1528,7 @@ void InventoryComponent::LoadPetXml(tinyxml2::XMLDocument* document) auto* petElement = petInventoryElement->FirstChildElement(); - while (petElement != nullptr) - { + while (petElement != nullptr) { LWOOBJID id; LOT lot; int32_t moderationStatus; @@ -1775,12 +1549,10 @@ void InventoryComponent::LoadPetXml(tinyxml2::XMLDocument* document) } } -void InventoryComponent::UpdatePetXml(tinyxml2::XMLDocument* document) -{ +void InventoryComponent::UpdatePetXml(tinyxml2::XMLDocument* document) { auto* petInventoryElement = document->FirstChildElement("obj")->FirstChildElement("pet"); - if (petInventoryElement == nullptr) - { + if (petInventoryElement == nullptr) { petInventoryElement = document->NewElement("pet"); document->FirstChildElement("obj")->LinkEndChild(petInventoryElement); @@ -1788,8 +1560,7 @@ void InventoryComponent::UpdatePetXml(tinyxml2::XMLDocument* document) petInventoryElement->DeleteChildren(); - for (const auto& pet : m_Pets) - { + for (const auto& pet : m_Pets) { auto* petElement = document->NewElement("p"); petElement->SetAttribute("id", pet.first); diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index a7d3f8ea..01b4ca86 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -38,66 +38,66 @@ public: static const uint32_t ComponentType = COMPONENT_TYPE_INVENTORY; explicit InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document = nullptr); - void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void LoadXml(tinyxml2::XMLDocument* document); - void UpdateXml(tinyxml2::XMLDocument* document) override; - void ResetFlags(); + void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void LoadXml(tinyxml2::XMLDocument* document); + void UpdateXml(tinyxml2::XMLDocument* document) override; + void ResetFlags(); - /** - * Returns an inventory of the specified type, if it exists - * @param type the inventory type to find an inventory for - * @return the inventory of the specified type - */ + /** + * Returns an inventory of the specified type, if it exists + * @param type the inventory type to find an inventory for + * @return the inventory of the specified type + */ Inventory* GetInventory(eInventoryType type); - /** - * Returns all the inventories this entity has, indexed by type - * @return all the inventories this entity has, indexed by type - */ + /** + * Returns all the inventories this entity has, indexed by type + * @return all the inventories this entity has, indexed by type + */ const std::map& GetInventories() const; - /** - * Returns the amount of items this entity possesses of a certain LOT - * @param lot the lot to search for - * @return the amount of items this entity possesses the specified LOT - */ + /** + * Returns the amount of items this entity possesses of a certain LOT + * @param lot the lot to search for + * @return the amount of items this entity possesses the specified LOT + */ uint32_t GetLotCount(LOT lot) const; - /** - * Returns the amount of items this entity possesses of a LOT, given that they're not in a temporary inventory - * (vendor buyback, vault, etc). - * @param lot the lot to search for - * @return the amount of items this entity possesses of the specified lot - */ + /** + * Returns the amount of items this entity possesses of a LOT, given that they're not in a temporary inventory + * (vendor buyback, vault, etc). + * @param lot the lot to search for + * @return the amount of items this entity possesses of the specified lot + */ uint32_t GetLotCountNonTransfer(LOT lot) const; - /** - * Returns the items that are currently equipped by this entity - * @return the items that are currently equipped by this entity - */ + /** + * Returns the items that are currently equipped by this entity + * @return the items that are currently equipped by this entity + */ const EquipmentMap& GetEquippedItems() const; - /** - * Adds an item to the inventory of the entity - * @param lot the lot to add - * @param count the amount of items to add - * @param inventoryType the inventory to add the item to - * @param config optional config for this item, used for example for rockets - * @param parent optional parent of this item, used for proxy items - * @param showFlyingLoot show a client animation if the item is added - * @param isModMoveAndEquip equips the item - * @param subKey optional sub ID of a related object, used by pets - * @param inventorySourceType if the inventory was moved, the source inventory - * @param sourceType the source of the item, used to determine if the item is dropped or mailed if the inventory is full - * @param bound whether this item is bound - * @param preferredSlot the preferred slot to store this item - * @param lootSourceType The source of the loot. Defaults to none. - */ + /** + * Adds an item to the inventory of the entity + * @param lot the lot to add + * @param count the amount of items to add + * @param inventoryType the inventory to add the item to + * @param config optional config for this item, used for example for rockets + * @param parent optional parent of this item, used for proxy items + * @param showFlyingLoot show a client animation if the item is added + * @param isModMoveAndEquip equips the item + * @param subKey optional sub ID of a related object, used by pets + * @param inventorySourceType if the inventory was moved, the source inventory + * @param sourceType the source of the item, used to determine if the item is dropped or mailed if the inventory is full + * @param bound whether this item is bound + * @param preferredSlot the preferred slot to store this item + * @param lootSourceType The source of the loot. Defaults to none. + */ void AddItem( LOT lot, uint32_t count, - eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE, + eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE, eInventoryType inventoryType = INVALID, const std::vector& config = {}, LWOOBJID parent = LWOOBJID_EMPTY, @@ -110,65 +110,65 @@ public: int32_t preferredSlot = -1 ); - /** - * Removes a LOT from the inventory - * @param lot the lot to remove - * @param count the number of items to remove - * @param inventoryType optional inventory type to remove the item from - * @param ignoreBound ignores bound items - */ + /** + * Removes a LOT from the inventory + * @param lot the lot to remove + * @param count the number of items to remove + * @param inventoryType optional inventory type to remove the item from + * @param ignoreBound ignores bound items + */ void RemoveItem(LOT lot, uint32_t count, eInventoryType inventoryType = INVALID, bool ignoreBound = false); - /** - * Moves an existing item to an inventory of the entity - * @param item the item to add - * @param inventory the inventory to add the item to - * @param count the number of items to add - * @param showFlyingLot displays UI animation to the user - * @param isModMoveAndEquip equips the item - * @param ignoreEquipped does not stack on equipped items - * @param preferredSlot the preferred slot to store the item in - */ + /** + * Moves an existing item to an inventory of the entity + * @param item the item to add + * @param inventory the inventory to add the item to + * @param count the number of items to add + * @param showFlyingLot displays UI animation to the user + * @param isModMoveAndEquip equips the item + * @param ignoreEquipped does not stack on equipped items + * @param preferredSlot the preferred slot to store the item in + */ void MoveItemToInventory(Item* item, eInventoryType inventory, uint32_t count, bool showFlyingLot = true, bool isModMoveAndEquip = false, bool ignoreEquipped = false, int32_t preferredSlot = -1); - /** - * Moves a stack of items to an inventory - * @param item the item to move - * @param inventory the inventory to move the item to - * @param slot the slot in the inventory to move the item to - */ + /** + * Moves a stack of items to an inventory + * @param item the item to move + * @param inventory the inventory to move the item to + * @param slot the slot in the inventory to move the item to + */ void MoveStack(Item* item, eInventoryType inventory, uint32_t slot = 0); - /** - * Returns an item in the inventory by object ID - * @param id the id of the item to find - * @return item in the inventory by object ID - */ + /** + * Returns an item in the inventory by object ID + * @param id the id of the item to find + * @return item in the inventory by object ID + */ Item* FindItemById(LWOOBJID id) const; - /** - * Returns an item in the inventory that matches the specified LOT - * @param lot the lot of the item to find - * @param inventoryType optional inventory to search in - * @param ignoreEquipped ignores items that are equipped - * @param ignoreBound ignores items that are bound - * @return item in the inventory that matches the specified LOT - */ + /** + * Returns an item in the inventory that matches the specified LOT + * @param lot the lot of the item to find + * @param inventoryType optional inventory to search in + * @param ignoreEquipped ignores items that are equipped + * @param ignoreBound ignores items that are bound + * @return item in the inventory that matches the specified LOT + */ Item* FindItemByLot(LOT lot, eInventoryType inventoryType = INVALID, bool ignoreEquipped = false, bool ignoreBound = false); - /** - * Finds an item in the inventory that has the specified subkey, useful for pets - * @param id the subkey to look for - * @param inventoryType optional inventory type to search in - * @return item in the inventory that has the specified subkey - */ + /** + * Finds an item in the inventory that has the specified subkey, useful for pets + * @param id the subkey to look for + * @param inventoryType optional inventory type to search in + * @return item in the inventory that has the specified subkey + */ Item* FindItemBySubKey(LWOOBJID id, eInventoryType inventoryType = INVALID); - /** - * Checks if the entity has enough space for a batch of loot - * @param loot a map of items to add and how many to add - * @return whether the entity has enough space for all the items - */ + /** + * Checks if the entity has enough space for a batch of loot + * @param loot a map of items to add and how many to add + * @return whether the entity has enough space for all the items + */ bool HasSpaceForLoot(const std::unordered_map& loot); /** @@ -179,84 +179,84 @@ public: */ void UpdateSlot(const std::string& location, EquippedItem item, bool keepCurrent = false); - /** - * Removes a slot from the inventory - * @param location the slot to remove - */ + /** + * Removes a slot from the inventory + * @param location the slot to remove + */ void RemoveSlot(const std::string& location); - /** - * Equips the given item, guesses the slot to equip it in - * @param item the item to equip - * @param skipChecks skips checks for equipping cars and rockets (e.g. no special behavior follows) - */ + /** + * Equips the given item, guesses the slot to equip it in + * @param item the item to equip + * @param skipChecks skips checks for equipping cars and rockets (e.g. no special behavior follows) + */ void EquipItem(Item* item, bool skipChecks = false); - /** - * Unequips an item from the inventory - * @param item the item to unequip - */ + /** + * Unequips an item from the inventory + * @param item the item to unequip + */ void UnEquipItem(Item* item); - /** - * Adds a buff related to equipping a lot to the entity - * @param item the item to find buffs for - */ + /** + * Adds a buff related to equipping a lot to the entity + * @param item the item to find buffs for + */ void ApplyBuff(Item* item) const; - /** - * Removes buffs related to equipping a lot from the entity - * @param item the item to find buffs for - */ + /** + * Removes buffs related to equipping a lot from the entity + * @param item the item to find buffs for + */ void RemoveBuff(Item* item) const; - /** - * Saves the equipped items into a temp state - */ + /** + * Saves the equipped items into a temp state + */ void PushEquippedItems(); - /** - * Unequips all the temporary items and equips the previous item state - */ + /** + * Unequips all the temporary items and equips the previous item state + */ void PopEquippedItems(); - /** - * Returns if the entity has an item equipped of the given lot - * @param lot to lot to search for - * @return if the entity has an item equipped of the given lot - */ + /** + * Returns if the entity has an item equipped of the given lot + * @param lot to lot to search for + * @return if the entity has an item equipped of the given lot + */ bool IsEquipped(LOT lot) const; - /** - * Checks and ensures that we have loaded the item set that might be related to this item - * @param lot the lot to check the item set for - */ + /** + * Checks and ensures that we have loaded the item set that might be related to this item + * @param lot the lot to check the item set for + */ void CheckItemSet(LOT lot); - /** - * Sets the current consumable lot - * @param lot the lot to set as consumable - */ + /** + * Sets the current consumable lot + * @param lot the lot to set as consumable + */ void SetConsumable(LOT lot); - /** - * Returns the current consumable lot - * @return the current consumable lot - */ + /** + * Returns the current consumable lot + * @return the current consumable lot + */ LOT GetConsumable() const; - /** - * Finds all the buffs related to a lot - * @param item the item to get the buffs for - * @param castOnEquip if true, the skill missions for these buffs will be progressed - * @return the buffs related to the specified lot - */ + /** + * Finds all the buffs related to a lot + * @param item the item to get the buffs for + * @param castOnEquip if true, the skill missions for these buffs will be progressed + * @return the buffs related to the specified lot + */ std::vector FindBuffs(Item* item, bool castOnEquip) const; - /** - * Initializes the equipped items with a list of items - * @param items the items to equip - */ + /** + * Initializes the equipped items with a list of items + * @param items the items to equip + */ void SetNPCItems(const std::vector& items); /** @@ -265,189 +265,189 @@ public: */ void AddItemSkills(LOT lot); - /** - * Removes the skills related to the passed LOT from the currently equipped skills - * @param lot the lot to remove - */ + /** + * Removes the skills related to the passed LOT from the currently equipped skills + * @param lot the lot to remove + */ void RemoveItemSkills(LOT lot); - /** - * Triggers one of the passive abilities from the equipped item set - * @param trigger the trigger to fire - */ + /** + * Triggers one of the passive abilities from the equipped item set + * @param trigger the trigger to fire + */ void TriggerPassiveAbility(PassiveAbilityTrigger trigger); - /** - * Returns if the entity has any of the passed passive abilities equipped - * @param passiveIDs the IDs to check for - * @param equipmentRequirement the number of equipment required to be allowed to have the ability - * @return if the entity has any of the passed passive abilities equipped - */ + /** + * Returns if the entity has any of the passed passive abilities equipped + * @param passiveIDs the IDs to check for + * @param equipmentRequirement the number of equipment required to be allowed to have the ability + * @return if the entity has any of the passed passive abilities equipped + */ bool HasAnyPassive(const std::vector& passiveIDs, int32_t equipmentRequirement) const; - /** - * Despawns the currently active pet, if any - */ + /** + * Despawns the currently active pet, if any + */ void DespawnPet(); - /** - * Spawns the item as a pet (if it is one) - * @param item the pet to spawn - */ + /** + * Spawns the item as a pet (if it is one) + * @param item the pet to spawn + */ void SpawnPet(Item* item); - /** - * Updates the database pet data for an item (e.g. moderation status) - * @param id the id of the pet to find - * @param data the data to store on the pet - */ + /** + * Updates the database pet data for an item (e.g. moderation status) + * @param id the id of the pet to find + * @param data the data to store on the pet + */ void SetDatabasePet(LWOOBJID id, const DatabasePet& data); - /** - * Returns the database pet information for an object - * @param id the object ID to search for - * @return the database pet information for the object that belongs to the passed id - */ + /** + * Returns the database pet information for an object + * @param id the object ID to search for + * @return the database pet information for the object that belongs to the passed id + */ const DatabasePet& GetDatabasePet(LWOOBJID id) const; - /** - * Checks if the provided object ID is in this inventory and is a pet - * @param id the id of the object to check for - * @return if the provided object ID is in this inventory and is a pet - */ + /** + * Checks if the provided object ID is in this inventory and is a pet + * @param id the id of the object to check for + * @return if the provided object ID is in this inventory and is a pet + */ bool IsPet(LWOOBJID id) const; - /** - * Removes pet database information from the item with the specified object id - * @param id the object id to remove pet info for - */ + /** + * Removes pet database information from the item with the specified object id + * @param id the object id to remove pet info for + */ void RemoveDatabasePet(LWOOBJID id); - /** - * Returns the current behavior slot active for the passed item type - * @param type the item type to find the behavior slot for - * @return the current behavior slot active for the passed item type - */ + /** + * Returns the current behavior slot active for the passed item type + * @param type the item type to find the behavior slot for + * @return the current behavior slot active for the passed item type + */ static BehaviorSlot FindBehaviorSlot(eItemType type); - /** - * Checks if the inventory type is a temp inventory - * @param type the inventory type to check - * @return if the inventory type is a temp inventory - */ + /** + * Checks if the inventory type is a temp inventory + * @param type the inventory type to check + * @return if the inventory type is a temp inventory + */ static bool IsTransferInventory(eInventoryType type); - /** - * Finds the skill related to the passed LOT from the ObjectSkills table - * @param lot the lot to find - * @return the skill related to the passed LOT - */ + /** + * Finds the skill related to the passed LOT from the ObjectSkills table + * @param lot the lot to find + * @return the skill related to the passed LOT + */ static uint32_t FindSkill(LOT lot); - + ~InventoryComponent() override; - + private: - /** - * All the inventory this entity possesses - */ + /** + * All the inventory this entity possesses + */ std::map m_Inventories; - /** - * The skills that this entity currently has active - */ + /** + * The skills that this entity currently has active + */ std::map m_Skills; - /** - * The pets this entity has, mapped by object ID and pet info - */ + /** + * The pets this entity has, mapped by object ID and pet info + */ std::unordered_map m_Pets; - /** - * Cache of item sets this entity has encountered - */ + /** + * Cache of item sets this entity has encountered + */ std::vector m_Itemsets; - /** - * The LOTs we've checked all the item sets for (for cache reasons) - */ + /** + * The LOTs we've checked all the item sets for (for cache reasons) + */ std::vector m_ItemSetsChecked; - /** - * all the equipped items - */ + /** + * all the equipped items + */ EquipmentMap m_Equipped; - /** - * Clone of the equipped items before unequipping all of them - */ + /** + * Clone of the equipped items before unequipping all of them + */ EquipmentMap m_Pushed; - /** - * If the inventory has changed - */ + /** + * If the inventory has changed + */ bool m_Dirty; - /** - * The currently active consumable - */ + /** + * The currently active consumable + */ LOT m_Consumable; - /** - * Currently has a car equipped - */ - bool hasCarEquipped = false; - Entity* equippedCarEntity = nullptr; - LWOOBJID previousPossessableID = LWOOBJID_EMPTY; - LWOOBJID previousPossessorID = LWOOBJID_EMPTY; - /** - * Creates all the proxy items (subitems) for a parent item - * @param parent the parent item to generate all the subitems for - * @return the proxy items (subitems) for a parent item - */ + /** + * Currently has a car equipped + */ + bool hasCarEquipped = false; + Entity* equippedCarEntity = nullptr; + LWOOBJID previousPossessableID = LWOOBJID_EMPTY; + LWOOBJID previousPossessorID = LWOOBJID_EMPTY; + /** + * Creates all the proxy items (subitems) for a parent item + * @param parent the parent item to generate all the subitems for + * @return the proxy items (subitems) for a parent item + */ std::vector GenerateProxies(Item* parent); - /** - * Finds all the proxy items in this inventory for a given parent item - * @param parent the parent to find proxy items for - * @return the proxy items for the parent - */ + /** + * Finds all the proxy items in this inventory for a given parent item + * @param parent the parent to find proxy items for + * @return the proxy items for the parent + */ std::vector FindProxies(LWOOBJID parent); - /** - * Returns true if the provided LWOOBJID is the parent of this Item. - * @param parent the parent item to check for proxies - * @return if the provided ID is a valid proxy item - */ + /** + * Returns true if the provided LWOOBJID is the parent of this Item. + * @param parent the parent item to check for proxies + * @return if the provided ID is a valid proxy item + */ bool IsValidProxy(LWOOBJID parent); - /** - * Returns if the provided ID is a valid proxy item (e.g. we have children for it) - * @param parent the parent item to check for - * @return if the provided ID is a valid proxy item - */ + /** + * Returns if the provided ID is a valid proxy item (e.g. we have children for it) + * @param parent the parent item to check for + * @return if the provided ID is a valid proxy item + */ bool IsParentValid(Item* root); - /** - * Removes all the proxy items that have a dangling parent - */ + /** + * Removes all the proxy items that have a dangling parent + */ void CheckProxyIntegrity(); - /** - * Removes all the proxy items for a given parent from the inventory - * @param item the item to remove proxy items for - */ + /** + * Removes all the proxy items for a given parent from the inventory + * @param item the item to remove proxy items for + */ void PurgeProxies(Item* item); - /** - * Saves all the pet information stored in inventory items to the database - * @param document the xml doc to save to - */ + /** + * Saves all the pet information stored in inventory items to the database + * @param document the xml doc to save to + */ void LoadPetXml(tinyxml2::XMLDocument* document); - /** - * Loads all the pet information from an xml doc into items - * @param document the xml doc to load from - */ + /** + * Loads all the pet information from an xml doc into items + * @param document the xml doc to load from + */ void UpdatePetXml(tinyxml2::XMLDocument* document); }; diff --git a/dGame/dComponents/LUPExhibitComponent.cpp b/dGame/dComponents/LUPExhibitComponent.cpp index 8c825a30..7b8c85ba 100644 --- a/dGame/dComponents/LUPExhibitComponent.cpp +++ b/dGame/dComponents/LUPExhibitComponent.cpp @@ -2,50 +2,43 @@ #include "EntityManager.h" -LUPExhibitComponent::LUPExhibitComponent(Entity* parent) : Component(parent) -{ - m_Exhibits = { 11121, 11295, 11423, 11979 }; +LUPExhibitComponent::LUPExhibitComponent(Entity* parent) : Component(parent) { + m_Exhibits = { 11121, 11295, 11423, 11979 }; - m_ExhibitIndex = 0; + m_ExhibitIndex = 0; - m_Exhibit = m_Exhibits[m_ExhibitIndex]; + m_Exhibit = m_Exhibits[m_ExhibitIndex]; } -LUPExhibitComponent::~LUPExhibitComponent() -{ - +LUPExhibitComponent::~LUPExhibitComponent() { + } -void LUPExhibitComponent::Update(float deltaTime) -{ - m_UpdateTimer += deltaTime; +void LUPExhibitComponent::Update(float deltaTime) { + m_UpdateTimer += deltaTime; - if (m_UpdateTimer > 20.0f) - { - NextExhibit(); + if (m_UpdateTimer > 20.0f) { + NextExhibit(); - m_UpdateTimer = 0.0f; - } + m_UpdateTimer = 0.0f; + } } -void LUPExhibitComponent::NextExhibit() -{ - m_ExhibitIndex++; +void LUPExhibitComponent::NextExhibit() { + m_ExhibitIndex++; - if (m_ExhibitIndex >= m_Exhibits.size()) - { - m_ExhibitIndex = 0; - } + if (m_ExhibitIndex >= m_Exhibits.size()) { + m_ExhibitIndex = 0; + } - m_Exhibit = m_Exhibits[m_ExhibitIndex]; + m_Exhibit = m_Exhibits[m_ExhibitIndex]; - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } -void LUPExhibitComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags) -{ - outBitStream->Write1(); // Dirty flag? - outBitStream->Write(m_Exhibit); +void LUPExhibitComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags) { + outBitStream->Write1(); // Dirty flag? + outBitStream->Write(m_Exhibit); } diff --git a/dGame/dComponents/LUPExhibitComponent.h b/dGame/dComponents/LUPExhibitComponent.h index b9ecf70a..2d128f6c 100644 --- a/dGame/dComponents/LUPExhibitComponent.h +++ b/dGame/dComponents/LUPExhibitComponent.h @@ -11,34 +11,34 @@ class LUPExhibitComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_EXHIBIT; - - LUPExhibitComponent(Entity* parent); - ~LUPExhibitComponent(); - void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags); - /** - * After the timer runs out, this changes the currently exhibited LOT to the next one - */ - void NextExhibit(); + LUPExhibitComponent(Entity* parent); + ~LUPExhibitComponent(); + void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags); + + /** + * After the timer runs out, this changes the currently exhibited LOT to the next one + */ + void NextExhibit(); private: - /** - * The LOT that's currently on exhibit - */ - LOT m_Exhibit; + /** + * The LOT that's currently on exhibit + */ + LOT m_Exhibit; - /** - * The time since we've last updated the exhibit - */ - float m_UpdateTimer; + /** + * The time since we've last updated the exhibit + */ + float m_UpdateTimer; - /** - * The list of possible exhibits to show - */ - std::vector m_Exhibits; + /** + * The list of possible exhibits to show + */ + std::vector m_Exhibits; - /** - * The current index in the exhibit list - */ - size_t m_ExhibitIndex; + /** + * The current index in the exhibit list + */ + size_t m_ExhibitIndex; }; diff --git a/dGame/dComponents/LevelProgressionComponent.cpp b/dGame/dComponents/LevelProgressionComponent.cpp index ff4f3f85..ee3cfc6b 100644 --- a/dGame/dComponents/LevelProgressionComponent.cpp +++ b/dGame/dComponents/LevelProgressionComponent.cpp @@ -19,7 +19,7 @@ void LevelProgressionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { } -void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc){ +void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { tinyxml2::XMLElement* level = doc->FirstChildElement("obj")->FirstChildElement("lvl"); if (!level) { Game::logger->Log("LevelProgressionComponent", "Failed to find lvl tag while loading XML!"); @@ -29,7 +29,7 @@ void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc){ } -void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags){ +void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { outBitStream->Write(bIsInitialUpdate || m_DirtyLevelInfo); if (bIsInitialUpdate || m_DirtyLevelInfo) outBitStream->Write(m_Level); m_DirtyLevelInfo = false; @@ -46,7 +46,7 @@ void LevelProgressionComponent::HandleLevelUp() { if (!inventoryComponent || !controllablePhysicsComponent) return; // Tell the client we beginning to send level rewards. - if(rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, rewardingItem); + if (rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, rewardingItem); for (auto* reward : rewards) { switch (reward->rewardType) { @@ -54,11 +54,11 @@ void LevelProgressionComponent::HandleLevelUp() { inventoryComponent->AddItem(reward->value, reward->count, eLootSourceType::LOOT_SOURCE_LEVEL_REWARD); break; case 4: - { - auto* items = inventoryComponent->GetInventory(eInventoryType::ITEMS); - items->SetSize(items->GetSize() + reward->value); - } - break; + { + auto* items = inventoryComponent->GetInventory(eInventoryType::ITEMS); + items->SetSize(items->GetSize() + reward->value); + } + break; case 9: controllablePhysicsComponent->SetSpeedMultiplier(static_cast(reward->value) / 500.0f); break; @@ -70,5 +70,5 @@ void LevelProgressionComponent::HandleLevelUp() { } } // Tell the client we have finished sending level rewards. - if(rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, !rewardingItem); + if (rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, !rewardingItem); } diff --git a/dGame/dComponents/MissionComponent.cpp b/dGame/dComponents/MissionComponent.cpp index 03cb65ea..ad77cf34 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -18,7 +18,7 @@ #include "Mail.h" #include "MissionPrerequisites.h" -// MARK: Mission Component + // MARK: Mission Component std::unordered_map> MissionComponent::m_AchievementCache = {}; @@ -28,588 +28,582 @@ MissionComponent::MissionComponent(Entity* parent) : Component(parent) { //! Destructor MissionComponent::~MissionComponent() { - for (const auto& mission : m_Missions) { - delete mission.second; - } + for (const auto& mission : m_Missions) { + delete mission.second; + } - this->m_Missions.clear(); + this->m_Missions.clear(); } Mission* MissionComponent::GetMission(const uint32_t missionId) const { - if (m_Missions.count(missionId) == 0) { - return nullptr; - } + if (m_Missions.count(missionId) == 0) { + return nullptr; + } - const auto& index = m_Missions.find(missionId); + const auto& index = m_Missions.find(missionId); - if (index == m_Missions.end()) { - return nullptr; - } + if (index == m_Missions.end()) { + return nullptr; + } - return index->second; + return index->second; } MissionState MissionComponent::GetMissionState(const uint32_t missionId) const { - auto* mission = GetMission(missionId); + auto* mission = GetMission(missionId); - if (mission == nullptr) { - return CanAccept(missionId) ? MissionState::MISSION_STATE_AVAILABLE : MissionState::MISSION_STATE_UNKNOWN; - } + if (mission == nullptr) { + return CanAccept(missionId) ? MissionState::MISSION_STATE_AVAILABLE : MissionState::MISSION_STATE_UNKNOWN; + } - return mission->GetMissionState(); + return mission->GetMissionState(); } const std::unordered_map& MissionComponent::GetMissions() const { - return m_Missions; + return m_Missions; } bool MissionComponent::CanAccept(const uint32_t missionId) const { - return MissionPrerequisites::CanAccept(missionId, m_Missions); + return MissionPrerequisites::CanAccept(missionId, m_Missions); } void MissionComponent::AcceptMission(const uint32_t missionId, const bool skipChecks) { - if (!skipChecks && !CanAccept(missionId)) { - return; - } + if (!skipChecks && !CanAccept(missionId)) { + return; + } - // If this is a daily mission, it may already be "accepted" - auto* mission = this->GetMission(missionId); + // If this is a daily mission, it may already be "accepted" + auto* mission = this->GetMission(missionId); - if (mission != nullptr) { - if (mission->GetClientInfo().repeatable) { - mission->Accept(); - } + if (mission != nullptr) { + if (mission->GetClientInfo().repeatable) { + mission->Accept(); + } - return; - } + return; + } - mission = new Mission(this, missionId); + mission = new Mission(this, missionId); - mission->Accept(); + mission->Accept(); - this->m_Missions.insert_or_assign(missionId, mission); + this->m_Missions.insert_or_assign(missionId, mission); - if (missionId == 1728) { - //Needs to send a mail + if (missionId == 1728) { + //Needs to send a mail - auto address = m_Parent->GetSystemAddress(); + auto address = m_Parent->GetSystemAddress(); - Mail::HandleNotificationRequest(address, m_Parent->GetObjectID()); - } + Mail::HandleNotificationRequest(address, m_Parent->GetObjectID()); + } } void MissionComponent::CompleteMission(const uint32_t missionId, const bool skipChecks, const bool yieldRewards) { - // Get the mission first - auto* mission = this->GetMission(missionId); + // Get the mission first + auto* mission = this->GetMission(missionId); - if (mission == nullptr) { - AcceptMission(missionId, skipChecks); + if (mission == nullptr) { + AcceptMission(missionId, skipChecks); - mission = this->GetMission(missionId); + mission = this->GetMission(missionId); - if (mission == nullptr) { - return; - } - } + if (mission == nullptr) { + return; + } + } - //If this mission is not repeatable, and already completed, we stop here. - if (mission->IsComplete() && !mission->IsRepeatable()) { - return; - } + //If this mission is not repeatable, and already completed, we stop here. + if (mission->IsComplete() && !mission->IsRepeatable()) { + return; + } - mission->Complete(yieldRewards); + mission->Complete(yieldRewards); } void MissionComponent::RemoveMission(uint32_t missionId) { - auto* mission = this->GetMission(missionId); + auto* mission = this->GetMission(missionId); - if (mission == nullptr) { - return; - } + if (mission == nullptr) { + return; + } - delete mission; + delete mission; - m_Missions.erase(missionId); + m_Missions.erase(missionId); } void MissionComponent::Progress(MissionTaskType type, int32_t value, LWOOBJID associate, const std::string& targets, int32_t count, bool ignoreAchievements) { - for (const auto& pair : m_Missions) { - auto* mission = pair.second; + for (const auto& pair : m_Missions) { + auto* mission = pair.second; - if (mission->IsAchievement() && ignoreAchievements) continue; + if (mission->IsAchievement() && ignoreAchievements) continue; - if (mission->IsComplete()) continue; + if (mission->IsComplete()) continue; - mission->Progress(type, value, associate, targets, count); - } + mission->Progress(type, value, associate, targets, count); + } - if (count > 0 && !ignoreAchievements) { - LookForAchievements(type, value, true, associate, targets, count); - } + if (count > 0 && !ignoreAchievements) { + LookForAchievements(type, value, true, associate, targets, count); + } } void MissionComponent::ForceProgress(const uint32_t missionId, const uint32_t taskId, const int32_t value, const bool acceptMission) { - auto* mission = GetMission(missionId); + auto* mission = GetMission(missionId); - if (mission == nullptr) { - if (!acceptMission) { - return; - } + if (mission == nullptr) { + if (!acceptMission) { + return; + } - AcceptMission(missionId); + AcceptMission(missionId); - mission = GetMission(missionId); + mission = GetMission(missionId); - if (mission == nullptr) { - return; - } - } + if (mission == nullptr) { + return; + } + } - for (auto* element : mission->GetTasks()) { - if (element->GetClientInfo().uid != taskId) continue; + for (auto* element : mission->GetTasks()) { + if (element->GetClientInfo().uid != taskId) continue; - element->AddProgress(value); - } + element->AddProgress(value); + } - if (!mission->IsComplete()) { - mission->CheckCompletion(); - } + if (!mission->IsComplete()) { + mission->CheckCompletion(); + } } void MissionComponent::ForceProgressTaskType(const uint32_t missionId, const uint32_t taskType, const int32_t value, const bool acceptMission) { - auto* mission = GetMission(missionId); + auto* mission = GetMission(missionId); - if (mission == nullptr) { - if (!acceptMission) { - return; - } + if (mission == nullptr) { + if (!acceptMission) { + return; + } - CDMissions missionInfo; + CDMissions missionInfo; - if (!GetMissionInfo(missionId, missionInfo)) { - return; - } + if (!GetMissionInfo(missionId, missionInfo)) { + return; + } - if (missionInfo.isMission) { - return; - } + if (missionInfo.isMission) { + return; + } - AcceptMission(missionId); + AcceptMission(missionId); - mission = GetMission(missionId); + mission = GetMission(missionId); - if (mission == nullptr) { - return; - } - } + if (mission == nullptr) { + return; + } + } - for (auto* element : mission->GetTasks()) { - if (element->GetType() != static_cast(taskType)) continue; + for (auto* element : mission->GetTasks()) { + if (element->GetType() != static_cast(taskType)) continue; - element->AddProgress(value); - } + element->AddProgress(value); + } - if (!mission->IsComplete()) { - mission->CheckCompletion(); - } + if (!mission->IsComplete()) { + mission->CheckCompletion(); + } } -void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission) -{ - auto* mission = GetMission(missionId); +void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission) { + auto* mission = GetMission(missionId); - if (mission == nullptr) { - if (!acceptMission) { - return; - } + if (mission == nullptr) { + if (!acceptMission) { + return; + } - CDMissions missionInfo; + CDMissions missionInfo; - if (!GetMissionInfo(missionId, missionInfo)) { - return; - } + if (!GetMissionInfo(missionId, missionInfo)) { + return; + } - if (missionInfo.isMission) { - return; - } + if (missionInfo.isMission) { + return; + } - AcceptMission(missionId); + AcceptMission(missionId); - mission = GetMission(missionId); + mission = GetMission(missionId); - if (mission == nullptr) { - return; - } - } + if (mission == nullptr) { + return; + } + } - for (auto* element : mission->GetTasks()) { - if (element->GetType() != static_cast(taskType) || !element->InAllTargets(value)) continue; + for (auto* element : mission->GetTasks()) { + if (element->GetType() != static_cast(taskType) || !element->InAllTargets(value)) continue; - element->AddProgress(1); - } + element->AddProgress(1); + } - if (!mission->IsComplete()) { - mission->CheckCompletion(); - } + if (!mission->IsComplete()) { + mission->CheckCompletion(); + } } bool MissionComponent::GetMissionInfo(uint32_t missionId, CDMissions& result) { - auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); + auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); - const auto missions = missionsTable->Query([=](const CDMissions& entry) { - return entry.id == static_cast(missionId); - }); + const auto missions = missionsTable->Query([=](const CDMissions& entry) { + return entry.id == static_cast(missionId); + }); - if (missions.empty()) { - return false; - } + if (missions.empty()) { + return false; + } - result = missions[0]; + result = missions[0]; - return true; + return true; } #define MISSION_NEW_METHOD bool MissionComponent::LookForAchievements(MissionTaskType type, int32_t value, bool progress, LWOOBJID associate, const std::string& targets, int32_t count) { #ifdef MISSION_NEW_METHOD - // Query for achievments, using the cache - const auto& result = QueryAchievements(type, value, targets); + // Query for achievments, using the cache + const auto& result = QueryAchievements(type, value, targets); - bool any = false; + bool any = false; - for (const uint32_t missionID : result) { - // Check if we already have this achievement - if (GetMission(missionID) != nullptr) { - continue; - } + for (const uint32_t missionID : result) { + // Check if we already have this achievement + if (GetMission(missionID) != nullptr) { + continue; + } - // Check if we can accept this achievement - if (!MissionPrerequisites::CanAccept(missionID, m_Missions)) { - continue; - } + // Check if we can accept this achievement + if (!MissionPrerequisites::CanAccept(missionID, m_Missions)) { + continue; + } - // Instantiate new mission and accept it - auto* instance = new Mission(this, missionID); + // Instantiate new mission and accept it + auto* instance = new Mission(this, missionID); - m_Missions.insert_or_assign(missionID, instance); + m_Missions.insert_or_assign(missionID, instance); - instance->Accept(); + instance->Accept(); - any = true; + any = true; - if (progress) { - // Progress mission to bring it up to speed - instance->Progress(type, value, associate, targets, count); - } - } + if (progress) { + // Progress mission to bring it up to speed + instance->Progress(type, value, associate, targets, count); + } + } - return any; + return any; #else - auto* missionTasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); - auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); + auto* missionTasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); + auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); - auto tasks = missionTasksTable->Query([=](const CDMissionTasks& entry) { - return entry.taskType == static_cast(type); - }); + auto tasks = missionTasksTable->Query([=](const CDMissionTasks& entry) { + return entry.taskType == static_cast(type); + }); - auto any = false; + auto any = false; - for (const auto& task : tasks) { - if (GetMission(task.id) != nullptr) { - continue; - } + for (const auto& task : tasks) { + if (GetMission(task.id) != nullptr) { + continue; + } - const auto missionEntries = missionsTable->Query([=](const CDMissions& entry) { - return entry.id == static_cast(task.id) && !entry.isMission; - }); + const auto missionEntries = missionsTable->Query([=](const CDMissions& entry) { + return entry.id == static_cast(task.id) && !entry.isMission; + }); - if (missionEntries.empty()) { - continue; - } + if (missionEntries.empty()) { + continue; + } - const auto mission = missionEntries[0]; + const auto mission = missionEntries[0]; - if (mission.isMission || !MissionPrerequisites::CanAccept(mission.id, m_Missions)) { - continue; - } + if (mission.isMission || !MissionPrerequisites::CanAccept(mission.id, m_Missions)) { + continue; + } - if (task.target != value && task.targetGroup != targets) { - auto stream = std::istringstream(task.targetGroup); - std::string token; + if (task.target != value && task.targetGroup != targets) { + auto stream = std::istringstream(task.targetGroup); + std::string token; - auto found = false; + auto found = false; - while (std::getline(stream, token, ',')) { - try { - const auto target = std::stoul(token); + while (std::getline(stream, token, ',')) { + try { + const auto target = std::stoul(token); - found = target == value; + found = target == value; - if (found) { - break; - } - } - catch (std::invalid_argument& exception) { - Game::logger->Log("MissionComponent", "Failed to parse target (%s): (%s)!", token.c_str(), exception.what()); - } - } + if (found) { + break; + } + } catch (std::invalid_argument& exception) { + Game::logger->Log("MissionComponent", "Failed to parse target (%s): (%s)!", token.c_str(), exception.what()); + } + } - if (!found) { - continue; - } - } + if (!found) { + continue; + } + } - auto* instance = new Mission(this, mission.id); + auto* instance = new Mission(this, mission.id); - m_Missions.insert_or_assign(mission.id, instance); + m_Missions.insert_or_assign(mission.id, instance); - instance->Accept(); + instance->Accept(); - any = true; + any = true; - if (progress) { - instance->Progress(type, value, associate, targets, count); - } - } + if (progress) { + instance->Progress(type, value, associate, targets, count); + } + } - return any; + return any; #endif } const std::vector& MissionComponent::QueryAchievements(MissionTaskType type, int32_t value, const std::string targets) { - // Create a hash which represent this query for achievements - size_t hash = 0; - GeneralUtils::hash_combine(hash, type); - GeneralUtils::hash_combine(hash, value); - GeneralUtils::hash_combine(hash, targets); + // Create a hash which represent this query for achievements + size_t hash = 0; + GeneralUtils::hash_combine(hash, type); + GeneralUtils::hash_combine(hash, value); + GeneralUtils::hash_combine(hash, targets); - const std::unordered_map>::iterator& iter = m_AchievementCache.find(hash); + const std::unordered_map>::iterator& iter = m_AchievementCache.find(hash); - // Check if this query is cached - if (iter != m_AchievementCache.end()) { - return iter->second; - } + // Check if this query is cached + if (iter != m_AchievementCache.end()) { + return iter->second; + } - // Find relevent tables - auto* missionTasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); - auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); + // Find relevent tables + auto* missionTasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); + auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); - std::vector result; + std::vector result; - // Loop through all mission tasks, might cache this task check later - for (const auto& task : missionTasksTable->GetEntries()) { - if (task.taskType != static_cast(type)) { - continue; - } + // Loop through all mission tasks, might cache this task check later + for (const auto& task : missionTasksTable->GetEntries()) { + if (task.taskType != static_cast(type)) { + continue; + } - // Seek the assosicated mission - auto foundMission = false; + // Seek the assosicated mission + auto foundMission = false; - const auto& mission = missionsTable->GetByMissionID(task.id, foundMission); + const auto& mission = missionsTable->GetByMissionID(task.id, foundMission); - if (!foundMission || mission.isMission) { - continue; - } + if (!foundMission || mission.isMission) { + continue; + } - // Compare the easy values - if (task.target == value || task.targetGroup == targets) { - result.push_back(mission.id); + // Compare the easy values + if (task.target == value || task.targetGroup == targets) { + result.push_back(mission.id); - continue; - } + continue; + } - // Compare the target group, array separated by ',' - auto stream = std::istringstream(task.targetGroup); - std::string token; + // Compare the target group, array separated by ',' + auto stream = std::istringstream(task.targetGroup); + std::string token; - while (std::getline(stream, token, ',')) { - try { - if (std::stoi(token) == value) { - result.push_back(mission.id); + while (std::getline(stream, token, ',')) { + try { + if (std::stoi(token) == value) { + result.push_back(mission.id); - continue; - } - } - catch (std::invalid_argument& exception) { - // Ignored - } - } - } + continue; + } + } catch (std::invalid_argument& exception) { + // Ignored + } + } + } - // Insert into cache - m_AchievementCache.insert_or_assign(hash, result); + // Insert into cache + m_AchievementCache.insert_or_assign(hash, result); - return m_AchievementCache.find(hash)->second; + return m_AchievementCache.find(hash)->second; } bool MissionComponent::RequiresItem(const LOT lot) { - auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT type FROM Objects WHERE id = ?;"); - query.bind(1, (int) lot); + auto query = CDClientDatabase::CreatePreppedStmt( + "SELECT type FROM Objects WHERE id = ?;"); + query.bind(1, (int)lot); - auto result = query.execQuery(); + auto result = query.execQuery(); - if (result.eof()) { - return false; - } + if (result.eof()) { + return false; + } - if (!result.fieldIsNull(0)) { - const auto type = std::string(result.getStringField(0)); + if (!result.fieldIsNull(0)) { + const auto type = std::string(result.getStringField(0)); - result.finalize(); + result.finalize(); - if (type == "Powerup") { - return true; - } - } + if (type == "Powerup") { + return true; + } + } - result.finalize(); + result.finalize(); - for (const auto& pair : m_Missions) { - auto* mission = pair.second; + for (const auto& pair : m_Missions) { + auto* mission = pair.second; - if (mission->IsComplete()) { - continue; - } + if (mission->IsComplete()) { + continue; + } - for (auto* task : mission->GetTasks()) { - if (task->IsComplete() || task->GetType() != MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { - continue; - } + for (auto* task : mission->GetTasks()) { + if (task->IsComplete() || task->GetType() != MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { + continue; + } - if (!task->InAllTargets(lot)) { - continue; - } + if (!task->InAllTargets(lot)) { + continue; + } - return true; - } - } + return true; + } + } - const auto required = LookForAchievements(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, false); + const auto required = LookForAchievements(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, false); - return required; + return required; } void MissionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { - if (doc == nullptr) return; + if (doc == nullptr) return; - auto* mis = doc->FirstChildElement("obj")->FirstChildElement("mis"); + auto* mis = doc->FirstChildElement("obj")->FirstChildElement("mis"); - if (mis == nullptr) return; + if (mis == nullptr) return; - auto* cur = mis->FirstChildElement("cur"); - auto* done = mis->FirstChildElement("done"); + auto* cur = mis->FirstChildElement("cur"); + auto* done = mis->FirstChildElement("done"); - auto* doneM = done->FirstChildElement(); + auto* doneM = done->FirstChildElement(); - while (doneM) { - int missionId; + while (doneM) { + int missionId; - doneM->QueryAttribute("id", &missionId); + doneM->QueryAttribute("id", &missionId); - auto* mission = new Mission(this, missionId); + auto* mission = new Mission(this, missionId); - mission->LoadFromXml(doneM); + mission->LoadFromXml(doneM); - doneM = doneM->NextSiblingElement(); + doneM = doneM->NextSiblingElement(); - m_Missions.insert_or_assign(missionId, mission); - } + m_Missions.insert_or_assign(missionId, mission); + } - auto* currentM = cur->FirstChildElement(); + auto* currentM = cur->FirstChildElement(); - while (currentM) { - int missionId; + while (currentM) { + int missionId; - currentM->QueryAttribute("id", &missionId); + currentM->QueryAttribute("id", &missionId); - auto* mission = new Mission(this, missionId); + auto* mission = new Mission(this, missionId); - mission->LoadFromXml(currentM); + mission->LoadFromXml(currentM); - currentM = currentM->NextSiblingElement(); + currentM = currentM->NextSiblingElement(); - m_Missions.insert_or_assign(missionId, mission); - } + m_Missions.insert_or_assign(missionId, mission); + } } void MissionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { - if (doc == nullptr) return; + if (doc == nullptr) return; - auto shouldInsertMis = false; + auto shouldInsertMis = false; - auto* obj = doc->FirstChildElement("obj"); + auto* obj = doc->FirstChildElement("obj"); - auto* mis = obj->FirstChildElement("mis"); + auto* mis = obj->FirstChildElement("mis"); - if (mis == nullptr) { - mis = doc->NewElement("mis"); + if (mis == nullptr) { + mis = doc->NewElement("mis"); - shouldInsertMis = true; - } + shouldInsertMis = true; + } - mis->DeleteChildren(); + mis->DeleteChildren(); - auto* done = doc->NewElement("done"); - auto* cur = doc->NewElement("cur"); + auto* done = doc->NewElement("done"); + auto* cur = doc->NewElement("cur"); - for (const auto& pair : m_Missions) { - auto* mission = pair.second; + for (const auto& pair : m_Missions) { + auto* mission = pair.second; - if (mission) { - const auto complete = mission->IsComplete(); + if (mission) { + const auto complete = mission->IsComplete(); - if (complete) { - auto* m = doc->NewElement("m"); + if (complete) { + auto* m = doc->NewElement("m"); - mission->UpdateXml(m); + mission->UpdateXml(m); - done->LinkEndChild(m); + done->LinkEndChild(m); - continue; - } + continue; + } - auto* m = doc->NewElement("m"); + auto* m = doc->NewElement("m"); - mission->UpdateXml(m); + mission->UpdateXml(m); - cur->LinkEndChild(m); - } - } + cur->LinkEndChild(m); + } + } - mis->InsertFirstChild(done); - mis->InsertEndChild(cur); + mis->InsertFirstChild(done); + mis->InsertEndChild(cur); - if (shouldInsertMis) { - obj->LinkEndChild(mis); - } + if (shouldInsertMis) { + obj->LinkEndChild(mis); + } } -void MissionComponent::AddCollectible(int32_t collectibleID) -{ - // Check if this collectible is already in the list - if (HasCollectible(collectibleID)) { - return; - } +void MissionComponent::AddCollectible(int32_t collectibleID) { + // Check if this collectible is already in the list + if (HasCollectible(collectibleID)) { + return; + } - m_Collectibles.push_back(collectibleID); + m_Collectibles.push_back(collectibleID); } -bool MissionComponent::HasCollectible(int32_t collectibleID) -{ - return std::find(m_Collectibles.begin(), m_Collectibles.end(), collectibleID) != m_Collectibles.end(); +bool MissionComponent::HasCollectible(int32_t collectibleID) { + return std::find(m_Collectibles.begin(), m_Collectibles.end(), collectibleID) != m_Collectibles.end(); } -bool MissionComponent::HasMission(uint32_t missionId) -{ - return GetMission(missionId) != nullptr; -} \ No newline at end of file +bool MissionComponent::HasMission(uint32_t missionId) { + return GetMission(missionId) != nullptr; +} diff --git a/dGame/dComponents/MissionComponent.h b/dGame/dComponents/MissionComponent.h index 13a812d2..b4e53001 100644 --- a/dGame/dComponents/MissionComponent.h +++ b/dGame/dComponents/MissionComponent.h @@ -17,182 +17,182 @@ #include "CDMissionsTable.h" #include "Component.h" -/** - * The mission inventory of an entity. Tracks mission state for each mission that can be accepted and allows for - * progression of each of the mission task types (see MissionTaskType). - */ + /** + * The mission inventory of an entity. Tracks mission state for each mission that can be accepted and allows for + * progression of each of the mission task types (see MissionTaskType). + */ class MissionComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MISSION; + static const uint32_t ComponentType = COMPONENT_TYPE_MISSION; explicit MissionComponent(Entity* parent); - ~MissionComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void LoadFromXml(tinyxml2::XMLDocument* doc) override; - void UpdateXml(tinyxml2::XMLDocument* doc) override; + ~MissionComponent() override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void LoadFromXml(tinyxml2::XMLDocument* doc) override; + void UpdateXml(tinyxml2::XMLDocument* doc) override; - /** - * Returns all the missions for this entity, mapped by mission ID - * @return the missions for this entity, mapped by mission ID - */ - const std::unordered_map& GetMissions() const; + /** + * Returns all the missions for this entity, mapped by mission ID + * @return the missions for this entity, mapped by mission ID + */ + const std::unordered_map& GetMissions() const; - /** - * Returns the mission for the given mission ID, if it exists - * @param missionId the id of the mission to get - * @return the mission for the given mission ID - */ - Mission* GetMission(uint32_t missionId) const; + /** + * Returns the mission for the given mission ID, if it exists + * @param missionId the id of the mission to get + * @return the mission for the given mission ID + */ + Mission* GetMission(uint32_t missionId) const; - /** - * Returns the current state of the entities progression for the mission of the specified ID - * @param missionId the ID of the mission to get the mission state for - * @return the mission state of the mission specified by the ID - */ - MissionState GetMissionState(uint32_t missionId) const; + /** + * Returns the current state of the entities progression for the mission of the specified ID + * @param missionId the ID of the mission to get the mission state for + * @return the mission state of the mission specified by the ID + */ + MissionState GetMissionState(uint32_t missionId) const; - /** - * Checks if the entity has all the requirements for accepting the mission specified by the ID. - * @param missionId the mission ID to check for if the character may accept it - * @return whether this entity can accept the mission represented by the given mission ID - */ - bool CanAccept(uint32_t missionId) const; + /** + * Checks if the entity has all the requirements for accepting the mission specified by the ID. + * @param missionId the mission ID to check for if the character may accept it + * @return whether this entity can accept the mission represented by the given mission ID + */ + bool CanAccept(uint32_t missionId) const; - /** - * Accepts the mission specified by the ID, if the entity may accept it. Also stores it in the mission inventory. - * @param missionId the ID of the mission to accept - * @param skipChecks skips the checks for the mission prerequisites - */ - void AcceptMission(uint32_t missionId, bool skipChecks = false); + /** + * Accepts the mission specified by the ID, if the entity may accept it. Also stores it in the mission inventory. + * @param missionId the ID of the mission to accept + * @param skipChecks skips the checks for the mission prerequisites + */ + void AcceptMission(uint32_t missionId, bool skipChecks = false); - /** - * Completes the mission specified by the given ID, if the entity has fulfilled all progress requirements. - * @param missionId the ID of the mission to complete - * @param skipChecks skips the checks for having completed all of the mission tasks - * @param yieldRewards whether to yield mission rewards, currently unused - */ - void CompleteMission(uint32_t missionId, bool skipChecks = false, bool yieldRewards = true); + /** + * Completes the mission specified by the given ID, if the entity has fulfilled all progress requirements. + * @param missionId the ID of the mission to complete + * @param skipChecks skips the checks for having completed all of the mission tasks + * @param yieldRewards whether to yield mission rewards, currently unused + */ + void CompleteMission(uint32_t missionId, bool skipChecks = false, bool yieldRewards = true); - /** - * Removes the mission from the entities' mission chain. Not used for normal gameplay but useful for debugging. - * @param missionId the ID of the mission to remove - */ - void RemoveMission(uint32_t missionId); + /** + * Removes the mission from the entities' mission chain. Not used for normal gameplay but useful for debugging. + * @param missionId the ID of the mission to remove + */ + void RemoveMission(uint32_t missionId); - /** - * Attempts to progress mission tasks for a given type using parameters to progress. Note that this function is - * very abstract and different mission tasks require different combinations of parameters. This also progresses - * achievements, which are basically just missions with the isMission flag set to false. - * @param type the type of the mission task to try and progress with - * @param value the value to progress with, could be a LOT for item collection for example - * @param associate an associated entity for the progression, might be an activity host for example - * @param targets optionally multiple target values that could exist for the mission that we wish to progress - * @param count the number to progress by, for example the number of items - * @param ignoreAchievements do not progress achievements - */ - void Progress(MissionTaskType type, int32_t value, LWOOBJID associate = 0, const std::string& targets = "", int32_t count = 1, bool ignoreAchievements = false); + /** + * Attempts to progress mission tasks for a given type using parameters to progress. Note that this function is + * very abstract and different mission tasks require different combinations of parameters. This also progresses + * achievements, which are basically just missions with the isMission flag set to false. + * @param type the type of the mission task to try and progress with + * @param value the value to progress with, could be a LOT for item collection for example + * @param associate an associated entity for the progression, might be an activity host for example + * @param targets optionally multiple target values that could exist for the mission that we wish to progress + * @param count the number to progress by, for example the number of items + * @param ignoreAchievements do not progress achievements + */ + void Progress(MissionTaskType type, int32_t value, LWOOBJID associate = 0, const std::string& targets = "", int32_t count = 1, bool ignoreAchievements = false); - /** - * Forces progression for a mission and task, ignoring checks - * @param missionId the mission ID to try and progress - * @param taskId the task ID of the task belonging to the mission trying to progress - * @param value the value to progress with - * @param acceptMission accept the mission if it was not already accepted - */ - void ForceProgress(uint32_t missionId, uint32_t taskId, int32_t value, bool acceptMission = true); + /** + * Forces progression for a mission and task, ignoring checks + * @param missionId the mission ID to try and progress + * @param taskId the task ID of the task belonging to the mission trying to progress + * @param value the value to progress with + * @param acceptMission accept the mission if it was not already accepted + */ + void ForceProgress(uint32_t missionId, uint32_t taskId, int32_t value, bool acceptMission = true); - /** - * Forces progress for all tasks of a certain type that belong to the same mission - * @param missionId the mission to progress - * @param taskType the task tyoe to progress - * @param value the value to progress with - * @param acceptMission accept the mission if it wasn't already - */ - void ForceProgressTaskType(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission = true); + /** + * Forces progress for all tasks of a certain type that belong to the same mission + * @param missionId the mission to progress + * @param taskType the task tyoe to progress + * @param value the value to progress with + * @param acceptMission accept the mission if it wasn't already + */ + void ForceProgressTaskType(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission = true); - /** - * Force progresses by checking the value and progressing by 1 - * @param missionId the mission to progress - * @param taskType the task to progress for - * @param value the value to check the mission values before progressing - * @param acceptMission accept the mission if it wasn't already - */ - void ForceProgressValue(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission = true); + /** + * Force progresses by checking the value and progressing by 1 + * @param missionId the mission to progress + * @param taskType the task to progress for + * @param value the value to check the mission values before progressing + * @param acceptMission accept the mission if it wasn't already + */ + void ForceProgressValue(uint32_t missionId, uint32_t taskType, int32_t value, bool acceptMission = true); - /** - * Returns client database mission information for a mission - * @param missionId the ID of the mission to get the info for - * @param result the result to store the information in - * @return true if the information was succesfully retrieved, false otherwise - */ - bool GetMissionInfo(uint32_t missionId, CDMissions& result); + /** + * Returns client database mission information for a mission + * @param missionId the ID of the mission to get the info for + * @param result the result to store the information in + * @return true if the information was succesfully retrieved, false otherwise + */ + bool GetMissionInfo(uint32_t missionId, CDMissions& result); - /** - * Checks if there's any achievements we might be able to accept for the given parameters - * @param type the task type for tasks in the achievement that we wish to progress - * @param value the value to progress by - * @param progress if we can accept the mission, this will apply the progression - * @param associate optional associate related to mission progression - * @param targets optional multiple targets related to mission progression - * @param count the number of values to progress by (differs by task type) - * @return true if a achievement was accepted, false otherwise - */ + /** + * Checks if there's any achievements we might be able to accept for the given parameters + * @param type the task type for tasks in the achievement that we wish to progress + * @param value the value to progress by + * @param progress if we can accept the mission, this will apply the progression + * @param associate optional associate related to mission progression + * @param targets optional multiple targets related to mission progression + * @param count the number of values to progress by (differs by task type) + * @return true if a achievement was accepted, false otherwise + */ bool LookForAchievements(MissionTaskType type, int32_t value, bool progress = true, LWOOBJID associate = LWOOBJID_EMPTY, const std::string& targets = "", int32_t count = 1); - /** - * Checks if there's a mission active that requires the collection of the specified LOT - * @param lot the LOT to check for - * @return if there's a mission active that requires the collection of the specified LOT - */ - bool RequiresItem(LOT lot); + /** + * Checks if there's a mission active that requires the collection of the specified LOT + * @param lot the LOT to check for + * @return if there's a mission active that requires the collection of the specified LOT + */ + bool RequiresItem(LOT lot); - /** - * Collects a collectable for the entity, unrendering it for the entity - * @param collectibleID the ID of the collectable to add - */ - void AddCollectible(int32_t collectibleID); + /** + * Collects a collectable for the entity, unrendering it for the entity + * @param collectibleID the ID of the collectable to add + */ + void AddCollectible(int32_t collectibleID); - /** - * Checks if the entity already has a collectible of the specified ID - * @param collectibleID the ID of the collectible to check - * @return if the entity already has a collectible of the specified ID - */ - bool HasCollectible(int32_t collectibleID); + /** + * Checks if the entity already has a collectible of the specified ID + * @param collectibleID the ID of the collectible to check + * @return if the entity already has a collectible of the specified ID + */ + bool HasCollectible(int32_t collectibleID); + + /** + * Checks if the entity has a certain mission in its inventory + * @param missionId the ID of the mission to check + * @return if the entity has a certain mission in its inventory + */ + bool HasMission(uint32_t missionId); - /** - * Checks if the entity has a certain mission in its inventory - * @param missionId the ID of the mission to check - * @return if the entity has a certain mission in its inventory - */ - bool HasMission(uint32_t missionId); - private: - /** - * All the missions owned by this entity, mapped by mission ID - */ - std::unordered_map m_Missions; + /** + * All the missions owned by this entity, mapped by mission ID + */ + std::unordered_map m_Missions; - /** - * All the collectibles currently collected by the entity - */ - std::vector m_Collectibles; + /** + * All the collectibles currently collected by the entity + */ + std::vector m_Collectibles; - /** - * For the given parameters, finds the mission IDs of the achievements that may be unlcoked - * @param type the mission task type to try and progress - * @param value the value to try and progress with - * @param targets optional targets to progress with - * @return list of mission IDs (achievements) that can be progressed for the given parameters - */ - static const std::vector& QueryAchievements(MissionTaskType type, int32_t value, const std::string targets); + /** + * For the given parameters, finds the mission IDs of the achievements that may be unlcoked + * @param type the mission task type to try and progress + * @param value the value to try and progress with + * @param targets optional targets to progress with + * @return list of mission IDs (achievements) that can be progressed for the given parameters + */ + static const std::vector& QueryAchievements(MissionTaskType type, int32_t value, const std::string targets); - /** - * As achievements can be hard to query, we here store a list of all the mission IDs that can be unlocked for a - * combination of tasks and values, so that they can be easily re-queried later - */ - static std::unordered_map> m_AchievementCache; + /** + * As achievements can be hard to query, we here store a list of all the mission IDs that can be unlocked for a + * combination of tasks and values, so that they can be easily re-queried later + */ + static std::unordered_map> m_AchievementCache; }; #endif // MISSIONCOMPONENT_H diff --git a/dGame/dComponents/MissionOfferComponent.cpp b/dGame/dComponents/MissionOfferComponent.cpp index 6e44d2e3..2f2ed0f0 100644 --- a/dGame/dComponents/MissionOfferComponent.cpp +++ b/dGame/dComponents/MissionOfferComponent.cpp @@ -15,224 +15,193 @@ #include "Game.h" #include "MissionPrerequisites.h" -OfferedMission::OfferedMission(const uint32_t missionId, const bool offersMission, const bool acceptsMission) -{ - this->missionId = missionId; - this->offersMission = offersMission; - this->acceptsMission = acceptsMission; +OfferedMission::OfferedMission(const uint32_t missionId, const bool offersMission, const bool acceptsMission) { + this->missionId = missionId; + this->offersMission = offersMission; + this->acceptsMission = acceptsMission; } -uint32_t OfferedMission::GetMissionId() const -{ - return this->missionId; +uint32_t OfferedMission::GetMissionId() const { + return this->missionId; } -bool OfferedMission::GetOfferMission() const -{ - return this->offersMission; +bool OfferedMission::GetOfferMission() const { + return this->offersMission; } -bool OfferedMission::GetAcceptMission() const -{ - return this->acceptsMission; +bool OfferedMission::GetAcceptMission() const { + return this->acceptsMission; } //------------------------ MissionOfferComponent below ------------------------ MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot) : Component(parent) { - auto* compRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); + auto* compRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); - auto value = compRegistryTable->GetByIDAndType(parentLot, COMPONENT_TYPE_MISSION_OFFER, -1); + auto value = compRegistryTable->GetByIDAndType(parentLot, COMPONENT_TYPE_MISSION_OFFER, -1); - if (value != -1) { - const uint32_t componentId = value; + if (value != -1) { + const uint32_t componentId = value; - // Now lookup the missions in the MissionNPCComponent table - auto* missionNpcComponentTable = CDClientManager::Instance()->GetTable("MissionNPCComponent"); + // Now lookup the missions in the MissionNPCComponent table + auto* missionNpcComponentTable = CDClientManager::Instance()->GetTable("MissionNPCComponent"); - auto missions = missionNpcComponentTable->Query([=](const CDMissionNPCComponent& entry) - { - return entry.id == static_cast(componentId); - }); + auto missions = missionNpcComponentTable->Query([=](const CDMissionNPCComponent& entry) { + return entry.id == static_cast(componentId); + }); - for (auto& mission : missions) - { - auto* offeredMission = new OfferedMission(mission.missionID, mission.offersMission, mission.acceptsMission); - this->offeredMissions.push_back(offeredMission); - } - } + for (auto& mission : missions) { + auto* offeredMission = new OfferedMission(mission.missionID, mission.offersMission, mission.acceptsMission); + this->offeredMissions.push_back(offeredMission); + } + } } -MissionOfferComponent::~MissionOfferComponent() -{ - for (auto* mission : this->offeredMissions) { - if (mission) { - delete mission; - mission = nullptr; - } - } +MissionOfferComponent::~MissionOfferComponent() { + for (auto* mission : this->offeredMissions) { + if (mission) { + delete mission; + mission = nullptr; + } + } - offeredMissions.clear(); + offeredMissions.clear(); } -void MissionOfferComponent::OnUse(Entity* originator) -{ - OfferMissions(originator); +void MissionOfferComponent::OnUse(Entity* originator) { + OfferMissions(originator); } -void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifiedMissionId) -{ - // First, get the entity's MissionComponent. If there is not one, then we cannot offer missions to this entity. - auto* missionComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION)); +void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifiedMissionId) { + // First, get the entity's MissionComponent. If there is not one, then we cannot offer missions to this entity. + auto* missionComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION)); - if (!missionComponent) { - Game::logger->Log("MissionOfferComponent", "Unable to get mission component for Entity %llu", entity->GetObjectID()); - return; - } + if (!missionComponent) { + Game::logger->Log("MissionOfferComponent", "Unable to get mission component for Entity %llu", entity->GetObjectID()); + return; + } - std::vector offered {}; + std::vector offered{}; - CDMissions info {}; + CDMissions info{}; - if (specifiedMissionId > 0 && !Mission::IsValidMission(specifiedMissionId, info)) - { - return; - } + if (specifiedMissionId > 0 && !Mission::IsValidMission(specifiedMissionId, info)) { + return; + } - for (auto* offeredMission : this->offeredMissions) - { - if (specifiedMissionId > 0) - { - if (offeredMission->GetMissionId() != specifiedMissionId && !info.isRandom) - { - continue; - } - } + for (auto* offeredMission : this->offeredMissions) { + if (specifiedMissionId > 0) { + if (offeredMission->GetMissionId() != specifiedMissionId && !info.isRandom) { + continue; + } + } - // First, check if we already have the mission - const auto missionId = offeredMission->GetMissionId(); + // First, check if we already have the mission + const auto missionId = offeredMission->GetMissionId(); - auto* mission = missionComponent->GetMission(missionId); + auto* mission = missionComponent->GetMission(missionId); - if (mission != nullptr) - { - if (specifiedMissionId <= 0) - { - // Handles the odd case where the offer object should not display the mission again - if (!mission->IsComplete() && mission->GetClientInfo().offer_objectID == m_Parent->GetLOT() && mission->GetClientInfo().target_objectID != m_Parent->GetLOT() && mission->IsFetchMission()) - { - continue; - } - } + if (mission != nullptr) { + if (specifiedMissionId <= 0) { + // Handles the odd case where the offer object should not display the mission again + if (!mission->IsComplete() && mission->GetClientInfo().offer_objectID == m_Parent->GetLOT() && mission->GetClientInfo().target_objectID != m_Parent->GetLOT() && mission->IsFetchMission()) { + continue; + } + } - // We have the mission, if it is not complete, offer it - if (mission->IsActive() || mission->IsReadyToComplete()) - { - GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), missionId, m_Parent->GetObjectID()); + // We have the mission, if it is not complete, offer it + if (mission->IsActive() || mission->IsReadyToComplete()) { + GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), missionId, m_Parent->GetObjectID()); - offered.push_back(missionId); + offered.push_back(missionId); - continue; - } - } + continue; + } + } - const auto canAccept = MissionPrerequisites::CanAccept(missionId, missionComponent->GetMissions()); + const auto canAccept = MissionPrerequisites::CanAccept(missionId, missionComponent->GetMissions()); - // Mission has not yet been accepted - check the prereqs - if (!canAccept) - continue; + // Mission has not yet been accepted - check the prereqs + if (!canAccept) + continue; - if (!Mission::IsValidMission(missionId, info)) - { - continue; - } + if (!Mission::IsValidMission(missionId, info)) { + continue; + } - const auto& randomPool = info.randomPool; - const auto isRandom = info.isRandom; + const auto& randomPool = info.randomPool; + const auto isRandom = info.isRandom; - if (isRandom && randomPool.empty()) // This means the mission is part of a random pool of missions. - { - continue; - } + if (isRandom && randomPool.empty()) // This means the mission is part of a random pool of missions. + { + continue; + } - if (isRandom && !randomPool.empty()) - { - std::istringstream stream(randomPool); - std::string token; + if (isRandom && !randomPool.empty()) { + std::istringstream stream(randomPool); + std::string token; - std::vector randomMissionPool; + std::vector randomMissionPool; - while (std::getline(stream, token, ',')) - { - try - { - const auto value = std::stoul(token); + while (std::getline(stream, token, ',')) { + try { + const auto value = std::stoul(token); - randomMissionPool.push_back(value); - } - catch (std::invalid_argument& exception) - { - Game::logger->Log("MissionOfferComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); - } - } + randomMissionPool.push_back(value); + } catch (std::invalid_argument& exception) { + Game::logger->Log("MissionOfferComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); + } + } - if (specifiedMissionId > 0) - { - const auto& iter = std::find(randomMissionPool.begin(), randomMissionPool.end(), specifiedMissionId); + if (specifiedMissionId > 0) { + const auto& iter = std::find(randomMissionPool.begin(), randomMissionPool.end(), specifiedMissionId); - if (iter != randomMissionPool.end() && MissionPrerequisites::CanAccept(specifiedMissionId, missionComponent->GetMissions())) - { - GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), specifiedMissionId, m_Parent->GetObjectID()); + if (iter != randomMissionPool.end() && MissionPrerequisites::CanAccept(specifiedMissionId, missionComponent->GetMissions())) { + GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), specifiedMissionId, m_Parent->GetObjectID()); - return; - } - } + return; + } + } - std::vector canAcceptPool; + std::vector canAcceptPool; - for (const auto sample : randomMissionPool) - { - const auto state = missionComponent->GetMissionState(sample); + for (const auto sample : randomMissionPool) { + const auto state = missionComponent->GetMissionState(sample); - if (state == MissionState::MISSION_STATE_ACTIVE || - state == MissionState::MISSION_STATE_COMPLETE_ACTIVE || - state == MissionState::MISSION_STATE_READY_TO_COMPLETE || - state == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE || - sample == specifiedMissionId) - { - mission = missionComponent->GetMission(sample); + if (state == MissionState::MISSION_STATE_ACTIVE || + state == MissionState::MISSION_STATE_COMPLETE_ACTIVE || + state == MissionState::MISSION_STATE_READY_TO_COMPLETE || + state == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE || + sample == specifiedMissionId) { + mission = missionComponent->GetMission(sample); - if (mission == nullptr || mission->IsAchievement()) - { - continue; - } + if (mission == nullptr || mission->IsAchievement()) { + continue; + } - GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), sample, m_Parent->GetObjectID()); + GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), sample, m_Parent->GetObjectID()); - canAcceptPool.clear(); + canAcceptPool.clear(); - break; - } + break; + } - if (std::find(offered.begin(), offered.end(), sample) == offered.end() && MissionPrerequisites::CanAccept(sample, missionComponent->GetMissions())) - { - canAcceptPool.push_back(sample); - } - } + if (std::find(offered.begin(), offered.end(), sample) == offered.end() && MissionPrerequisites::CanAccept(sample, missionComponent->GetMissions())) { + canAcceptPool.push_back(sample); + } + } - // If the mission is already active or we already completed one of them today - if (canAcceptPool.empty()) - continue; + // If the mission is already active or we already completed one of them today + if (canAcceptPool.empty()) + continue; - const auto selected = canAcceptPool[GeneralUtils::GenerateRandomNumber(0, canAcceptPool.size() - 1)]; + const auto selected = canAcceptPool[GeneralUtils::GenerateRandomNumber(0, canAcceptPool.size() - 1)]; - GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), selected, m_Parent->GetObjectID()); - } - else if (std::find(offered.begin(), offered.end(), missionId) == offered.end() && offeredMission->GetOfferMission()) - { - GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), missionId, m_Parent->GetObjectID()); - } - } + GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), selected, m_Parent->GetObjectID()); + } else if (std::find(offered.begin(), offered.end(), missionId) == offered.end() && offeredMission->GetOfferMission()) { + GameMessages::SendOfferMission(entity->GetObjectID(), entity->GetSystemAddress(), missionId, m_Parent->GetObjectID()); + } + } } diff --git a/dGame/dComponents/MissionOfferComponent.h b/dGame/dComponents/MissionOfferComponent.h index 6719810e..42aad3c4 100644 --- a/dGame/dComponents/MissionOfferComponent.h +++ b/dGame/dComponents/MissionOfferComponent.h @@ -19,40 +19,40 @@ class Entity; struct OfferedMission { OfferedMission(uint32_t missionId, bool offersMission, bool acceptsMission); - /** - * Returns the ID of the mission - * @return the ID of the mission - */ - uint32_t GetMissionId() const; + /** + * Returns the ID of the mission + * @return the ID of the mission + */ + uint32_t GetMissionId() const; - /** - * Returns if this mission is offered by the entity - * @return true if this mission is offered by the entity, false otherwise - */ - bool GetOfferMission() const; + /** + * Returns if this mission is offered by the entity + * @return true if this mission is offered by the entity, false otherwise + */ + bool GetOfferMission() const; + + /** + * Returns if this mission may be accepted by the entity (currently unused) + * @return true if this mission may be accepted by the entity, false otherwise + */ + bool GetAcceptMission() const; - /** - * Returns if this mission may be accepted by the entity (currently unused) - * @return true if this mission may be accepted by the entity, false otherwise - */ - bool GetAcceptMission() const; - private: - /** - * The ID of the mission - */ - uint32_t missionId; + /** + * The ID of the mission + */ + uint32_t missionId; - /** - * Determines if the mission is offered by the entity - */ - bool offersMission; + /** + * Determines if the mission is offered by the entity + */ + bool offersMission; - /** - * Determines if the mission can be accepted by the entity - */ - bool acceptsMission; + /** + * Determines if the mission can be accepted by the entity + */ + bool acceptsMission; }; /** @@ -60,31 +60,31 @@ private: */ class MissionOfferComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MISSION_OFFER; - - MissionOfferComponent(Entity* parent, LOT parentLot); - ~MissionOfferComponent() override; + static const uint32_t ComponentType = COMPONENT_TYPE_MISSION_OFFER; - /** - * Handles the OnUse event triggered by some entity, determines which missions to show based on what they may - * hand in now and what they may start based on their mission history. - * @param originator the entity that triggered the event - */ - void OnUse(Entity* originator) override; + MissionOfferComponent(Entity* parent, LOT parentLot); + ~MissionOfferComponent() override; - /** - * Offers all the missions an entity can accept to said entity - * @param entity the entity to offer missions to - * @param specifiedMissionId optional mission ID if you wish to offer a specific mission - */ - void OfferMissions(Entity* entity, uint32_t specifiedMissionId = 0); + /** + * Handles the OnUse event triggered by some entity, determines which missions to show based on what they may + * hand in now and what they may start based on their mission history. + * @param originator the entity that triggered the event + */ + void OnUse(Entity* originator) override; + + /** + * Offers all the missions an entity can accept to said entity + * @param entity the entity to offer missions to + * @param specifiedMissionId optional mission ID if you wish to offer a specific mission + */ + void OfferMissions(Entity* entity, uint32_t specifiedMissionId = 0); private: - /** - * The missions this entity has to offer - */ - std::vector offeredMissions; + /** + * The missions this entity has to offer + */ + std::vector offeredMissions; }; #endif // MISSIONOFFERCOMPONENT_H diff --git a/dGame/dComponents/ModelComponent.cpp b/dGame/dComponents/ModelComponent.cpp index 65259912..8fa085f2 100644 --- a/dGame/dComponents/ModelComponent.cpp +++ b/dGame/dComponents/ModelComponent.cpp @@ -1,8 +1,7 @@ #include "ModelComponent.h" #include "Entity.h" -ModelComponent::ModelComponent(Entity* parent) : Component(parent) -{ +ModelComponent::ModelComponent(Entity* parent) : Component(parent) { m_OriginalPosition = m_Parent->GetDefaultPosition(); m_OriginalRotation = m_Parent->GetDefaultRotation(); @@ -16,17 +15,17 @@ void ModelComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialU outBitStream->Write(m_userModelID != LWOOBJID_EMPTY ? m_userModelID : m_Parent->GetObjectID()); outBitStream->Write(0); outBitStream->Write0(); - } - + } + //actual model component: outBitStream->Write1(); // Yes we are writing model info - outBitStream->Write0(); // Is pickable - outBitStream->Write(2); // Physics type - outBitStream->Write(m_OriginalPosition); // Original position - outBitStream->Write(m_OriginalRotation); // Original rotation + outBitStream->Write0(); // Is pickable + outBitStream->Write(2); // Physics type + outBitStream->Write(m_OriginalPosition); // Original position + outBitStream->Write(m_OriginalRotation); // Original rotation outBitStream->Write1(); // We are writing behavior info - outBitStream->Write(0); // Number of behaviors - outBitStream->Write1(); // Is this model paused + outBitStream->Write(0); // Number of behaviors + outBitStream->Write1(); // Is this model paused if (bIsInitialUpdate) outBitStream->Write0(); // We are not writing model editing info } diff --git a/dGame/dComponents/ModuleAssemblyComponent.cpp b/dGame/dComponents/ModuleAssemblyComponent.cpp index 0095b68f..8e197f0c 100644 --- a/dGame/dComponents/ModuleAssemblyComponent.cpp +++ b/dGame/dComponents/ModuleAssemblyComponent.cpp @@ -1,84 +1,70 @@ #include "ModuleAssemblyComponent.h" -ModuleAssemblyComponent::ModuleAssemblyComponent(Entity* parent) : Component(parent) -{ - m_SubKey = LWOOBJID_EMPTY; - m_UseOptionalParts = false; - m_AssemblyPartsLOTs = u""; +ModuleAssemblyComponent::ModuleAssemblyComponent(Entity* parent) : Component(parent) { + m_SubKey = LWOOBJID_EMPTY; + m_UseOptionalParts = false; + m_AssemblyPartsLOTs = u""; } -ModuleAssemblyComponent::~ModuleAssemblyComponent() -{ - +ModuleAssemblyComponent::~ModuleAssemblyComponent() { + } -void ModuleAssemblyComponent::SetSubKey(LWOOBJID value) -{ - m_SubKey = value; +void ModuleAssemblyComponent::SetSubKey(LWOOBJID value) { + m_SubKey = value; } -LWOOBJID ModuleAssemblyComponent::GetSubKey() const -{ - return m_SubKey; +LWOOBJID ModuleAssemblyComponent::GetSubKey() const { + return m_SubKey; } -void ModuleAssemblyComponent::SetUseOptionalParts(bool value) -{ - m_UseOptionalParts = value; +void ModuleAssemblyComponent::SetUseOptionalParts(bool value) { + m_UseOptionalParts = value; } -bool ModuleAssemblyComponent::GetUseOptionalParts() const -{ - return m_UseOptionalParts; +bool ModuleAssemblyComponent::GetUseOptionalParts() const { + return m_UseOptionalParts; } -void ModuleAssemblyComponent::SetAssemblyPartsLOTs(const std::u16string& value) -{ - std::u16string val {}; +void ModuleAssemblyComponent::SetAssemblyPartsLOTs(const std::u16string& value) { + std::u16string val{}; - val.reserve(value.size() + 1); + val.reserve(value.size() + 1); - for (auto character : value) - { - if (character == '+') character = ';'; + for (auto character : value) { + if (character == '+') character = ';'; - val.push_back(character); - } + val.push_back(character); + } - val.push_back(';'); - - m_AssemblyPartsLOTs = val; + val.push_back(';'); + + m_AssemblyPartsLOTs = val; } -const std::u16string& ModuleAssemblyComponent::GetAssemblyPartsLOTs() const -{ - return m_AssemblyPartsLOTs; +const std::u16string& ModuleAssemblyComponent::GetAssemblyPartsLOTs() const { + return m_AssemblyPartsLOTs; } -void ModuleAssemblyComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) -{ - if (bIsInitialUpdate) - { - outBitStream->Write1(); +void ModuleAssemblyComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { + if (bIsInitialUpdate) { + outBitStream->Write1(); - outBitStream->Write(m_SubKey != LWOOBJID_EMPTY); - if (m_SubKey != LWOOBJID_EMPTY) - { - outBitStream->Write(m_SubKey); - } + outBitStream->Write(m_SubKey != LWOOBJID_EMPTY); + if (m_SubKey != LWOOBJID_EMPTY) { + outBitStream->Write(m_SubKey); + } - outBitStream->Write(m_UseOptionalParts); + outBitStream->Write(m_UseOptionalParts); - outBitStream->Write(static_cast(m_AssemblyPartsLOTs.size())); - for (char16_t character : m_AssemblyPartsLOTs) - { - outBitStream->Write(character); - } - } + outBitStream->Write(static_cast(m_AssemblyPartsLOTs.size())); + for (char16_t character : m_AssemblyPartsLOTs) { + outBitStream->Write(character); + } + } } -void ModuleAssemblyComponent::Update(float deltaTime) -{ - +void ModuleAssemblyComponent::Update(float deltaTime) { + } diff --git a/dGame/dComponents/ModuleAssemblyComponent.h b/dGame/dComponents/ModuleAssemblyComponent.h index 7153f30b..24e1c1ee 100644 --- a/dGame/dComponents/ModuleAssemblyComponent.h +++ b/dGame/dComponents/ModuleAssemblyComponent.h @@ -12,65 +12,65 @@ class ModuleAssemblyComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_MODULE_ASSEMBLY; - + ModuleAssemblyComponent(Entity* MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); ~ModuleAssemblyComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Update(float deltaTime) override; - /** - * Sets the subkey of this entity - * @param value the subkey to set - */ - void SetSubKey(LWOOBJID value); + /** + * Sets the subkey of this entity + * @param value the subkey to set + */ + void SetSubKey(LWOOBJID value); - /** - * Returns the subkey for this entity - * @return the subkey for this entity - */ - LWOOBJID GetSubKey() const; + /** + * Returns the subkey for this entity + * @return the subkey for this entity + */ + LWOOBJID GetSubKey() const; - /** - * Sets the optional parts value - * @param value the value to set - */ - void SetUseOptionalParts(bool value); + /** + * Sets the optional parts value + * @param value the value to set + */ + void SetUseOptionalParts(bool value); - /** - * Returns the optional parts value - * @return the value to set - */ - bool GetUseOptionalParts() const; + /** + * Returns the optional parts value + * @return the value to set + */ + bool GetUseOptionalParts() const; - /** - * Sets the assembly part lots (the subsections of this modular build) - * @param value the assembly part lots to set - */ - void SetAssemblyPartsLOTs(const std::u16string& value); + /** + * Sets the assembly part lots (the subsections of this modular build) + * @param value the assembly part lots to set + */ + void SetAssemblyPartsLOTs(const std::u16string& value); - /** - * Returns the assembly part lots (the subsections of this modular build) - * @return - */ - const std::u16string& GetAssemblyPartsLOTs() const; + /** + * Returns the assembly part lots (the subsections of this modular build) + * @return + */ + const std::u16string& GetAssemblyPartsLOTs() const; private: - /** - * The sub key is the entity that this entity is an instance of. E.g. the item in the inventory. If a car for - * example is to be rendered, this sub key refers to the car item that was used to build this entity. - */ - LWOOBJID m_SubKey; + /** + * The sub key is the entity that this entity is an instance of. E.g. the item in the inventory. If a car for + * example is to be rendered, this sub key refers to the car item that was used to build this entity. + */ + LWOOBJID m_SubKey; - /** - * Whether to use optional parts, currently unused - */ - bool m_UseOptionalParts; + /** + * Whether to use optional parts, currently unused + */ + bool m_UseOptionalParts; - /** - * The sub items that this entity is made of - */ - std::u16string m_AssemblyPartsLOTs; + /** + * The sub items that this entity is made of + */ + std::u16string m_AssemblyPartsLOTs; }; diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index ff7c0cef..9c76b286 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -17,7 +17,7 @@ MovementAIComponent::MovementAIComponent(Entity* parent, MovementAIInfo info) : m_Done = true; m_BaseCombatAI = nullptr; - + m_BaseCombatAI = reinterpret_cast(m_Parent->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); //Try and fix the insane values: @@ -42,12 +42,11 @@ MovementAIComponent::MovementAIComponent(Entity* parent, MovementAIInfo info) : MovementAIComponent::~MovementAIComponent() = default; void MovementAIComponent::Update(const float deltaTime) { - if (m_Interrupted) - { + if (m_Interrupted) { const auto source = GetCurrentWaypoint(); const auto speed = deltaTime * 2.5f; - + NiPoint3 velocity; velocity.x = (m_PullPoint.x - source.x) * speed; @@ -56,21 +55,19 @@ void MovementAIComponent::Update(const float deltaTime) { SetPosition(source + velocity); - if (Vector3::DistanceSquared(GetCurrentPosition(), m_PullPoint) < 2 * 2) - { + if (Vector3::DistanceSquared(GetCurrentPosition(), m_PullPoint) < 2 * 2) { m_Interrupted = false; } return; } - + if (AtFinalWaypoint()) // Are we done? { return; } - if (m_HaltDistance > 0) - { + if (m_HaltDistance > 0) { if (Vector3::DistanceSquared(ApproximateLocation(), GetDestination()) < m_HaltDistance * m_HaltDistance) // Prevent us from hugging the target { Stop(); @@ -79,12 +76,10 @@ void MovementAIComponent::Update(const float deltaTime) { } } - if (m_Timer > 0) - { + if (m_Timer > 0) { m_Timer -= deltaTime; - if (m_Timer > 0) - { + if (m_Timer > 0) { return; } @@ -92,7 +87,7 @@ void MovementAIComponent::Update(const float deltaTime) { } const auto source = GetCurrentWaypoint(); - + SetPosition(source); NiPoint3 velocity = NiPoint3::ZERO; @@ -101,20 +96,17 @@ void MovementAIComponent::Update(const float deltaTime) { { m_NextWaypoint = GetCurrentWaypoint(); - if (m_NextWaypoint == source) - { + if (m_NextWaypoint == source) { m_Timer = 0; goto nextAction; } - if (m_CurrentSpeed < m_Speed) - { + if (m_CurrentSpeed < m_Speed) { m_CurrentSpeed += m_Acceleration; } - if (m_CurrentSpeed > m_Speed) - { + if (m_CurrentSpeed > m_Speed) { m_CurrentSpeed = m_Speed; } @@ -125,8 +117,7 @@ void MovementAIComponent::Update(const float deltaTime) { // Normalize the vector const auto length = sqrtf(delta.x * delta.x + delta.y * delta.y + delta.z * delta.z); - if (length > 0) - { + if (length > 0) { velocity.x = (delta.x / length) * speed; velocity.y = (delta.y / length) * speed; velocity.z = (delta.z / length) * speed; @@ -134,80 +125,66 @@ void MovementAIComponent::Update(const float deltaTime) { // Calclute the time it will take to reach the next waypoint with the current speed m_TotalTime = m_Timer = length / speed; - + SetRotation(NiQuaternion::LookAt(source, m_NextWaypoint)); - } - else - { + } else { // Check if there are more waypoints in the queue, if so set our next destination to the next waypoint - if (!m_Queue.empty()) - { + if (!m_Queue.empty()) { SetDestination(m_Queue.top()); m_Queue.pop(); - } - else - { + } else { // We have reached our final waypoint Stop(); return; } } - - nextAction: + +nextAction: SetVelocity(velocity); EntityManager::Instance()->SerializeEntity(m_Parent); } -const MovementAIInfo& MovementAIComponent::GetInfo() const -{ +const MovementAIInfo& MovementAIComponent::GetInfo() const { return m_Info; } -bool MovementAIComponent::AdvanceWaypointIndex() -{ - if (m_PathIndex >= m_CurrentPath.size()) - { +bool MovementAIComponent::AdvanceWaypointIndex() { + if (m_PathIndex >= m_CurrentPath.size()) { return false; } - + m_PathIndex++; return true; } -NiPoint3 MovementAIComponent::GetCurrentWaypoint() const -{ - if (m_PathIndex >= m_CurrentPath.size()) - { +NiPoint3 MovementAIComponent::GetCurrentWaypoint() const { + if (m_PathIndex >= m_CurrentPath.size()) { return GetCurrentPosition(); } return m_CurrentPath[m_PathIndex]; } -NiPoint3 MovementAIComponent::GetNextWaypoint() const -{ +NiPoint3 MovementAIComponent::GetNextWaypoint() const { return m_NextWaypoint; } -NiPoint3 MovementAIComponent::GetCurrentPosition() const -{ +NiPoint3 MovementAIComponent::GetCurrentPosition() const { return m_Parent->GetPosition(); } -NiPoint3 MovementAIComponent::ApproximateLocation() const -{ +NiPoint3 MovementAIComponent::ApproximateLocation() const { auto source = GetCurrentPosition(); - - if (m_Done) - { + + if (m_Done) { return source; } - + auto destination = m_NextWaypoint; auto factor = m_TotalTime > 0 ? (m_TotalTime - m_Timer) / m_TotalTime : 0; @@ -217,27 +194,23 @@ NiPoint3 MovementAIComponent::ApproximateLocation() const auto z = source.z + factor * (destination.z - source.z); NiPoint3 approximation = NiPoint3(x, y, z); - - if (dpWorld::Instance().IsLoaded()) - { + + if (dpWorld::Instance().IsLoaded()) { approximation.y = dpWorld::Instance().GetHeightAtPoint(approximation); } return approximation; } -bool MovementAIComponent::Warp(const NiPoint3& point) -{ +bool MovementAIComponent::Warp(const NiPoint3& point) { Stop(); - + NiPoint3 destination = point; - if (dpWorld::Instance().IsLoaded()) - { + if (dpWorld::Instance().IsLoaded()) { destination.y = dpWorld::Instance().GetHeightAtPoint(point); - if (std::abs(destination.y - point.y) > 3) - { + if (std::abs(destination.y - point.y) > 3) { return false; } } @@ -249,29 +222,25 @@ bool MovementAIComponent::Warp(const NiPoint3& point) return true; } -float MovementAIComponent::GetTimer() const -{ +float MovementAIComponent::GetTimer() const { return m_Timer; } -bool MovementAIComponent::AtFinalWaypoint() const -{ +bool MovementAIComponent::AtFinalWaypoint() const { return m_Done; } -void MovementAIComponent::Stop() -{ - if (m_Done) - { +void MovementAIComponent::Stop() { + if (m_Done) { return; } SetPosition(ApproximateLocation()); SetVelocity(NiPoint3::ZERO); - + m_TotalTime = m_Timer = 0; - + m_Done = true; m_CurrentPath = {}; @@ -279,24 +248,21 @@ void MovementAIComponent::Stop() m_PathIndex = 0; m_CurrentSpeed = 0; - + EntityManager::Instance()->SerializeEntity(m_Parent); } -void MovementAIComponent::PullToPoint(const NiPoint3& point) -{ +void MovementAIComponent::PullToPoint(const NiPoint3& point) { Stop(); - + m_Interrupted = true; m_PullPoint = point; } -void MovementAIComponent::SetPath(std::vector path) -{ +void MovementAIComponent::SetPath(std::vector path) { std::reverse(path.begin(), path.end()); - for (const auto& point : path) - { + for (const auto& point : path) { m_Queue.push(point); } @@ -305,26 +271,23 @@ void MovementAIComponent::SetPath(std::vector path) m_Queue.pop(); } -float MovementAIComponent::GetBaseSpeed(LOT lot) -{ +float MovementAIComponent::GetBaseSpeed(LOT lot) { // Check if the lot is in the cache const auto& it = m_PhysicsSpeedCache.find(lot); - - if (it != m_PhysicsSpeedCache.end()) - { + + if (it != m_PhysicsSpeedCache.end()) { return it->second; } - + CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance()->GetTable("PhysicsComponent"); int32_t componentID; CDPhysicsComponent* physicsComponent = nullptr; - componentID = componentRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_CONTROLLABLE_PHYSICS, -1); + componentID = componentRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_CONTROLLABLE_PHYSICS, -1); - if (componentID != -1) - { + if (componentID != -1) { physicsComponent = physicsComponentTable->GetByID(componentID); goto foundComponent; @@ -332,23 +295,19 @@ float MovementAIComponent::GetBaseSpeed(LOT lot) componentID = componentRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_SIMPLE_PHYSICS, -1); - if (componentID != -1) - { + if (componentID != -1) { physicsComponent = physicsComponentTable->GetByID(componentID); goto foundComponent; } - foundComponent: +foundComponent: float speed; - if (physicsComponent == nullptr) - { + if (physicsComponent == nullptr) { speed = 8; - } - else - { + } else { speed = physicsComponent->speed; } @@ -357,12 +316,10 @@ float MovementAIComponent::GetBaseSpeed(LOT lot) return speed; } -void MovementAIComponent::SetPosition(const NiPoint3& value) -{ +void MovementAIComponent::SetPosition(const NiPoint3& value) { auto* controllablePhysicsComponent = m_Parent->GetComponent(); - if (controllablePhysicsComponent != nullptr) - { + if (controllablePhysicsComponent != nullptr) { controllablePhysicsComponent->SetPosition(value); return; @@ -370,23 +327,19 @@ void MovementAIComponent::SetPosition(const NiPoint3& value) auto* simplePhysicsComponent = m_Parent->GetComponent(); - if (simplePhysicsComponent != nullptr) - { + if (simplePhysicsComponent != nullptr) { simplePhysicsComponent->SetPosition(value); } } -void MovementAIComponent::SetRotation(const NiQuaternion& value) -{ - if (m_LockRotation) - { +void MovementAIComponent::SetRotation(const NiQuaternion& value) { + if (m_LockRotation) { return; } auto* controllablePhysicsComponent = m_Parent->GetComponent(); - if (controllablePhysicsComponent != nullptr) - { + if (controllablePhysicsComponent != nullptr) { controllablePhysicsComponent->SetRotation(value); return; @@ -394,18 +347,15 @@ void MovementAIComponent::SetRotation(const NiQuaternion& value) auto* simplePhysicsComponent = m_Parent->GetComponent(); - if (simplePhysicsComponent != nullptr) - { + if (simplePhysicsComponent != nullptr) { simplePhysicsComponent->SetRotation(value); } } -void MovementAIComponent::SetVelocity(const NiPoint3& value) -{ +void MovementAIComponent::SetVelocity(const NiPoint3& value) { auto* controllablePhysicsComponent = m_Parent->GetComponent(); - if (controllablePhysicsComponent != nullptr) - { + if (controllablePhysicsComponent != nullptr) { controllablePhysicsComponent->SetVelocity(value); return; @@ -413,19 +363,16 @@ void MovementAIComponent::SetVelocity(const NiPoint3& value) auto* simplePhysicsComponent = m_Parent->GetComponent(); - if (simplePhysicsComponent != nullptr) - { + if (simplePhysicsComponent != nullptr) { simplePhysicsComponent->SetVelocity(value); } } -void MovementAIComponent::SetDestination(const NiPoint3& value) -{ - if (m_Interrupted) - { +void MovementAIComponent::SetDestination(const NiPoint3& value) { + if (m_Interrupted) { return; } - + /*if (Vector3::DistanceSquared(value, GetDestination()) < 2 * 2) { return; @@ -433,19 +380,15 @@ void MovementAIComponent::SetDestination(const NiPoint3& value) const auto location = ApproximateLocation(); - if (!AtFinalWaypoint()) - { + if (!AtFinalWaypoint()) { SetPosition(location); } std::vector computedPath; - - if (dpWorld::Instance().IsLoaded()) - { + + if (dpWorld::Instance().IsLoaded()) { computedPath = dpWorld::Instance().GetPath(GetCurrentPosition(), value, m_Info.wanderSpeed); - } - else - { + } else { // Than take 10 points between the current position and the destination and make that the path auto point = location; @@ -454,8 +397,7 @@ void MovementAIComponent::SetDestination(const NiPoint3& value) auto step = delta / 10; - for (int i = 0; i < 10; i++) - { + for (int i = 0; i < 10; i++) { point = point + step; computedPath.push_back(point); @@ -472,10 +414,8 @@ void MovementAIComponent::SetDestination(const NiPoint3& value) m_CurrentPath.push_back(location); // Simply path - for (auto point : computedPath) - { - if (dpWorld::Instance().IsLoaded()) - { + for (auto point : computedPath) { + if (dpWorld::Instance().IsLoaded()) { point.y = dpWorld::Instance().GetHeightAtPoint(point); } @@ -483,71 +423,59 @@ void MovementAIComponent::SetDestination(const NiPoint3& value) } m_CurrentPath.push_back(computedPath[computedPath.size() - 1]); - + m_PathIndex = 0; - + m_TotalTime = m_Timer = 0; - + m_Done = false; } -NiPoint3 MovementAIComponent::GetDestination() const -{ - if (m_CurrentPath.empty()) - { +NiPoint3 MovementAIComponent::GetDestination() const { + if (m_CurrentPath.empty()) { return GetCurrentPosition(); } return m_CurrentPath[m_CurrentPath.size() - 1]; } -void MovementAIComponent::SetSpeed(const float value) -{ +void MovementAIComponent::SetSpeed(const float value) { m_Speed = value; m_Acceleration = value / 5; } -float MovementAIComponent::GetSpeed() const -{ +float MovementAIComponent::GetSpeed() const { return m_Speed; } -void MovementAIComponent::SetAcceleration(const float value) -{ +void MovementAIComponent::SetAcceleration(const float value) { m_Acceleration = value; } -float MovementAIComponent::GetAcceleration() const -{ +float MovementAIComponent::GetAcceleration() const { return m_Acceleration; } -void MovementAIComponent::SetHaltDistance(const float value) -{ +void MovementAIComponent::SetHaltDistance(const float value) { m_HaltDistance = value; } -float MovementAIComponent::GetHaltDistance() const -{ +float MovementAIComponent::GetHaltDistance() const { return m_HaltDistance; } -void MovementAIComponent::SetCurrentSpeed(float value) -{ +void MovementAIComponent::SetCurrentSpeed(float value) { m_CurrentSpeed = value; } -float MovementAIComponent::GetCurrentSpeed() const -{ +float MovementAIComponent::GetCurrentSpeed() const { return m_CurrentSpeed; } -void MovementAIComponent::SetLockRotation(bool value) -{ +void MovementAIComponent::SetLockRotation(bool value) { m_LockRotation = value; } -bool MovementAIComponent::GetLockRotation() const -{ +bool MovementAIComponent::GetLockRotation() const { return m_LockRotation; } diff --git a/dGame/dComponents/MovementAIComponent.h b/dGame/dComponents/MovementAIComponent.h index 032732cc..82cd48a0 100644 --- a/dGame/dComponents/MovementAIComponent.h +++ b/dGame/dComponents/MovementAIComponent.h @@ -24,29 +24,29 @@ class BaseCombatAIComponent; struct MovementAIInfo { std::string movementType; - /** - * The radius that the entity can wander in - */ + /** + * The radius that the entity can wander in + */ float wanderRadius; - /** - * The speed at which the entity wanders - */ + /** + * The speed at which the entity wanders + */ float wanderSpeed; - /** - * This is only used for the emotes - */ + /** + * This is only used for the emotes + */ float wanderChance; - /** - * The min amount of delay before wandering - */ + /** + * The min amount of delay before wandering + */ float wanderDelayMin; - /** - * The max amount of delay before wandering - */ + /** + * The max amount of delay before wandering + */ float wanderDelayMax; }; @@ -57,273 +57,273 @@ struct MovementAIInfo { class MovementAIComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_MOVEMENT_AI; - + MovementAIComponent(Entity* parentEntity, MovementAIInfo info); ~MovementAIComponent() override; - + void Update(float deltaTime) override; - /** - * Returns the basic settings that this entity uses to move around - * @return the basic settings that this entity uses to move around - */ + /** + * Returns the basic settings that this entity uses to move around + * @return the basic settings that this entity uses to move around + */ const MovementAIInfo& GetInfo() const; - /** - * Set a destination point for the entity to move towards - * @param value the destination point to move towards - */ + /** + * Set a destination point for the entity to move towards + * @param value the destination point to move towards + */ void SetDestination(const NiPoint3& value); - /** - * Returns the current rotation this entity is moving towards - * @return the current rotation this entity is moving towards - */ + /** + * Returns the current rotation this entity is moving towards + * @return the current rotation this entity is moving towards + */ NiPoint3 GetDestination() const; - /** - * Sets the max speed at which this entity may run - * @param value the speed value to set - */ + /** + * Sets the max speed at which this entity may run + * @param value the speed value to set + */ void SetSpeed(float value); - /** - * Returns the max speed at which this entity may run - * @return the max speed at which this entity may run - */ + /** + * Returns the max speed at which this entity may run + * @return the max speed at which this entity may run + */ float GetSpeed() const; - /** - * Sets how fast the entity will accelerate when not running at full speed - * @param value the acceleration to set - */ + /** + * Sets how fast the entity will accelerate when not running at full speed + * @param value the acceleration to set + */ void SetAcceleration(float value); - /** - * Returns the current speed at which this entity accelerates when not running at full speed - * @return the current speed at which this entity accelerates when not running at full speed - */ + /** + * Returns the current speed at which this entity accelerates when not running at full speed + * @return the current speed at which this entity accelerates when not running at full speed + */ float GetAcceleration() const; - /** - * Sets the halting distance (the distance at which we consider the target to be reached) - * @param value the halting distance to set - */ + /** + * Sets the halting distance (the distance at which we consider the target to be reached) + * @param value the halting distance to set + */ void SetHaltDistance(float value); - /** - * Returns the current halting distance (the distance at which we consider the target to be reached) - * @return the current halting distance - */ + /** + * Returns the current halting distance (the distance at which we consider the target to be reached) + * @return the current halting distance + */ float GetHaltDistance() const; - /** - * Sets the speed the entity is currently running at - * @param value the speed value to set - */ + /** + * Sets the speed the entity is currently running at + * @param value the speed value to set + */ void SetCurrentSpeed(float value); - /** - * Returns the speed the entity is currently running at - * @return the speed the entity is currently running at - */ + /** + * Returns the speed the entity is currently running at + * @return the speed the entity is currently running at + */ float GetCurrentSpeed() const; - /** - * Locks the rotation of this entity in place, depending on the argument - * @param value if true, the entity will be rotationally locked - */ + /** + * Locks the rotation of this entity in place, depending on the argument + * @param value if true, the entity will be rotationally locked + */ void SetLockRotation(bool value); - /** - * Returns whether this entity is currently rotationally locked - * @return true if the entity is rotationally locked, false otherwise - */ + /** + * Returns whether this entity is currently rotationally locked + * @return true if the entity is rotationally locked, false otherwise + */ bool GetLockRotation() const; - /** - * Attempts to update the waypoint index, making the entity move to the next waypoint - * @return true if the waypoint could be increased, false if the entity is at the last waypoint already - */ + /** + * Attempts to update the waypoint index, making the entity move to the next waypoint + * @return true if the waypoint could be increased, false if the entity is at the last waypoint already + */ bool AdvanceWaypointIndex(); - /** - * Returns the waypoint the entity is currently moving towards - * @return the waypoint the entity is currently moving towards - */ + /** + * Returns the waypoint the entity is currently moving towards + * @return the waypoint the entity is currently moving towards + */ NiPoint3 GetCurrentWaypoint() const; - /** - * Returns the waypoint this entity is supposed to move towards next - * @return the waypoint this entity is supposed to move towards next - */ + /** + * Returns the waypoint this entity is supposed to move towards next + * @return the waypoint this entity is supposed to move towards next + */ NiPoint3 GetNextWaypoint() const; - /** - * Returns the current position of this entity - * @return the current position of this entity - */ + /** + * Returns the current position of this entity + * @return the current position of this entity + */ NiPoint3 GetCurrentPosition() const; - /** - * Returns the approximate current location of the entity, including y coordinates - * @return the approximate current location of the entity - */ + /** + * Returns the approximate current location of the entity, including y coordinates + * @return the approximate current location of the entity + */ NiPoint3 ApproximateLocation() const; - /** - * Teleports this entity to a position. If the distance between the provided point and the y it should have - * according to map data, this will not succeed (to avoid teleporting entities into the sky). - * @param point the point to teleport to - * @return true if the warp was successful, false otherwise - */ + /** + * Teleports this entity to a position. If the distance between the provided point and the y it should have + * according to map data, this will not succeed (to avoid teleporting entities into the sky). + * @param point the point to teleport to + * @return true if the warp was successful, false otherwise + */ bool Warp(const NiPoint3& point); - /** - * Returns the time it will take to reach the final waypoint according to the current speed - * @return the time it will take to reach the final waypoint according to the current speed - */ + /** + * Returns the time it will take to reach the final waypoint according to the current speed + * @return the time it will take to reach the final waypoint according to the current speed + */ float GetTimer() const; - /** - * Returns if the entity is at its final waypoint - * @return if the entity is at its final waypoint - */ + /** + * Returns if the entity is at its final waypoint + * @return if the entity is at its final waypoint + */ bool AtFinalWaypoint() const; - /** - * Renders the entity stationary - */ + /** + * Renders the entity stationary + */ void Stop(); - /** - * Stops the current movement and moves the entity to a certain point. Will continue until it's close enough, - * after which its AI is enabled again. - * @param point the point to move towards - */ + /** + * Stops the current movement and moves the entity to a certain point. Will continue until it's close enough, + * after which its AI is enabled again. + * @param point the point to move towards + */ void PullToPoint(const NiPoint3& point); - /** - * Sets a path to follow for the AI - * @param path the path to follow - */ + /** + * Sets a path to follow for the AI + * @param path the path to follow + */ void SetPath(std::vector path); - /** - * Returns the base speed from the DB for a given LOT - * @param lot the lot to check for - * @return the base speed of the lot - */ + /** + * Returns the base speed from the DB for a given LOT + * @param lot the lot to check for + * @return the base speed of the lot + */ static float GetBaseSpeed(LOT lot); private: - /** - * Sets the current position of the entity - * @param value the position to set - */ + /** + * Sets the current position of the entity + * @param value the position to set + */ void SetPosition(const NiPoint3& value); - /** - * Sets the current rotation of the entity - * @param value the rotation to set - */ + /** + * Sets the current rotation of the entity + * @param value the rotation to set + */ void SetRotation(const NiQuaternion& value); - /** - * Sets the current velocity of the entityes - * @param value the velocity to set - */ + /** + * Sets the current velocity of the entityes + * @param value the velocity to set + */ void SetVelocity(const NiPoint3& value); - /** - * Base information regarding the movement information for this entity - */ + /** + * Base information regarding the movement information for this entity + */ MovementAIInfo m_Info; - /** - * The point this entity is moving towards - */ + /** + * The point this entity is moving towards + */ NiPoint3 m_NextWaypoint; - /** - * The max speed this entity may move at - */ + /** + * The max speed this entity may move at + */ float m_Speed; - /** - * The time it will take to reach the next waypoint using the current speed - */ + /** + * The time it will take to reach the next waypoint using the current speed + */ float m_Timer; - /** - * The total time it will take to reach the waypoint form its starting point - */ + /** + * The total time it will take to reach the waypoint form its starting point + */ float m_TotalTime; - /** - * The path this entity is currently traversing - */ + /** + * The path this entity is currently traversing + */ uint32_t m_PathIndex; - /** - * If the entity has reached it last waypoint - */ + /** + * If the entity has reached it last waypoint + */ bool m_Done; - /** - * The speed the entity is currently moving at - */ + /** + * The speed the entity is currently moving at + */ float m_CurrentSpeed; - /** - * The acceleration this entity has when not moving at its top speed yet - */ + /** + * The acceleration this entity has when not moving at its top speed yet + */ float m_Acceleration; - /** - * The distance between the current position and the target waypoint to consider it reached (to not ghost into it). - */ + /** + * The distance between the current position and the target waypoint to consider it reached (to not ghost into it). + */ float m_HaltDistance; - /** - * The base speed this entity has - */ + /** + * The base speed this entity has + */ float m_BaseSpeed; - /** - * If the AI is currently turned of (e.g. when teleporting to some location) - */ + /** + * If the AI is currently turned of (e.g. when teleporting to some location) + */ bool m_Interrupted; - /** - * A position that the entity is currently moving towards while being interrupted - */ + /** + * A position that the entity is currently moving towards while being interrupted + */ NiPoint3 m_PullPoint; - /** - * If the entity is currently rotationally locked - */ + /** + * If the entity is currently rotationally locked + */ bool m_LockRotation; - /** - * Optional direct link to the combat AI component of the parent entity - */ + /** + * Optional direct link to the combat AI component of the parent entity + */ BaseCombatAIComponent* m_BaseCombatAI = nullptr; - /** - * The path the entity is currently following - */ + /** + * The path the entity is currently following + */ std::vector m_CurrentPath; - /** - * Queue of positions to traverse - */ + /** + * Queue of positions to traverse + */ std::stack m_Queue; - /** - * Cache of all lots and their respective speeds - */ + /** + * Cache of all lots and their respective speeds + */ static std::map m_PhysicsSpeedCache; }; diff --git a/dGame/dComponents/MovingPlatformComponent.cpp b/dGame/dComponents/MovingPlatformComponent.cpp index 4e99e6d6..42699672 100644 --- a/dGame/dComponents/MovingPlatformComponent.cpp +++ b/dGame/dComponents/MovingPlatformComponent.cpp @@ -14,370 +14,339 @@ #include "SimplePhysicsComponent.h" MoverSubComponent::MoverSubComponent(const NiPoint3& startPos) { - mPosition = {}; + mPosition = {}; mState = MovementPlatformState::Stopped; - mDesiredWaypointIndex = 0; // -1; - mInReverse = false; - mShouldStopAtDesiredWaypoint = false; + mDesiredWaypointIndex = 0; // -1; + mInReverse = false; + mShouldStopAtDesiredWaypoint = false; - mPercentBetweenPoints = 0.0f; + mPercentBetweenPoints = 0.0f; - mCurrentWaypointIndex = 0; - mNextWaypointIndex = 0; //mCurrentWaypointIndex + 1; + mCurrentWaypointIndex = 0; + mNextWaypointIndex = 0; //mCurrentWaypointIndex + 1; - mIdleTimeElapsed = 0.0f; + mIdleTimeElapsed = 0.0f; } MoverSubComponent::~MoverSubComponent() = default; void MoverSubComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) const { - outBitStream->Write(true); + outBitStream->Write(true); - outBitStream->Write(static_cast(mState)); - outBitStream->Write(mDesiredWaypointIndex); - outBitStream->Write(mShouldStopAtDesiredWaypoint); - outBitStream->Write(mInReverse); + outBitStream->Write(static_cast(mState)); + outBitStream->Write(mDesiredWaypointIndex); + outBitStream->Write(mShouldStopAtDesiredWaypoint); + outBitStream->Write(mInReverse); - outBitStream->Write(mPercentBetweenPoints); + outBitStream->Write(mPercentBetweenPoints); - outBitStream->Write(mPosition.x); - outBitStream->Write(mPosition.y); - outBitStream->Write(mPosition.z); + outBitStream->Write(mPosition.x); + outBitStream->Write(mPosition.y); + outBitStream->Write(mPosition.z); - outBitStream->Write(mCurrentWaypointIndex); - outBitStream->Write(mNextWaypointIndex); + outBitStream->Write(mCurrentWaypointIndex); + outBitStream->Write(mNextWaypointIndex); - outBitStream->Write(mIdleTimeElapsed); - outBitStream->Write(0.0f); // Move time elapsed + outBitStream->Write(mIdleTimeElapsed); + outBitStream->Write(0.0f); // Move time elapsed } //------------- MovingPlatformComponent below -------------- MovingPlatformComponent::MovingPlatformComponent(Entity* parent, const std::string& pathName) : Component(parent) { - m_MoverSubComponentType = eMoverSubComponentType::mover; - m_MoverSubComponent = new MoverSubComponent(m_Parent->GetDefaultPosition()); - m_PathName = GeneralUtils::ASCIIToUTF16(pathName); - m_Path = dZoneManager::Instance()->GetZone()->GetPath(pathName); - m_NoAutoStart = false; + m_MoverSubComponentType = eMoverSubComponentType::mover; + m_MoverSubComponent = new MoverSubComponent(m_Parent->GetDefaultPosition()); + m_PathName = GeneralUtils::ASCIIToUTF16(pathName); + m_Path = dZoneManager::Instance()->GetZone()->GetPath(pathName); + m_NoAutoStart = false; - if (m_Path == nullptr) { - Game::logger->Log("MovingPlatformComponent", "Path not found: %s", pathName.c_str()); - } + if (m_Path == nullptr) { + Game::logger->Log("MovingPlatformComponent", "Path not found: %s", pathName.c_str()); + } } MovingPlatformComponent::~MovingPlatformComponent() { - delete static_cast(m_MoverSubComponent); + delete static_cast(m_MoverSubComponent); } void MovingPlatformComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - // Here we don't serialize the moving platform to let the client simulate the movement + // Here we don't serialize the moving platform to let the client simulate the movement - if (!m_Serialize) - { - outBitStream->Write(false); - outBitStream->Write(false); + if (!m_Serialize) { + outBitStream->Write(false); + outBitStream->Write(false); - return; - } + return; + } - outBitStream->Write(true); + outBitStream->Write(true); - auto hasPath = !m_PathingStopped && !m_PathName.empty(); - outBitStream->Write(hasPath); + auto hasPath = !m_PathingStopped && !m_PathName.empty(); + outBitStream->Write(hasPath); - if (hasPath) { - // Is on rail - outBitStream->Write1(); + if (hasPath) { + // Is on rail + outBitStream->Write1(); - outBitStream->Write(static_cast(m_PathName.size())); - for (const auto& c : m_PathName) { - outBitStream->Write(static_cast(c)); - } + outBitStream->Write(static_cast(m_PathName.size())); + for (const auto& c : m_PathName) { + outBitStream->Write(static_cast(c)); + } - // Starting point - outBitStream->Write(0); + // Starting point + outBitStream->Write(0); - // Reverse - outBitStream->Write(false); - } + // Reverse + outBitStream->Write(false); + } - const auto hasPlatform = m_MoverSubComponent != nullptr; - outBitStream->Write(hasPlatform); + const auto hasPlatform = m_MoverSubComponent != nullptr; + outBitStream->Write(hasPlatform); - if (hasPlatform) { - auto* mover = static_cast(m_MoverSubComponent); - outBitStream->Write(static_cast(m_MoverSubComponentType)); + if (hasPlatform) { + auto* mover = static_cast(m_MoverSubComponent); + outBitStream->Write(static_cast(m_MoverSubComponentType)); - if (m_MoverSubComponentType == eMoverSubComponentType::simpleMover) { - // TODO - } else { - mover->Serialize(outBitStream, bIsInitialUpdate, flags); - } - } + if (m_MoverSubComponentType == eMoverSubComponentType::simpleMover) { + // TODO + } else { + mover->Serialize(outBitStream, bIsInitialUpdate, flags); + } + } } void MovingPlatformComponent::OnRebuildInitilized() { - StopPathing(); + StopPathing(); } void MovingPlatformComponent::OnCompleteRebuild() { - if (m_NoAutoStart) - return; + if (m_NoAutoStart) + return; - StartPathing(); + StartPathing(); } -void MovingPlatformComponent::SetMovementState(MovementPlatformState value) -{ - auto* subComponent = static_cast(m_MoverSubComponent); +void MovingPlatformComponent::SetMovementState(MovementPlatformState value) { + auto* subComponent = static_cast(m_MoverSubComponent); - subComponent->mState = value; + subComponent->mState = value; - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } -void MovingPlatformComponent::GotoWaypoint(uint32_t index, bool stopAtWaypoint) -{ - auto* subComponent = static_cast(m_MoverSubComponent); +void MovingPlatformComponent::GotoWaypoint(uint32_t index, bool stopAtWaypoint) { + auto* subComponent = static_cast(m_MoverSubComponent); - subComponent->mDesiredWaypointIndex = index; - subComponent->mNextWaypointIndex = index; - subComponent->mShouldStopAtDesiredWaypoint = stopAtWaypoint; + subComponent->mDesiredWaypointIndex = index; + subComponent->mNextWaypointIndex = index; + subComponent->mShouldStopAtDesiredWaypoint = stopAtWaypoint; - StartPathing(); + StartPathing(); } -void MovingPlatformComponent::StartPathing() -{ +void MovingPlatformComponent::StartPathing() { //GameMessages::SendStartPathing(m_Parent); - m_PathingStopped = false; + m_PathingStopped = false; - auto* subComponent = static_cast(m_MoverSubComponent); + auto* subComponent = static_cast(m_MoverSubComponent); - subComponent->mShouldStopAtDesiredWaypoint = true; - subComponent->mState = MovementPlatformState::Stationary; + subComponent->mShouldStopAtDesiredWaypoint = true; + subComponent->mState = MovementPlatformState::Stationary; - NiPoint3 targetPosition; + NiPoint3 targetPosition; - if (m_Path != nullptr) { - const auto& currentWaypoint = m_Path->pathWaypoints[subComponent->mCurrentWaypointIndex]; - const auto& nextWaypoint = m_Path->pathWaypoints[subComponent->mNextWaypointIndex]; + if (m_Path != nullptr) { + const auto& currentWaypoint = m_Path->pathWaypoints[subComponent->mCurrentWaypointIndex]; + const auto& nextWaypoint = m_Path->pathWaypoints[subComponent->mNextWaypointIndex]; - subComponent->mPosition = currentWaypoint.position; - subComponent->mSpeed = currentWaypoint.movingPlatform.speed; - subComponent->mWaitTime = currentWaypoint.movingPlatform.wait; + subComponent->mPosition = currentWaypoint.position; + subComponent->mSpeed = currentWaypoint.movingPlatform.speed; + subComponent->mWaitTime = currentWaypoint.movingPlatform.wait; - targetPosition = nextWaypoint.position; - } - else { - subComponent->mPosition = m_Parent->GetPosition(); - subComponent->mSpeed = 1.0f; - subComponent->mWaitTime = 2.0f; + targetPosition = nextWaypoint.position; + } else { + subComponent->mPosition = m_Parent->GetPosition(); + subComponent->mSpeed = 1.0f; + subComponent->mWaitTime = 2.0f; - targetPosition = m_Parent->GetPosition() + NiPoint3(0.0f, 10.0f, 0.0f); - } + targetPosition = m_Parent->GetPosition() + NiPoint3(0.0f, 10.0f, 0.0f); + } - m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] - { - SetMovementState(MovementPlatformState::Moving); - }); + m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] { + SetMovementState(MovementPlatformState::Moving); + }); - const auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5f; + const auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5f; - const auto travelNext = subComponent->mWaitTime + travelTime; + const auto travelNext = subComponent->mWaitTime + travelTime; - m_Parent->AddCallbackTimer(travelTime, [subComponent, this] { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnWaypointReached(m_Parent, subComponent->mNextWaypointIndex); - } - }); + m_Parent->AddCallbackTimer(travelTime, [subComponent, this] { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { + script->OnWaypointReached(m_Parent, subComponent->mNextWaypointIndex); + } + }); - m_Parent->AddCallbackTimer(travelNext, [this] - { - ContinuePathing(); - }); + m_Parent->AddCallbackTimer(travelNext, [this] { + ContinuePathing(); + }); - //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); + //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } -void MovingPlatformComponent::ContinuePathing() -{ - auto* subComponent = static_cast(m_MoverSubComponent); +void MovingPlatformComponent::ContinuePathing() { + auto* subComponent = static_cast(m_MoverSubComponent); - subComponent->mState = MovementPlatformState::Stationary; + subComponent->mState = MovementPlatformState::Stationary; - subComponent->mCurrentWaypointIndex = subComponent->mNextWaypointIndex; + subComponent->mCurrentWaypointIndex = subComponent->mNextWaypointIndex; - NiPoint3 targetPosition; - uint32_t pathSize; - PathBehavior behavior; + NiPoint3 targetPosition; + uint32_t pathSize; + PathBehavior behavior; - if (m_Path != nullptr) { - const auto& currentWaypoint = m_Path->pathWaypoints[subComponent->mCurrentWaypointIndex]; - const auto& nextWaypoint = m_Path->pathWaypoints[subComponent->mNextWaypointIndex]; + if (m_Path != nullptr) { + const auto& currentWaypoint = m_Path->pathWaypoints[subComponent->mCurrentWaypointIndex]; + const auto& nextWaypoint = m_Path->pathWaypoints[subComponent->mNextWaypointIndex]; - subComponent->mPosition = currentWaypoint.position; - subComponent->mSpeed = currentWaypoint.movingPlatform.speed; - subComponent->mWaitTime = currentWaypoint.movingPlatform.wait; // + 2; + subComponent->mPosition = currentWaypoint.position; + subComponent->mSpeed = currentWaypoint.movingPlatform.speed; + subComponent->mWaitTime = currentWaypoint.movingPlatform.wait; // + 2; - pathSize = m_Path->pathWaypoints.size() - 1; + pathSize = m_Path->pathWaypoints.size() - 1; - behavior = static_cast(m_Path->pathBehavior); + behavior = static_cast(m_Path->pathBehavior); - targetPosition = nextWaypoint.position; - } - else - { - subComponent->mPosition = m_Parent->GetPosition(); - subComponent->mSpeed = 1.0f; - subComponent->mWaitTime = 2.0f; + targetPosition = nextWaypoint.position; + } else { + subComponent->mPosition = m_Parent->GetPosition(); + subComponent->mSpeed = 1.0f; + subComponent->mWaitTime = 2.0f; - targetPosition = m_Parent->GetPosition() + NiPoint3(0.0f, 10.0f, 0.0f); + targetPosition = m_Parent->GetPosition() + NiPoint3(0.0f, 10.0f, 0.0f); - pathSize = 1; - behavior = PathBehavior::Loop; - } + pathSize = 1; + behavior = PathBehavior::Loop; + } - if (m_Parent->GetLOT() == 9483) - { - behavior = PathBehavior::Bounce; - } - else - { - return; - } + if (m_Parent->GetLOT() == 9483) { + behavior = PathBehavior::Bounce; + } else { + return; + } - if (subComponent->mCurrentWaypointIndex >= pathSize) - { - subComponent->mCurrentWaypointIndex = pathSize; - switch (behavior) - { - case PathBehavior::Once: - EntityManager::Instance()->SerializeEntity(m_Parent); - return; + if (subComponent->mCurrentWaypointIndex >= pathSize) { + subComponent->mCurrentWaypointIndex = pathSize; + switch (behavior) { + case PathBehavior::Once: + EntityManager::Instance()->SerializeEntity(m_Parent); + return; - case PathBehavior::Bounce: - subComponent->mInReverse = true; - break; + case PathBehavior::Bounce: + subComponent->mInReverse = true; + break; - case PathBehavior::Loop: - subComponent->mNextWaypointIndex = 0; - break; + case PathBehavior::Loop: + subComponent->mNextWaypointIndex = 0; + break; - default: - break; - } - } - else if (subComponent->mCurrentWaypointIndex == 0) - { - subComponent->mInReverse = false; - } + default: + break; + } + } else if (subComponent->mCurrentWaypointIndex == 0) { + subComponent->mInReverse = false; + } - if (subComponent->mInReverse) - { - subComponent->mNextWaypointIndex = subComponent->mCurrentWaypointIndex - 1; - } - else - { - subComponent->mNextWaypointIndex = subComponent->mCurrentWaypointIndex + 1; - } + if (subComponent->mInReverse) { + subComponent->mNextWaypointIndex = subComponent->mCurrentWaypointIndex - 1; + } else { + subComponent->mNextWaypointIndex = subComponent->mCurrentWaypointIndex + 1; + } - /* - subComponent->mNextWaypointIndex = 0; - subComponent->mCurrentWaypointIndex = 1; - */ + /* + subComponent->mNextWaypointIndex = 0; + subComponent->mCurrentWaypointIndex = 1; + */ - //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); + //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); - if (subComponent->mCurrentWaypointIndex == subComponent->mDesiredWaypointIndex) - { - // TODO: Send event? - StopPathing(); + if (subComponent->mCurrentWaypointIndex == subComponent->mDesiredWaypointIndex) { + // TODO: Send event? + StopPathing(); - return; - } + return; + } - m_Parent->CancelCallbackTimers(); + m_Parent->CancelCallbackTimers(); - m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] - { - SetMovementState(MovementPlatformState::Moving); - }); + m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] { + SetMovementState(MovementPlatformState::Moving); + }); - auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5; + auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5; - if (m_Parent->GetLOT() == 9483) - { - travelTime += 20; - } + if (m_Parent->GetLOT() == 9483) { + travelTime += 20; + } - const auto travelNext = subComponent->mWaitTime + travelTime; + const auto travelNext = subComponent->mWaitTime + travelTime; - m_Parent->AddCallbackTimer(travelTime, [subComponent, this] { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnWaypointReached(m_Parent, subComponent->mNextWaypointIndex); - } - }); + m_Parent->AddCallbackTimer(travelTime, [subComponent, this] { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { + script->OnWaypointReached(m_Parent, subComponent->mNextWaypointIndex); + } + }); - m_Parent->AddCallbackTimer(travelNext, [this] - { - ContinuePathing(); - }); + m_Parent->AddCallbackTimer(travelNext, [this] { + ContinuePathing(); + }); - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } -void MovingPlatformComponent::StopPathing() -{ - //m_Parent->CancelCallbackTimers(); +void MovingPlatformComponent::StopPathing() { + //m_Parent->CancelCallbackTimers(); - auto* subComponent = static_cast(m_MoverSubComponent); + auto* subComponent = static_cast(m_MoverSubComponent); - m_PathingStopped = true; + m_PathingStopped = true; - subComponent->mState = MovementPlatformState::Stopped; - subComponent->mDesiredWaypointIndex = -1; - subComponent->mShouldStopAtDesiredWaypoint = false; + subComponent->mState = MovementPlatformState::Stopped; + subComponent->mDesiredWaypointIndex = -1; + subComponent->mShouldStopAtDesiredWaypoint = false; - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); + //GameMessages::SendPlatformResync(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); } -void MovingPlatformComponent::SetSerialized(bool value) -{ - m_Serialize = value; +void MovingPlatformComponent::SetSerialized(bool value) { + m_Serialize = value; } -bool MovingPlatformComponent::GetNoAutoStart() const -{ - return m_NoAutoStart; +bool MovingPlatformComponent::GetNoAutoStart() const { + return m_NoAutoStart; } -void MovingPlatformComponent::SetNoAutoStart(const bool value) -{ - m_NoAutoStart = value; +void MovingPlatformComponent::SetNoAutoStart(const bool value) { + m_NoAutoStart = value; } -void MovingPlatformComponent::WarpToWaypoint(size_t index) -{ - const auto& waypoint = m_Path->pathWaypoints[index]; +void MovingPlatformComponent::WarpToWaypoint(size_t index) { + const auto& waypoint = m_Path->pathWaypoints[index]; - m_Parent->SetPosition(waypoint.position); - m_Parent->SetRotation(waypoint.rotation); + m_Parent->SetPosition(waypoint.position); + m_Parent->SetRotation(waypoint.rotation); - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } -size_t MovingPlatformComponent::GetLastWaypointIndex() const -{ - return m_Path->pathWaypoints.size() - 1; +size_t MovingPlatformComponent::GetLastWaypointIndex() const { + return m_Path->pathWaypoints.size() - 1; } -MoverSubComponent* MovingPlatformComponent::GetMoverSubComponent() const -{ - return static_cast(m_MoverSubComponent); +MoverSubComponent* MovingPlatformComponent::GetMoverSubComponent() const { + return static_cast(m_MoverSubComponent); } diff --git a/dGame/dComponents/MovingPlatformComponent.h b/dGame/dComponents/MovingPlatformComponent.h index da377916..efa3a4cf 100644 --- a/dGame/dComponents/MovingPlatformComponent.h +++ b/dGame/dComponents/MovingPlatformComponent.h @@ -14,16 +14,16 @@ #include "EntityManager.h" #include "Component.h" -/** - * Different types of available platforms - */ + /** + * Different types of available platforms + */ enum class eMoverSubComponentType : uint32_t { - mover = 4, + mover = 4, - /** - * Used in NJ - */ - simpleMover = 5, + /** + * Used in NJ + */ + simpleMover = 5, }; /** @@ -31,9 +31,9 @@ enum class eMoverSubComponentType : uint32_t { */ enum class MovementPlatformState : uint32_t { - Moving = 0b00010, - Stationary = 0b11001, - Stopped = 0b01100 + Moving = 0b00010, + Stationary = 0b11001, + Stopped = 0b01100 }; /** @@ -41,65 +41,65 @@ enum class MovementPlatformState : uint32_t */ class MoverSubComponent { public: - MoverSubComponent(const NiPoint3& startPos); - ~MoverSubComponent(); - - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) const; + MoverSubComponent(const NiPoint3& startPos); + ~MoverSubComponent(); - /** - * The state the platform is currently in - */ - MovementPlatformState mState = MovementPlatformState::Stationary; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) const; - /** - * The waypoint this platform currently wants to traverse to - */ - int32_t mDesiredWaypointIndex = 0; + /** + * The state the platform is currently in + */ + MovementPlatformState mState = MovementPlatformState::Stationary; - /** - * Whether the platform is currently reversing away from the desired waypoint - */ - bool mInReverse = false; + /** + * The waypoint this platform currently wants to traverse to + */ + int32_t mDesiredWaypointIndex = 0; - /** - * Whether the platform should stop moving when reaching the desired waypoint - */ - bool mShouldStopAtDesiredWaypoint = false; + /** + * Whether the platform is currently reversing away from the desired waypoint + */ + bool mInReverse = false; - /** - * The percentage of the way between the last point and the desired point - */ - float mPercentBetweenPoints = 0; + /** + * Whether the platform should stop moving when reaching the desired waypoint + */ + bool mShouldStopAtDesiredWaypoint = false; - /** - * The current position of the platofrm - */ - NiPoint3 mPosition {}; + /** + * The percentage of the way between the last point and the desired point + */ + float mPercentBetweenPoints = 0; - /** - * The waypoint the platform is (was) at - */ - uint32_t mCurrentWaypointIndex; + /** + * The current position of the platofrm + */ + NiPoint3 mPosition{}; - /** - * The waypoint the platform is attempting to go to - */ - uint32_t mNextWaypointIndex; + /** + * The waypoint the platform is (was) at + */ + uint32_t mCurrentWaypointIndex; - /** - * The timer that handles the time before stopping idling and continue platform movement - */ - float mIdleTimeElapsed = 0; + /** + * The waypoint the platform is attempting to go to + */ + uint32_t mNextWaypointIndex; - /** - * The speed the platform is currently moving at - */ - float mSpeed = 0; + /** + * The timer that handles the time before stopping idling and continue platform movement + */ + float mIdleTimeElapsed = 0; - /** - * The time to wait before continuing movement - */ - float mWaitTime = 0; + /** + * The speed the platform is currently moving at + */ + float mSpeed = 0; + + /** + * The time to wait before continuing movement + */ + float mWaitTime = 0; }; @@ -112,123 +112,123 @@ public: */ class MovingPlatformComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MOVING_PLATFORM; - - MovingPlatformComponent(Entity* parent, const std::string& pathName); - ~MovingPlatformComponent() override; - - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + static const uint32_t ComponentType = COMPONENT_TYPE_MOVING_PLATFORM; - /** - * Stops all pathing, called when an entity starts a quick build associated with this platform - */ - void OnRebuildInitilized(); + MovingPlatformComponent(Entity* parent, const std::string& pathName); + ~MovingPlatformComponent() override; - /** - * Starts the pathing, called when an entity completed a quick build associated with this platform - */ - void OnCompleteRebuild(); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Updates the movement state for the moving platform - * @param value the movement state to set - */ - void SetMovementState(MovementPlatformState value); + /** + * Stops all pathing, called when an entity starts a quick build associated with this platform + */ + void OnRebuildInitilized(); - /** - * Instructs the moving platform to go to some waypoint - * @param index the index of the waypoint - * @param stopAtWaypoint determines if the platform should stop at the waypoint - */ - void GotoWaypoint(uint32_t index, bool stopAtWaypoint = true); + /** + * Starts the pathing, called when an entity completed a quick build associated with this platform + */ + void OnCompleteRebuild(); - /** - * Starts the pathing of this platform, setting appropriate waypoints and speeds - */ - void StartPathing(); + /** + * Updates the movement state for the moving platform + * @param value the movement state to set + */ + void SetMovementState(MovementPlatformState value); - /** - * Continues the path of the platform, after it's been stopped - */ - void ContinuePathing(); + /** + * Instructs the moving platform to go to some waypoint + * @param index the index of the waypoint + * @param stopAtWaypoint determines if the platform should stop at the waypoint + */ + void GotoWaypoint(uint32_t index, bool stopAtWaypoint = true); - /** - * Stops the platform from moving, waiting for it to be activated again. - */ - void StopPathing(); + /** + * Starts the pathing of this platform, setting appropriate waypoints and speeds + */ + void StartPathing(); - /** - * Determines if the entity should be serialized on the next update - * @param value whether to serialize the entity or not - */ - void SetSerialized(bool value); + /** + * Continues the path of the platform, after it's been stopped + */ + void ContinuePathing(); - /** - * Returns if this platform will start automatically after spawn - * @return if this platform will start automatically after spawn - */ - bool GetNoAutoStart() const; + /** + * Stops the platform from moving, waiting for it to be activated again. + */ + void StopPathing(); - /** - * Sets the auto start value for this platform - * @param value the auto start value to set - */ - void SetNoAutoStart(bool value); + /** + * Determines if the entity should be serialized on the next update + * @param value whether to serialize the entity or not + */ + void SetSerialized(bool value); - /** - * Warps the platform to a waypoint index, skipping its current path - * @param index the index to go to - */ - void WarpToWaypoint(size_t index); + /** + * Returns if this platform will start automatically after spawn + * @return if this platform will start automatically after spawn + */ + bool GetNoAutoStart() const; - /** - * Returns the waypoint this platform was previously at - * @return the waypoint this platform was previously at - */ - size_t GetLastWaypointIndex() const; + /** + * Sets the auto start value for this platform + * @param value the auto start value to set + */ + void SetNoAutoStart(bool value); + + /** + * Warps the platform to a waypoint index, skipping its current path + * @param index the index to go to + */ + void WarpToWaypoint(size_t index); + + /** + * Returns the waypoint this platform was previously at + * @return the waypoint this platform was previously at + */ + size_t GetLastWaypointIndex() const; + + /** + * Returns the sub component that actually defines how the platform moves around (speeds, etc). + * @return the sub component that actually defines how the platform moves around + */ + MoverSubComponent* GetMoverSubComponent() const; - /** - * Returns the sub component that actually defines how the platform moves around (speeds, etc). - * @return the sub component that actually defines how the platform moves around - */ - MoverSubComponent* GetMoverSubComponent() const; - private: - /** - * The path this platform is currently on - */ - const Path* m_Path = nullptr; + /** + * The path this platform is currently on + */ + const Path* m_Path = nullptr; - /** - * The name of the path this platform is currently on - */ - std::u16string m_PathName; + /** + * The name of the path this platform is currently on + */ + std::u16string m_PathName; - /** - * Whether the platform has stopped pathing - */ - bool m_PathingStopped = false; + /** + * Whether the platform has stopped pathing + */ + bool m_PathingStopped = false; - /** - * The type of the subcomponent - */ - eMoverSubComponentType m_MoverSubComponentType; + /** + * The type of the subcomponent + */ + eMoverSubComponentType m_MoverSubComponentType; - /** - * The mover sub component that belongs to this platform - */ - void* m_MoverSubComponent; + /** + * The mover sub component that belongs to this platform + */ + void* m_MoverSubComponent; - /** - * Whether the platform shouldn't auto start - */ - bool m_NoAutoStart; + /** + * Whether the platform shouldn't auto start + */ + bool m_NoAutoStart; - /** - * Whether to serialize the entity on the next update - */ - bool m_Serialize = false; + /** + * Whether to serialize the entity on the next update + */ + bool m_Serialize = false; }; #endif // MOVINGPLATFORMCOMPONENT_H diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 0151fbf4..42aceaf3 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -20,860 +20,783 @@ #include "dChatFilter.h" #include "Database.h" -std::unordered_map PetComponent::buildCache {}; -std::unordered_map PetComponent::currentActivities {}; -std::unordered_map PetComponent::activePets {}; +std::unordered_map PetComponent::buildCache{}; +std::unordered_map PetComponent::currentActivities{}; +std::unordered_map PetComponent::activePets{}; /** * Maps all the pet lots to a flag indicating that the player has caught it. All basic pets have been guessed by ObjID * while the faction ones could be checked using their respective missions. */ std::map PetComponent::petFlags = { - { 3050, 801 }, // Elephant - { 3054, 803 }, // Cat - { 3195, 806 }, // Triceratops - { 3254, 807 }, // Terrier - { 3261, 811 }, // Skunk - { 3672, 813 }, // Bunny - { 3994, 814 }, // Crocodile - { 5635, 815 }, // Doberman - { 5636, 816 }, // Buffalo - { 5637, 818 }, // Robot Dog - { 5639, 819 }, // Red Dragon - { 5640, 820 }, // Tortoise - { 5641, 821 }, // Green Dragon - { 5643, 822 }, // Panda, see mission 786 - { 5642, 823 }, // Mantis - { 6720, 824 }, // Warthog - { 3520, 825 }, // Lion, see mission 1318 - { 7638, 826 }, // Goat - { 7694, 827 }, // Crab - { 12294, 829 }, // Reindeer - { 12431, 830 }, // Stegosaurus, see mission 1386 - { 12432, 831 }, // Saber cat, see mission 1389 - { 12433, 832 }, // Gryphon, see mission 1392 - { 12434, 833 }, // Alien, see mission 1188 - // 834: unknown?, see mission 506, 688 - { 16210, 836 }, // Ninjago Earth Dragon, see mission 1836 - { 13067, 838 }, // Skeleton dragon + { 3050, 801 }, // Elephant + { 3054, 803 }, // Cat + { 3195, 806 }, // Triceratops + { 3254, 807 }, // Terrier + { 3261, 811 }, // Skunk + { 3672, 813 }, // Bunny + { 3994, 814 }, // Crocodile + { 5635, 815 }, // Doberman + { 5636, 816 }, // Buffalo + { 5637, 818 }, // Robot Dog + { 5639, 819 }, // Red Dragon + { 5640, 820 }, // Tortoise + { 5641, 821 }, // Green Dragon + { 5643, 822 }, // Panda, see mission 786 + { 5642, 823 }, // Mantis + { 6720, 824 }, // Warthog + { 3520, 825 }, // Lion, see mission 1318 + { 7638, 826 }, // Goat + { 7694, 827 }, // Crab + { 12294, 829 }, // Reindeer + { 12431, 830 }, // Stegosaurus, see mission 1386 + { 12432, 831 }, // Saber cat, see mission 1389 + { 12433, 832 }, // Gryphon, see mission 1392 + { 12434, 833 }, // Alien, see mission 1188 + // 834: unknown?, see mission 506, 688 + { 16210, 836 }, // Ninjago Earth Dragon, see mission 1836 + { 13067, 838 }, // Skeleton dragon }; -PetComponent::PetComponent(Entity* parent, uint32_t componentId) : Component(parent) -{ - m_ComponentId = componentId; +PetComponent::PetComponent(Entity* parent, uint32_t componentId) : Component(parent) { + m_ComponentId = componentId; - m_Interaction = LWOOBJID_EMPTY; - m_Owner = LWOOBJID_EMPTY; - m_ModerationStatus = 0; - m_Tamer = LWOOBJID_EMPTY; - m_ModelId = LWOOBJID_EMPTY; - m_Timer = 0; - m_TimerAway = 0; - m_DatabaseId = LWOOBJID_EMPTY; - m_Status = 67108866; // Tamable - m_Ability = PetAbilityType::Invalid; - m_StartPosition = NiPoint3::ZERO; - m_MovementAI = nullptr; - m_TresureTime = 0; - m_Preconditions = nullptr; + m_Interaction = LWOOBJID_EMPTY; + m_Owner = LWOOBJID_EMPTY; + m_ModerationStatus = 0; + m_Tamer = LWOOBJID_EMPTY; + m_ModelId = LWOOBJID_EMPTY; + m_Timer = 0; + m_TimerAway = 0; + m_DatabaseId = LWOOBJID_EMPTY; + m_Status = 67108866; // Tamable + m_Ability = PetAbilityType::Invalid; + m_StartPosition = NiPoint3::ZERO; + m_MovementAI = nullptr; + m_TresureTime = 0; + m_Preconditions = nullptr; std::string checkPreconditions = GeneralUtils::UTF16ToWTF8(parent->GetVar(u"CheckPrecondition")); if (!checkPreconditions.empty()) { SetPreconditions(checkPreconditions); } - // Get the imagination drain rate from the CDClient - auto query = CDClientDatabase::CreatePreppedStmt("SELECT imaginationDrainRate FROM PetComponent WHERE id = ?;"); + // Get the imagination drain rate from the CDClient + auto query = CDClientDatabase::CreatePreppedStmt("SELECT imaginationDrainRate FROM PetComponent WHERE id = ?;"); - query.bind(1, static_cast(componentId)); + query.bind(1, static_cast(componentId)); - auto result = query.execQuery(); + auto result = query.execQuery(); - // Should a result not exist for this pet default to 60 seconds. - if (!result.eof() && !result.fieldIsNull(0)) { - imaginationDrainRate = result.getFloatField(0, 60.0f); - } else { - imaginationDrainRate = 60.0f; - } - result.finalize(); + // Should a result not exist for this pet default to 60 seconds. + if (!result.eof() && !result.fieldIsNull(0)) { + imaginationDrainRate = result.getFloatField(0, 60.0f); + } else { + imaginationDrainRate = 60.0f; + } + result.finalize(); } -void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) -{ - const bool tamed = m_Owner != LWOOBJID_EMPTY; +void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { + const bool tamed = m_Owner != LWOOBJID_EMPTY; - outBitStream->Write1(); // Always serialize as dirty for now + outBitStream->Write1(); // Always serialize as dirty for now - outBitStream->Write(static_cast(m_Status)); - outBitStream->Write(static_cast(tamed ? m_Ability : PetAbilityType::Invalid)); // Something with the overhead icon? + outBitStream->Write(static_cast(m_Status)); + outBitStream->Write(static_cast(tamed ? m_Ability : PetAbilityType::Invalid)); // Something with the overhead icon? - const bool interacting = m_Interaction != LWOOBJID_EMPTY; + const bool interacting = m_Interaction != LWOOBJID_EMPTY; - outBitStream->Write(interacting); - if (interacting) - { - outBitStream->Write(m_Interaction); - } + outBitStream->Write(interacting); + if (interacting) { + outBitStream->Write(m_Interaction); + } - outBitStream->Write(tamed); - if (tamed) - { - outBitStream->Write(m_Owner); - } + outBitStream->Write(tamed); + if (tamed) { + outBitStream->Write(m_Owner); + } - outBitStream->Write(tamed); - if (tamed) - { - outBitStream->Write(m_ModerationStatus); + outBitStream->Write(tamed); + if (tamed) { + outBitStream->Write(m_ModerationStatus); - const auto nameData = GeneralUtils::ASCIIToUTF16(m_Name); - const auto ownerNameData = GeneralUtils::ASCIIToUTF16(m_OwnerName); + const auto nameData = GeneralUtils::ASCIIToUTF16(m_Name); + const auto ownerNameData = GeneralUtils::ASCIIToUTF16(m_OwnerName); - outBitStream->Write(static_cast(nameData.size())); - for (const auto c : nameData) - { - outBitStream->Write(c); - } + outBitStream->Write(static_cast(nameData.size())); + for (const auto c : nameData) { + outBitStream->Write(c); + } - outBitStream->Write(static_cast(ownerNameData.size())); - for (const auto c : ownerNameData) - { - outBitStream->Write(c); - } - } + outBitStream->Write(static_cast(ownerNameData.size())); + for (const auto c : ownerNameData) { + outBitStream->Write(c); + } + } } -void PetComponent::OnUse(Entity* originator) -{ - if (m_Owner != LWOOBJID_EMPTY) - { - return; - } +void PetComponent::OnUse(Entity* originator) { + if (m_Owner != LWOOBJID_EMPTY) { + return; + } - if (m_Tamer != LWOOBJID_EMPTY) - { - auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); + if (m_Tamer != LWOOBJID_EMPTY) { + auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); - if (tamer != nullptr) - { - return; - } + if (tamer != nullptr) { + return; + } - m_Tamer = LWOOBJID_EMPTY; - } + m_Tamer = LWOOBJID_EMPTY; + } - auto* inventoryComponent = originator->GetComponent(); + auto* inventoryComponent = originator->GetComponent(); - if (inventoryComponent == nullptr) - { - return; - } + if (inventoryComponent == nullptr) { + return; + } - if (m_Preconditions != nullptr && !m_Preconditions->Check(originator, true)) { - return; - } + if (m_Preconditions != nullptr && !m_Preconditions->Check(originator, true)) { + return; + } - auto* movementAIComponent = m_Parent->GetComponent(); + auto* movementAIComponent = m_Parent->GetComponent(); - if (movementAIComponent != nullptr) - { - movementAIComponent->Stop(); - } + if (movementAIComponent != nullptr) { + movementAIComponent->Stop(); + } - inventoryComponent->DespawnPet(); + inventoryComponent->DespawnPet(); - const auto& cached = buildCache.find(m_Parent->GetLOT()); - int32_t imaginationCost = 0; + const auto& cached = buildCache.find(m_Parent->GetLOT()); + int32_t imaginationCost = 0; - std::string buildFile; + std::string buildFile; - if (cached == buildCache.end()) { - auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT ValidPiecesLXF, PuzzleModelLot, Timelimit, NumValidPieces, imagCostPerBuild FROM TamingBuildPuzzles WHERE NPCLot = ?;"); - query.bind(1, (int) m_Parent->GetLOT()); + if (cached == buildCache.end()) { + auto query = CDClientDatabase::CreatePreppedStmt( + "SELECT ValidPiecesLXF, PuzzleModelLot, Timelimit, NumValidPieces, imagCostPerBuild FROM TamingBuildPuzzles WHERE NPCLot = ?;"); + query.bind(1, (int)m_Parent->GetLOT()); - auto result = query.execQuery(); + auto result = query.execQuery(); - if (result.eof()) - { - ChatPackets::SendSystemMessage(originator->GetSystemAddress(), u"Failed to find the puzzle minigame for this pet."); + if (result.eof()) { + ChatPackets::SendSystemMessage(originator->GetSystemAddress(), u"Failed to find the puzzle minigame for this pet."); - return; - } + return; + } - if (result.fieldIsNull(0)) - { - result.finalize(); + if (result.fieldIsNull(0)) { + result.finalize(); - return; - } + return; + } - auto lxfAsset = std::string(result.getStringField(0)); + auto lxfAsset = std::string(result.getStringField(0)); - std::vector lxfAssetSplit = GeneralUtils::SplitString(lxfAsset, '\\'); + std::vector lxfAssetSplit = GeneralUtils::SplitString(lxfAsset, '\\'); - lxfAssetSplit.erase(lxfAssetSplit.begin()); + lxfAssetSplit.erase(lxfAssetSplit.begin()); - buildFile = "res/BrickModels"; + buildFile = "res/BrickModels"; - for (auto part: lxfAssetSplit) - { - std::transform(part.begin(), part.end(), part.begin(), [](unsigned char c) { - return std::tolower(c); - }); + for (auto part : lxfAssetSplit) { + std::transform(part.begin(), part.end(), part.begin(), [](unsigned char c) { + return std::tolower(c); + }); - buildFile += "/" + part; - } + buildFile += "/" + part; + } - PetPuzzleData data; - data.buildFile = buildFile; - data.puzzleModelLot = result.getIntField(1); - data.timeLimit = result.getFloatField(2); - data.numValidPieces = result.getIntField(3); - data.imaginationCost = result.getIntField(4); - if (data.timeLimit <= 0) data.timeLimit = 60; - imaginationCost = data.imaginationCost; + PetPuzzleData data; + data.buildFile = buildFile; + data.puzzleModelLot = result.getIntField(1); + data.timeLimit = result.getFloatField(2); + data.numValidPieces = result.getIntField(3); + data.imaginationCost = result.getIntField(4); + if (data.timeLimit <= 0) data.timeLimit = 60; + imaginationCost = data.imaginationCost; - buildCache[m_Parent->GetLOT()] = data; + buildCache[m_Parent->GetLOT()] = data; - result.finalize(); - } - else - { - buildFile = cached->second.buildFile; - imaginationCost = cached->second.imaginationCost; - } + result.finalize(); + } else { + buildFile = cached->second.buildFile; + imaginationCost = cached->second.imaginationCost; + } - auto* destroyableComponent = originator->GetComponent(); + auto* destroyableComponent = originator->GetComponent(); - if (destroyableComponent == nullptr) - { - return; - } + if (destroyableComponent == nullptr) { + return; + } - auto imagination = destroyableComponent->GetImagination(); + auto imagination = destroyableComponent->GetImagination(); - if (imagination < imaginationCost) - { - return; - } + if (imagination < imaginationCost) { + return; + } - auto& bricks = BrickDatabase::Instance()->GetBricks(buildFile); + auto& bricks = BrickDatabase::Instance()->GetBricks(buildFile); - if (bricks.empty()) - { - ChatPackets::SendSystemMessage(originator->GetSystemAddress(), u"Failed to load the puzzle minigame for this pet."); - Game::logger->Log("PetComponent", "Couldn't find %s for minigame!", buildFile.c_str()); + if (bricks.empty()) { + ChatPackets::SendSystemMessage(originator->GetSystemAddress(), u"Failed to load the puzzle minigame for this pet."); + Game::logger->Log("PetComponent", "Couldn't find %s for minigame!", buildFile.c_str()); - return; - } + return; + } - auto petPosition = m_Parent->GetPosition(); + auto petPosition = m_Parent->GetPosition(); - auto originatorPosition = originator->GetPosition(); + auto originatorPosition = originator->GetPosition(); - m_Parent->SetRotation(NiQuaternion::LookAt(petPosition, originatorPosition)); + m_Parent->SetRotation(NiQuaternion::LookAt(petPosition, originatorPosition)); - float interactionDistance = m_Parent->GetVar(u"interaction_distance"); + float interactionDistance = m_Parent->GetVar(u"interaction_distance"); - if (interactionDistance <= 0) - { - interactionDistance = 15; - } + if (interactionDistance <= 0) { + interactionDistance = 15; + } - auto position = originatorPosition; + auto position = originatorPosition; - NiPoint3 forward = NiQuaternion::LookAt(m_Parent->GetPosition(), originator->GetPosition()).GetForwardVector(); - forward.y = 0; + NiPoint3 forward = NiQuaternion::LookAt(m_Parent->GetPosition(), originator->GetPosition()).GetForwardVector(); + forward.y = 0; - if (dpWorld::Instance().IsLoaded()) - { - NiPoint3 attempt = petPosition + forward * interactionDistance; + if (dpWorld::Instance().IsLoaded()) { + NiPoint3 attempt = petPosition + forward * interactionDistance; - float y = dpWorld::Instance().GetHeightAtPoint(attempt); + float y = dpWorld::Instance().GetHeightAtPoint(attempt); - while (std::abs(y - petPosition.y) > 4 && interactionDistance > 10) - { - const NiPoint3 forward = m_Parent->GetRotation().GetForwardVector(); + while (std::abs(y - petPosition.y) > 4 && interactionDistance > 10) { + const NiPoint3 forward = m_Parent->GetRotation().GetForwardVector(); - attempt = originatorPosition + forward * interactionDistance; + attempt = originatorPosition + forward * interactionDistance; - y = dpWorld::Instance().GetHeightAtPoint(attempt); + y = dpWorld::Instance().GetHeightAtPoint(attempt); - interactionDistance -= 0.5f; - } + interactionDistance -= 0.5f; + } - position = attempt; - } - else - { - position = petPosition + forward * interactionDistance; - } + position = attempt; + } else { + position = petPosition + forward * interactionDistance; + } - auto rotation = NiQuaternion::LookAt(position, petPosition); + auto rotation = NiQuaternion::LookAt(position, petPosition); - GameMessages::SendNotifyPetTamingMinigame( - originator->GetObjectID(), - m_Parent->GetObjectID(), - LWOOBJID_EMPTY, - true, - NOTIFY_TYPE_BEGIN, - petPosition, - position, - rotation, - UNASSIGNED_SYSTEM_ADDRESS - ); + GameMessages::SendNotifyPetTamingMinigame( + originator->GetObjectID(), + m_Parent->GetObjectID(), + LWOOBJID_EMPTY, + true, + NOTIFY_TYPE_BEGIN, + petPosition, + position, + rotation, + UNASSIGNED_SYSTEM_ADDRESS + ); - GameMessages::SendNotifyPetTamingMinigame( - m_Parent->GetObjectID(), - LWOOBJID_EMPTY, - originator->GetObjectID(), - true, - NOTIFY_TYPE_BEGIN, - petPosition, - position, - rotation, - UNASSIGNED_SYSTEM_ADDRESS - ); + GameMessages::SendNotifyPetTamingMinigame( + m_Parent->GetObjectID(), + LWOOBJID_EMPTY, + originator->GetObjectID(), + true, + NOTIFY_TYPE_BEGIN, + petPosition, + position, + rotation, + UNASSIGNED_SYSTEM_ADDRESS + ); - GameMessages::SendNotifyPetTamingPuzzleSelected(originator->GetObjectID(), bricks, originator->GetSystemAddress()); + GameMessages::SendNotifyPetTamingPuzzleSelected(originator->GetObjectID(), bricks, originator->GetSystemAddress()); - m_Tamer = originator->GetObjectID(); - SetStatus(5); + m_Tamer = originator->GetObjectID(); + SetStatus(5); - currentActivities.insert_or_assign(m_Tamer, m_Parent->GetObjectID()); + currentActivities.insert_or_assign(m_Tamer, m_Parent->GetObjectID()); - // Notify the start of a pet taming minigame - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, originator, NOTIFY_TYPE_BEGIN); - } + // Notify the start of a pet taming minigame + for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { + script->OnNotifyPetTamingMinigame(m_Parent, originator, NOTIFY_TYPE_BEGIN); + } } -void PetComponent::Update(float deltaTime) -{ - if (m_StartPosition == NiPoint3::ZERO) - { - m_StartPosition = m_Parent->GetPosition(); - } +void PetComponent::Update(float deltaTime) { + if (m_StartPosition == NiPoint3::ZERO) { + m_StartPosition = m_Parent->GetPosition(); + } - if (m_Owner == LWOOBJID_EMPTY) - { - if (m_Tamer != LWOOBJID_EMPTY) - { - if (m_Timer > 0) - { - m_Timer -= deltaTime; + if (m_Owner == LWOOBJID_EMPTY) { + if (m_Tamer != LWOOBJID_EMPTY) { + if (m_Timer > 0) { + m_Timer -= deltaTime; - if (m_Timer <= 0) - { - m_Timer = 0; + if (m_Timer <= 0) { + m_Timer = 0; - ClientFailTamingMinigame(); - } - } - } - else - { - if (m_Timer > 0) - { - m_Timer -= deltaTime; + ClientFailTamingMinigame(); + } + } + } else { + if (m_Timer > 0) { + m_Timer -= deltaTime; - if (m_Timer <= 0) - { - Wander(); - EntityManager::Instance()->SerializeEntity(m_Parent); - } - } - else - { - m_Timer = 5; - } - } + if (m_Timer <= 0) { + Wander(); + EntityManager::Instance()->SerializeEntity(m_Parent); + } + } else { + m_Timer = 5; + } + } - return; - } + return; + } - auto* owner = GetOwner(); + auto* owner = GetOwner(); - if (owner == nullptr) - { - m_Parent->Kill(); + if (owner == nullptr) { + m_Parent->Kill(); - return; - } + return; + } - m_MovementAI = m_Parent->GetComponent(); + m_MovementAI = m_Parent->GetComponent(); - if (m_MovementAI == nullptr) - { - return; - } + if (m_MovementAI == nullptr) { + return; + } - if (m_TresureTime > 0) - { - auto* tresure = EntityManager::Instance()->GetEntity(m_Interaction); + if (m_TresureTime > 0) { + auto* tresure = EntityManager::Instance()->GetEntity(m_Interaction); - if (tresure == nullptr) - { - m_TresureTime = 0; + if (tresure == nullptr) { + m_TresureTime = 0; - return; - } + return; + } - m_TresureTime -= deltaTime; + m_TresureTime -= deltaTime; - m_MovementAI->Stop(); + m_MovementAI->Stop(); - if (m_TresureTime <= 0) - { - m_Parent->SetOwnerOverride(m_Owner); + if (m_TresureTime <= 0) { + m_Parent->SetOwnerOverride(m_Owner); - tresure->Smash(m_Parent->GetObjectID()); + tresure->Smash(m_Parent->GetObjectID()); - m_Interaction = LWOOBJID_EMPTY; + m_Interaction = LWOOBJID_EMPTY; - m_TresureTime = 0; - } + m_TresureTime = 0; + } - return; - } + return; + } - auto destination = owner->GetPosition(); - NiPoint3 position = m_MovementAI->GetCurrentPosition(); + auto destination = owner->GetPosition(); + NiPoint3 position = m_MovementAI->GetCurrentPosition(); - float distanceToOwner = Vector3::DistanceSquared(position, destination); + float distanceToOwner = Vector3::DistanceSquared(position, destination); - if (distanceToOwner > 50 * 50 || m_TimerAway > 5) - { - m_MovementAI->Warp(destination); + if (distanceToOwner > 50 * 50 || m_TimerAway > 5) { + m_MovementAI->Warp(destination); - m_Timer = 1; - m_TimerAway = 0; + m_Timer = 1; + m_TimerAway = 0; - return; - } + return; + } - if (distanceToOwner > 15 * 15 || std::abs(destination.y - position.y) >= 3) - { - m_TimerAway += deltaTime; - } - else - { - m_TimerAway = 0; - } + if (distanceToOwner > 15 * 15 || std::abs(destination.y - position.y) >= 3) { + m_TimerAway += deltaTime; + } else { + m_TimerAway = 0; + } - if (m_Timer > 0) - { - m_Timer -= deltaTime; + if (m_Timer > 0) { + m_Timer -= deltaTime; - return; - } + return; + } - SwitchComponent* closestSwitch = SwitchComponent::GetClosestSwitch(position); + SwitchComponent* closestSwitch = SwitchComponent::GetClosestSwitch(position); - float haltDistance = 5; + float haltDistance = 5; - if (closestSwitch != nullptr) - { - if (!closestSwitch->GetActive()) - { - NiPoint3 switchPosition = closestSwitch->GetParentEntity()->GetPosition(); - float distance = Vector3::DistanceSquared(position, switchPosition); - if (distance < 3 * 3) - { - m_Interaction = closestSwitch->GetParentEntity()->GetObjectID(); - closestSwitch->EntityEnter(m_Parent); - } - else if (distance < 20 * 20) - { - haltDistance = 1; + if (closestSwitch != nullptr) { + if (!closestSwitch->GetActive()) { + NiPoint3 switchPosition = closestSwitch->GetParentEntity()->GetPosition(); + float distance = Vector3::DistanceSquared(position, switchPosition); + if (distance < 3 * 3) { + m_Interaction = closestSwitch->GetParentEntity()->GetObjectID(); + closestSwitch->EntityEnter(m_Parent); + } else if (distance < 20 * 20) { + haltDistance = 1; - destination = switchPosition; - } - } - } + destination = switchPosition; + } + } + } - Entity* closestTresure = PetDigServer::GetClosestTresure(position); + Entity* closestTresure = PetDigServer::GetClosestTresure(position); - if (closestTresure != nullptr) - { - // Skeleton Dragon Pat special case for bone digging - if (closestTresure->GetLOT() == 12192 && m_Parent->GetLOT() != 13067) - { - goto skipTresure; - } + if (closestTresure != nullptr) { + // Skeleton Dragon Pat special case for bone digging + if (closestTresure->GetLOT() == 12192 && m_Parent->GetLOT() != 13067) { + goto skipTresure; + } - NiPoint3 tresurePosition = closestTresure->GetPosition(); - float distance = Vector3::DistanceSquared(position, tresurePosition); - if (distance < 3 * 3) - { - m_Interaction = closestTresure->GetObjectID(); + NiPoint3 tresurePosition = closestTresure->GetPosition(); + float distance = Vector3::DistanceSquared(position, tresurePosition); + if (distance < 3 * 3) { + m_Interaction = closestTresure->GetObjectID(); - Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 1, 202, true); + Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 1, 202, true); - m_TresureTime = 2; - } - else if (distance < 10 * 10) - { - haltDistance = 1; + m_TresureTime = 2; + } else if (distance < 10 * 10) { + haltDistance = 1; - destination = tresurePosition; - } - } + destination = tresurePosition; + } + } - skipTresure: +skipTresure: - m_MovementAI->SetHaltDistance(haltDistance); + m_MovementAI->SetHaltDistance(haltDistance); - m_MovementAI->SetSpeed(2.5f); + m_MovementAI->SetSpeed(2.5f); - m_MovementAI->SetDestination(destination); + m_MovementAI->SetDestination(destination); - m_Timer = 1; + m_Timer = 1; } void PetComponent::TryBuild(uint32_t numBricks, bool clientFailed) { - if (m_Tamer == LWOOBJID_EMPTY) return; + if (m_Tamer == LWOOBJID_EMPTY) return; - auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); + auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); - if (tamer == nullptr) { - m_Tamer = LWOOBJID_EMPTY; + if (tamer == nullptr) { + m_Tamer = LWOOBJID_EMPTY; - return; - } + return; + } - const auto& cached = buildCache.find(m_Parent->GetLOT()); + const auto& cached = buildCache.find(m_Parent->GetLOT()); - if (cached == buildCache.end()) return; + if (cached == buildCache.end()) return; - auto* destroyableComponent = tamer->GetComponent(); + auto* destroyableComponent = tamer->GetComponent(); - if (destroyableComponent == nullptr) return; + if (destroyableComponent == nullptr) return; - auto imagination = destroyableComponent->GetImagination(); + auto imagination = destroyableComponent->GetImagination(); - imagination -= cached->second.imaginationCost; + imagination -= cached->second.imaginationCost; - destroyableComponent->SetImagination(imagination); + destroyableComponent->SetImagination(imagination); - EntityManager::Instance()->SerializeEntity(tamer); + EntityManager::Instance()->SerializeEntity(tamer); - if (clientFailed) { - if (imagination < cached->second.imaginationCost) { - ClientFailTamingMinigame(); - } - } else { - m_Timer = 0; - } + if (clientFailed) { + if (imagination < cached->second.imaginationCost) { + ClientFailTamingMinigame(); + } + } else { + m_Timer = 0; + } - if (numBricks == 0) return; + if (numBricks == 0) return; - GameMessages::SendPetTamingTryBuildResult(m_Tamer, !clientFailed, numBricks, tamer->GetSystemAddress()); + GameMessages::SendPetTamingTryBuildResult(m_Tamer, !clientFailed, numBricks, tamer->GetSystemAddress()); } -void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) -{ - if (m_Tamer == LWOOBJID_EMPTY) return; +void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { + if (m_Tamer == LWOOBJID_EMPTY) return; - auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); + auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); - if (tamer == nullptr) - { - m_Tamer = LWOOBJID_EMPTY; + if (tamer == nullptr) { + m_Tamer = LWOOBJID_EMPTY; - return; - } + return; + } - const auto& cached = buildCache.find(m_Parent->GetLOT()); + const auto& cached = buildCache.find(m_Parent->GetLOT()); - if (cached == buildCache.end()) - { - return; - } + if (cached == buildCache.end()) { + return; + } - GameMessages::SendPlayFXEffect(tamer, -1, u"petceleb", "", LWOOBJID_EMPTY, 1, 1, true); - GameMessages::SendPlayAnimation(tamer, u"rebuild-celebrate"); + GameMessages::SendPlayFXEffect(tamer, -1, u"petceleb", "", LWOOBJID_EMPTY, 1, 1, true); + GameMessages::SendPlayAnimation(tamer, u"rebuild-celebrate"); - EntityInfo info {}; - info.lot = cached->second.puzzleModelLot; - info.pos = position; - info.rot = NiQuaternion::IDENTITY; - info.spawnerID = tamer->GetObjectID(); + EntityInfo info{}; + info.lot = cached->second.puzzleModelLot; + info.pos = position; + info.rot = NiQuaternion::IDENTITY; + info.spawnerID = tamer->GetObjectID(); - auto* modelEntity = EntityManager::Instance()->CreateEntity(info); + auto* modelEntity = EntityManager::Instance()->CreateEntity(info); - m_ModelId = modelEntity->GetObjectID(); + m_ModelId = modelEntity->GetObjectID(); - EntityManager::Instance()->ConstructEntity(modelEntity); + EntityManager::Instance()->ConstructEntity(modelEntity); - GameMessages::SendNotifyTamingModelLoadedOnServer(m_Tamer, tamer->GetSystemAddress()); + GameMessages::SendNotifyTamingModelLoadedOnServer(m_Tamer, tamer->GetSystemAddress()); - GameMessages::SendPetResponse(m_Tamer, m_Parent->GetObjectID(), 0, 10, 0, tamer->GetSystemAddress()); + GameMessages::SendPetResponse(m_Tamer, m_Parent->GetObjectID(), 0, 10, 0, tamer->GetSystemAddress()); - auto* inventoryComponent = tamer->GetComponent(); + auto* inventoryComponent = tamer->GetComponent(); - if (inventoryComponent == nullptr) - { - return; - } + if (inventoryComponent == nullptr) { + return; + } - LWOOBJID petSubKey = ObjectIDManager::Instance()->GenerateRandomObjectID(); + LWOOBJID petSubKey = ObjectIDManager::Instance()->GenerateRandomObjectID(); petSubKey = GeneralUtils::SetBit(petSubKey, OBJECT_BIT_CHARACTER); petSubKey = GeneralUtils::SetBit(petSubKey, OBJECT_BIT_PERSISTENT); - m_DatabaseId = petSubKey; + m_DatabaseId = petSubKey; - std::string petName = tamer->GetCharacter()->GetName(); - petName += "'s Pet"; + std::string petName = tamer->GetCharacter()->GetName(); + petName += "'s Pet"; - GameMessages::SendAddPetToPlayer(m_Tamer, 0, GeneralUtils::ASCIIToUTF16(petName), petSubKey, m_Parent->GetLOT(), tamer->GetSystemAddress()); + GameMessages::SendAddPetToPlayer(m_Tamer, 0, GeneralUtils::ASCIIToUTF16(petName), petSubKey, m_Parent->GetLOT(), tamer->GetSystemAddress()); - GameMessages::SendRegisterPetID(m_Tamer, m_Parent->GetObjectID(), tamer->GetSystemAddress()); + GameMessages::SendRegisterPetID(m_Tamer, m_Parent->GetObjectID(), tamer->GetSystemAddress()); - GameMessages::SendRegisterPetDBID(m_Tamer, petSubKey, tamer->GetSystemAddress()); + GameMessages::SendRegisterPetDBID(m_Tamer, petSubKey, tamer->GetSystemAddress()); - inventoryComponent->AddItem(m_Parent->GetLOT(), 1, eLootSourceType::LOOT_SOURCE_ACTIVITY, eInventoryType::MODELS, {}, LWOOBJID_EMPTY, true, false, petSubKey); - auto* item = inventoryComponent->FindItemBySubKey(petSubKey, MODELS); + inventoryComponent->AddItem(m_Parent->GetLOT(), 1, eLootSourceType::LOOT_SOURCE_ACTIVITY, eInventoryType::MODELS, {}, LWOOBJID_EMPTY, true, false, petSubKey); + auto* item = inventoryComponent->FindItemBySubKey(petSubKey, MODELS); - if (item == nullptr) - { - return; - } + if (item == nullptr) { + return; + } - DatabasePet databasePet {}; + DatabasePet databasePet{}; - databasePet.lot = m_Parent->GetLOT(); - databasePet.moderationState = 1; - databasePet.name = petName; + databasePet.lot = m_Parent->GetLOT(); + databasePet.moderationState = 1; + databasePet.name = petName; - inventoryComponent->SetDatabasePet(petSubKey, databasePet); + inventoryComponent->SetDatabasePet(petSubKey, databasePet); - Activate(item, false, true); + Activate(item, false, true); - m_Timer = 0; + m_Timer = 0; - GameMessages::SendNotifyPetTamingMinigame( - m_Tamer, - LWOOBJID_EMPTY, - LWOOBJID_EMPTY, - false, - NOTIFY_TYPE_NAMINGPET, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, - UNASSIGNED_SYSTEM_ADDRESS - ); + GameMessages::SendNotifyPetTamingMinigame( + m_Tamer, + LWOOBJID_EMPTY, + LWOOBJID_EMPTY, + false, + NOTIFY_TYPE_NAMINGPET, + NiPoint3::ZERO, + NiPoint3::ZERO, + NiQuaternion::IDENTITY, + UNASSIGNED_SYSTEM_ADDRESS + ); - // Triggers the catch a pet missions - if (petFlags.find(m_Parent->GetLOT()) != petFlags.end()) { - tamer->GetCharacter()->SetPlayerFlag(petFlags.at(m_Parent->GetLOT()), true); - } + // Triggers the catch a pet missions + if (petFlags.find(m_Parent->GetLOT()) != petFlags.end()) { + tamer->GetCharacter()->SetPlayerFlag(petFlags.at(m_Parent->GetLOT()), true); + } - auto* missionComponent = tamer->GetComponent(); + auto* missionComponent = tamer->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_PET_TAMING, m_Parent->GetLOT()); - } + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_PET_TAMING, m_Parent->GetLOT()); + } - SetStatus(1); + SetStatus(1); - auto* characterComponent = tamer->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(PetsTamed); - } + auto* characterComponent = tamer->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(PetsTamed); + } } -void PetComponent::RequestSetPetName(std::u16string name) -{ - if (m_Tamer == LWOOBJID_EMPTY) - { - if (m_Owner != LWOOBJID_EMPTY) - { - auto* owner = GetOwner(); +void PetComponent::RequestSetPetName(std::u16string name) { + if (m_Tamer == LWOOBJID_EMPTY) { + if (m_Owner != LWOOBJID_EMPTY) { + auto* owner = GetOwner(); - m_ModerationStatus = 1; // Pending - m_Name = ""; + m_ModerationStatus = 1; // Pending + m_Name = ""; - //Save our pet's new name to the db: - SetPetNameForModeration(GeneralUtils::UTF16ToWTF8(name)); + //Save our pet's new name to the db: + SetPetNameForModeration(GeneralUtils::UTF16ToWTF8(name)); - GameMessages::SendSetPetName(m_Owner, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); - GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); - } + GameMessages::SendSetPetName(m_Owner, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); + GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); + } - return; - } + return; + } - auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); + auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); - if (tamer == nullptr) - { - m_Tamer = LWOOBJID_EMPTY; + if (tamer == nullptr) { + m_Tamer = LWOOBJID_EMPTY; - return; - } + return; + } - Game::logger->Log("PetComponent", "Got set pet name (%s)", GeneralUtils::UTF16ToWTF8(name).c_str()); + Game::logger->Log("PetComponent", "Got set pet name (%s)", GeneralUtils::UTF16ToWTF8(name).c_str()); - auto* inventoryComponent = tamer->GetComponent(); + auto* inventoryComponent = tamer->GetComponent(); - if (inventoryComponent == nullptr) - { - return; - } + if (inventoryComponent == nullptr) { + return; + } - m_ModerationStatus = 1; // Pending - m_Name = ""; + m_ModerationStatus = 1; // Pending + m_Name = ""; - //Save our pet's new name to the db: - SetPetNameForModeration(GeneralUtils::UTF16ToWTF8(name)); + //Save our pet's new name to the db: + SetPetNameForModeration(GeneralUtils::UTF16ToWTF8(name)); - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - GameMessages::SendSetPetName(m_Tamer, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, tamer->GetSystemAddress()); - GameMessages::SendSetPetName(m_Tamer, GeneralUtils::ASCIIToUTF16(m_Name), LWOOBJID_EMPTY, tamer->GetSystemAddress()); - GameMessages::SendPetNameChanged(m_Parent->GetObjectID(), m_ModerationStatus, GeneralUtils::ASCIIToUTF16(m_Name), GeneralUtils::ASCIIToUTF16(m_OwnerName), UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendSetPetNameModerated(m_Tamer, m_DatabaseId, m_ModerationStatus, tamer->GetSystemAddress()); + GameMessages::SendSetPetName(m_Tamer, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, tamer->GetSystemAddress()); + GameMessages::SendSetPetName(m_Tamer, GeneralUtils::ASCIIToUTF16(m_Name), LWOOBJID_EMPTY, tamer->GetSystemAddress()); + GameMessages::SendPetNameChanged(m_Parent->GetObjectID(), m_ModerationStatus, GeneralUtils::ASCIIToUTF16(m_Name), GeneralUtils::ASCIIToUTF16(m_OwnerName), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendSetPetNameModerated(m_Tamer, m_DatabaseId, m_ModerationStatus, tamer->GetSystemAddress()); - GameMessages::SendNotifyPetTamingMinigame( - m_Tamer, - m_Parent->GetObjectID(), - m_Tamer, - false, - NOTIFY_TYPE_SUCCESS, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, - UNASSIGNED_SYSTEM_ADDRESS - ); + GameMessages::SendNotifyPetTamingMinigame( + m_Tamer, + m_Parent->GetObjectID(), + m_Tamer, + false, + NOTIFY_TYPE_SUCCESS, + NiPoint3::ZERO, + NiPoint3::ZERO, + NiQuaternion::IDENTITY, + UNASSIGNED_SYSTEM_ADDRESS + ); - GameMessages::SendTerminateInteraction(m_Tamer, eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); + GameMessages::SendTerminateInteraction(m_Tamer, eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); - auto* modelEntity = EntityManager::Instance()->GetEntity(m_ModelId); + auto* modelEntity = EntityManager::Instance()->GetEntity(m_ModelId); - if (modelEntity != nullptr) - { - modelEntity->Smash(m_Tamer); - } + if (modelEntity != nullptr) { + modelEntity->Smash(m_Tamer); + } - currentActivities.erase(m_Tamer); + currentActivities.erase(m_Tamer); - m_Tamer = LWOOBJID_EMPTY; + m_Tamer = LWOOBJID_EMPTY; - // Notify the end of a pet taming minigame - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_SUCCESS); - } + // Notify the end of a pet taming minigame + for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { + script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_SUCCESS); + } } -void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) -{ - if (m_Tamer == LWOOBJID_EMPTY) return; +void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) { + if (m_Tamer == LWOOBJID_EMPTY) return; - auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); + auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); - if (tamer == nullptr) - { - m_Tamer = LWOOBJID_EMPTY; + if (tamer == nullptr) { + m_Tamer = LWOOBJID_EMPTY; - return; - } + return; + } - GameMessages::SendNotifyPetTamingMinigame( - m_Tamer, - m_Parent->GetObjectID(), - m_Tamer, - false, - NOTIFY_TYPE_QUIT, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, - UNASSIGNED_SYSTEM_ADDRESS - ); + GameMessages::SendNotifyPetTamingMinigame( + m_Tamer, + m_Parent->GetObjectID(), + m_Tamer, + false, + NOTIFY_TYPE_QUIT, + NiPoint3::ZERO, + NiPoint3::ZERO, + NiQuaternion::IDENTITY, + UNASSIGNED_SYSTEM_ADDRESS + ); - GameMessages::SendNotifyTamingModelLoadedOnServer(m_Tamer, tamer->GetSystemAddress()); + GameMessages::SendNotifyTamingModelLoadedOnServer(m_Tamer, tamer->GetSystemAddress()); - GameMessages::SendTerminateInteraction(m_Tamer, eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); + GameMessages::SendTerminateInteraction(m_Tamer, eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); - currentActivities.erase(m_Tamer); + currentActivities.erase(m_Tamer); - SetStatus(67108866); - m_Tamer = LWOOBJID_EMPTY; - m_Timer = 0; + SetStatus(67108866); + m_Tamer = LWOOBJID_EMPTY; + m_Timer = 0; - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - // Notify the end of a pet taming minigame - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_QUIT); - } + // Notify the end of a pet taming minigame + for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { + script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_QUIT); + } } -void PetComponent::StartTimer() -{ - const auto& cached = buildCache.find(m_Parent->GetLOT()); +void PetComponent::StartTimer() { + const auto& cached = buildCache.find(m_Parent->GetLOT()); - if (cached == buildCache.end()) - { - return; - } + if (cached == buildCache.end()) { + return; + } - m_Timer = cached->second.timeLimit; + m_Timer = cached->second.timeLimit; } -void PetComponent::ClientFailTamingMinigame() -{ - if (m_Tamer == LWOOBJID_EMPTY) return; +void PetComponent::ClientFailTamingMinigame() { + if (m_Tamer == LWOOBJID_EMPTY) return; - auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); + auto* tamer = EntityManager::Instance()->GetEntity(m_Tamer); - if (tamer == nullptr) - { - m_Tamer = LWOOBJID_EMPTY; + if (tamer == nullptr) { + m_Tamer = LWOOBJID_EMPTY; - return; - } + return; + } - GameMessages::SendNotifyPetTamingMinigame( - m_Tamer, - m_Parent->GetObjectID(), - m_Tamer, - false, - NOTIFY_TYPE_FAILED, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, - UNASSIGNED_SYSTEM_ADDRESS - ); + GameMessages::SendNotifyPetTamingMinigame( + m_Tamer, + m_Parent->GetObjectID(), + m_Tamer, + false, + NOTIFY_TYPE_FAILED, + NiPoint3::ZERO, + NiPoint3::ZERO, + NiQuaternion::IDENTITY, + UNASSIGNED_SYSTEM_ADDRESS + ); - GameMessages::SendNotifyTamingModelLoadedOnServer(m_Tamer, tamer->GetSystemAddress()); + GameMessages::SendNotifyTamingModelLoadedOnServer(m_Tamer, tamer->GetSystemAddress()); - GameMessages::SendTerminateInteraction(m_Tamer, eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); + GameMessages::SendTerminateInteraction(m_Tamer, eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); - currentActivities.erase(m_Tamer); + currentActivities.erase(m_Tamer); - SetStatus(67108866); - m_Tamer = LWOOBJID_EMPTY; - m_Timer = 0; + SetStatus(67108866); + m_Tamer = LWOOBJID_EMPTY; + m_Timer = 0; - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - // Notify the end of a pet taming minigame - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_FAILED); - } + // Notify the end of a pet taming minigame + for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { + script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_FAILED); + } } -void PetComponent::Wander() -{ - m_MovementAI = m_Parent->GetComponent(); +void PetComponent::Wander() { + m_MovementAI = m_Parent->GetComponent(); - if (m_MovementAI == nullptr || !m_MovementAI->AtFinalWaypoint()) { - return; + if (m_MovementAI == nullptr || !m_MovementAI->AtFinalWaypoint()) { + return; } m_MovementAI->SetHaltDistance(0); @@ -912,325 +835,294 @@ void PetComponent::Wander() m_Timer += (m_MovementAI->GetCurrentPosition().x - destination.x) / info.wanderSpeed; } -void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) -{ - AddDrainImaginationTimer(item, fromTaming); +void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) { + AddDrainImaginationTimer(item, fromTaming); - m_ItemId = item->GetId(); - m_DatabaseId = item->GetSubKey(); + m_ItemId = item->GetId(); + m_DatabaseId = item->GetSubKey(); - auto* inventoryComponent = item->GetInventory()->GetComponent(); + auto* inventoryComponent = item->GetInventory()->GetComponent(); - if (inventoryComponent == nullptr) return; + if (inventoryComponent == nullptr) return; - inventoryComponent->DespawnPet(); + inventoryComponent->DespawnPet(); - m_Owner = inventoryComponent->GetParent()->GetObjectID(); + m_Owner = inventoryComponent->GetParent()->GetObjectID(); - auto* owner = GetOwner(); + auto* owner = GetOwner(); - if (owner == nullptr) return; - SetStatus(1); + if (owner == nullptr) return; + SetStatus(1); - auto databaseData = inventoryComponent->GetDatabasePet(m_DatabaseId); + auto databaseData = inventoryComponent->GetDatabasePet(m_DatabaseId); - m_ModerationStatus = databaseData.moderationState; + m_ModerationStatus = databaseData.moderationState; - bool updatedModerationStatus = false; + bool updatedModerationStatus = false; - //Load mod status from db: - if (m_ModerationStatus != 2) - { - LoadPetNameFromModeration(); + //Load mod status from db: + if (m_ModerationStatus != 2) { + LoadPetNameFromModeration(); - databaseData.name = m_Name; - databaseData.moderationState = m_ModerationStatus; + databaseData.name = m_Name; + databaseData.moderationState = m_ModerationStatus; - inventoryComponent->SetDatabasePet(m_DatabaseId, databaseData); + inventoryComponent->SetDatabasePet(m_DatabaseId, databaseData); - updatedModerationStatus = true; - } - else - { - m_Name = databaseData.name; - } + updatedModerationStatus = true; + } else { + m_Name = databaseData.name; + } - m_OwnerName = owner->GetCharacter()->GetName(); + m_OwnerName = owner->GetCharacter()->GetName(); - if (updatedModerationStatus) - { - GameMessages::SendSetPetName(m_Owner, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); - GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); - } + if (updatedModerationStatus) { + GameMessages::SendSetPetName(m_Owner, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); + GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); + } - GameMessages::SendMarkInventoryItemAsActive(m_Owner, true, 0, m_ItemId, GetOwner()->GetSystemAddress()); + GameMessages::SendMarkInventoryItemAsActive(m_Owner, true, 0, m_ItemId, GetOwner()->GetSystemAddress()); - activePets[m_Owner] = m_Parent->GetObjectID(); + activePets[m_Owner] = m_Parent->GetObjectID(); - m_Timer = 3; + m_Timer = 3; - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - owner->GetCharacter()->SetPlayerFlag(69, true); + owner->GetCharacter()->SetPlayerFlag(69, true); - if (registerPet) - { - GameMessages::SendAddPetToPlayer(m_Owner, 0, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, m_Parent->GetLOT(), owner->GetSystemAddress()); + if (registerPet) { + GameMessages::SendAddPetToPlayer(m_Owner, 0, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, m_Parent->GetLOT(), owner->GetSystemAddress()); - GameMessages::SendRegisterPetID(m_Owner, m_Parent->GetObjectID(), owner->GetSystemAddress()); + GameMessages::SendRegisterPetID(m_Owner, m_Parent->GetObjectID(), owner->GetSystemAddress()); - GameMessages::SendRegisterPetDBID(m_Owner, m_DatabaseId, owner->GetSystemAddress()); - } + GameMessages::SendRegisterPetDBID(m_Owner, m_DatabaseId, owner->GetSystemAddress()); + } - GameMessages::SendShowPetActionButton(m_Owner, 3, true, owner->GetSystemAddress()); + GameMessages::SendShowPetActionButton(m_Owner, 3, true, owner->GetSystemAddress()); } void PetComponent::AddDrainImaginationTimer(Item* item, bool fromTaming) { - if (Game::config->GetValue("pets_take_imagination") != "1") return; + if (Game::config->GetValue("pets_take_imagination") != "1") return; - auto playerInventory = item->GetInventory(); - if (!playerInventory) return; + auto playerInventory = item->GetInventory(); + if (!playerInventory) return; - auto playerInventoryComponent = playerInventory->GetComponent(); - if (!playerInventoryComponent) return; + auto playerInventoryComponent = playerInventory->GetComponent(); + if (!playerInventoryComponent) return; - auto playerEntity = playerInventoryComponent->GetParent(); - if (!playerEntity) return; + auto playerEntity = playerInventoryComponent->GetParent(); + if (!playerEntity) return; - auto playerDestroyableComponent = playerEntity->GetComponent(); - if (!playerDestroyableComponent) return; + auto playerDestroyableComponent = playerEntity->GetComponent(); + if (!playerDestroyableComponent) return; - // Drain by 1 when you summon pet or when this method is called, but not when we have just tamed this pet. - if (!fromTaming) playerDestroyableComponent->Imagine(-1); + // Drain by 1 when you summon pet or when this method is called, but not when we have just tamed this pet. + if (!fromTaming) playerDestroyableComponent->Imagine(-1); - // Set this to a variable so when this is called back from the player the timer doesn't fire off. - m_Parent->AddCallbackTimer(imaginationDrainRate, [playerDestroyableComponent, this, item](){ - if (!playerDestroyableComponent) { - Game::logger->Log("PetComponent", "No petComponent and/or no playerDestroyableComponent"); - return; - } + // Set this to a variable so when this is called back from the player the timer doesn't fire off. + m_Parent->AddCallbackTimer(imaginationDrainRate, [playerDestroyableComponent, this, item]() { + if (!playerDestroyableComponent) { + Game::logger->Log("PetComponent", "No petComponent and/or no playerDestroyableComponent"); + return; + } - // If we are out of imagination despawn the pet. - if (playerDestroyableComponent->GetImagination() == 0) { - this->Deactivate(); - auto playerEntity = playerDestroyableComponent->GetParent(); - if (!playerEntity) return; + // If we are out of imagination despawn the pet. + if (playerDestroyableComponent->GetImagination() == 0) { + this->Deactivate(); + auto playerEntity = playerDestroyableComponent->GetParent(); + if (!playerEntity) return; - GameMessages::SendUseItemRequirementsResponse(playerEntity->GetObjectID(), playerEntity->GetSystemAddress(), UseItemResponse::NoImaginationForPet); - } + GameMessages::SendUseItemRequirementsResponse(playerEntity->GetObjectID(), playerEntity->GetSystemAddress(), UseItemResponse::NoImaginationForPet); + } - this->AddDrainImaginationTimer(item); - }); + this->AddDrainImaginationTimer(item); + }); } -void PetComponent::Deactivate() -{ - GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), -1, u"despawn", "", LWOOBJID_EMPTY, 1, 1, true); +void PetComponent::Deactivate() { + GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), -1, u"despawn", "", LWOOBJID_EMPTY, 1, 1, true); - GameMessages::SendMarkInventoryItemAsActive(m_Owner, false, 0, m_ItemId, GetOwner()->GetSystemAddress()); + GameMessages::SendMarkInventoryItemAsActive(m_Owner, false, 0, m_ItemId, GetOwner()->GetSystemAddress()); - activePets.erase(m_Owner); + activePets.erase(m_Owner); - m_Parent->Kill(); + m_Parent->Kill(); - auto* owner = GetOwner(); + auto* owner = GetOwner(); - if (owner == nullptr) return; + if (owner == nullptr) return; - GameMessages::SendAddPetToPlayer(m_Owner, 0, u"", LWOOBJID_EMPTY, LOT_NULL, owner->GetSystemAddress()); + GameMessages::SendAddPetToPlayer(m_Owner, 0, u"", LWOOBJID_EMPTY, LOT_NULL, owner->GetSystemAddress()); - GameMessages::SendRegisterPetID(m_Owner, LWOOBJID_EMPTY, owner->GetSystemAddress()); + GameMessages::SendRegisterPetID(m_Owner, LWOOBJID_EMPTY, owner->GetSystemAddress()); - GameMessages::SendRegisterPetDBID(m_Owner, LWOOBJID_EMPTY, owner->GetSystemAddress()); + GameMessages::SendRegisterPetDBID(m_Owner, LWOOBJID_EMPTY, owner->GetSystemAddress()); - GameMessages::SendShowPetActionButton(m_Owner, 0, false, owner->GetSystemAddress()); + GameMessages::SendShowPetActionButton(m_Owner, 0, false, owner->GetSystemAddress()); } -void PetComponent::Release() -{ - auto* inventoryComponent = GetOwner()->GetComponent(); +void PetComponent::Release() { + auto* inventoryComponent = GetOwner()->GetComponent(); - if (inventoryComponent == nullptr) - { - return; - } + if (inventoryComponent == nullptr) { + return; + } - Deactivate(); + Deactivate(); - inventoryComponent->RemoveDatabasePet(m_DatabaseId); + inventoryComponent->RemoveDatabasePet(m_DatabaseId); - auto* item = inventoryComponent->FindItemBySubKey(m_DatabaseId); + auto* item = inventoryComponent->FindItemBySubKey(m_DatabaseId); - item->SetCount(0, false, false); + item->SetCount(0, false, false); } -void PetComponent::Command(NiPoint3 position, LWOOBJID source, int32_t commandType, int32_t typeId, bool overrideObey) -{ - auto* owner = GetOwner(); +void PetComponent::Command(NiPoint3 position, LWOOBJID source, int32_t commandType, int32_t typeId, bool overrideObey) { + auto* owner = GetOwner(); - if (owner == nullptr) - { - return; - } + if (owner == nullptr) { + return; + } - if (commandType == 1) { - // Emotes - GameMessages::SendPlayEmote(m_Parent->GetObjectID(), typeId, owner->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - } else if (commandType == 3) { - // Follow me, ??? - } else if (commandType == 6) { - // TODO: Go to player - } + if (commandType == 1) { + // Emotes + GameMessages::SendPlayEmote(m_Parent->GetObjectID(), typeId, owner->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + } else if (commandType == 3) { + // Follow me, ??? + } else if (commandType == 6) { + // TODO: Go to player + } - if (owner->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { - ChatPackets::SendSystemMessage(owner->GetSystemAddress(), u"Commmand Type: " + (GeneralUtils::to_u16string(commandType)) + u" - Type Id: " + (GeneralUtils::to_u16string(typeId))); - } + if (owner->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + ChatPackets::SendSystemMessage(owner->GetSystemAddress(), u"Commmand Type: " + (GeneralUtils::to_u16string(commandType)) + u" - Type Id: " + (GeneralUtils::to_u16string(typeId))); + } } -LWOOBJID PetComponent::GetOwnerId() const -{ - return m_Owner; +LWOOBJID PetComponent::GetOwnerId() const { + return m_Owner; } -Entity* PetComponent::GetOwner() const -{ - return EntityManager::Instance()->GetEntity(m_Owner); +Entity* PetComponent::GetOwner() const { + return EntityManager::Instance()->GetEntity(m_Owner); } -LWOOBJID PetComponent::GetDatabaseId() const -{ - return m_DatabaseId; +LWOOBJID PetComponent::GetDatabaseId() const { + return m_DatabaseId; } -LWOOBJID PetComponent::GetInteraction() const -{ - return m_Interaction; +LWOOBJID PetComponent::GetInteraction() const { + return m_Interaction; } -LWOOBJID PetComponent::GetItemId() const -{ - return m_ItemId; +LWOOBJID PetComponent::GetItemId() const { + return m_ItemId; } -uint32_t PetComponent::GetStatus() const -{ - return m_Status; +uint32_t PetComponent::GetStatus() const { + return m_Status; } -PetAbilityType PetComponent::GetAbility() const -{ - return m_Ability; +PetAbilityType PetComponent::GetAbility() const { + return m_Ability; } -void PetComponent::SetInteraction(LWOOBJID value) -{ - m_Interaction = value; +void PetComponent::SetInteraction(LWOOBJID value) { + m_Interaction = value; } -void PetComponent::SetStatus(uint32_t value) -{ - m_Status = value; +void PetComponent::SetStatus(uint32_t value) { + m_Status = value; } -void PetComponent::SetAbility(PetAbilityType value) -{ - m_Ability = value; +void PetComponent::SetAbility(PetAbilityType value) { + m_Ability = value; } -PetComponent* PetComponent::GetTamingPet(LWOOBJID tamer) -{ - const auto& pair = currentActivities.find(tamer); +PetComponent* PetComponent::GetTamingPet(LWOOBJID tamer) { + const auto& pair = currentActivities.find(tamer); - if (pair == currentActivities.end()) - { - return nullptr; - } + if (pair == currentActivities.end()) { + return nullptr; + } - auto* entity = EntityManager::Instance()->GetEntity(pair->second); + auto* entity = EntityManager::Instance()->GetEntity(pair->second); - if (entity == nullptr) - { - currentActivities.erase(tamer); + if (entity == nullptr) { + currentActivities.erase(tamer); - return nullptr; - } + return nullptr; + } - return entity->GetComponent(); + return entity->GetComponent(); } -PetComponent* PetComponent::GetActivePet(LWOOBJID owner) -{ - const auto& pair = activePets.find(owner); +PetComponent* PetComponent::GetActivePet(LWOOBJID owner) { + const auto& pair = activePets.find(owner); - if (pair == activePets.end()) - { - return nullptr; - } + if (pair == activePets.end()) { + return nullptr; + } - auto* entity = EntityManager::Instance()->GetEntity(pair->second); + auto* entity = EntityManager::Instance()->GetEntity(pair->second); - if (entity == nullptr) - { - activePets.erase(owner); + if (entity == nullptr) { + activePets.erase(owner); - return nullptr; - } + return nullptr; + } - return entity->GetComponent(); + return entity->GetComponent(); } -Entity* PetComponent::GetParentEntity() const -{ - return m_Parent; +Entity* PetComponent::GetParentEntity() const { + return m_Parent; } -PetComponent::~PetComponent() -{ +PetComponent::~PetComponent() { } void PetComponent::SetPetNameForModeration(const std::string& petName) { - int approved = 1; //default, in mod + int approved = 1; //default, in mod - //Make sure that the name isn't already auto-approved: - if (Game::chatFilter->IsSentenceOkay(petName, 0).empty()) { - approved = 2; //approved - } + //Make sure that the name isn't already auto-approved: + if (Game::chatFilter->IsSentenceOkay(petName, 0).empty()) { + approved = 2; //approved + } - auto deleteStmt = Database::CreatePreppedStmt("DELETE FROM pet_names WHERE id = ? LIMIT 1;"); - deleteStmt->setUInt64(1, m_DatabaseId); + auto deleteStmt = Database::CreatePreppedStmt("DELETE FROM pet_names WHERE id = ? LIMIT 1;"); + deleteStmt->setUInt64(1, m_DatabaseId); - deleteStmt->execute(); + deleteStmt->execute(); - delete deleteStmt; + delete deleteStmt; - //Save to db: - auto stmt = Database::CreatePreppedStmt("INSERT INTO `pet_names` (`id`, `pet_name`, `approved`) VALUES (?, ?, ?);"); - stmt->setUInt64(1, m_DatabaseId); - stmt->setString(2, petName); - stmt->setInt(3, approved); - stmt->execute(); - delete stmt; + //Save to db: + auto stmt = Database::CreatePreppedStmt("INSERT INTO `pet_names` (`id`, `pet_name`, `approved`) VALUES (?, ?, ?);"); + stmt->setUInt64(1, m_DatabaseId); + stmt->setString(2, petName); + stmt->setInt(3, approved); + stmt->execute(); + delete stmt; } void PetComponent::LoadPetNameFromModeration() { - auto stmt = Database::CreatePreppedStmt("SELECT pet_name, approved FROM pet_names WHERE id = ? LIMIT 1;"); - stmt->setUInt64(1, m_DatabaseId); + auto stmt = Database::CreatePreppedStmt("SELECT pet_name, approved FROM pet_names WHERE id = ? LIMIT 1;"); + stmt->setUInt64(1, m_DatabaseId); - auto res = stmt->executeQuery(); - while (res->next()) { - m_ModerationStatus = res->getInt(2); + auto res = stmt->executeQuery(); + while (res->next()) { + m_ModerationStatus = res->getInt(2); - if (m_ModerationStatus == 2) - { - m_Name = res->getString(1); - } - } + if (m_ModerationStatus == 2) { + m_Name = res->getString(1); + } + } - delete res; - delete stmt; + delete res; + delete stmt; } void PetComponent::SetPreconditions(std::string& preconditions) { - m_Preconditions = new PreconditionExpression(preconditions); + m_Preconditions = new PreconditionExpression(preconditions); } diff --git a/dGame/dComponents/PetComponent.h b/dGame/dComponents/PetComponent.h index 913cbc56..efde0e8a 100644 --- a/dGame/dComponents/PetComponent.h +++ b/dGame/dComponents/PetComponent.h @@ -7,10 +7,10 @@ enum class PetAbilityType { - Invalid, - GoToObject, - JumpOnObject, - DigAtPosition + Invalid, + GoToObject, + JumpOnObject, + DigAtPosition }; /** @@ -20,343 +20,343 @@ enum class PetAbilityType class PetComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PET; + static const uint32_t ComponentType = COMPONENT_TYPE_PET; - explicit PetComponent(Entity* parentEntity, uint32_t componentId); - ~PetComponent() override; + explicit PetComponent(Entity* parentEntity, uint32_t componentId); + ~PetComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Update(float deltaTime) override; - /** - * Handles an OnUse event from another entity, initializing the pet taming minigame if this pet is untamed. - * @param originator the entity that triggered the event - */ - void OnUse(Entity* originator) override; + /** + * Handles an OnUse event from another entity, initializing the pet taming minigame if this pet is untamed. + * @param originator the entity that triggered the event + */ + void OnUse(Entity* originator) override; - /** - * Attempts to complete the pet minigame by passing a list of bricks to build the minigame model. - * @param bricks the bricks to try to complete the minigame with - * @param clientFailed unused - */ - void TryBuild(uint32_t numBricks, bool clientFailed); + /** + * Attempts to complete the pet minigame by passing a list of bricks to build the minigame model. + * @param bricks the bricks to try to complete the minigame with + * @param clientFailed unused + */ + void TryBuild(uint32_t numBricks, bool clientFailed); - /** - * Handles a notification from the client regarding the completion of the pet minigame, adding the pet to their - * inventory. - * @param position the position to spawn the completed model at - */ - void NotifyTamingBuildSuccess(NiPoint3 position); + /** + * Handles a notification from the client regarding the completion of the pet minigame, adding the pet to their + * inventory. + * @param position the position to spawn the completed model at + */ + void NotifyTamingBuildSuccess(NiPoint3 position); - /** - * Handles the notification of the client to set the name of the pet (indicating that minigame was completed - * successfully). - * @param name the name of the pet to set - */ - void RequestSetPetName(std::u16string name); + /** + * Handles the notification of the client to set the name of the pet (indicating that minigame was completed + * successfully). + * @param name the name of the pet to set + */ + void RequestSetPetName(std::u16string name); - /** - * Handles a notification of the client that the taming entity is leaving the minigame, either voluntary or because - * time ran out. - * @param voluntaryExit whether the client voluntarily exited the minigame - */ - void ClientExitTamingMinigame(bool voluntaryExit); + /** + * Handles a notification of the client that the taming entity is leaving the minigame, either voluntary or because + * time ran out. + * @param voluntaryExit whether the client voluntarily exited the minigame + */ + void ClientExitTamingMinigame(bool voluntaryExit); - /** - * Starts the internal timer for the build limit for building the minigame model - */ - void StartTimer(); + /** + * Starts the internal timer for the build limit for building the minigame model + */ + void StartTimer(); - /** - * Notifies the client that they failed the minigame because time ran out - */ - void ClientFailTamingMinigame(); + /** + * Notifies the client that they failed the minigame because time ran out + */ + void ClientFailTamingMinigame(); - /** - * Makes the pet wander around - */ - void Wander(); + /** + * Makes the pet wander around + */ + void Wander(); - /** - * Spawns a pet from an item in the inventory of an owner - * @param item the item to create the pet from - * @param registerPet notifies the client that the pet was spawned, not necessary if this pet is being tamed - */ - void Activate(Item* item, bool registerPet = true, bool fromTaming = false); + /** + * Spawns a pet from an item in the inventory of an owner + * @param item the item to create the pet from + * @param registerPet notifies the client that the pet was spawned, not necessary if this pet is being tamed + */ + void Activate(Item* item, bool registerPet = true, bool fromTaming = false); - /** - * Despawns the pet - */ - void Deactivate(); + /** + * Despawns the pet + */ + void Deactivate(); - /** - * Removes the pet from the inventory - */ - void Release(); + /** + * Removes the pet from the inventory + */ + void Release(); - /** - * Commands the pet to do an action, actions are still a relative mystery, next to playing emotes - * @param position a position to execute the command at, currently unused - * @param source the source object that triggered the command - * @param commandType the type of the command (see function body for types) - * @param typeId extra information about the command, e.g. the emote to play - * @param overrideObey unused - */ - void Command(NiPoint3 position, LWOOBJID source, int32_t commandType, int32_t typeId, bool overrideObey); + /** + * Commands the pet to do an action, actions are still a relative mystery, next to playing emotes + * @param position a position to execute the command at, currently unused + * @param source the source object that triggered the command + * @param commandType the type of the command (see function body for types) + * @param typeId extra information about the command, e.g. the emote to play + * @param overrideObey unused + */ + void Command(NiPoint3 position, LWOOBJID source, int32_t commandType, int32_t typeId, bool overrideObey); - /** - * Returns the ID of the owner of this pet (if any) - * @return the ID of the owner of this pet - */ - LWOOBJID GetOwnerId() const; + /** + * Returns the ID of the owner of this pet (if any) + * @return the ID of the owner of this pet + */ + LWOOBJID GetOwnerId() const; - /** - * Returns the entity that owns this pet (if any) - * @return the entity that owns this pet - */ - Entity* GetOwner() const; + /** + * Returns the entity that owns this pet (if any) + * @return the entity that owns this pet + */ + Entity* GetOwner() const; - /** - * Returns the ID that is stored in the database with regards to this pet, only set for pets that are tamed - * @return the ID that is stored in the database with regards to this pet - */ - LWOOBJID GetDatabaseId() const; + /** + * Returns the ID that is stored in the database with regards to this pet, only set for pets that are tamed + * @return the ID that is stored in the database with regards to this pet + */ + LWOOBJID GetDatabaseId() const; - /** - * Returns the ID of the object that the pet is currently interacting with, could be a treasure chest or a switch - * @return the ID of the object that the pet is currently interacting with - */ - LWOOBJID GetInteraction() const; + /** + * Returns the ID of the object that the pet is currently interacting with, could be a treasure chest or a switch + * @return the ID of the object that the pet is currently interacting with + */ + LWOOBJID GetInteraction() const; - /** - * Sets the ID that the pet is interacting with - * @param value the ID that the pet is interacting with - */ - void SetInteraction(LWOOBJID value); + /** + * Sets the ID that the pet is interacting with + * @param value the ID that the pet is interacting with + */ + void SetInteraction(LWOOBJID value); - /** - * Returns the ID that this pet was spawned from, only set for tamed pets - * @return the ID that this pet was spawned from - */ - LWOOBJID GetItemId() const; + /** + * Returns the ID that this pet was spawned from, only set for tamed pets + * @return the ID that this pet was spawned from + */ + LWOOBJID GetItemId() const; - /** - * Returns the status of this pet, e.g. tamable or tamed. The values here are still a bit of mystery and likely a - * bit map - * @return the status of this pet - */ - uint32_t GetStatus() const; + /** + * Returns the status of this pet, e.g. tamable or tamed. The values here are still a bit of mystery and likely a + * bit map + * @return the status of this pet + */ + uint32_t GetStatus() const; - /** - * Sets the current status of the pet - * @param value the current status of the pet to set - */ - void SetStatus(uint32_t value); + /** + * Sets the current status of the pet + * @param value the current status of the pet to set + */ + void SetStatus(uint32_t value); - /** - * Returns an ability the pet may perform, currently unused - * @return an ability the pet may perform - */ - PetAbilityType GetAbility() const; + /** + * Returns an ability the pet may perform, currently unused + * @return an ability the pet may perform + */ + PetAbilityType GetAbility() const; - /** - * Sets the ability of the pet, currently unused - * @param value the ability to set - */ - void SetAbility(PetAbilityType value); + /** + * Sets the ability of the pet, currently unused + * @param value the ability to set + */ + void SetAbility(PetAbilityType value); - /** - * Sets preconditions for the pet that need to be met before it can be tamed - * @param conditions the preconditions to set - */ - void SetPreconditions(std::string& conditions); + /** + * Sets preconditions for the pet that need to be met before it can be tamed + * @param conditions the preconditions to set + */ + void SetPreconditions(std::string& conditions); - /** - * Returns the entity that this component belongs to - * @return the entity that this component belongs to - */ - Entity* GetParentEntity() const; + /** + * Returns the entity that this component belongs to + * @return the entity that this component belongs to + */ + Entity* GetParentEntity() const; - /** - * Sets the name of the pet to be moderated - * @param petName the name of the pet to set - */ - void SetPetNameForModeration(const std::string& petName); + /** + * Sets the name of the pet to be moderated + * @param petName the name of the pet to set + */ + void SetPetNameForModeration(const std::string& petName); - /** - * Loads the pet name up for moderation along with the moderation status from the database and sets them for this - * pet. - */ - void LoadPetNameFromModeration(); + /** + * Loads the pet name up for moderation along with the moderation status from the database and sets them for this + * pet. + */ + void LoadPetNameFromModeration(); - /** - * Returns the component of the pet some entity is currently taming (if any) - * @param tamer the entity that's currently taming - * @return the pet component of the entity that's being tamed - */ - static PetComponent* GetTamingPet(LWOOBJID tamer); + /** + * Returns the component of the pet some entity is currently taming (if any) + * @param tamer the entity that's currently taming + * @return the pet component of the entity that's being tamed + */ + static PetComponent* GetTamingPet(LWOOBJID tamer); - /** - * Returns the pet that's currently spawned for some entity (if any) - * @param owner the owner of the pet that's spawned - * @return the pet component of the entity that was spawned by the owner - */ - static PetComponent* GetActivePet(LWOOBJID owner); + /** + * Returns the pet that's currently spawned for some entity (if any) + * @param owner the owner of the pet that's spawned + * @return the pet component of the entity that was spawned by the owner + */ + static PetComponent* GetActivePet(LWOOBJID owner); - /** - * Adds the timer to the owner of this pet to drain imagination at the rate - * specified by the parameter imaginationDrainRate - * - * @param item The item that represents this pet in the inventory. - */ - void AddDrainImaginationTimer(Item* item, bool fromTaming = false); + /** + * Adds the timer to the owner of this pet to drain imagination at the rate + * specified by the parameter imaginationDrainRate + * + * @param item The item that represents this pet in the inventory. + */ + void AddDrainImaginationTimer(Item* item, bool fromTaming = false); private: - /** - * Information for the minigame to be completed - */ - struct PetPuzzleData - { - /** - * The LOT of the object that is to be created - */ - LOT puzzleModelLot; + /** + * Information for the minigame to be completed + */ + struct PetPuzzleData + { + /** + * The LOT of the object that is to be created + */ + LOT puzzleModelLot; - /** - * That file that contains the bricks required to build the model - */ - std::string buildFile; + /** + * That file that contains the bricks required to build the model + */ + std::string buildFile; - /** - * The time limit to complete the build - */ - int32_t timeLimit; + /** + * The time limit to complete the build + */ + int32_t timeLimit; - /** - * The imagination cost for the tamer to start the minigame - */ - int32_t imaginationCost; + /** + * The imagination cost for the tamer to start the minigame + */ + int32_t imaginationCost; - /** - * The number of pieces required to complete the minigame - */ - int32_t numValidPieces; - }; + /** + * The number of pieces required to complete the minigame + */ + int32_t numValidPieces; + }; - /** - * Cache of all the pets that are currently spawned, indexed by tamer - */ - static std::unordered_map activePets; + /** + * Cache of all the pets that are currently spawned, indexed by tamer + */ + static std::unordered_map activePets; - /** - * Cache of all the pets that are currently being tamed, indexed by tamer - */ - static std::unordered_map currentActivities; + /** + * Cache of all the pets that are currently being tamed, indexed by tamer + */ + static std::unordered_map currentActivities; - /** - * Cache of all the minigames and their information from the database - */ - static std::unordered_map buildCache; + /** + * Cache of all the minigames and their information from the database + */ + static std::unordered_map buildCache; - /** - * Flags that indicate that a player has tamed a pet, indexed by the LOT of the pet - */ - static std::map petFlags; + /** + * Flags that indicate that a player has tamed a pet, indexed by the LOT of the pet + */ + static std::map petFlags; - /** - * The ID of the component in the pet component table - */ - uint32_t m_ComponentId; + /** + * The ID of the component in the pet component table + */ + uint32_t m_ComponentId; - /** - * The ID of the model that was built to complete the taming minigame for this pet - */ - LWOOBJID m_ModelId; + /** + * The ID of the model that was built to complete the taming minigame for this pet + */ + LWOOBJID m_ModelId; - /** - * The ID of the object that the pet is currently interacting with (e.g. a treasure chest or switch) - */ - LWOOBJID m_Interaction; + /** + * The ID of the object that the pet is currently interacting with (e.g. a treasure chest or switch) + */ + LWOOBJID m_Interaction; - /** - * The ID of the entity that owns this pet - */ - LWOOBJID m_Owner; + /** + * The ID of the entity that owns this pet + */ + LWOOBJID m_Owner; - /** - * The ID of the entity that is currently taming this pet - */ - LWOOBJID m_Tamer; + /** + * The ID of the entity that is currently taming this pet + */ + LWOOBJID m_Tamer; - /** - * The ID under which this pet is stored in the database (if it's tamed) - */ - LWOOBJID m_DatabaseId; + /** + * The ID under which this pet is stored in the database (if it's tamed) + */ + LWOOBJID m_DatabaseId; - /** - * The ID of the item from which this pet was created - */ - LWOOBJID m_ItemId; + /** + * The ID of the item from which this pet was created + */ + LWOOBJID m_ItemId; - /** - * The moderation status for the name of this pet - */ - uint32_t m_ModerationStatus; + /** + * The moderation status for the name of this pet + */ + uint32_t m_ModerationStatus; - /** - * The name of this pet - */ - std::string m_Name; + /** + * The name of this pet + */ + std::string m_Name; - /** - * The name of the owner of this pet - */ - std::string m_OwnerName; + /** + * The name of the owner of this pet + */ + std::string m_OwnerName; - /** - * The current state of the pet (e.g. tamable, tamed, etc). - */ - uint32_t m_Status; + /** + * The current state of the pet (e.g. tamable, tamed, etc). + */ + uint32_t m_Status; - /** - * A currently active ability, mostly unused - */ - PetAbilityType m_Ability; + /** + * A currently active ability, mostly unused + */ + PetAbilityType m_Ability; - /** - * The time an entity has left to complete the minigame - */ - float m_Timer; + /** + * The time an entity has left to complete the minigame + */ + float m_Timer; - /** - * A timer that tracks how long a tamed pet has been to far away from its owner, triggering a teleport after timeout - */ - float m_TimerAway; + /** + * A timer that tracks how long a tamed pet has been to far away from its owner, triggering a teleport after timeout + */ + float m_TimerAway; - /** - * Timer that tracks how long a pet has been digging up some treasure, required to spawn the treasure contents - * on time - */ - float m_TresureTime; + /** + * Timer that tracks how long a pet has been digging up some treasure, required to spawn the treasure contents + * on time + */ + float m_TresureTime; - /** - * The position that this pet was spawned at - */ - NiPoint3 m_StartPosition; + /** + * The position that this pet was spawned at + */ + NiPoint3 m_StartPosition; - /** - * The movement AI component that is related to this pet, required to move it around - */ - MovementAIComponent* m_MovementAI; + /** + * The movement AI component that is related to this pet, required to move it around + */ + MovementAIComponent* m_MovementAI; - /** - * Preconditions that need to be met before an entity can tame this pet - */ - PreconditionExpression* m_Preconditions; + /** + * Preconditions that need to be met before an entity can tame this pet + */ + PreconditionExpression* m_Preconditions; - /** - * The rate at which imagination is drained from the user for having the pet out. - */ - float imaginationDrainRate; -}; \ No newline at end of file + /** + * The rate at which imagination is drained from the user for having the pet out. + */ + float imaginationDrainRate; +}; diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index 3c8394f6..8cafec52 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -27,23 +27,23 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(parent) { m_Position = m_Parent->GetDefaultPosition(); - m_Rotation = m_Parent->GetDefaultRotation(); + m_Rotation = m_Parent->GetDefaultRotation(); m_Scale = m_Parent->GetDefaultScale(); m_dpEntity = nullptr; - m_EffectInfoDirty = false; + m_EffectInfoDirty = false; m_PositionInfoDirty = false; - m_IsPhysicsEffectActive = false; - m_EffectType = 0; - m_DirectionalMultiplier = 0.0f; + m_IsPhysicsEffectActive = false; + m_EffectType = 0; + m_DirectionalMultiplier = 0.0f; - m_MinMax = false; - m_Min = 0; - m_Max = 1; + m_MinMax = false; + m_Min = 0; + m_Max = 1; - m_IsDirectional = false; - m_Direction = NiPoint3(); // * m_DirectionalMultiplier + m_IsDirectional = false; + m_Direction = NiPoint3(); // * m_DirectionalMultiplier if (m_Parent->GetVar(u"create_physics")) { CreatePhysics(); @@ -82,8 +82,7 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par } // HF - RespawnPoints. Legacy respawn entity. - if (m_Parent->GetLOT() == 4945) - { + if (m_Parent->GetLOT() == 4945) { m_IsRespawnVolume = true; m_RespawnPos = m_Position; m_RespawnRot = m_Rotation; @@ -162,8 +161,7 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par m_dpEntity->SetPosition(m_Position); dpWorld::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "miscellaneous\\misc_phys_640x640.hkx") { + } else if (info->physicsAsset == "miscellaneous\\misc_phys_640x640.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 640.0f, 20.0f, 640.0f); m_dpEntity->SetScale(m_Scale); @@ -171,53 +169,43 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par m_dpEntity->SetPosition(m_Position); dpWorld::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "env\\trigger_wall_tall.hkx") { - m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 10.0f, 25.0f, 1.0f); + } 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::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "env\\env_gen_placeholderphysics.hkx") { + } 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::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "env\\POI_trigger_wall.hkx") { + } 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::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "env\\NG_NinjaGo\\env_ng_gen_gate_chamber_puzzle_ceiling_tile_falling_phantom.hkx") - { + } 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::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "env\\NG_NinjaGo\\ng_flamejet_brick_phantom.HKX") - { + } 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::Instance().AddEntity(m_dpEntity); - } - else if (info->physicsAsset == "env\\Ring_Trigger.hkx") - { + } 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::Instance().AddEntity(m_dpEntity); - } - else { + } else { //Game::logger->Log("PhantomPhysicsComponent", "This one is supposed to have %s", info->physicsAsset.c_str()); //add fallback cube: @@ -254,8 +242,7 @@ void PhantomPhysicsComponent::CreatePhysics() { x = m_Parent->GetVar(u"primitiveModelValueX"); y = m_Parent->GetVar(u"primitiveModelValueY"); z = m_Parent->GetVar(u"primitiveModelValueZ"); - } - else { + } else { CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), COMPONENT_TYPE_PHANTOM_PHYSICS); @@ -294,7 +281,7 @@ void PhantomPhysicsComponent::CreatePhysics() { if (!m_dpEntity) return; - m_dpEntity->SetPosition({m_Position.x, m_Position.y - (height / 2), m_Position.z}); + m_dpEntity->SetPosition({ m_Position.x, m_Position.y - (height / 2), m_Position.z }); dpWorld::Instance().AddEntity(m_dpEntity); @@ -302,9 +289,8 @@ void PhantomPhysicsComponent::CreatePhysics() { } void PhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - outBitStream->Write(m_PositionInfoDirty || bIsInitialUpdate); - if (m_PositionInfoDirty || bIsInitialUpdate) - { + outBitStream->Write(m_PositionInfoDirty || bIsInitialUpdate); + if (m_PositionInfoDirty || bIsInitialUpdate) { outBitStream->Write(m_Position.x); outBitStream->Write(m_Position.y); outBitStream->Write(m_Position.z); @@ -316,13 +302,13 @@ void PhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bI m_PositionInfoDirty = false; } - outBitStream->Write(m_EffectInfoDirty || bIsInitialUpdate); - if (m_EffectInfoDirty || bIsInitialUpdate) { - outBitStream->Write(m_IsPhysicsEffectActive); + outBitStream->Write(m_EffectInfoDirty || bIsInitialUpdate); + if (m_EffectInfoDirty || bIsInitialUpdate) { + outBitStream->Write(m_IsPhysicsEffectActive); - if (m_IsPhysicsEffectActive) { - outBitStream->Write(m_EffectType); - outBitStream->Write(m_DirectionalMultiplier); + if (m_IsPhysicsEffectActive) { + outBitStream->Write(m_EffectType); + outBitStream->Write(m_DirectionalMultiplier); // forgive me father for i have sinned outBitStream->Write0(); @@ -332,20 +318,20 @@ void PhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bI //outBitStream->Write(m_Max); //} - outBitStream->Write(m_IsDirectional); - if (m_IsDirectional) { - outBitStream->Write(m_Direction.x); - outBitStream->Write(m_Direction.y); - outBitStream->Write(m_Direction.z); - } - } + outBitStream->Write(m_IsDirectional); + if (m_IsDirectional) { + outBitStream->Write(m_Direction.x); + outBitStream->Write(m_Direction.y); + outBitStream->Write(m_Direction.z); + } + } m_EffectInfoDirty = false; - } + } } void PhantomPhysicsComponent::ResetFlags() { - m_EffectInfoDirty = false; + m_EffectInfoDirty = false; m_PositionInfoDirty = false; } @@ -375,13 +361,13 @@ void PhantomPhysicsComponent::Update(float deltaTime) { } void PhantomPhysicsComponent::SetDirection(const NiPoint3& pos) { - m_Direction = pos; - m_Direction.x *= m_DirectionalMultiplier; - m_Direction.y *= m_DirectionalMultiplier; - m_Direction.z *= m_DirectionalMultiplier; + m_Direction = pos; + m_Direction.x *= m_DirectionalMultiplier; + m_Direction.y *= m_DirectionalMultiplier; + m_Direction.z *= m_DirectionalMultiplier; - m_EffectInfoDirty = true; - m_IsDirectional = true; + m_EffectInfoDirty = true; + m_IsDirectional = true; } void PhantomPhysicsComponent::SpawnVertices() { @@ -405,35 +391,35 @@ void PhantomPhysicsComponent::SpawnVertices() { } void PhantomPhysicsComponent::SetDirectionalMultiplier(float mul) { - m_DirectionalMultiplier = mul; - m_EffectInfoDirty = true; + m_DirectionalMultiplier = mul; + m_EffectInfoDirty = true; } void PhantomPhysicsComponent::SetEffectType(uint32_t type) { - m_EffectType = type; - m_EffectInfoDirty = true; + m_EffectType = type; + m_EffectInfoDirty = true; } void PhantomPhysicsComponent::SetMin(uint32_t min) { - m_Min = min; - m_MinMax = true; - m_EffectInfoDirty = true; + m_Min = min; + m_MinMax = true; + m_EffectInfoDirty = true; } void PhantomPhysicsComponent::SetMax(uint32_t max) { - m_Max = max; - m_MinMax = true; - m_EffectInfoDirty = true; + m_Max = max; + m_MinMax = true; + m_EffectInfoDirty = true; } void PhantomPhysicsComponent::SetPosition(const NiPoint3& pos) { - m_Position = pos; + m_Position = pos; if (m_dpEntity) m_dpEntity->SetPosition(pos); } void PhantomPhysicsComponent::SetRotation(const NiQuaternion& rot) { - m_Rotation = rot; + m_Rotation = rot; if (m_dpEntity) m_dpEntity->SetRotation(rot); } diff --git a/dGame/dComponents/PhantomPhysicsComponent.h b/dGame/dComponents/PhantomPhysicsComponent.h index faf6362f..1e9a7b60 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.h +++ b/dGame/dComponents/PhantomPhysicsComponent.h @@ -25,191 +25,191 @@ class dpEntity; */ class PhantomPhysicsComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PHANTOM_PHYSICS; - - PhantomPhysicsComponent(Entity* parent); - ~PhantomPhysicsComponent() override; - void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void ResetFlags(); + static const uint32_t ComponentType = COMPONENT_TYPE_PHANTOM_PHYSICS; - /** - * Creates the physics shape for this entity based on LDF data - */ + PhantomPhysicsComponent(Entity* parent); + ~PhantomPhysicsComponent() override; + void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void ResetFlags(); + + /** + * Creates the physics shape for this entity based on LDF data + */ void CreatePhysics(); - /** - * Sets the direction this physics object is pointed at - * @param pos the direction to set - */ - void SetDirection(const NiPoint3& pos); + /** + * Sets the direction this physics object is pointed at + * @param pos the direction to set + */ + void SetDirection(const NiPoint3& pos); - /** - * Returns the direction this physics object is pointed at - * @return the direction this physics object is pointed at - */ - const NiPoint3& GetDirection() const { return m_Direction; } + /** + * Returns the direction this physics object is pointed at + * @return the direction this physics object is pointed at + */ + const NiPoint3& GetDirection() const { return m_Direction; } - /** - * Returns the multiplier by which the direction coordinates are multiplied - * @return the multiplier by which the direction coordinates are multiplied - */ - float GetDirectionalMultiplier() const { return m_DirectionalMultiplier; } + /** + * Returns the multiplier by which the direction coordinates are multiplied + * @return the multiplier by which the direction coordinates are multiplied + */ + float GetDirectionalMultiplier() const { return m_DirectionalMultiplier; } - /** - * Sets the multiplier by which direction coordinates are multiplied - * @param mul the multiplier to set - */ - void SetDirectionalMultiplier(float mul); + /** + * Sets the multiplier by which direction coordinates are multiplied + * @param mul the multiplier to set + */ + void SetDirectionalMultiplier(float mul); - /** - * Returns whether or not there's currently an effect active - * @return true if there's an effect active, false otherwise - */ - bool GetPhysicsEffectActive() const { return m_IsPhysicsEffectActive; } + /** + * Returns whether or not there's currently an effect active + * @return true if there's an effect active, false otherwise + */ + bool GetPhysicsEffectActive() const { return m_IsPhysicsEffectActive; } - /** - * Sets whether or not there's a physics effect active - * @param val whether or not there's an effect active - */ - void SetPhysicsEffectActive(bool val) { m_IsPhysicsEffectActive = val; m_EffectInfoDirty = true; } + /** + * Sets whether or not there's a physics effect active + * @param val whether or not there's an effect active + */ + void SetPhysicsEffectActive(bool val) { m_IsPhysicsEffectActive = val; m_EffectInfoDirty = true; } - /** - * Returns the position of this physics object - * @return the position of this physics object - */ - const NiPoint3& GetPosition() const { return m_Position; } + /** + * Returns the position of this physics object + * @return the position of this physics object + */ + const NiPoint3& GetPosition() const { return m_Position; } - /** - * Sets the position of this physics object - * @param pos the position to set - */ - void SetPosition(const NiPoint3& pos); + /** + * Sets the position of this physics object + * @param pos the position to set + */ + void SetPosition(const NiPoint3& pos); - /** - * Returns the rotation of this physics object - * @return the rotation of this physics object - */ - const NiQuaternion& GetRotation() const { return m_Rotation; } + /** + * Returns the rotation of this physics object + * @return the rotation of this physics object + */ + const NiQuaternion& GetRotation() const { return m_Rotation; } - /** - * Sets the rotation of this physics object - * @param rot the rotation to set - */ - void SetRotation(const NiQuaternion& rot); + /** + * Sets the rotation of this physics object + * @param rot the rotation to set + */ + void SetRotation(const NiQuaternion& rot); - /** - * Returns the effect that's currently active, defaults to 0 - * @return the effect that's currently active - */ - uint32_t GetEffectType() const { return m_EffectType; } + /** + * Returns the effect that's currently active, defaults to 0 + * @return the effect that's currently active + */ + uint32_t GetEffectType() const { return m_EffectType; } - /** - * Sets the effect that's currently active - * @param type the effect to set - */ - void SetEffectType(uint32_t type); + /** + * Sets the effect that's currently active + * @param type the effect to set + */ + void SetEffectType(uint32_t type); - /** - * Returns the Physics entity for the component - * @return Physics entity for the component - */ + /** + * Returns the Physics entity for the component + * @return Physics entity for the component + */ - dpEntity* GetdpEntity() const { return m_dpEntity; } + dpEntity* GetdpEntity() const { return m_dpEntity; } - /** - * Spawns an object at each of the vertices for debugging purposes - */ - void SpawnVertices(); + /** + * Spawns an object at each of the vertices for debugging purposes + */ + void SpawnVertices(); - /** - * Legacy stuff no clue what this does - */ - void SetMin(uint32_t min); + /** + * Legacy stuff no clue what this does + */ + void SetMin(uint32_t min); + + /** + * Legacy stuff no clue what this does + */ + void SetMax(uint32_t max); - /** - * Legacy stuff no clue what this does - */ - void SetMax(uint32_t max); - private: - /** - * The position of the physics object - */ - NiPoint3 m_Position; + /** + * The position of the physics object + */ + NiPoint3 m_Position; - /** - * The rotation of the physics object - */ - NiQuaternion m_Rotation; + /** + * The rotation of the physics object + */ + NiQuaternion m_Rotation; - /** - * A scale to apply to the size of the physics object - */ + /** + * A scale to apply to the size of the physics object + */ float m_Scale; - /** - * Whether or not the position has changed and needs to be serialized - */ - bool m_PositionInfoDirty; + /** + * Whether or not the position has changed and needs to be serialized + */ + bool m_PositionInfoDirty; - /** - * Whether or not the effect has changed and needs to be serialized - */ - bool m_EffectInfoDirty; + /** + * Whether or not the effect has changed and needs to be serialized + */ + bool m_EffectInfoDirty; - /** - * Whether or not there's currently a physics effect active - */ - bool m_IsPhysicsEffectActive; + /** + * Whether or not there's currently a physics effect active + */ + bool m_IsPhysicsEffectActive; - /** - * The physics effect that's currently active, defaults to 0 - */ - uint32_t m_EffectType; + /** + * The physics effect that's currently active, defaults to 0 + */ + uint32_t m_EffectType; - /** - * A scaling multiplier to add to the directional vector - */ - float m_DirectionalMultiplier; - - bool m_MinMax; - uint32_t m_Min; - uint32_t m_Max; + /** + * A scaling multiplier to add to the directional vector + */ + float m_DirectionalMultiplier; - /** - * Whether or not this physics object is pointed in some direction - */ - bool m_IsDirectional; + bool m_MinMax; + uint32_t m_Min; + uint32_t m_Max; - /** - * The direction this physics object is pointed in, if any - */ - NiPoint3 m_Direction; + /** + * Whether or not this physics object is pointed in some direction + */ + bool m_IsDirectional; - /** - * The parent entity of this component - */ - dpEntity* m_dpEntity; + /** + * The direction this physics object is pointed in, if any + */ + NiPoint3 m_Direction; - /** - * Whether or not the physics object has been created yet - */ + /** + * The parent entity of this component + */ + dpEntity* m_dpEntity; + + /** + * Whether or not the physics object has been created yet + */ bool m_HasCreatedPhysics = false; - /** - * Whether or not this physics object represents an object that updates the respawn pos of an entity that crosses it - */ + /** + * Whether or not this physics object represents an object that updates the respawn pos of an entity that crosses it + */ bool m_IsRespawnVolume = false; - /** - * If this is a respawn volume, the exact position an entity will respawn - */ + /** + * If this is a respawn volume, the exact position an entity will respawn + */ NiPoint3 m_RespawnPos; - /** - * If this is a respawn volume, the exact rotation an entity will respawn - */ + /** + * If this is a respawn volume, the exact rotation an entity will respawn + */ NiQuaternion m_RespawnRot; -}; \ No newline at end of file +}; diff --git a/dGame/dComponents/PlayerForcedMovementComponent.cpp b/dGame/dComponents/PlayerForcedMovementComponent.cpp index 94b79188..3bcad677 100644 --- a/dGame/dComponents/PlayerForcedMovementComponent.cpp +++ b/dGame/dComponents/PlayerForcedMovementComponent.cpp @@ -6,11 +6,11 @@ PlayerForcedMovementComponent::PlayerForcedMovementComponent(Entity* parent) : C PlayerForcedMovementComponent::~PlayerForcedMovementComponent() {} -void PlayerForcedMovementComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags){ +void PlayerForcedMovementComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { outBitStream->Write(m_DirtyInfo); if (m_DirtyInfo) { outBitStream->Write(m_PlayerOnRail); outBitStream->Write(m_ShowBillboard); } m_DirtyInfo = false; -} \ No newline at end of file +} diff --git a/dGame/dComponents/PlayerForcedMovementComponent.h b/dGame/dComponents/PlayerForcedMovementComponent.h index d023155c..43b99997 100644 --- a/dGame/dComponents/PlayerForcedMovementComponent.h +++ b/dGame/dComponents/PlayerForcedMovementComponent.h @@ -25,14 +25,14 @@ public: * * @param value if the player is on a rail */ - void SetPlayerOnRail(bool value){ m_PlayerOnRail = value; m_DirtyInfo = true; } + void SetPlayerOnRail(bool value) { m_PlayerOnRail = value; m_DirtyInfo = true; } /** * @brief Set the Show Billboard object * * @param value if the billboard should be shown */ - void SetShowBillboard(bool value){ m_ShowBillboard = value; m_DirtyInfo = true; } + void SetShowBillboard(bool value) { m_ShowBillboard = value; m_DirtyInfo = true; } /** * @brief Get the Player On Rail object @@ -41,14 +41,14 @@ public: * @return false */ - /** - * @brief Get the Player On Rail object - * - * @return true - * @return false - */ - bool GetPlayerOnRail(){ return m_PlayerOnRail; } - bool GetShowBillboard(){ return m_ShowBillboard; } + /** + * @brief Get the Player On Rail object + * + * @return true + * @return false + */ + bool GetPlayerOnRail() { return m_PlayerOnRail; } + bool GetShowBillboard() { return m_ShowBillboard; } private: /** diff --git a/dGame/dComponents/PossessableComponent.cpp b/dGame/dComponents/PossessableComponent.cpp index 8190b9eb..be31914b 100644 --- a/dGame/dComponents/PossessableComponent.cpp +++ b/dGame/dComponents/PossessableComponent.cpp @@ -4,7 +4,7 @@ #include "Inventory.h" #include "Item.h" -PossessableComponent::PossessableComponent(Entity* parent, uint32_t componentId) : Component(parent){ +PossessableComponent::PossessableComponent(Entity* parent, uint32_t componentId) : Component(parent) { m_Possessor = LWOOBJID_EMPTY; CDItemComponent item = Inventory::FindItemComponent(m_Parent->GetLOT()); m_AnimationFlag = static_cast(item.animationFlag); @@ -35,7 +35,7 @@ void PossessableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIn if (m_Possessor != LWOOBJID_EMPTY) outBitStream->Write(m_Possessor); outBitStream->Write(m_AnimationFlag != eAnimationFlags::IDLE_INVALID); - if(m_AnimationFlag != eAnimationFlags::IDLE_INVALID) outBitStream->Write(m_AnimationFlag); + if (m_AnimationFlag != eAnimationFlags::IDLE_INVALID) outBitStream->Write(m_AnimationFlag); outBitStream->Write(m_ImmediatelyDepossess); } @@ -43,4 +43,4 @@ void PossessableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIn void PossessableComponent::OnUse(Entity* originator) { // TODO: Implement this -} \ No newline at end of file +} diff --git a/dGame/dComponents/PossessableComponent.h b/dGame/dComponents/PossessableComponent.h index a37b6e34..77905c9c 100644 --- a/dGame/dComponents/PossessableComponent.h +++ b/dGame/dComponents/PossessableComponent.h @@ -12,104 +12,104 @@ * player is controlling it. */ class PossessableComponent : public Component { - public: - static const uint32_t ComponentType = COMPONENT_TYPE_POSSESSABLE; +public: + static const uint32_t ComponentType = COMPONENT_TYPE_POSSESSABLE; - PossessableComponent(Entity* parentEntity, uint32_t componentId); + PossessableComponent(Entity* parentEntity, uint32_t componentId); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Sets the possessor of this entity - * @param value the ID of the possessor to set - */ - void SetPossessor(LWOOBJID value) { m_Possessor = value; m_DirtyPossessable = true;}; + /** + * Sets the possessor of this entity + * @param value the ID of the possessor to set + */ + void SetPossessor(LWOOBJID value) { m_Possessor = value; m_DirtyPossessable = true; }; - /** - * Returns the possessor of this entity - * @return the possessor of this entity - */ - LWOOBJID GetPossessor() const { return m_Possessor; }; + /** + * Returns the possessor of this entity + * @return the possessor of this entity + */ + LWOOBJID GetPossessor() const { return m_Possessor; }; - /** - * Sets the animation Flag of the possessable - * @param value the animation flag to set to - */ - void SetAnimationFlag(eAnimationFlags value) { m_AnimationFlag = value; m_DirtyPossessable = true;}; + /** + * Sets the animation Flag of the possessable + * @param value the animation flag to set to + */ + void SetAnimationFlag(eAnimationFlags value) { m_AnimationFlag = value; m_DirtyPossessable = true; }; - /** - * Returns the possession type of this entity - * @return the possession type of this entity - */ - ePossessionType GetPossessionType() const { return m_PossessionType; }; + /** + * Returns the possession type of this entity + * @return the possession type of this entity + */ + ePossessionType GetPossessionType() const { return m_PossessionType; }; - /** - * Returns if the entity should deposses on hit - * @return if the entity should deposses on hit - */ - bool GetDepossessOnHit() const { return m_DepossessOnHit; }; + /** + * Returns if the entity should deposses on hit + * @return if the entity should deposses on hit + */ + bool GetDepossessOnHit() const { return m_DepossessOnHit; }; - /** - * Forcibly depossess the entity - */ - void ForceDepossess() { m_ImmediatelyDepossess = true; m_DirtyPossessable = true;}; + /** + * Forcibly depossess the entity + */ + void ForceDepossess() { m_ImmediatelyDepossess = true; m_DirtyPossessable = true; }; - /** - * Set if the parent entity was spawned from an item - * @param value if the parent entity was spawned from an item - */ - void SetItemSpawned(bool value) { m_ItemSpawned = value;}; + /** + * Set if the parent entity was spawned from an item + * @param value if the parent entity was spawned from an item + */ + void SetItemSpawned(bool value) { m_ItemSpawned = value; }; - /** - * Returns if the parent entity was spawned from an item - * @return if the parent entity was spawned from an item - */ - LWOOBJID GetItemSpawned() const { return m_ItemSpawned; }; + /** + * Returns if the parent entity was spawned from an item + * @return if the parent entity was spawned from an item + */ + LWOOBJID GetItemSpawned() const { return m_ItemSpawned; }; - /** - * Handles an OnUsed event by some other entity, if said entity has a Possessor it becomes the possessor - * of this entity - * @param originator the entity that caused the event to trigger - */ - void OnUse(Entity* originator) override; + /** + * Handles an OnUsed event by some other entity, if said entity has a Possessor it becomes the possessor + * of this entity + * @param originator the entity that caused the event to trigger + */ + void OnUse(Entity* originator) override; - private: +private: - /** - * @brief Whether the possessor is dirty - */ - bool m_DirtyPossessable = true; + /** + * @brief Whether the possessor is dirty + */ + bool m_DirtyPossessable = true; - /** - * @brief The possessor of this entity, e.g. the entity that controls this entity - */ - LWOOBJID m_Possessor = LWOOBJID_EMPTY; + /** + * @brief The possessor of this entity, e.g. the entity that controls this entity + */ + LWOOBJID m_Possessor = LWOOBJID_EMPTY; - /** - * @brief The type of possesstion to use on this entity - */ - ePossessionType m_PossessionType = ePossessionType::NO_POSSESSION; + /** + * @brief The type of possesstion to use on this entity + */ + ePossessionType m_PossessionType = ePossessionType::NO_POSSESSION; - /** - * @brief Should the possessable be dismount on hit - */ - bool m_DepossessOnHit = false; + /** + * @brief Should the possessable be dismount on hit + */ + bool m_DepossessOnHit = false; - /** - * @brief What animaiton flag to use - * - */ - eAnimationFlags m_AnimationFlag = eAnimationFlags::IDLE_INVALID; + /** + * @brief What animaiton flag to use + * + */ + eAnimationFlags m_AnimationFlag = eAnimationFlags::IDLE_INVALID; - /** - * @brief Should this be immediately depossessed - * - */ - bool m_ImmediatelyDepossess = false; + /** + * @brief Should this be immediately depossessed + * + */ + bool m_ImmediatelyDepossess = false; - /** - * @brief Whether the parent entity was spawned from an item - * - */ - bool m_ItemSpawned = false; + /** + * @brief Whether the parent entity was spawned from an item + * + */ + bool m_ItemSpawned = false; }; diff --git a/dGame/dComponents/PossessorComponent.h b/dGame/dComponents/PossessorComponent.h index a81868a5..2735adac 100644 --- a/dGame/dComponents/PossessorComponent.h +++ b/dGame/dComponents/PossessorComponent.h @@ -16,66 +16,66 @@ enum class ePossessionType : uint8_t { * Represents an entity that can posess other entities. Generally used by players to drive a car. */ class PossessorComponent : public Component { - public: - static const uint32_t ComponentType = COMPONENT_TYPE_POSSESSOR; +public: + static const uint32_t ComponentType = COMPONENT_TYPE_POSSESSOR; - PossessorComponent(Entity* parent); - ~PossessorComponent() override; + PossessorComponent(Entity* parent); + ~PossessorComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Sets the entity that this entity is possessing - * @param value the ID of the entity this ID should posess - */ - void SetPossessable(LWOOBJID value) { m_Possessable = value; m_DirtyPossesor = true; } + /** + * Sets the entity that this entity is possessing + * @param value the ID of the entity this ID should posess + */ + void SetPossessable(LWOOBJID value) { m_Possessable = value; m_DirtyPossesor = true; } - /** - * Returns the entity that this entity is currently posessing - * @return the entity that this entity is currently posessing - */ - LWOOBJID GetPossessable() const { return m_Possessable; } + /** + * Returns the entity that this entity is currently posessing + * @return the entity that this entity is currently posessing + */ + LWOOBJID GetPossessable() const { return m_Possessable; } - /** - * Sets if we are busy mounting or dismounting - * @param value if we are busy mounting or dismounting - */ - void SetIsBusy(bool value) { m_IsBusy = value; } + /** + * Sets if we are busy mounting or dismounting + * @param value if we are busy mounting or dismounting + */ + void SetIsBusy(bool value) { m_IsBusy = value; } - /** - * Returns if we are busy mounting or dismounting - * @return if we are busy mounting or dismounting - */ - bool GetIsBusy() const { return m_IsBusy; } + /** + * Returns if we are busy mounting or dismounting + * @return if we are busy mounting or dismounting + */ + bool GetIsBusy() const { return m_IsBusy; } - /** - * Sets the possesible type that's currently used, merely used by the shooting gallery if it's 0 - * @param value the possesible type to set - */ - void SetPossessableType(ePossessionType value) { m_PossessableType = value; m_DirtyPossesor = true; } + /** + * Sets the possesible type that's currently used, merely used by the shooting gallery if it's 0 + * @param value the possesible type to set + */ + void SetPossessableType(ePossessionType value) { m_PossessableType = value; m_DirtyPossesor = true; } - private: +private: - /** - * The ID of the entity this entity is possessing (e.g. the ID of a car) - */ - LWOOBJID m_Possessable = LWOOBJID_EMPTY; + /** + * The ID of the entity this entity is possessing (e.g. the ID of a car) + */ + LWOOBJID m_Possessable = LWOOBJID_EMPTY; - /** - * @brief possessable type - * - */ - ePossessionType m_PossessableType = ePossessionType::NO_POSSESSION; + /** + * @brief possessable type + * + */ + ePossessionType m_PossessableType = ePossessionType::NO_POSSESSION; - /** - * @brief if the possessor is dirty - * - */ - bool m_DirtyPossesor = false; + /** + * @brief if the possessor is dirty + * + */ + bool m_DirtyPossesor = false; - /** - * @brief if the possessor is busy mounting or dismounting - * - */ - bool m_IsBusy = false; + /** + * @brief if the possessor is busy mounting or dismounting + * + */ + bool m_IsBusy = false; }; diff --git a/dGame/dComponents/PropertyComponent.cpp b/dGame/dComponents/PropertyComponent.cpp index cbe8d156..4f8df40c 100644 --- a/dGame/dComponents/PropertyComponent.cpp +++ b/dGame/dComponents/PropertyComponent.cpp @@ -3,7 +3,7 @@ #include "dZoneManager.h" PropertyComponent::PropertyComponent(Entity* parent) : Component(parent) { - m_PropertyName = parent->GetVar(u"propertyName"); + m_PropertyName = parent->GetVar(u"propertyName"); m_PropertyState = new PropertyState(); } diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index 5bc24a9f..e6540417 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -12,15 +12,14 @@ #include "UserManager.h" #include "dLogger.h" -PropertyEntranceComponent::PropertyEntranceComponent(uint32_t componentID, Entity* parent) : Component(parent) -{ - this->propertyQueries = {}; +PropertyEntranceComponent::PropertyEntranceComponent(uint32_t componentID, Entity* parent) : Component(parent) { + this->propertyQueries = {}; - auto table = CDClientManager::Instance()->GetTable("PropertyEntranceComponent"); - const auto& entry = table->GetByID(componentID); + auto table = CDClientManager::Instance()->GetTable("PropertyEntranceComponent"); + const auto& entry = table->GetByID(componentID); - this->m_MapID = entry.mapID; - this->m_PropertyName = entry.propertyName; + this->m_MapID = entry.mapID; + this->m_PropertyName = entry.propertyName; } void PropertyEntranceComponent::OnUse(Entity* entity) { @@ -42,304 +41,294 @@ void PropertyEntranceComponent::OnUse(Entity* entity) { GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "pushGameState", &args); } -void PropertyEntranceComponent::OnEnterProperty(Entity* entity, uint32_t index, bool returnToZone, const SystemAddress& sysAddr) -{ - LWOCLONEID cloneId = 0; +void PropertyEntranceComponent::OnEnterProperty(Entity* entity, uint32_t index, bool returnToZone, const SystemAddress& sysAddr) { + LWOCLONEID cloneId = 0; - if (index == -1 && !returnToZone) - { - cloneId = entity->GetCharacter()->GetPropertyCloneID(); - } - else if (index == -1 && returnToZone) - { - cloneId = 0; - } - else if (index >= 0) - { - // Increment index once here because the first index of other player properties is 2 in the propertyQueries cache. - index++; + if (index == -1 && !returnToZone) { + cloneId = entity->GetCharacter()->GetPropertyCloneID(); + } else if (index == -1 && returnToZone) { + cloneId = 0; + } else if (index >= 0) { + // Increment index once here because the first index of other player properties is 2 in the propertyQueries cache. + index++; - const auto& pair = propertyQueries.find(entity->GetObjectID()); + const auto& pair = propertyQueries.find(entity->GetObjectID()); - if (pair == propertyQueries.end()) return; + if (pair == propertyQueries.end()) return; - const auto& query = pair->second; + const auto& query = pair->second; - if (index >= query.size()) return; + if (index >= query.size()) return; - cloneId = query[index].CloneId; - } + cloneId = query[index].CloneId; + } - auto* launcher = m_Parent->GetComponent(); + auto* launcher = m_Parent->GetComponent(); - if (launcher == nullptr) - { - return; - } + if (launcher == nullptr) { + return; + } - launcher->SetSelectedCloneId(entity->GetObjectID(), cloneId); + launcher->SetSelectedCloneId(entity->GetObjectID(), cloneId); - launcher->Launch(entity, launcher->GetTargetZone(), cloneId); + launcher->Launch(entity, launcher->GetTargetZone(), cloneId); } PropertySelectQueryProperty PropertyEntranceComponent::SetPropertyValues(PropertySelectQueryProperty property, LWOCLONEID cloneId, std::string ownerName, std::string propertyName, std::string propertyDescription, float reputation, bool isBFF, bool isFriend, bool isModeratorApproved, bool isAlt, bool isOwned, uint32_t privacyOption, uint32_t timeLastUpdated, float performanceCost) { - property.CloneId = cloneId; - property.OwnerName = ownerName; - property.Name = propertyName; - property.Description = propertyDescription; - property.Reputation = reputation; - property.IsBestFriend = isBFF; - property.IsFriend = isFriend; - property.IsModeratorApproved = isModeratorApproved; - property.IsAlt = isAlt; - property.IsOwned = isOwned; - property.AccessType = privacyOption; - property.DateLastPublished = timeLastUpdated; - property.PerformanceCost = performanceCost; + property.CloneId = cloneId; + property.OwnerName = ownerName; + property.Name = propertyName; + property.Description = propertyDescription; + property.Reputation = reputation; + property.IsBestFriend = isBFF; + property.IsFriend = isFriend; + property.IsModeratorApproved = isModeratorApproved; + property.IsAlt = isAlt; + property.IsOwned = isOwned; + property.AccessType = privacyOption; + property.DateLastPublished = timeLastUpdated; + property.PerformanceCost = performanceCost; - return property; + return property; } std::string PropertyEntranceComponent::BuildQuery(Entity* entity, int32_t sortMethod, Character* character, std::string customQuery, bool wantLimits) { - std::string base; - if (customQuery == "") { - base = baseQueryForProperties; - } else { - base = customQuery; - } - std::string orderBy = ""; - if (sortMethod == SORT_TYPE_FEATURED || sortMethod == SORT_TYPE_FRIENDS) { - std::string friendsList = " AND p.owner_id IN ("; + std::string base; + if (customQuery == "") { + base = baseQueryForProperties; + } else { + base = customQuery; + } + std::string orderBy = ""; + if (sortMethod == SORT_TYPE_FEATURED || sortMethod == SORT_TYPE_FRIENDS) { + std::string friendsList = " AND p.owner_id IN ("; - auto friendsListQuery = Database::CreatePreppedStmt("SELECT * FROM (SELECT CASE WHEN player_id = ? THEN friend_id WHEN friend_id = ? THEN player_id END AS requested_player FROM friends ) AS fr WHERE requested_player IS NOT NULL ORDER BY requested_player DESC;"); + auto friendsListQuery = Database::CreatePreppedStmt("SELECT * FROM (SELECT CASE WHEN player_id = ? THEN friend_id WHEN friend_id = ? THEN player_id END AS requested_player FROM friends ) AS fr WHERE requested_player IS NOT NULL ORDER BY requested_player DESC;"); - friendsListQuery->setUInt(1, character->GetID()); - friendsListQuery->setUInt(2, character->GetID()); + friendsListQuery->setUInt(1, character->GetID()); + friendsListQuery->setUInt(2, character->GetID()); - auto friendsListQueryResult = friendsListQuery->executeQuery(); + auto friendsListQueryResult = friendsListQuery->executeQuery(); - while (friendsListQueryResult->next()) { - auto playerIDToConvert = friendsListQueryResult->getInt(1); - friendsList = friendsList + std::to_string(playerIDToConvert) + ","; - } - // Replace trailing comma with the closing parenthesis. - if (friendsList.at(friendsList.size() - 1) == ',') friendsList.erase(friendsList.size() - 1, 1); - friendsList += ") "; + while (friendsListQueryResult->next()) { + auto playerIDToConvert = friendsListQueryResult->getInt(1); + friendsList = friendsList + std::to_string(playerIDToConvert) + ","; + } + // Replace trailing comma with the closing parenthesis. + if (friendsList.at(friendsList.size() - 1) == ',') friendsList.erase(friendsList.size() - 1, 1); + friendsList += ") "; - // If we have no friends then use a -1 for the query. - if (friendsList.find("()") != std::string::npos) friendsList = " AND p.owner_id IN (-1) "; + // If we have no friends then use a -1 for the query. + if (friendsList.find("()") != std::string::npos) friendsList = " AND p.owner_id IN (-1) "; - orderBy += friendsList + "ORDER BY ci.name ASC "; + orderBy += friendsList + "ORDER BY ci.name ASC "; - delete friendsListQueryResult; - friendsListQueryResult = nullptr; + delete friendsListQueryResult; + friendsListQueryResult = nullptr; - delete friendsListQuery; - friendsListQuery = nullptr; - } - else if (sortMethod == SORT_TYPE_RECENT) { - orderBy = "ORDER BY p.last_updated DESC "; - } - else if (sortMethod == SORT_TYPE_REPUTATION) { - orderBy = "ORDER BY p.reputation DESC, p.last_updated DESC "; - } - else { - orderBy = "ORDER BY p.last_updated DESC "; - } - return base + orderBy + (wantLimits ? "LIMIT ? OFFSET ?;" : ";"); + delete friendsListQuery; + friendsListQuery = nullptr; + } else if (sortMethod == SORT_TYPE_RECENT) { + orderBy = "ORDER BY p.last_updated DESC "; + } else if (sortMethod == SORT_TYPE_REPUTATION) { + orderBy = "ORDER BY p.reputation DESC, p.last_updated DESC "; + } else { + orderBy = "ORDER BY p.last_updated DESC "; + } + return base + orderBy + (wantLimits ? "LIMIT ? OFFSET ?;" : ";"); } -void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool includeNullAddress, bool includeNullDescription, bool playerOwn, bool updateUi, int32_t numResults, int32_t lReputationTime, int32_t sortMethod, int32_t startIndex, std::string filterText, const SystemAddress& sysAddr){ +void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool includeNullAddress, bool includeNullDescription, bool playerOwn, bool updateUi, int32_t numResults, int32_t lReputationTime, int32_t sortMethod, int32_t startIndex, std::string filterText, const SystemAddress& sysAddr) { - std::vector entries {}; - PropertySelectQueryProperty playerEntry {}; + std::vector entries{}; + PropertySelectQueryProperty playerEntry{}; - auto character = entity->GetCharacter(); - if (!character) return; + auto character = entity->GetCharacter(); + if (!character) return; - // Player property goes in index 1 of the vector. This is how the client expects it. - auto playerPropertyLookup = Database::CreatePreppedStmt("SELECT * FROM properties WHERE owner_id = ? AND zone_id = ?"); + // Player property goes in index 1 of the vector. This is how the client expects it. + auto playerPropertyLookup = Database::CreatePreppedStmt("SELECT * FROM properties WHERE owner_id = ? AND zone_id = ?"); - playerPropertyLookup->setInt(1, character->GetID()); - playerPropertyLookup->setInt(2, this->m_MapID); + playerPropertyLookup->setInt(1, character->GetID()); + playerPropertyLookup->setInt(2, this->m_MapID); - auto playerPropertyLookupResults = playerPropertyLookup->executeQuery(); + auto playerPropertyLookupResults = playerPropertyLookup->executeQuery(); - // If the player has a property this query will have a single result. - if (playerPropertyLookupResults->next()) { - const auto cloneId = playerPropertyLookupResults->getUInt64(4); - const auto propertyName = std::string(playerPropertyLookupResults->getString(5).c_str()); - const auto propertyDescription = std::string(playerPropertyLookupResults->getString(6).c_str()); - const auto privacyOption = playerPropertyLookupResults->getInt(9); - const auto modApproved = playerPropertyLookupResults->getBoolean(10); - const auto dateLastUpdated = playerPropertyLookupResults->getInt64(11); - const auto reputation = playerPropertyLookupResults->getUInt(14); - const auto performanceCost = (float)playerPropertyLookupResults->getDouble(16); + // If the player has a property this query will have a single result. + if (playerPropertyLookupResults->next()) { + const auto cloneId = playerPropertyLookupResults->getUInt64(4); + const auto propertyName = std::string(playerPropertyLookupResults->getString(5).c_str()); + const auto propertyDescription = std::string(playerPropertyLookupResults->getString(6).c_str()); + const auto privacyOption = playerPropertyLookupResults->getInt(9); + const auto modApproved = playerPropertyLookupResults->getBoolean(10); + const auto dateLastUpdated = playerPropertyLookupResults->getInt64(11); + const auto reputation = playerPropertyLookupResults->getUInt(14); + const auto performanceCost = (float)playerPropertyLookupResults->getDouble(16); - playerEntry = SetPropertyValues(playerEntry, cloneId, character->GetName(), propertyName, propertyDescription, reputation, true, true, modApproved, true, true, privacyOption, dateLastUpdated, performanceCost); - } else { - playerEntry = SetPropertyValues(playerEntry, character->GetPropertyCloneID(), character->GetName(), "", "", 0, true, true); - } + playerEntry = SetPropertyValues(playerEntry, cloneId, character->GetName(), propertyName, propertyDescription, reputation, true, true, modApproved, true, true, privacyOption, dateLastUpdated, performanceCost); + } else { + playerEntry = SetPropertyValues(playerEntry, character->GetPropertyCloneID(), character->GetName(), "", "", 0, true, true); + } - delete playerPropertyLookupResults; - playerPropertyLookupResults = nullptr; + delete playerPropertyLookupResults; + playerPropertyLookupResults = nullptr; - delete playerPropertyLookup; - playerPropertyLookup = nullptr; + delete playerPropertyLookup; + playerPropertyLookup = nullptr; - entries.push_back(playerEntry); + entries.push_back(playerEntry); - const auto query = BuildQuery(entity, sortMethod, character); + const auto query = BuildQuery(entity, sortMethod, character); - auto propertyLookup = Database::CreatePreppedStmt(query); + auto propertyLookup = Database::CreatePreppedStmt(query); - const auto searchString = "%" + filterText + "%"; - propertyLookup->setUInt(1, this->m_MapID); - propertyLookup->setString(2, searchString.c_str()); - propertyLookup->setString(3, searchString.c_str()); - propertyLookup->setString(4, searchString.c_str()); - propertyLookup->setInt(5, sortMethod == SORT_TYPE_FEATURED || sortMethod == SORT_TYPE_FRIENDS ? (uint32_t)PropertyPrivacyOption::Friends : (uint32_t)PropertyPrivacyOption::Public); - propertyLookup->setInt(6, numResults); - propertyLookup->setInt(7, startIndex); + const auto searchString = "%" + filterText + "%"; + propertyLookup->setUInt(1, this->m_MapID); + propertyLookup->setString(2, searchString.c_str()); + propertyLookup->setString(3, searchString.c_str()); + propertyLookup->setString(4, searchString.c_str()); + propertyLookup->setInt(5, sortMethod == SORT_TYPE_FEATURED || sortMethod == SORT_TYPE_FRIENDS ? (uint32_t)PropertyPrivacyOption::Friends : (uint32_t)PropertyPrivacyOption::Public); + propertyLookup->setInt(6, numResults); + propertyLookup->setInt(7, startIndex); - auto propertyEntry = propertyLookup->executeQuery(); + auto propertyEntry = propertyLookup->executeQuery(); - while (propertyEntry->next()) { - const auto propertyId = propertyEntry->getUInt64(1); - const auto owner = propertyEntry->getInt(2); - const auto cloneId = propertyEntry->getUInt64(4); - const auto propertyNameFromDb = std::string(propertyEntry->getString(5).c_str()); - const auto propertyDescriptionFromDb = std::string(propertyEntry->getString(6).c_str()); - const auto privacyOption = propertyEntry->getInt(9); - const auto modApproved = propertyEntry->getBoolean(10); - const auto dateLastUpdated = propertyEntry->getInt(11); - const float reputation = propertyEntry->getInt(14); - const auto performanceCost = (float)propertyEntry->getDouble(16); + while (propertyEntry->next()) { + const auto propertyId = propertyEntry->getUInt64(1); + const auto owner = propertyEntry->getInt(2); + const auto cloneId = propertyEntry->getUInt64(4); + const auto propertyNameFromDb = std::string(propertyEntry->getString(5).c_str()); + const auto propertyDescriptionFromDb = std::string(propertyEntry->getString(6).c_str()); + const auto privacyOption = propertyEntry->getInt(9); + const auto modApproved = propertyEntry->getBoolean(10); + const auto dateLastUpdated = propertyEntry->getInt(11); + const float reputation = propertyEntry->getInt(14); + const auto performanceCost = (float)propertyEntry->getDouble(16); - PropertySelectQueryProperty entry{}; + PropertySelectQueryProperty entry{}; - std::string ownerName = ""; - bool isOwned = true; - auto nameLookup = Database::CreatePreppedStmt("SELECT name FROM charinfo WHERE prop_clone_id = ?;"); + std::string ownerName = ""; + bool isOwned = true; + auto nameLookup = Database::CreatePreppedStmt("SELECT name FROM charinfo WHERE prop_clone_id = ?;"); - nameLookup->setUInt64(1, cloneId); + nameLookup->setUInt64(1, cloneId); - auto nameResult = nameLookup->executeQuery(); + auto nameResult = nameLookup->executeQuery(); - if (!nameResult->next()) { - delete nameLookup; - nameLookup = nullptr; + if (!nameResult->next()) { + delete nameLookup; + nameLookup = nullptr; - Game::logger->Log("PropertyEntranceComponent", "Failed to find property owner name for %llu!", cloneId); + Game::logger->Log("PropertyEntranceComponent", "Failed to find property owner name for %llu!", cloneId); - continue; - } else { - isOwned = cloneId == character->GetPropertyCloneID(); - ownerName = std::string(nameResult->getString(1).c_str()); - } + continue; + } else { + isOwned = cloneId == character->GetPropertyCloneID(); + ownerName = std::string(nameResult->getString(1).c_str()); + } - delete nameResult; - nameResult = nullptr; + delete nameResult; + nameResult = nullptr; - delete nameLookup; - nameLookup = nullptr; + delete nameLookup; + nameLookup = nullptr; - std::string propertyName = propertyNameFromDb; - std::string propertyDescription = propertyDescriptionFromDb; + std::string propertyName = propertyNameFromDb; + std::string propertyDescription = propertyDescriptionFromDb; - bool isBestFriend = false; - bool isFriend = false; + bool isBestFriend = false; + bool isFriend = false; - // Convert owner char id to LWOOBJID - LWOOBJID ownerObjId = owner; - ownerObjId = GeneralUtils::SetBit(ownerObjId, OBJECT_BIT_CHARACTER); - ownerObjId = GeneralUtils::SetBit(ownerObjId, OBJECT_BIT_PERSISTENT); + // Convert owner char id to LWOOBJID + LWOOBJID ownerObjId = owner; + ownerObjId = GeneralUtils::SetBit(ownerObjId, OBJECT_BIT_CHARACTER); + ownerObjId = GeneralUtils::SetBit(ownerObjId, OBJECT_BIT_PERSISTENT); - // Query to get friend and best friend fields - auto friendCheck = Database::CreatePreppedStmt("SELECT best_friend FROM friends WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?)"); + // Query to get friend and best friend fields + auto friendCheck = Database::CreatePreppedStmt("SELECT best_friend FROM friends WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?)"); - friendCheck->setUInt(1, character->GetID()); - friendCheck->setUInt(2, ownerObjId); - friendCheck->setUInt(3, ownerObjId); - friendCheck->setUInt(4, character->GetID()); + friendCheck->setUInt(1, character->GetID()); + friendCheck->setUInt(2, ownerObjId); + friendCheck->setUInt(3, ownerObjId); + friendCheck->setUInt(4, character->GetID()); - auto friendResult = friendCheck->executeQuery(); + auto friendResult = friendCheck->executeQuery(); - // If we got a result than the two players are friends. - if (friendResult->next()) { - isFriend = true; - if (friendResult->getInt(1) == 3) { - isBestFriend = true; - } - } + // If we got a result than the two players are friends. + if (friendResult->next()) { + isFriend = true; + if (friendResult->getInt(1) == 3) { + isBestFriend = true; + } + } - delete friendCheck; - friendCheck = nullptr; + delete friendCheck; + friendCheck = nullptr; - delete friendResult; - friendResult = nullptr; + delete friendResult; + friendResult = nullptr; - bool isModeratorApproved = propertyEntry->getBoolean(10); + bool isModeratorApproved = propertyEntry->getBoolean(10); - if (!isModeratorApproved && entity->GetGMLevel() >= GAME_MASTER_LEVEL_LEAD_MODERATOR) { - propertyName = "[AWAITING APPROVAL]"; - propertyDescription = "[AWAITING APPROVAL]"; - isModeratorApproved = true; - } + if (!isModeratorApproved && entity->GetGMLevel() >= GAME_MASTER_LEVEL_LEAD_MODERATOR) { + propertyName = "[AWAITING APPROVAL]"; + propertyDescription = "[AWAITING APPROVAL]"; + isModeratorApproved = true; + } - bool isAlt = false; - // Query to determine whether this property is an alt character of the entity. - auto isAltQuery = Database::CreatePreppedStmt("SELECT id FROM charinfo where account_id in (SELECT account_id from charinfo WHERE id = ?) AND id = ?;"); + bool isAlt = false; + // Query to determine whether this property is an alt character of the entity. + auto isAltQuery = Database::CreatePreppedStmt("SELECT id FROM charinfo where account_id in (SELECT account_id from charinfo WHERE id = ?) AND id = ?;"); - isAltQuery->setInt(1, character->GetID()); - isAltQuery->setInt(2, owner); + isAltQuery->setInt(1, character->GetID()); + isAltQuery->setInt(2, owner); - auto isAltQueryResults = isAltQuery->executeQuery(); + auto isAltQueryResults = isAltQuery->executeQuery(); - if (isAltQueryResults->next()) { - isAlt = true; - } + if (isAltQueryResults->next()) { + isAlt = true; + } - delete isAltQueryResults; - isAltQueryResults = nullptr; + delete isAltQueryResults; + isAltQueryResults = nullptr; - delete isAltQuery; - isAltQuery = nullptr; + delete isAltQuery; + isAltQuery = nullptr; - entry = SetPropertyValues(entry, cloneId, ownerName, propertyName, propertyDescription, reputation, isBestFriend, isFriend, isModeratorApproved, isAlt, isOwned, privacyOption, dateLastUpdated, performanceCost); + entry = SetPropertyValues(entry, cloneId, ownerName, propertyName, propertyDescription, reputation, isBestFriend, isFriend, isModeratorApproved, isAlt, isOwned, privacyOption, dateLastUpdated, performanceCost); - entries.push_back(entry); - } + entries.push_back(entry); + } - delete propertyEntry; - propertyEntry = nullptr; + delete propertyEntry; + propertyEntry = nullptr; - delete propertyLookup; - propertyLookup = nullptr; + delete propertyLookup; + propertyLookup = nullptr; - propertyQueries[entity->GetObjectID()] = entries; + propertyQueries[entity->GetObjectID()] = entries; - // Query here is to figure out whether or not to display the button to go to the next page or not. - int32_t numberOfProperties = 0; + // Query here is to figure out whether or not to display the button to go to the next page or not. + int32_t numberOfProperties = 0; - auto buttonQuery = BuildQuery(entity, sortMethod, character, "SELECT COUNT(*) FROM properties as p JOIN charinfo as ci ON ci.prop_clone_id = p.clone_id where p.zone_id = ? AND (p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ?) AND p.privacy_option >= ? ", false); - auto propertiesLeft = Database::CreatePreppedStmt(buttonQuery); + auto buttonQuery = BuildQuery(entity, sortMethod, character, "SELECT COUNT(*) FROM properties as p JOIN charinfo as ci ON ci.prop_clone_id = p.clone_id where p.zone_id = ? AND (p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ?) AND p.privacy_option >= ? ", false); + auto propertiesLeft = Database::CreatePreppedStmt(buttonQuery); - propertiesLeft->setUInt(1, this->m_MapID); - propertiesLeft->setString(2, searchString.c_str()); - propertiesLeft->setString(3, searchString.c_str()); - propertiesLeft->setString(4, searchString.c_str()); - propertiesLeft->setInt(5, sortMethod == SORT_TYPE_FEATURED || sortMethod == SORT_TYPE_FRIENDS ? 1 : 2); + propertiesLeft->setUInt(1, this->m_MapID); + propertiesLeft->setString(2, searchString.c_str()); + propertiesLeft->setString(3, searchString.c_str()); + propertiesLeft->setString(4, searchString.c_str()); + propertiesLeft->setInt(5, sortMethod == SORT_TYPE_FEATURED || sortMethod == SORT_TYPE_FRIENDS ? 1 : 2); - auto result = propertiesLeft->executeQuery(); - result->next(); - numberOfProperties = result->getInt(1); + auto result = propertiesLeft->executeQuery(); + result->next(); + numberOfProperties = result->getInt(1); - delete result; - result = nullptr; + delete result; + result = nullptr; - delete propertiesLeft; - propertiesLeft = nullptr; + delete propertiesLeft; + propertiesLeft = nullptr; - GameMessages::SendPropertySelectQuery(m_Parent->GetObjectID(), startIndex, numberOfProperties - (startIndex + numResults) > 0, character->GetPropertyCloneID(), false, true, entries, sysAddr); + GameMessages::SendPropertySelectQuery(m_Parent->GetObjectID(), startIndex, numberOfProperties - (startIndex + numResults) > 0, character->GetPropertyCloneID(), false, true, entries, sysAddr); } diff --git a/dGame/dComponents/PropertyEntranceComponent.h b/dGame/dComponents/PropertyEntranceComponent.h index fe583e92..6087faf2 100644 --- a/dGame/dComponents/PropertyEntranceComponent.h +++ b/dGame/dComponents/PropertyEntranceComponent.h @@ -11,79 +11,79 @@ * Represents the launch pad that's used to select and browse properties */ class PropertyEntranceComponent : public Component { - public: - static const uint32_t ComponentType = COMPONENT_TYPE_PROPERTY_ENTRANCE; - explicit PropertyEntranceComponent(uint32_t componentID, Entity* parent); +public: + static const uint32_t ComponentType = COMPONENT_TYPE_PROPERTY_ENTRANCE; + explicit PropertyEntranceComponent(uint32_t componentID, Entity* parent); - /** - * Handles an OnUse request for some other entity, rendering the property browse menu - * @param entity the entity that triggered the event - */ - void OnUse(Entity* entity) override; + /** + * Handles an OnUse request for some other entity, rendering the property browse menu + * @param entity the entity that triggered the event + */ + void OnUse(Entity* entity) override; - /** - * Handles the event triggered when the entity selects a property to visit and makes the entity to there - * @param entity the entity that triggered the event - * @param index the index of the property property - * @param returnToZone whether or not the entity wishes to go back to the launch zone - * @param sysAddr the address to send gamemessage responses to - */ - void OnEnterProperty(Entity* entity, uint32_t index, bool returnToZone, const SystemAddress& sysAddr); + /** + * Handles the event triggered when the entity selects a property to visit and makes the entity to there + * @param entity the entity that triggered the event + * @param index the index of the property property + * @param returnToZone whether or not the entity wishes to go back to the launch zone + * @param sysAddr the address to send gamemessage responses to + */ + void OnEnterProperty(Entity* entity, uint32_t index, bool returnToZone, const SystemAddress& sysAddr); - /** - * Handles a request for information on available properties when an entity lands on the property - * @param entity the entity that triggered the event - * @param includeNullAddress unused - * @param includeNullDescription unused - * @param playerOwn only query properties owned by the entity - * @param updateUi unused - * @param numResults unused - * @param lReputationTime unused - * @param sortMethod unused - * @param startIndex the minimum index to start the query off - * @param filterText property names to search for - * @param sysAddr the address to send gamemessage responses to - */ - void OnPropertyEntranceSync(Entity* entity, bool includeNullAddress, bool includeNullDescription, bool playerOwn, bool updateUi, int32_t numResults, int32_t lReputationTime, int32_t sortMethod, int32_t startIndex, std::string filterText, const SystemAddress& sysAddr); + /** + * Handles a request for information on available properties when an entity lands on the property + * @param entity the entity that triggered the event + * @param includeNullAddress unused + * @param includeNullDescription unused + * @param playerOwn only query properties owned by the entity + * @param updateUi unused + * @param numResults unused + * @param lReputationTime unused + * @param sortMethod unused + * @param startIndex the minimum index to start the query off + * @param filterText property names to search for + * @param sysAddr the address to send gamemessage responses to + */ + void OnPropertyEntranceSync(Entity* entity, bool includeNullAddress, bool includeNullDescription, bool playerOwn, bool updateUi, int32_t numResults, int32_t lReputationTime, int32_t sortMethod, int32_t startIndex, std::string filterText, const SystemAddress& sysAddr); - /** - * Returns the name of this property - * @return the name of this property - */ - [[nodiscard]] std::string GetPropertyName() const { return m_PropertyName; }; + /** + * Returns the name of this property + * @return the name of this property + */ + [[nodiscard]] std::string GetPropertyName() const { return m_PropertyName; }; - /** - * Returns the map ID for this property - * @return the map ID for this property - */ - [[nodiscard]] LWOMAPID GetMapID() const { return m_MapID; }; + /** + * Returns the map ID for this property + * @return the map ID for this property + */ + [[nodiscard]] LWOMAPID GetMapID() const { return m_MapID; }; - PropertySelectQueryProperty SetPropertyValues(PropertySelectQueryProperty property, LWOCLONEID cloneId = LWOCLONEID_INVALID, std::string ownerName = "", std::string propertyName = "", std::string propertyDescription = "", float reputation = 0, bool isBFF = false, bool isFriend = false, bool isModeratorApproved = false, bool isAlt = false, bool isOwned = false, uint32_t privacyOption = 0, uint32_t timeLastUpdated = 0, float performanceCost = 0.0f); + PropertySelectQueryProperty SetPropertyValues(PropertySelectQueryProperty property, LWOCLONEID cloneId = LWOCLONEID_INVALID, std::string ownerName = "", std::string propertyName = "", std::string propertyDescription = "", float reputation = 0, bool isBFF = false, bool isFriend = false, bool isModeratorApproved = false, bool isAlt = false, bool isOwned = false, uint32_t privacyOption = 0, uint32_t timeLastUpdated = 0, float performanceCost = 0.0f); - std::string BuildQuery(Entity* entity, int32_t sortMethod, Character* character, std::string customQuery = "", bool wantLimits = true); + std::string BuildQuery(Entity* entity, int32_t sortMethod, Character* character, std::string customQuery = "", bool wantLimits = true); - private: - /** - * Cache of property information that was queried for property launched, indexed by property ID - */ - std::map> propertyQueries; +private: + /** + * Cache of property information that was queried for property launched, indexed by property ID + */ + std::map> propertyQueries; - /** - * The custom name for this property - */ - std::string m_PropertyName; + /** + * The custom name for this property + */ + std::string m_PropertyName; - /** - * The base map ID for this property (Avant Grove, etc). - */ - LWOMAPID m_MapID; + /** + * The base map ID for this property (Avant Grove, etc). + */ + LWOMAPID m_MapID; - enum ePropertySortType : int32_t { - SORT_TYPE_FRIENDS = 0, - SORT_TYPE_REPUTATION = 1, - SORT_TYPE_RECENT = 3, - SORT_TYPE_FEATURED = 5 - }; + enum ePropertySortType : int32_t { + SORT_TYPE_FRIENDS = 0, + SORT_TYPE_REPUTATION = 1, + SORT_TYPE_RECENT = 3, + SORT_TYPE_FEATURED = 5 + }; - std::string baseQueryForProperties = "SELECT p.* FROM properties as p JOIN charinfo as ci ON ci.prop_clone_id = p.clone_id where p.zone_id = ? AND (p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ?) AND p.privacy_option >= ? "; + std::string baseQueryForProperties = "SELECT p.* FROM properties as p JOIN charinfo as ci ON ci.prop_clone_id = p.clone_id where p.zone_id = ? AND (p.description LIKE ? OR p.name LIKE ? OR ci.name LIKE ?) AND p.privacy_option >= ? "; }; diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index fa9a7e52..bc3d8395 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -23,8 +23,7 @@ PropertyManagementComponent* PropertyManagementComponent::instance = nullptr; -PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Component(parent) -{ +PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Component(parent) { this->owner = LWOOBJID_EMPTY; this->templateId = 0; this->propertyId = LWOOBJID_EMPTY; @@ -43,12 +42,11 @@ PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Compo auto query = CDClientDatabase::CreatePreppedStmt( "SELECT id FROM PropertyTemplate WHERE mapID = ?;"); - query.bind(1, (int) zoneId); + query.bind(1, (int)zoneId); auto result = query.execQuery(); - if (result.eof() || result.fieldIsNull(0)) - { + if (result.eof() || result.fieldIsNull(0)) { return; } @@ -63,8 +61,7 @@ PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Compo auto* propertyEntry = propertyLookup->executeQuery(); - if (propertyEntry->next()) - { + if (propertyEntry->next()) { this->propertyId = propertyEntry->getUInt64(1); this->owner = propertyEntry->getUInt64(2); this->owner = GeneralUtils::SetBit(this->owner, OBJECT_BIT_CHARACTER); @@ -85,35 +82,30 @@ PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Compo delete propertyLookup; } -LWOOBJID PropertyManagementComponent::GetOwnerId() const -{ +LWOOBJID PropertyManagementComponent::GetOwnerId() const { return owner; } -Entity* PropertyManagementComponent::GetOwner() const -{ +Entity* PropertyManagementComponent::GetOwner() const { return EntityManager::Instance()->GetEntity(owner); } -void PropertyManagementComponent::SetOwner(Entity* value) -{ +void PropertyManagementComponent::SetOwner(Entity* value) { owner = value->GetObjectID(); } -std::vector PropertyManagementComponent::GetPaths() const -{ +std::vector PropertyManagementComponent::GetPaths() const { const auto zoneId = dZoneManager::Instance()->GetZone()->GetWorldID(); auto query = CDClientDatabase::CreatePreppedStmt( "SELECT path FROM PropertyTemplate WHERE mapID = ?;"); - query.bind(1, (int) zoneId); + query.bind(1, (int)zoneId); auto result = query.execQuery(); - std::vector paths {}; + std::vector paths{}; - if (result.eof()) - { + if (result.eof()) { return paths; } @@ -122,35 +114,28 @@ std::vector PropertyManagementComponent::GetPaths() const std::istringstream stream(result.getStringField(0)); std::string token; - while (std::getline(stream, token, ' ')) - { - try - { + while (std::getline(stream, token, ' ')) { + try { auto value = std::stof(token); points.push_back(value); - } - catch (std::invalid_argument& exception) - { + } catch (std::invalid_argument& exception) { Game::logger->Log("PropertyManagementComponent", "Failed to parse value (%s): (%s)!", token.c_str(), exception.what()); } } - for (auto i = 0u; i < points.size(); i += 3) - { + for (auto i = 0u; i < points.size(); i += 3) { paths.emplace_back(points[i], points[i + 1], points[i + 2]); } return paths; } -PropertyPrivacyOption PropertyManagementComponent::GetPrivacyOption() const -{ +PropertyPrivacyOption PropertyManagementComponent::GetPrivacyOption() const { return privacyOption; } -void PropertyManagementComponent::SetPrivacyOption(PropertyPrivacyOption value) -{ +void PropertyManagementComponent::SetPrivacyOption(PropertyPrivacyOption value) { if (owner == LWOOBJID_EMPTY) return; if (value == static_cast(3)) // Client sends 3 for private for some reason, but expects 0 in return? @@ -174,8 +159,7 @@ void PropertyManagementComponent::SetPrivacyOption(PropertyPrivacyOption value) propertyUpdate->executeUpdate(); } -void PropertyManagementComponent::UpdatePropertyDetails(std::string name, std::string description) -{ +void PropertyManagementComponent::UpdatePropertyDetails(std::string name, std::string description) { if (owner == LWOOBJID_EMPTY) return; propertyName = name; @@ -193,10 +177,8 @@ void PropertyManagementComponent::UpdatePropertyDetails(std::string name, std::s OnQueryPropertyData(GetOwner(), UNASSIGNED_SYSTEM_ADDRESS); } -bool PropertyManagementComponent::Claim(const LWOOBJID playerId) -{ - if (owner != LWOOBJID_EMPTY) - { +bool PropertyManagementComponent::Claim(const LWOOBJID playerId) { + if (owner != LWOOBJID_EMPTY) { return false; } @@ -228,19 +210,16 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) "VALUES (?, ?, ?, ?, ?, '', 0, 0, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), '', 0, ?, 0.0)" ); insertion->setUInt64(1, propertyId); - insertion->setUInt64(2, (uint32_t) playerId); + insertion->setUInt64(2, (uint32_t)playerId); insertion->setUInt(3, templateId); insertion->setUInt64(4, playerCloneId); insertion->setString(5, zone->GetZoneName().c_str()); insertion->setInt(6, propertyZoneId); // Try and execute the query, print an error if it fails. - try - { + try { insertion->execute(); - } - catch (sql::SQLException& exception) - { + } catch (sql::SQLException& exception) { Game::logger->Log("PropertyManagementComponent", "Failed to execute query: (%s)!", exception.what()); throw exception; @@ -248,14 +227,13 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) } auto* zoneControlObject = dZoneManager::Instance()->GetZoneControlObject(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControlObject)) { - script->OnZonePropertyRented(zoneControlObject, entity); - } + for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControlObject)) { + script->OnZonePropertyRented(zoneControlObject, entity); + } return true; } -void PropertyManagementComponent::OnStartBuilding() -{ +void PropertyManagementComponent::OnStartBuilding() { auto* ownerEntity = GetOwner(); if (ownerEntity == nullptr) return; @@ -270,18 +248,15 @@ void PropertyManagementComponent::OnStartBuilding() SetPrivacyOption(PropertyPrivacyOption::Private); // Cant visit player which is building - if (!entrance.empty()) - { + if (!entrance.empty()) { auto* rocketPad = entrance[0]->GetComponent(); - if (rocketPad != nullptr) - { + if (rocketPad != nullptr) { zoneId = rocketPad->GetDefaultZone(); } } - for (auto* player : players) - { + for (auto* player : players) { if (player == ownerEntity) continue; player->SendToZone(zoneId); @@ -292,8 +267,7 @@ void PropertyManagementComponent::OnStartBuilding() if (inventoryComponent) inventoryComponent->PushEquippedItems(); } -void PropertyManagementComponent::OnFinishBuilding() -{ +void PropertyManagementComponent::OnFinishBuilding() { auto* ownerEntity = GetOwner(); if (ownerEntity == nullptr) return; @@ -305,28 +279,24 @@ void PropertyManagementComponent::OnFinishBuilding() Save(); } -void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const NiPoint3 position, NiQuaternion rotation) -{ +void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const NiPoint3 position, NiQuaternion rotation) { Game::logger->Log("PropertyManagementComponent", "Placing model <%f, %f, %f>", position.x, position.y, position.z); auto* entity = GetOwner(); - if (entity == nullptr) - { + if (entity == nullptr) { return; } auto* inventoryComponent = entity->GetComponent(); - if (inventoryComponent == nullptr) - { + if (inventoryComponent == nullptr) { return; } auto* item = inventoryComponent->FindItemById(id); - if (item == nullptr) - { + if (item == nullptr) { Game::logger->Log("PropertyManagementComponent", "Failed to find item with id %d", id); return; @@ -336,8 +306,7 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N const auto modelLOT = item->GetLot(); - if (rotation != NiQuaternion::IDENTITY) - { + if (rotation != NiQuaternion::IDENTITY) { rotation = { rotation.w, rotation.z, rotation.y, rotation.x }; } @@ -377,78 +346,73 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N node->position = position; node->rotation = rotation; - ObjectIDManager::Instance()->RequestPersistentID([this, node, modelLOT, entity, position, rotation, originalRotation](uint32_t persistentId) - { - SpawnerInfo info{}; + ObjectIDManager::Instance()->RequestPersistentID([this, node, modelLOT, entity, position, rotation, originalRotation](uint32_t persistentId) { + SpawnerInfo info{}; - info.templateID = modelLOT; - info.nodes = { node }; - info.templateScale = 1.0f; - info.activeOnLoad = true; - info.amountMaintained = 1; - info.respawnTime = 10; + info.templateID = modelLOT; + info.nodes = { node }; + info.templateScale = 1.0f; + info.activeOnLoad = true; + info.amountMaintained = 1; + info.respawnTime = 10; - info.emulated = true; - info.emulator = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); + info.emulated = true; + info.emulator = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); - LWOOBJID id = static_cast(persistentId) | 1ull << OBJECT_BIT_CLIENT; + LWOOBJID id = static_cast(persistentId) | 1ull << OBJECT_BIT_CLIENT; - info.spawnerID = id; + info.spawnerID = id; - const auto spawnerId = dZoneManager::Instance()->MakeSpawner(info); + const auto spawnerId = dZoneManager::Instance()->MakeSpawner(info); - auto* spawner = dZoneManager::Instance()->GetSpawner(spawnerId); + auto* spawner = dZoneManager::Instance()->GetSpawner(spawnerId); - auto ldfModelBehavior = new LDFData(u"modelBehaviors", 0); - auto userModelID = new LDFData(u"userModelID", id); - auto modelType = new LDFData(u"modelType", 2); - auto propertyObjectID = new LDFData(u"propertyObjectID", true); - auto componentWhitelist = new LDFData(u"componentWhitelist", 1); - info.nodes[0]->config.push_back(componentWhitelist); - info.nodes[0]->config.push_back(ldfModelBehavior); - info.nodes[0]->config.push_back(modelType); - info.nodes[0]->config.push_back(propertyObjectID); - info.nodes[0]->config.push_back(userModelID); + auto ldfModelBehavior = new LDFData(u"modelBehaviors", 0); + auto userModelID = new LDFData(u"userModelID", id); + auto modelType = new LDFData(u"modelType", 2); + auto propertyObjectID = new LDFData(u"propertyObjectID", true); + auto componentWhitelist = new LDFData(u"componentWhitelist", 1); + info.nodes[0]->config.push_back(componentWhitelist); + info.nodes[0]->config.push_back(ldfModelBehavior); + info.nodes[0]->config.push_back(modelType); + info.nodes[0]->config.push_back(propertyObjectID); + info.nodes[0]->config.push_back(userModelID); - auto* model = spawner->Spawn(); + auto* model = spawner->Spawn(); - models.insert_or_assign(model->GetObjectID(), spawnerId); + models.insert_or_assign(model->GetObjectID(), spawnerId); - GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), position, m_Parent->GetObjectID(), 14, originalRotation); + GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), position, m_Parent->GetObjectID(), 14, originalRotation); - GameMessages::SendUGCEquipPreCreateBasedOnEditMode(entity->GetObjectID(), entity->GetSystemAddress(), 0, spawnerId); + GameMessages::SendUGCEquipPreCreateBasedOnEditMode(entity->GetObjectID(), entity->GetSystemAddress(), 0, spawnerId); - GameMessages::SendGetModelsOnProperty(entity->GetObjectID(), GetModels(), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendGetModelsOnProperty(entity->GetObjectID(), GetModels(), UNASSIGNED_SYSTEM_ADDRESS); - EntityManager::Instance()->GetZoneControlEntity()->OnZonePropertyModelPlaced(entity); + EntityManager::Instance()->GetZoneControlEntity()->OnZonePropertyModelPlaced(entity); }); - // Progress place model missions - auto missionComponent = entity->GetComponent(); - if (missionComponent != nullptr) missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_PLACE_MODEL, 0); + // Progress place model missions + auto missionComponent = entity->GetComponent(); + if (missionComponent != nullptr) missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_PLACE_MODEL, 0); } -void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int deleteReason) -{ +void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int deleteReason) { Game::logger->Log("PropertyManagementComponent", "Delete model: (%llu) (%i)", id, deleteReason); auto* entity = GetOwner(); - if (entity == nullptr) - { + if (entity == nullptr) { return; } auto* inventoryComponent = entity->GetComponent(); - if (inventoryComponent == nullptr) - { + if (inventoryComponent == nullptr) { return; } const auto index = models.find(id); - if (index == models.end()) - { + if (index == models.end()) { Game::logger->Log("PropertyManagementComponent", "Failed to find model"); return; @@ -460,15 +424,13 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet models.erase(id); - if (spawner == nullptr) - { + if (spawner == nullptr) { Game::logger->Log("PropertyManagementComponent", "Failed to find spawner"); } auto* model = EntityManager::Instance()->GetEntity(id); - if (model == nullptr) - { + if (model == nullptr) { Game::logger->Log("PropertyManagementComponent", "Failed to find model entity"); return; @@ -478,8 +440,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet Game::logger->Log("PropertyManagementComponent", "Deleting model LOT %i", model->GetLOT()); - if (model->GetLOT() == 14) - { + if (model->GetLOT() == 14) { //add it to the inv std::vector settings; @@ -509,13 +470,11 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet return; } - if (deleteReason == 0) - { + if (deleteReason == 0) { //item->Equip(); } - if (deleteReason == 0 || deleteReason == 2) - { + if (deleteReason == 0 || deleteReason == 2) { GameMessages::SendUGCEquipPostDeleteBasedOnEditMode(entity->GetObjectID(), entity->GetSystemAddress(), item->GetId(), item->GetCount()); } @@ -523,12 +482,9 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3::ZERO, LWOOBJID_EMPTY, 16, NiQuaternion::IDENTITY); - if (spawner != nullptr) - { + if (spawner != nullptr) { dZoneManager::Instance()->RemoveSpawner(spawner->m_Info.spawnerID); - } - else - { + } else { model->Smash(SILENT); } @@ -545,8 +501,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet return; } - switch (deleteReason) - { + switch (deleteReason) { case 0: // Pickup { item->Equip(); @@ -580,18 +535,14 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3::ZERO, LWOOBJID_EMPTY, 16, NiQuaternion::IDENTITY); - if (spawner != nullptr) - { + if (spawner != nullptr) { dZoneManager::Instance()->RemoveSpawner(spawner->m_Info.spawnerID); - } - else - { + } else { model->Smash(SILENT); } } -void PropertyManagementComponent::UpdateApprovedStatus(const bool value) -{ +void PropertyManagementComponent::UpdateApprovedStatus(const bool value) { if (owner == LWOOBJID_EMPTY) return; auto* update = Database::CreatePreppedStmt("UPDATE properties SET mod_approved = ? WHERE id = ?;"); @@ -604,10 +555,8 @@ void PropertyManagementComponent::UpdateApprovedStatus(const bool value) delete update; } -void PropertyManagementComponent::Load() -{ - if (propertyId == LWOOBJID_EMPTY) - { +void PropertyManagementComponent::Load() { + if (propertyId == LWOOBJID_EMPTY) { return; } @@ -617,8 +566,7 @@ void PropertyManagementComponent::Load() auto* lookupResult = lookup->executeQuery(); - while (lookupResult->next()) - { + while (lookupResult->next()) { const LWOOBJID id = lookupResult->getUInt64(1); const LOT lot = lookupResult->getInt(2); @@ -703,10 +651,8 @@ void PropertyManagementComponent::Load() delete lookup; } -void PropertyManagementComponent::Save() -{ - if (propertyId == LWOOBJID_EMPTY) - { +void PropertyManagementComponent::Save() { + if (propertyId == LWOOBJID_EMPTY) { return; } @@ -724,8 +670,7 @@ void PropertyManagementComponent::Save() } std::vector present; - while (lookupResult->next()) - { + while (lookupResult->next()) { const auto dbId = lookupResult->getUInt64(1); present.push_back(dbId); @@ -735,24 +680,21 @@ void PropertyManagementComponent::Save() std::vector modelIds; - for (const auto& pair : models) - { + for (const auto& pair : models) { const auto id = pair.second; modelIds.push_back(id); auto* entity = EntityManager::Instance()->GetEntity(pair.first); - if (entity == nullptr) - { + if (entity == nullptr) { continue; } const auto position = entity->GetPosition(); const auto rotation = entity->GetRotation(); - if (std::find(present.begin(), present.end(), id) == present.end()) - { + if (std::find(present.begin(), present.end(), id) == present.end()) { insertion->setInt64(1, id); insertion->setUInt64(2, propertyId); insertion->setNull(3, 0); @@ -769,9 +711,7 @@ void PropertyManagementComponent::Save() } catch (sql::SQLException& ex) { Game::logger->Log("PropertyManagementComponent", "Error inserting into properties_contents. Error %s", ex.what()); } - } - else - { + } else { update->setDouble(1, position.x); update->setDouble(2, position.y); update->setDouble(3, position.z); @@ -789,10 +729,8 @@ void PropertyManagementComponent::Save() } } - for (auto id : present) - { - if (std::find(modelIds.begin(), modelIds.end(), id) != modelIds.end()) - { + for (auto id : present) { + if (std::find(modelIds.begin(), modelIds.end(), id) != modelIds.end()) { continue; } @@ -815,26 +753,23 @@ void PropertyManagementComponent::Save() delete remove; } -void PropertyManagementComponent::AddModel(LWOOBJID modelId, LWOOBJID spawnerId) -{ +void PropertyManagementComponent::AddModel(LWOOBJID modelId, LWOOBJID spawnerId) { models[modelId] = spawnerId; } -PropertyManagementComponent* PropertyManagementComponent::Instance() -{ +PropertyManagementComponent* PropertyManagementComponent::Instance() { return instance; } -void PropertyManagementComponent::OnQueryPropertyData(Entity* originator, const SystemAddress& sysAddr, LWOOBJID author) -{ +void PropertyManagementComponent::OnQueryPropertyData(Entity* originator, const SystemAddress& sysAddr, LWOOBJID author) { if (author == LWOOBJID_EMPTY) { author = m_Parent->GetObjectID(); } - const auto& worldId = dZoneManager::Instance()->GetZone()->GetZoneID(); - const auto zoneId = worldId.GetMapID(); + const auto& worldId = dZoneManager::Instance()->GetZone()->GetZoneID(); + const auto zoneId = worldId.GetMapID(); - Game::logger->Log("Properties", "Getting property info for %d", zoneId); + Game::logger->Log("Properties", "Getting property info for %d", zoneId); GameMessages::PropertyDataMessage message = GameMessages::PropertyDataMessage(zoneId); const auto isClaimed = GetOwnerId() != LWOOBJID_EMPTY; @@ -904,18 +839,15 @@ void PropertyManagementComponent::OnQueryPropertyData(Entity* originator, const // send rejection here? } -void PropertyManagementComponent::OnUse(Entity* originator) -{ +void PropertyManagementComponent::OnUse(Entity* originator) { OnQueryPropertyData(originator, UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendOpenPropertyManagment(m_Parent->GetObjectID(), originator->GetSystemAddress()); } -void PropertyManagementComponent::SetOwnerId(const LWOOBJID value) -{ +void PropertyManagementComponent::SetOwnerId(const LWOOBJID value) { owner = value; } -const std::map& PropertyManagementComponent::GetModels() const -{ +const std::map& PropertyManagementComponent::GetModels() const { return models; } diff --git a/dGame/dComponents/PropertyManagementComponent.h b/dGame/dComponents/PropertyManagementComponent.h index c03c4949..c22adc21 100644 --- a/dGame/dComponents/PropertyManagementComponent.h +++ b/dGame/dComponents/PropertyManagementComponent.h @@ -9,20 +9,20 @@ */ enum class PropertyPrivacyOption { - /** - * Default, only you can visit your property - */ + /** + * Default, only you can visit your property + */ Private = 0, - /** - * Your friends can visit your property - */ - Friends = 1, + /** + * Your friends can visit your property + */ + Friends = 1, - /** - * Requires Mythran approval, everyone can visit your property - */ - Public = 2 + /** + * Requires Mythran approval, everyone can visit your property + */ + Public = 2 }; /** @@ -33,209 +33,209 @@ class PropertyManagementComponent : public Component public: static const uint32_t ComponentType = COMPONENT_TYPE_PROPERTY_MANAGEMENT; PropertyManagementComponent(Entity* parent); - static PropertyManagementComponent* Instance(); + static PropertyManagementComponent* Instance(); - /** - * Event handler for when an entity requests information about this property, will send back whether it's owned, etc. - * @param originator the entity that triggered the event - * @param sysAddr the address to send game message responses to - * @param author optional explicit ID for the property, if not set defaults to the originator - */ + /** + * Event handler for when an entity requests information about this property, will send back whether it's owned, etc. + * @param originator the entity that triggered the event + * @param sysAddr the address to send game message responses to + * @param author optional explicit ID for the property, if not set defaults to the originator + */ void OnQueryPropertyData(Entity* originator, const SystemAddress& sysAddr, LWOOBJID author = LWOOBJID_EMPTY); - /** - * Handles an OnUse event, telling the client who owns this property, etc. - * @param originator the entity that triggered the event - */ + /** + * Handles an OnUse event, telling the client who owns this property, etc. + * @param originator the entity that triggered the event + */ void OnUse(Entity* originator) override; - /** - * Sets the owner of this property - * @param value the owner to set - */ + /** + * Sets the owner of this property + * @param value the owner to set + */ void SetOwnerId(LWOOBJID value); - /** - * Returns the ID of the owner of this property - * @return the ID of the owner of this property - */ + /** + * Returns the ID of the owner of this property + * @return the ID of the owner of this property + */ LWOOBJID GetOwnerId() const; - /** - * Returns the owner of this property - * @return the owner of this property - */ + /** + * Returns the owner of this property + * @return the owner of this property + */ Entity* GetOwner() const; - /** - * sets the owner of this property - * @param value the owner to set - */ + /** + * sets the owner of this property + * @param value the owner to set + */ void SetOwner(Entity* value); - /** - * Returns the paths that this property has - * @return the paths that this property has - */ + /** + * Returns the paths that this property has + * @return the paths that this property has + */ std::vector GetPaths() const; - /** - * Returns the privacy options for this property - * @return the privacy options for this property - */ + /** + * Returns the privacy options for this property + * @return the privacy options for this property + */ PropertyPrivacyOption GetPrivacyOption() const; - /** - * Updates the privacy option for this property - * @param value the privacy option to set - */ + /** + * Updates the privacy option for this property + * @param value the privacy option to set + */ void SetPrivacyOption(PropertyPrivacyOption value); - /** - * Updates information of this property, saving it to the database - * @param name the name to set for the property - * @param description the description to set for the property - */ + /** + * Updates information of this property, saving it to the database + * @param name the name to set for the property + * @param description the description to set for the property + */ void UpdatePropertyDetails(std::string name, std::string description); - /** - * Makes this property owned by the passed player ID, storing it in the database - * @param playerId the ID of the entity that claimed the property - * - * @return If the claim is successful return true. - */ + /** + * Makes this property owned by the passed player ID, storing it in the database + * @param playerId the ID of the entity that claimed the property + * + * @return If the claim is successful return true. + */ bool Claim(LWOOBJID playerId); - /** - * Event triggered when the owner of the property starts building, will kick other entities out - */ + /** + * Event triggered when the owner of the property starts building, will kick other entities out + */ void OnStartBuilding(); - /** - * Event triggered when the owner of the property finished building, will re-apply this property for moderation - * request. - */ + /** + * Event triggered when the owner of the property finished building, will re-apply this property for moderation + * request. + */ void OnFinishBuilding(); - /** - * Updates the position of a model on the property - * @param id the ID of the model to reposition - * @param position the position to place the model on - * @param rotation the rotation to place the model on - */ + /** + * Updates the position of a model on the property + * @param id the ID of the model to reposition + * @param position the position to place the model on + * @param rotation the rotation to place the model on + */ void UpdateModelPosition(LWOOBJID id, NiPoint3 position, NiQuaternion rotation); - /** - * Deletes a model for a property - * @param id the ID of the model to delete - * @param deleteReason the reason of the deletion, e.g. picked up or destroyed (in case of UGC) - */ + /** + * Deletes a model for a property + * @param id the ID of the model to delete + * @param deleteReason the reason of the deletion, e.g. picked up or destroyed (in case of UGC) + */ void DeleteModel(LWOOBJID id, int deleteReason); - /** - * Updates whether or not this property is approved by a moderator - * @param value true if the property should be approved, false otherwise - */ + /** + * Updates whether or not this property is approved by a moderator + * @param value true if the property should be approved, false otherwise + */ void UpdateApprovedStatus(bool value); - /** - * Loads all the models on this property from the database - */ + /** + * Loads all the models on this property from the database + */ void Load(); - /** - * Saves all the models from this property to the database - */ + /** + * Saves all the models from this property to the database + */ void Save(); - /** - * Adds a model to the cache of models - * @param modelId the ID of the model - * @param spawnerId the ID of the object that spawned the model - */ + /** + * Adds a model to the cache of models + * @param modelId the ID of the model + * @param spawnerId the ID of the object that spawned the model + */ void AddModel(LWOOBJID modelId, LWOOBJID spawnerId); - /** - * Returns all the models on this property, indexed by property ID, containing their spawn objects - * @return all the models on this proeprty - */ + /** + * Returns all the models on this property, indexed by property ID, containing their spawn objects + * @return all the models on this proeprty + */ const std::map& GetModels() const; - - LWOCLONEID GetCloneId() { return clone_Id; }; + + LWOCLONEID GetCloneId() { return clone_Id; }; private: - /** - * This - */ + /** + * This + */ static PropertyManagementComponent* instance; - /** - * The ID of the owner of this property - */ + /** + * The ID of the owner of this property + */ LWOOBJID owner = LWOOBJID_EMPTY; - /** - * The LOT of this console - */ + /** + * The LOT of this console + */ uint32_t templateId = 0; - /** - * The unique ID for this property, if it's owned - */ + /** + * The unique ID for this property, if it's owned + */ LWOOBJID propertyId = LWOOBJID_EMPTY; - /** - * The time since this property was claimed - */ + /** + * The time since this property was claimed + */ uint64_t claimedTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); - /** - * The models that are placed on this property - */ + /** + * The models that are placed on this property + */ std::map models = {}; - /** - * The name of this property - */ + /** + * The name of this property + */ std::string propertyName = ""; - /** - * The clone ID of this property - */ + /** + * The clone ID of this property + */ LWOCLONEID clone_Id = 0; - /** - * Whether a moderator was requested - */ - bool moderatorRequested = false; + /** + * Whether a moderator was requested + */ + bool moderatorRequested = false; - /** - * The rejection reason for the property - */ + /** + * The rejection reason for the property + */ std::string rejectionReason = ""; - /** - * The description of this property - */ + /** + * The description of this property + */ std::string propertyDescription = ""; - /** - * The reputation of this property - */ + /** + * The reputation of this property + */ uint32_t reputation = 0; - /** - * The last time this property was updated - */ - uint32_t LastUpdatedTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + /** + * The last time this property was updated + */ + uint32_t LastUpdatedTime = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); - /** - * Determines which players may visit this property - */ + /** + * Determines which players may visit this property + */ PropertyPrivacyOption privacyOption = PropertyPrivacyOption::Private; - /** - * The privacy setting before it was changed, saved to set back after a player finishes building - */ + /** + * The privacy setting before it was changed, saved to set back after a player finishes building + */ PropertyPrivacyOption originalPrivacyOption = PropertyPrivacyOption::Private; }; diff --git a/dGame/dComponents/PropertyVendorComponent.cpp b/dGame/dComponents/PropertyVendorComponent.cpp index 5ab8340b..4ad24af5 100644 --- a/dGame/dComponents/PropertyVendorComponent.cpp +++ b/dGame/dComponents/PropertyVendorComponent.cpp @@ -10,18 +10,15 @@ #include "PropertyManagementComponent.h" #include "UserManager.h" -PropertyVendorComponent::PropertyVendorComponent(Entity* parent) : Component(parent) -{ +PropertyVendorComponent::PropertyVendorComponent(Entity* parent) : Component(parent) { } -void PropertyVendorComponent::OnUse(Entity* originator) -{ +void PropertyVendorComponent::OnUse(Entity* originator) { if (PropertyManagementComponent::Instance() == nullptr) return; OnQueryPropertyData(originator, originator->GetSystemAddress()); - if (PropertyManagementComponent::Instance()->GetOwnerId() == LWOOBJID_EMPTY) - { + if (PropertyManagementComponent::Instance()->GetOwnerId() == LWOOBJID_EMPTY) { Game::logger->Log("PropertyVendorComponent", "Property vendor opening!"); GameMessages::SendOpenPropertyVendor(m_Parent->GetObjectID(), originator->GetSystemAddress()); @@ -30,15 +27,13 @@ void PropertyVendorComponent::OnUse(Entity* originator) } } -void PropertyVendorComponent::OnQueryPropertyData(Entity* originator, const SystemAddress& sysAddr) -{ +void PropertyVendorComponent::OnQueryPropertyData(Entity* originator, const SystemAddress& sysAddr) { if (PropertyManagementComponent::Instance() == nullptr) return; PropertyManagementComponent::Instance()->OnQueryPropertyData(originator, sysAddr, m_Parent->GetObjectID()); } -void PropertyVendorComponent::OnBuyFromVendor(Entity* originator, const bool confirmed, const LOT lot, const uint32_t count) -{ +void PropertyVendorComponent::OnBuyFromVendor(Entity* originator, const bool confirmed, const LOT lot, const uint32_t count) { if (PropertyManagementComponent::Instance() == nullptr) return; if (PropertyManagementComponent::Instance()->Claim(originator->GetObjectID()) == false) { diff --git a/dGame/dComponents/PropertyVendorComponent.h b/dGame/dComponents/PropertyVendorComponent.h index 1a469589..4641b38d 100644 --- a/dGame/dComponents/PropertyVendorComponent.h +++ b/dGame/dComponents/PropertyVendorComponent.h @@ -12,26 +12,26 @@ public: static const uint32_t ComponentType = COMPONENT_TYPE_PROPERTY_VENDOR; explicit PropertyVendorComponent(Entity* parent); - /** - * Handles a use event from some entity, if the property is cleared this allows the entity to claim it - * @param originator the entity that triggered this event - */ + /** + * Handles a use event from some entity, if the property is cleared this allows the entity to claim it + * @param originator the entity that triggered this event + */ void OnUse(Entity* originator) override; - /** - * Handles a property data query after the property has been claimed, sending information about the property to the - * triggering entity. - * @param originator the entity that triggered the event - * @param sysAddr the system address to send game message response to - */ + /** + * Handles a property data query after the property has been claimed, sending information about the property to the + * triggering entity. + * @param originator the entity that triggered the event + * @param sysAddr the system address to send game message response to + */ void OnQueryPropertyData(Entity* originator, const SystemAddress& sysAddr); - /** - * Claims the property - * @param originator the entity that attempted to claim the property - * @param confirmed unused - * @param lot unused - * @param count unused - */ + /** + * Claims the property + * @param originator the entity that attempted to claim the property + * @param confirmed unused + * @param lot unused + * @param count unused + */ void OnBuyFromVendor(Entity* originator, bool confirmed, LOT lot, uint32_t count); }; diff --git a/dGame/dComponents/ProximityMonitorComponent.cpp b/dGame/dComponents/ProximityMonitorComponent.cpp index f2ef9b9a..acc93fde 100644 --- a/dGame/dComponents/ProximityMonitorComponent.cpp +++ b/dGame/dComponents/ProximityMonitorComponent.cpp @@ -27,7 +27,7 @@ ProximityMonitorComponent::~ProximityMonitorComponent() { void ProximityMonitorComponent::SetProximityRadius(float proxRadius, const std::string& name) { dpEntity* en = new dpEntity(m_Parent->GetObjectID(), proxRadius); en->SetPosition(m_Parent->GetPosition()); - + dpWorld::Instance().AddEntity(en); m_ProximitiesData.insert(std::make_pair(name, en)); } diff --git a/dGame/dComponents/ProximityMonitorComponent.h b/dGame/dComponents/ProximityMonitorComponent.h index 11cc7ab3..a98397a2 100644 --- a/dGame/dComponents/ProximityMonitorComponent.h +++ b/dGame/dComponents/ProximityMonitorComponent.h @@ -12,63 +12,63 @@ #include "dpEntity.h" #include "Component.h" -/** - * Utility component for detecting how close entities are to named proximities for this entity. Allows you to store - * proximity checks for multiple ojects. - */ + /** + * Utility component for detecting how close entities are to named proximities for this entity. Allows you to store + * proximity checks for multiple ojects. + */ class ProximityMonitorComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_PROXIMITY_MONITOR; - + ProximityMonitorComponent(Entity* parentEntity, int smallRadius = -1, int largeRadius = -1); ~ProximityMonitorComponent() override; - void Update(float deltaTime) override; + void Update(float deltaTime) override; - /** - * Creates an entry to check proximity for, given a name - * @param proxRadius the radius to use for the physics entity we use to detect proximity - * @param name the name of this check - */ + /** + * Creates an entry to check proximity for, given a name + * @param proxRadius the radius to use for the physics entity we use to detect proximity + * @param name the name of this check + */ void SetProximityRadius(float proxRadius, const std::string& name); - /** - * Creates an entry to check proximity for, given a name - * @param entity the physics entity to add to our proximity sensors - * @param name the name of this check - */ + /** + * Creates an entry to check proximity for, given a name + * @param entity the physics entity to add to our proximity sensors + * @param name the name of this check + */ void SetProximityRadius(dpEntity* entity, const std::string& name); - /** - * Returns the last of entities that are used to check proximity, given a name - * @param name the proximity name to retrieve physics objects for - * @return a map of physics entities for this name, indexed by object ID - */ + /** + * Returns the last of entities that are used to check proximity, given a name + * @param name the proximity name to retrieve physics objects for + * @return a map of physics entities for this name, indexed by object ID + */ const std::map& GetProximityObjects(const std::string& name); - /** - * Checks if the passed object is in proximity of the named proximity sensor - * @param name the name of the sensor to check proximity for - * @param objectID the entity to check if they're in proximity - * @return true if the object is in proximity, false otherwise - */ + /** + * Checks if the passed object is in proximity of the named proximity sensor + * @param name the name of the sensor to check proximity for + * @param objectID the entity to check if they're in proximity + * @return true if the object is in proximity, false otherwise + */ bool IsInProximity(const std::string& name, LWOOBJID objectID); - /** - * Returns all the proximity sensors stored on this component, indexed by name - * @return all the proximity sensors stored on this component - */ + /** + * Returns all the proximity sensors stored on this component, indexed by name + * @return all the proximity sensors stored on this component + */ const std::map& GetProximitiesData() const { return m_ProximitiesData; } private: - /** - * All the proximity sensors for this component, indexed by name - */ + /** + * All the proximity sensors for this component, indexed by name + */ std::map m_ProximitiesData = {}; - /** - * Default value for the proximity data - */ + /** + * Default value for the proximity data + */ static const std::map m_EmptyObjectMap; }; diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index e157ca5f..f6f257d2 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -26,884 +26,884 @@ #define M_PI 3.14159265358979323846264338327950288 #endif -RacingControlComponent::RacingControlComponent(Entity *parent) - : Component(parent) { - m_PathName = u"MainPath"; - m_RemainingLaps = 3; - m_LeadingPlayer = LWOOBJID_EMPTY; - m_RaceBestTime = 0; - m_RaceBestLap = 0; - m_Started = false; - m_StartTimer = 0; - m_Loaded = false; - m_LoadedPlayers = 0; - m_LoadTimer = 0; - m_Finished = 0; - m_StartTime = 0; - m_EmptyTimer = 0; - m_SoloRacing = Game::config->GetValue("solo_racing") == "1"; +RacingControlComponent::RacingControlComponent(Entity* parent) + : Component(parent) { + m_PathName = u"MainPath"; + m_RemainingLaps = 3; + m_LeadingPlayer = LWOOBJID_EMPTY; + m_RaceBestTime = 0; + m_RaceBestLap = 0; + m_Started = false; + m_StartTimer = 0; + m_Loaded = false; + m_LoadedPlayers = 0; + m_LoadTimer = 0; + m_Finished = 0; + m_StartTime = 0; + m_EmptyTimer = 0; + m_SoloRacing = Game::config->GetValue("solo_racing") == "1"; - // Select the main world ID as fallback when a player fails to load. + // Select the main world ID as fallback when a player fails to load. - const auto worldID = Game::server->GetZoneID(); + const auto worldID = Game::server->GetZoneID(); - switch (worldID) { - case 1203: - m_ActivityID = 42; - m_MainWorld = 1200; - break; + switch (worldID) { + case 1203: + m_ActivityID = 42; + m_MainWorld = 1200; + break; - case 1261: - m_ActivityID = 60; - m_MainWorld = 1260; - break; + case 1261: + m_ActivityID = 60; + m_MainWorld = 1260; + break; - case 1303: - m_ActivityID = 39; - m_MainWorld = 1300; - break; + case 1303: + m_ActivityID = 39; + m_MainWorld = 1300; + break; - case 1403: - m_ActivityID = 54; - m_MainWorld = 1400; - break; + case 1403: + m_ActivityID = 54; + m_MainWorld = 1400; + break; - default: - m_ActivityID = 42; - m_MainWorld = 1200; - break; - } + default: + m_ActivityID = 42; + m_MainWorld = 1200; + break; + } } RacingControlComponent::~RacingControlComponent() {} -void RacingControlComponent::OnPlayerLoaded(Entity *player) { - // If the race has already started, send the player back to the main world. - if (m_Loaded) { - auto *playerInstance = dynamic_cast(player); +void RacingControlComponent::OnPlayerLoaded(Entity* player) { + // If the race has already started, send the player back to the main world. + if (m_Loaded) { + auto* playerInstance = dynamic_cast(player); - playerInstance->SendToZone(m_MainWorld); + playerInstance->SendToZone(m_MainWorld); - return; - } + return; + } - const auto objectID = player->GetObjectID(); + const auto objectID = player->GetObjectID(); - m_LoadedPlayers++; + m_LoadedPlayers++; - Game::logger->Log("RacingControlComponent", "Loading player %i", - m_LoadedPlayers); + Game::logger->Log("RacingControlComponent", "Loading player %i", + m_LoadedPlayers); - m_LobbyPlayers.push_back(objectID); + m_LobbyPlayers.push_back(objectID); } -void RacingControlComponent::LoadPlayerVehicle(Entity *player, - bool initialLoad) { - // Load the player's vehicle. +void RacingControlComponent::LoadPlayerVehicle(Entity* player, + bool initialLoad) { + // Load the player's vehicle. - if (player == nullptr) { - return; - } + if (player == nullptr) { + return; + } - auto *inventoryComponent = player->GetComponent(); + auto* inventoryComponent = player->GetComponent(); - if (inventoryComponent == nullptr) { - return; - } + if (inventoryComponent == nullptr) { + return; + } - // Find the player's vehicle. + // Find the player's vehicle. - auto *item = inventoryComponent->FindItemByLot(8092); + auto* item = inventoryComponent->FindItemByLot(8092); - if (item == nullptr) { - Game::logger->Log("RacingControlComponent", "Failed to find item"); + if (item == nullptr) { + Game::logger->Log("RacingControlComponent", "Failed to find item"); - return; - } + return; + } - // Calculate the vehicle's starting position. + // Calculate the vehicle's starting position. - auto *path = dZoneManager::Instance()->GetZone()->GetPath( - GeneralUtils::UTF16ToWTF8(m_PathName)); + auto* path = dZoneManager::Instance()->GetZone()->GetPath( + GeneralUtils::UTF16ToWTF8(m_PathName)); - auto startPosition = path->pathWaypoints[0].position + NiPoint3::UNIT_Y * 3; + auto startPosition = path->pathWaypoints[0].position + NiPoint3::UNIT_Y * 3; - const auto spacing = 15; + const auto spacing = 15; - // This sometimes spawns the vehicle out of the map if there are lots of - // players loaded. + // This sometimes spawns the vehicle out of the map if there are lots of + // players loaded. - const auto range = m_LoadedPlayers * spacing; + const auto range = m_LoadedPlayers * spacing; - startPosition = - startPosition + NiPoint3::UNIT_Z * ((m_LeadingPlayer / 2) + - m_RacingPlayers.size() * spacing); + startPosition = + startPosition + NiPoint3::UNIT_Z * ((m_LeadingPlayer / 2) + + m_RacingPlayers.size() * spacing); - auto startRotation = - NiQuaternion::LookAt(startPosition, startPosition + NiPoint3::UNIT_X); + auto startRotation = + NiQuaternion::LookAt(startPosition, startPosition + NiPoint3::UNIT_X); - auto angles = startRotation.GetEulerAngles(); + auto angles = startRotation.GetEulerAngles(); - angles.y -= M_PI; + angles.y -= M_PI; - startRotation = NiQuaternion::FromEulerAngles(angles); + startRotation = NiQuaternion::FromEulerAngles(angles); - Game::logger->Log("RacingControlComponent", - "Start position <%f, %f, %f>, <%f, %f, %f>", - startPosition.x, startPosition.y, startPosition.z, - angles.x * (180.0f / M_PI), angles.y * (180.0f / M_PI), - angles.z * (180.0f / M_PI)); + Game::logger->Log("RacingControlComponent", + "Start position <%f, %f, %f>, <%f, %f, %f>", + startPosition.x, startPosition.y, startPosition.z, + angles.x * (180.0f / M_PI), angles.y * (180.0f / M_PI), + angles.z * (180.0f / M_PI)); - // Make sure the player is at the correct position. + // Make sure the player is at the correct position. - GameMessages::SendTeleport(player->GetObjectID(), startPosition, - startRotation, player->GetSystemAddress(), true, - true); + GameMessages::SendTeleport(player->GetObjectID(), startPosition, + startRotation, player->GetSystemAddress(), true, + true); - // Spawn the vehicle entity. + // Spawn the vehicle entity. - EntityInfo info{}; - info.lot = 8092; - info.pos = startPosition; - info.rot = startRotation; - info.spawnerID = m_Parent->GetObjectID(); + EntityInfo info{}; + info.lot = 8092; + info.pos = startPosition; + info.rot = startRotation; + info.spawnerID = m_Parent->GetObjectID(); - auto *carEntity = - EntityManager::Instance()->CreateEntity(info, nullptr, m_Parent); + auto* carEntity = + EntityManager::Instance()->CreateEntity(info, nullptr, m_Parent); - // Make the vehicle a child of the racing controller. - m_Parent->AddChild(carEntity); + // Make the vehicle a child of the racing controller. + m_Parent->AddChild(carEntity); - auto *destroyableComponent = - carEntity->GetComponent(); + auto* destroyableComponent = + carEntity->GetComponent(); - // Setup the vehicle stats. - if (destroyableComponent != nullptr) { - destroyableComponent->SetMaxImagination(60); - destroyableComponent->SetImagination(0); - } + // Setup the vehicle stats. + if (destroyableComponent != nullptr) { + destroyableComponent->SetMaxImagination(60); + destroyableComponent->SetImagination(0); + } - // Setup the vehicle as being possessed by the player. - auto *possessableComponent = - carEntity->GetComponent(); + // Setup the vehicle as being possessed by the player. + auto* possessableComponent = + carEntity->GetComponent(); - if (possessableComponent != nullptr) { - possessableComponent->SetPossessor(player->GetObjectID()); - } + if (possessableComponent != nullptr) { + possessableComponent->SetPossessor(player->GetObjectID()); + } - // Load the vehicle's assemblyPartLOTs for display. - auto *moduleAssemblyComponent = - carEntity->GetComponent(); + // Load the vehicle's assemblyPartLOTs for display. + auto* moduleAssemblyComponent = + carEntity->GetComponent(); - if (moduleAssemblyComponent) { - moduleAssemblyComponent->SetSubKey(item->GetSubKey()); - moduleAssemblyComponent->SetUseOptionalParts(false); + if (moduleAssemblyComponent) { + moduleAssemblyComponent->SetSubKey(item->GetSubKey()); + moduleAssemblyComponent->SetUseOptionalParts(false); - for (auto *config : item->GetConfig()) { - if (config->GetKey() == u"assemblyPartLOTs") { - moduleAssemblyComponent->SetAssemblyPartsLOTs( - GeneralUtils::ASCIIToUTF16(config->GetValueAsString())); - } - } - } + for (auto* config : item->GetConfig()) { + if (config->GetKey() == u"assemblyPartLOTs") { + moduleAssemblyComponent->SetAssemblyPartsLOTs( + GeneralUtils::ASCIIToUTF16(config->GetValueAsString())); + } + } + } - // Setup the player as possessing the vehicle. - auto *possessorComponent = player->GetComponent(); + // Setup the player as possessing the vehicle. + auto* possessorComponent = player->GetComponent(); - if (possessorComponent != nullptr) { - possessorComponent->SetPossessable(carEntity->GetObjectID()); - possessorComponent->SetPossessableType(ePossessionType::ATTACHED_VISIBLE); // for racing it's always Attached_Visible - } + if (possessorComponent != nullptr) { + possessorComponent->SetPossessable(carEntity->GetObjectID()); + possessorComponent->SetPossessableType(ePossessionType::ATTACHED_VISIBLE); // for racing it's always Attached_Visible + } - // Set the player's current activity as racing. - auto *characterComponent = player->GetComponent(); + // Set the player's current activity as racing. + auto* characterComponent = player->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->SetIsRacing(true); - } + if (characterComponent != nullptr) { + characterComponent->SetIsRacing(true); + } - // Init the player's racing entry. - if (initialLoad) { - m_RacingPlayers.push_back( - {player->GetObjectID(), - carEntity->GetObjectID(), - static_cast(m_RacingPlayers.size()), - false, - {}, - startPosition, - startRotation, - 0, - 0, - 0, - 0}); - } + // Init the player's racing entry. + if (initialLoad) { + m_RacingPlayers.push_back( + { player->GetObjectID(), + carEntity->GetObjectID(), + static_cast(m_RacingPlayers.size()), + false, + {}, + startPosition, + startRotation, + 0, + 0, + 0, + 0 }); + } - // Construct and serialize everything when done. + // Construct and serialize everything when done. - EntityManager::Instance()->ConstructEntity(carEntity); - EntityManager::Instance()->SerializeEntity(player); - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->ConstructEntity(carEntity); + EntityManager::Instance()->SerializeEntity(player); + EntityManager::Instance()->SerializeEntity(m_Parent); - GameMessages::SendRacingSetPlayerResetInfo( - m_Parent->GetObjectID(), 0, 0, player->GetObjectID(), startPosition, 1, - UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendRacingSetPlayerResetInfo( + m_Parent->GetObjectID(), 0, 0, player->GetObjectID(), startPosition, 1, + UNASSIGNED_SYSTEM_ADDRESS); - const auto playerID = player->GetObjectID(); + const auto playerID = player->GetObjectID(); - // Reset the player to the start position during downtime, in case something - // went wrong. - m_Parent->AddCallbackTimer(1, [this, playerID]() { - auto *player = EntityManager::Instance()->GetEntity(playerID); + // Reset the player to the start position during downtime, in case something + // went wrong. + m_Parent->AddCallbackTimer(1, [this, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) { - return; - } + if (player == nullptr) { + return; + } - GameMessages::SendRacingResetPlayerToLastReset( - m_Parent->GetObjectID(), playerID, UNASSIGNED_SYSTEM_ADDRESS); - }); + GameMessages::SendRacingResetPlayerToLastReset( + m_Parent->GetObjectID(), playerID, UNASSIGNED_SYSTEM_ADDRESS); + }); - GameMessages::SendSetJetPackMode(player, false); + GameMessages::SendSetJetPackMode(player, false); - // Set the vehicle's state. - GameMessages::SendNotifyVehicleOfRacingObject(carEntity->GetObjectID(), - m_Parent->GetObjectID(), - UNASSIGNED_SYSTEM_ADDRESS); + // Set the vehicle's state. + GameMessages::SendNotifyVehicleOfRacingObject(carEntity->GetObjectID(), + m_Parent->GetObjectID(), + UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendVehicleSetWheelLockState(carEntity->GetObjectID(), false, - initialLoad, - UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendVehicleSetWheelLockState(carEntity->GetObjectID(), false, + initialLoad, + UNASSIGNED_SYSTEM_ADDRESS); - // Make sure everything has the correct position. - GameMessages::SendTeleport(player->GetObjectID(), startPosition, - startRotation, player->GetSystemAddress(), true, - true); - GameMessages::SendTeleport(carEntity->GetObjectID(), startPosition, - startRotation, player->GetSystemAddress(), true, - true); + // Make sure everything has the correct position. + GameMessages::SendTeleport(player->GetObjectID(), startPosition, + startRotation, player->GetSystemAddress(), true, + true); + GameMessages::SendTeleport(carEntity->GetObjectID(), startPosition, + startRotation, player->GetSystemAddress(), true, + true); } -void RacingControlComponent::OnRacingClientReady(Entity *player) { - // Notify the other players that this player is ready. +void RacingControlComponent::OnRacingClientReady(Entity* player) { + // Notify the other players that this player is ready. - for (auto &racingPlayer : m_RacingPlayers) { - if (racingPlayer.playerID != player->GetObjectID()) { - if (racingPlayer.playerLoaded) { - GameMessages::SendRacingPlayerLoaded( - m_Parent->GetObjectID(), racingPlayer.playerID, - racingPlayer.vehicleID, UNASSIGNED_SYSTEM_ADDRESS); - } + for (auto& racingPlayer : m_RacingPlayers) { + if (racingPlayer.playerID != player->GetObjectID()) { + if (racingPlayer.playerLoaded) { + GameMessages::SendRacingPlayerLoaded( + m_Parent->GetObjectID(), racingPlayer.playerID, + racingPlayer.vehicleID, UNASSIGNED_SYSTEM_ADDRESS); + } - continue; - } + continue; + } - racingPlayer.playerLoaded = true; + racingPlayer.playerLoaded = true; - GameMessages::SendRacingPlayerLoaded( - m_Parent->GetObjectID(), racingPlayer.playerID, - racingPlayer.vehicleID, UNASSIGNED_SYSTEM_ADDRESS); - } + GameMessages::SendRacingPlayerLoaded( + m_Parent->GetObjectID(), racingPlayer.playerID, + racingPlayer.vehicleID, UNASSIGNED_SYSTEM_ADDRESS); + } - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } -void RacingControlComponent::OnRequestDie(Entity *player) { - // Sent by the client when they collide with something which should smash - // them. +void RacingControlComponent::OnRequestDie(Entity* player) { + // Sent by the client when they collide with something which should smash + // them. - for (auto &racingPlayer : m_RacingPlayers) { - if (racingPlayer.playerID != player->GetObjectID()) { - continue; - } + for (auto& racingPlayer : m_RacingPlayers) { + if (racingPlayer.playerID != player->GetObjectID()) { + continue; + } - auto *vehicle = - EntityManager::Instance()->GetEntity(racingPlayer.vehicleID); + auto* vehicle = + EntityManager::Instance()->GetEntity(racingPlayer.vehicleID); - if (vehicle == nullptr) { - return; - } + if (vehicle == nullptr) { + return; + } - if (!racingPlayer.noSmashOnReload) { - racingPlayer.smashedTimes++; - } + if (!racingPlayer.noSmashOnReload) { + racingPlayer.smashedTimes++; + } - // Reset player to last checkpoint - GameMessages::SendRacingSetPlayerResetInfo( - m_Parent->GetObjectID(), racingPlayer.lap, - racingPlayer.respawnIndex, player->GetObjectID(), - racingPlayer.respawnPosition, racingPlayer.respawnIndex + 1, - UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendRacingResetPlayerToLastReset( - m_Parent->GetObjectID(), racingPlayer.playerID, - UNASSIGNED_SYSTEM_ADDRESS); + // Reset player to last checkpoint + GameMessages::SendRacingSetPlayerResetInfo( + m_Parent->GetObjectID(), racingPlayer.lap, + racingPlayer.respawnIndex, player->GetObjectID(), + racingPlayer.respawnPosition, racingPlayer.respawnIndex + 1, + UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendRacingResetPlayerToLastReset( + m_Parent->GetObjectID(), racingPlayer.playerID, + UNASSIGNED_SYSTEM_ADDRESS); - auto *characterComponent = player->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(RacingTimesWrecked); - } + auto* characterComponent = player->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(RacingTimesWrecked); + } - return; - } + return; + } } -void RacingControlComponent::OnRacingPlayerInfoResetFinished(Entity *player) { - // When the player has respawned. +void RacingControlComponent::OnRacingPlayerInfoResetFinished(Entity* player) { + // When the player has respawned. - for (auto &racingPlayer : m_RacingPlayers) { - if (racingPlayer.playerID != player->GetObjectID()) { - continue; - } + for (auto& racingPlayer : m_RacingPlayers) { + if (racingPlayer.playerID != player->GetObjectID()) { + continue; + } - auto *vehicle = - EntityManager::Instance()->GetEntity(racingPlayer.vehicleID); + auto* vehicle = + EntityManager::Instance()->GetEntity(racingPlayer.vehicleID); - if (vehicle == nullptr) { - return; - } + if (vehicle == nullptr) { + return; + } - if (!racingPlayer.noSmashOnReload) { - GameMessages::SendDie(vehicle, LWOOBJID_EMPTY, LWOOBJID_EMPTY, true, - VIOLENT, u"", 0, 0, 0, true, false, 0); + if (!racingPlayer.noSmashOnReload) { + GameMessages::SendDie(vehicle, LWOOBJID_EMPTY, LWOOBJID_EMPTY, true, + VIOLENT, u"", 0, 0, 0, true, false, 0); - GameMessages::SendVehicleUnlockInput(racingPlayer.vehicleID, false, - UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendVehicleSetWheelLockState( - racingPlayer.vehicleID, false, false, - UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendVehicleUnlockInput(racingPlayer.vehicleID, false, + UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendVehicleSetWheelLockState( + racingPlayer.vehicleID, false, false, + UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendResurrect(vehicle); - } + GameMessages::SendResurrect(vehicle); + } - racingPlayer.noSmashOnReload = false; + racingPlayer.noSmashOnReload = false; - return; - } + return; + } } -void RacingControlComponent::HandleMessageBoxResponse(Entity *player, - const std::string &id) { - auto *data = GetPlayerData(player->GetObjectID()); +void RacingControlComponent::HandleMessageBoxResponse(Entity* player, + const std::string& id) { + auto* data = GetPlayerData(player->GetObjectID()); - if (data == nullptr) { - return; - } + if (data == nullptr) { + return; + } - if (id == "rewardButton") { - if (data->collectedRewards) { - return; - } + if (id == "rewardButton") { + if (data->collectedRewards) { + return; + } - data->collectedRewards = true; + data->collectedRewards = true; - // Calculate the score, different loot depending on player count - const auto score = m_LoadedPlayers * 10 + data->finished; + // Calculate the score, different loot depending on player count + const auto score = m_LoadedPlayers * 10 + data->finished; - LootGenerator::Instance().GiveActivityLoot(player, m_Parent, m_ActivityID, score); + LootGenerator::Instance().GiveActivityLoot(player, m_Parent, m_ActivityID, score); - // Giving rewards - GameMessages::SendNotifyRacingClient( - m_Parent->GetObjectID(), 2, 0, LWOOBJID_EMPTY, u"", - player->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + // Giving rewards + GameMessages::SendNotifyRacingClient( + m_Parent->GetObjectID(), 2, 0, LWOOBJID_EMPTY, u"", + player->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - auto *missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent == nullptr) return; + if (missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPETED_IN_RACE); // Progress task for competing in a race - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, data->smashedTimes, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SAFE_DRIVER); // Finish a race without being smashed. + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPETED_IN_RACE); // Progress task for competing in a race + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, data->smashedTimes, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SAFE_DRIVER); // Finish a race without being smashed. - // If solo racing is enabled OR if there are 3 players in the race, progress placement tasks. - if(m_SoloRacing || m_LoadedPlayers > 2) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, data->finished, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_FINISH_WITH_PLACEMENT); // Finish in 1st place on a race - if(data->finished == 1) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_FIRST_PLACE_MULTIPLE_TRACKS); // Finish in 1st place on multiple tracks. - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_WIN_RACE_IN_WORLD); // Finished first place in specific world. - } - if (data->finished == m_LoadedPlayers) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_LAST_PLACE_FINISH); // Finished first place in specific world. - } - } - } else if (id == "ACT_RACE_EXIT_THE_RACE?" || id == "Exit") { - auto *vehicle = EntityManager::Instance()->GetEntity(data->vehicleID); + // If solo racing is enabled OR if there are 3 players in the race, progress placement tasks. + if (m_SoloRacing || m_LoadedPlayers > 2) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, data->finished, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_FINISH_WITH_PLACEMENT); // Finish in 1st place on a race + if (data->finished == 1) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_FIRST_PLACE_MULTIPLE_TRACKS); // Finish in 1st place on multiple tracks. + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_WIN_RACE_IN_WORLD); // Finished first place in specific world. + } + if (data->finished == m_LoadedPlayers) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_LAST_PLACE_FINISH); // Finished first place in specific world. + } + } + } else if (id == "ACT_RACE_EXIT_THE_RACE?" || id == "Exit") { + auto* vehicle = EntityManager::Instance()->GetEntity(data->vehicleID); - if (vehicle == nullptr) { - return; - } + if (vehicle == nullptr) { + return; + } - // Exiting race - GameMessages::SendNotifyRacingClient( - m_Parent->GetObjectID(), 3, 0, LWOOBJID_EMPTY, u"", - player->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + // Exiting race + GameMessages::SendNotifyRacingClient( + m_Parent->GetObjectID(), 3, 0, LWOOBJID_EMPTY, u"", + player->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - auto *playerInstance = dynamic_cast(player); + auto* playerInstance = dynamic_cast(player); - playerInstance->SendToZone(m_MainWorld); + playerInstance->SendToZone(m_MainWorld); - vehicle->Kill(); - } + vehicle->Kill(); + } } -void RacingControlComponent::Serialize(RakNet::BitStream *outBitStream, - bool bIsInitialUpdate, - unsigned int &flags) { - // BEGIN Scripted Activity +void RacingControlComponent::Serialize(RakNet::BitStream* outBitStream, + bool bIsInitialUpdate, + unsigned int& flags) { + // BEGIN Scripted Activity - outBitStream->Write1(); + outBitStream->Write1(); - outBitStream->Write(static_cast(m_RacingPlayers.size())); - for (const auto &player : m_RacingPlayers) { - outBitStream->Write(player.playerID); + outBitStream->Write(static_cast(m_RacingPlayers.size())); + for (const auto& player : m_RacingPlayers) { + outBitStream->Write(player.playerID); - for (int i = 0; i < 10; i++) { - outBitStream->Write(player.data[i]); - } - } + for (int i = 0; i < 10; i++) { + outBitStream->Write(player.data[i]); + } + } - // END Scripted Activity + // END Scripted Activity - outBitStream->Write1(); // Dirty? - outBitStream->Write(static_cast(m_RacingPlayers.size())); + outBitStream->Write1(); // Dirty? + outBitStream->Write(static_cast(m_RacingPlayers.size())); - outBitStream->Write(!m_RacingPlayers.empty()); - if (!m_RacingPlayers.empty()) { - for (const auto &player : m_RacingPlayers) { - outBitStream->Write1(); // Has more date + outBitStream->Write(!m_RacingPlayers.empty()); + if (!m_RacingPlayers.empty()) { + for (const auto& player : m_RacingPlayers) { + outBitStream->Write1(); // Has more date - outBitStream->Write(player.playerID); - outBitStream->Write(player.vehicleID); - outBitStream->Write(player.playerIndex); - outBitStream->Write(player.playerLoaded); - } + outBitStream->Write(player.playerID); + outBitStream->Write(player.vehicleID); + outBitStream->Write(player.playerIndex); + outBitStream->Write(player.playerLoaded); + } - outBitStream->Write0(); // No more data - } + outBitStream->Write0(); // No more data + } - outBitStream->Write(!m_RacingPlayers.empty()); - if (!m_RacingPlayers.empty()) { - for (const auto &player : m_RacingPlayers) { - outBitStream->Write1(); // Has more date + outBitStream->Write(!m_RacingPlayers.empty()); + if (!m_RacingPlayers.empty()) { + for (const auto& player : m_RacingPlayers) { + outBitStream->Write1(); // Has more date - outBitStream->Write(player.playerID); - outBitStream->Write(0); - } + outBitStream->Write(player.playerID); + outBitStream->Write(0); + } - outBitStream->Write0(); // No more data - } + outBitStream->Write0(); // No more data + } - outBitStream->Write1(); // Dirty? + outBitStream->Write1(); // Dirty? - outBitStream->Write(m_RemainingLaps); + outBitStream->Write(m_RemainingLaps); - outBitStream->Write(static_cast(m_PathName.size())); - for (const auto character : m_PathName) { - outBitStream->Write(character); - } + outBitStream->Write(static_cast(m_PathName.size())); + for (const auto character : m_PathName) { + outBitStream->Write(character); + } - outBitStream->Write1(); // ??? - outBitStream->Write1(); // ??? + outBitStream->Write1(); // ??? + outBitStream->Write1(); // ??? - outBitStream->Write(m_LeadingPlayer); - outBitStream->Write(m_RaceBestLap); - outBitStream->Write(m_RaceBestTime); + outBitStream->Write(m_LeadingPlayer); + outBitStream->Write(m_RaceBestLap); + outBitStream->Write(m_RaceBestTime); } -RacingPlayerInfo *RacingControlComponent::GetPlayerData(LWOOBJID playerID) { - for (auto &player : m_RacingPlayers) { - if (player.playerID == playerID) { - return &player; - } - } +RacingPlayerInfo* RacingControlComponent::GetPlayerData(LWOOBJID playerID) { + for (auto& player : m_RacingPlayers) { + if (player.playerID == playerID) { + return &player; + } + } - return nullptr; + return nullptr; } void RacingControlComponent::Update(float deltaTime) { - // This method is a mess. + // This method is a mess. - // Pre-load routine - if (!m_Loaded) { - // Check if any players has disconnected before loading in - for (size_t i = 0; i < m_LobbyPlayers.size(); i++) { - auto *playerEntity = - EntityManager::Instance()->GetEntity(m_LobbyPlayers[i]); + // Pre-load routine + if (!m_Loaded) { + // Check if any players has disconnected before loading in + for (size_t i = 0; i < m_LobbyPlayers.size(); i++) { + auto* playerEntity = + EntityManager::Instance()->GetEntity(m_LobbyPlayers[i]); - if (playerEntity == nullptr) { - --m_LoadedPlayers; + if (playerEntity == nullptr) { + --m_LoadedPlayers; - m_LobbyPlayers.erase(m_LobbyPlayers.begin() + i); + m_LobbyPlayers.erase(m_LobbyPlayers.begin() + i); - return; - } - } + return; + } + } - if (m_LoadedPlayers >= 2 || (m_LoadedPlayers == 1 && m_SoloRacing)) { - m_LoadTimer += deltaTime; - } else { - m_EmptyTimer += deltaTime; - } + if (m_LoadedPlayers >= 2 || (m_LoadedPlayers == 1 && m_SoloRacing)) { + m_LoadTimer += deltaTime; + } else { + m_EmptyTimer += deltaTime; + } - // If a player happens to be left alone for more then 30 seconds without - // anyone else loading in, send them back to the main world - if (m_EmptyTimer >= 30) { - for (const auto player : m_LobbyPlayers) { - auto *playerEntity = - EntityManager::Instance()->GetEntity(player); + // If a player happens to be left alone for more then 30 seconds without + // anyone else loading in, send them back to the main world + if (m_EmptyTimer >= 30) { + for (const auto player : m_LobbyPlayers) { + auto* playerEntity = + EntityManager::Instance()->GetEntity(player); - if (playerEntity == nullptr) { - continue; - } + if (playerEntity == nullptr) { + continue; + } - auto *playerInstance = dynamic_cast(playerEntity); + auto* playerInstance = dynamic_cast(playerEntity); - playerInstance->SendToZone(m_MainWorld); - } + playerInstance->SendToZone(m_MainWorld); + } - m_LobbyPlayers.clear(); - } + m_LobbyPlayers.clear(); + } - // From the first 2 players loading in the rest have a max of 15 seconds - // to load in, can raise this if it's too low - if (m_LoadTimer >= 15) { - Game::logger->Log("RacingControlComponent", - "Loading all players..."); + // From the first 2 players loading in the rest have a max of 15 seconds + // to load in, can raise this if it's too low + if (m_LoadTimer >= 15) { + Game::logger->Log("RacingControlComponent", + "Loading all players..."); - for (size_t i = 0; i < m_LobbyPlayers.size(); i++) { - Game::logger->Log("RacingControlComponent", - "Loading player now!"); + for (size_t i = 0; i < m_LobbyPlayers.size(); i++) { + Game::logger->Log("RacingControlComponent", + "Loading player now!"); - auto *player = - EntityManager::Instance()->GetEntity(m_LobbyPlayers[i]); + auto* player = + EntityManager::Instance()->GetEntity(m_LobbyPlayers[i]); - if (player == nullptr) { - return; - } - - Game::logger->Log("RacingControlComponent", - "Loading player now NOW!"); + if (player == nullptr) { + return; + } + + Game::logger->Log("RacingControlComponent", + "Loading player now NOW!"); - LoadPlayerVehicle(player, true); + LoadPlayerVehicle(player, true); - m_Loaded = true; - } + m_Loaded = true; + } - m_Loaded = true; - } + m_Loaded = true; + } - return; - } + return; + } - // The players who will be participating have loaded - if (!m_Started) { - // Check if anyone has disconnected during this period - for (size_t i = 0; i < m_RacingPlayers.size(); i++) { - auto *playerEntity = EntityManager::Instance()->GetEntity( - m_RacingPlayers[i].playerID); - - if (playerEntity == nullptr) { - m_RacingPlayers.erase(m_RacingPlayers.begin() + i); + // The players who will be participating have loaded + if (!m_Started) { + // Check if anyone has disconnected during this period + for (size_t i = 0; i < m_RacingPlayers.size(); i++) { + auto* playerEntity = EntityManager::Instance()->GetEntity( + m_RacingPlayers[i].playerID); + + if (playerEntity == nullptr) { + m_RacingPlayers.erase(m_RacingPlayers.begin() + i); - --m_LoadedPlayers; + --m_LoadedPlayers; - return; - } - } - - // If less then 2 players are left, send the rest back to the main world - if (m_LoadedPlayers < 2 && !(m_LoadedPlayers == 1 && m_SoloRacing)) { - for (const auto player : m_LobbyPlayers) { - auto *playerEntity = - EntityManager::Instance()->GetEntity(player); - - if (playerEntity == nullptr) { - continue; - } - - auto *playerInstance = dynamic_cast(playerEntity); - - playerInstance->SendToZone(m_MainWorld); - } - - return; - } - - // Check if all players have send a ready message - - int32_t readyPlayers = 0; - - for (const auto &player : m_RacingPlayers) { - if (player.playerLoaded) { - ++readyPlayers; - } - } + return; + } + } + + // If less then 2 players are left, send the rest back to the main world + if (m_LoadedPlayers < 2 && !(m_LoadedPlayers == 1 && m_SoloRacing)) { + for (const auto player : m_LobbyPlayers) { + auto* playerEntity = + EntityManager::Instance()->GetEntity(player); + + if (playerEntity == nullptr) { + continue; + } + + auto* playerInstance = dynamic_cast(playerEntity); + + playerInstance->SendToZone(m_MainWorld); + } + + return; + } + + // Check if all players have send a ready message + + int32_t readyPlayers = 0; + + for (const auto& player : m_RacingPlayers) { + if (player.playerLoaded) { + ++readyPlayers; + } + } - if (readyPlayers >= m_LoadedPlayers) { - // Setup for racing - if (m_StartTimer == 0) { - GameMessages::SendNotifyRacingClient( - m_Parent->GetObjectID(), 1, 0, LWOOBJID_EMPTY, u"", - LWOOBJID_EMPTY, UNASSIGNED_SYSTEM_ADDRESS); - - for (const auto &player : m_RacingPlayers) { - auto *vehicle = - EntityManager::Instance()->GetEntity(player.vehicleID); - auto *playerEntity = - EntityManager::Instance()->GetEntity(player.playerID); + if (readyPlayers >= m_LoadedPlayers) { + // Setup for racing + if (m_StartTimer == 0) { + GameMessages::SendNotifyRacingClient( + m_Parent->GetObjectID(), 1, 0, LWOOBJID_EMPTY, u"", + LWOOBJID_EMPTY, UNASSIGNED_SYSTEM_ADDRESS); + + for (const auto& player : m_RacingPlayers) { + auto* vehicle = + EntityManager::Instance()->GetEntity(player.vehicleID); + auto* playerEntity = + EntityManager::Instance()->GetEntity(player.playerID); - if (vehicle != nullptr && playerEntity != nullptr) { - GameMessages::SendTeleport( - player.playerID, player.respawnPosition, - player.respawnRotation, - playerEntity->GetSystemAddress(), true, true); + if (vehicle != nullptr && playerEntity != nullptr) { + GameMessages::SendTeleport( + player.playerID, player.respawnPosition, + player.respawnRotation, + playerEntity->GetSystemAddress(), true, true); - vehicle->SetPosition(player.respawnPosition); - vehicle->SetRotation(player.respawnRotation); + vehicle->SetPosition(player.respawnPosition); + vehicle->SetRotation(player.respawnRotation); - auto *destroyableComponent = - vehicle->GetComponent(); + auto* destroyableComponent = + vehicle->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetImagination(0); - } - - EntityManager::Instance()->SerializeEntity(vehicle); - EntityManager::Instance()->SerializeEntity( - playerEntity); - } - } + if (destroyableComponent != nullptr) { + destroyableComponent->SetImagination(0); + } + + EntityManager::Instance()->SerializeEntity(vehicle); + EntityManager::Instance()->SerializeEntity( + playerEntity); + } + } - // Spawn imagination pickups - auto *minSpawner = dZoneManager::Instance()->GetSpawnersByName( - "ImaginationSpawn_Min")[0]; - auto *medSpawner = dZoneManager::Instance()->GetSpawnersByName( - "ImaginationSpawn_Med")[0]; - auto *maxSpawner = dZoneManager::Instance()->GetSpawnersByName( - "ImaginationSpawn_Max")[0]; - - minSpawner->Activate(); - - if (m_LoadedPlayers > 2) { - medSpawner->Activate(); - } - - if (m_LoadedPlayers > 4) { - maxSpawner->Activate(); - } - - // Reset players to their start location, without smashing them - for (auto &player : m_RacingPlayers) { - auto *vehicleEntity = - EntityManager::Instance()->GetEntity(player.vehicleID); - auto *playerEntity = - EntityManager::Instance()->GetEntity(player.playerID); - - if (vehicleEntity == nullptr || playerEntity == nullptr) { - continue; - } + // Spawn imagination pickups + auto* minSpawner = dZoneManager::Instance()->GetSpawnersByName( + "ImaginationSpawn_Min")[0]; + auto* medSpawner = dZoneManager::Instance()->GetSpawnersByName( + "ImaginationSpawn_Med")[0]; + auto* maxSpawner = dZoneManager::Instance()->GetSpawnersByName( + "ImaginationSpawn_Max")[0]; + + minSpawner->Activate(); + + if (m_LoadedPlayers > 2) { + medSpawner->Activate(); + } + + if (m_LoadedPlayers > 4) { + maxSpawner->Activate(); + } + + // Reset players to their start location, without smashing them + for (auto& player : m_RacingPlayers) { + auto* vehicleEntity = + EntityManager::Instance()->GetEntity(player.vehicleID); + auto* playerEntity = + EntityManager::Instance()->GetEntity(player.playerID); + + if (vehicleEntity == nullptr || playerEntity == nullptr) { + continue; + } - player.noSmashOnReload = true; + player.noSmashOnReload = true; - OnRequestDie(playerEntity); - } - } - // This 6 seconds seems to be hardcoded in the client, start race - // after that amount of time - else if (m_StartTimer >= 6) { - // Activate the players movement - for (auto &player : m_RacingPlayers) { - auto *vehicleEntity = - EntityManager::Instance()->GetEntity(player.vehicleID); - auto *playerEntity = - EntityManager::Instance()->GetEntity(player.playerID); - - if (vehicleEntity == nullptr || playerEntity == nullptr) { - continue; - } - - GameMessages::SendVehicleUnlockInput( - player.vehicleID, false, UNASSIGNED_SYSTEM_ADDRESS); - } - - // Start the race - GameMessages::SendActivityStart(m_Parent->GetObjectID(), - UNASSIGNED_SYSTEM_ADDRESS); - - m_Started = true; - - Game::logger->Log("RacingControlComponent", "Starting race"); - - EntityManager::Instance()->SerializeEntity(m_Parent); - - m_StartTime = std::time(nullptr); - } - - m_StartTimer += deltaTime; - } else { - m_StartTimer = 0; - } + OnRequestDie(playerEntity); + } + } + // This 6 seconds seems to be hardcoded in the client, start race + // after that amount of time + else if (m_StartTimer >= 6) { + // Activate the players movement + for (auto& player : m_RacingPlayers) { + auto* vehicleEntity = + EntityManager::Instance()->GetEntity(player.vehicleID); + auto* playerEntity = + EntityManager::Instance()->GetEntity(player.playerID); + + if (vehicleEntity == nullptr || playerEntity == nullptr) { + continue; + } + + GameMessages::SendVehicleUnlockInput( + player.vehicleID, false, UNASSIGNED_SYSTEM_ADDRESS); + } + + // Start the race + GameMessages::SendActivityStart(m_Parent->GetObjectID(), + UNASSIGNED_SYSTEM_ADDRESS); + + m_Started = true; + + Game::logger->Log("RacingControlComponent", "Starting race"); + + EntityManager::Instance()->SerializeEntity(m_Parent); + + m_StartTime = std::time(nullptr); + } + + m_StartTimer += deltaTime; + } else { + m_StartTimer = 0; + } - return; - } + return; + } - // Race routines - auto *path = dZoneManager::Instance()->GetZone()->GetPath( - GeneralUtils::UTF16ToWTF8(m_PathName)); + // Race routines + auto* path = dZoneManager::Instance()->GetZone()->GetPath( + GeneralUtils::UTF16ToWTF8(m_PathName)); - for (auto &player : m_RacingPlayers) { - auto *vehicle = EntityManager::Instance()->GetEntity(player.vehicleID); - auto *playerEntity = - EntityManager::Instance()->GetEntity(player.playerID); + for (auto& player : m_RacingPlayers) { + auto* vehicle = EntityManager::Instance()->GetEntity(player.vehicleID); + auto* playerEntity = + EntityManager::Instance()->GetEntity(player.playerID); - if (vehicle == nullptr || playerEntity == nullptr) { - continue; - } + if (vehicle == nullptr || playerEntity == nullptr) { + continue; + } - const auto vehiclePosition = vehicle->GetPosition(); + const auto vehiclePosition = vehicle->GetPosition(); - // If the player is this far below the map, safe to assume they should - // be smashed by death plane - if (vehiclePosition.y < -500) { - GameMessages::SendDie(vehicle, m_Parent->GetObjectID(), - LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, - true, false, 0); + // If the player is this far below the map, safe to assume they should + // be smashed by death plane + if (vehiclePosition.y < -500) { + GameMessages::SendDie(vehicle, m_Parent->GetObjectID(), + LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, + true, false, 0); - OnRequestDie(playerEntity); + OnRequestDie(playerEntity); - continue; - } + continue; + } - // Loop through all the waypoints and see if the player has reached a - // new checkpoint - uint32_t respawnIndex = 0; - for (const auto &waypoint : path->pathWaypoints) { - if (player.lap == 3) { - break; - } + // Loop through all the waypoints and see if the player has reached a + // new checkpoint + uint32_t respawnIndex = 0; + for (const auto& waypoint : path->pathWaypoints) { + if (player.lap == 3) { + break; + } - if (player.respawnIndex == respawnIndex) { - ++respawnIndex; + if (player.respawnIndex == respawnIndex) { + ++respawnIndex; - continue; - } + continue; + } - const auto &position = waypoint.position; + const auto& position = waypoint.position; - if (std::abs((int)respawnIndex - (int)player.respawnIndex) > 10 && - player.respawnIndex != path->pathWaypoints.size() - 1) { - ++respawnIndex; + if (std::abs((int)respawnIndex - (int)player.respawnIndex) > 10 && + player.respawnIndex != path->pathWaypoints.size() - 1) { + ++respawnIndex; - continue; - } + continue; + } - if (Vector3::DistanceSquared(position, vehiclePosition) > 50 * 50) { - ++respawnIndex; + if (Vector3::DistanceSquared(position, vehiclePosition) > 50 * 50) { + ++respawnIndex; - continue; - } + continue; + } - // Only go upwards, except if we've lapped - // Not sure how we are supposed to check if they've reach a - // checkpoint, within 50 units seems safe - if (!(respawnIndex > player.respawnIndex || - player.respawnIndex == path->pathWaypoints.size() - 1)) { - ++respawnIndex; + // Only go upwards, except if we've lapped + // Not sure how we are supposed to check if they've reach a + // checkpoint, within 50 units seems safe + if (!(respawnIndex > player.respawnIndex || + player.respawnIndex == path->pathWaypoints.size() - 1)) { + ++respawnIndex; - continue; - } + continue; + } - // 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.respawnRotation = vehicle->GetRotation(); - player.respawnIndex = respawnIndex; + // 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.respawnRotation = vehicle->GetRotation(); + player.respawnIndex = respawnIndex; - // Reached the start point, lapped - if (respawnIndex == 0) { - time_t lapTime = std::time(nullptr) - (player.lap == 1 ? m_StartTime : player.lapTime); + // Reached the start point, lapped + if (respawnIndex == 0) { + time_t lapTime = std::time(nullptr) - (player.lap == 1 ? m_StartTime : player.lapTime); - // Cheating check - if (lapTime < 40) { - continue; - } + // Cheating check + if (lapTime < 40) { + continue; + } - player.lap++; + player.lap++; - player.lapTime = std::time(nullptr); + player.lapTime = std::time(nullptr); - if (player.bestLapTime == 0 || player.bestLapTime > lapTime) { - player.bestLapTime = lapTime; + if (player.bestLapTime == 0 || player.bestLapTime > lapTime) { + player.bestLapTime = lapTime; - Game::logger->Log("RacingControlComponent", - "Best lap time (%llu)", lapTime); - } + Game::logger->Log("RacingControlComponent", + "Best lap time (%llu)", lapTime); + } - auto *missionComponent = - playerEntity->GetComponent(); + auto* missionComponent = + playerEntity->GetComponent(); - if (missionComponent != nullptr) { + if (missionComponent != nullptr) { - // Progress lap time tasks - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, (lapTime)*1000, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_LAP_TIME); + // Progress lap time tasks + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, (lapTime) * 1000, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_LAP_TIME); - if (player.lap == 3) { - m_Finished++; - player.finished = m_Finished; + if (player.lap == 3) { + m_Finished++; + player.finished = m_Finished; - const auto raceTime = - (std::time(nullptr) - m_StartTime); + const auto raceTime = + (std::time(nullptr) - m_StartTime); - player.raceTime = raceTime; + player.raceTime = raceTime; - Game::logger->Log("RacingControlComponent", - "Completed time %llu, %llu", - raceTime, raceTime * 1000); + Game::logger->Log("RacingControlComponent", + "Completed time %llu, %llu", + raceTime, raceTime * 1000); - // Entire race time - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, (raceTime)*1000, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_TOTAL_TRACK_TIME); + // Entire race time + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, (raceTime) * 1000, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_TOTAL_TRACK_TIME); - auto *characterComponent = playerEntity->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->TrackRaceCompleted(m_Finished == 1); - } + auto* characterComponent = playerEntity->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->TrackRaceCompleted(m_Finished == 1); + } - // TODO: Figure out how to update the GUI leaderboard. - } - } + // TODO: Figure out how to update the GUI leaderboard. + } + } - Game::logger->Log("RacingControlComponent", - "Lapped (%i) in (%llu)", player.lap, - lapTime); - } + Game::logger->Log("RacingControlComponent", + "Lapped (%i) in (%llu)", player.lap, + lapTime); + } - Game::logger->Log("RacingControlComponent", - "Reached point (%i)/(%i)", player.respawnIndex, - path->pathWaypoints.size()); + Game::logger->Log("RacingControlComponent", + "Reached point (%i)/(%i)", player.respawnIndex, + path->pathWaypoints.size()); - break; - } - } + break; + } + } } std::string RacingControlComponent::FormatTimeString(time_t time) { - int32_t min = time / 60; - time -= min * 60; - int32_t sec = time; + int32_t min = time / 60; + time -= min * 60; + int32_t sec = time; - std::string minText; - std::string secText; + std::string minText; + std::string secText; - if (min <= 0) { - minText = "0"; - } else { - minText = std::to_string(min); - } + if (min <= 0) { + minText = "0"; + } else { + minText = std::to_string(min); + } - if (sec <= 0) { - secText = "00"; - } else if (sec <= 9) { - secText = "0" + std::to_string(sec); - } else { - secText = std::to_string(sec); - } + if (sec <= 0) { + secText = "00"; + } else if (sec <= 9) { + secText = "0" + std::to_string(sec); + } else { + secText = std::to_string(sec); + } - return minText + ":" + secText + ".00"; + return minText + ":" + secText + ".00"; } diff --git a/dGame/dComponents/RacingControlComponent.h b/dGame/dComponents/RacingControlComponent.h index 63d5b2e4..dac60962 100644 --- a/dGame/dComponents/RacingControlComponent.h +++ b/dGame/dComponents/RacingControlComponent.h @@ -8,95 +8,95 @@ #include "Entity.h" #include "Component.h" -/** - * Information for each player in the race - */ + /** + * Information for each player in the race + */ struct RacingPlayerInfo { - /** - * The ID of the player - */ - LWOOBJID playerID; + /** + * The ID of the player + */ + LWOOBJID playerID; - /** - * The ID of the car the player is driving - */ - LWOOBJID vehicleID; + /** + * The ID of the car the player is driving + */ + LWOOBJID vehicleID; - /** - * The index of this player in the list of players - */ - uint32_t playerIndex; + /** + * The index of this player in the list of players + */ + uint32_t playerIndex; - /** - * Whether the player has finished loading or not - */ - bool playerLoaded; + /** + * Whether the player has finished loading or not + */ + bool playerLoaded; - /** - * Scripted activity component score - */ - float data[10] {}; + /** + * Scripted activity component score + */ + float data[10]{}; - /** - * Point that the player will respawn at if they smash their car - */ - NiPoint3 respawnPosition; + /** + * Point that the player will respawn at if they smash their car + */ + NiPoint3 respawnPosition; - /** - * Rotation that the player will respawn at if they smash their car - */ - NiQuaternion respawnRotation; + /** + * Rotation that the player will respawn at if they smash their car + */ + NiQuaternion respawnRotation; - /** - * The index in the respawn point the player is now at - */ - uint32_t respawnIndex; + /** + * The index in the respawn point the player is now at + */ + uint32_t respawnIndex; - /** - * The number of laps the player has completed - */ - uint32_t lap; + /** + * The number of laps the player has completed + */ + uint32_t lap; - /** - * Whether or not the player has finished the race - */ - uint32_t finished; + /** + * Whether or not the player has finished the race + */ + uint32_t finished; - /** - * Unused - */ - uint16_t reachedPoints; + /** + * Unused + */ + uint16_t reachedPoints; - /** - * The fastest lap time of the player - */ - time_t bestLapTime = 0; + /** + * The fastest lap time of the player + */ + time_t bestLapTime = 0; - /** - * The current lap time of the player - */ - time_t lapTime = 0; + /** + * The current lap time of the player + */ + time_t lapTime = 0; - /** - * The number of times this player smashed their car - */ - uint32_t smashedTimes = 0; + /** + * The number of times this player smashed their car + */ + uint32_t smashedTimes = 0; - /** - * Whether or not the player should be smashed if the game is reloaded - */ - bool noSmashOnReload = false; + /** + * Whether or not the player should be smashed if the game is reloaded + */ + bool noSmashOnReload = false; - /** - * Whether or not this player has collected their rewards from completing the race - */ - bool collectedRewards = false; + /** + * Whether or not this player has collected their rewards from completing the race + */ + bool collectedRewards = false; - /** - * Unused - */ - time_t raceTime = 0; + /** + * Unused + */ + time_t raceTime = 0; }; /** @@ -105,144 +105,144 @@ struct RacingPlayerInfo { class RacingControlComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_RACING_CONTROL; - + RacingControlComponent(Entity* parentEntity); ~RacingControlComponent(); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void Update(float deltaTime); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Update(float deltaTime); - /** - * Invoked when a player loads into the zone. - */ - void OnPlayerLoaded(Entity* player); + /** + * Invoked when a player loads into the zone. + */ + void OnPlayerLoaded(Entity* player); - /** - * Initalize the player's vehicle. - * - * @param player The player who's vehicle to initialize. - * @param initialLoad Is this the first time the player is loading in this race? - */ - void LoadPlayerVehicle(Entity* player, bool initialLoad = false); + /** + * Initalize the player's vehicle. + * + * @param player The player who's vehicle to initialize. + * @param initialLoad Is this the first time the player is loading in this race? + */ + void LoadPlayerVehicle(Entity* player, bool initialLoad = false); - /** - * Invoked when the client says it has loaded in. - */ - void OnRacingClientReady(Entity* player); + /** + * Invoked when the client says it has loaded in. + */ + void OnRacingClientReady(Entity* player); - /** - * Invoked when the client says it should be smashed. - */ - void OnRequestDie(Entity* player); + /** + * Invoked when the client says it should be smashed. + */ + void OnRequestDie(Entity* player); - /** - * Invoked when the player has finished respawning. - */ - void OnRacingPlayerInfoResetFinished(Entity* player); + /** + * Invoked when the player has finished respawning. + */ + void OnRacingPlayerInfoResetFinished(Entity* player); - /** - * Invoked when the player responds to the GUI. - */ - void HandleMessageBoxResponse(Entity* player, const std::string& id); + /** + * Invoked when the player responds to the GUI. + */ + void HandleMessageBoxResponse(Entity* player, const std::string& id); - /** - * Get the racing data from a player's LWOOBJID. - */ - RacingPlayerInfo* GetPlayerData(LWOOBJID playerID); + /** + * Get the racing data from a player's LWOOBJID. + */ + RacingPlayerInfo* GetPlayerData(LWOOBJID playerID); - /** - * Formats a time to a string, currently unused - * @param time the time to format - * @return the time formatted as string - */ - static std::string FormatTimeString(time_t time); + /** + * Formats a time to a string, currently unused + * @param time the time to format + * @return the time formatted as string + */ + static std::string FormatTimeString(time_t time); private: - /** - * The players that are currently racing - */ - std::vector m_RacingPlayers; + /** + * The players that are currently racing + */ + std::vector m_RacingPlayers; - /** - * The paths that are followed for the camera scenes - */ - std::u16string m_PathName; + /** + * The paths that are followed for the camera scenes + */ + std::u16string m_PathName; - /** - * The ID of the activity for participating in this race - */ - uint32_t m_ActivityID; + /** + * The ID of the activity for participating in this race + */ + uint32_t m_ActivityID; - /** - * The world the players return to when they finish the race - */ - uint32_t m_MainWorld; + /** + * The world the players return to when they finish the race + */ + uint32_t m_MainWorld; - /** - * The number of laps that are remaining for the winning player - */ - uint16_t m_RemainingLaps; + /** + * The number of laps that are remaining for the winning player + */ + uint16_t m_RemainingLaps; - /** - * The ID of the player that's currently winning the race - */ - LWOOBJID m_LeadingPlayer; + /** + * The ID of the player that's currently winning the race + */ + LWOOBJID m_LeadingPlayer; - /** - * The overall best lap from all the players - */ - float m_RaceBestLap; + /** + * The overall best lap from all the players + */ + float m_RaceBestLap; - /** - * The overall best time from all the players - */ - float m_RaceBestTime; + /** + * The overall best time from all the players + */ + float m_RaceBestTime; - /** - * Whether or not the race has started - */ - bool m_Started; + /** + * Whether or not the race has started + */ + bool m_Started; - /** - * The time left until the race will start - */ - float m_StartTimer; + /** + * The time left until the race will start + */ + float m_StartTimer; - /** - * The time left for loading the players - */ - float m_LoadTimer; + /** + * The time left for loading the players + */ + float m_LoadTimer; - /** - * Whether or not all players have loaded - */ - bool m_Loaded; + /** + * Whether or not all players have loaded + */ + bool m_Loaded; - /** - * The number of loaded players - */ - uint32_t m_LoadedPlayers; + /** + * The number of loaded players + */ + uint32_t m_LoadedPlayers; - /** - * All the players that are in the lobby, loaded or not - */ - std::vector m_LobbyPlayers; + /** + * All the players that are in the lobby, loaded or not + */ + std::vector m_LobbyPlayers; - /** - * The number of players that have finished the race - */ - uint32_t m_Finished; + /** + * The number of players that have finished the race + */ + uint32_t m_Finished; - /** - * The time the race was started - */ - time_t m_StartTime; + /** + * The time the race was started + */ + time_t m_StartTime; - /** - * Timer for tracking how long a player was alone in this race - */ - float m_EmptyTimer; + /** + * Timer for tracking how long a player was alone in this race + */ + float m_EmptyTimer; - bool m_SoloRacing; + bool m_SoloRacing; }; diff --git a/dGame/dComponents/RailActivatorComponent.cpp b/dGame/dComponents/RailActivatorComponent.cpp index 9cdc93f1..1b94fc4a 100644 --- a/dGame/dComponents/RailActivatorComponent.cpp +++ b/dGame/dComponents/RailActivatorComponent.cpp @@ -8,159 +8,150 @@ #include "Game.h" #include "dLogger.h" -RailActivatorComponent::RailActivatorComponent(Entity *parent, int32_t componentID) : Component(parent) { - m_ComponentID = componentID; - const auto tableData = CDClientManager::Instance() - ->GetTable("RailActivatorComponent")->GetEntryByID(componentID); +RailActivatorComponent::RailActivatorComponent(Entity* parent, int32_t componentID) : Component(parent) { + m_ComponentID = componentID; + const auto tableData = CDClientManager::Instance() + ->GetTable("RailActivatorComponent")->GetEntryByID(componentID); - m_Path = parent->GetVar(u"rail_path"); - m_PathDirection = parent->GetVar(u"rail_path_direction"); - m_PathStart = parent->GetVar(u"rail_path_start"); + m_Path = parent->GetVar(u"rail_path"); + m_PathDirection = parent->GetVar(u"rail_path_direction"); + m_PathStart = parent->GetVar(u"rail_path_start"); - m_StartSound = tableData.startSound; - m_loopSound = tableData.loopSound; - m_StopSound = tableData.stopSound; + m_StartSound = tableData.startSound; + m_loopSound = tableData.loopSound; + m_StopSound = tableData.stopSound; - m_StartAnimation = tableData.startAnimation; - m_LoopAnimation = tableData.loopAnimation; - m_StopAnimation = tableData.stopAnimation; + m_StartAnimation = tableData.startAnimation; + m_LoopAnimation = tableData.loopAnimation; + m_StopAnimation = tableData.stopAnimation; - m_StartEffect = tableData.startEffectID; - m_LoopEffect = tableData.loopEffectID; - m_StopEffect = tableData.stopEffectID; + m_StartEffect = tableData.startEffectID; + m_LoopEffect = tableData.loopEffectID; + m_StopEffect = tableData.stopEffectID; - m_DamageImmune = parent->GetVar(u"rail_activator_damage_immune"); - m_NoAggro = parent->GetVar(u"rail_no_aggro"); - m_NotifyArrived = parent->GetVar(u"rail_notify_activator_arrived"); - m_ShowNameBillboard = parent->GetVar(u"rail_show_name_billboard"); - m_UseDB = parent->GetVar(u"rail_use_db"); - m_CameraLocked = tableData.cameraLocked; - m_CollisionEnabled = tableData.playerCollision; + m_DamageImmune = parent->GetVar(u"rail_activator_damage_immune"); + m_NoAggro = parent->GetVar(u"rail_no_aggro"); + m_NotifyArrived = parent->GetVar(u"rail_notify_activator_arrived"); + m_ShowNameBillboard = parent->GetVar(u"rail_show_name_billboard"); + m_UseDB = parent->GetVar(u"rail_use_db"); + m_CameraLocked = tableData.cameraLocked; + m_CollisionEnabled = tableData.playerCollision; } RailActivatorComponent::~RailActivatorComponent() = default; -void RailActivatorComponent::OnUse(Entity *originator) { - auto* rebuildComponent = m_Parent->GetComponent(); - if (rebuildComponent != nullptr && rebuildComponent->GetState() != REBUILD_COMPLETED) - return; +void RailActivatorComponent::OnUse(Entity* originator) { + auto* rebuildComponent = m_Parent->GetComponent(); + if (rebuildComponent != nullptr && rebuildComponent->GetState() != REBUILD_COMPLETED) + return; - if (rebuildComponent != nullptr) { - // Don't want it to be destroyed while a player is using it - rebuildComponent->SetResetTime(rebuildComponent->GetResetTime() + 10.0f); - } + if (rebuildComponent != nullptr) { + // Don't want it to be destroyed while a player is using it + rebuildComponent->SetResetTime(rebuildComponent->GetResetTime() + 10.0f); + } - m_EntitiesOnRail.push_back(originator->GetObjectID()); + m_EntitiesOnRail.push_back(originator->GetObjectID()); - // Start the initial effects - if (!m_StartEffect.second.empty()) { - GameMessages::SendPlayFXEffect(originator->GetObjectID(), m_StartEffect.first, m_StartEffect.second, - std::to_string(m_StartEffect.first)); - } + // Start the initial effects + if (!m_StartEffect.second.empty()) { + GameMessages::SendPlayFXEffect(originator->GetObjectID(), m_StartEffect.first, m_StartEffect.second, + std::to_string(m_StartEffect.first)); + } - if (!m_StartAnimation.empty()) { - GameMessages::SendPlayAnimation(originator, m_StartAnimation); - } + if (!m_StartAnimation.empty()) { + GameMessages::SendPlayAnimation(originator, m_StartAnimation); + } - float animationLength; - - if (m_StartAnimation == u"whirlwind-rail-up-earth") - { - animationLength = 1.5f; - } - else if (m_StartAnimation == u"whirlwind-rail-up-lightning") - { - animationLength = 0.5f; - } - else if (m_StartAnimation == u"whirlwind-rail-up-ice") - { - animationLength = 0.5f; - } - else if (m_StartAnimation == u"whirlwind-rail-up-fire") - { - animationLength = 0.5f; - } - else - { - animationLength = 0.5f; - } + float animationLength; - const auto originatorID = originator->GetObjectID(); + if (m_StartAnimation == u"whirlwind-rail-up-earth") { + animationLength = 1.5f; + } else if (m_StartAnimation == u"whirlwind-rail-up-lightning") { + animationLength = 0.5f; + } else if (m_StartAnimation == u"whirlwind-rail-up-ice") { + animationLength = 0.5f; + } else if (m_StartAnimation == u"whirlwind-rail-up-fire") { + animationLength = 0.5f; + } else { + animationLength = 0.5f; + } - m_Parent->AddCallbackTimer(animationLength, [originatorID, this] () { - auto* originator = EntityManager::Instance()->GetEntity(originatorID); + const auto originatorID = originator->GetObjectID(); - if (originator == nullptr) { - return; - } + m_Parent->AddCallbackTimer(animationLength, [originatorID, this]() { + auto* originator = EntityManager::Instance()->GetEntity(originatorID); - GameMessages::SendStartRailMovement(originator->GetObjectID(), m_Path, m_StartSound, - m_loopSound, m_StopSound, originator->GetSystemAddress(), - m_PathStart, m_PathDirection, m_DamageImmune, m_NoAggro, m_NotifyArrived, - m_ShowNameBillboard, m_CameraLocked, m_CollisionEnabled, m_UseDB, m_ComponentID, - m_Parent->GetObjectID()); - }); + if (originator == nullptr) { + return; + } + + GameMessages::SendStartRailMovement(originator->GetObjectID(), m_Path, m_StartSound, + m_loopSound, m_StopSound, originator->GetSystemAddress(), + m_PathStart, m_PathDirection, m_DamageImmune, m_NoAggro, m_NotifyArrived, + m_ShowNameBillboard, m_CameraLocked, m_CollisionEnabled, m_UseDB, m_ComponentID, + m_Parent->GetObjectID()); + }); } -void RailActivatorComponent::OnRailMovementReady(Entity *originator) const { - // Stun the originator - GameMessages::SendSetStunned(originator->GetObjectID(), PUSH, originator->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); +void RailActivatorComponent::OnRailMovementReady(Entity* originator) const { + // Stun the originator + GameMessages::SendSetStunned(originator->GetObjectID(), PUSH, originator->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - if (std::find(m_EntitiesOnRail.begin(), m_EntitiesOnRail.end(), originator->GetObjectID()) != m_EntitiesOnRail.end()) { - // Stop the initial effects - if (!m_StartEffect.second.empty()) { - GameMessages::SendStopFXEffect(originator, false, std::to_string(m_StartEffect.first)); - } + if (std::find(m_EntitiesOnRail.begin(), m_EntitiesOnRail.end(), originator->GetObjectID()) != m_EntitiesOnRail.end()) { + // Stop the initial effects + if (!m_StartEffect.second.empty()) { + GameMessages::SendStopFXEffect(originator, false, std::to_string(m_StartEffect.first)); + } - // Start the looping effects - if (!m_LoopEffect.second.empty()) { - GameMessages::SendPlayFXEffect(originator->GetObjectID(), m_LoopEffect.first, m_LoopEffect.second, - std::to_string(m_LoopEffect.first)); - } + // Start the looping effects + if (!m_LoopEffect.second.empty()) { + GameMessages::SendPlayFXEffect(originator->GetObjectID(), m_LoopEffect.first, m_LoopEffect.second, + std::to_string(m_LoopEffect.first)); + } - if (!m_LoopAnimation.empty()) { - GameMessages::SendPlayAnimation(originator, m_LoopAnimation); - } + if (!m_LoopAnimation.empty()) { + GameMessages::SendPlayAnimation(originator, m_LoopAnimation); + } - GameMessages::SendSetRailMovement(originator->GetObjectID(), m_PathDirection, m_Path, m_PathStart, - originator->GetSystemAddress(), m_ComponentID, - m_Parent->GetObjectID()); - } + GameMessages::SendSetRailMovement(originator->GetObjectID(), m_PathDirection, m_Path, m_PathStart, + originator->GetSystemAddress(), m_ComponentID, + m_Parent->GetObjectID()); + } } -void RailActivatorComponent::OnCancelRailMovement(Entity *originator) { - // Remove the stun from the originator - GameMessages::SendSetStunned(originator->GetObjectID(), POP, originator->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); +void RailActivatorComponent::OnCancelRailMovement(Entity* originator) { + // Remove the stun from the originator + GameMessages::SendSetStunned(originator->GetObjectID(), POP, originator->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - auto* rebuildComponent = m_Parent->GetComponent(); + auto* rebuildComponent = m_Parent->GetComponent(); - if (rebuildComponent != nullptr) { - // Set back reset time - rebuildComponent->SetResetTime(rebuildComponent->GetResetTime() - 10.0f); - } + if (rebuildComponent != nullptr) { + // Set back reset time + rebuildComponent->SetResetTime(rebuildComponent->GetResetTime() - 10.0f); + } - if (std::find(m_EntitiesOnRail.begin(), m_EntitiesOnRail.end(), originator->GetObjectID()) != m_EntitiesOnRail.end()) { - // Stop the looping effects - if (!m_LoopEffect.second.empty()) { - GameMessages::SendStopFXEffect(originator, false, std::to_string(m_LoopEffect.first)); - } + if (std::find(m_EntitiesOnRail.begin(), m_EntitiesOnRail.end(), originator->GetObjectID()) != m_EntitiesOnRail.end()) { + // Stop the looping effects + if (!m_LoopEffect.second.empty()) { + GameMessages::SendStopFXEffect(originator, false, std::to_string(m_LoopEffect.first)); + } - // Start the end effects - if (!m_StopEffect.second.empty()) { - GameMessages::SendPlayFXEffect(originator->GetObjectID(), m_StopEffect.first, m_StopEffect.second, - std::to_string(m_StopEffect.first)); - } + // Start the end effects + if (!m_StopEffect.second.empty()) { + GameMessages::SendPlayFXEffect(originator->GetObjectID(), m_StopEffect.first, m_StopEffect.second, + std::to_string(m_StopEffect.first)); + } - if (!m_StopAnimation.empty()) { - GameMessages::SendPlayAnimation(originator, m_StopAnimation); - } + if (!m_StopAnimation.empty()) { + GameMessages::SendPlayAnimation(originator, m_StopAnimation); + } - // Remove the player after they've signalled they're done railing - m_EntitiesOnRail.erase(std::remove(m_EntitiesOnRail.begin(), m_EntitiesOnRail.end(), - originator->GetObjectID()),m_EntitiesOnRail.end()); - } + // Remove the player after they've signalled they're done railing + m_EntitiesOnRail.erase(std::remove(m_EntitiesOnRail.begin(), m_EntitiesOnRail.end(), + originator->GetObjectID()), m_EntitiesOnRail.end()); + } } diff --git a/dGame/dComponents/RailActivatorComponent.h b/dGame/dComponents/RailActivatorComponent.h index 82607dcf..8f67e7e3 100644 --- a/dGame/dComponents/RailActivatorComponent.h +++ b/dGame/dComponents/RailActivatorComponent.h @@ -11,134 +11,134 @@ */ class RailActivatorComponent final : public Component { public: - explicit RailActivatorComponent(Entity* parent, int32_t componentID); - ~RailActivatorComponent() override; + explicit RailActivatorComponent(Entity* parent, int32_t componentID); + ~RailActivatorComponent() override; - static const uint32_t ComponentType = COMPONENT_TYPE_RAIL_ACTIVATOR; + static const uint32_t ComponentType = COMPONENT_TYPE_RAIL_ACTIVATOR; - /** - * Handles the OnUse event from some entity, initiates the rail movement - * @param originator the entity that triggered the event - */ - void OnUse(Entity *originator) override; + /** + * Handles the OnUse event from some entity, initiates the rail movement + * @param originator the entity that triggered the event + */ + void OnUse(Entity* originator) override; - /** - * Event handler that's called when some entity has played the start animation for rail movement and now wants to - * start the actual movement. - * @param originator the entity that triggered the event - */ - void OnRailMovementReady(Entity* originator) const; + /** + * Event handler that's called when some entity has played the start animation for rail movement and now wants to + * start the actual movement. + * @param originator the entity that triggered the event + */ + void OnRailMovementReady(Entity* originator) const; - /** - * Event handler that's called when some entity has finished traversing the rail and wants to end its interaction - * with it - * @param originator the entity that triggered the event - */ - void OnCancelRailMovement(Entity* originator); + /** + * Event handler that's called when some entity has finished traversing the rail and wants to end its interaction + * with it + * @param originator the entity that triggered the event + */ + void OnCancelRailMovement(Entity* originator); private: - /** - * The ID of this component in the components database - */ - int32_t m_ComponentID; + /** + * The ID of this component in the components database + */ + int32_t m_ComponentID; - /** - * The entities that are currently traversing the rail - */ - std::vector m_EntitiesOnRail {}; + /** + * The entities that are currently traversing the rail + */ + std::vector m_EntitiesOnRail{}; - /** - * The path the entities will follow when traversing the rail - */ - std::u16string m_Path; + /** + * The path the entities will follow when traversing the rail + */ + std::u16string m_Path; - /** - * The index of the path that is the start - */ - uint32_t m_PathStart; + /** + * The index of the path that is the start + */ + uint32_t m_PathStart; - /** - * The direction on the path - */ - bool m_PathDirection; + /** + * The direction on the path + */ + bool m_PathDirection; - /** - * The animation that plays when starting the rail - */ - std::u16string m_StartAnimation; + /** + * The animation that plays when starting the rail + */ + std::u16string m_StartAnimation; - /** - * The animation that plays during the rail - */ - std::u16string m_LoopAnimation; + /** + * The animation that plays during the rail + */ + std::u16string m_LoopAnimation; - /** - * The animation that plays after the rail - */ - std::u16string m_StopAnimation; + /** + * The animation that plays after the rail + */ + std::u16string m_StopAnimation; - /** - * The sound that plays at the start of the rail - */ - std::u16string m_StartSound; + /** + * The sound that plays at the start of the rail + */ + std::u16string m_StartSound; - /** - * The sound that plays during the rail - */ - std::u16string m_loopSound; + /** + * The sound that plays during the rail + */ + std::u16string m_loopSound; - /** - * The sound that plays at the end of the rail - */ - std::u16string m_StopSound; + /** + * The sound that plays at the end of the rail + */ + std::u16string m_StopSound; - /** - * The effects that play at the start of the rail - */ - std::pair m_StartEffect; + /** + * The effects that play at the start of the rail + */ + std::pair m_StartEffect; - /** - * The effects that play during the rail - */ - std::pair m_LoopEffect; + /** + * The effects that play during the rail + */ + std::pair m_LoopEffect; - /** - * The effects that play at the end of the rail - */ - std::pair m_StopEffect; + /** + * The effects that play at the end of the rail + */ + std::pair m_StopEffect; - /** - * Client flag - */ - bool m_DamageImmune; + /** + * Client flag + */ + bool m_DamageImmune; - /** - * Client flag - */ - bool m_NoAggro; + /** + * Client flag + */ + bool m_NoAggro; - /** - * Client flag - */ - bool m_UseDB; + /** + * Client flag + */ + bool m_UseDB; - /** - * Client flag - */ - bool m_CameraLocked; + /** + * Client flag + */ + bool m_CameraLocked; - /** - * Client flag - */ - bool m_CollisionEnabled; + /** + * Client flag + */ + bool m_CollisionEnabled; - /** - * Client flag, notifies the server when the player finished the rail - */ - bool m_NotifyArrived; + /** + * Client flag, notifies the server when the player finished the rail + */ + bool m_NotifyArrived; - /** - * Client flag - */ - bool m_ShowNameBillboard; + /** + * Client flag + */ + bool m_ShowNameBillboard; }; diff --git a/dGame/dComponents/RebuildComponent.cpp b/dGame/dComponents/RebuildComponent.cpp index f2c2707f..6ec9b964 100644 --- a/dGame/dComponents/RebuildComponent.cpp +++ b/dGame/dComponents/RebuildComponent.cpp @@ -20,8 +20,7 @@ RebuildComponent::RebuildComponent(Entity* entity) : Component(entity) { std::u16string checkPreconditions = entity->GetVar(u"CheckPrecondition"); - if (!checkPreconditions.empty()) - { + if (!checkPreconditions.empty()) { m_Precondition = new PreconditionExpression(GeneralUtils::UTF16ToWTF8(checkPreconditions)); } @@ -81,8 +80,7 @@ void RebuildComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitia for (int i = 0; i < 10; i++) { outBitStream->Write(0.0f); } - } - else { + } else { outBitStream->Write((uint32_t)0); } // END Scripted Activity @@ -154,20 +152,20 @@ void RebuildComponent::Update(float deltaTime) { // For reset times < 0 this has to be handled manually if (m_ResetTime > 0) { - if (m_Timer >= m_ResetTime - 4.0f) { - if (!m_ShowResetEffect) { - m_ShowResetEffect = true; + if (m_Timer >= m_ResetTime - 4.0f) { + if (!m_ShowResetEffect) { + m_ShowResetEffect = true; - EntityManager::Instance()->SerializeEntity(m_Parent); - } - } + EntityManager::Instance()->SerializeEntity(m_Parent); + } + } - if (m_Timer >= m_ResetTime) { + if (m_Timer >= m_ResetTime) { - GameMessages::SendDieNoImplCode(m_Parent, LWOOBJID_EMPTY, LWOOBJID_EMPTY, eKillType::VIOLENT, u"", 0.0f, 0.0f, 0.0f, false, true); + GameMessages::SendDieNoImplCode(m_Parent, LWOOBJID_EMPTY, LWOOBJID_EMPTY, eKillType::VIOLENT, u"", 0.0f, 0.0f, 0.0f, false, true); - ResetRebuild(false); - } + ResetRebuild(false); + } } break; } @@ -175,8 +173,7 @@ void RebuildComponent::Update(float deltaTime) { { Entity* builder = GetBuilder(); - if (builder == nullptr) - { + if (builder == nullptr) { ResetRebuild(false); return; @@ -218,19 +215,19 @@ void RebuildComponent::Update(float deltaTime) { // For reset times < 0 this has to be handled manually if (m_TimeBeforeSmash > 0) { - if (m_TimerIncomplete >= m_TimeBeforeSmash - 4.0f) { - m_ShowResetEffect = true; + if (m_TimerIncomplete >= m_TimeBeforeSmash - 4.0f) { + m_ShowResetEffect = true; - EntityManager::Instance()->SerializeEntity(m_Parent); - } + EntityManager::Instance()->SerializeEntity(m_Parent); + } - if (m_TimerIncomplete >= m_TimeBeforeSmash) { + if (m_TimerIncomplete >= m_TimeBeforeSmash) { m_Builder = LWOOBJID_EMPTY; - GameMessages::SendDieNoImplCode(m_Parent, LWOOBJID_EMPTY, LWOOBJID_EMPTY, eKillType::VIOLENT, u"", 0.0f, 0.0f, 0.0f, false, true); + GameMessages::SendDieNoImplCode(m_Parent, LWOOBJID_EMPTY, LWOOBJID_EMPTY, eKillType::VIOLENT, u"", 0.0f, 0.0f, 0.0f, false, true); - ResetRebuild(false); - } + ResetRebuild(false); + } } break; } @@ -281,8 +278,7 @@ void RebuildComponent::DespawnActivator() { } } -Entity* RebuildComponent::GetActivator() -{ +Entity* RebuildComponent::GetActivator() { return EntityManager::Instance()->GetEntity(m_ActivatorId); } @@ -345,14 +341,13 @@ void RebuildComponent::SetActivatorPosition(NiPoint3 value) { } void RebuildComponent::SetResetTime(float value) { - m_ResetTime = value; + m_ResetTime = value; } void RebuildComponent::SetCompleteTime(float value) { if (value < 0) { m_CompleteTime = 4.5f; - } - else { + } else { m_CompleteTime = value; } } @@ -384,8 +379,7 @@ void RebuildComponent::SetPostImaginationCost(int value) { void RebuildComponent::SetTimeBeforeSmash(float value) { if (value < 0) { m_TimeBeforeSmash = 10.0f; - } - else { + } else { m_TimeBeforeSmash = value; } } @@ -419,11 +413,11 @@ void RebuildComponent::StartRebuild(Entity* user) { script->OnRebuildStart(m_Parent, user); } - // Notify scripts and possible subscribers - for (auto* script : CppScripts::GetEntityScripts(m_Parent)) - script->OnRebuildNotifyState(m_Parent, m_State); - for (const auto& cb : m_RebuildStateCallbacks) - cb(m_State); + // Notify scripts and possible subscribers + for (auto* script : CppScripts::GetEntityScripts(m_Parent)) + script->OnRebuildNotifyState(m_Parent, m_State); + for (const auto& cb : m_RebuildStateCallbacks) + cb(m_State); } } @@ -435,7 +429,7 @@ void RebuildComponent::CompleteRebuild(Entity* user) { auto* characterComponent = user->GetComponent(); if (characterComponent != nullptr) { characterComponent->SetCurrentActivity(eGameActivities::ACTIVITY_NONE); - characterComponent->TrackRebuildComplete(); + characterComponent->TrackRebuildComplete(); } else { Game::logger->Log("RebuildComponent", "Some user tried to finish the rebuild but they didn't have a character somehow."); return; @@ -465,7 +459,7 @@ void RebuildComponent::CompleteRebuild(Entity* user) { DespawnActivator(); - // Set owner override so that entities smashed by this quickbuild will result in the builder getting rewards. + // Set owner override so that entities smashed by this quickbuild will result in the builder getting rewards. m_Parent->SetOwnerOverride(user->GetObjectID()); auto* builder = GetBuilder(); @@ -487,9 +481,9 @@ void RebuildComponent::CompleteRebuild(Entity* user) { // Notify subscribers for (const auto& callback : m_RebuildStateCallbacks) - callback(m_State); + callback(m_State); for (const auto& callback : m_RebuildCompleteCallbacks) - callback(user); + callback(user); auto* movingPlatform = m_Parent->GetComponent(); if (movingPlatform != nullptr) { @@ -535,12 +529,11 @@ void RebuildComponent::ResetRebuild(bool failed) { for (auto* script : CppScripts::GetEntityScripts(m_Parent)) script->OnRebuildNotifyState(m_Parent, m_State); for (const auto& cb : m_RebuildStateCallbacks) - cb(m_State); + cb(m_State); m_Parent->ScheduleKillAfterUpdate(); - if (m_Activator) - { + if (m_Activator) { m_Activator->ScheduleKillAfterUpdate(); } } @@ -564,11 +557,11 @@ void RebuildComponent::CancelRebuild(Entity* entity, eFailReason failReason, boo m_State = eRebuildState::REBUILD_INCOMPLETE; m_StateDirty = true; - // Notify scripts and possible subscribers - for (auto* script : CppScripts::GetEntityScripts(m_Parent)) - script->OnRebuildNotifyState(m_Parent, m_State); - for (const auto& cb : m_RebuildStateCallbacks) - cb(m_State); + // Notify scripts and possible subscribers + for (auto* script : CppScripts::GetEntityScripts(m_Parent)) + script->OnRebuildNotifyState(m_Parent, m_State); + for (const auto& cb : m_RebuildStateCallbacks) + cb(m_State); EntityManager::Instance()->SerializeEntity(m_Parent); } @@ -585,9 +578,9 @@ void RebuildComponent::CancelRebuild(Entity* entity, eFailReason failReason, boo } void RebuildComponent::AddRebuildCompleteCallback(const std::function& callback) { - m_RebuildCompleteCallbacks.push_back(callback); + m_RebuildCompleteCallbacks.push_back(callback); } void RebuildComponent::AddRebuildStateCallback(const std::function& callback) { - m_RebuildStateCallbacks.push_back(callback); + m_RebuildStateCallbacks.push_back(callback); } diff --git a/dGame/dComponents/RebuildComponent.h b/dGame/dComponents/RebuildComponent.h index 72c57bb0..bd3edd7d 100644 --- a/dGame/dComponents/RebuildComponent.h +++ b/dGame/dComponents/RebuildComponent.h @@ -20,342 +20,342 @@ class Entity; class RebuildComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_REBUILD; - + RebuildComponent(Entity* entity); ~RebuildComponent() override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); void Update(float deltaTime) override; - /** - * Handles a OnUse event from some entity, initiating the quick build - * @param originator the entity that triggered the event - */ + /** + * Handles a OnUse event from some entity, initiating the quick build + * @param originator the entity that triggered the event + */ void OnUse(Entity* originator) override; - /** - * Spawns the activator that can be used to initiate the rebuild - */ + /** + * Spawns the activator that can be used to initiate the rebuild + */ void SpawnActivator(); - /** - * Despawns the activiator that can be used to initiate the rebuild - */ + /** + * Despawns the activiator that can be used to initiate the rebuild + */ void DespawnActivator(); - /** - * Returns the entity that acts as the activator for this rebuild - * @return the entity that acts as the activator for this rebuild - */ + /** + * Returns the entity that acts as the activator for this rebuild + * @return the entity that acts as the activator for this rebuild + */ Entity* GetActivator(); - /** - * Returns the spawn position of the activator for this rebuild, if any - * @return the spawn position of the activator for this rebuild, if any - */ + /** + * Returns the spawn position of the activator for this rebuild, if any + * @return the spawn position of the activator for this rebuild, if any + */ NiPoint3 GetActivatorPosition(); - /** - * Sets the spawn position for the activator of this rebuild - * @param value the spawn position to set for the activator - */ + /** + * Sets the spawn position for the activator of this rebuild + * @param value the spawn position to set for the activator + */ void SetActivatorPosition(NiPoint3 value); - /** - * Returns the time it takes for the rebuild to reset after being built - * @return the time it takes for the rebuild to reset after being built - */ + /** + * Returns the time it takes for the rebuild to reset after being built + * @return the time it takes for the rebuild to reset after being built + */ float GetResetTime(); - /** - * Sets the time it takes for the rebuild to reset after being built - * @param value the reset time to set - */ - void SetResetTime(float value); + /** + * Sets the time it takes for the rebuild to reset after being built + * @param value the reset time to set + */ + void SetResetTime(float value); - /** - * Returns the time it takes to complete the rebuild - * @return the time it takes to complete the rebuild - */ + /** + * Returns the time it takes to complete the rebuild + * @return the time it takes to complete the rebuild + */ float GetCompleteTime(); - /** - * Sets the time it takes to complete the rebuild - * @param value the completion time to set - */ - void SetCompleteTime(float value); + /** + * Sets the time it takes to complete the rebuild + * @param value the completion time to set + */ + void SetCompleteTime(float value); - /** - * Returns the imagination that's taken when completing the rebuild - * @return the imagination that's taken when completing the rebuild - */ + /** + * Returns the imagination that's taken when completing the rebuild + * @return the imagination that's taken when completing the rebuild + */ int GetTakeImagination(); - /** - * Sets the imagination that's taken when completing the rebuild - * @param value the imagination deduction to set - */ - void SetTakeImagination(int value); + /** + * Sets the imagination that's taken when completing the rebuild + * @param value the imagination deduction to set + */ + void SetTakeImagination(int value); - /** - * Returns if the rebuild can be interrupted, currently unused - * @return if the rebuild can be interrupted - */ + /** + * Returns if the rebuild can be interrupted, currently unused + * @return if the rebuild can be interrupted + */ bool GetInterruptible(); - /** - * Sets whether or not the rebuild can be interrupted, currently unused - * @param value true if the rebuild may be interrupted, false otherwise - */ - void SetInterruptible(bool value); + /** + * Sets whether or not the rebuild can be interrupted, currently unused + * @param value true if the rebuild may be interrupted, false otherwise + */ + void SetInterruptible(bool value); - /** - * Returns whether or not this entity contains a built-in activator - * @return whether or not this entity contains a built-in activator - */ + /** + * Returns whether or not this entity contains a built-in activator + * @return whether or not this entity contains a built-in activator + */ bool GetSelfActivator(); - /** - * Sets whether or not this entity contains a built-in activator. If set to false this will spawn activators on - * each new rebuild. - * @param value whether or not this entity contains a built-in activator - */ - void SetSelfActivator(bool value); + /** + * Sets whether or not this entity contains a built-in activator. If set to false this will spawn activators on + * each new rebuild. + * @param value whether or not this entity contains a built-in activator + */ + void SetSelfActivator(bool value); - /** - * Currently unused - */ + /** + * Currently unused + */ std::vector GetCustomModules(); - /** - * Currently unused - */ - void SetCustomModules(std::vector value); + /** + * Currently unused + */ + void SetCustomModules(std::vector value); - /** - * Returns the activity ID for participating in this rebuild - * @return the activity ID for participating in this rebuild - */ + /** + * Returns the activity ID for participating in this rebuild + * @return the activity ID for participating in this rebuild + */ int GetActivityId(); - /** - * Sets the activity ID for participating in this rebuild - * @param value the activity ID to set - */ - void SetActivityId(int value); + /** + * Sets the activity ID for participating in this rebuild + * @param value the activity ID to set + */ + void SetActivityId(int value); - /** - * Currently unused - */ + /** + * Currently unused + */ int GetPostImaginationCost(); - /** - * Currently unused - */ - void SetPostImaginationCost(int value); + /** + * Currently unused + */ + void SetPostImaginationCost(int value); - /** - * Returns the time it takes for an incomplete rebuild to be smashed automatically - * @return the time it takes for an incomplete rebuild to be smashed automatically - */ + /** + * Returns the time it takes for an incomplete rebuild to be smashed automatically + * @return the time it takes for an incomplete rebuild to be smashed automatically + */ float GetTimeBeforeSmash(); - /** - * Sets the time it takes for an incomplete rebuild to be smashed automatically - * @param value the time to set - */ - void SetTimeBeforeSmash(float value); + /** + * Sets the time it takes for an incomplete rebuild to be smashed automatically + * @param value the time to set + */ + void SetTimeBeforeSmash(float value); - /** - * Returns the current rebuild state - * @return the current rebuild state - */ + /** + * Returns the current rebuild state + * @return the current rebuild state + */ eRebuildState GetState(); - /** - * Returns the player that is currently building this rebuild - * @return the player that is currently building this rebuild - */ + /** + * Returns the player that is currently building this rebuild + * @return the player that is currently building this rebuild + */ Entity* GetBuilder() const; - /** - * Returns whether or not the player is repositioned when initiating the rebuild - * @return whether or not the player is repositioned when initiating the rebuild - */ + /** + * Returns whether or not the player is repositioned when initiating the rebuild + * @return whether or not the player is repositioned when initiating the rebuild + */ bool GetRepositionPlayer() const; - /** - * Sets whether or not the player is repositioned when initiating the rebuild - * @param value whether or not the player is repositioned when initiating the rebuild - */ + /** + * Sets whether or not the player is repositioned when initiating the rebuild + * @param value whether or not the player is repositioned when initiating the rebuild + */ void SetRepositionPlayer(bool value); - /** - * Adds a callback that is called when the rebuild is completed - * @param callback the callback to add - */ + /** + * Adds a callback that is called when the rebuild is completed + * @param callback the callback to add + */ void AddRebuildCompleteCallback(const std::function& callback); - /** - * Adds a callback when the rebuild state is updated - * @param callback the callback to add - */ + /** + * Adds a callback when the rebuild state is updated + * @param callback the callback to add + */ void AddRebuildStateCallback(const std::function& callback); - /** - * Resets the rebuild - * @param failed whether or not the player failed to complete the rebuild, triggers an extra animation - */ - void ResetRebuild(bool failed); + /** + * Resets the rebuild + * @param failed whether or not the player failed to complete the rebuild, triggers an extra animation + */ + void ResetRebuild(bool failed); - /** - * Cancels the rebuild if it wasn't completed - * @param builder the player that's currently building - * @param failReason the reason the rebuild was cancelled - * @param skipChecks whether or not to skip the check for the rebuild not being completed - */ + /** + * Cancels the rebuild if it wasn't completed + * @param builder the player that's currently building + * @param failReason the reason the rebuild was cancelled + * @param skipChecks whether or not to skip the check for the rebuild not being completed + */ void CancelRebuild(Entity* builder, eFailReason failReason, bool skipChecks = false); private: - /** - * Whether or not the quickbuild state has been changed since we last serialized it. - */ - bool m_StateDirty = true; - - /** - * The state the rebuild is currently in - */ + /** + * Whether or not the quickbuild state has been changed since we last serialized it. + */ + bool m_StateDirty = true; + + /** + * The state the rebuild is currently in + */ eRebuildState m_State = eRebuildState::REBUILD_OPEN; - /** - * The time that has passed since initiating the rebuild - */ + /** + * The time that has passed since initiating the rebuild + */ float m_Timer = 0; - /** - * The time that has passed before completing the rebuild - */ + /** + * The time that has passed before completing the rebuild + */ float m_TimerIncomplete = 0; - /** - * The position that the rebuild activator is spawned at - */ + /** + * The position that the rebuild activator is spawned at + */ NiPoint3 m_ActivatorPosition = NiPoint3::ZERO; - /** - * The entity that represents the rebuild activator - */ + /** + * The entity that represents the rebuild activator + */ Entity* m_Activator = nullptr; - /** - * The ID of the entity that represents the rebuild activator - */ + /** + * The ID of the entity that represents the rebuild activator + */ LWOOBJID m_ActivatorId = LWOOBJID_EMPTY; - /** - * Triggers the blinking that indicates that the rebuild is resetting - */ + /** + * Triggers the blinking that indicates that the rebuild is resetting + */ bool m_ShowResetEffect = false; - /** - * Currently unused - */ + /** + * Currently unused + */ float m_Taken = 0; - /** - * The callbacks that are called when the rebuild is completed - */ - std::vector> m_RebuildCompleteCallbacks {}; + /** + * The callbacks that are called when the rebuild is completed + */ + std::vector> m_RebuildCompleteCallbacks{}; - /** - * The callbacks that are called when the rebuild state is updated - */ - std::vector> m_RebuildStateCallbacks {}; + /** + * The callbacks that are called when the rebuild state is updated + */ + std::vector> m_RebuildStateCallbacks{}; - /** - * The time it takes for the rebuild to reset after being completed - */ + /** + * The time it takes for the rebuild to reset after being completed + */ float m_ResetTime = 0; - /** - * The time it takes to complete the rebuild - */ + /** + * The time it takes to complete the rebuild + */ float m_CompleteTime = 0; - /** - * The imagination that's deducted when compeleting the rebuild - */ + /** + * The imagination that's deducted when compeleting the rebuild + */ int m_TakeImagination = 0; - /** - * Currently unused - */ + /** + * Currently unused + */ bool m_Interruptible = false; - /** - * Whether or not this rebuild entity also has an activator attached. If not a new one will be spawned - */ + /** + * Whether or not this rebuild entity also has an activator attached. If not a new one will be spawned + */ bool m_SelfActivator = false; - /** - * Currently unused - */ - std::vector m_CustomModules {}; + /** + * Currently unused + */ + std::vector m_CustomModules{}; - /** - * The activity ID that players partake in when doing this rebuild - */ + /** + * The activity ID that players partake in when doing this rebuild + */ int m_ActivityId = 0; - /** - * Currently unused - */ + /** + * Currently unused + */ int m_PostImaginationCost = 0; - /** - * The time it takes for the rebuild to reset when it's not completed yet - */ + /** + * The time it takes for the rebuild to reset when it's not completed yet + */ float m_TimeBeforeSmash = 0; - /** - * The time it takes to drain imagination - */ + /** + * The time it takes to drain imagination + */ float m_TimeBeforeDrain = 0; - /** - * The amount of imagination that was drained when building this rebuild - */ + /** + * The amount of imagination that was drained when building this rebuild + */ int m_DrainedImagination = 0; - /** - * Whether to reposition the player or not when building - */ + /** + * Whether to reposition the player or not when building + */ bool m_RepositionPlayer = true; - /** - * Currently unused - */ + /** + * Currently unused + */ float m_SoftTimer = 0; - /** - * The ID of the entity that's currently building the rebuild - */ + /** + * The ID of the entity that's currently building the rebuild + */ LWOOBJID m_Builder = LWOOBJID_EMPTY; - /** - * Preconditions to be met before being able to start the rebuild - */ + /** + * Preconditions to be met before being able to start the rebuild + */ PreconditionExpression* m_Precondition = nullptr; - /** - * Starts the rebuild for a certain entity - * @param user the entity to start the rebuild - */ + /** + * Starts the rebuild for a certain entity + * @param user the entity to start the rebuild + */ void StartRebuild(Entity* user); - /** - * Completes the rebuild for an entity, dropping loot and despawning the activator - * @param user the entity that completed the rebuild - */ + /** + * Completes the rebuild for an entity, dropping loot and despawning the activator + * @param user the entity that completed the rebuild + */ void CompleteRebuild(Entity* user); }; diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index faec4ab6..3002ae33 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -12,226 +12,215 @@ #include "Game.h" #include "dLogger.h" -std::unordered_map RenderComponent::m_DurationCache {}; +std::unordered_map RenderComponent::m_DurationCache{}; RenderComponent::RenderComponent(Entity* parent) : Component(parent) { - m_Effects = std::vector(); + m_Effects = std::vector(); - return; + return; - /* - auto* table = CDClientManager::Instance()->GetTable("ComponentsRegistry"); + /* + auto* table = CDClientManager::Instance()->GetTable("ComponentsRegistry"); - const auto entry = table->GetByIDAndType(parent->GetLOT(), COMPONENT_TYPE_RENDER); + const auto entry = table->GetByIDAndType(parent->GetLOT(), COMPONENT_TYPE_RENDER); std::stringstream query; - query << "SELECT effect1, effect2, effect3, effect4, effect5, effect6 FROM RenderComponent WHERE id = " << std::to_string(entry) << ";"; + query << "SELECT effect1, effect2, effect3, effect4, effect5, effect6 FROM RenderComponent WHERE id = " << std::to_string(entry) << ";"; - auto result = CDClientDatabase::ExecuteQuery(query.str()); + auto result = CDClientDatabase::ExecuteQuery(query.str()); + + if (result.eof()) + { + return; + } - if (result.eof()) - { - return; - } - for (auto i = 0; i < 6; ++i) - { + { if (result.fieldIsNull(i)) { continue; } - - const auto id = result.getIntField(i); + + const auto id = result.getIntField(i); if (id <= 0) { continue; } - - query.clear(); - query << "SELECT effectType, effectName FROM BehaviorEffect WHERE effectID = " << std::to_string(id) << ";"; + query.clear(); - auto effectResult = CDClientDatabase::ExecuteQuery(query.str()); + query << "SELECT effectType, effectName FROM BehaviorEffect WHERE effectID = " << std::to_string(id) << ";"; - while (!effectResult.eof()) - { - const auto type = effectResult.fieldIsNull(0) ? "" : std::string(effectResult.getStringField(0)); - - const auto name = effectResult.fieldIsNull(1) ? "" : std::string(effectResult.getStringField(1)); + auto effectResult = CDClientDatabase::ExecuteQuery(query.str()); - auto* effect = new Effect(); + while (!effectResult.eof()) + { + const auto type = effectResult.fieldIsNull(0) ? "" : std::string(effectResult.getStringField(0)); - effect->name = name; - effect->type = GeneralUtils::ASCIIToUTF16(type); - effect->scale = 1; - effect->effectID = id; - effect->secondary = LWOOBJID_EMPTY; - - m_Effects.push_back(effect); - - effectResult.nextRow(); - } - } + const auto name = effectResult.fieldIsNull(1) ? "" : std::string(effectResult.getStringField(1)); + + auto* effect = new Effect(); + + effect->name = name; + effect->type = GeneralUtils::ASCIIToUTF16(type); + effect->scale = 1; + effect->effectID = id; + effect->secondary = LWOOBJID_EMPTY; + + m_Effects.push_back(effect); + + effectResult.nextRow(); + } + } result.finalize(); - */ + */ } RenderComponent::~RenderComponent() { - for (Effect* eff : m_Effects) { - if (eff) { - delete eff; - eff = nullptr; - } - } - - m_Effects.clear(); + for (Effect* eff : m_Effects) { + if (eff) { + delete eff; + eff = nullptr; + } + } + + m_Effects.clear(); } void RenderComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - if (!bIsInitialUpdate) return; - - outBitStream->Write(m_Effects.size()); - - for (Effect* eff : m_Effects) { - // Check that the effect is non-null - assert(eff); + if (!bIsInitialUpdate) return; - outBitStream->Write(eff->name.size()); - for (const auto& value : eff->name) - outBitStream->Write(value); + outBitStream->Write(m_Effects.size()); - outBitStream->Write(eff->effectID); + for (Effect* eff : m_Effects) { + // Check that the effect is non-null + assert(eff); - outBitStream->Write(eff->type.size()); - for (const auto& value : eff->type) - outBitStream->Write(value); + outBitStream->Write(eff->name.size()); + for (const auto& value : eff->name) + outBitStream->Write(value); - outBitStream->Write(eff->scale); - outBitStream->Write(eff->secondary); - } + outBitStream->Write(eff->effectID); + + outBitStream->Write(eff->type.size()); + for (const auto& value : eff->type) + outBitStream->Write(value); + + outBitStream->Write(eff->scale); + outBitStream->Write(eff->secondary); + } } Effect* RenderComponent::AddEffect(const int32_t effectId, const std::string& name, const std::u16string& type) { - auto* eff = new Effect(); - - eff->effectID = effectId; - - eff->name = name; - - eff->type = type; - - m_Effects.push_back(eff); + auto* eff = new Effect(); - return eff; + eff->effectID = effectId; + + eff->name = name; + + eff->type = type; + + m_Effects.push_back(eff); + + return eff; } void RenderComponent::RemoveEffect(const std::string& name) { - uint32_t index = -1; + uint32_t index = -1; - for (auto i = 0u; i < m_Effects.size(); ++i) - { - auto* eff = m_Effects[i]; + for (auto i = 0u; i < m_Effects.size(); ++i) { + auto* eff = m_Effects[i]; - if (eff->name == name) - { - index = i; + if (eff->name == name) { + index = i; - delete eff; + delete eff; - break; - } - } + break; + } + } - if (index == -1) - { + if (index == -1) { return; } - - m_Effects.erase(m_Effects.begin() + index);} -void RenderComponent::Update(const float deltaTime) -{ - std::vector dead; - - for (auto* effect : m_Effects) - { - if (effect->time == 0) - { - continue; // Skip persistent effects - } - - const auto result = effect->time - deltaTime; - - if (result <= 0) - { - dead.push_back(effect); - - continue; - } - - effect->time = result; - } - - for (auto* effect : dead) - { -// StopEffect(effect->name); - } + m_Effects.erase(m_Effects.begin() + index); } -void RenderComponent::PlayEffect(const int32_t effectId, const std::u16string& effectType, const std::string& name, const LWOOBJID secondary, const float priority, const float scale, const bool serialize) -{ - RemoveEffect(name); - - GameMessages::SendPlayFXEffect(m_Parent, effectId, effectType, name, secondary, priority, scale, serialize); +void RenderComponent::Update(const float deltaTime) { + std::vector dead; - auto* effect = AddEffect(effectId, name, effectType); + for (auto* effect : m_Effects) { + if (effect->time == 0) { + continue; // Skip persistent effects + } - const auto& pair = m_DurationCache.find(effectId); + const auto result = effect->time - deltaTime; - if (pair != m_DurationCache.end()) - { - effect->time = pair->second; + if (result <= 0) { + dead.push_back(effect); - return; - } + continue; + } - const std::string effectType_str = GeneralUtils::UTF16ToWTF8(effectType); + effect->time = result; + } - auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT animation_length FROM Animations WHERE animation_type IN (SELECT animationName FROM BehaviorEffect WHERE effectID = ? AND effectType = ?);"); - query.bind(1, effectId); - query.bind(2, effectType_str.c_str()); + for (auto* effect : dead) { + // StopEffect(effect->name); + } +} - auto result = query.execQuery(); +void RenderComponent::PlayEffect(const int32_t effectId, const std::u16string& effectType, const std::string& name, const LWOOBJID secondary, const float priority, const float scale, const bool serialize) { + RemoveEffect(name); - if (result.eof() || result.fieldIsNull(0)) { - result.finalize(); + GameMessages::SendPlayFXEffect(m_Parent, effectId, effectType, name, secondary, priority, scale, serialize); - m_DurationCache[effectId] = 0; + auto* effect = AddEffect(effectId, name, effectType); - effect->time = 0; // Persistent effect - - return; - } + const auto& pair = m_DurationCache.find(effectId); + + if (pair != m_DurationCache.end()) { + effect->time = pair->second; + + return; + } + + const std::string effectType_str = GeneralUtils::UTF16ToWTF8(effectType); + + auto query = CDClientDatabase::CreatePreppedStmt( + "SELECT animation_length FROM Animations WHERE animation_type IN (SELECT animationName FROM BehaviorEffect WHERE effectID = ? AND effectType = ?);"); + query.bind(1, effectId); + query.bind(2, effectType_str.c_str()); + + auto result = query.execQuery(); + + if (result.eof() || result.fieldIsNull(0)) { + result.finalize(); + + m_DurationCache[effectId] = 0; + + 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) -{ - GameMessages::SendStopFXEffect(m_Parent, killImmediate, name); +void RenderComponent::StopEffect(const std::string& name, const bool killImmediate) { + GameMessages::SendStopFXEffect(m_Parent, killImmediate, name); - RemoveEffect(name); + RemoveEffect(name); } -std::vector& RenderComponent::GetEffects() -{ - return m_Effects; +std::vector& RenderComponent::GetEffects() { + return m_Effects; } diff --git a/dGame/dComponents/RenderComponent.h b/dGame/dComponents/RenderComponent.h index 5107ae7b..e6184564 100644 --- a/dGame/dComponents/RenderComponent.h +++ b/dGame/dComponents/RenderComponent.h @@ -18,35 +18,35 @@ class Entity; struct Effect { Effect() { scale = 1.0f; } - /** - * The ID of the effect - */ - int32_t effectID = 0; + /** + * The ID of the effect + */ + int32_t effectID = 0; - /** - * The name of the effect - */ - std::string name = ""; + /** + * The name of the effect + */ + std::string name = ""; - /** - * The type of the effect - */ - std::u16string type = u""; + /** + * The type of the effect + */ + std::u16string type = u""; - /** - * How scaled (enlarged) the effect is - */ - float scale = 1.0f; + /** + * How scaled (enlarged) the effect is + */ + float scale = 1.0f; - /** - * Some related entity that casted the effect - */ - uint64_t secondary = 0; + /** + * Some related entity that casted the effect + */ + uint64_t secondary = 0; - /** - * The time that this effect plays for - */ - float time = 0; + /** + * The time that this effect plays for + */ + float time = 0; }; /** @@ -55,65 +55,65 @@ struct Effect { */ class RenderComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_RENDER; - - RenderComponent(Entity* entity); - ~RenderComponent() override; - - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void Update(float deltaTime) override; + static const uint32_t ComponentType = COMPONENT_TYPE_RENDER; - /** - * Adds an effect to this entity, if successful the effect is returned - * @param effectId the ID of the effect - * @param name the name of the effect - * @param type the type of the effect - * @return if successful, the effect that was created - */ - Effect* AddEffect(int32_t effectId, const std::string& name, const std::u16string& type); + RenderComponent(Entity* entity); + ~RenderComponent() override; - /** - * Removes an effect for this entity - * @param name the name of the effect to remove - */ - void RemoveEffect(const std::string& name); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Update(float deltaTime) override; - /** - * Plays an effect, removes any effects under this name and plays the one according to these params - * @param effectId the ID of the effect - * @param effectType the type of the effect - * @param name the name of the effect - * @param secondary some entity that cast the effect - * @param priority effect priority (determines if the client will play it over other effects) - * @param scale effect scale - * @param serialize whether to serialize the change or not - */ - void PlayEffect(int32_t effectId, const std::u16string& effectType, const std::string& name, LWOOBJID secondary = LWOOBJID_EMPTY, float priority = 1, float scale = 1, bool serialize = true); + /** + * Adds an effect to this entity, if successful the effect is returned + * @param effectId the ID of the effect + * @param name the name of the effect + * @param type the type of the effect + * @return if successful, the effect that was created + */ + Effect* AddEffect(int32_t effectId, const std::string& name, const std::u16string& type); - /** - * Removes and stops the effect for a certain name - * @param name name of the effect to stop - * @param killImmediate whether ot not to immediately stop playing the effect or phase it out - */ - void StopEffect(const std::string& name, bool killImmediate = true); + /** + * Removes an effect for this entity + * @param name the name of the effect to remove + */ + void RemoveEffect(const std::string& name); + + /** + * Plays an effect, removes any effects under this name and plays the one according to these params + * @param effectId the ID of the effect + * @param effectType the type of the effect + * @param name the name of the effect + * @param secondary some entity that cast the effect + * @param priority effect priority (determines if the client will play it over other effects) + * @param scale effect scale + * @param serialize whether to serialize the change or not + */ + void PlayEffect(int32_t effectId, const std::u16string& effectType, const std::string& name, LWOOBJID secondary = LWOOBJID_EMPTY, float priority = 1, float scale = 1, bool serialize = true); + + /** + * Removes and stops the effect for a certain name + * @param name name of the effect to stop + * @param killImmediate whether ot not to immediately stop playing the effect or phase it out + */ + void StopEffect(const std::string& name, bool killImmediate = true); + + /** + * Returns the list of currently active effects + * @return + */ + std::vector& GetEffects(); - /** - * Returns the list of currently active effects - * @return - */ - std::vector& GetEffects(); - private: - /** - * List of currently active effects - */ - std::vector m_Effects; + /** + * List of currently active effects + */ + std::vector m_Effects; - /** - * Cache of queries that look for the length of each effect, indexed by effect ID - */ - static std::unordered_map m_DurationCache; + /** + * Cache of queries that look for the length of each effect, indexed by effect ID + */ + static std::unordered_map m_DurationCache; }; #endif // RENDERCOMPONENT_H diff --git a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.cpp b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.cpp index 7a656d31..babd1974 100644 --- a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.cpp +++ b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.cpp @@ -7,27 +7,26 @@ #include "Entity.h" RigidbodyPhantomPhysicsComponent::RigidbodyPhantomPhysicsComponent(Entity* parent) : Component(parent) { - m_Position = m_Parent->GetDefaultPosition(); - m_Rotation = m_Parent->GetDefaultRotation(); - m_IsDirty = true; + m_Position = m_Parent->GetDefaultPosition(); + m_Rotation = m_Parent->GetDefaultRotation(); + m_IsDirty = true; } RigidbodyPhantomPhysicsComponent::~RigidbodyPhantomPhysicsComponent() { } void RigidbodyPhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - outBitStream->Write(m_IsDirty || bIsInitialUpdate); - if (m_IsDirty || bIsInitialUpdate) - { - outBitStream->Write(m_Position.x); - outBitStream->Write(m_Position.y); - outBitStream->Write(m_Position.z); - - outBitStream->Write(m_Rotation.x); - outBitStream->Write(m_Rotation.y); - outBitStream->Write(m_Rotation.z); - outBitStream->Write(m_Rotation.w); + outBitStream->Write(m_IsDirty || bIsInitialUpdate); + if (m_IsDirty || bIsInitialUpdate) { + outBitStream->Write(m_Position.x); + outBitStream->Write(m_Position.y); + outBitStream->Write(m_Position.z); - m_IsDirty = false; - } + outBitStream->Write(m_Rotation.x); + outBitStream->Write(m_Rotation.y); + outBitStream->Write(m_Rotation.z); + outBitStream->Write(m_Rotation.w); + + m_IsDirty = false; + } } diff --git a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h index e3ef45c2..c8faa930 100644 --- a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h +++ b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h @@ -12,59 +12,59 @@ #include "NiQuaternion.h" #include "Component.h" -/** - * Component that handles rigid bodies that can be interacted with, mostly client-side rendered. An example is the - * bananas that fall from trees in GF. - */ + /** + * Component that handles rigid bodies that can be interacted with, mostly client-side rendered. An example is the + * bananas that fall from trees in GF. + */ class RigidbodyPhantomPhysicsComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PHANTOM_PHYSICS; - - RigidbodyPhantomPhysicsComponent(Entity* parent); - ~RigidbodyPhantomPhysicsComponent() override; - - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + static const uint32_t ComponentType = COMPONENT_TYPE_PHANTOM_PHYSICS; - /** - * Returns the position of this entity - * @return the position of this entity - */ - NiPoint3& GetPosition() { return m_Position; } + RigidbodyPhantomPhysicsComponent(Entity* parent); + ~RigidbodyPhantomPhysicsComponent() override; - /** - * Sets the position of this entity - * @param pos the position to set - */ - void SetPosition(const NiPoint3& pos) { m_Position = pos; m_IsDirty = true; } + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Returns the rotation of this entity - * @return the rotation of this entity - */ - NiQuaternion& GetRotation() { return m_Rotation; } + /** + * Returns the position of this entity + * @return the position of this entity + */ + NiPoint3& GetPosition() { return m_Position; } - /** - * Sets the rotation for this entity - * @param rot the rotation to tset - */ - void SetRotation(const NiQuaternion& rot) { m_Rotation = rot; m_IsDirty = true; } + /** + * Sets the position of this entity + * @param pos the position to set + */ + void SetPosition(const NiPoint3& pos) { m_Position = pos; m_IsDirty = true; } + + /** + * Returns the rotation of this entity + * @return the rotation of this entity + */ + NiQuaternion& GetRotation() { return m_Rotation; } + + /** + * Sets the rotation for this entity + * @param rot the rotation to tset + */ + void SetRotation(const NiQuaternion& rot) { m_Rotation = rot; m_IsDirty = true; } private: - /** - * The position of this entity - */ - NiPoint3 m_Position; + /** + * The position of this entity + */ + NiPoint3 m_Position; - /** - * The rotation of this entity - */ - NiQuaternion m_Rotation; + /** + * The rotation of this entity + */ + NiQuaternion m_Rotation; - /** - * Whether or not the component should be serialized - */ - bool m_IsDirty; + /** + * Whether or not the component should be serialized + */ + bool m_IsDirty; }; #endif // RIGIDBODYPHANTOMPHYSICS_H diff --git a/dGame/dComponents/RocketLaunchLupComponent.h b/dGame/dComponents/RocketLaunchLupComponent.h index ce915d70..3fc0b444 100644 --- a/dGame/dComponents/RocketLaunchLupComponent.h +++ b/dGame/dComponents/RocketLaunchLupComponent.h @@ -35,5 +35,5 @@ private: /** * vector of the LUP World Zone IDs, built from CDServer's LUPZoneIDs table */ - std::vector m_LUPWorlds {}; + std::vector m_LUPWorlds{}; }; diff --git a/dGame/dComponents/RocketLaunchpadControlComponent.cpp b/dGame/dComponents/RocketLaunchpadControlComponent.cpp index 108335ae..4f248a40 100644 --- a/dGame/dComponents/RocketLaunchpadControlComponent.cpp +++ b/dGame/dComponents/RocketLaunchpadControlComponent.cpp @@ -25,8 +25,7 @@ RocketLaunchpadControlComponent::RocketLaunchpadControlComponent(Entity* parent, auto result = query.execQuery(); - if (!result.eof() && !result.fieldIsNull(0)) - { + if (!result.eof() && !result.fieldIsNull(0)) { m_TargetZone = result.getIntField(0); m_DefaultZone = result.getIntField(1); m_TargetScene = result.getStringField(2); @@ -44,8 +43,7 @@ RocketLaunchpadControlComponent::~RocketLaunchpadControlComponent() { void RocketLaunchpadControlComponent::Launch(Entity* originator, LWOMAPID mapId, LWOCLONEID cloneId) { auto zone = mapId == LWOMAPID_INVALID ? m_TargetZone : mapId; - if (zone == 0) - { + if (zone == 0) { return; } @@ -67,8 +65,7 @@ void RocketLaunchpadControlComponent::Launch(Entity* originator, LWOMAPID mapId, // Achievement unlocked: "All zones unlocked" if (!m_AltLandingScene.empty() && m_AltPrecondition->Check(originator)) { character->SetTargetScene(m_AltLandingScene); - } - else { + } else { character->SetTargetScene(m_TargetScene); } @@ -112,13 +109,11 @@ void RocketLaunchpadControlComponent::OnProximityUpdate(Entity* entering, std::s // Proximity rockets are handled by item equipment } -void RocketLaunchpadControlComponent::SetSelectedMapId(LWOOBJID player, LWOMAPID mapID) -{ +void RocketLaunchpadControlComponent::SetSelectedMapId(LWOOBJID player, LWOMAPID mapID) { m_SelectedMapIds[player] = mapID; } -LWOMAPID RocketLaunchpadControlComponent::GetSelectedMapId(LWOOBJID player) const -{ +LWOMAPID RocketLaunchpadControlComponent::GetSelectedMapId(LWOOBJID player) const { const auto index = m_SelectedMapIds.find(player); if (index == m_SelectedMapIds.end()) return 0; @@ -126,13 +121,11 @@ LWOMAPID RocketLaunchpadControlComponent::GetSelectedMapId(LWOOBJID player) cons return index->second; } -void RocketLaunchpadControlComponent::SetSelectedCloneId(LWOOBJID player, LWOCLONEID cloneId) -{ +void RocketLaunchpadControlComponent::SetSelectedCloneId(LWOOBJID player, LWOCLONEID cloneId) { m_SelectedCloneIds[player] = cloneId; } -LWOCLONEID RocketLaunchpadControlComponent::GetSelectedCloneId(LWOOBJID player) const -{ +LWOCLONEID RocketLaunchpadControlComponent::GetSelectedCloneId(LWOOBJID player) const { const auto index = m_SelectedCloneIds.find(player); if (index == m_SelectedCloneIds.end()) return 0; @@ -148,12 +141,10 @@ void RocketLaunchpadControlComponent::TellMasterToPrepZone(int zoneID) { } -LWOMAPID RocketLaunchpadControlComponent::GetTargetZone() const -{ +LWOMAPID RocketLaunchpadControlComponent::GetTargetZone() const { return m_TargetZone; } -LWOMAPID RocketLaunchpadControlComponent::GetDefaultZone() const -{ +LWOMAPID RocketLaunchpadControlComponent::GetDefaultZone() const { return m_DefaultZone; } diff --git a/dGame/dComponents/RocketLaunchpadControlComponent.h b/dGame/dComponents/RocketLaunchpadControlComponent.h index 7fdf4b32..8a10f0f7 100644 --- a/dGame/dComponents/RocketLaunchpadControlComponent.h +++ b/dGame/dComponents/RocketLaunchpadControlComponent.h @@ -18,114 +18,114 @@ class PreconditionExpression; class RocketLaunchpadControlComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_ROCKET_LAUNCH; - + RocketLaunchpadControlComponent(Entity* parent, int rocketId); ~RocketLaunchpadControlComponent() override; - /** - * Launches some entity to another world - * @param originator the entity to launch - * @param mapId the world to go to - * @param cloneId the clone ID (for properties) - */ + /** + * Launches some entity to another world + * @param originator the entity to launch + * @param mapId the world to go to + * @param cloneId the clone ID (for properties) + */ void Launch(Entity* originator, LWOMAPID mapId = LWOMAPID_INVALID, LWOCLONEID cloneId = LWOCLONEID_INVALID); - /** - * Handles an OnUse event from some entity, preparing it for launch to some other world - * @param originator the entity that triggered the event - */ + /** + * Handles an OnUse event from some entity, preparing it for launch to some other world + * @param originator the entity that triggered the event + */ void OnUse(Entity* originator) override; - /** - * Currently unused - */ + /** + * Currently unused + */ void OnProximityUpdate(Entity* entering, std::string name, std::string status); - /** - * Sets the map ID that a player will go to - * @param player the entity to set the map ID for - * @param cloneId the map ID of the property to set - */ + /** + * Sets the map ID that a player will go to + * @param player the entity to set the map ID for + * @param cloneId the map ID of the property to set + */ void SetSelectedMapId(LWOOBJID player, LWOMAPID cloneId); - /** - * Returns the map ID that a player will go to - * @param player the player to find the map ID for - * @return the map ID that a player will go to - */ + /** + * Returns the map ID that a player will go to + * @param player the player to find the map ID for + * @return the map ID that a player will go to + */ LWOMAPID GetSelectedMapId(LWOOBJID player) const; - /** - * Sets the clone ID that a player will go to (for properties) - * @param player the entity to set the clone ID for - * @param cloneId the clone ID of the property to set - */ + /** + * Sets the clone ID that a player will go to (for properties) + * @param player the entity to set the clone ID for + * @param cloneId the clone ID of the property to set + */ void SetSelectedCloneId(LWOOBJID player, LWOCLONEID cloneId); - /** - * Returns the clone ID that a player will go to (for properties) - * @param player the player to find the clone ID for - * @return the clone ID that a player will go to - */ + /** + * Returns the clone ID that a player will go to (for properties) + * @param player the player to find the clone ID for + * @return the clone ID that a player will go to + */ LWOCLONEID GetSelectedCloneId(LWOOBJID player) const; - /** - * Returns the zone that this rocket launchpad points to by default - * @return the zone that this rocket launchpad points to by default - */ + /** + * Returns the zone that this rocket launchpad points to by default + * @return the zone that this rocket launchpad points to by default + */ LWOMAPID GetTargetZone() const; - /** - * Currently unused - */ + /** + * Currently unused + */ LWOMAPID GetDefaultZone() const; private: - /** - * All the players that are in the proximity of the rocket launchpad - */ + /** + * All the players that are in the proximity of the rocket launchpad + */ std::map m_PlayersInRadius = {}; - /** - * The map that the launchpad goes to - */ + /** + * The map that the launchpad goes to + */ LWOMAPID m_TargetZone; - /** - * Currently unused - */ + /** + * Currently unused + */ LWOMAPID m_DefaultZone; - /** - * The clone IDs selected for each player to go to (for properies) - */ + /** + * The clone IDs selected for each player to go to (for properies) + */ std::map m_SelectedCloneIds = {}; - /** - * The map IDs selected for each player to go to - */ + /** + * The map IDs selected for each player to go to + */ std::map m_SelectedMapIds = {}; - /** - * The scene that plays when the player lands - */ + /** + * The scene that plays when the player lands + */ std::string m_TargetScene; - /** - * Alternative landing scene that plays if the alternative precondition is met - */ + /** + * Alternative landing scene that plays if the alternative precondition is met + */ std::string m_AltLandingScene; - /** - * Some precondition that needs to be met to trigger the alternative landing scene - */ + /** + * Some precondition that needs to be met to trigger the alternative landing scene + */ PreconditionExpression* m_AltPrecondition; - /** - * Notifies the master server to prepare some world for a player to be able to travel to it - * @param zoneID the ID of the zone to prepare - */ + /** + * Notifies the master server to prepare some world for a player to be able to travel to it + * @param zoneID the ID of the zone to prepare + */ void TellMasterToPrepZone(int zoneID); }; diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index edc6b70d..4b5ec41d 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -18,29 +18,28 @@ #include "dConfig.h" #include "DestroyableComponent.h" -ScriptedActivityComponent::ScriptedActivityComponent(Entity* parent, int activityID) : Component(parent) -{ +ScriptedActivityComponent::ScriptedActivityComponent(Entity* parent, int activityID) : Component(parent) { CDActivitiesTable* activitiesTable = CDClientManager::Instance()->GetTable("Activities"); std::vector activities = activitiesTable->Query([=](CDActivities entry) {return (entry.ActivityID == activityID); }); for (CDActivities activity : activities) { m_ActivityInfo = activity; - const auto mapID = m_ActivityInfo.instanceMapID; + const auto mapID = m_ActivityInfo.instanceMapID; - if ((mapID == 1203 || mapID == 1261 || mapID == 1303 || mapID == 1403) && Game::config->GetValue("solo_racing") == "1") { - m_ActivityInfo.minTeamSize = 1; - m_ActivityInfo.minTeams = 1; - } + if ((mapID == 1203 || mapID == 1261 || mapID == 1303 || mapID == 1403) && Game::config->GetValue("solo_racing") == "1") { + m_ActivityInfo.minTeamSize = 1; + m_ActivityInfo.minTeams = 1; + } - const auto& transferOverride = parent->GetVar(u"transferZoneID"); - if (!transferOverride.empty()) { - m_ActivityInfo.instanceMapID = std::stoi(GeneralUtils::UTF16ToWTF8(transferOverride)); + const auto& transferOverride = parent->GetVar(u"transferZoneID"); + if (!transferOverride.empty()) { + m_ActivityInfo.instanceMapID = std::stoi(GeneralUtils::UTF16ToWTF8(transferOverride)); // TODO: LU devs made me do it (for some reason cannon cove instancer is marked to go to GF survival) // NOTE: 1301 is GF survival if (m_ActivityInfo.instanceMapID == 1301) { - m_ActivityInfo.instanceMapID = 1302; + m_ActivityInfo.instanceMapID = 1302; } } } @@ -75,30 +74,30 @@ ScriptedActivityComponent::~ScriptedActivityComponent() = default; void ScriptedActivityComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) const { - outBitStream->Write(true); - outBitStream->Write(m_ActivityPlayers.size()); + outBitStream->Write(true); + outBitStream->Write(m_ActivityPlayers.size()); - if (!m_ActivityPlayers.empty()) { - for (const auto& activityPlayer : m_ActivityPlayers) { + if (!m_ActivityPlayers.empty()) { + for (const auto& activityPlayer : m_ActivityPlayers) { - outBitStream->Write(activityPlayer->playerID); - for (const auto& activityValue : activityPlayer->values) { - outBitStream->Write(activityValue); - } - } - } + outBitStream->Write(activityPlayer->playerID); + for (const auto& activityValue : activityPlayer->values) { + outBitStream->Write(activityValue); + } + } + } } void ScriptedActivityComponent::HandleMessageBoxResponse(Entity* player, const std::string& id) { - if (m_ActivityInfo.ActivityID == 103) { - return; - } + if (m_ActivityInfo.ActivityID == 103) { + return; + } - if (id == "LobbyExit") { - PlayerLeave(player->GetObjectID()); - } else if (id == "PlayButton") { - PlayerJoin(player); - } + if (id == "LobbyExit") { + PlayerLeave(player->GetObjectID()); + } else if (id == "PlayButton") { + PlayerJoin(player); + } } void ScriptedActivityComponent::PlayerJoin(Entity* player) { @@ -108,10 +107,10 @@ void ScriptedActivityComponent::PlayerJoin(Entity* player) { // If we have a lobby, queue the player and allow others to join, otherwise spin up an instance on the spot if (HasLobby()) { - PlayerJoinLobby(player); + PlayerJoinLobby(player); } else if (!IsPlayedBy(player)) { - auto* instance = NewInstance(); - instance->AddParticipant(player); + auto* instance = NewInstance(); + instance->AddParticipant(player); } EntityManager::Instance()->SerializeEntity(m_Parent); @@ -119,57 +118,56 @@ void ScriptedActivityComponent::PlayerJoin(Entity* player) { void ScriptedActivityComponent::PlayerJoinLobby(Entity* player) { if (!m_Parent->HasComponent(COMPONENT_TYPE_REBUILD)) - GameMessages::SendMatchResponse(player, player->GetSystemAddress(), 0); // tell the client they joined a lobby - LobbyPlayer* newLobbyPlayer = new LobbyPlayer(); - newLobbyPlayer->entityID = player->GetObjectID(); - Lobby* playerLobby = nullptr; + GameMessages::SendMatchResponse(player, player->GetSystemAddress(), 0); // tell the client they joined a lobby + LobbyPlayer* newLobbyPlayer = new LobbyPlayer(); + newLobbyPlayer->entityID = player->GetObjectID(); + Lobby* playerLobby = nullptr; - auto* character = player->GetCharacter(); - if (character != nullptr) - character->SetLastNonInstanceZoneID(dZoneManager::Instance()->GetZone()->GetWorldID()); + auto* character = player->GetCharacter(); + if (character != nullptr) + character->SetLastNonInstanceZoneID(dZoneManager::Instance()->GetZone()->GetWorldID()); - for (Lobby* lobby : m_Queue) { - if (lobby->players.size() < m_ActivityInfo.maxTeamSize || m_ActivityInfo.maxTeamSize == 1 && lobby->players.size() < m_ActivityInfo.maxTeams) { - // If an empty slot in an existing lobby is found - lobby->players.push_back(newLobbyPlayer); - playerLobby = lobby; + for (Lobby* lobby : m_Queue) { + if (lobby->players.size() < m_ActivityInfo.maxTeamSize || m_ActivityInfo.maxTeamSize == 1 && lobby->players.size() < m_ActivityInfo.maxTeams) { + // If an empty slot in an existing lobby is found + lobby->players.push_back(newLobbyPlayer); + playerLobby = lobby; - // Update the joining player on players already in the lobby, and update players already in the lobby on the joining player - std::string matchUpdateJoined = "player=9:" + std::to_string(player->GetObjectID()) + "\nplayerName=0:" + player->GetCharacter()->GetName(); - for (LobbyPlayer* joinedPlayer : lobby->players) { - auto* entity = joinedPlayer->GetEntity(); + // Update the joining player on players already in the lobby, and update players already in the lobby on the joining player + std::string matchUpdateJoined = "player=9:" + std::to_string(player->GetObjectID()) + "\nplayerName=0:" + player->GetCharacter()->GetName(); + for (LobbyPlayer* joinedPlayer : lobby->players) { + auto* entity = joinedPlayer->GetEntity(); - if (entity == nullptr) - { - continue; - } + if (entity == nullptr) { + continue; + } - std::string matchUpdate = "player=9:" + std::to_string(entity->GetObjectID()) + "\nplayerName=0:" + entity->GetCharacter()->GetName(); - GameMessages::SendMatchUpdate(player, player->GetSystemAddress(), matchUpdate, eMatchUpdate::MATCH_UPDATE_PLAYER_JOINED); - PlayerReady(entity, joinedPlayer->ready); - GameMessages::SendMatchUpdate(entity, entity->GetSystemAddress(), matchUpdateJoined, eMatchUpdate::MATCH_UPDATE_PLAYER_JOINED); - } - } - } + std::string matchUpdate = "player=9:" + std::to_string(entity->GetObjectID()) + "\nplayerName=0:" + entity->GetCharacter()->GetName(); + GameMessages::SendMatchUpdate(player, player->GetSystemAddress(), matchUpdate, eMatchUpdate::MATCH_UPDATE_PLAYER_JOINED); + PlayerReady(entity, joinedPlayer->ready); + GameMessages::SendMatchUpdate(entity, entity->GetSystemAddress(), matchUpdateJoined, eMatchUpdate::MATCH_UPDATE_PLAYER_JOINED); + } + } + } - if (!playerLobby) { - // If all lobbies are full - playerLobby = new Lobby(); - playerLobby->players.push_back(newLobbyPlayer); - playerLobby->timer = m_ActivityInfo.waitTime / 1000; - m_Queue.push_back(playerLobby); - } + if (!playerLobby) { + // If all lobbies are full + playerLobby = new Lobby(); + playerLobby->players.push_back(newLobbyPlayer); + playerLobby->timer = m_ActivityInfo.waitTime / 1000; + m_Queue.push_back(playerLobby); + } - if (m_ActivityInfo.maxTeamSize != 1 && playerLobby->players.size() >= m_ActivityInfo.minTeamSize || m_ActivityInfo.maxTeamSize == 1 && playerLobby->players.size() >= m_ActivityInfo.minTeams) { - // Update the joining player on the match timer - std::string matchTimerUpdate = "time=3:" + std::to_string(playerLobby->timer); - GameMessages::SendMatchUpdate(player, player->GetSystemAddress(), matchTimerUpdate, eMatchUpdate::MATCH_UPDATE_TIME); - } + if (m_ActivityInfo.maxTeamSize != 1 && playerLobby->players.size() >= m_ActivityInfo.minTeamSize || m_ActivityInfo.maxTeamSize == 1 && playerLobby->players.size() >= m_ActivityInfo.minTeams) { + // Update the joining player on the match timer + std::string matchTimerUpdate = "time=3:" + std::to_string(playerLobby->timer); + GameMessages::SendMatchUpdate(player, player->GetSystemAddress(), matchTimerUpdate, eMatchUpdate::MATCH_UPDATE_TIME); + } } void ScriptedActivityComponent::PlayerLeave(LWOOBJID playerID) { - // Removes the player from a lobby and notifies the others, not applicable for non-lobby instances + // Removes the player from a lobby and notifies the others, not applicable for non-lobby instances for (Lobby* lobby : m_Queue) { for (int i = 0; i < lobby->players.size(); ++i) { if (lobby->players[i]->entityID == playerID) { @@ -194,7 +192,7 @@ void ScriptedActivityComponent::PlayerLeave(LWOOBJID playerID) { void ScriptedActivityComponent::Update(float deltaTime) { - // Ticks all the lobbies, not applicable for non-instance activities + // Ticks all the lobbies, not applicable for non-instance activities for (Lobby* lobby : m_Queue) { for (LobbyPlayer* player : lobby->players) { auto* entity = player->GetEntity(); @@ -206,7 +204,7 @@ void ScriptedActivityComponent::Update(float deltaTime) { // Update the match time for all players if (m_ActivityInfo.maxTeamSize != 1 && lobby->players.size() >= m_ActivityInfo.minTeamSize - || m_ActivityInfo.maxTeamSize == 1 && lobby->players.size() >= m_ActivityInfo.minTeams) { + || m_ActivityInfo.maxTeamSize == 1 && lobby->players.size() >= m_ActivityInfo.minTeams) { if (lobby->timer == m_ActivityInfo.waitTime / 1000) { for (LobbyPlayer* joinedPlayer : lobby->players) { auto* entity = joinedPlayer->GetEntity(); @@ -266,25 +264,25 @@ void ScriptedActivityComponent::RemoveLobby(Lobby* lobby) { } bool ScriptedActivityComponent::HasLobby() const { - // If the player is not in the world he has to be, create a lobby for the transfer - return m_ActivityInfo.instanceMapID != UINT_MAX && m_ActivityInfo.instanceMapID != Game::server->GetZoneID(); + // If the player is not in the world he has to be, create a lobby for the transfer + return m_ActivityInfo.instanceMapID != UINT_MAX && m_ActivityInfo.instanceMapID != Game::server->GetZoneID(); } bool ScriptedActivityComponent::IsValidActivity(Entity* player) { - // Makes it so that scripted activities with an unimplemented map cannot be joined - /*if (player->GetGMLevel() < GAME_MASTER_LEVEL_DEVELOPER && (m_ActivityInfo.instanceMapID == 1302 || m_ActivityInfo.instanceMapID == 1301)) { - if (m_Parent->GetLOT() == 4860) { - auto* missionComponent = player->GetComponent(); - missionComponent->CompleteMission(229); - } + // Makes it so that scripted activities with an unimplemented map cannot be joined + /*if (player->GetGMLevel() < GAME_MASTER_LEVEL_DEVELOPER && (m_ActivityInfo.instanceMapID == 1302 || m_ActivityInfo.instanceMapID == 1301)) { + if (m_Parent->GetLOT() == 4860) { + auto* missionComponent = player->GetComponent(); + missionComponent->CompleteMission(229); + } - ChatPackets::SendSystemMessage(player->GetSystemAddress(), u"Sorry, this activity is not ready."); - static_cast(player)->SendToZone(dZoneManager::Instance()->GetZone()->GetWorldID()); // Gets them out of this stuck state + ChatPackets::SendSystemMessage(player->GetSystemAddress(), u"Sorry, this activity is not ready."); + static_cast(player)->SendToZone(dZoneManager::Instance()->GetZone()->GetWorldID()); // Gets them out of this stuck state - return false; - }*/ + return false; + }*/ - return true; + return true; } bool ScriptedActivityComponent::PlayerIsInQueue(Entity* player) { @@ -298,25 +296,25 @@ bool ScriptedActivityComponent::PlayerIsInQueue(Entity* player) { } bool ScriptedActivityComponent::IsPlayedBy(Entity* player) const { - for (const auto* instance : this->m_Instances) { - for (const auto* instancePlayer : instance->GetParticipants()) { - if (instancePlayer != nullptr && instancePlayer->GetObjectID() == player->GetObjectID()) - return true; - } - } + for (const auto* instance : this->m_Instances) { + for (const auto* instancePlayer : instance->GetParticipants()) { + if (instancePlayer != nullptr && instancePlayer->GetObjectID() == player->GetObjectID()) + return true; + } + } - return false; + return false; } bool ScriptedActivityComponent::IsPlayedBy(LWOOBJID playerID) const { - for (const auto* instance : this->m_Instances) { - for (const auto* instancePlayer : instance->GetParticipants()) { - if (instancePlayer != nullptr && instancePlayer->GetObjectID() == playerID) - return true; - } - } + for (const auto* instance : this->m_Instances) { + for (const auto* instancePlayer : instance->GetParticipants()) { + if (instancePlayer != nullptr && instancePlayer->GetObjectID() == playerID) + return true; + } + } - return false; + return false; } bool ScriptedActivityComponent::TakeCost(Entity* player) const { @@ -365,14 +363,14 @@ ActivityInstance* ScriptedActivityComponent::NewInstance() { } void ScriptedActivityComponent::LoadPlayersIntoInstance(ActivityInstance* instance, const std::vector& lobby) const { - for (LobbyPlayer* player : lobby) { - auto* entity = player->GetEntity(); - if (entity == nullptr || !TakeCost(entity)) { - continue; - } + for (LobbyPlayer* player : lobby) { + auto* entity = player->GetEntity(); + if (entity == nullptr || !TakeCost(entity)) { + continue; + } - instance->AddParticipant(entity); - } + instance->AddParticipant(entity); + } } const std::vector& ScriptedActivityComponent::GetInstances() const { @@ -380,14 +378,14 @@ const std::vector& ScriptedActivityComponent::GetInstances() } ActivityInstance* ScriptedActivityComponent::GetInstance(const LWOOBJID playerID) { - for (const auto* instance : GetInstances()) { - for (const auto* participant : instance->GetParticipants()) { - if (participant->GetObjectID() == playerID) - return const_cast(instance); - } - } + for (const auto* instance : GetInstances()) { + for (const auto* participant : instance->GetParticipants()) { + if (participant->GetObjectID() == playerID) + return const_cast(instance); + } + } - return nullptr; + return nullptr; } void ScriptedActivityComponent::ClearInstances() { @@ -397,12 +395,9 @@ void ScriptedActivityComponent::ClearInstances() { m_Instances.clear(); } -ActivityPlayer* ScriptedActivityComponent::GetActivityPlayerData(LWOOBJID playerID) -{ - for (auto* activityData : m_ActivityPlayers) - { - if (activityData->playerID == playerID) - { +ActivityPlayer* ScriptedActivityComponent::GetActivityPlayerData(LWOOBJID playerID) { + for (auto* activityData : m_ActivityPlayers) { + if (activityData->playerID == playerID) { return activityData; } } @@ -410,87 +405,83 @@ ActivityPlayer* ScriptedActivityComponent::GetActivityPlayerData(LWOOBJID player return nullptr; } -void ScriptedActivityComponent::RemoveActivityPlayerData(LWOOBJID playerID) -{ - for (size_t i = 0; i < m_ActivityPlayers.size(); i++) - { - if (m_ActivityPlayers[i]->playerID == playerID) - { +void ScriptedActivityComponent::RemoveActivityPlayerData(LWOOBJID playerID) { + for (size_t i = 0; i < m_ActivityPlayers.size(); i++) { + if (m_ActivityPlayers[i]->playerID == playerID) { delete m_ActivityPlayers[i]; m_ActivityPlayers[i] = nullptr; m_ActivityPlayers.erase(m_ActivityPlayers.begin() + i); - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); return; } } } -ActivityPlayer* ScriptedActivityComponent::AddActivityPlayerData(LWOOBJID playerID) -{ +ActivityPlayer* ScriptedActivityComponent::AddActivityPlayerData(LWOOBJID playerID) { auto* data = GetActivityPlayerData(playerID); if (data != nullptr) - return data; + return data; - m_ActivityPlayers.push_back(new ActivityPlayer{playerID, {}}); - EntityManager::Instance()->SerializeEntity(m_Parent); + m_ActivityPlayers.push_back(new ActivityPlayer{ playerID, {} }); + EntityManager::Instance()->SerializeEntity(m_Parent); return GetActivityPlayerData(playerID); } float_t ScriptedActivityComponent::GetActivityValue(LWOOBJID playerID, uint32_t index) { - auto value = -1.0f; + auto value = -1.0f; - auto* data = GetActivityPlayerData(playerID); - if (data != nullptr) { - value = data->values[std::min(index, (uint32_t) 9)]; - } + auto* data = GetActivityPlayerData(playerID); + if (data != nullptr) { + value = data->values[std::min(index, (uint32_t)9)]; + } - return value; + return value; } void ScriptedActivityComponent::SetActivityValue(LWOOBJID playerID, uint32_t index, float_t value) { - auto* data = AddActivityPlayerData(playerID); - if (data != nullptr) { - data->values[std::min(index, (uint32_t) 9)] = value; - } + auto* data = AddActivityPlayerData(playerID); + if (data != nullptr) { + data->values[std::min(index, (uint32_t)9)] = value; + } - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); } void ScriptedActivityComponent::PlayerRemove(LWOOBJID playerID) { - for (auto* instance : GetInstances()) { - auto participants = instance->GetParticipants(); - for (const auto* participant : participants) { - if (participant != nullptr && participant->GetObjectID() == playerID) { - instance->RemoveParticipant(participant); - RemoveActivityPlayerData(playerID); + for (auto* instance : GetInstances()) { + auto participants = instance->GetParticipants(); + for (const auto* participant : participants) { + if (participant != nullptr && participant->GetObjectID() == playerID) { + instance->RemoveParticipant(participant); + RemoveActivityPlayerData(playerID); - // If the instance is empty after the delete of the participant, delete the instance too - if (instance->GetParticipants().empty()) { - m_Instances.erase(std::find(m_Instances.begin(), m_Instances.end(), instance)); - delete instance; - } - return; - } - } - } + // If the instance is empty after the delete of the participant, delete the instance too + if (instance->GetParticipants().empty()) { + m_Instances.erase(std::find(m_Instances.begin(), m_Instances.end(), instance)); + delete instance; + } + return; + } + } + } } void ActivityInstance::StartZone() { if (m_Participants.empty()) - return; + return; const auto& participants = GetParticipants(); if (participants.empty()) - return; + return; auto* leader = participants[0]; LWOZONEID zoneId = LWOZONEID(m_ActivityInfo.instanceMapID, 0, leader->GetCharacter()->GetPropertyCloneID()); // only make a team if we have more than one participant - if (participants.size() > 1){ + if (participants.size() > 1) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_CREATE_TEAM); @@ -524,7 +515,7 @@ void ActivityInstance::StartZone() { WorldPackets::SendTransferToWorld(player->GetSystemAddress(), serverIP, serverPort, mythranShift); return; - }); + }); } m_NextZoneCloneID++; @@ -572,24 +563,24 @@ std::vector ActivityInstance::GetParticipants() const { void ActivityInstance::AddParticipant(Entity* participant) { const auto id = participant->GetObjectID(); if (std::count(m_Participants.begin(), m_Participants.end(), id)) - return; + return; m_Participants.push_back(id); } -void ActivityInstance::RemoveParticipant(const Entity *participant) { - const auto loadedParticipant = std::find(m_Participants.begin(), m_Participants.end(), participant->GetObjectID()); - if (loadedParticipant != m_Participants.end()) { - m_Participants.erase(loadedParticipant); - } +void ActivityInstance::RemoveParticipant(const Entity* participant) { + const auto loadedParticipant = std::find(m_Participants.begin(), m_Participants.end(), participant->GetObjectID()); + if (loadedParticipant != m_Participants.end()) { + m_Participants.erase(loadedParticipant); + } } uint32_t ActivityInstance::GetScore() const { - return score; + return score; } void ActivityInstance::SetScore(uint32_t score) { - this->score = score; + this->score = score; } Entity* LobbyPlayer::GetEntity() const { diff --git a/dGame/dComponents/ScriptedActivityComponent.h b/dGame/dComponents/ScriptedActivityComponent.h index 8d79df8b..66ca799f 100644 --- a/dGame/dComponents/ScriptedActivityComponent.h +++ b/dGame/dComponents/ScriptedActivityComponent.h @@ -12,82 +12,82 @@ #include "Entity.h" #include "Component.h" -/** - * Represents an instance of an activity, having participants and score - */ + /** + * Represents an instance of an activity, having participants and score + */ class ActivityInstance { public: ActivityInstance(Entity* parent, CDActivities activityInfo) { m_Parent = parent; m_ActivityInfo = activityInfo; }; //~ActivityInstance(); - /** - * Adds an entity to this activity - * @param participant the entity to add - */ + /** + * Adds an entity to this activity + * @param participant the entity to add + */ void AddParticipant(Entity* participant); - /** - * Removes all the participants from this activity - */ + /** + * Removes all the participants from this activity + */ void ClearParticipants() { m_Participants.clear(); }; - /** - * Starts the instance world for this activity and sends all participants there - */ + /** + * Starts the instance world for this activity and sends all participants there + */ void StartZone(); - /** - * Gives the rewards for completing this activity to some participant - * @param participant the participant to give rewards to - */ + /** + * Gives the rewards for completing this activity to some participant + * @param participant the participant to give rewards to + */ void RewardParticipant(Entity* participant); - /** - * Removes a participant from this activity - * @param participant the participant to remove - */ + /** + * Removes a participant from this activity + * @param participant the participant to remove + */ void RemoveParticipant(const Entity* participant); - /** - * Returns all the participants of this activity - * @return all the participants of this activity - */ + /** + * Returns all the participants of this activity + * @return all the participants of this activity + */ std::vector GetParticipants() const; - /** - * Currently unused - */ + /** + * Currently unused + */ uint32_t GetScore() const; - /** - * Currently unused - */ + /** + * Currently unused + */ void SetScore(uint32_t score); private: - /** - * Currently unused - */ - uint32_t score = 0; + /** + * Currently unused + */ + uint32_t score = 0; - /** - * The instance ID of this activity - */ + /** + * The instance ID of this activity + */ uint32_t m_NextZoneCloneID = 0; - /** - * The database information for this activity - */ + /** + * The database information for this activity + */ CDActivities m_ActivityInfo; - /** - * The entity that owns this activity (the entity that has the ScriptedActivityComponent) - */ + /** + * The entity that owns this activity (the entity that has the ScriptedActivityComponent) + */ Entity* m_Parent; - /** - * All the participants of this activity - */ + /** + * All the participants of this activity + */ std::vector m_Participants; }; @@ -96,20 +96,20 @@ private: */ struct LobbyPlayer { - /** - * The ID of the entity that is in the lobby - */ + /** + * The ID of the entity that is in the lobby + */ LWOOBJID entityID; - /** - * Whether or not the entity is ready - */ + /** + * Whether or not the entity is ready + */ bool ready = false; - /** - * Returns the entity that is in the lobby - * @return the entity that is in the lobby - */ + /** + * Returns the entity that is in the lobby + * @return the entity that is in the lobby + */ Entity* GetEntity() const; }; @@ -118,14 +118,14 @@ struct LobbyPlayer { */ struct Lobby { - /** - * The lobby of players - */ + /** + * The lobby of players + */ std::vector players; - /** - * The timer that determines when the activity should start - */ + /** + * The timer that determines when the activity should start + */ float timer; }; @@ -134,14 +134,14 @@ struct Lobby { */ struct ActivityPlayer { - /** - * The entity that the score is tracked for - */ + /** + * The entity that the score is tracked for + */ LWOOBJID playerID; - /** - * The list of score for this entity - */ + /** + * The list of score for this entity + */ float values[10]; }; @@ -154,213 +154,213 @@ struct ActivityPlayer { class ScriptedActivityComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_SCRIPTED_ACTIVITY; - + ScriptedActivityComponent(Entity* parent, int activityID); ~ScriptedActivityComponent() override; - void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) const; + void Update(float deltaTime) override; + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) const; - /** - * Makes some entity join the minigame, if it's a lobbied one, the entity will be placed in the lobby - * @param player the entity to join the game - */ + /** + * Makes some entity join the minigame, if it's a lobbied one, the entity will be placed in the lobby + * @param player the entity to join the game + */ void PlayerJoin(Entity* player); - /** - * Makes an entity join the lobby for this minigame, if it exists - * @param player the entity to join - */ + /** + * Makes an entity join the lobby for this minigame, if it exists + * @param player the entity to join + */ void PlayerJoinLobby(Entity* player); - /** - * Makes the player leave the lobby - * @param playerID the entity to leave the lobby - */ + /** + * Makes the player leave the lobby + * @param playerID the entity to leave the lobby + */ void PlayerLeave(LWOOBJID playerID); - /** - * Removes the entity from the minigame (and its score) - * @param playerID the entity to remove from the minigame - */ + /** + * Removes the entity from the minigame (and its score) + * @param playerID the entity to remove from the minigame + */ void PlayerRemove(LWOOBJID playerID); - /** - * Adds all the players to an instance of some activity - * @param instance the instance to load the players into - * @param lobby the players to load into the instance - */ + /** + * Adds all the players to an instance of some activity + * @param instance the instance to load the players into + * @param lobby the players to load into the instance + */ void LoadPlayersIntoInstance(ActivityInstance* instance, const std::vector& lobby) const; - /** - * Removes a lobby from the activity manager - * @param lobby the lobby to remove - */ + /** + * Removes a lobby from the activity manager + * @param lobby the lobby to remove + */ void RemoveLobby(Lobby* lobby); - /** - * Marks a player as (un)ready in a lobby - * @param player the entity to mark - * @param bReady true if the entity is ready, false otherwise - */ + /** + * Marks a player as (un)ready in a lobby + * @param player the entity to mark + * @param bReady true if the entity is ready, false otherwise + */ void PlayerReady(Entity* player, bool bReady); - /** - * Returns the ID of this activity - * @return the ID of this activity - */ + /** + * Returns the ID of this activity + * @return the ID of this activity + */ int GetActivityID() { return m_ActivityInfo.ActivityID; } - /** - * Returns if this activity has a lobby, e.g. if it needs to instance players to some other map - * @return true if this activity has a lobby, false otherwise - */ - bool HasLobby() const; + /** + * Returns if this activity has a lobby, e.g. if it needs to instance players to some other map + * @return true if this activity has a lobby, false otherwise + */ + bool HasLobby() const; - /** - * Checks if a player is currently waiting in a lobby - * @param player the entity to check for - * @return true if the entity is waiting in a lobby, false otherwise - */ + /** + * Checks if a player is currently waiting in a lobby + * @param player the entity to check for + * @return true if the entity is waiting in a lobby, false otherwise + */ bool PlayerIsInQueue(Entity* player); - /** - * Checks if an entity is currently playing this activity - * @param player the entity to check - * @return true if the entity is playing this lobby, false otherwise - */ + /** + * Checks if an entity is currently playing this activity + * @param player the entity to check + * @return true if the entity is playing this lobby, false otherwise + */ bool IsPlayedBy(Entity* player) const; - /** - * Checks if an entity is currently playing this activity - * @param playerID the entity to check - * @return true if the entity is playing this lobby, false otherwise - */ - bool IsPlayedBy(LWOOBJID playerID) const; + /** + * Checks if an entity is currently playing this activity + * @param playerID the entity to check + * @return true if the entity is playing this lobby, false otherwise + */ + bool IsPlayedBy(LWOOBJID playerID) const; - /** - * Legacy: used to check for unimplemented maps, gladly, this now just returns true :) - */ + /** + * Legacy: used to check for unimplemented maps, gladly, this now just returns true :) + */ bool IsValidActivity(Entity* player); - /** - * Removes the cost of the activity (e.g. green imaginate) for the entity that plays this activity - * @param player the entity to take cost for - * @return true if the cost was successfully deducted, false otherwise - */ + /** + * Removes the cost of the activity (e.g. green imaginate) for the entity that plays this activity + * @param player the entity to take cost for + * @return true if the cost was successfully deducted, false otherwise + */ bool TakeCost(Entity* player) const; - /** - * Handles any response from a player clicking on a lobby / instance menu - * @param player the entity that clicked - * @param id the message that was passed - */ + /** + * Handles any response from a player clicking on a lobby / instance menu + * @param player the entity that clicked + * @param id the message that was passed + */ void HandleMessageBoxResponse(Entity* player, const std::string& id); - /** - * Creates a new instance for this activity - * @return a new instance for this activity - */ + /** + * Creates a new instance for this activity + * @return a new instance for this activity + */ ActivityInstance* NewInstance(); - /** - * Returns all the currently active instances of this activity - * @return all the currently active instances of this activity - */ + /** + * Returns all the currently active instances of this activity + * @return all the currently active instances of this activity + */ const std::vector& GetInstances() const; - /** - * Returns the instance that some entity is currently playing in - * @param playerID the entity to check for - * @return if any, the instance that the entity is currently in - */ + /** + * Returns the instance that some entity is currently playing in + * @param playerID the entity to check for + * @return if any, the instance that the entity is currently in + */ ActivityInstance* GetInstance(const LWOOBJID playerID); - /** - * Removes all the instances - */ + /** + * Removes all the instances + */ void ClearInstances(); - /** - * Returns all the score for the players that are currently playing this activity - * @return - */ + /** + * Returns all the score for the players that are currently playing this activity + * @return + */ std::vector GetActivityPlayers() { return m_ActivityPlayers; }; - /** - * Returns activity data for a specific entity (e.g. score and such). - * @param playerID the entity to get data for - * @return the activity data (score) for the passed player in this activity, if it exists - */ + /** + * Returns activity data for a specific entity (e.g. score and such). + * @param playerID the entity to get data for + * @return the activity data (score) for the passed player in this activity, if it exists + */ ActivityPlayer* GetActivityPlayerData(LWOOBJID playerID); - /** - * Sets some score value for an entity - * @param playerID the entity to set score for - * @param index the score index to set - * @param value the value to set in for that index - */ + /** + * Sets some score value for an entity + * @param playerID the entity to set score for + * @param index the score index to set + * @param value the value to set in for that index + */ void SetActivityValue(LWOOBJID playerID, uint32_t index, float_t value); - /** - * Returns activity score for the passed parameters - * @param playerID the entity to get score for - * @param index the index to get score for - * @return activity score for the passed parameters - */ + /** + * Returns activity score for the passed parameters + * @param playerID the entity to get score for + * @param index the index to get score for + * @return activity score for the passed parameters + */ float_t GetActivityValue(LWOOBJID playerID, uint32_t index); - /** - * Removes activity score tracking for some entity - * @param playerID the entity to remove score for - */ + /** + * Removes activity score tracking for some entity + * @param playerID the entity to remove score for + */ void RemoveActivityPlayerData(LWOOBJID playerID); - /** - * Adds activity score tracking for some entity - * @param playerID the entity to add the activity score for - * @return the created entry - */ + /** + * Adds activity score tracking for some entity + * @param playerID the entity to add the activity score for + * @return the created entry + */ ActivityPlayer* AddActivityPlayerData(LWOOBJID playerID); - /** - * Sets the mapID that this activity points to - * @param mapID the map ID to set - */ + /** + * Sets the mapID that this activity points to + * @param mapID the map ID to set + */ void SetInstanceMapID(uint32_t mapID) { m_ActivityInfo.instanceMapID = mapID; }; - /** - * Returns the LMI that this activity points to for a team size - * @param teamSize the team size to get the LMI for - * @return the LMI that this activity points to for a team size - */ - uint32_t GetLootMatrixForTeamSize(uint32_t teamSize) { return m_ActivityLootMatrices[teamSize]; } + /** + * Returns the LMI that this activity points to for a team size + * @param teamSize the team size to get the LMI for + * @return the LMI that this activity points to for a team size + */ + uint32_t GetLootMatrixForTeamSize(uint32_t teamSize) { return m_ActivityLootMatrices[teamSize]; } private: - /** - * The database information for this activity - */ + /** + * The database information for this activity + */ CDActivities m_ActivityInfo; - /** - * All the active instances of this activity - */ + /** + * All the active instances of this activity + */ std::vector m_Instances; - /** - * The current lobbies for this activity - */ + /** + * The current lobbies for this activity + */ std::vector m_Queue; - /** - * All the activity score for the players in this activity - */ + /** + * All the activity score for the players in this activity + */ std::vector m_ActivityPlayers; - /** - * LMIs for team sizes - */ - std::unordered_map m_ActivityLootMatrices; + /** + * LMIs for team sizes + */ + std::unordered_map m_ActivityLootMatrices; }; #endif // SCRIPTEDACTIVITYCOMPONENT_H diff --git a/dGame/dComponents/ShootingGalleryComponent.cpp b/dGame/dComponents/ShootingGalleryComponent.cpp index f0fac7f4..d5e12b28 100644 --- a/dGame/dComponents/ShootingGalleryComponent.cpp +++ b/dGame/dComponents/ShootingGalleryComponent.cpp @@ -2,66 +2,64 @@ #include "EntityManager.h" #include "ScriptedActivityComponent.h" -ShootingGalleryComponent::ShootingGalleryComponent(Entity *parent) : Component(parent) { +ShootingGalleryComponent::ShootingGalleryComponent(Entity* parent) : Component(parent) { } ShootingGalleryComponent::~ShootingGalleryComponent() = default; -void ShootingGalleryComponent::SetStaticParams(const StaticShootingGalleryParams ¶ms) { - m_StaticParams = params; +void ShootingGalleryComponent::SetStaticParams(const StaticShootingGalleryParams& params) { + m_StaticParams = params; } -void ShootingGalleryComponent::SetDynamicParams(const DynamicShootingGalleryParams ¶ms) { - m_DynamicParams = params; - m_Dirty = true; - EntityManager::Instance()->SerializeEntity(m_Parent); +void ShootingGalleryComponent::SetDynamicParams(const DynamicShootingGalleryParams& params) { + m_DynamicParams = params; + m_Dirty = true; + EntityManager::Instance()->SerializeEntity(m_Parent); } -void ShootingGalleryComponent::Serialize(RakNet::BitStream *outBitStream, bool isInitialUpdate, uint32_t& flags) const { - // Start ScriptedActivityComponent - outBitStream->Write(true); - if (m_CurrentPlayerID == LWOOBJID_EMPTY) { - outBitStream->Write(0); - } - else { - outBitStream->Write(1); - for (size_t i = 0; i < 10; i++) - { - outBitStream->Write(0.0f); - } - - } - // End ScriptedActivityComponent +void ShootingGalleryComponent::Serialize(RakNet::BitStream* outBitStream, bool isInitialUpdate, uint32_t& flags) const { + // Start ScriptedActivityComponent + outBitStream->Write(true); + if (m_CurrentPlayerID == LWOOBJID_EMPTY) { + outBitStream->Write(0); + } else { + outBitStream->Write(1); + for (size_t i = 0; i < 10; i++) { + outBitStream->Write(0.0f); + } - if (isInitialUpdate) { - outBitStream->Write(m_StaticParams.cameraPosition.GetX()); - outBitStream->Write(m_StaticParams.cameraPosition.GetY()); - outBitStream->Write(m_StaticParams.cameraPosition.GetZ()); + } + // End ScriptedActivityComponent - outBitStream->Write(m_StaticParams.cameraLookatPosition.GetX()); - outBitStream->Write(m_StaticParams.cameraLookatPosition.GetY()); - outBitStream->Write(m_StaticParams.cameraLookatPosition.GetZ()); - } + if (isInitialUpdate) { + outBitStream->Write(m_StaticParams.cameraPosition.GetX()); + outBitStream->Write(m_StaticParams.cameraPosition.GetY()); + outBitStream->Write(m_StaticParams.cameraPosition.GetZ()); - outBitStream->Write(m_Dirty || isInitialUpdate); - if (m_Dirty || isInitialUpdate) { - outBitStream->Write(m_DynamicParams.cannonVelocity); - outBitStream->Write(m_DynamicParams.cannonRefireRate); - outBitStream->Write(m_DynamicParams.cannonMinDistance); + outBitStream->Write(m_StaticParams.cameraLookatPosition.GetX()); + outBitStream->Write(m_StaticParams.cameraLookatPosition.GetY()); + outBitStream->Write(m_StaticParams.cameraLookatPosition.GetZ()); + } - outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetX()); - outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetY()); - outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetZ()); + outBitStream->Write(m_Dirty || isInitialUpdate); + if (m_Dirty || isInitialUpdate) { + outBitStream->Write(m_DynamicParams.cannonVelocity); + outBitStream->Write(m_DynamicParams.cannonRefireRate); + outBitStream->Write(m_DynamicParams.cannonMinDistance); - outBitStream->Write(m_DynamicParams.cannonAngle); + outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetX()); + outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetY()); + outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetZ()); - outBitStream->Write(m_DynamicParams.facing.GetX()); - outBitStream->Write(m_DynamicParams.facing.GetY()); - outBitStream->Write(m_DynamicParams.facing.GetZ()); + outBitStream->Write(m_DynamicParams.cannonAngle); - outBitStream->Write(m_CurrentPlayerID); - outBitStream->Write(m_DynamicParams.cannonTimeout); - outBitStream->Write(m_DynamicParams.cannonFOV); - } + outBitStream->Write(m_DynamicParams.facing.GetX()); + outBitStream->Write(m_DynamicParams.facing.GetY()); + outBitStream->Write(m_DynamicParams.facing.GetZ()); + + outBitStream->Write(m_CurrentPlayerID); + outBitStream->Write(m_DynamicParams.cannonTimeout); + outBitStream->Write(m_DynamicParams.cannonFOV); + } } diff --git a/dGame/dComponents/ShootingGalleryComponent.h b/dGame/dComponents/ShootingGalleryComponent.h index 323bf88f..c43f20c2 100644 --- a/dGame/dComponents/ShootingGalleryComponent.h +++ b/dGame/dComponents/ShootingGalleryComponent.h @@ -9,45 +9,45 @@ */ struct DynamicShootingGalleryParams { - /** - * The distance from the camera to the barrel - */ - Vector3 cameraBarrelOffset; + /** + * The distance from the camera to the barrel + */ + Vector3 cameraBarrelOffset; - /** - * The area the barrel is looking at - */ - Vector3 facing; + /** + * The area the barrel is looking at + */ + Vector3 facing; - /** - * The velocity of the cannonballs - */ - double_t cannonVelocity; + /** + * The velocity of the cannonballs + */ + double_t cannonVelocity; - /** - * The max firerate of the cannon - */ - double_t cannonRefireRate; + /** + * The max firerate of the cannon + */ + double_t cannonRefireRate; - /** - * The min distance the cannonballs traverse - */ - double_t cannonMinDistance; + /** + * The min distance the cannonballs traverse + */ + double_t cannonMinDistance; - /** - * The angle at which the cannon is shooting - */ - float_t cannonAngle; + /** + * The angle at which the cannon is shooting + */ + float_t cannonAngle; - /** - * The timeout between cannon shots - */ - float_t cannonTimeout; + /** + * The timeout between cannon shots + */ + float_t cannonTimeout; - /** - * The FOV while in the canon - */ - float_t cannonFOV; + /** + * The FOV while in the canon + */ + float_t cannonFOV; }; /** @@ -55,15 +55,15 @@ struct DynamicShootingGalleryParams { */ struct StaticShootingGalleryParams { - /** - * The position of the camera - */ - Vector3 cameraPosition; + /** + * The position of the camera + */ + Vector3 cameraPosition; - /** - * The position that the camera is looking at - */ - Vector3 cameraLookatPosition; + /** + * The position that the camera is looking at + */ + Vector3 cameraLookatPosition; }; /** @@ -72,66 +72,66 @@ struct StaticShootingGalleryParams { */ class ShootingGalleryComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SHOOTING_GALLERY; + static const uint32_t ComponentType = COMPONENT_TYPE_SHOOTING_GALLERY; - explicit ShootingGalleryComponent(Entity* parent); - ~ShootingGalleryComponent(); - void Serialize(RakNet::BitStream* outBitStream, bool isInitialUpdate, uint32_t& flags) const; + explicit ShootingGalleryComponent(Entity* parent); + ~ShootingGalleryComponent(); + void Serialize(RakNet::BitStream* outBitStream, bool isInitialUpdate, uint32_t& flags) const; - /** - * Returns the static params for the shooting gallery - * @return the static params for the shooting gallery - */ - const StaticShootingGalleryParams& GetStaticParams() const { return m_StaticParams; }; + /** + * Returns the static params for the shooting gallery + * @return the static params for the shooting gallery + */ + const StaticShootingGalleryParams& GetStaticParams() const { return m_StaticParams; }; - /** - * Sets the static parameters for the shooting gallery, see `StaticShootingGalleryParams` - * @param params the params to set - */ - void SetStaticParams(const StaticShootingGalleryParams& params); + /** + * Sets the static parameters for the shooting gallery, see `StaticShootingGalleryParams` + * @param params the params to set + */ + void SetStaticParams(const StaticShootingGalleryParams& params); - /** - * Returns the dynamic params for the shooting gallery - * @return the dynamic params for the shooting gallery - */ - const DynamicShootingGalleryParams& GetDynamicParams() const { return m_DynamicParams; }; + /** + * Returns the dynamic params for the shooting gallery + * @return the dynamic params for the shooting gallery + */ + const DynamicShootingGalleryParams& GetDynamicParams() const { return m_DynamicParams; }; - /** - * Sets the mutable params for the shooting gallery, see `DynamicShootingGalleryParams` - * @param params the params to set - */ - void SetDynamicParams(const DynamicShootingGalleryParams& params); + /** + * Sets the mutable params for the shooting gallery, see `DynamicShootingGalleryParams` + * @param params the params to set + */ + void SetDynamicParams(const DynamicShootingGalleryParams& params); - /** - * Sets the entity that's currently playing the shooting gallery - * @param playerID the entity to set - */ - void SetCurrentPlayerID(LWOOBJID playerID) { m_CurrentPlayerID = playerID; m_Dirty = true; }; + /** + * Sets the entity that's currently playing the shooting gallery + * @param playerID the entity to set + */ + void SetCurrentPlayerID(LWOOBJID playerID) { m_CurrentPlayerID = playerID; m_Dirty = true; }; - /** - * Returns the player that's currently playing the shooting gallery - * @return the player that's currently playing the shooting gallery - */ - LWOOBJID GetCurrentPlayerID() const { return m_CurrentPlayerID; }; + /** + * Returns the player that's currently playing the shooting gallery + * @return the player that's currently playing the shooting gallery + */ + LWOOBJID GetCurrentPlayerID() const { return m_CurrentPlayerID; }; private: - /** - * The player that's currently playing the shooting gallery - */ - LWOOBJID m_CurrentPlayerID = LWOOBJID_EMPTY; + /** + * The player that's currently playing the shooting gallery + */ + LWOOBJID m_CurrentPlayerID = LWOOBJID_EMPTY; - /** - * The static parameters for the shooting gallery, see `StaticShootingGalleryParams` - */ - StaticShootingGalleryParams m_StaticParams {}; + /** + * The static parameters for the shooting gallery, see `StaticShootingGalleryParams` + */ + StaticShootingGalleryParams m_StaticParams{}; - /** - * The dynamic params for the shooting gallery, see `DynamicShootingGalleryParams` - */ - DynamicShootingGalleryParams m_DynamicParams {}; + /** + * The dynamic params for the shooting gallery, see `DynamicShootingGalleryParams` + */ + DynamicShootingGalleryParams m_DynamicParams{}; - /** - * Whether or not the component should be serialized - */ - bool m_Dirty = false; + /** + * Whether or not the component should be serialized + */ + bool m_Dirty = false; }; diff --git a/dGame/dComponents/SimplePhysicsComponent.cpp b/dGame/dComponents/SimplePhysicsComponent.cpp index c9a42971..54a2e616 100644 --- a/dGame/dComponents/SimplePhysicsComponent.cpp +++ b/dGame/dComponents/SimplePhysicsComponent.cpp @@ -14,70 +14,65 @@ #include "Entity.h" SimplePhysicsComponent::SimplePhysicsComponent(uint32_t componentID, Entity* parent) : Component(parent) { - m_Position = m_Parent->GetDefaultPosition(); - m_Rotation = m_Parent->GetDefaultRotation(); - m_IsDirty = true; + m_Position = m_Parent->GetDefaultPosition(); + m_Rotation = m_Parent->GetDefaultRotation(); + m_IsDirty = true; - const auto& climbable_type = m_Parent->GetVar(u"climbable"); - if (climbable_type == u"wall") { - SetClimbableType(eClimbableType::CLIMBABLE_TYPE_WALL); - } else if (climbable_type == u"ladder") { - SetClimbableType(eClimbableType::CLIMBABLE_TYPE_LADDER); - } else if (climbable_type == u"wallstick") { - SetClimbableType(eClimbableType::CLIMBABLE_TYPE_WALL_STICK); - } else { - SetClimbableType(eClimbableType::CLIMBABLE_TYPE_NOT); - } + const auto& climbable_type = m_Parent->GetVar(u"climbable"); + if (climbable_type == u"wall") { + SetClimbableType(eClimbableType::CLIMBABLE_TYPE_WALL); + } else if (climbable_type == u"ladder") { + SetClimbableType(eClimbableType::CLIMBABLE_TYPE_LADDER); + } else if (climbable_type == u"wallstick") { + SetClimbableType(eClimbableType::CLIMBABLE_TYPE_WALL_STICK); + } else { + SetClimbableType(eClimbableType::CLIMBABLE_TYPE_NOT); + } } SimplePhysicsComponent::~SimplePhysicsComponent() { } void SimplePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - if (bIsInitialUpdate) { - outBitStream->Write(m_ClimbableType != eClimbableType::CLIMBABLE_TYPE_NOT); - outBitStream->Write(m_ClimbableType); - } + if (bIsInitialUpdate) { + outBitStream->Write(m_ClimbableType != eClimbableType::CLIMBABLE_TYPE_NOT); + outBitStream->Write(m_ClimbableType); + } - outBitStream->Write(m_DirtyVelocity || bIsInitialUpdate); - if (m_DirtyVelocity || bIsInitialUpdate) { - outBitStream->Write(m_Velocity); - outBitStream->Write(m_AngularVelocity); + outBitStream->Write(m_DirtyVelocity || bIsInitialUpdate); + if (m_DirtyVelocity || bIsInitialUpdate) { + outBitStream->Write(m_Velocity); + outBitStream->Write(m_AngularVelocity); - m_DirtyVelocity = false; - } + m_DirtyVelocity = false; + } - // Physics motion state - if (m_PhysicsMotionState != 0) - { - outBitStream->Write1(); - outBitStream->Write(m_PhysicsMotionState); - } - else - { - outBitStream->Write0(); - } + // Physics motion state + if (m_PhysicsMotionState != 0) { + outBitStream->Write1(); + outBitStream->Write(m_PhysicsMotionState); + } else { + outBitStream->Write0(); + } - outBitStream->Write(m_IsDirty || bIsInitialUpdate); - if (m_IsDirty || bIsInitialUpdate) { - outBitStream->Write(m_Position.x); - outBitStream->Write(m_Position.y); - outBitStream->Write(m_Position.z); - outBitStream->Write(m_Rotation.x); - outBitStream->Write(m_Rotation.y); - outBitStream->Write(m_Rotation.z); - outBitStream->Write(m_Rotation.w); + outBitStream->Write(m_IsDirty || bIsInitialUpdate); + if (m_IsDirty || bIsInitialUpdate) { + outBitStream->Write(m_Position.x); + outBitStream->Write(m_Position.y); + outBitStream->Write(m_Position.z); + outBitStream->Write(m_Rotation.x); + outBitStream->Write(m_Rotation.y); + outBitStream->Write(m_Rotation.z); + outBitStream->Write(m_Rotation.w); - m_IsDirty = false; - } + m_IsDirty = false; + } } -uint32_t SimplePhysicsComponent::GetPhysicsMotionState() const -{ - return m_PhysicsMotionState; +uint32_t SimplePhysicsComponent::GetPhysicsMotionState() const { + return m_PhysicsMotionState; } -void SimplePhysicsComponent::SetPhysicsMotionState(uint32_t value) -{ - m_PhysicsMotionState = value; +void SimplePhysicsComponent::SetPhysicsMotionState(uint32_t value) { + m_PhysicsMotionState = value; } diff --git a/dGame/dComponents/SimplePhysicsComponent.h b/dGame/dComponents/SimplePhysicsComponent.h index 49e6be5b..ebb8b124 100644 --- a/dGame/dComponents/SimplePhysicsComponent.h +++ b/dGame/dComponents/SimplePhysicsComponent.h @@ -27,72 +27,72 @@ enum class eClimbableType : int32_t { */ class SimplePhysicsComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SIMPLE_PHYSICS; + static const uint32_t ComponentType = COMPONENT_TYPE_SIMPLE_PHYSICS; SimplePhysicsComponent(uint32_t componentID, Entity* parent); - ~SimplePhysicsComponent() override; + ~SimplePhysicsComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Returns the position of this entity - * @return the position of this entity - */ - NiPoint3& GetPosition() { return m_Position; } + /** + * Returns the position of this entity + * @return the position of this entity + */ + NiPoint3& GetPosition() { return m_Position; } - /** - * Sets the position of this entity - * @param pos the position to set - */ - void SetPosition(const NiPoint3& pos) { m_Position = pos; m_IsDirty = true; } + /** + * Sets the position of this entity + * @param pos the position to set + */ + void SetPosition(const NiPoint3& pos) { m_Position = pos; m_IsDirty = true; } - /** - * Returns the rotation of this entity - * @return the rotation of this entity - */ - NiQuaternion& GetRotation() { return m_Rotation; } + /** + * Returns the rotation of this entity + * @return the rotation of this entity + */ + NiQuaternion& GetRotation() { return m_Rotation; } - /** - * Sets the rotation of this entity - * @param rot - */ - void SetRotation(const NiQuaternion& rot) { m_Rotation = rot; m_IsDirty = true; } + /** + * Sets the rotation of this entity + * @param rot + */ + void SetRotation(const NiQuaternion& rot) { m_Rotation = rot; m_IsDirty = true; } - /** - * Returns the velocity of this entity - * @return the velocity of this entity - */ - const NiPoint3& GetVelocity() { return m_Velocity; } + /** + * Returns the velocity of this entity + * @return the velocity of this entity + */ + const NiPoint3& GetVelocity() { return m_Velocity; } - /** - * Sets the velocity of this entity - * @param value the velocity to set - */ - void SetVelocity(const NiPoint3& value) { m_Velocity = value; m_DirtyVelocity = true; } + /** + * Sets the velocity of this entity + * @param value the velocity to set + */ + void SetVelocity(const NiPoint3& value) { m_Velocity = value; m_DirtyVelocity = true; } - /** - * Returns the angular velocity of this entity - * @return the angular velocity of this entity - */ - const NiPoint3& GetAngularVelocity() { return m_AngularVelocity; } + /** + * Returns the angular velocity of this entity + * @return the angular velocity of this entity + */ + const NiPoint3& GetAngularVelocity() { return m_AngularVelocity; } - /** - * Sets the angular velocity of this entity - * @param value the angular velocity to set - */ - void SetAngularVelocity(const NiPoint3& value) { m_AngularVelocity = value; m_DirtyVelocity = true; } + /** + * Sets the angular velocity of this entity + * @param value the angular velocity to set + */ + void SetAngularVelocity(const NiPoint3& value) { m_AngularVelocity = value; m_DirtyVelocity = true; } - /** - * Returns the physics motion state - * @return the physics motion state - */ - uint32_t GetPhysicsMotionState() const; + /** + * Returns the physics motion state + * @return the physics motion state + */ + uint32_t GetPhysicsMotionState() const; - /** - * Sets the physics motion state - * @param value the motion state to set - */ - void SetPhysicsMotionState(uint32_t value); + /** + * Sets the physics motion state + * @param value the motion state to set + */ + void SetPhysicsMotionState(uint32_t value); /** * Returns the ClimbableType of this entity @@ -108,45 +108,45 @@ public: private: - /** - * The current position of the entity - */ - NiPoint3 m_Position = NiPoint3::ZERO; + /** + * The current position of the entity + */ + NiPoint3 m_Position = NiPoint3::ZERO; - /** - * The current rotation of the entity - */ - NiQuaternion m_Rotation = NiQuaternion::IDENTITY; + /** + * The current rotation of the entity + */ + NiQuaternion m_Rotation = NiQuaternion::IDENTITY; - /** - * The current velocity of the entity - */ - NiPoint3 m_Velocity = NiPoint3::ZERO; + /** + * The current velocity of the entity + */ + NiPoint3 m_Velocity = NiPoint3::ZERO; - /** - * The current angular velocity of the entity - */ - NiPoint3 m_AngularVelocity = NiPoint3::ZERO; + /** + * The current angular velocity of the entity + */ + NiPoint3 m_AngularVelocity = NiPoint3::ZERO; - /** - * Whether or not the velocity has changed - */ - bool m_DirtyVelocity = true; + /** + * Whether or not the velocity has changed + */ + bool m_DirtyVelocity = true; - /** - * Whether or not the position has changed - */ - bool m_IsDirty = true; + /** + * Whether or not the position has changed + */ + bool m_IsDirty = true; - /** - * The current physics motion state - */ - uint32_t m_PhysicsMotionState = 0; + /** + * The current physics motion state + */ + uint32_t m_PhysicsMotionState = 0; - /** - * Whether or not the entity is climbable - */ - eClimbableType m_ClimbableType = eClimbableType::CLIMBABLE_TYPE_NOT; + /** + * Whether or not the entity is climbable + */ + eClimbableType m_ClimbableType = eClimbableType::CLIMBABLE_TYPE_NOT; }; #endif // SIMPLEPHYSICSCOMPONENT_H diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index 608eced6..f7e8e7d9 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -21,12 +21,10 @@ #include "BuffComponent.h" -ProjectileSyncEntry::ProjectileSyncEntry() -{ +ProjectileSyncEntry::ProjectileSyncEntry() { } -bool SkillComponent::CastPlayerSkill(const uint32_t behaviorId, const uint32_t skillUid, RakNet::BitStream* bitStream, const LWOOBJID target, uint32_t skillID) -{ +bool SkillComponent::CastPlayerSkill(const uint32_t behaviorId, const uint32_t skillUid, RakNet::BitStream* bitStream, const LWOOBJID target, uint32_t skillID) { auto* context = new BehaviorContext(this->m_Parent->GetObjectID()); context->caster = m_Parent->GetObjectID(); @@ -46,12 +44,10 @@ bool SkillComponent::CastPlayerSkill(const uint32_t behaviorId, const uint32_t s return !context->failed; } -void SkillComponent::SyncPlayerSkill(const uint32_t skillUid, const uint32_t syncId, RakNet::BitStream* bitStream) -{ +void SkillComponent::SyncPlayerSkill(const uint32_t skillUid, const uint32_t syncId, RakNet::BitStream* bitStream) { const auto index = this->m_managedBehaviors.find(skillUid); - if (index == this->m_managedBehaviors.end()) - { + if (index == this->m_managedBehaviors.end()) { Game::logger->Log("SkillComponent", "Failed to find skill with uid (%i)!", skillUid, syncId); return; @@ -63,24 +59,20 @@ void SkillComponent::SyncPlayerSkill(const uint32_t skillUid, const uint32_t syn } -void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::BitStream* bitStream, const LWOOBJID target) -{ +void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::BitStream* bitStream, const LWOOBJID target) { auto index = -1; - for (auto i = 0u; i < this->m_managedProjectiles.size(); ++i) - { + for (auto i = 0u; i < this->m_managedProjectiles.size(); ++i) { const auto& projectile = this->m_managedProjectiles.at(i); - if (projectile.id == projectileId) - { + if (projectile.id == projectileId) { index = i; break; } } - if (index == -1) - { + if (index == -1) { Game::logger->Log("SkillComponent", "Failed to find projectile id (%llu)!", projectileId); return; @@ -90,7 +82,7 @@ void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::B auto query = CDClientDatabase::CreatePreppedStmt( "SELECT behaviorID FROM SkillBehavior WHERE skillID = (SELECT skillID FROM ObjectSkills WHERE objectTemplate = ?);"); - query.bind(1, (int) sync_entry.lot); + query.bind(1, (int)sync_entry.lot); auto result = query.execQuery(); @@ -110,8 +102,7 @@ void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::B branch.isProjectile = true; - if (target != LWOOBJID_EMPTY) - { + if (target != LWOOBJID_EMPTY) { branch.target = target; } @@ -120,8 +111,7 @@ void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::B this->m_managedProjectiles.erase(this->m_managedProjectiles.begin() + index); } -void SkillComponent::RegisterPlayerProjectile(const LWOOBJID projectileId, BehaviorContext* context, const BehaviorBranchContext& branch, const LOT lot) -{ +void SkillComponent::RegisterPlayerProjectile(const LWOOBJID projectileId, BehaviorContext* context, const BehaviorBranchContext& branch, const LOT lot) { ProjectileSyncEntry entry; entry.context = context; @@ -132,50 +122,39 @@ void SkillComponent::RegisterPlayerProjectile(const LWOOBJID projectileId, Behav this->m_managedProjectiles.push_back(entry); } -void SkillComponent::Update(const float deltaTime) -{ - if (!m_Parent->HasComponent(COMPONENT_TYPE_BASE_COMBAT_AI) && m_Parent->GetLOT() != 1) - { +void SkillComponent::Update(const float deltaTime) { + if (!m_Parent->HasComponent(COMPONENT_TYPE_BASE_COMBAT_AI) && m_Parent->GetLOT() != 1) { CalculateUpdate(deltaTime); } - std::map keep {}; + std::map keep{}; - for (const auto& pair : this->m_managedBehaviors) - { + for (const auto& pair : this->m_managedBehaviors) { auto* context = pair.second; - if (context == nullptr) - { + if (context == nullptr) { continue; } - if (context->clientInitalized) - { + if (context->clientInitalized) { context->CalculateUpdate(deltaTime); - } - else - { + } else { context->Update(deltaTime); } // Cleanup old behaviors - if (context->syncEntries.empty() && context->timerEntries.empty()) - { + if (context->syncEntries.empty() && context->timerEntries.empty()) { auto any = false; - for (const auto& projectile : this->m_managedProjectiles) - { - if (projectile.context == context) - { + for (const auto& projectile : this->m_managedProjectiles) { + if (projectile.context == context) { any = true; break; } } - if (!any) - { + if (!any) { context->Reset(); delete context; @@ -192,10 +171,8 @@ void SkillComponent::Update(const float deltaTime) this->m_managedBehaviors = keep; } -void SkillComponent::Reset() -{ - for (const auto& behavior : this->m_managedBehaviors) - { +void SkillComponent::Reset() { + for (const auto& behavior : this->m_managedBehaviors) { delete behavior.second; } @@ -203,26 +180,22 @@ void SkillComponent::Reset() this->m_managedBehaviors.clear(); } -void SkillComponent::Interrupt() -{ +void SkillComponent::Interrupt() { if (m_Parent->IsPlayer()) return; auto* combat = m_Parent->GetComponent(); - if (combat != nullptr && combat->GetStunImmune()) - { + if (combat != nullptr && combat->GetStunImmune()) { return; } - for (const auto& behavior : this->m_managedBehaviors) - { + for (const auto& behavior : this->m_managedBehaviors) { behavior.second->Interrupt(); } } void SkillComponent::RegisterCalculatedProjectile(const LWOOBJID projectileId, BehaviorContext* context, const BehaviorBranchContext& branch, const LOT lot, const float maxTime, - const NiPoint3& startPosition, const NiPoint3& velocity, const bool trackTarget, const float trackRadius) -{ + const NiPoint3& startPosition, const NiPoint3& velocity, const bool trackTarget, const float trackRadius) { ProjectileSyncEntry entry; entry.context = context; @@ -242,8 +215,7 @@ void SkillComponent::RegisterCalculatedProjectile(const LWOOBJID projectileId, B } -SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, const uint32_t behaviorId, const LWOOBJID target, const bool ignoreTarget, const bool clientInitalized, const LWOOBJID originatorOverride) -{ +SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, const uint32_t behaviorId, const LWOOBJID target, const bool ignoreTarget, const bool clientInitalized, const LWOOBJID originatorOverride) { auto* bitStream = new RakNet::BitStream(); auto* behavior = Behavior::CreateBehavior(behaviorId); @@ -256,14 +228,13 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c context->foundTarget = target != LWOOBJID_EMPTY || ignoreTarget || clientInitalized; - behavior->Calculate(context, bitStream, { target, 0}); + behavior->Calculate(context, bitStream, { target, 0 }); for (auto* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnSkillCast(m_Parent, skillId); + script->OnSkillCast(m_Parent, skillId); } - if (!context->foundTarget) - { + if (!context->foundTarget) { delete bitStream; delete context; @@ -273,8 +244,7 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c this->m_managedBehaviors.insert_or_assign(context->skillUId, context); - if (!clientInitalized) - { + if (!clientInitalized) { // Echo start skill GameMessages::EchoStartSkill start; @@ -285,8 +255,7 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c auto* originator = EntityManager::Instance()->GetEntity(context->originator); - if (originator != nullptr) - { + if (originator != nullptr) { start.originatorRot = originator->GetRotation(); } //start.optionalTargetID = target; @@ -311,23 +280,19 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c return { true, context->skillTime }; } -void SkillComponent::CalculateUpdate(const float deltaTime) -{ - if (this->m_managedBehaviors.empty()) - return; +void SkillComponent::CalculateUpdate(const float deltaTime) { + if (this->m_managedBehaviors.empty()) + return; - for (const auto& managedBehavior : this->m_managedBehaviors) - { - if (managedBehavior.second == nullptr) - { + for (const auto& managedBehavior : this->m_managedBehaviors) { + if (managedBehavior.second == nullptr) { continue; } managedBehavior.second->CalculateUpdate(deltaTime); } - for (auto& managedProjectile : this->m_managedProjectiles) - { + for (auto& managedProjectile : this->m_managedProjectiles) { auto entry = managedProjectile; if (!entry.calculation) continue; @@ -336,8 +301,7 @@ void SkillComponent::CalculateUpdate(const float deltaTime) auto* origin = EntityManager::Instance()->GetEntity(entry.context->originator); - if (origin == nullptr) - { + if (origin == nullptr) { continue; } @@ -345,8 +309,7 @@ void SkillComponent::CalculateUpdate(const float deltaTime) const auto position = entry.startPosition + (entry.velocity * entry.time); - for (const auto& targetId : targets) - { + for (const auto& targetId : targets) { auto* target = EntityManager::Instance()->GetEntity(targetId); const auto targetPosition = target->GetPosition(); @@ -355,8 +318,7 @@ void SkillComponent::CalculateUpdate(const float deltaTime) const auto distance = Vector3::DistanceSquared(targetPosition, closestPoint); - if (distance > 3 * 3) - { + if (distance > 3 * 3) { /* if (entry.TrackTarget && distance <= entry.TrackRadius) { @@ -404,12 +366,9 @@ void SkillComponent::CalculateUpdate(const float deltaTime) std::vector valid; - for (auto& entry : this->m_managedProjectiles) - { - if (entry.calculation) - { - if (entry.time >= entry.maxTime) - { + for (auto& entry : this->m_managedProjectiles) { + if (entry.calculation) { + if (entry.time >= entry.maxTime) { entry.branchContext.target = LWOOBJID_EMPTY; SyncProjectileCalculation(entry); @@ -425,13 +384,11 @@ void SkillComponent::CalculateUpdate(const float deltaTime) } -void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) const -{ +void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) const { auto* other = EntityManager::Instance()->GetEntity(entry.branchContext.target); if (other == nullptr) { - if (entry.branchContext.target != LWOOBJID_EMPTY) - { + if (entry.branchContext.target != LWOOBJID_EMPTY) { Game::logger->Log("SkillComponent", "Invalid projectile target (%llu)!", entry.branchContext.target); } @@ -440,7 +397,7 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) auto query = CDClientDatabase::CreatePreppedStmt( "SELECT behaviorID FROM SkillBehavior WHERE skillID = (SELECT skillID FROM ObjectSkills WHERE objectTemplate = ?);"); - query.bind(1, (int) entry.lot); + query.bind(1, (int)entry.lot); auto result = query.execQuery(); if (result.eof()) { @@ -461,7 +418,7 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) GameMessages::DoClientProjectileImpact projectileImpact; - projectileImpact.sBitStream.assign((char*) bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); + projectileImpact.sBitStream.assign((char*)bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); projectileImpact.i64OwnerID = this->m_Parent->GetObjectID(); projectileImpact.i64OrgID = entry.id; projectileImpact.i64TargetID = entry.branchContext.target; @@ -479,8 +436,7 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) delete bitStream; } -void SkillComponent::HandleUnmanaged(const uint32_t behaviorId, const LWOOBJID target, LWOOBJID source) -{ +void SkillComponent::HandleUnmanaged(const uint32_t behaviorId, const LWOOBJID target, LWOOBJID source) { auto* context = new BehaviorContext(source); context->unmanaged = true; @@ -497,8 +453,7 @@ void SkillComponent::HandleUnmanaged(const uint32_t behaviorId, const LWOOBJID t delete context; } -void SkillComponent::HandleUnCast(const uint32_t behaviorId, const LWOOBJID target) -{ +void SkillComponent::HandleUnCast(const uint32_t behaviorId, const LWOOBJID target) { auto* context = new BehaviorContext(target); context->caster = target; @@ -510,25 +465,22 @@ void SkillComponent::HandleUnCast(const uint32_t behaviorId, const LWOOBJID targ delete context; } -SkillComponent::SkillComponent(Entity* parent) : Component(parent) -{ +SkillComponent::SkillComponent(Entity* parent) : Component(parent) { this->m_skillUid = 0; } -SkillComponent::~SkillComponent() -{ +SkillComponent::~SkillComponent() { Reset(); } void SkillComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - if (bIsInitialUpdate) outBitStream->Write0(); + if (bIsInitialUpdate) outBitStream->Write0(); } /// /// Get a unique skill ID for syncing behaviors to the client /// /// Unique skill ID -uint32_t SkillComponent::GetUniqueSkillId() -{ +uint32_t SkillComponent::GetUniqueSkillId() { return ++this->m_skillUid; } diff --git a/dGame/dComponents/SkillComponent.h b/dGame/dComponents/SkillComponent.h index ad2449c3..f43276f1 100644 --- a/dGame/dComponents/SkillComponent.h +++ b/dGame/dComponents/SkillComponent.h @@ -15,186 +15,186 @@ #include "dLogger.h" struct ProjectileSyncEntry { - LWOOBJID id = LWOOBJID_EMPTY; + LWOOBJID id = LWOOBJID_EMPTY; - bool calculation = false; + bool calculation = false; - mutable float time = 0; + mutable float time = 0; - float maxTime = 0; + float maxTime = 0; - NiPoint3 startPosition{}; + NiPoint3 startPosition{}; - NiPoint3 lastPosition{}; + NiPoint3 lastPosition{}; - NiPoint3 velocity{}; + NiPoint3 velocity{}; - bool trackTarget = false; + bool trackTarget = false; - float trackRadius = 0; + float trackRadius = 0; - BehaviorContext* context = nullptr; + BehaviorContext* context = nullptr; - LOT lot = LOT_NULL; + LOT lot = LOT_NULL; - BehaviorBranchContext branchContext{0, 0}; + BehaviorBranchContext branchContext{ 0, 0 }; - explicit ProjectileSyncEntry(); + explicit ProjectileSyncEntry(); }; struct SkillExecutionResult { - bool success; + bool success; - float skillTime; + float skillTime; }; /** * The SkillComponent of an entity. This manages both player and AI skills, such as attacks and consumables. * There are two sets of skill methods: one for player skills and one for server-side calculations. - * + * * Skills are a built up by a tree of behaviors. See dGame/dBehaviors/ for a list of behaviors. - * + * * This system is very conveluted and still has a lot of unknowns. */ class SkillComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SKILL; + static const uint32_t ComponentType = COMPONENT_TYPE_SKILL; - explicit SkillComponent(Entity* parent); - ~SkillComponent() override; + explicit SkillComponent(Entity* parent); + ~SkillComponent() override; - static void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + static void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Computes skill updates. Invokes CalculateUpdate. - */ - void Update(float deltaTime) override; + /** + * Computes skill updates. Invokes CalculateUpdate. + */ + void Update(float deltaTime) override; - /** - * Computes server-side skill updates. - */ - void CalculateUpdate(float deltaTime); + /** + * Computes server-side skill updates. + */ + void CalculateUpdate(float deltaTime); - /** - * Resets all skills, projectiles, and other calculations. - */ - void Reset(); + /** + * Resets all skills, projectiles, and other calculations. + */ + void Reset(); - /** - * Interrupts active skills. - */ - void Interrupt(); + /** + * Interrupts active skills. + */ + void Interrupt(); - /** - * Starts a player skill. Should only be called when the server receives a start skill message from the client. - * @param behaviorId the root behavior ID of the skill - * @param skillUid the unique ID of the skill given by the client - * @param bitStream the bitSteam given by the client to determine the behavior path - * @param target the explicit target of the skill - */ - bool CastPlayerSkill(uint32_t behaviorId, uint32_t skillUid, RakNet::BitStream* bitStream, LWOOBJID target, uint32_t skillID = 0); + /** + * Starts a player skill. Should only be called when the server receives a start skill message from the client. + * @param behaviorId the root behavior ID of the skill + * @param skillUid the unique ID of the skill given by the client + * @param bitStream the bitSteam given by the client to determine the behavior path + * @param target the explicit target of the skill + */ + bool CastPlayerSkill(uint32_t behaviorId, uint32_t skillUid, RakNet::BitStream* bitStream, LWOOBJID target, uint32_t skillID = 0); - /** - * Continues a player skill. Should only be called when the server receives a sync message from the client. - * @param skillUid the unique ID of the skill given by the client - * @param syncId the unique sync ID of the skill given by the client - * @param bitStream the bitSteam given by the client to determine the behavior path - */ - void SyncPlayerSkill(uint32_t skillUid, uint32_t syncId, RakNet::BitStream* bitStream); - - /** - * Continues a player projectile calculation. Should only be called when the server receives a projectile sync message from the client. - * @param projectileId the unique ID of the projectile given by the client - * @param bitStream the bitSteam given by the client to determine the behavior path - * @param target the explicit target of the target - */ - void SyncPlayerProjectile(LWOOBJID projectileId, RakNet::BitStream* bitStream, LWOOBJID target); + /** + * Continues a player skill. Should only be called when the server receives a sync message from the client. + * @param skillUid the unique ID of the skill given by the client + * @param syncId the unique sync ID of the skill given by the client + * @param bitStream the bitSteam given by the client to determine the behavior path + */ + void SyncPlayerSkill(uint32_t skillUid, uint32_t syncId, RakNet::BitStream* bitStream); - /** - * Registers a player projectile. Should only be called when the server is computing a player projectile. - * @param projectileId the unique ID of the projectile given by the client - * @param context the current behavior context of the active skill - * @param branch the current behavior branch context of the active skill - * @param lot the LOT of the projectile - */ - void RegisterPlayerProjectile(LWOOBJID projectileId, BehaviorContext* context, const BehaviorBranchContext& branch, LOT lot); + /** + * Continues a player projectile calculation. Should only be called when the server receives a projectile sync message from the client. + * @param projectileId the unique ID of the projectile given by the client + * @param bitStream the bitSteam given by the client to determine the behavior path + * @param target the explicit target of the target + */ + void SyncPlayerProjectile(LWOOBJID projectileId, RakNet::BitStream* bitStream, LWOOBJID target); - /** - * Initializes a server-side skill calculation. - * @param skillId the skill ID - * @param behaviorId the root behavior ID of the skill - * @param target the explicit target of the skill - * @param ignoreTarget continue the skill calculation even if the target is invalid or no target is found - * @param clientInitalized indicates if the skill calculation was initiated by a client skill, ignores some checks - * @param originatorOverride an override for the originator of the skill calculation - * @return the result of the skill calculation - */ - SkillExecutionResult CalculateBehavior(uint32_t skillId, uint32_t behaviorId, LWOOBJID target, bool ignoreTarget = false, bool clientInitalized = false, LWOOBJID originatorOverride = LWOOBJID_EMPTY); + /** + * Registers a player projectile. Should only be called when the server is computing a player projectile. + * @param projectileId the unique ID of the projectile given by the client + * @param context the current behavior context of the active skill + * @param branch the current behavior branch context of the active skill + * @param lot the LOT of the projectile + */ + void RegisterPlayerProjectile(LWOOBJID projectileId, BehaviorContext* context, const BehaviorBranchContext& branch, LOT lot); - /** - * Register a server-side projectile. - * @param projectileId the unique ID of the projectile - * @param context the current behavior context of the active skill - * @param branch the current behavior branch context of the active skill - * @param lot the LOT of the projectile - * @param maxTime the maximum travel time of the projectile - * @param startPosition the start position of the projectile - * @param velocity the velocity of the projectile - * @param trackTarget whether the projectile should track the target - * @param trackRadius the radius of the tracking circle - */ - void RegisterCalculatedProjectile( - LWOOBJID projectileId, - BehaviorContext* context, - const BehaviorBranchContext& branch, - LOT lot, - const float maxTime, - const NiPoint3& startPosition, - const NiPoint3& velocity, - bool trackTarget, - float TrackRadius); + /** + * Initializes a server-side skill calculation. + * @param skillId the skill ID + * @param behaviorId the root behavior ID of the skill + * @param target the explicit target of the skill + * @param ignoreTarget continue the skill calculation even if the target is invalid or no target is found + * @param clientInitalized indicates if the skill calculation was initiated by a client skill, ignores some checks + * @param originatorOverride an override for the originator of the skill calculation + * @return the result of the skill calculation + */ + SkillExecutionResult CalculateBehavior(uint32_t skillId, uint32_t behaviorId, LWOOBJID target, bool ignoreTarget = false, bool clientInitalized = false, LWOOBJID originatorOverride = LWOOBJID_EMPTY); - /** - * Computes a server-side skill calculation without an associated entity. - * @param behaviorId the root behavior ID of the skill - * @param target the explicit target of the skill - * @param source the explicit source of the skill - */ - static void HandleUnmanaged(uint32_t behaviorId, LWOOBJID target, LWOOBJID source = LWOOBJID_EMPTY); + /** + * Register a server-side projectile. + * @param projectileId the unique ID of the projectile + * @param context the current behavior context of the active skill + * @param branch the current behavior branch context of the active skill + * @param lot the LOT of the projectile + * @param maxTime the maximum travel time of the projectile + * @param startPosition the start position of the projectile + * @param velocity the velocity of the projectile + * @param trackTarget whether the projectile should track the target + * @param trackRadius the radius of the tracking circle + */ + void RegisterCalculatedProjectile( + LWOOBJID projectileId, + BehaviorContext* context, + const BehaviorBranchContext& branch, + LOT lot, + const float maxTime, + const NiPoint3& startPosition, + const NiPoint3& velocity, + bool trackTarget, + float TrackRadius); - /** - * Computes a server-side skill uncast calculation without an associated entity. - * @param behaviorId the root behavior ID of the skill - * @param target the explicit target of the skill - */ - static void HandleUnCast(uint32_t behaviorId, LWOOBJID target); + /** + * Computes a server-side skill calculation without an associated entity. + * @param behaviorId the root behavior ID of the skill + * @param target the explicit target of the skill + * @param source the explicit source of the skill + */ + static void HandleUnmanaged(uint32_t behaviorId, LWOOBJID target, LWOOBJID source = LWOOBJID_EMPTY); - /** - * @returns a unique ID for the next skill calculation - */ - uint32_t GetUniqueSkillId(); + /** + * Computes a server-side skill uncast calculation without an associated entity. + * @param behaviorId the root behavior ID of the skill + * @param target the explicit target of the skill + */ + static void HandleUnCast(uint32_t behaviorId, LWOOBJID target); + + /** + * @returns a unique ID for the next skill calculation + */ + uint32_t GetUniqueSkillId(); private: - /** - * All of the active skills mapped by their unique ID. - */ - std::map m_managedBehaviors; + /** + * All of the active skills mapped by their unique ID. + */ + std::map m_managedBehaviors; - /** - * All active projectiles. - */ - std::vector m_managedProjectiles; + /** + * All active projectiles. + */ + std::vector m_managedProjectiles; - /** - * Unique ID counter. - */ - uint32_t m_skillUid; + /** + * Unique ID counter. + */ + uint32_t m_skillUid; - /** - * Sync a server-side projectile calculation. - * @param entry the projectile information - */ - void SyncProjectileCalculation(const ProjectileSyncEntry& entry) const; + /** + * Sync a server-side projectile calculation. + * @param entry the projectile information + */ + void SyncProjectileCalculation(const ProjectileSyncEntry& entry) const; }; #endif // SKILLCOMPONENT_H diff --git a/dGame/dComponents/SoundTriggerComponent.cpp b/dGame/dComponents/SoundTriggerComponent.cpp index 9714eca7..be62beee 100644 --- a/dGame/dComponents/SoundTriggerComponent.cpp +++ b/dGame/dComponents/SoundTriggerComponent.cpp @@ -3,91 +3,91 @@ #include "Game.h" SoundTriggerComponent::SoundTriggerComponent(Entity* parent) : Component(parent) { - const auto musicCueName = parent->GetVar(u"NDAudioMusicCue_Name"); - const auto musicCueBoredomTime = parent->GetVar(u"NDAudioMusicCue_BoredomTime"); + const auto musicCueName = parent->GetVar(u"NDAudioMusicCue_Name"); + const auto musicCueBoredomTime = parent->GetVar(u"NDAudioMusicCue_BoredomTime"); - this->musicCues.push_back({ - musicCueName, - 1, - musicCueBoredomTime - }); + this->musicCues.push_back({ + musicCueName, + 1, + musicCueBoredomTime + }); - const auto mixerName = parent->GetVar(u"NDAudioMixerProgram_Name"); - this->mixerPrograms.push_back(mixerName); + const auto mixerName = parent->GetVar(u"NDAudioMixerProgram_Name"); + this->mixerPrograms.push_back(mixerName); - const auto guid2String = parent->GetVar(u"NDAudioEventGUID2"); - if (!guid2String.empty()) { - this->guids.emplace_back(guid2String); - } + const auto guid2String = parent->GetVar(u"NDAudioEventGUID2"); + if (!guid2String.empty()) { + this->guids.emplace_back(guid2String); + } } SoundTriggerComponent::~SoundTriggerComponent() = default; -void SoundTriggerComponent::Serialize(RakNet::BitStream *outBitStream, bool bIsInitialUpdate, unsigned int &flags) { - if (bIsInitialUpdate) - dirty = true; +void SoundTriggerComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { + if (bIsInitialUpdate) + dirty = true; - outBitStream->Write(dirty); + outBitStream->Write(dirty); - if (dirty) { - outBitStream->Write(this->musicCues.size()); - for (const auto& musicCue : this->musicCues) { - outBitStream->Write(musicCue.name.size()); - outBitStream->Write(musicCue.name.c_str(), musicCue.name.size()); - outBitStream->Write(musicCue.result); - outBitStream->Write(musicCue.boredomTime); - } + if (dirty) { + outBitStream->Write(this->musicCues.size()); + for (const auto& musicCue : this->musicCues) { + outBitStream->Write(musicCue.name.size()); + outBitStream->Write(musicCue.name.c_str(), musicCue.name.size()); + outBitStream->Write(musicCue.result); + outBitStream->Write(musicCue.boredomTime); + } - // Unknown part - outBitStream->Write(0); + // Unknown part + outBitStream->Write(0); - // GUID part - outBitStream->Write(this->guids.size()); + // GUID part + outBitStream->Write(this->guids.size()); - for (const auto guid : this->guids) { - outBitStream->Write(guid.GetData1()); - outBitStream->Write(guid.GetData2()); - outBitStream->Write(guid.GetData3()); - for (const auto& guidSubPart : guid.GetData4()) { - outBitStream->Write(guidSubPart); - } - outBitStream->Write(1); // Unknown - } + for (const auto guid : this->guids) { + outBitStream->Write(guid.GetData1()); + outBitStream->Write(guid.GetData2()); + outBitStream->Write(guid.GetData3()); + for (const auto& guidSubPart : guid.GetData4()) { + outBitStream->Write(guidSubPart); + } + outBitStream->Write(1); // Unknown + } - // Mixer program part - outBitStream->Write(this->mixerPrograms.size()); - for (const auto& mixerProgram : mixerPrograms) { - outBitStream->Write(mixerProgram.size()); - outBitStream->Write(mixerProgram.c_str(), mixerProgram.size()); - outBitStream->Write(1); // Unknown - } + // Mixer program part + outBitStream->Write(this->mixerPrograms.size()); + for (const auto& mixerProgram : mixerPrograms) { + outBitStream->Write(mixerProgram.size()); + outBitStream->Write(mixerProgram.c_str(), mixerProgram.size()); + outBitStream->Write(1); // Unknown + } - dirty = false; - } + dirty = false; + } } void SoundTriggerComponent::ActivateMusicCue(const std::string& name) { - if (std::find_if(this->musicCues.begin(), this->musicCues.end(), [name](const MusicCue& musicCue) { - return musicCue.name == name; - }) == this->musicCues.end()) { - this->musicCues.push_back({ - name, - 1, - -1.0f - }); - dirty = true; - EntityManager::Instance()->SerializeEntity(m_Parent); - } + if (std::find_if(this->musicCues.begin(), this->musicCues.end(), [name](const MusicCue& musicCue) { + return musicCue.name == name; + }) == this->musicCues.end()) { + this->musicCues.push_back({ + name, + 1, + -1.0f + }); + dirty = true; + EntityManager::Instance()->SerializeEntity(m_Parent); + } } void SoundTriggerComponent::DeactivateMusicCue(const std::string& name) { - const auto musicCue = std::find_if(this->musicCues.begin(), this->musicCues.end(), [name](const MusicCue& musicCue) { - return musicCue.name == name; - }); + const auto musicCue = std::find_if(this->musicCues.begin(), this->musicCues.end(), [name](const MusicCue& musicCue) { + return musicCue.name == name; + }); - if (musicCue != this->musicCues.end()) { - this->musicCues.erase(musicCue); - dirty = true; - EntityManager::Instance()->SerializeEntity(m_Parent); - } + if (musicCue != this->musicCues.end()) { + this->musicCues.erase(musicCue); + dirty = true; + EntityManager::Instance()->SerializeEntity(m_Parent); + } } diff --git a/dGame/dComponents/SoundTriggerComponent.h b/dGame/dComponents/SoundTriggerComponent.h index 6f16a0dd..e1178150 100644 --- a/dGame/dComponents/SoundTriggerComponent.h +++ b/dGame/dComponents/SoundTriggerComponent.h @@ -8,9 +8,9 @@ * Music that should be played by the client */ struct MusicCue { - std::string name; - uint32_t result; - float boredomTime; + std::string name; + uint32_t result; + float boredomTime; }; /** @@ -19,40 +19,40 @@ struct MusicCue { */ class SoundTriggerComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SOUND_TRIGGER; + static const uint32_t ComponentType = COMPONENT_TYPE_SOUND_TRIGGER; - explicit SoundTriggerComponent(Entity* parent); - ~SoundTriggerComponent() override; + explicit SoundTriggerComponent(Entity* parent); + ~SoundTriggerComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - /** - * Activates a music cue, making it played by any client in range - * @param name the name of the music to play - */ - void ActivateMusicCue(const std::string& name); + /** + * Activates a music cue, making it played by any client in range + * @param name the name of the music to play + */ + void ActivateMusicCue(const std::string& name); - /** - * Deactivates a music cue (if active) - * @param name name of the music to deactivate - */ - void DeactivateMusicCue(const std::string& name); + /** + * Deactivates a music cue (if active) + * @param name name of the music to deactivate + */ + void DeactivateMusicCue(const std::string& name); private: - /** - * Currently active cues - */ - std::vector musicCues = {}; + /** + * Currently active cues + */ + std::vector musicCues = {}; - /** - * Currently active mixer programs - */ - std::vector mixerPrograms = {}; + /** + * Currently active mixer programs + */ + std::vector mixerPrograms = {}; - /** - * GUID found in the LDF - */ - std::vector guids = {}; - bool dirty = false; + /** + * GUID found in the LDF + */ + std::vector guids = {}; + bool dirty = false; }; diff --git a/dGame/dComponents/SwitchComponent.cpp b/dGame/dComponents/SwitchComponent.cpp index fb694e30..2263a866 100644 --- a/dGame/dComponents/SwitchComponent.cpp +++ b/dGame/dComponents/SwitchComponent.cpp @@ -7,15 +7,14 @@ SwitchComponent::SwitchComponent(Entity* parent) : Component(parent) { m_Active = false; m_ResetTime = m_Parent->GetVarAs(u"switch_reset_time"); - + m_Rebuild = m_Parent->GetComponent(); } SwitchComponent::~SwitchComponent() { const auto& iterator = std::find(petSwitches.begin(), petSwitches.end(), this); - if (iterator != petSwitches.end()) - { + if (iterator != petSwitches.end()) { petSwitches.erase(iterator); } } @@ -27,14 +26,12 @@ void SwitchComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitial void SwitchComponent::SetActive(bool active) { m_Active = active; - if (m_PetBouncer != nullptr) - { + if (m_PetBouncer != nullptr) { m_PetBouncer->SetPetBouncerEnabled(active); } } -bool SwitchComponent::GetActive() const -{ +bool SwitchComponent::GetActive() const { return m_Active; } @@ -49,85 +46,71 @@ void SwitchComponent::EntityEnter(Entity* entity) { const auto grpName = m_Parent->GetVarAsString(u"grp_name"); - if (!grpName.empty()) - { + if (!grpName.empty()) { const auto entities = EntityManager::Instance()->GetEntitiesInGroup(grpName); - for (auto* entity : entities) - { + for (auto* entity : entities) { entity->OnFireEventServerSide(entity, "OnActivated"); } } m_Timer = m_ResetTime; - if (m_PetBouncer != nullptr) - { + if (m_PetBouncer != nullptr) { GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), 2602, u"pettriggeractive", "BounceEffect", LWOOBJID_EMPTY, 1, 1, true); GameMessages::SendPlayAnimation(m_Parent, u"engaged", 0, 1); m_PetBouncer->SetPetBouncerEnabled(true); - } - else - { + } else { EntityManager::Instance()->SerializeEntity(m_Parent); } - + } } void SwitchComponent::EntityLeave(Entity* entity) { - + } void SwitchComponent::Update(float deltaTime) { if (m_Active) { m_Timer -= deltaTime; - + if (m_Timer <= 0.0f) { m_Active = false; if (!m_Parent) return; m_Parent->TriggerEvent("OnDectivated"); - + const auto grpName = m_Parent->GetVarAsString(u"grp_name"); - if (!grpName.empty()) - { + if (!grpName.empty()) { const auto entities = EntityManager::Instance()->GetEntitiesInGroup(grpName); - for (auto* entity : entities) - { + for (auto* entity : entities) { entity->OnFireEventServerSide(entity, "OnDectivated"); } } - if (m_PetBouncer != nullptr) - { + if (m_PetBouncer != nullptr) { m_PetBouncer->SetPetBouncerEnabled(false); - } - else - { + } else { EntityManager::Instance()->SerializeEntity(m_Parent); } } } } -Entity* SwitchComponent::GetParentEntity() const -{ +Entity* SwitchComponent::GetParentEntity() const { return m_Parent; } -SwitchComponent* SwitchComponent::GetClosestSwitch(NiPoint3 position) -{ +SwitchComponent* SwitchComponent::GetClosestSwitch(NiPoint3 position) { float closestDistance = 0; SwitchComponent* closest = nullptr; - for (SwitchComponent* petSwitch : petSwitches) - { + for (SwitchComponent* petSwitch : petSwitches) { float distance = Vector3::DistanceSquared(petSwitch->m_Parent->GetPosition(), position); - - if (closest == nullptr || distance < closestDistance) - { + + if (closest == nullptr || distance < closestDistance) { closestDistance = distance; closest = petSwitch; } @@ -137,18 +120,15 @@ SwitchComponent* SwitchComponent::GetClosestSwitch(NiPoint3 position) } -void SwitchComponent::SetPetBouncer(BouncerComponent* value) -{ +void SwitchComponent::SetPetBouncer(BouncerComponent* value) { m_PetBouncer = value; - - if (value != nullptr) - { + + if (value != nullptr) { m_PetBouncer->SetPetEnabled(true); petSwitches.push_back(this); } } -BouncerComponent* SwitchComponent::GetPetBouncer() const -{ +BouncerComponent* SwitchComponent::GetPetBouncer() const { return m_PetBouncer; } diff --git a/dGame/dComponents/SwitchComponent.h b/dGame/dComponents/SwitchComponent.h index c7ff04c2..ea5955d8 100644 --- a/dGame/dComponents/SwitchComponent.h +++ b/dGame/dComponents/SwitchComponent.h @@ -16,12 +16,12 @@ class SwitchComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_SWITCH; - + SwitchComponent(Entity* parent); ~SwitchComponent() override; void Update(float deltaTime) override; - + Entity* GetParentEntity() const; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); diff --git a/dGame/dComponents/VehiclePhysicsComponent.cpp b/dGame/dComponents/VehiclePhysicsComponent.cpp index dc6dcf1a..bf6a3bb7 100644 --- a/dGame/dComponents/VehiclePhysicsComponent.cpp +++ b/dGame/dComponents/VehiclePhysicsComponent.cpp @@ -1,8 +1,7 @@ #include "VehiclePhysicsComponent.h" #include "EntityManager.h" -VehiclePhysicsComponent::VehiclePhysicsComponent(Entity* parent) : Component(parent) -{ +VehiclePhysicsComponent::VehiclePhysicsComponent(Entity* parent) : Component(parent) { m_Position = NiPoint3::ZERO; m_Rotation = NiQuaternion::IDENTITY; m_Velocity = NiPoint3::ZERO; @@ -14,119 +13,99 @@ VehiclePhysicsComponent::VehiclePhysicsComponent(Entity* parent) : Component(par m_DirtyAngularVelocity = true; } -VehiclePhysicsComponent::~VehiclePhysicsComponent() -{ - +VehiclePhysicsComponent::~VehiclePhysicsComponent() { + } -void VehiclePhysicsComponent::SetPosition(const NiPoint3& pos) -{ - m_Position = pos; +void VehiclePhysicsComponent::SetPosition(const NiPoint3& pos) { + m_Position = pos; } -void VehiclePhysicsComponent::SetRotation(const NiQuaternion& rot) -{ +void VehiclePhysicsComponent::SetRotation(const NiQuaternion& rot) { m_DirtyPosition = true; - m_Rotation = rot; + m_Rotation = rot; } -void VehiclePhysicsComponent::SetVelocity(const NiPoint3& vel) -{ +void VehiclePhysicsComponent::SetVelocity(const NiPoint3& vel) { m_DirtyPosition = true; - m_Velocity = vel; + m_Velocity = vel; } -void VehiclePhysicsComponent::SetAngularVelocity(const NiPoint3& vel) -{ +void VehiclePhysicsComponent::SetAngularVelocity(const NiPoint3& vel) { m_DirtyPosition = true; - m_AngularVelocity = vel; + m_AngularVelocity = vel; } -void VehiclePhysicsComponent::SetIsOnGround(bool val) -{ +void VehiclePhysicsComponent::SetIsOnGround(bool val) { m_DirtyPosition = true; - m_IsOnGround = val; + m_IsOnGround = val; } -void VehiclePhysicsComponent::SetIsOnRail(bool val) -{ +void VehiclePhysicsComponent::SetIsOnRail(bool val) { m_DirtyPosition = true; - m_IsOnRail = val; + m_IsOnRail = val; } -void VehiclePhysicsComponent::SetDirtyPosition(bool val) -{ - m_DirtyPosition = val; +void VehiclePhysicsComponent::SetDirtyPosition(bool val) { + m_DirtyPosition = val; } -void VehiclePhysicsComponent::SetDirtyVelocity(bool val) -{ - m_DirtyVelocity = val; +void VehiclePhysicsComponent::SetDirtyVelocity(bool val) { + m_DirtyVelocity = val; } -void VehiclePhysicsComponent::SetDirtyAngularVelocity(bool val) -{ - m_DirtyAngularVelocity = val; +void VehiclePhysicsComponent::SetDirtyAngularVelocity(bool val) { + m_DirtyAngularVelocity = val; } -void VehiclePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) -{ - outBitStream->Write(bIsInitialUpdate || m_DirtyPosition); +void VehiclePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { + outBitStream->Write(bIsInitialUpdate || m_DirtyPosition); - if (bIsInitialUpdate || m_DirtyPosition) - { - outBitStream->Write(m_Position); - - outBitStream->Write(m_Rotation); + if (bIsInitialUpdate || m_DirtyPosition) { + outBitStream->Write(m_Position); - outBitStream->Write(m_IsOnGround); - outBitStream->Write(m_IsOnRail); + outBitStream->Write(m_Rotation); - outBitStream->Write(bIsInitialUpdate || m_DirtyVelocity); + outBitStream->Write(m_IsOnGround); + outBitStream->Write(m_IsOnRail); - if (bIsInitialUpdate || m_DirtyVelocity) - { - outBitStream->Write(m_Velocity); - } + outBitStream->Write(bIsInitialUpdate || m_DirtyVelocity); - outBitStream->Write(bIsInitialUpdate || m_DirtyAngularVelocity); + if (bIsInitialUpdate || m_DirtyVelocity) { + outBitStream->Write(m_Velocity); + } - if (bIsInitialUpdate || m_DirtyAngularVelocity) - { - outBitStream->Write(m_AngularVelocity); - } + outBitStream->Write(bIsInitialUpdate || m_DirtyAngularVelocity); - outBitStream->Write0(); + if (bIsInitialUpdate || m_DirtyAngularVelocity) { + outBitStream->Write(m_AngularVelocity); + } + + outBitStream->Write0(); outBitStream->Write0(); outBitStream->Write(0.0f); - if (!bIsInitialUpdate) - { - outBitStream->Write0(); - } - } + if (!bIsInitialUpdate) { + outBitStream->Write0(); + } + } - if (bIsInitialUpdate) - { - outBitStream->Write(5); - outBitStream->Write1(); - } + if (bIsInitialUpdate) { + outBitStream->Write(5); + outBitStream->Write1(); + } - outBitStream->Write0(); + outBitStream->Write0(); } -void VehiclePhysicsComponent::Update(float deltaTime) -{ - if (m_SoftUpdate > 5) - { - EntityManager::Instance()->SerializeEntity(m_Parent); +void VehiclePhysicsComponent::Update(float deltaTime) { + if (m_SoftUpdate > 5) { + EntityManager::Instance()->SerializeEntity(m_Parent); - m_SoftUpdate = 0; - } - else - { - m_SoftUpdate += deltaTime; - } + m_SoftUpdate = 0; + } else { + m_SoftUpdate += deltaTime; + } } diff --git a/dGame/dComponents/VehiclePhysicsComponent.h b/dGame/dComponents/VehiclePhysicsComponent.h index de2e6b82..f5ab1917 100644 --- a/dGame/dComponents/VehiclePhysicsComponent.h +++ b/dGame/dComponents/VehiclePhysicsComponent.h @@ -10,102 +10,102 @@ class VehiclePhysicsComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_VEHICLE_PHYSICS; - + VehiclePhysicsComponent(Entity* parentEntity); ~VehiclePhysicsComponent() override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - void Update(float deltaTime) override; - - /** - * Sets the position - * @param pos the new position - */ - void SetPosition(const NiPoint3& pos); - - /** - * Gets the position - * @return the position - */ - const NiPoint3& GetPosition() const { return m_Position; } - - /** - * Sets the rotation - * @param rot the new rotation - */ - void SetRotation(const NiQuaternion& rot); + void Update(float deltaTime) override; - /** - * Gets the rotation - * @return the rotation - */ - const NiQuaternion& GetRotation() const { return m_Rotation; } + /** + * Sets the position + * @param pos the new position + */ + void SetPosition(const NiPoint3& pos); - /** - * Sets the velocity - * @param vel the new velocity - */ - void SetVelocity(const NiPoint3& vel); + /** + * Gets the position + * @return the position + */ + const NiPoint3& GetPosition() const { return m_Position; } - /** - * Gets the velocity - * @return the velocity - */ - const NiPoint3& GetVelocity() const { return m_Velocity; } + /** + * Sets the rotation + * @param rot the new rotation + */ + void SetRotation(const NiQuaternion& rot); - /** - * Sets the angular velocity - * @param vel the new angular velocity - */ - void SetAngularVelocity(const NiPoint3& vel); + /** + * Gets the rotation + * @return the rotation + */ + const NiQuaternion& GetRotation() const { return m_Rotation; } - /** - * Gets the angular velocity - * @return the angular velocity - */ - const NiPoint3& GetAngularVelocity() const { return m_AngularVelocity; } + /** + * Sets the velocity + * @param vel the new velocity + */ + void SetVelocity(const NiPoint3& vel); - /** - * Sets whether the vehicle is on the ground - * @param val whether the vehicle is on the ground - */ - void SetIsOnGround(bool val); + /** + * Gets the velocity + * @return the velocity + */ + const NiPoint3& GetVelocity() const { return m_Velocity; } - /** - * Gets whether the vehicle is on the ground - * @return whether the vehicle is on the ground - */ - const bool GetIsOnGround() const { return m_IsOnGround; } + /** + * Sets the angular velocity + * @param vel the new angular velocity + */ + void SetAngularVelocity(const NiPoint3& vel); - /** - * Gets whether the vehicle is on rail - * @return whether the vehicle is on rail - */ - void SetIsOnRail(bool val); + /** + * Gets the angular velocity + * @return the angular velocity + */ + const NiPoint3& GetAngularVelocity() const { return m_AngularVelocity; } - /** - * Gets whether the vehicle is on rail - * @return whether the vehicle is on rail - */ - const bool GetIsOnRail() const { return m_IsOnRail; } + /** + * Sets whether the vehicle is on the ground + * @param val whether the vehicle is on the ground + */ + void SetIsOnGround(bool val); - void SetDirtyPosition(bool val); - void SetDirtyVelocity(bool val); - void SetDirtyAngularVelocity(bool val); + /** + * Gets whether the vehicle is on the ground + * @return whether the vehicle is on the ground + */ + const bool GetIsOnGround() const { return m_IsOnGround; } + + /** + * Gets whether the vehicle is on rail + * @return whether the vehicle is on rail + */ + void SetIsOnRail(bool val); + + /** + * Gets whether the vehicle is on rail + * @return whether the vehicle is on rail + */ + const bool GetIsOnRail() const { return m_IsOnRail; } + + void SetDirtyPosition(bool val); + void SetDirtyVelocity(bool val); + void SetDirtyAngularVelocity(bool val); private: - bool m_DirtyPosition; - NiPoint3 m_Position; - NiQuaternion m_Rotation; - - bool m_DirtyVelocity; - NiPoint3 m_Velocity; - - bool m_DirtyAngularVelocity; - NiPoint3 m_AngularVelocity; - bool m_IsOnGround; - bool m_IsOnRail; + bool m_DirtyPosition; + NiPoint3 m_Position; + NiQuaternion m_Rotation; - float m_SoftUpdate = 0; + bool m_DirtyVelocity; + NiPoint3 m_Velocity; + + bool m_DirtyAngularVelocity; + NiPoint3 m_AngularVelocity; + bool m_IsOnGround; + bool m_IsOnRail; + + float m_SoftUpdate = 0; }; diff --git a/dGame/dComponents/VendorComponent.cpp b/dGame/dComponents/VendorComponent.cpp index 6a8e7356..96dfb2c0 100644 --- a/dGame/dComponents/VendorComponent.cpp +++ b/dGame/dComponents/VendorComponent.cpp @@ -13,9 +13,9 @@ VendorComponent::VendorComponent(Entity* parent) : Component(parent) { VendorComponent::~VendorComponent() = default; void VendorComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - outBitStream->Write1(); + outBitStream->Write1(); outBitStream->Write1(); // Has standard items (Required for vendors with missions.) - outBitStream->Write(HasCraftingStation()); // Has multi use items + outBitStream->Write(HasCraftingStation()); // Has multi use items } void VendorComponent::OnUse(Entity* originator) { @@ -52,10 +52,10 @@ void VendorComponent::RefreshInventory(bool isCreation) { //Custom code for Max vanity NPC if (m_Parent->GetLOT() == 9749 && Game::server->GetZoneID() == 1201) { if (!isCreation) return; - m_Inventory.insert({11909, 0}); //Top hat w frog - m_Inventory.insert({7785, 0}); //Flash bulb - m_Inventory.insert({12764, 0}); //Big fountain soda - m_Inventory.insert({12241, 0}); //Hot cocoa (from fb) + m_Inventory.insert({ 11909, 0 }); //Top hat w frog + m_Inventory.insert({ 7785, 0 }); //Flash bulb + m_Inventory.insert({ 12764, 0 }); //Big fountain soda + m_Inventory.insert({ 12241, 0 }); //Hot cocoa (from fb) return; } m_Inventory.clear(); @@ -72,7 +72,7 @@ void VendorComponent::RefreshInventory(bool isCreation) { std::vector vendorItems = lootTableTable->Query([=](CDLootTable entry) { return (entry.LootTableIndex == lootTableID); }); if (lootMatrix.maxToDrop == 0 || lootMatrix.minToDrop == 0) { for (CDLootTable item : vendorItems) { - m_Inventory.insert({item.itemid, item.sortPriority}); + m_Inventory.insert({ item.itemid, item.sortPriority }); } } else { auto randomCount = GeneralUtils::GenerateRandomNumber(lootMatrix.minToDrop, lootMatrix.maxToDrop); @@ -86,7 +86,7 @@ void VendorComponent::RefreshInventory(bool isCreation) { vendorItems.erase(vendorItems.begin() + randomItemIndex); - m_Inventory.insert({randomItem.itemid, randomItem.sortPriority}); + m_Inventory.insert({ randomItem.itemid, randomItem.sortPriority }); } } } @@ -96,24 +96,24 @@ void VendorComponent::RefreshInventory(bool isCreation) { auto randomCamera = GeneralUtils::GenerateRandomNumber(0, 2); switch (randomCamera) { - case 0: - m_Inventory.insert({16253, 0}); //Grungagroid - break; - case 1: - m_Inventory.insert({16254, 0}); //Hipstabrick - break; - case 2: - m_Inventory.insert({16204, 0}); //Megabrixel snapshot - break; - default: - break; + case 0: + m_Inventory.insert({ 16253, 0 }); //Grungagroid + break; + case 1: + m_Inventory.insert({ 16254, 0 }); //Hipstabrick + break; + case 2: + m_Inventory.insert({ 16204, 0 }); //Megabrixel snapshot + break; + default: + break; } } // Callback timer to refresh this inventory. m_Parent->AddCallbackTimer(m_RefreshTimeSeconds, [this]() { RefreshInventory(); - }); + }); GameMessages::SendVendorStatusUpdate(m_Parent, UNASSIGNED_SYSTEM_ADDRESS); } @@ -128,4 +128,4 @@ void VendorComponent::SetupConstants() { m_SellScalar = vendorComps[0].sellScalar; m_RefreshTimeSeconds = vendorComps[0].refreshTimeSeconds; m_LootMatrixID = vendorComps[0].LootMatrixIndex; -} \ No newline at end of file +} diff --git a/dGame/dComponents/VendorComponent.h b/dGame/dComponents/VendorComponent.h index c037d875..72a5816d 100644 --- a/dGame/dComponents/VendorComponent.h +++ b/dGame/dComponents/VendorComponent.h @@ -14,43 +14,43 @@ class VendorComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_VENDOR; - + VendorComponent(Entity* parent); ~VendorComponent() override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); - + void OnUse(Entity* originator) override; - + /** * Gets the buy scaler * @return the buy scaler */ float GetBuyScalar() const; - /** - * Sets the buy scalar. - * @param value the new value. - */ + /** + * Sets the buy scalar. + * @param value the new value. + */ void SetBuyScalar(float value); - + /** * Gets the buy scaler * @return the buy scaler */ float GetSellScalar() const; - /** - * Sets the sell scalar. - * @param value the new value. - */ + /** + * Sets the sell scalar. + * @param value the new value. + */ void SetSellScalar(float value); /** * True if the NPC LOT is 13800, the only NPC with a crafting station. */ bool HasCraftingStation(); - + /** * Gets the list if items the vendor sells. * @return the list of items. @@ -61,7 +61,7 @@ public: * Refresh the inventory of this vendor. */ void RefreshInventory(bool isCreation = false); - + /** * Called on startup of vendor to setup the variables for the component. */ diff --git a/dGame/dEntity/EntityCallbackTimer.cpp b/dGame/dEntity/EntityCallbackTimer.cpp index 48a0ab06..e07c1189 100644 --- a/dGame/dEntity/EntityCallbackTimer.cpp +++ b/dGame/dEntity/EntityCallbackTimer.cpp @@ -6,7 +6,7 @@ EntityCallbackTimer::EntityCallbackTimer(float time, std::function callb } EntityCallbackTimer::~EntityCallbackTimer() { - + } std::function EntityCallbackTimer::GetCallback() { diff --git a/dGame/dEntity/EntityCallbackTimer.h b/dGame/dEntity/EntityCallbackTimer.h index 63613dda..2a7e58f0 100644 --- a/dGame/dEntity/EntityCallbackTimer.h +++ b/dGame/dEntity/EntityCallbackTimer.h @@ -10,7 +10,7 @@ public: std::function GetCallback(); float GetTime(); - + void Update(float deltaTime); private: diff --git a/dGame/dEntity/EntityInfo.h b/dGame/dEntity/EntityInfo.h index 7e5fa5b5..049c5ce3 100644 --- a/dGame/dEntity/EntityInfo.h +++ b/dGame/dEntity/EntityInfo.h @@ -17,24 +17,24 @@ struct EntityInfo { spawnerNodeID = 0; id = 0; lot = LOT_NULL; - pos = {0,0,0}; - rot = {0,0,0,0}; + pos = { 0,0,0 }; + rot = { 0,0,0,0 }; settings = {}; networkSettings = {}; scale = 1.0f; } Spawner* spawner; - LWOOBJID spawnerID; - - bool hasSpawnerNodeID; - uint32_t spawnerNodeID; - - LWOOBJID id; - LOT lot; - NiPoint3 pos; - NiQuaternion rot; - std::vector settings; - std::vector networkSettings; + LWOOBJID spawnerID; + + bool hasSpawnerNodeID; + uint32_t spawnerNodeID; + + LWOOBJID id; + LOT lot; + NiPoint3 pos; + NiQuaternion rot; + std::vector settings; + std::vector networkSettings; float scale; }; diff --git a/dGame/dEntity/EntityTimer.cpp b/dGame/dEntity/EntityTimer.cpp index deff2d31..0363fc5b 100644 --- a/dGame/dEntity/EntityTimer.cpp +++ b/dGame/dEntity/EntityTimer.cpp @@ -6,7 +6,7 @@ EntityTimer::EntityTimer(std::string name, float time) { } EntityTimer::~EntityTimer() { - + } std::string EntityTimer::GetName() { @@ -19,4 +19,4 @@ float EntityTimer::GetTime() { void EntityTimer::Update(float deltaTime) { m_Time -= deltaTime; -} \ No newline at end of file +} diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 9cd8995a..b9115e50 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -33,13 +33,12 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System CBITSTREAM - // Get the entity - Entity* entity = EntityManager::Instance()->GetEntity(objectID); + // Get the entity + Entity* entity = EntityManager::Instance()->GetEntity(objectID); - User * usr = UserManager::Instance()->GetUser(sysAddr); + User* usr = UserManager::Instance()->GetUser(sysAddr); - if (!entity) - { + if (!entity) { Game::logger->Log("GameMessageHandler", "Failed to find associated entity (%llu), aborting GM (%X)!", objectID, messageID); return; @@ -47,618 +46,615 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System switch (messageID) { - case GAME_MSG_PLAY_EMOTE: { - GameMessages::HandlePlayEmote(inStream, entity); - break; + case GAME_MSG_PLAY_EMOTE: { + GameMessages::HandlePlayEmote(inStream, entity); + break; + } + + case GAME_MSG_MOVE_ITEM_IN_INVENTORY: { + GameMessages::HandleMoveItemInInventory(inStream, entity); + break; + } + + case GAME_MSG_REMOVE_ITEM_FROM_INVENTORY: { + GameMessages::HandleRemoveItemFromInventory(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_EQUIP_ITEM: + GameMessages::HandleEquipItem(inStream, entity); + break; + + case GAME_MSG_UN_EQUIP_ITEM: + GameMessages::HandleUnequipItem(inStream, entity); + break; + + case GAME_MSG_RESPOND_TO_MISSION: { + GameMessages::HandleRespondToMission(inStream, entity); + break; + } + + case GAME_MSG_REQUEST_USE: { + GameMessages::HandleRequestUse(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_SET_FLAG: { + GameMessages::HandleSetFlag(inStream, entity); + break; + } + + case GAME_MSG_HAS_BEEN_COLLECTED: { + GameMessages::HandleHasBeenCollected(inStream, entity); + break; + } + + case GAME_MSG_PLAYER_LOADED: { + GameMessages::SendRestoreToPostLoadStats(entity, sysAddr); + entity->SetPlayerReadyForUpdates(); + + auto* player = dynamic_cast(entity); + if (player != nullptr) { + player->ConstructLimboEntities(); } - case GAME_MSG_MOVE_ITEM_IN_INVENTORY: { - GameMessages::HandleMoveItemInInventory(inStream, entity); - break; - } + InventoryComponent* inv = entity->GetComponent(); + if (inv) { + auto items = inv->GetEquippedItems(); + for (auto pair : items) { + const auto item = pair.second; - case GAME_MSG_REMOVE_ITEM_FROM_INVENTORY: { - GameMessages::HandleRemoveItemFromInventory(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_EQUIP_ITEM: - GameMessages::HandleEquipItem(inStream, entity); - break; - - case GAME_MSG_UN_EQUIP_ITEM: - GameMessages::HandleUnequipItem(inStream, entity); - break; - - case GAME_MSG_RESPOND_TO_MISSION: { - GameMessages::HandleRespondToMission(inStream, entity); - break; - } - - case GAME_MSG_REQUEST_USE: { - GameMessages::HandleRequestUse(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_SET_FLAG: { - GameMessages::HandleSetFlag(inStream, entity); - break; - } - - case GAME_MSG_HAS_BEEN_COLLECTED: { - GameMessages::HandleHasBeenCollected(inStream, entity); - break; - } - - case GAME_MSG_PLAYER_LOADED: { - GameMessages::SendRestoreToPostLoadStats(entity, sysAddr); - entity->SetPlayerReadyForUpdates(); - - auto* player = dynamic_cast(entity); - if (player != nullptr) - { - player->ConstructLimboEntities(); + inv->AddItemSkills(item.lot); } + } - InventoryComponent* inv = entity->GetComponent(); - if (inv) { - auto items = inv->GetEquippedItems(); - for (auto pair : items) { - const auto item = pair.second; + auto* destroyable = entity->GetComponent(); + destroyable->SetImagination(destroyable->GetImagination()); + EntityManager::Instance()->SerializeEntity(entity); - inv->AddItemSkills(item.lot); + std::vector racingControllers = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RACING_CONTROL); + for (Entity* racingController : racingControllers) { + auto* racingComponent = racingController->GetComponent(); + if (racingComponent != nullptr) { + racingComponent->OnPlayerLoaded(entity); + } + } + + Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { + script->OnPlayerLoaded(zoneControl, player); + } + + std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); + 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->OnPlayerLoaded(scriptEntity, player); } } + } - auto* destroyable = entity->GetComponent(); - destroyable->SetImagination(destroyable->GetImagination()); + //Kill player if health == 0 + if (entity->GetIsDead()) { + entity->Smash(entity->GetObjectID()); + } + + //if the player has moved significantly, move them back: + if ((entity->GetPosition().y - entity->GetCharacter()->GetOriginalPos().y) > 2.0f) { + // Disabled until fixed + //GameMessages::SendTeleport(entity->GetObjectID(), entity->GetCharacter()->GetOriginalPos(), entity->GetCharacter()->GetOriginalRot(), entity->GetSystemAddress(), true, true); + } + + /** + * Invoke the OnZoneLoad event on the player character + */ + auto* character = entity->GetCharacter(); + + if (character != nullptr) { + character->OnZoneLoad(); + } + + Game::logger->Log("GameMessageHandler", "Player %s (%llu) loaded.", entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); + + // After we've done our thing, tell the client they're ready + GameMessages::SendPlayerReady(dZoneManager::Instance()->GetZoneControlObject(), sysAddr); + GameMessages::SendPlayerReady(entity, sysAddr); + + break; + } + + case GAME_MSG_REQUEST_LINKED_MISSION: { + GameMessages::HandleRequestLinkedMission(inStream, entity); + break; + } + + case GAME_MSG_MISSION_DIALOGUE_OK: { + GameMessages::HandleMissionDialogOK(inStream, entity); + break; + } + + case GAME_MSG_MISSION_DIALOGUE_CANCELLED: { + //This message is pointless for our implementation, as the client just carries on after + //rejecting a mission offer. We dont need to do anything. This is just here to remove a warning in our logs :) + break; + } + + case GAME_MSG_REQUEST_PLATFORM_RESYNC: { + GameMessages::HandleRequestPlatformResync(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_FIRE_EVENT_SERVER_SIDE: { + GameMessages::HandleFireEventServerSide(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { + GameMessages::HandleActivitySummaryLeaderboardData(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { + GameMessages::HandleRequestActivitySummaryLeaderboardData(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST: { + GameMessages::HandleActivityStateChangeRequest(inStream, entity); + break; + } + + case GAME_MSG_PARSE_CHAT_MESSAGE: { + GameMessages::HandleParseChatMessage(inStream, entity, sysAddr); + break; + } + + case GAME_MSG_NOTIFY_SERVER_LEVEL_PROCESSING_COMPLETE: { + GameMessages::HandleNotifyServerLevelProcessingComplete(inStream, entity); + break; + } + + case GAME_MSG_PICKUP_CURRENCY: { + GameMessages::HandlePickupCurrency(inStream, entity); + break; + } + + case GAME_MSG_PICKUP_ITEM: { + GameMessages::HandlePickupItem(inStream, entity); + break; + } + + case GAME_MSG_RESURRECT: { + GameMessages::HandleResurrect(inStream, entity); + break; + } + + case GAME_MSG_REQUEST_RESURRECT: { + GameMessages::SendResurrect(entity); + /*auto* dest = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); + if (dest) { + dest->SetHealth(4); + dest->SetArmor(0); + dest->SetImagination(6); EntityManager::Instance()->SerializeEntity(entity); + }*/ + break; + } + case GAME_MSG_HANDLE_HOT_PROPERTY_DATA: { + GameMessages::HandleGetHotPropertyData(inStream, entity, sysAddr); + break; + } - std::vector racingControllers = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RACING_CONTROL); - for (Entity* racingController : racingControllers) { - auto* racingComponent = racingController->GetComponent(); - if (racingComponent != nullptr) - { - racingComponent->OnPlayerLoaded(entity); - } + case GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT: + { + auto message = GameMessages::RequestServerProjectileImpact(); + + message.Deserialize(inStream); + + auto* skill_component = entity->GetComponent(); + + if (skill_component != nullptr) { + auto* bs = new RakNet::BitStream((unsigned char*)message.sBitStream.c_str(), message.sBitStream.size(), false); + + skill_component->SyncPlayerProjectile(message.i64LocalID, bs, message.i64TargetID); + + delete bs; + } + + break; + } + + case GAME_MSG_START_SKILL: { + GameMessages::StartSkill startSkill = GameMessages::StartSkill(); + startSkill.Deserialize(inStream); // inStream replaces &bitStream + + if (startSkill.skillID == 1561 || startSkill.skillID == 1562 || startSkill.skillID == 1541) return; + + MissionComponent* comp = entity->GetComponent(); + if (comp) { + comp->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, startSkill.skillID); + } + + CDSkillBehaviorTable* skillTable = CDClientManager::Instance()->GetTable("SkillBehavior"); + unsigned int behaviorId = skillTable->GetSkillByID(startSkill.skillID).behaviorID; + + bool success = false; + + if (behaviorId > 0) { + RakNet::BitStream* bs = new RakNet::BitStream((unsigned char*)startSkill.sBitStream.c_str(), startSkill.sBitStream.size(), false); + + auto* skillComponent = entity->GetComponent(); + + success = skillComponent->CastPlayerSkill(behaviorId, startSkill.uiSkillHandle, bs, startSkill.optionalTargetID, startSkill.skillID); + + if (success && entity->GetCharacter()) { + DestroyableComponent* destComp = entity->GetComponent(); + destComp->SetImagination(destComp->GetImagination() - skillTable->GetSkillByID(startSkill.skillID).imaginationcost); } - Entity* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerLoaded(zoneControl, player); - } - - std::vector scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); - 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->OnPlayerLoaded(scriptEntity, player); - } - } - } - - //Kill player if health == 0 - if (entity->GetIsDead()) { - entity->Smash(entity->GetObjectID()); - } - - //if the player has moved significantly, move them back: - if ((entity->GetPosition().y - entity->GetCharacter()->GetOriginalPos().y) > 2.0f) { - // Disabled until fixed - //GameMessages::SendTeleport(entity->GetObjectID(), entity->GetCharacter()->GetOriginalPos(), entity->GetCharacter()->GetOriginalRot(), entity->GetSystemAddress(), true, true); - } - - /** - * Invoke the OnZoneLoad event on the player character - */ - auto* character = entity->GetCharacter(); - - if (character != nullptr) { - character->OnZoneLoad(); - } - - Game::logger->Log("GameMessageHandler", "Player %s (%llu) loaded.", entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); - - // After we've done our thing, tell the client they're ready - GameMessages::SendPlayerReady(dZoneManager::Instance()->GetZoneControlObject(), sysAddr); - GameMessages::SendPlayerReady(entity, sysAddr); + delete bs; + } + if (Game::server->GetZoneID() == 1302) { break; } - case GAME_MSG_REQUEST_LINKED_MISSION: { - GameMessages::HandleRequestLinkedMission(inStream, entity); - break; - } - - case GAME_MSG_MISSION_DIALOGUE_OK: { - GameMessages::HandleMissionDialogOK(inStream, entity); - break; - } - - case GAME_MSG_MISSION_DIALOGUE_CANCELLED: { - //This message is pointless for our implementation, as the client just carries on after - //rejecting a mission offer. We dont need to do anything. This is just here to remove a warning in our logs :) - break; - } - - case GAME_MSG_REQUEST_PLATFORM_RESYNC: { - GameMessages::HandleRequestPlatformResync(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_FIRE_EVENT_SERVER_SIDE: { - GameMessages::HandleFireEventServerSide(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { - GameMessages::HandleActivitySummaryLeaderboardData(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { - GameMessages::HandleRequestActivitySummaryLeaderboardData(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST: { - GameMessages::HandleActivityStateChangeRequest(inStream, entity); - break; - } - - case GAME_MSG_PARSE_CHAT_MESSAGE: { - GameMessages::HandleParseChatMessage(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_NOTIFY_SERVER_LEVEL_PROCESSING_COMPLETE: { - GameMessages::HandleNotifyServerLevelProcessingComplete(inStream, entity); - break; - } - - case GAME_MSG_PICKUP_CURRENCY: { - GameMessages::HandlePickupCurrency(inStream, entity); - break; - } - - case GAME_MSG_PICKUP_ITEM: { - GameMessages::HandlePickupItem(inStream, entity); - break; - } - - case GAME_MSG_RESURRECT: { - GameMessages::HandleResurrect(inStream, entity); - break; - } - - case GAME_MSG_REQUEST_RESURRECT: { - GameMessages::SendResurrect(entity); - /*auto* dest = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - if (dest) { - dest->SetHealth(4); - dest->SetArmor(0); - dest->SetImagination(6); - EntityManager::Instance()->SerializeEntity(entity); - }*/ - break; - } - case GAME_MSG_HANDLE_HOT_PROPERTY_DATA: { - GameMessages::HandleGetHotPropertyData(inStream, entity, sysAddr); - break; - } - - case GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT: - { - auto message = GameMessages::RequestServerProjectileImpact(); - - message.Deserialize(inStream); - - auto* skill_component = entity->GetComponent(); - - if (skill_component != nullptr) - { - auto* bs = new RakNet::BitStream((unsigned char*) message.sBitStream.c_str(), message.sBitStream.size(), false); - - skill_component->SyncPlayerProjectile(message.i64LocalID, bs, message.i64TargetID); - - delete bs; - } - - break; - } - - case GAME_MSG_START_SKILL: { - GameMessages::StartSkill startSkill = GameMessages::StartSkill(); - startSkill.Deserialize(inStream); // inStream replaces &bitStream - - if (startSkill.skillID == 1561 || startSkill.skillID == 1562 || startSkill.skillID == 1541) return; - - MissionComponent* comp = entity->GetComponent(); - if (comp) { - comp->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, startSkill.skillID); - } - - CDSkillBehaviorTable* skillTable = CDClientManager::Instance()->GetTable("SkillBehavior"); - unsigned int behaviorId = skillTable->GetSkillByID(startSkill.skillID).behaviorID; - - bool success = false; - - if (behaviorId > 0) { - RakNet::BitStream * bs = new RakNet::BitStream((unsigned char *)startSkill.sBitStream.c_str(), startSkill.sBitStream.size(), false); - - auto* skillComponent = entity->GetComponent(); - - success = skillComponent->CastPlayerSkill(behaviorId, startSkill.uiSkillHandle, bs, startSkill.optionalTargetID, startSkill.skillID); - - if (success && entity->GetCharacter()) { - DestroyableComponent* destComp = entity->GetComponent(); - destComp->SetImagination(destComp->GetImagination() - skillTable->GetSkillByID(startSkill.skillID).imaginationcost); - } - - delete bs; - } - - if (Game::server->GetZoneID() == 1302) { - break; - } - - if (success) { - //Broadcast our startSkill: - RakNet::BitStream bitStreamLocal; - PacketUtils::WriteHeader(bitStreamLocal, CLIENT, MSG_CLIENT_GAME_MSG); - bitStreamLocal.Write(entity->GetObjectID()); - - GameMessages::EchoStartSkill echoStartSkill; - echoStartSkill.bUsedMouse = startSkill.bUsedMouse; - echoStartSkill.fCasterLatency = startSkill.fCasterLatency; - echoStartSkill.iCastType = startSkill.iCastType; - echoStartSkill.lastClickedPosit = startSkill.lastClickedPosit; - echoStartSkill.optionalOriginatorID = startSkill.optionalOriginatorID; - echoStartSkill.optionalTargetID = startSkill.optionalTargetID; - echoStartSkill.originatorRot = startSkill.originatorRot; - echoStartSkill.sBitStream = startSkill.sBitStream; - echoStartSkill.skillID = startSkill.skillID; - echoStartSkill.uiSkillHandle = startSkill.uiSkillHandle; - echoStartSkill.Serialize(&bitStreamLocal); - - Game::server->Send(&bitStreamLocal, entity->GetSystemAddress(), true); - } - } break; - - case GAME_MSG_SYNC_SKILL: { + if (success) { + //Broadcast our startSkill: RakNet::BitStream bitStreamLocal; PacketUtils::WriteHeader(bitStreamLocal, CLIENT, MSG_CLIENT_GAME_MSG); bitStreamLocal.Write(entity->GetObjectID()); - //bitStreamLocal.Write((unsigned short)GAME_MSG_ECHO_SYNC_SKILL); - //bitStreamLocal.Write(inStream); - GameMessages::SyncSkill sync = GameMessages::SyncSkill(inStream); // inStream replaced &bitStream - //sync.Serialize(&bitStreamLocal); + GameMessages::EchoStartSkill echoStartSkill; + echoStartSkill.bUsedMouse = startSkill.bUsedMouse; + echoStartSkill.fCasterLatency = startSkill.fCasterLatency; + echoStartSkill.iCastType = startSkill.iCastType; + echoStartSkill.lastClickedPosit = startSkill.lastClickedPosit; + echoStartSkill.optionalOriginatorID = startSkill.optionalOriginatorID; + echoStartSkill.optionalTargetID = startSkill.optionalTargetID; + echoStartSkill.originatorRot = startSkill.originatorRot; + echoStartSkill.sBitStream = startSkill.sBitStream; + echoStartSkill.skillID = startSkill.skillID; + echoStartSkill.uiSkillHandle = startSkill.uiSkillHandle; + echoStartSkill.Serialize(&bitStreamLocal); - ostringstream buffer; + Game::server->Send(&bitStreamLocal, entity->GetSystemAddress(), true); + } + } break; - for (unsigned int k = 0; k < sync.sBitStream.size(); k++){ - char s; - s = sync.sBitStream.at(k); - buffer << setw(2) << hex << setfill('0') << (int) s << " "; - } + case GAME_MSG_SYNC_SKILL: { + RakNet::BitStream bitStreamLocal; + PacketUtils::WriteHeader(bitStreamLocal, CLIENT, MSG_CLIENT_GAME_MSG); + bitStreamLocal.Write(entity->GetObjectID()); + //bitStreamLocal.Write((unsigned short)GAME_MSG_ECHO_SYNC_SKILL); + //bitStreamLocal.Write(inStream); - //cout << buffer.str() << endl; + GameMessages::SyncSkill sync = GameMessages::SyncSkill(inStream); // inStream replaced &bitStream + //sync.Serialize(&bitStreamLocal); - if(usr != nullptr) { - RakNet::BitStream * bs = new RakNet::BitStream((unsigned char *)sync.sBitStream.c_str(), sync.sBitStream.size(), false); + ostringstream buffer; - auto* skillComponent = entity->GetComponent(); + for (unsigned int k = 0; k < sync.sBitStream.size(); k++) { + char s; + s = sync.sBitStream.at(k); + buffer << setw(2) << hex << setfill('0') << (int)s << " "; + } - skillComponent->SyncPlayerSkill(sync.uiSkillHandle, sync.uiBehaviorHandle, bs); + //cout << buffer.str() << endl; - delete bs; - } + if (usr != nullptr) { + RakNet::BitStream* bs = new RakNet::BitStream((unsigned char*)sync.sBitStream.c_str(), sync.sBitStream.size(), false); - GameMessages::EchoSyncSkill echo = GameMessages::EchoSyncSkill(); - echo.bDone = sync.bDone; - echo.sBitStream = sync.sBitStream; - echo.uiBehaviorHandle = sync.uiBehaviorHandle; - echo.uiSkillHandle = sync.uiSkillHandle; + auto* skillComponent = entity->GetComponent(); - echo.Serialize(&bitStreamLocal); + skillComponent->SyncPlayerSkill(sync.uiSkillHandle, sync.uiBehaviorHandle, bs); - Game::server->Send(&bitStreamLocal, sysAddr, true); - } break; + delete bs; + } - case GAME_MSG_REQUEST_SMASH_PLAYER: - entity->Smash(entity->GetObjectID()); - break; + GameMessages::EchoSyncSkill echo = GameMessages::EchoSyncSkill(); + echo.bDone = sync.bDone; + echo.sBitStream = sync.sBitStream; + echo.uiBehaviorHandle = sync.uiBehaviorHandle; + echo.uiSkillHandle = sync.uiSkillHandle; - case GAME_MSG_MOVE_ITEM_BETWEEN_INVENTORY_TYPES: - GameMessages::HandleMoveItemBetweenInventoryTypes(inStream, entity, sysAddr); - break; + echo.Serialize(&bitStreamLocal); - case GAME_MSG_MODULAR_BUILD_FINISH: - GameMessages::HandleModularBuildFinish(inStream, entity, sysAddr); - break; + Game::server->Send(&bitStreamLocal, sysAddr, true); + } break; - case GAME_MSG_PUSH_EQUIPPED_ITEMS_STATE: - GameMessages::HandlePushEquippedItemsState(inStream, entity); - break; + case GAME_MSG_REQUEST_SMASH_PLAYER: + entity->Smash(entity->GetObjectID()); + break; - case GAME_MSG_POP_EQUIPPED_ITEMS_STATE: - GameMessages::HandlePopEquippedItemsState(inStream, entity); - break; + case GAME_MSG_MOVE_ITEM_BETWEEN_INVENTORY_TYPES: + GameMessages::HandleMoveItemBetweenInventoryTypes(inStream, entity, sysAddr); + break; - case GAME_MSG_BUY_FROM_VENDOR: - GameMessages::HandleBuyFromVendor(inStream, entity, sysAddr); - break; + case GAME_MSG_MODULAR_BUILD_FINISH: + GameMessages::HandleModularBuildFinish(inStream, entity, sysAddr); + break; - case GAME_MSG_SELL_TO_VENDOR: - GameMessages::HandleSellToVendor(inStream, entity, sysAddr); - break; + case GAME_MSG_PUSH_EQUIPPED_ITEMS_STATE: + GameMessages::HandlePushEquippedItemsState(inStream, entity); + break; - case GAME_MSG_BUYBACK_FROM_VENDOR: - GameMessages::HandleBuybackFromVendor(inStream, entity, sysAddr); - break; + case GAME_MSG_POP_EQUIPPED_ITEMS_STATE: + GameMessages::HandlePopEquippedItemsState(inStream, entity); + break; - case GAME_MSG_MODULAR_BUILD_MOVE_AND_EQUIP: - GameMessages::HandleModularBuildMoveAndEquip(inStream, entity, sysAddr); - break; + case GAME_MSG_BUY_FROM_VENDOR: + GameMessages::HandleBuyFromVendor(inStream, entity, sysAddr); + break; - case GAME_MSG_DONE_ARRANGING_WITH_ITEM: - GameMessages::HandleDoneArrangingWithItem(inStream, entity, sysAddr); - break; + case GAME_MSG_SELL_TO_VENDOR: + GameMessages::HandleSellToVendor(inStream, entity, sysAddr); + break; - case GAME_MSG_MODULAR_BUILD_CONVERT_MODEL: - GameMessages::HandleModularBuildConvertModel(inStream, entity, sysAddr); - break; + case GAME_MSG_BUYBACK_FROM_VENDOR: + GameMessages::HandleBuybackFromVendor(inStream, entity, sysAddr); + break; - case GAME_MSG_BUILD_MODE_SET: - GameMessages::HandleBuildModeSet(inStream, entity); - break; + case GAME_MSG_MODULAR_BUILD_MOVE_AND_EQUIP: + GameMessages::HandleModularBuildMoveAndEquip(inStream, entity, sysAddr); + break; - case GAME_MSG_REBUILD_CANCEL: - GameMessages::HandleRebuildCancel(inStream, entity); - break; + case GAME_MSG_DONE_ARRANGING_WITH_ITEM: + GameMessages::HandleDoneArrangingWithItem(inStream, entity, sysAddr); + break; - case GAME_MSG_MATCH_REQUEST: - GameMessages::HandleMatchRequest(inStream, entity); - break; + case GAME_MSG_MODULAR_BUILD_CONVERT_MODEL: + GameMessages::HandleModularBuildConvertModel(inStream, entity, sysAddr); + break; - case GAME_MSG_USE_NON_EQUIPMENT_ITEM: - GameMessages::HandleUseNonEquipmentItem(inStream, entity); - break; + case GAME_MSG_BUILD_MODE_SET: + GameMessages::HandleBuildModeSet(inStream, entity); + break; - case GAME_MSG_CLIENT_ITEM_CONSUMED: - GameMessages::HandleClientItemConsumed(inStream, entity); - break; + case GAME_MSG_REBUILD_CANCEL: + GameMessages::HandleRebuildCancel(inStream, entity); + break; - case GAME_MSG_SET_CONSUMABLE_ITEM: - GameMessages::HandleSetConsumableItem(inStream, entity, sysAddr); - break; + case GAME_MSG_MATCH_REQUEST: + GameMessages::HandleMatchRequest(inStream, entity); + break; - case GAME_MSG_VERIFY_ACK: - GameMessages::HandleVerifyAck(inStream, entity, sysAddr); - break; + case GAME_MSG_USE_NON_EQUIPMENT_ITEM: + GameMessages::HandleUseNonEquipmentItem(inStream, entity); + break; + + case GAME_MSG_CLIENT_ITEM_CONSUMED: + GameMessages::HandleClientItemConsumed(inStream, entity); + break; + + case GAME_MSG_SET_CONSUMABLE_ITEM: + GameMessages::HandleSetConsumableItem(inStream, entity, sysAddr); + break; + + case GAME_MSG_VERIFY_ACK: + GameMessages::HandleVerifyAck(inStream, entity, sysAddr); + break; // Trading - case GAME_MSG_CLIENT_TRADE_REQUEST: - GameMessages::HandleClientTradeRequest(inStream, entity, sysAddr); - break; - case GAME_MSG_CLIENT_TRADE_CANCEL: - GameMessages::HandleClientTradeCancel(inStream, entity, sysAddr); - break; - case GAME_MSG_CLIENT_TRADE_ACCEPT: - GameMessages::HandleClientTradeAccept(inStream, entity, sysAddr); - break; - case GAME_MSG_CLIENT_TRADE_UPDATE: - GameMessages::HandleClientTradeUpdate(inStream, entity, sysAddr); - break; + case GAME_MSG_CLIENT_TRADE_REQUEST: + GameMessages::HandleClientTradeRequest(inStream, entity, sysAddr); + break; + case GAME_MSG_CLIENT_TRADE_CANCEL: + GameMessages::HandleClientTradeCancel(inStream, entity, sysAddr); + break; + case GAME_MSG_CLIENT_TRADE_ACCEPT: + GameMessages::HandleClientTradeAccept(inStream, entity, sysAddr); + break; + case GAME_MSG_CLIENT_TRADE_UPDATE: + GameMessages::HandleClientTradeUpdate(inStream, entity, sysAddr); + break; // Pets - case GAME_MSG_PET_TAMING_TRY_BUILD: - GameMessages::HandlePetTamingTryBuild(inStream, entity, sysAddr); - break; + case GAME_MSG_PET_TAMING_TRY_BUILD: + GameMessages::HandlePetTamingTryBuild(inStream, entity, sysAddr); + break; - case GAME_MSG_NOTIFY_TAMING_BUILD_SUCCESS: - GameMessages::HandleNotifyTamingBuildSuccess(inStream, entity, sysAddr); - break; + case GAME_MSG_NOTIFY_TAMING_BUILD_SUCCESS: + GameMessages::HandleNotifyTamingBuildSuccess(inStream, entity, sysAddr); + break; - case GAME_MSG_REQUEST_SET_PET_NAME: - GameMessages::HandleRequestSetPetName(inStream, entity, sysAddr); - break; + case GAME_MSG_REQUEST_SET_PET_NAME: + GameMessages::HandleRequestSetPetName(inStream, entity, sysAddr); + break; - case GAME_MSG_START_SERVER_PET_MINIGAME_TIMER: - GameMessages::HandleStartServerPetMinigameTimer(inStream, entity, sysAddr); - break; + case GAME_MSG_START_SERVER_PET_MINIGAME_TIMER: + GameMessages::HandleStartServerPetMinigameTimer(inStream, entity, sysAddr); + break; - case GAME_MSG_CLIENT_EXIT_TAMING_MINIGAME: - GameMessages::HandleClientExitTamingMinigame(inStream, entity, sysAddr); - break; + case GAME_MSG_CLIENT_EXIT_TAMING_MINIGAME: + GameMessages::HandleClientExitTamingMinigame(inStream, entity, sysAddr); + break; - case GAME_MSG_COMMAND_PET: - GameMessages::HandleCommandPet(inStream, entity, sysAddr); - break; + case GAME_MSG_COMMAND_PET: + GameMessages::HandleCommandPet(inStream, entity, sysAddr); + break; - case GAME_MSG_DESPAWN_PET: - GameMessages::HandleDespawnPet(inStream, entity, sysAddr); - break; + case GAME_MSG_DESPAWN_PET: + GameMessages::HandleDespawnPet(inStream, entity, sysAddr); + break; - case GAME_MSG_MESSAGE_BOX_RESPOND: - GameMessages::HandleMessageBoxResponse(inStream, entity, sysAddr); - break; + case GAME_MSG_MESSAGE_BOX_RESPOND: + GameMessages::HandleMessageBoxResponse(inStream, entity, sysAddr); + break; - case GAME_MSG_CHOICE_BOX_RESPOND: - GameMessages::HandleChoiceBoxRespond(inStream, entity, sysAddr); - break; + case GAME_MSG_CHOICE_BOX_RESPOND: + GameMessages::HandleChoiceBoxRespond(inStream, entity, sysAddr); + break; // Property - case GAME_MSG_QUERY_PROPERTY_DATA: - GameMessages::HandleQueryPropertyData(inStream, entity, sysAddr); - break; + case GAME_MSG_QUERY_PROPERTY_DATA: + GameMessages::HandleQueryPropertyData(inStream, entity, sysAddr); + break; - case GAME_MSG_START_BUILDING_WITH_ITEM: - GameMessages::HandleStartBuildingWithItem(inStream, entity, sysAddr); - break; + case GAME_MSG_START_BUILDING_WITH_ITEM: + GameMessages::HandleStartBuildingWithItem(inStream, entity, sysAddr); + break; - case GAME_MSG_SET_BUILD_MODE: - GameMessages::HandleSetBuildMode(inStream, entity, sysAddr); - break; + case GAME_MSG_SET_BUILD_MODE: + GameMessages::HandleSetBuildMode(inStream, entity, sysAddr); + break; - case GAME_MSG_PROPERTY_EDITOR_BEGIN: - GameMessages::HandlePropertyEditorBegin(inStream, entity, sysAddr); - break; + case GAME_MSG_PROPERTY_EDITOR_BEGIN: + GameMessages::HandlePropertyEditorBegin(inStream, entity, sysAddr); + break; - case GAME_MSG_PROPERTY_EDITOR_END: - GameMessages::HandlePropertyEditorEnd(inStream, entity, sysAddr); - break; + case GAME_MSG_PROPERTY_EDITOR_END: + GameMessages::HandlePropertyEditorEnd(inStream, entity, sysAddr); + break; - case GAME_MSG_PROPERTY_CONTENTS_FROM_CLIENT: - GameMessages::HandlePropertyContentsFromClient(inStream, entity, sysAddr); - break; + case GAME_MSG_PROPERTY_CONTENTS_FROM_CLIENT: + GameMessages::HandlePropertyContentsFromClient(inStream, entity, sysAddr); + break; - case GAME_MSG_ZONE_PROPERTY_MODEL_EQUIPPED: - GameMessages::HandlePropertyModelEquipped(inStream, entity, sysAddr); - break; + case GAME_MSG_ZONE_PROPERTY_MODEL_EQUIPPED: + GameMessages::HandlePropertyModelEquipped(inStream, entity, sysAddr); + break; - case GAME_MSG_PLACE_PROPERTY_MODEL: - GameMessages::HandlePlacePropertyModel(inStream, entity, sysAddr); - break; + case GAME_MSG_PLACE_PROPERTY_MODEL: + GameMessages::HandlePlacePropertyModel(inStream, entity, sysAddr); + break; - case GAME_MSG_UPDATE_MODEL_FROM_CLIENT: - GameMessages::HandleUpdatePropertyModel(inStream, entity, sysAddr); - break; + case GAME_MSG_UPDATE_MODEL_FROM_CLIENT: + GameMessages::HandleUpdatePropertyModel(inStream, entity, sysAddr); + break; - case GAME_MSG_DELETE_MODEL_FROM_CLIENT: - GameMessages::HandleDeletePropertyModel(inStream, entity, sysAddr); - break; + case GAME_MSG_DELETE_MODEL_FROM_CLIENT: + GameMessages::HandleDeletePropertyModel(inStream, entity, sysAddr); + break; - case GAME_MSG_BBB_LOAD_ITEM_REQUEST: - GameMessages::HandleBBBLoadItemRequest(inStream, entity, sysAddr); - break; + case GAME_MSG_BBB_LOAD_ITEM_REQUEST: + GameMessages::HandleBBBLoadItemRequest(inStream, entity, sysAddr); + break; - case GAME_MSG_BBB_SAVE_REQUEST: - GameMessages::HandleBBBSaveRequest(inStream, entity, sysAddr); - break; + case GAME_MSG_BBB_SAVE_REQUEST: + GameMessages::HandleBBBSaveRequest(inStream, entity, sysAddr); + break; - case GAME_MSG_CONTROL_BEHAVIOR: - GameMessages::HandleControlBehaviors(inStream, entity, sysAddr); - break; + case GAME_MSG_CONTROL_BEHAVIOR: + GameMessages::HandleControlBehaviors(inStream, entity, sysAddr); + break; - case GAME_MSG_PROPERTY_ENTRANCE_SYNC: - GameMessages::HandlePropertyEntranceSync(inStream, entity, sysAddr); - break; + case GAME_MSG_PROPERTY_ENTRANCE_SYNC: + GameMessages::HandlePropertyEntranceSync(inStream, entity, sysAddr); + break; - case GAME_MSG_ENTER_PROPERTY1: - GameMessages::HandleEnterProperty(inStream, entity, sysAddr); - break; + case GAME_MSG_ENTER_PROPERTY1: + GameMessages::HandleEnterProperty(inStream, entity, sysAddr); + break; - case GAME_MSG_ZONE_PROPERTY_MODEL_ROTATED: - EntityManager::Instance()->GetZoneControlEntity()->OnZonePropertyModelRotated(usr->GetLastUsedChar()->GetEntity()); - break; + case GAME_MSG_ZONE_PROPERTY_MODEL_ROTATED: + EntityManager::Instance()->GetZoneControlEntity()->OnZonePropertyModelRotated(usr->GetLastUsedChar()->GetEntity()); + break; - case GAME_MSG_UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK: - GameMessages::HandleUpdatePropertyOrModelForFilterCheck(inStream, entity, sysAddr); - break; + case GAME_MSG_UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK: + GameMessages::HandleUpdatePropertyOrModelForFilterCheck(inStream, entity, sysAddr); + break; - case GAME_MSG_SET_PROPERTY_ACCESS: - GameMessages::HandleSetPropertyAccess(inStream, entity, sysAddr); - break; + case GAME_MSG_SET_PROPERTY_ACCESS: + GameMessages::HandleSetPropertyAccess(inStream, entity, sysAddr); + break; // Racing - case GAME_MSG_MODULE_ASSEMBLY_QUERY_DATA: - GameMessages::HandleModuleAssemblyQueryData(inStream, entity, sysAddr); - break; + case GAME_MSG_MODULE_ASSEMBLY_QUERY_DATA: + GameMessages::HandleModuleAssemblyQueryData(inStream, entity, sysAddr); + break; - case GAME_MSG_ACKNOWLEDGE_POSSESSION: - GameMessages::HandleAcknowledgePossession(inStream, entity, sysAddr); - break; + case GAME_MSG_ACKNOWLEDGE_POSSESSION: + GameMessages::HandleAcknowledgePossession(inStream, entity, sysAddr); + break; - case GAME_MSG_VEHICLE_SET_WHEEL_LOCK_STATE: - GameMessages::HandleVehicleSetWheelLockState(inStream, entity, sysAddr); - break; + case GAME_MSG_VEHICLE_SET_WHEEL_LOCK_STATE: + GameMessages::HandleVehicleSetWheelLockState(inStream, entity, sysAddr); + break; - case GAME_MSG_MODULAR_ASSEMBLY_NIF_COMPLETED: - GameMessages::HandleModularAssemblyNIFCompleted(inStream, entity, sysAddr); - break; + case GAME_MSG_MODULAR_ASSEMBLY_NIF_COMPLETED: + GameMessages::HandleModularAssemblyNIFCompleted(inStream, entity, sysAddr); + break; - case GAME_MSG_RACING_CLIENT_READY: - GameMessages::HandleRacingClientReady(inStream, entity, sysAddr); - break; + case GAME_MSG_RACING_CLIENT_READY: + GameMessages::HandleRacingClientReady(inStream, entity, sysAddr); + break; - case GAME_MSG_REQUEST_DIE: - GameMessages::HandleRequestDie(inStream, entity, sysAddr); - break; + case GAME_MSG_REQUEST_DIE: + GameMessages::HandleRequestDie(inStream, entity, sysAddr); + break; - case GAME_MSG_VEHICLE_NOTIFY_SERVER_ADD_PASSIVE_BOOST_ACTION: - GameMessages::HandleVehicleNotifyServerAddPassiveBoostAction(inStream, entity, sysAddr); - break; + case GAME_MSG_VEHICLE_NOTIFY_SERVER_ADD_PASSIVE_BOOST_ACTION: + GameMessages::HandleVehicleNotifyServerAddPassiveBoostAction(inStream, entity, sysAddr); + break; - case GAME_MSG_VEHICLE_NOTIFY_SERVER_REMOVE_PASSIVE_BOOST_ACTION: - GameMessages::HandleVehicleNotifyServerRemovePassiveBoostAction(inStream, entity, sysAddr); - break; + case GAME_MSG_VEHICLE_NOTIFY_SERVER_REMOVE_PASSIVE_BOOST_ACTION: + GameMessages::HandleVehicleNotifyServerRemovePassiveBoostAction(inStream, entity, sysAddr); + break; - case GAME_MSG_RACING_PLAYER_INFO_RESET_FINISHED: - GameMessages::HandleRacingPlayerInfoResetFinished(inStream, entity, sysAddr); - break; + case GAME_MSG_RACING_PLAYER_INFO_RESET_FINISHED: + GameMessages::HandleRacingPlayerInfoResetFinished(inStream, entity, sysAddr); + break; - case GAME_MSG_VEHICLE_NOTIFY_HIT_IMAGINATION_SERVER: - GameMessages::HandleVehicleNotifyHitImaginationServer(inStream, entity, sysAddr); - break; - case GAME_MSG_UPDATE_PROPERTY_PERFORMANCE_COST: - GameMessages::HandleUpdatePropertyPerformanceCost(inStream, entity, sysAddr); - break; + case GAME_MSG_VEHICLE_NOTIFY_HIT_IMAGINATION_SERVER: + GameMessages::HandleVehicleNotifyHitImaginationServer(inStream, entity, sysAddr); + break; + case GAME_MSG_UPDATE_PROPERTY_PERFORMANCE_COST: + GameMessages::HandleUpdatePropertyPerformanceCost(inStream, entity, sysAddr); + break; // SG - case GAME_MSG_UPDATE_SHOOTING_GALLERY_ROTATION: - GameMessages::HandleUpdateShootingGalleryRotation(inStream, entity, sysAddr); - break; + case GAME_MSG_UPDATE_SHOOTING_GALLERY_ROTATION: + GameMessages::HandleUpdateShootingGalleryRotation(inStream, entity, sysAddr); + break; // NT - case GAME_MSG_REQUEST_MOVE_ITEM_BETWEEN_INVENTORY_TYPES: - GameMessages::HandleRequestMoveItemBetweenInventoryTypes(inStream, entity, sysAddr); - break; + case GAME_MSG_REQUEST_MOVE_ITEM_BETWEEN_INVENTORY_TYPES: + GameMessages::HandleRequestMoveItemBetweenInventoryTypes(inStream, entity, sysAddr); + break; - case GAME_MSG_TOGGLE_GHOST_REFERENCE_OVERRIDE: - GameMessages::HandleToggleGhostReferenceOverride(inStream, entity, sysAddr); - break; + case GAME_MSG_TOGGLE_GHOST_REFERENCE_OVERRIDE: + GameMessages::HandleToggleGhostReferenceOverride(inStream, entity, sysAddr); + break; - case GAME_MSG_SET_GHOST_REFERENCE_POSITION: - GameMessages::HandleSetGhostReferencePosition(inStream, entity, sysAddr); - break; + case GAME_MSG_SET_GHOST_REFERENCE_POSITION: + GameMessages::HandleSetGhostReferencePosition(inStream, entity, sysAddr); + break; - case GAME_MSG_READY_FOR_UPDATES: - //We don't really care about this message, as it's simply here to inform us that the client is done loading an object. - //In the event we _do_ send an update to an object that hasn't finished loading, the client will handle it anyway. - break; + case GAME_MSG_READY_FOR_UPDATES: + //We don't really care about this message, as it's simply here to inform us that the client is done loading an object. + //In the event we _do_ send an update to an object that hasn't finished loading, the client will handle it anyway. + break; - case GAME_MSG_REPORT_BUG: - GameMessages::HandleReportBug(inStream, entity); - break; + case GAME_MSG_REPORT_BUG: + GameMessages::HandleReportBug(inStream, entity); + break; - case GAME_MSG_CLIENT_RAIL_MOVEMENT_READY: - GameMessages::HandleClientRailMovementReady(inStream, entity, sysAddr); - break; + case GAME_MSG_CLIENT_RAIL_MOVEMENT_READY: + GameMessages::HandleClientRailMovementReady(inStream, entity, sysAddr); + break; - case GAME_MSG_CANCEL_RAIL_MOVEMENT: - GameMessages::HandleCancelRailMovement(inStream, entity, sysAddr); - break; + case GAME_MSG_CANCEL_RAIL_MOVEMENT: + GameMessages::HandleCancelRailMovement(inStream, entity, sysAddr); + break; - case GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION: - GameMessages::HandlePlayerRailArrivedNotification(inStream, entity, sysAddr); - break; + case GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION: + GameMessages::HandlePlayerRailArrivedNotification(inStream, entity, sysAddr); + break; - case GAME_MSG_CINEMATIC_UPDATE: - GameMessages::HandleCinematicUpdate(inStream, entity, sysAddr); - break; + case GAME_MSG_CINEMATIC_UPDATE: + GameMessages::HandleCinematicUpdate(inStream, entity, sysAddr); + break; - case GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC: - GameMessages::HandleModifyPlayerZoneStatistic(inStream, entity); - break; + case GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC: + GameMessages::HandleModifyPlayerZoneStatistic(inStream, entity); + break; - case GAME_MSG_UPDATE_PLAYER_STATISTIC: - GameMessages::HandleUpdatePlayerStatistic(inStream, entity); - break; + case GAME_MSG_UPDATE_PLAYER_STATISTIC: + GameMessages::HandleUpdatePlayerStatistic(inStream, entity); + break; - default: - //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X", messageID); - break; + default: + //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X", messageID); + break; } } diff --git a/dGame/dGameMessages/GameMessageHandler.h b/dGame/dGameMessages/GameMessageHandler.h index 0d14dc5b..063e97f6 100644 --- a/dGame/dGameMessages/GameMessageHandler.h +++ b/dGame/dGameMessages/GameMessageHandler.h @@ -22,7 +22,7 @@ #include "../dDatabase/CDClientDatabase.h" namespace GameMessageHandler { - void HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, GAME_MSG messageID); + void HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, GAME_MSG messageID); }; #endif // GAMEMESSAGEHANDLER_H diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 66d71ca1..f4546416 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -70,9 +70,9 @@ void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_FIRE_EVENT_CLIENT_SIDE); //bitStream.Write(args); @@ -93,8 +93,8 @@ void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const Syste void GameMessages::SendTeleport(const LWOOBJID& objectID, const NiPoint3& pos, const NiQuaternion& rot, const SystemAddress& sysAddr, bool bSetRotation, bool noGravTeleport) { CBITSTREAM - CMSGHEADER - bitStream.Write(objectID); + CMSGHEADER + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_TELEPORT); bool bIgnoreY = (pos.y == 0.0f); @@ -170,9 +170,9 @@ void GameMessages::SendPlayerReady(Entity* entity, const SystemAddress& sysAddr) SEND_PACKET; } -void GameMessages::SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptRespawn, const SystemAddress &sysAddr) { +void GameMessages::SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptRespawn, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER; + CMSGHEADER; bitStream.Write(entityID); bitStream.Write(GAME_MSG::GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN); @@ -183,9 +183,9 @@ void GameMessages::SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptR void GameMessages::SendInvalidZoneTransferList(Entity* entity, const SystemAddress& sysAddr, const std::u16string& feedbackURL, const std::u16string& invalidMapTransferList, bool feedbackOnExit, bool feedbackOnInvalidTransfer) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_INVALID_ZONE_TRANSFER_LIST); uint32_t CustomerFeedbackURLLength = feedbackURL.size(); @@ -206,12 +206,11 @@ void GameMessages::SendInvalidZoneTransferList(Entity* entity, const SystemAddre SEND_PACKET } -void GameMessages::SendKnockback(const LWOOBJID& objectID, const LWOOBJID& caster, const LWOOBJID& originator, int knockBackTimeMS, const NiPoint3& vector) -{ +void GameMessages::SendKnockback(const LWOOBJID& objectID, const LWOOBJID& caster, const LWOOBJID& originator, int knockBackTimeMS, const NiPoint3& vector) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG_KNOCKBACK); bool casterFlag = caster != LWOOBJID_EMPTY; @@ -245,9 +244,9 @@ void GameMessages::SendStartArrangingWithItem( int targetTYPE ) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_START_ARRANGING_WITH_ITEM); bitStream.Write(bFirstTime); @@ -267,11 +266,11 @@ void GameMessages::SendStartArrangingWithItem( } void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, const SystemAddress& sysAddr, - bool bAllowCyclingWhileDeadOnly, eCyclingMode cyclingMode) { + bool bAllowCyclingWhileDeadOnly, eCyclingMode cyclingMode) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG_PLAYER_SET_CAMERA_CYCLING_MODE); bitStream.Write(bAllowCyclingWhileDeadOnly); @@ -286,9 +285,9 @@ void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, cons void GameMessages::SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& sysAddr, std::string audioGUID) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY_ND_AUDIO_EMITTER); bitStream.Write0(); bitStream.Write0(); @@ -324,15 +323,14 @@ void GameMessages::SendStartPathing(Entity* entity) { } void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAddr, bool bStopAtDesiredWaypoint, - int iIndex, int iDesiredWaypointIndex, int nextIndex, - MovementPlatformState movementState) { + int iIndex, int iDesiredWaypointIndex, int nextIndex, + MovementPlatformState movementState) { CBITSTREAM - CMSGHEADER + CMSGHEADER - const auto lot = entity->GetLOT(); + const auto lot = entity->GetLOT(); - if (lot == 12341 || lot == 5027 || lot == 5028 || lot == 14335 || lot == 14447 || lot == 14449) - { + if (lot == 12341 || lot == 5027 || lot == 5028 || lot == 14335 || lot == 14447 || lot == 14449) { iDesiredWaypointIndex = 0; iIndex = 0; nextIndex = 0; @@ -380,24 +378,24 @@ void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAd void GameMessages::SendRestoreToPostLoadStats(Entity* entity, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER - bitStream.Write(entity->GetObjectID()); + CMSGHEADER + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_RESTORE_TO_POST_LOAD_STATS); SEND_PACKET } void GameMessages::SendServerDoneLoadingAllObjects(Entity* entity, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER - bitStream.Write(entity->GetObjectID()); + CMSGHEADER + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_SERVER_DONE_LOADING_ALL_OBJECTS); SEND_PACKET } void GameMessages::SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level) { CBITSTREAM - CMSGHEADER - bitStream.Write(objectID); + CMSGHEADER + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_UPDATE_CHAT_MODE); bitStream.Write(level); SEND_PACKET_BROADCAST @@ -405,8 +403,8 @@ void GameMessages::SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level) { void GameMessages::SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level) { CBITSTREAM - CMSGHEADER - bitStream.Write(objectID); + CMSGHEADER + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_SET_GM_LEVEL); bitStream.Write1(); bitStream.Write(level); @@ -415,9 +413,9 @@ void GameMessages::SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level) void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const SystemAddress& sysAddr, Item* item, const LWOOBJID& objectID, bool showFlyingLoot, int itemCount, LWOOBJID subKey, eLootSourceType lootSourceType) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(static_cast(GAME_MSG_ADD_ITEM_TO_INVENTORY_CLIENT_SYNC)); bitStream.Write(item->GetBound()); bitStream.Write(item->GetInfo().isBOE); @@ -429,8 +427,7 @@ void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const System auto config = item->GetConfig(); - for (auto* data : config) - { + for (auto* data : config) { extraInfo.name += GeneralUtils::ASCIIToUTF16(data->GetString()) + u","; } @@ -475,9 +472,9 @@ void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const System void GameMessages::SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFlagID, bool bFlag, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_NOTIFY_CLIENT_FLAG_CHANGE); bitStream.Write(bFlag); bitStream.Write(iFlagID); @@ -485,17 +482,16 @@ void GameMessages::SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFla SEND_PACKET } -void GameMessages::SendChangeObjectWorldState(const LWOOBJID& objectID, int state, const SystemAddress& sysAddr) -{ +void GameMessages::SendChangeObjectWorldState(const LWOOBJID& objectID, int state, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_CHANGE_OBJECT_WORLD_STATE); bitStream.Write(state); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST - SEND_PACKET + SEND_PACKET } void GameMessages::SendOfferMission(const LWOOBJID& entity, const SystemAddress& sysAddr, int32_t missionID, const LWOOBJID& offererID) { @@ -506,9 +502,9 @@ void GameMessages::SendOfferMission(const LWOOBJID& entity, const SystemAddress& //Why is it like this? Because LU isn't just a clown, it's the entire circus. CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(offererID); + bitStream.Write(offererID); bitStream.Write(uint16_t(GAME_MSG_OFFER_MISSION)); bitStream.Write(missionID); bitStream.Write(offererID); @@ -530,9 +526,9 @@ void GameMessages::SendOfferMission(const LWOOBJID& entity, const SystemAddress& void GameMessages::SendNotifyMission(Entity* entity, const SystemAddress& sysAddr, int missionID, int missionState, bool sendingRewards) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_NOTIFY_MISSION)); bitStream.Write(missionID); bitStream.Write(missionState); @@ -543,9 +539,9 @@ void GameMessages::SendNotifyMission(Entity* entity, const SystemAddress& sysAdd void GameMessages::SendNotifyMissionTask(Entity* entity, const SystemAddress& sysAddr, int missionID, int taskMask, std::vector updates) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_NOTIFY_MISSION_TASK); bitStream.Write(missionID); @@ -561,9 +557,9 @@ void GameMessages::SendNotifyMissionTask(Entity* entity, const SystemAddress& sy void GameMessages::SendModifyLEGOScore(Entity* entity, const SystemAddress& sysAddr, int64_t score, eLootSourceType sourceType) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_MODIFY_LEGO_SCORE); bitStream.Write(score); @@ -575,9 +571,9 @@ void GameMessages::SendModifyLEGOScore(Entity* entity, const SystemAddress& sysA void GameMessages::SendUIMessageServerToSingleClient(Entity* entity, const SystemAddress& sysAddr, const std::string& message, NDGFxValue args) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_UI_MESSAGE_SERVER_TO_SINGLE_CLIENT); bitStream.Write(args); @@ -610,12 +606,11 @@ void GameMessages::SendUIMessageServerToAllClients(const std::string& message, N SEND_PACKET_BROADCAST; } -void GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(Entity* entity, std::u16string effectName, const LWOOBJID& fromObjectID, float radius) -{ +void GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(Entity* entity, std::u16string effectName, const LWOOBJID& fromObjectID, float radius) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY_EMBEDDED_EFFECT_ON_ALL_CLIENTS_NEAR_OBJECT); bitStream.Write(static_cast(effectName.length())); @@ -668,9 +663,9 @@ void GameMessages::SendPlayFXEffect(const LWOOBJID& entity, int32_t effectID, co void GameMessages::SendStopFXEffect(Entity* entity, bool killImmediate, std::string name) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_STOP_FX_EFFECT); bitStream.Write(killImmediate); @@ -682,9 +677,9 @@ void GameMessages::SendStopFXEffect(Entity* entity, bool killImmediate, std::str void GameMessages::SendBroadcastTextToChatbox(Entity* entity, const SystemAddress& sysAddr, const std::u16string& attrs, const std::u16string& wsText) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG::GAME_MSG_BROADCAST_TEXT_TO_CHATBOX); LWONameValue attribs; @@ -708,9 +703,9 @@ void GameMessages::SendBroadcastTextToChatbox(Entity* entity, const SystemAddres void GameMessages::SendSetCurrency(Entity* entity, int64_t currency, int lootType, const LWOOBJID& sourceID, const LOT& sourceLOT, int sourceTradeID, bool overrideCurrent, eLootSourceType sourceType) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_CURRENCY)); bitStream.Write(currency); @@ -736,12 +731,11 @@ void GameMessages::SendSetCurrency(Entity* entity, int64_t currency, int lootTyp SEND_PACKET } -void GameMessages::SendRebuildNotifyState(Entity* entity, int prevState, int state, const LWOOBJID& playerID) -{ +void GameMessages::SendRebuildNotifyState(Entity* entity, int prevState, int state, const LWOOBJID& playerID) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_REBUILD_NOTIFY_STATE); bitStream.Write(prevState); @@ -751,12 +745,11 @@ void GameMessages::SendRebuildNotifyState(Entity* entity, int prevState, int sta SEND_PACKET_BROADCAST } -void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, bool success, int failReason, float duration, const LWOOBJID& playerID) -{ +void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, bool success, int failReason, float duration, const LWOOBJID& playerID) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_ENABLE_REBUILD); bitStream.Write(enable); @@ -774,9 +767,9 @@ void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, boo void GameMessages::SendTerminateInteraction(const LWOOBJID& objectID, eTerminateType type, const LWOOBJID& terminator) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_TERMINATE_INTERACTION); bitStream.Write(terminator); @@ -785,12 +778,11 @@ void GameMessages::SendTerminateInteraction(const LWOOBJID& objectID, eTerminate SEND_PACKET_BROADCAST } -void GameMessages::SendDieNoImplCode(Entity* entity, const LWOOBJID& killerID, const LWOOBJID& lootOwnerID, eKillType killType, std::u16string deathType, float directionRelative_AngleY, float directionRelative_AngleXZ, float directionRelative_Force, bool bClientDeath, bool bSpawnLoot) -{ +void GameMessages::SendDieNoImplCode(Entity* entity, const LWOOBJID& killerID, const LWOOBJID& lootOwnerID, eKillType killType, std::u16string deathType, float directionRelative_AngleY, float directionRelative_AngleXZ, float directionRelative_Force, bool bClientDeath, bool bSpawnLoot) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_DIE)); bitStream.Write(bClientDeath); bitStream.Write(bSpawnLoot); @@ -847,9 +839,9 @@ void GameMessages::SendDie(Entity* entity, const LWOOBJID& killerID, const LWOOB void GameMessages::SendSetInventorySize(Entity* entity, int invType, int size) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_INVENTORY_SIZE)); bitStream.Write(invType); bitStream.Write(size); @@ -858,12 +850,11 @@ void GameMessages::SendSetInventorySize(Entity* entity, int invType, int size) { SEND_PACKET } -void GameMessages::SendSetEmoteLockState(Entity* entity, bool bLock, int emoteID) -{ +void GameMessages::SendSetEmoteLockState(Entity* entity, bool bLock, int emoteID) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_EMOTE_LOCK_STATE)); bitStream.Write(bLock); bitStream.Write(emoteID); @@ -882,9 +873,9 @@ void GameMessages::SendSetJetPackMode(Entity* entity, bool use, bool bypassCheck */ CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_JET_PACK_MODE)); bitStream.Write(bypassChecks); @@ -938,12 +929,11 @@ void GameMessages::SendResurrect(Entity* entity) { SEND_PACKET_BROADCAST; } -void GameMessages::SendStop2DAmbientSound(Entity* entity, bool force, std::string audioGUID, bool result) -{ +void GameMessages::SendStop2DAmbientSound(Entity* entity, bool force, std::string audioGUID, bool result) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY2_DAMBIENT_SOUND); uint32_t audioGUIDSize = audioGUID.size(); @@ -951,8 +941,7 @@ void GameMessages::SendStop2DAmbientSound(Entity* entity, bool force, std::strin bitStream.Write(force); bitStream.Write(audioGUIDSize); - for (uint32_t k = 0; k < audioGUIDSize; k++) - { + for (uint32_t k = 0; k < audioGUIDSize; k++) { bitStream.Write(static_cast(audioGUID[k])); } @@ -965,9 +954,9 @@ void GameMessages::SendStop2DAmbientSound(Entity* entity, bool force, std::strin void GameMessages::SendPlay2DAmbientSound(Entity* entity, std::string audioGUID, bool result) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY2_DAMBIENT_SOUND); uint32_t audioGUIDSize = audioGUID.size(); @@ -984,9 +973,9 @@ void GameMessages::SendPlay2DAmbientSound(Entity* entity, std::string audioGUID, void GameMessages::SendSetNetworkScriptVar(Entity* entity, const SystemAddress& sysAddr, std::string data) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_SET_NETWORK_SCRIPT_VAR); const auto u16Data = GeneralUtils::ASCIIToUTF16(data); @@ -1063,16 +1052,13 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, auto* team = TeamManager::Instance()->GetTeam(owner); // Currency and powerups should not sync - if (team != nullptr && currency == 0) - { + if (team != nullptr && currency == 0) { CDObjectsTable* objectsTable = CDClientManager::Instance()->GetTable("Objects"); const CDObjects& object = objectsTable->GetByID(item); - if (object.type != "Powerup") - { - for (const auto memberId : team->members) - { + if (object.type != "Powerup") { + for (const auto memberId : team->members) { auto* member = EntityManager::Instance()->GetEntity(memberId); if (member == nullptr) continue; @@ -1190,9 +1176,9 @@ void GameMessages::SendRemoveSkill(Entity* entity, TSkillID skillID) { void GameMessages::SendFinishArrangingWithItem(Entity* entity, const LWOOBJID& buildArea) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bool bFirstTime = true; + bool bFirstTime = true; const LWOOBJID& buildAreaID = buildArea; int newSourceBAG = 0; const LWOOBJID& newSourceID = LWOOBJID_EMPTY; @@ -1232,9 +1218,9 @@ void GameMessages::SendFinishArrangingWithItem(Entity* entity, const LWOOBJID& b void GameMessages::SendModularBuildEnd(Entity* entity) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_MODULAR_BUILD_END); SystemAddress sysAddr = entity->GetSystemAddress(); @@ -1243,9 +1229,9 @@ void GameMessages::SendModularBuildEnd(Entity* entity) { void GameMessages::SendVendorOpenWindow(Entity* entity, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_VENDOR_OPEN_WINDOW); SEND_PACKET @@ -1253,9 +1239,9 @@ void GameMessages::SendVendorOpenWindow(Entity* entity, const SystemAddress& sys void GameMessages::SendVendorStatusUpdate(Entity* entity, const SystemAddress& sysAddr, bool bUpdateOnly) { CBITSTREAM - CMSGHEADER + CMSGHEADER - VendorComponent* vendor = static_cast(entity->GetComponent(COMPONENT_TYPE_VENDOR)); + VendorComponent* vendor = static_cast(entity->GetComponent(COMPONENT_TYPE_VENDOR)); if (!vendor) return; std::map vendorItems = vendor->GetInventory(); @@ -1272,14 +1258,14 @@ void GameMessages::SendVendorStatusUpdate(Entity* entity, const SystemAddress& s } if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST - SEND_PACKET + SEND_PACKET } void GameMessages::SendVendorTransactionResult(Entity* entity, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - int iResult = 0x02; // success, seems to be the only relevant one + int iResult = 0x02; // success, seems to be the only relevant one bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_VENDOR_TRANSACTION_RESULT); @@ -1290,9 +1276,9 @@ void GameMessages::SendVendorTransactionResult(Entity* entity, const SystemAddre void GameMessages::SendRemoveItemFromInventory(Entity* entity, const SystemAddress& sysAddr, LWOOBJID objectID, LOT templateID, int inventoryType, uint32_t stackCount, uint32_t stackRemaining) { CBITSTREAM - CMSGHEADER - // this is used for a lot more than just inventory trashing (trades, vendors, etc.) but for now since it's just used for that, that's all im going to implement - bool bConfirmed = true; + CMSGHEADER + // this is used for a lot more than just inventory trashing (trades, vendors, etc.) but for now since it's just used for that, that's all im going to implement + bool bConfirmed = true; bool bDeleteItem = true; bool bOutSuccess = false; int eInvType = inventoryType; @@ -1337,9 +1323,9 @@ void GameMessages::SendRemoveItemFromInventory(Entity* entity, const SystemAddre void GameMessages::SendConsumeClientItem(Entity* entity, bool bSuccess, LWOOBJID item) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG_CONSUME_CLIENT_ITEM); bitStream.Write(bSuccess); bitStream.Write(item); @@ -1350,9 +1336,9 @@ void GameMessages::SendConsumeClientItem(Entity* entity, bool bSuccess, LWOOBJID void GameMessages::SendUseItemResult(Entity* entity, LOT templateID, bool useItemResult) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG_USE_ITEM_RESULT); bitStream.Write(templateID); bitStream.Write(useItemResult); @@ -1363,9 +1349,9 @@ void GameMessages::SendUseItemResult(Entity* entity, LOT templateID, bool useIte void GameMessages::SendUseItemRequirementsResponse(LWOOBJID objectID, const SystemAddress& sysAddr, UseItemResponse itemResponse) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_USE_ITEM_REQUIREMENTS_RESPONSE); bitStream.Write(itemResponse); @@ -1375,9 +1361,9 @@ void GameMessages::SendUseItemRequirementsResponse(LWOOBJID objectID, const Syst void GameMessages::SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, int srcInv, int dstInv, const LWOOBJID& iObjID) { CBITSTREAM - CMSGHEADER + CMSGHEADER - InventoryComponent* inv = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); if (!inv) return; Item* itemStack = inv->FindItemById(iObjID); @@ -1397,15 +1383,13 @@ void GameMessages::SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, i bitStream.Write(bOutSuccess); if (count == 1) { bitStream.Write0(); - } - else { + } else { bitStream.Write1(); bitStream.Write(count); } if (dstBag == 0) { bitStream.Write0(); - } - else { + } else { bitStream.Write1(); bitStream.Write(dstBag); } @@ -1413,8 +1397,7 @@ void GameMessages::SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, i bitStream.Write(showFlyingLoot); if (srcBag == 0) { bitStream.Write0(); - } - else { + } else { bitStream.Write1(); bitStream.Write(srcBag); } @@ -1428,9 +1411,9 @@ void GameMessages::SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, i void GameMessages::SendMatchResponse(Entity* entity, const SystemAddress& sysAddr, int response) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_MATCH_RESPONSE); bitStream.Write(response); @@ -1439,9 +1422,9 @@ void GameMessages::SendMatchResponse(Entity* entity, const SystemAddress& sysAdd void GameMessages::SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, std::string data, int type) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_MATCH_UPDATE); bitStream.Write(uint32_t(data.size())); for (char character : data) { @@ -1454,13 +1437,13 @@ void GameMessages::SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, } void GameMessages::SendRequestActivitySummaryLeaderboardData(const LWOOBJID& objectID, const LWOOBJID& targetID, - const SystemAddress& sysAddr, const int32_t& gameID, - const int32_t& queryType, const int32_t& resultsEnd, - const int32_t& resultsStart, bool weekly) { + const SystemAddress& sysAddr, const int32_t& gameID, + const int32_t& queryType, const int32_t& resultsEnd, + const int32_t& resultsStart, bool weekly) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA); bitStream.Write(gameID != 0); @@ -1491,9 +1474,9 @@ void GameMessages::SendRequestActivitySummaryLeaderboardData(const LWOOBJID& obj void GameMessages::SendActivityPause(LWOOBJID objectId, bool pause, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_ACTIVITY_PAUSE); bitStream.Write(pause); @@ -1503,9 +1486,9 @@ void GameMessages::SendActivityPause(LWOOBJID objectId, bool pause, const System void GameMessages::SendStartActivityTime(LWOOBJID objectId, float_t startTime, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_START_ACTIVITY_TIME); bitStream.Write(startTime); @@ -1515,9 +1498,9 @@ void GameMessages::SendStartActivityTime(LWOOBJID objectId, float_t startTime, c void GameMessages::SendRequestActivityEnter(LWOOBJID objectId, const SystemAddress& sysAddr, bool bStart, LWOOBJID userID) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_ENTER); bitStream.Write(bStart); bitStream.Write(userID); @@ -1528,9 +1511,9 @@ void GameMessages::SendRequestActivityEnter(LWOOBJID objectId, const SystemAddre void GameMessages::NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sysAddr, int level, bool sending_rewards) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG::GAME_MSG_NOTIFY_LEVEL_REWARDS); bitStream.Write(level); @@ -1540,19 +1523,18 @@ void GameMessages::NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sy } void GameMessages::SendSetShootingGalleryParams(LWOOBJID objectId, const SystemAddress& sysAddr, - float cameraFOV, - float cooldown, - float minDistance, - NiPoint3 muzzlePosOffset, - NiPoint3 playerPosOffset, - float projectileVelocity, - float timeLimit, - bool bUseLeaderboards) -{ + float cameraFOV, + float cooldown, + float minDistance, + NiPoint3 muzzlePosOffset, + NiPoint3 playerPosOffset, + float projectileVelocity, + float timeLimit, + bool bUseLeaderboards) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_SET_SHOOTING_GALLERY_PARAMS); /* bitStream.Write(cameraFOV); @@ -1580,15 +1562,14 @@ void GameMessages::SendSetShootingGalleryParams(LWOOBJID objectId, const SystemA void GameMessages::SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const SystemAddress& sysAddr, - float addTime, - int32_t score, - LWOOBJID target, - NiPoint3 targetPos) -{ + float addTime, + int32_t score, + LWOOBJID target, + NiPoint3 targetPos) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_CLIENT_SHOOTING_GALLERY_SCORE); bitStream.Write(addTime); bitStream.Write(score); @@ -1600,8 +1581,7 @@ void GameMessages::SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const } -void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { float angle = 0.0f; NiPoint3 facing = NiPoint3::ZERO; NiPoint3 muzzlePos = NiPoint3::ZERO; @@ -1612,15 +1592,15 @@ void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStre void GameMessages::HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, - const SystemAddress& sysAddr) { + const SystemAddress& sysAddr) { Game::logger->Log("AGS", "We got mail!"); } void GameMessages::SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA); bitStream.Write(leaderboard->GetGameID()); @@ -1653,7 +1633,7 @@ void GameMessages::HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream int32_t resultsStart = 0; if (inStream->ReadBit()) inStream->Read(resultsStart); - LWOOBJID target {}; + LWOOBJID target{}; inStream->Read(target); bool weekly = inStream->ReadBit(); @@ -1663,7 +1643,7 @@ void GameMessages::HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream delete leaderboard; } -void GameMessages::HandleActivityStateChangeRequest(RakNet::BitStream *inStream, Entity *entity) { +void GameMessages::HandleActivityStateChangeRequest(RakNet::BitStream* inStream, Entity* entity) { LWOOBJID objectID; inStream->Read(objectID); @@ -1725,8 +1705,8 @@ void GameMessages::SendStartCelebrationEffect(Entity* entity, const SystemAddres void GameMessages::SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForward, std::u16string pathName, - uint32_t pathStart, const SystemAddress& sysAddr, int32_t railActivatorComponentID, - LWOOBJID railActivatorObjectID) { + uint32_t pathStart, const SystemAddress& sysAddr, int32_t railActivatorComponentID, + LWOOBJID railActivatorObjectID) { CBITSTREAM; CMSGHEADER; @@ -1756,11 +1736,11 @@ void GameMessages::SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForw SEND_PACKET; } -void GameMessages::SendStartRailMovement(const LWOOBJID &objectID, std::u16string pathName, std::u16string startSound, - std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr, - uint32_t pathStart, bool goForward, bool damageImmune, bool noAggro, bool notifyActor, - bool showNameBillboard, bool cameraLocked, bool collisionEnabled, bool useDB, - int32_t railComponentID, LWOOBJID railActivatorObjectID) { +void GameMessages::SendStartRailMovement(const LWOOBJID& objectID, std::u16string pathName, std::u16string startSound, + std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr, + uint32_t pathStart, bool goForward, bool damageImmune, bool noAggro, bool notifyActor, + bool showNameBillboard, bool cameraLocked, bool collisionEnabled, bool useDB, + int32_t railComponentID, LWOOBJID railActivatorObjectID) { CBITSTREAM; CMSGHEADER; @@ -1848,8 +1828,8 @@ void GameMessages::SendNotifyClientObject(const LWOOBJID& objectID, std::u16stri } void GameMessages::SendNotifyClientZoneObject(const LWOOBJID& objectID, const std::u16string& name, int param1, - int param2, const LWOOBJID& paramObj, const std::string& paramStr, - const SystemAddress& sysAddr) { + int param2, const LWOOBJID& paramObj, const std::string& paramStr, + const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -1875,8 +1855,7 @@ void GameMessages::SendNotifyClientZoneObject(const LWOOBJID& objectID, const st } void GameMessages::SendNotifyClientFailedPrecondition(LWOOBJID objectId, const SystemAddress& sysAddr, - const std::u16string& failedReason, int preconditionID) -{ + const std::u16string& failedReason, int preconditionID) { CBITSTREAM; CMSGHEADER; @@ -1894,8 +1873,7 @@ void GameMessages::SendNotifyClientFailedPrecondition(LWOOBJID objectId, const S SEND_PACKET; } -void GameMessages::SendToggleGMInvis(LWOOBJID objectId, bool enabled, const SystemAddress& sysAddr) -{ +void GameMessages::SendToggleGMInvis(LWOOBJID objectId, bool enabled, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -1907,8 +1885,7 @@ void GameMessages::SendToggleGMInvis(LWOOBJID objectId, bool enabled, const Syst SEND_PACKET; } -void GameMessages::SendSetName(LWOOBJID objectID, std::u16string name, const SystemAddress& sysAddr) -{ +void GameMessages::SendSetName(LWOOBJID objectID, std::u16string name, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -1951,8 +1928,7 @@ void GameMessages::SendBBBSaveResponse(const LWOOBJID& objectId, const LWOOBJID& // Property -void GameMessages::SendOpenPropertyVendor(const LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendOpenPropertyVendor(const LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -1963,20 +1939,18 @@ void GameMessages::SendOpenPropertyVendor(const LWOOBJID objectId, const SystemA SEND_PACKET; } -void GameMessages::SendOpenPropertyManagment(const LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendOpenPropertyManagment(const LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(PropertyManagementComponent::Instance()->GetParent()->GetObjectID()); + bitStream.Write(PropertyManagementComponent::Instance()->GetParent()->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_OPEN_PROPERTY_MANAGEMENT); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; } -void GameMessages::SendDownloadPropertyData(const LWOOBJID objectId, const PropertyDataMessage& data, const SystemAddress& sysAddr) -{ +void GameMessages::SendDownloadPropertyData(const LWOOBJID objectId, const PropertyDataMessage& data, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -1991,8 +1965,7 @@ void GameMessages::SendDownloadPropertyData(const LWOOBJID objectId, const Prope SEND_PACKET; } -void GameMessages::SendPropertyRentalResponse(const LWOOBJID objectId, const LWOCLONEID cloneId, const uint32_t code, const LWOOBJID propertyId, const int64_t rentDue, const SystemAddress& sysAddr) -{ +void GameMessages::SendPropertyRentalResponse(const LWOOBJID objectId, const LWOCLONEID cloneId, const uint32_t code, const LWOOBJID propertyId, const int64_t rentDue, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -2023,8 +1996,7 @@ void GameMessages::SendLockNodeRotation(Entity* entity, std::string nodeName) { SEND_PACKET_BROADCAST; } -void GameMessages::SendSetBuildModeConfirmed(LWOOBJID objectId, const SystemAddress& sysAddr, bool start, bool warnVisitors, bool modePaused, int32_t modeValue, LWOOBJID playerId, NiPoint3 startPos) -{ +void GameMessages::SendSetBuildModeConfirmed(LWOOBJID objectId, const SystemAddress& sysAddr, bool start, bool warnVisitors, bool modePaused, int32_t modeValue, LWOOBJID playerId, NiPoint3 startPos) { CBITSTREAM; CMSGHEADER; @@ -2044,8 +2016,7 @@ void GameMessages::SendSetBuildModeConfirmed(LWOOBJID objectId, const SystemAddr SEND_PACKET; } -void GameMessages::SendGetModelsOnProperty(LWOOBJID objectId, std::map models, const SystemAddress& sysAddr) -{ +void GameMessages::SendGetModelsOnProperty(LWOOBJID objectId, std::map models, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -2054,8 +2025,7 @@ void GameMessages::SendGetModelsOnProperty(LWOOBJID objectId, std::map(models.size())); - for (const auto& pair : models) - { + for (const auto& pair : models) { bitStream.Write(pair.first); bitStream.Write(pair.second); } @@ -2066,8 +2036,7 @@ void GameMessages::SendGetModelsOnProperty(LWOOBJID objectId, std::mapSetPrivacyOption(static_cast(accessType)); } -void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool isProperty{}; LWOOBJID objectId{}; LWOOBJID playerId{}; @@ -2191,16 +2150,14 @@ void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* inStream->Read(worldId); inStream->Read(descriptionLength); - for (uint32_t i = 0; i < descriptionLength; ++i) - { + for (uint32_t i = 0; i < descriptionLength; ++i) { uint16_t character; inStream->Read(character); description.push_back(character); } inStream->Read(nameLength); - for (uint32_t i = 0; i < nameLength; ++i) - { + for (uint32_t i = 0; i < nameLength; ++i) { uint16_t character; inStream->Read(character); name.push_back(character); @@ -2209,8 +2166,7 @@ void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* PropertyManagementComponent::Instance()->UpdatePropertyDetails(GeneralUtils::UTF16ToWTF8(name), GeneralUtils::UTF16ToWTF8(description)); } -void GameMessages::HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { Game::logger->Log("HandleQueryPropertyData", "Entity (%i) requesting data", entity->GetLOT()); /* @@ -2238,8 +2194,7 @@ void GameMessages::HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* } } -void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool start{}; int32_t distanceType = -1; bool modePaused{}; @@ -2275,10 +2230,8 @@ void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entit SendSetBuildModeConfirmed(entity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS, start, false, modePaused, modeValue, playerId, startPosition); } -void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ - if (!entity->HasComponent(COMPONENT_TYPE_PROPERTY_MANAGEMENT)) - { +void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + if (!entity->HasComponent(COMPONENT_TYPE_PROPERTY_MANAGEMENT)) { return; } @@ -2331,22 +2284,19 @@ void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Enti ); } -void GameMessages::HandlePropertyEditorBegin(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePropertyEditorBegin(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { PropertyManagementComponent::Instance()->OnStartBuilding(); dZoneManager::Instance()->GetZoneControlObject()->OnZonePropertyEditBegin(); } -void GameMessages::HandlePropertyEditorEnd(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePropertyEditorEnd(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { PropertyManagementComponent::Instance()->OnFinishBuilding(); dZoneManager::Instance()->GetZoneControlObject()->OnZonePropertyEditEnd(); } -void GameMessages::HandlePropertyContentsFromClient(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePropertyContentsFromClient(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { User* user = UserManager::Instance()->GetUser(sysAddr); Entity* player = EntityManager::Instance()->GetEntity(user->GetLoggedInChar()); @@ -2354,13 +2304,11 @@ void GameMessages::HandlePropertyContentsFromClient(RakNet::BitStream* inStream, SendGetModelsOnProperty(player->GetObjectID(), PropertyManagementComponent::Instance()->GetModels(), UNASSIGNED_SYSTEM_ADDRESS); } -void GameMessages::HandlePropertyModelEquipped(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePropertyModelEquipped(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { dZoneManager::Instance()->GetZoneControlObject()->OnZonePropertyModelEquipped(); } -void GameMessages::HandlePlacePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePlacePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID model; inStream->Read(model); @@ -2368,8 +2316,7 @@ void GameMessages::HandlePlacePropertyModel(RakNet::BitStream* inStream, Entity* PropertyManagementComponent::Instance()->UpdateModelPosition(model, NiPoint3::ZERO, NiQuaternion::IDENTITY); } -void GameMessages::HandleUpdatePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleUpdatePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID model; NiPoint3 position; NiQuaternion rotation = NiQuaternion::IDENTITY; @@ -2377,26 +2324,22 @@ void GameMessages::HandleUpdatePropertyModel(RakNet::BitStream* inStream, Entity inStream->Read(model); inStream->Read(position); - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(rotation); } PropertyManagementComponent::Instance()->UpdateModelPosition(model, position, rotation); } -void GameMessages::HandleDeletePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleDeletePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID model = LWOOBJID_EMPTY; int deleteReason = 0; - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(model); } - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(deleteReason); } @@ -2420,9 +2363,9 @@ void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* void GameMessages::SendSmash(Entity* entity, float force, float ghostOpacity, LWOOBJID killerID, bool ignoreObjectVisibility) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_SMASH); bitStream.Write(ignoreObjectVisibility); @@ -2435,9 +2378,9 @@ void GameMessages::SendSmash(Entity* entity, float force, float ghostOpacity, LW void GameMessages::SendUnSmash(Entity* entity, LWOOBJID builderID, float duration) { CBITSTREAM - CMSGHEADER + CMSGHEADER - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_UNSMASH); bitStream.Write(builderID != LWOOBJID_EMPTY); @@ -2563,7 +2506,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent auto query = CDClientDatabase::CreatePreppedStmt( "SELECT id FROM PropertyTemplate WHERE mapID = ?;"); - query.bind(1, (int) zoneId); + query.bind(1, (int)zoneId); auto result = query.execQuery(); @@ -2707,13 +2650,12 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //there was an issue with builds not appearing since it was placed above ConstructEntity. PropertyManagementComponent::Instance()->AddModel(newEntity->GetObjectID(), newIDL); } + }); }); }); - }); } -void GameMessages::HandlePropertyEntranceSync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePropertyEntranceSync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool includeNullAddress{}; bool includeNullDescription{}; bool playerOwn{}; @@ -2735,8 +2677,7 @@ void GameMessages::HandlePropertyEntranceSync(RakNet::BitStream* inStream, Entit inStream->Read(startIndex); inStream->Read(filterTextLength); - for (auto i = 0u; i < filterTextLength; i++) - { + for (auto i = 0u; i < filterTextLength; i++) { char c; inStream->Read(c); filterText.push_back(c); @@ -2762,8 +2703,7 @@ void GameMessages::HandlePropertyEntranceSync(RakNet::BitStream* inStream, Entit ); } -void GameMessages::HandleEnterProperty(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleEnterProperty(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t index{}; bool returnToZone{}; @@ -2784,8 +2724,7 @@ void GameMessages::HandleEnterProperty(RakNet::BitStream* inStream, Entity* enti } } -void GameMessages::HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LOT lot; inStream->Read(lot); @@ -2798,10 +2737,9 @@ void GameMessages::HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* } void GameMessages::SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, - bool allowGhostUpdates, bool bCloseMultiInteract, bool bSendServerNotify, bool bUseControlledObjectForAudioListener, - int endBehavior, bool hidePlayerDuringCine, float leadIn, bool leavePlayerLockedWhenFinished, - bool lockPlayer, bool result, bool skipIfSamePath, float startTimeAdvance) -{ + bool allowGhostUpdates, bool bCloseMultiInteract, bool bSendServerNotify, bool bUseControlledObjectForAudioListener, + int endBehavior, bool hidePlayerDuringCine, float leadIn, bool leavePlayerLockedWhenFinished, + bool lockPlayer, bool result, bool skipIfSamePath, float startTimeAdvance) { CBITSTREAM; CMSGHEADER; @@ -2840,8 +2778,7 @@ void GameMessages::SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, } void GameMessages::SendEndCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, - float leadOut, bool leavePlayerLocked) -{ + float leadOut, bool leavePlayerLocked) { CBITSTREAM; CMSGHEADER; @@ -2862,7 +2799,7 @@ void GameMessages::SendEndCinematic(LWOOBJID objectId, std::u16string pathName, SEND_PACKET; } -void GameMessages::HandleCinematicUpdate(RakNet::BitStream *inStream, Entity *entity, const SystemAddress &sysAddr) { +void GameMessages::HandleCinematicUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { eCinematicEvent event; if (!inStream->ReadBit()) { event = STARTED; @@ -2908,14 +2845,13 @@ void GameMessages::HandleCinematicUpdate(RakNet::BitStream *inStream, Entity *en } void GameMessages::SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, const SystemAddress& sysAddr, - LWOOBJID originator, bool bCantAttack, bool bCantEquip, - bool bCantInteract, bool bCantJump, bool bCantMove, bool bCantTurn, - bool bCantUseItem, bool bDontTerminateInteract, bool bIgnoreImmunity, - bool bCantAttackOutChangeWasApplied, bool bCantEquipOutChangeWasApplied, - bool bCantInteractOutChangeWasApplied, bool bCantJumpOutChangeWasApplied, - bool bCantMoveOutChangeWasApplied, bool bCantTurnOutChangeWasApplied, - bool bCantUseItemOutChangeWasApplied) -{ + LWOOBJID originator, bool bCantAttack, bool bCantEquip, + bool bCantInteract, bool bCantJump, bool bCantMove, bool bCantTurn, + bool bCantUseItem, bool bDontTerminateInteract, bool bIgnoreImmunity, + bool bCantAttackOutChangeWasApplied, bool bCantEquipOutChangeWasApplied, + bool bCantInteractOutChangeWasApplied, bool bCantJumpOutChangeWasApplied, + bool bCantMoveOutChangeWasApplied, bool bCantTurnOutChangeWasApplied, + bool bCantUseItemOutChangeWasApplied) { CBITSTREAM; CMSGHEADER; @@ -2957,8 +2893,7 @@ void GameMessages::SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, } -void GameMessages::SendOrientToAngle(LWOOBJID objectId, bool bRelativeToCurrent, float fAngle, const SystemAddress& sysAddr) -{ +void GameMessages::SendOrientToAngle(LWOOBJID objectId, bool bRelativeToCurrent, float fAngle, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -2973,8 +2908,7 @@ void GameMessages::SendOrientToAngle(LWOOBJID objectId, bool bRelativeToCurrent, } -void GameMessages::SendAddRunSpeedModifier(LWOOBJID objectId, LWOOBJID caster, uint32_t modifier, const SystemAddress& sysAddr) -{ +void GameMessages::SendAddRunSpeedModifier(LWOOBJID objectId, LWOOBJID caster, uint32_t modifier, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -2991,8 +2925,7 @@ void GameMessages::SendAddRunSpeedModifier(LWOOBJID objectId, LWOOBJID caster, u SEND_PACKET; } -void GameMessages::SendRemoveRunSpeedModifier(LWOOBJID objectId, uint32_t modifier, const SystemAddress& sysAddr) -{ +void GameMessages::SendRemoveRunSpeedModifier(LWOOBJID objectId, uint32_t modifier, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3006,8 +2939,7 @@ void GameMessages::SendRemoveRunSpeedModifier(LWOOBJID objectId, uint32_t modifi SEND_PACKET; } -void GameMessages::SendPropertyEntranceBegin(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendPropertyEntranceBegin(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3018,8 +2950,7 @@ void GameMessages::SendPropertyEntranceBegin(LWOOBJID objectId, const SystemAddr SEND_PACKET; } -void GameMessages::SendPropertySelectQuery(LWOOBJID objectId, int32_t navOffset, bool thereAreMore, int32_t cloneId, bool hasFeaturedProperty, bool wasFriends, const std::vector& entries, const SystemAddress& sysAddr) -{ +void GameMessages::SendPropertySelectQuery(LWOOBJID objectId, int32_t navOffset, bool thereAreMore, int32_t cloneId, bool hasFeaturedProperty, bool wasFriends, const std::vector& entries, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3034,8 +2965,7 @@ void GameMessages::SendPropertySelectQuery(LWOOBJID objectId, int32_t navOffset, bitStream.Write(entries.size()); - for (auto& entry : entries) - { + for (auto& entry : entries) { entry.Serialize(bitStream); } @@ -3043,8 +2973,7 @@ void GameMessages::SendPropertySelectQuery(LWOOBJID objectId, int32_t navOffset, SEND_PACKET; } -void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std::u16string name, const SystemAddress& sysAddr, int param1, int param2) -{ +void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std::u16string name, const SystemAddress& sysAddr, int param1, int param2) { CBITSTREAM; CMSGHEADER; @@ -3053,8 +2982,7 @@ void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std bitStream.Write(objIDSender); bitStream.Write(static_cast(name.size())); - for (const auto character : name) - { + for (const auto character : name) { bitStream.Write(character); } @@ -3065,8 +2993,7 @@ void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std SEND_PACKET; } -void GameMessages::HandleVerifyAck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleVerifyAck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bDifferent; std::string sBitStream; uint32_t uiHandle = 0; @@ -3081,14 +3008,12 @@ void GameMessages::HandleVerifyAck(RakNet::BitStream* inStream, Entity* entity, sBitStream.push_back(character); } - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(uiHandle); } } -void GameMessages::SendTeamPickupItem(LWOOBJID objectId, LWOOBJID lootID, LWOOBJID lootOwnerID, const SystemAddress& sysAddr) -{ +void GameMessages::SendTeamPickupItem(LWOOBJID objectId, LWOOBJID lootID, LWOOBJID lootOwnerID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3104,8 +3029,7 @@ void GameMessages::SendTeamPickupItem(LWOOBJID objectId, LWOOBJID lootID, LWOOBJ //Trading: -void GameMessages::SendServerTradeInvite(LWOOBJID objectId, bool bNeedInvitePopUp, LWOOBJID i64Requestor, std::u16string wsName, const SystemAddress& sysAddr) -{ +void GameMessages::SendServerTradeInvite(LWOOBJID objectId, bool bNeedInvitePopUp, LWOOBJID i64Requestor, std::u16string wsName, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3115,8 +3039,7 @@ void GameMessages::SendServerTradeInvite(LWOOBJID objectId, bool bNeedInvitePopU bitStream.Write(bNeedInvitePopUp); bitStream.Write(i64Requestor); bitStream.Write(static_cast(wsName.size())); - for (const auto character : wsName) - { + for (const auto character : wsName) { bitStream.Write(character); } @@ -3124,8 +3047,7 @@ void GameMessages::SendServerTradeInvite(LWOOBJID objectId, bool bNeedInvitePopU SEND_PACKET; } -void GameMessages::SendServerTradeInitialReply(LWOOBJID objectId, LWOOBJID i64Invitee, int32_t resultType, std::u16string wsName, const SystemAddress& sysAddr) -{ +void GameMessages::SendServerTradeInitialReply(LWOOBJID objectId, LWOOBJID i64Invitee, int32_t resultType, std::u16string wsName, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3135,8 +3057,7 @@ void GameMessages::SendServerTradeInitialReply(LWOOBJID objectId, LWOOBJID i64In bitStream.Write(i64Invitee); bitStream.Write(resultType); bitStream.Write(static_cast(wsName.size())); - for (const auto character : wsName) - { + for (const auto character : wsName) { bitStream.Write(character); } @@ -3144,8 +3065,7 @@ void GameMessages::SendServerTradeInitialReply(LWOOBJID objectId, LWOOBJID i64In SEND_PACKET; } -void GameMessages::SendServerTradeFinalReply(LWOOBJID objectId, bool bResult, LWOOBJID i64Invitee, std::u16string wsName, const SystemAddress& sysAddr) -{ +void GameMessages::SendServerTradeFinalReply(LWOOBJID objectId, bool bResult, LWOOBJID i64Invitee, std::u16string wsName, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3155,8 +3075,7 @@ void GameMessages::SendServerTradeFinalReply(LWOOBJID objectId, bool bResult, LW bitStream.Write(bResult); bitStream.Write(i64Invitee); bitStream.Write(static_cast(wsName.size())); - for (const auto character : wsName) - { + for (const auto character : wsName) { bitStream.Write(character); } @@ -3164,8 +3083,7 @@ void GameMessages::SendServerTradeFinalReply(LWOOBJID objectId, bool bResult, LW SEND_PACKET; } -void GameMessages::SendServerTradeAccept(LWOOBJID objectId, bool bFirst, const SystemAddress& sysAddr) -{ +void GameMessages::SendServerTradeAccept(LWOOBJID objectId, bool bFirst, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3178,8 +3096,7 @@ void GameMessages::SendServerTradeAccept(LWOOBJID objectId, bool bFirst, const S SEND_PACKET; } -void GameMessages::SendServerTradeCancel(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendServerTradeCancel(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3190,8 +3107,7 @@ void GameMessages::SendServerTradeCancel(LWOOBJID objectId, const SystemAddress& SEND_PACKET; } -void GameMessages::SendServerTradeUpdate(LWOOBJID objectId, uint64_t coins, const std::vector& items, const SystemAddress& sysAddr) -{ +void GameMessages::SendServerTradeUpdate(LWOOBJID objectId, uint64_t coins, const std::vector& items, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3202,8 +3118,7 @@ void GameMessages::SendServerTradeUpdate(LWOOBJID objectId, uint64_t coins, cons bitStream.Write(coins); bitStream.Write(static_cast(items.size())); - for (const auto& item : items) - { + for (const auto& item : items) { bitStream.Write(item.itemId); bitStream.Write(item.itemId); @@ -3221,13 +3136,11 @@ void GameMessages::SendServerTradeUpdate(LWOOBJID objectId, uint64_t coins, cons SEND_PACKET; } -void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { // Check if the player has restricted trade access auto* character = entity->GetCharacter(); - if (character->HasPermission(PermissionMap::RestrictedTradeAccess)) - { + if (character->HasPermission(PermissionMap::RestrictedTradeAccess)) { // Send a message to the player ChatPackets::SendSystemMessage( sysAddr, @@ -3244,12 +3157,10 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* auto* invitee = EntityManager::Instance()->GetEntity(i64Invitee); - if (invitee != nullptr && invitee->IsPlayer()) - { + if (invitee != nullptr && invitee->IsPlayer()) { character = invitee->GetCharacter(); - if (character->HasPermission(PermissionMap::RestrictedTradeAccess)) - { + if (character->HasPermission(PermissionMap::RestrictedTradeAccess)) { // Send a message to the player ChatPackets::SendSystemMessage( sysAddr, @@ -3263,17 +3174,13 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); - if (trade != nullptr) - { - if (!trade->IsParticipant(i64Invitee)) - { + if (trade != nullptr) { + if (!trade->IsParticipant(i64Invitee)) { TradingManager::Instance()->CancelTrade(trade->GetTradeId()); TradingManager::Instance()->NewTrade(entity->GetObjectID(), i64Invitee); } - } - else - { + } else { TradingManager::Instance()->NewTrade(entity->GetObjectID(), i64Invitee); } @@ -3287,8 +3194,7 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* } } -void GameMessages::HandleClientTradeCancel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleClientTradeCancel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); if (trade == nullptr) return; @@ -3298,8 +3204,7 @@ void GameMessages::HandleClientTradeCancel(RakNet::BitStream* inStream, Entity* TradingManager::Instance()->CancelTrade(trade->GetTradeId()); } -void GameMessages::HandleClientTradeAccept(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleClientTradeAccept(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bFirst = inStream->ReadBit(); Game::logger->Log("GameMessages", "Trade accepted from (%llu) -> (%d)", entity->GetObjectID(), bFirst); @@ -3311,8 +3216,7 @@ void GameMessages::HandleClientTradeAccept(RakNet::BitStream* inStream, Entity* trade->SetAccepted(entity->GetObjectID(), bFirst); } -void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { uint64_t currency; uint32_t itemCount; @@ -3321,10 +3225,9 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* Game::logger->Log("GameMessages", "Trade update from (%llu) -> (%llu), (%i)", entity->GetObjectID(), currency, itemCount); - std::vector items {}; + std::vector items{}; - for (size_t i = 0; i < itemCount; i++) - { + for (size_t i = 0; i < itemCount; i++) { LWOOBJID itemId; LWOOBJID itemId2; @@ -3340,40 +3243,33 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* bool unknown4; inStream->Read(lot); - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(unknown1); } - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(unknown2); } - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(slot); } - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(unknown3); } if (inStream->ReadBit()) // No { inStream->Read(ldfSize); bool compressed = inStream->ReadBit(); - if (compressed) - { + if (compressed) { uint32_t ldfCompressedSize = 0; inStream->Read(ldfCompressedSize); inStream->IgnoreBytes(ldfCompressedSize); - } - else - { + } else { inStream->IgnoreBytes(ldfSize); } } unknown4 = inStream->ReadBit(); - items.push_back({itemId, lot, unknown2}); + items.push_back({ itemId, lot, unknown2 }); Game::logger->Log("GameMessages", "Trade item from (%llu) -> (%llu)/(%llu), (%i), (%llu), (%i), (%i)", entity->GetObjectID(), itemId, itemId2, lot, unknown1, unknown2, unknown3); } @@ -3389,8 +3285,7 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* //Pets: -void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId, LWOOBJID playerTamingId, bool bForceTeleport, uint32_t notifyType, NiPoint3 petsDestPos, NiPoint3 telePos, NiQuaternion teleRot, const SystemAddress& sysAddr) -{ +void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId, LWOOBJID playerTamingId, bool bForceTeleport, uint32_t notifyType, NiPoint3 petsDestPos, NiPoint3 telePos, NiQuaternion teleRot, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3412,8 +3307,7 @@ void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId SEND_PACKET; } -void GameMessages::SendNotifyTamingModelLoadedOnServer(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendNotifyTamingModelLoadedOnServer(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3424,8 +3318,7 @@ void GameMessages::SendNotifyTamingModelLoadedOnServer(LWOOBJID objectId, const SEND_PACKET; } -void GameMessages::SendNotifyPetTamingPuzzleSelected(LWOOBJID objectId, std::vector& bricks, const SystemAddress& sysAddr) -{ +void GameMessages::SendNotifyPetTamingPuzzleSelected(LWOOBJID objectId, std::vector& bricks, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3433,8 +3326,7 @@ void GameMessages::SendNotifyPetTamingPuzzleSelected(LWOOBJID objectId, std::vec bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_PET_TAMING_PUZZLE_SELECTED); bitStream.Write(static_cast(bricks.size())); - for (const auto& brick : bricks) - { + for (const auto& brick : bricks) { bitStream.Write(brick.designerID); bitStream.Write(brick.materialID); } @@ -3443,8 +3335,7 @@ void GameMessages::SendNotifyPetTamingPuzzleSelected(LWOOBJID objectId, std::vec SEND_PACKET; } -void GameMessages::SendPetTamingTryBuildResult(LWOOBJID objectId, bool bSuccess, int32_t iNumCorrect, const SystemAddress& sysAddr) -{ +void GameMessages::SendPetTamingTryBuildResult(LWOOBJID objectId, bool bSuccess, int32_t iNumCorrect, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3459,8 +3350,7 @@ void GameMessages::SendPetTamingTryBuildResult(LWOOBJID objectId, bool bSuccess, SEND_PACKET; } -void GameMessages::SendPetResponse(LWOOBJID objectId, LWOOBJID objIDPet, int32_t iPetCommandType, int32_t iResponse, int32_t iTypeID, const SystemAddress& sysAddr) -{ +void GameMessages::SendPetResponse(LWOOBJID objectId, LWOOBJID objIDPet, int32_t iPetCommandType, int32_t iResponse, int32_t iTypeID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3476,8 +3366,7 @@ void GameMessages::SendPetResponse(LWOOBJID objectId, LWOOBJID objIDPet, int32_t SEND_PACKET; } -void GameMessages::SendAddPetToPlayer(LWOOBJID objectId, int32_t iElementalType, std::u16string name, LWOOBJID petDBID, LOT petLOT, const SystemAddress& sysAddr) -{ +void GameMessages::SendAddPetToPlayer(LWOOBJID objectId, int32_t iElementalType, std::u16string name, LWOOBJID petDBID, LOT petLOT, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3486,8 +3375,7 @@ void GameMessages::SendAddPetToPlayer(LWOOBJID objectId, int32_t iElementalType, bitStream.Write(iElementalType); bitStream.Write(static_cast(name.size())); - for (const auto character : name) - { + for (const auto character : name) { bitStream.Write(character); } @@ -3498,8 +3386,7 @@ void GameMessages::SendAddPetToPlayer(LWOOBJID objectId, int32_t iElementalType, SEND_PACKET; } -void GameMessages::SendRegisterPetID(LWOOBJID objectId, LWOOBJID objID, const SystemAddress& sysAddr) -{ +void GameMessages::SendRegisterPetID(LWOOBJID objectId, LWOOBJID objID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3512,8 +3399,7 @@ void GameMessages::SendRegisterPetID(LWOOBJID objectId, LWOOBJID objID, const Sy SEND_PACKET; } -void GameMessages::SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, const SystemAddress& sysAddr) -{ +void GameMessages::SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3526,8 +3412,7 @@ void GameMessages::SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, cons SEND_PACKET; } -void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, int32_t iType, LWOOBJID itemID, const SystemAddress& sysAddr) -{ +void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, int32_t iType, LWOOBJID itemID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3546,8 +3431,7 @@ void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive SEND_PACKET; } -void GameMessages::SendClientExitTamingMinigame(LWOOBJID objectId, bool bVoluntaryExit, const SystemAddress& sysAddr) -{ +void GameMessages::SendClientExitTamingMinigame(LWOOBJID objectId, bool bVoluntaryExit, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3560,8 +3444,7 @@ void GameMessages::SendClientExitTamingMinigame(LWOOBJID objectId, bool bVolunta SEND_PACKET; } -void GameMessages::SendShowPetActionButton(LWOOBJID objectId, int32_t buttonLabel, bool bShow, const SystemAddress& sysAddr) -{ +void GameMessages::SendShowPetActionButton(LWOOBJID objectId, int32_t buttonLabel, bool bShow, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3575,8 +3458,7 @@ void GameMessages::SendShowPetActionButton(LWOOBJID objectId, int32_t buttonLabe SEND_PACKET; } -void GameMessages::SendPlayEmote(LWOOBJID objectId, int32_t emoteID, LWOOBJID target, const SystemAddress& sysAddr) -{ +void GameMessages::SendPlayEmote(LWOOBJID objectId, int32_t emoteID, LWOOBJID target, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3591,8 +3473,7 @@ void GameMessages::SendPlayEmote(LWOOBJID objectId, int32_t emoteID, LWOOBJID ta } -void GameMessages::SendBouncerActiveStatus(LWOOBJID objectId, bool bActive, const SystemAddress& sysAddr) -{ +void GameMessages::SendBouncerActiveStatus(LWOOBJID objectId, bool bActive, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3606,8 +3487,7 @@ void GameMessages::SendBouncerActiveStatus(LWOOBJID objectId, bool bActive, cons } -void GameMessages::SendSetPetName(LWOOBJID objectId, std::u16string name, LWOOBJID petDBID, const SystemAddress& sysAddr) -{ +void GameMessages::SendSetPetName(LWOOBJID objectId, std::u16string name, LWOOBJID petDBID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3615,8 +3495,7 @@ void GameMessages::SendSetPetName(LWOOBJID objectId, std::u16string name, LWOOBJ bitStream.Write(GAME_MSG::GAME_MSG_SET_PET_NAME); bitStream.Write(static_cast(name.size())); - for (const auto character : name) - { + for (const auto character : name) { bitStream.Write(character); } @@ -3628,8 +3507,7 @@ void GameMessages::SendSetPetName(LWOOBJID objectId, std::u16string name, LWOOBJ } -void GameMessages::SendSetPetNameModerated(LWOOBJID objectId, LWOOBJID petDBID, int32_t nModerationStatus, const SystemAddress& sysAddr) -{ +void GameMessages::SendSetPetNameModerated(LWOOBJID objectId, LWOOBJID petDBID, int32_t nModerationStatus, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3646,8 +3524,7 @@ void GameMessages::SendSetPetNameModerated(LWOOBJID objectId, LWOOBJID petDBID, } -void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatus, std::u16string name, std::u16string ownerName, const SystemAddress& sysAddr) -{ +void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatus, std::u16string name, std::u16string ownerName, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3657,14 +3534,12 @@ void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatu bitStream.Write(moderationStatus); bitStream.Write(static_cast(name.size())); - for (const auto character : name) - { + for (const auto character : name) { bitStream.Write(character); } bitStream.Write(static_cast(ownerName.size())); - for (const auto character : ownerName) - { + for (const auto character : ownerName) { bitStream.Write(character); } @@ -3673,34 +3548,29 @@ void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatu } -void GameMessages::HandleClientExitTamingMinigame(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleClientExitTamingMinigame(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bVoluntaryExit = inStream->ReadBit(); auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } petComponent->ClientExitTamingMinigame(bVoluntaryExit); } -void GameMessages::HandleStartServerPetMinigameTimer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleStartServerPetMinigameTimer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } petComponent->StartTimer(); } -void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t brickCount; std::vector bricks; bool clientFailed; @@ -3709,8 +3579,7 @@ void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* bricks.reserve(brickCount); - for (uint32_t i = 0; i < brickCount; i++) - { + for (uint32_t i = 0; i < brickCount; i++) { Brick brick; inStream->Read(brick); @@ -3722,39 +3591,34 @@ void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } petComponent->TryBuild(bricks.size(), clientFailed); } -void GameMessages::HandleNotifyTamingBuildSuccess(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleNotifyTamingBuildSuccess(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { NiPoint3 position; inStream->Read(position); auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } petComponent->NotifyTamingBuildSuccess(position); } -void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t nameLength; std::u16string name; inStream->Read(nameLength); - for (size_t i = 0; i < nameLength; i++) - { + for (size_t i = 0; i < nameLength; i++) { char16_t character; inStream->Read(character); name.push_back(character); @@ -3762,12 +3626,10 @@ void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { petComponent = PetComponent::GetActivePet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } } @@ -3775,8 +3637,7 @@ void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* petComponent->RequestSetPetName(name); } -void GameMessages::HandleCommandPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleCommandPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { NiPoint3 genericPosInfo; LWOOBJID objIdSource; int32_t iPetCommandType; @@ -3791,39 +3652,32 @@ void GameMessages::HandleCommandPet(RakNet::BitStream* inStream, Entity* entity, auto* petComponent = entity->GetComponent(); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } petComponent->Command(genericPosInfo, objIdSource, iPetCommandType, iTypeID, overrideObey); } -void GameMessages::HandleDespawnPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleDespawnPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bDeletePet; bDeletePet = inStream->ReadBit(); auto* petComponent = PetComponent::GetActivePet(entity->GetObjectID()); - if (petComponent == nullptr) - { + if (petComponent == nullptr) { return; } - if (bDeletePet) - { + if (bDeletePet) { petComponent->Release(); - } - else - { + } else { petComponent->Deactivate(); } } -void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { int32_t iButton; uint32_t identifierLength; std::u16string identifier; @@ -3833,16 +3687,14 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* inStream->Read(iButton); inStream->Read(identifierLength); - for (size_t i = 0; i < identifierLength; i++) - { + for (size_t i = 0; i < identifierLength; i++) { char16_t character; inStream->Read(character); identifier.push_back(character); } inStream->Read(userDataLength); - for (size_t i = 0; i < userDataLength; i++) - { + for (size_t i = 0; i < userDataLength; i++) { char16_t character; inStream->Read(character); userData.push_back(character); @@ -3852,15 +3704,13 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* auto* user = UserManager::Instance()->GetUser(sysAddr); - if (user == nullptr) - { + if (user == nullptr) { return; } auto* userEntity = user->GetLastUsedChar()->GetEntity(); - if (userEntity == nullptr) - { + if (userEntity == nullptr) { return; } @@ -3868,26 +3718,22 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* auto* scriptedActivityComponent = entity->GetComponent(); - if (scriptedActivityComponent != nullptr) - { + if (scriptedActivityComponent != nullptr) { scriptedActivityComponent->HandleMessageBoxResponse(userEntity, GeneralUtils::UTF16ToWTF8(identifier)); } auto* racingControlComponent = entity->GetComponent(); - if (racingControlComponent != nullptr) - { + if (racingControlComponent != nullptr) { racingControlComponent->HandleMessageBoxResponse(userEntity, GeneralUtils::UTF16ToWTF8(identifier)); } - for (auto* shootingGallery : EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SHOOTING_GALLERY)) - { + for (auto* shootingGallery : EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SHOOTING_GALLERY)) { shootingGallery->OnMessageBoxResponse(userEntity, iButton, identifier, userData); } } -void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { int32_t iButton; uint32_t buttonIdentifierLength; std::u16string buttonIdentifier; @@ -3895,8 +3741,7 @@ void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* e std::u16string identifier; inStream->Read(buttonIdentifierLength); - for (size_t i = 0; i < buttonIdentifierLength; i++) - { + for (size_t i = 0; i < buttonIdentifierLength; i++) { char16_t character; inStream->Read(character); buttonIdentifier.push_back(character); @@ -3905,8 +3750,7 @@ void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* e inStream->Read(iButton); inStream->Read(identifierLength); - for (size_t i = 0; i < identifierLength; i++) - { + for (size_t i = 0; i < identifierLength; i++) { char16_t character; inStream->Read(character); identifier.push_back(character); @@ -3916,23 +3760,20 @@ void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* e auto* user = UserManager::Instance()->GetUser(sysAddr); - if (user == nullptr) - { + if (user == nullptr) { return; } auto* userEntity = user->GetLastUsedChar()->GetEntity(); - if (userEntity == nullptr) - { + if (userEntity == nullptr) { return; } entity->OnChoiceBoxResponse(userEntity, iButton, buttonIdentifier, identifier); } -void GameMessages::SendDisplayZoneSummary(LWOOBJID objectId, const SystemAddress& sysAddr, bool isPropertyMap, bool isZoneStart, LWOOBJID sender) -{ +void GameMessages::SendDisplayZoneSummary(LWOOBJID objectId, const SystemAddress& sysAddr, bool isPropertyMap, bool isZoneStart, LWOOBJID sender) { CBITSTREAM; CMSGHEADER; @@ -3950,8 +3791,7 @@ void GameMessages::SendDisplayZoneSummary(LWOOBJID objectId, const SystemAddress //UI -void GameMessages::SendNotifyNotEnoughInvSpace(LWOOBJID objectId, uint32_t freeSlotsNeeded, eInventoryType inventoryType, const SystemAddress& sysAddr) -{ +void GameMessages::SendNotifyNotEnoughInvSpace(LWOOBJID objectId, uint32_t freeSlotsNeeded, eInventoryType inventoryType, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3966,8 +3806,7 @@ void GameMessages::SendNotifyNotEnoughInvSpace(LWOOBJID objectId, uint32_t freeS SEND_PACKET; } -void GameMessages::SendDisplayMessageBox(LWOOBJID objectId, bool bShow, LWOOBJID callbackClient, const std::u16string& identifier, int32_t imageID, const std::u16string& text, const std::u16string& userData, const SystemAddress& sysAddr) -{ +void GameMessages::SendDisplayMessageBox(LWOOBJID objectId, bool bShow, LWOOBJID callbackClient, const std::u16string& identifier, int32_t imageID, const std::u16string& text, const std::u16string& userData, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3978,22 +3817,19 @@ void GameMessages::SendDisplayMessageBox(LWOOBJID objectId, bool bShow, LWOOBJID bitStream.Write(callbackClient); bitStream.Write(static_cast(identifier.size())); - for (const auto character : identifier) - { + for (const auto character : identifier) { bitStream.Write(character); } bitStream.Write(imageID); bitStream.Write(static_cast(text.size())); - for (const auto character : text) - { + for (const auto character : text) { bitStream.Write(character); } bitStream.Write(static_cast(userData.size())); - for (const auto character : userData) - { + for (const auto character : userData) { bitStream.Write(character); } @@ -4001,8 +3837,7 @@ void GameMessages::SendDisplayMessageBox(LWOOBJID objectId, bool bShow, LWOOBJID SEND_PACKET; } -void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string& text, const SystemAddress& sysAddr) -{ +void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string& text, const SystemAddress& sysAddr) { // GAME_MSG_DISPLAY_CHAT_BUBBLE CBITSTREAM; CMSGHEADER; @@ -4011,8 +3846,7 @@ void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string bitStream.Write(GAME_MSG::GAME_MSG_DISPLAY_CHAT_BUBBLE); bitStream.Write(static_cast(text.size())); - for (const auto character : text) - { + for (const auto character : text) { bitStream.Write(character); } @@ -4022,7 +3856,7 @@ void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string // Mounts -void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objectID, const SystemAddress& sysAddr){ +void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objectID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4034,7 +3868,7 @@ void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objec } -void GameMessages::HandleDismountComplete(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr){ +void GameMessages::HandleDismountComplete(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID objectId{}; inStream->Read(objectId); auto* mount = EntityManager::Instance()->GetEntity(objectId); @@ -4063,14 +3897,12 @@ void GameMessages::HandleAcknowledgePossession(RakNet::BitStream* inStream, Enti //Racing -void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { auto* moduleAssemblyComponent = entity->GetComponent(); Game::logger->Log("HandleModuleAssemblyQueryData", "Got Query from %i", entity->GetLOT()); - if (moduleAssemblyComponent != nullptr) - { + if (moduleAssemblyComponent != nullptr) { Game::logger->Log("HandleModuleAssemblyQueryData", "Returning assembly %s", GeneralUtils::UTF16ToWTF8(moduleAssemblyComponent->GetAssemblyPartsLOTs()).c_str()); SendModuleAssemblyDBDataForClient(entity->GetObjectID(), moduleAssemblyComponent->GetSubKey(), moduleAssemblyComponent->GetAssemblyPartsLOTs(), UNASSIGNED_SYSTEM_ADDRESS); @@ -4078,38 +3910,33 @@ void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, En } -void GameMessages::HandleModularAssemblyNIFCompleted(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleModularAssemblyNIFCompleted(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID objectID; inStream->Read(objectID); } -void GameMessages::HandleVehicleSetWheelLockState(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleVehicleSetWheelLockState(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bExtraFriction = inStream->ReadBit(); bool bLocked = inStream->ReadBit(); } -void GameMessages::HandleRacingClientReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleRacingClientReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID playerID; inStream->Read(playerID); auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { + if (player == nullptr) { return; } auto* racingControlComponent = dZoneManager::Instance()->GetZoneControlObject()->GetComponent(); - if (racingControlComponent == nullptr) - { + if (racingControlComponent == nullptr) { return; } @@ -4117,8 +3944,7 @@ void GameMessages::HandleRacingClientReady(RakNet::BitStream* inStream, Entity* } -void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bClientDeath; bool bSpawnLoot; std::u16string deathType; @@ -4135,8 +3961,7 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, uint32_t deathTypeLength = 0; inStream->Read(deathTypeLength); - for (size_t i = 0; i < deathTypeLength; i++) - { + for (size_t i = 0; i < deathTypeLength; i++) { char16_t character; inStream->Read(character); @@ -4147,15 +3972,13 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, inStream->Read(directionRelativeAngleY); inStream->Read(directionRelativeForce); - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(killType); } inStream->Read(killerID); - if (inStream->ReadBit()) - { + if (inStream->ReadBit()) { inStream->Read(lootOwnerID); } @@ -4165,16 +3988,13 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, Game::logger->Log("HandleRequestDie", "Got die request: %i", entity->GetLOT()); - if (racingControlComponent != nullptr) - { + if (racingControlComponent != nullptr) { auto* possessableComponent = entity->GetComponent(); - if (possessableComponent != nullptr) - { + if (possessableComponent != nullptr) { entity = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (entity == nullptr) - { + if (entity == nullptr) { return; } } @@ -4184,28 +4004,24 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, } -void GameMessages::HandleVehicleNotifyServerAddPassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleVehicleNotifyServerAddPassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { //SendVehicleAddPassiveBoostAction(entity->GetObjectID(), sysAddr); } -void GameMessages::HandleVehicleNotifyServerRemovePassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleVehicleNotifyServerRemovePassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { //SendVehicleRemovePassiveBoostAction(entity->GetObjectID(), sysAddr); } -void GameMessages::HandleRacingPlayerInfoResetFinished(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleRacingPlayerInfoResetFinished(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID playerID; inStream->Read(playerID); auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { + if (player == nullptr) { return; } @@ -4215,8 +4031,7 @@ void GameMessages::HandleRacingPlayerInfoResetFinished(RakNet::BitStream* inStre Game::logger->Log("HandleRacingPlayerInfoResetFinished", "Got finished: %i", entity->GetLOT()); - if (racingControlComponent != nullptr) - { + if (racingControlComponent != nullptr) { racingControlComponent->OnRacingPlayerInfoResetFinished(player); } } @@ -4257,8 +4072,7 @@ void GameMessages::HandleUpdatePropertyPerformanceCost(RakNet::BitStream* inStre updatePerformanceCostQuery = nullptr; } -void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID pickupObjID = LWOOBJID_EMPTY; LWOOBJID pickupSpawnerID = LWOOBJID_EMPTY; int32_t pickupSpawnerIndex = -1; @@ -4271,19 +4085,16 @@ void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* in auto* pickup = EntityManager::Instance()->GetEntity(pickupObjID); - if (pickup == nullptr) - { + if (pickup == nullptr) { return; } auto* possessableComponent = entity->GetComponent(); - if (possessableComponent != nullptr) - { + if (possessableComponent != nullptr) { entity = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (entity == nullptr) - { + if (entity == nullptr) { return; } } @@ -4299,8 +4110,7 @@ void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* in } -void GameMessages::SendModuleAssemblyDBDataForClient(LWOOBJID objectId, LWOOBJID assemblyID, const std::u16string& data, const SystemAddress& sysAddr) -{ +void GameMessages::SendModuleAssemblyDBDataForClient(LWOOBJID objectId, LWOOBJID assemblyID, const std::u16string& data, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4310,8 +4120,7 @@ void GameMessages::SendModuleAssemblyDBDataForClient(LWOOBJID objectId, LWOOBJID bitStream.Write(assemblyID); bitStream.Write(static_cast(data.size())); - for (auto character : data) - { + for (auto character : data) { bitStream.Write(character); } @@ -4320,8 +4129,7 @@ void GameMessages::SendModuleAssemblyDBDataForClient(LWOOBJID objectId, LWOOBJID } -void GameMessages::SendNotifyVehicleOfRacingObject(LWOOBJID objectId, LWOOBJID racingObjectID, const SystemAddress& sysAddr) -{ +void GameMessages::SendNotifyVehicleOfRacingObject(LWOOBJID objectId, LWOOBJID racingObjectID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4336,8 +4144,7 @@ void GameMessages::SendNotifyVehicleOfRacingObject(LWOOBJID objectId, LWOOBJID r } -void GameMessages::SendRacingPlayerLoaded(LWOOBJID objectId, LWOOBJID playerID, LWOOBJID vehicleID, const SystemAddress& sysAddr) -{ +void GameMessages::SendRacingPlayerLoaded(LWOOBJID objectId, LWOOBJID playerID, LWOOBJID vehicleID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4352,8 +4159,7 @@ void GameMessages::SendRacingPlayerLoaded(LWOOBJID objectId, LWOOBJID playerID, } -void GameMessages::SendVehicleUnlockInput(LWOOBJID objectId, bool bLockWheels, const SystemAddress& sysAddr) -{ +void GameMessages::SendVehicleUnlockInput(LWOOBJID objectId, bool bLockWheels, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4367,8 +4173,7 @@ void GameMessages::SendVehicleUnlockInput(LWOOBJID objectId, bool bLockWheels, c } -void GameMessages::SendVehicleSetWheelLockState(LWOOBJID objectId, bool bExtraFriction, bool bLocked, const SystemAddress& sysAddr) -{ +void GameMessages::SendVehicleSetWheelLockState(LWOOBJID objectId, bool bExtraFriction, bool bLocked, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4383,8 +4188,7 @@ void GameMessages::SendVehicleSetWheelLockState(LWOOBJID objectId, bool bExtraFr } -void GameMessages::SendRacingSetPlayerResetInfo(LWOOBJID objectId, int32_t currentLap, uint32_t furthestResetPlane, LWOOBJID playerID, NiPoint3 respawnPos, uint32_t upcomingPlane, const SystemAddress& sysAddr) -{ +void GameMessages::SendRacingSetPlayerResetInfo(LWOOBJID objectId, int32_t currentLap, uint32_t furthestResetPlane, LWOOBJID playerID, NiPoint3 respawnPos, uint32_t upcomingPlane, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4402,8 +4206,7 @@ void GameMessages::SendRacingSetPlayerResetInfo(LWOOBJID objectId, int32_t curre } -void GameMessages::SendRacingResetPlayerToLastReset(LWOOBJID objectId, LWOOBJID playerID, const SystemAddress& sysAddr) -{ +void GameMessages::SendRacingResetPlayerToLastReset(LWOOBJID objectId, LWOOBJID playerID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4417,8 +4220,7 @@ void GameMessages::SendRacingResetPlayerToLastReset(LWOOBJID objectId, LWOOBJID } -void GameMessages::SendNotifyRacingClient(LWOOBJID objectId, int32_t eventType, int32_t param1, LWOOBJID paramObj, std::u16string paramStr, LWOOBJID singleClient, const SystemAddress& sysAddr) -{ +void GameMessages::SendNotifyRacingClient(LWOOBJID objectId, int32_t eventType, int32_t param1, LWOOBJID paramObj, std::u16string paramStr, LWOOBJID singleClient, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4433,8 +4235,7 @@ void GameMessages::SendNotifyRacingClient(LWOOBJID objectId, int32_t eventType, bitStream.Write(paramObj); bitStream.Write(static_cast(paramStr.size())); - for (auto character : paramStr) - { + for (auto character : paramStr) { bitStream.Write(character); } @@ -4445,8 +4246,7 @@ void GameMessages::SendNotifyRacingClient(LWOOBJID objectId, int32_t eventType, } -void GameMessages::SendActivityEnter(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendActivityEnter(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4458,8 +4258,7 @@ void GameMessages::SendActivityEnter(LWOOBJID objectId, const SystemAddress& sys } -void GameMessages::SendActivityStart(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendActivityStart(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4471,8 +4270,7 @@ void GameMessages::SendActivityStart(LWOOBJID objectId, const SystemAddress& sys } -void GameMessages::SendActivityExit(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendActivityExit(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4484,8 +4282,7 @@ void GameMessages::SendActivityExit(LWOOBJID objectId, const SystemAddress& sysA } -void GameMessages::SendActivityStop(LWOOBJID objectId, bool bExit, bool bUserCancel, const SystemAddress& sysAddr) -{ +void GameMessages::SendActivityStop(LWOOBJID objectId, bool bExit, bool bUserCancel, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4500,8 +4297,7 @@ void GameMessages::SendActivityStop(LWOOBJID objectId, bool bExit, bool bUserCan } -void GameMessages::SendVehicleAddPassiveBoostAction(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendVehicleAddPassiveBoostAction(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4513,8 +4309,7 @@ void GameMessages::SendVehicleAddPassiveBoostAction(LWOOBJID objectId, const Sys } -void GameMessages::SendVehicleRemovePassiveBoostAction(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendVehicleRemovePassiveBoostAction(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4526,8 +4321,7 @@ void GameMessages::SendVehicleRemovePassiveBoostAction(LWOOBJID objectId, const } -void GameMessages::SendVehicleNotifyFinishedRace(LWOOBJID objectId, const SystemAddress& sysAddr) -{ +void GameMessages::SendVehicleNotifyFinishedRace(LWOOBJID objectId, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4539,9 +4333,9 @@ void GameMessages::SendVehicleNotifyFinishedRace(LWOOBJID objectId, const System } void GameMessages::SendAddBuff(LWOOBJID& objectID, const LWOOBJID& casterID, uint32_t buffID, uint32_t msDuration, - bool addImmunity, bool cancelOnDamaged, bool cancelOnDeath, bool cancelOnLogout, - bool cancelOnRemoveBuff, bool cancelOnUi, bool cancelOnUnequip, bool cancelOnZone, - const SystemAddress& sysAddr) { + bool addImmunity, bool cancelOnDamaged, bool cancelOnDeath, bool cancelOnLogout, + bool cancelOnRemoveBuff, bool cancelOnUi, bool cancelOnUnequip, bool cancelOnZone, + const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4577,8 +4371,7 @@ void GameMessages::SendAddBuff(LWOOBJID& objectID, const LWOOBJID& casterID, uin // NT -void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bAllowPartial; int32_t destSlot = -1; int32_t iStackCount = 1; @@ -4599,26 +4392,21 @@ void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* if (inStream->ReadBit()) inStream->Read(subkey); if (inStream->ReadBit()) inStream->Read(itemLOT); - if (invTypeDst == invTypeSrc) - { + if (invTypeDst == invTypeSrc) { return; } auto* inventoryComponent = entity->GetComponent(); - if (inventoryComponent != nullptr) - { - if (itemID != LWOOBJID_EMPTY) - { + if (inventoryComponent != nullptr) { + if (itemID != LWOOBJID_EMPTY) { auto* item = inventoryComponent->FindItemById(itemID); - if (item == nullptr) - { + if (item == nullptr) { return; } - if (inventoryComponent->IsPet(item->GetSubKey()) || !item->GetConfig().empty()) - { + if (inventoryComponent->IsPet(item->GetSubKey()) || !item->GetConfig().empty()) { return; } @@ -4628,8 +4416,7 @@ void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* } -void GameMessages::SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditionalSound, bool bPlayCountdownSound, std::u16string sndName, int32_t stateToPlaySoundOn, const SystemAddress& sysAddr) -{ +void GameMessages::SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditionalSound, bool bPlayCountdownSound, std::u16string sndName, int32_t stateToPlaySoundOn, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4641,8 +4428,7 @@ void GameMessages::SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditi bitStream.Write(bPlayCountdownSound); bitStream.Write(static_cast(sndName.size())); - for (auto character : sndName) - { + for (auto character : sndName) { bitStream.Write(character); } @@ -4657,16 +4443,14 @@ void GameMessages::SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditi //------------------------------------------------------------------- Handlers ------------------------------------------------------------------ //----------------------------------------------------------------------------------------------------------------------------------------------- -void GameMessages::HandleToggleGhostReferenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleToggleGhostReferenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool bOverride = false; inStream->Read(bOverride); auto* player = Player::GetPlayer(sysAddr); - if (player != nullptr) - { + if (player != nullptr) { player->SetGhostOverride(bOverride); EntityManager::Instance()->UpdateGhosting(player); @@ -4674,16 +4458,14 @@ void GameMessages::HandleToggleGhostReferenceOverride(RakNet::BitStream* inStrea } -void GameMessages::HandleSetGhostReferencePosition(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) -{ +void GameMessages::HandleSetGhostReferencePosition(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { NiPoint3 position; inStream->Read(position); auto* player = Player::GetPlayer(sysAddr); - if (player != nullptr) - { + if (player != nullptr) { player->SetGhostOverridePoint(position); EntityManager::Instance()->UpdateGhosting(player); @@ -4709,8 +4491,7 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti auto* propertyVendorComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_PROPERTY_VENDOR)); - if (propertyVendorComponent != nullptr) - { + if (propertyVendorComponent != nullptr) { propertyVendorComponent->OnBuyFromVendor(player, bConfirmed, item, count); return; @@ -4739,17 +4520,14 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti inv->RemoveItem(craftingCurrency.first, craftingCurrency.second * count); } - if (isCommendationVendor) - { - if (itemComp.commendationLOT != 13763) - { + if (isCommendationVendor) { + if (itemComp.commendationLOT != 13763) { return; } auto* missionComponent = player->GetComponent(); - if (missionComponent == nullptr) - { + if (missionComponent == nullptr) { return; } @@ -4777,32 +4555,26 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti const uint32_t altCurrencyCost = itemComp.commendationCost * count; - if (inv->GetLotCount(tokenId) < altCurrencyCost) - { + if (inv->GetLotCount(tokenId) < altCurrencyCost) { return; } inv->RemoveItem(tokenId, altCurrencyCost); inv->AddItem(item, count, eLootSourceType::LOOT_SOURCE_VENDOR); - } - else - { + } else { float buyScalar = vend->GetBuyScalar(); const auto coinCost = static_cast(std::floor((itemComp.baseValue * buyScalar) * count)); - if (character->GetCoins() < coinCost) - { + if (character->GetCoins() < coinCost) { return; } - if (Inventory::IsValidItem(itemComp.currencyLOT)) - { + if (Inventory::IsValidItem(itemComp.currencyLOT)) { const uint32_t altCurrencyCost = std::floor(itemComp.altCurrencyCost * buyScalar) * count; - if (inv->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) - { + if (inv->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) { return; } @@ -4850,15 +4622,14 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit if (itemComp.baseValue == 0 || itemComp.baseValue == UINT_MAX) return; float sellScalar = vend->GetSellScalar(); - if (Inventory::IsValidItem(itemComp.currencyLOT)) - { + if (Inventory::IsValidItem(itemComp.currencyLOT)) { const auto altCurrency = (itemComp.altCurrencyCost * sellScalar) * count; inv->AddItem(itemComp.currencyLOT, std::floor(altCurrency), eLootSourceType::LOOT_SOURCE_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() + ((itemComp.baseValue * sellScalar)*count)), eLootSourceType::LOOT_SOURCE_VENDOR); + character->SetCoins(std::floor(character->GetCoins() + ((itemComp.baseValue * sellScalar) * count)), eLootSourceType::LOOT_SOURCE_VENDOR); //EntityManager::Instance()->SerializeEntity(player); // so inventory updates GameMessages::SendVendorTransactionResult(entity, sysAddr); } @@ -4901,17 +4672,14 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* const auto cost = static_cast(std::floor(((itemComp.baseValue * sellScalar) * count))); - if (character->GetCoins() < cost) - { + if (character->GetCoins() < cost) { return; } - if (Inventory::IsValidItem(itemComp.currencyLOT)) - { + if (Inventory::IsValidItem(itemComp.currencyLOT)) { const uint32_t altCurrencyCost = std::floor(itemComp.altCurrencyCost * sellScalar) * count; - if (inv->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) - { + if (inv->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) { return; } @@ -4996,22 +4764,19 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity if (param2) { mapId = rocketPad->GetDefaultZone(); - } - else { + } else { mapId = param3; } - if (mapId == 0) - { + if (mapId == 0) { mapId = rocketPad->GetSelectedMapId(player->GetObjectID()); } - if (mapId == 0) - { + if (mapId == 0) { mapId = dZoneManager::Instance()->GetZoneID().GetMapID(); // Fallback to sending the player back to the same zone. } - Game::logger->Log("FireEventServerSide", "Player %llu has requested zone transfer to (%i, %i).", sender->GetObjectID(), (int) mapId, (int) cloneId); + Game::logger->Log("FireEventServerSide", "Player %llu has requested zone transfer to (%i, %i).", sender->GetObjectID(), (int)mapId, (int)cloneId); auto* character = player->GetCharacter(); @@ -5030,7 +4795,7 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); return; - }); + }); } entity->OnFireEventServerSide(sender, GeneralUtils::UTF16ToWTF8(args), param1, param2, param3); @@ -5069,35 +4834,27 @@ void GameMessages::HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, Entity* interactedObject = EntityManager::Instance()->GetEntity(objectID); - if (interactedObject == nullptr) - { + if (interactedObject == nullptr) { Game::logger->Log("GameMessages", "Object %llu tried to interact, but doesn't exist!", objectID); return; } - if (interactedObject->GetLOT() == 9524) - { + if (interactedObject->GetLOT() == 9524) { entity->GetCharacter()->SetBuildMode(true); } - if (bIsMultiInteractUse) - { - if (multiInteractType == 0) - { + if (bIsMultiInteractUse) { + if (multiInteractType == 0) { auto* missionOfferComponent = static_cast(interactedObject->GetComponent(COMPONENT_TYPE_MISSION_OFFER)); - if (missionOfferComponent != nullptr) - { + if (missionOfferComponent != nullptr) { missionOfferComponent->OfferMissions(entity, multiInteractID); } - } - else { + } else { interactedObject->OnUse(entity); } - } - else - { + } else { interactedObject->OnUse(entity); } @@ -5129,25 +4886,20 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) mission->Progress(MissionTaskType::MISSION_TASK_TYPE_EMOTE, emoteID, targetID); } - if (targetID != LWOOBJID_EMPTY) - { + if (targetID != LWOOBJID_EMPTY) { auto* targetEntity = EntityManager::Instance()->GetEntity(targetID); Game::logger->Log("GameMessages", "Emote target found (%d)", targetEntity != nullptr); - if (targetEntity != nullptr) - { + if (targetEntity != nullptr) { targetEntity->OnEmoteReceived(emoteID, entity); } - } - else - { + } else { const auto scriptedEntities = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); const auto& referencePoint = entity->GetPosition(); - for (auto* scripted : scriptedEntities) - { + for (auto* scripted : scriptedEntities) { if (Vector3::DistanceSquared(scripted->GetPosition(), referencePoint) > 5.0f * 5.0f) continue; scripted->OnEmoteReceived(emoteID, entity); @@ -5177,8 +4929,7 @@ void GameMessages::HandleModularBuildConvertModel(RakNet::BitStream* inStream, E auto* item = inv->FindItemById(modelID); - if (item == nullptr) - { + if (item == nullptr) { return; } @@ -5225,8 +4976,7 @@ void GameMessages::HandleRespondToMission(RakNet::BitStream* inStream, Entity* e Mission* mission = missionComponent->GetMission(missionID); if (mission) { mission->SetReward(reward); - } - else { + } else { Game::logger->Log("GameMessages", "Unable to get mission %i for entity %llu to update reward in RespondToMission", missionID, playerID); } @@ -5268,8 +5018,7 @@ void GameMessages::HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* en if (iMissionState == MissionState::MISSION_STATE_AVAILABLE || iMissionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) { missionComponent->AcceptMission(missionID); - } - else if (iMissionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || iMissionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + } else if (iMissionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || iMissionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { missionComponent->CompleteMission(missionID); } } @@ -5287,8 +5036,7 @@ void GameMessages::HandleRequestLinkedMission(RakNet::BitStream* inStream, Entit auto* missionOfferComponent = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION_OFFER)); - if (missionOfferComponent != nullptr) - { + if (missionOfferComponent != nullptr) { missionOfferComponent->OfferMissions(player, 0); } } @@ -5408,10 +5156,10 @@ void GameMessages::HandleEquipItem(RakNet::BitStream* inStream, Entity* entity) Item* item = inv->FindItemById(objectID); if (!item) return; - item->Equip(); + item->Equip(); - EntityManager::Instance()->SerializeEntity(entity); - } + EntityManager::Instance()->SerializeEntity(entity); +} void GameMessages::HandleUnequipItem(RakNet::BitStream* inStream, Entity* entity) { bool immediate; @@ -5501,8 +5249,7 @@ void GameMessages::HandleRemoveItemFromInventory(RakNet::BitStream* inStream, En auto* item = inv->FindItemById(iObjID); - if (item == nullptr) - { + if (item == nullptr) { return; } @@ -5510,8 +5257,7 @@ void GameMessages::HandleRemoveItemFromInventory(RakNet::BitStream* inStream, En if (bConfirmed) { for (auto i = 0; i < iStackCount; ++i) { - if (eInvType == eInventoryType::MODELS) - { + if (eInvType == eInventoryType::MODELS) { item->DisassembleModel(); } } @@ -5521,8 +5267,7 @@ void GameMessages::HandleRemoveItemFromInventory(RakNet::BitStream* inStream, En auto* missionComponent = entity->GetComponent(); - if (missionComponent != nullptr) - { + if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, item->GetLot(), LWOOBJID_EMPTY, "", -iStackCount); } } @@ -5547,8 +5292,7 @@ void GameMessages::HandleMoveItemInInventory(RakNet::BitStream* inStream, Entity auto* item = inv->FindItemById(iObjID); - if (!item) - { + if (!item) { return; } @@ -5648,12 +5392,9 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* modules += u"1:" + (GeneralUtils::to_u16string(mod)); if (k + 1 != count) modules += u"+"; - if (temp->GetLotCount(mod) > 0) - { + if (temp->GetLotCount(mod) > 0) { inv->RemoveItem(mod, 1, TEMP_MODELS); - } - else - { + } else { inv->RemoveItem(mod, 1); } } @@ -5663,21 +5404,16 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* std::vector config; config.push_back(moduleAssembly); - if (count == 3) - { + if (count == 3) { inv->AddItem(6416, 1, eLootSourceType::LOOT_SOURCE_QUICKBUILD, eInventoryType::MODELS, config); - } - else if (count == 7) - { + } else if (count == 7) { inv->AddItem(8092, 1, eLootSourceType::LOOT_SOURCE_QUICKBUILD, eInventoryType::MODELS, config); } auto* missionComponent = character->GetComponent(); - if (entity->GetLOT() != 9980 || Game::server->GetZoneID() != 1200) - { - if (missionComponent != nullptr) - { + if (entity->GetLOT() != 9980 || Game::server->GetZoneID() != 1200) { + if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, entity->GetLOT(), entity->GetObjectID()); } } @@ -5692,13 +5428,11 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* // Move remaining temp models back to models std::vector items; - for (const auto& pair : temp->GetItems()) - { + for (const auto& pair : temp->GetItems()) { items.push_back(pair.second); } - for (auto* item : items) - { + for (auto* item : items) { inv->MoveItemToInventory(item, eInventoryType::MODELS, item->GetCount(), false); } } @@ -5767,13 +5501,11 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti if (!buildAreas.empty()) { buildArea = buildAreas[0]; - } - else if (!entities.empty()) { + } else if (!entities.empty()) { buildArea = entities[0]; Game::logger->Log("BuildBorderComponent", "Using PropertyPlaque"); - } - else { + } else { Game::logger->Log("BuildBorderComponent", "No build area found"); return; @@ -5807,13 +5539,11 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti std::vector items; - for (const auto& pair : inventory->GetItems()) - { + for (const auto& pair : inventory->GetItems()) { items.push_back(pair.second); } - for (auto* item : items) - { + for (auto* item : items) { inv->MoveItemToInventory(item, eInventoryType::MODELS, item->GetCount(), false, false); } } @@ -5835,8 +5565,7 @@ void GameMessages::HandleModularBuildMoveAndEquip(RakNet::BitStream* inStream, E auto* item = inv->FindItemByLot(templateID, TEMP_MODELS); - if (item == nullptr) - { + if (item == nullptr) { return; } @@ -5853,10 +5582,8 @@ void GameMessages::HandlePickupItem(RakNet::BitStream* inStream, Entity* entity) auto* team = TeamManager::Instance()->GetTeam(entity->GetObjectID()); - if (team != nullptr) - { - for (const auto memberId : team->members) - { + if (team != nullptr) { + for (const auto memberId : team->members) { auto* member = EntityManager::Instance()->GetEntity(memberId); if (member == nullptr || memberId == playerID) continue; @@ -5898,31 +5625,27 @@ void GameMessages::HandlePopEquippedItemsState(RakNet::BitStream* inStream, Enti } -void GameMessages::HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* entity) -{ +void GameMessages::HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* entity) { LWOOBJID itemConsumed; inStream->Read(itemConsumed); auto* inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); - if (inventory == nullptr) - { + if (inventory == nullptr) { return; } auto* item = inventory->FindItemById(itemConsumed); - if (item == nullptr) - { + if (item == nullptr) { return; } item->Consume(); auto* missions = static_cast(entity->GetComponent(COMPONENT_TYPE_MISSION)); - if (missions != nullptr) - { + if (missions != nullptr) { missions->Progress(MissionTaskType::MISSION_TASK_TYPE_FOOD, item->GetLot()); } } @@ -5939,8 +5662,7 @@ void GameMessages::HandleUseNonEquipmentItem(RakNet::BitStream* inStream, Entity auto* item = inv->FindItemById(itemConsumed); - if (item == nullptr) - { + if (item == nullptr) { return; } @@ -5979,12 +5701,10 @@ void GameMessages::HandleMatchRequest(RakNet::BitStream* inStream, Entity* entit comp->PlayerJoin(entity); } } - } - else { + } else { } - } - else if (type == 1) { // ready/unready + } else if (type == 1) { // ready/unready for (Entity* scriptedAct : scriptedActs) { ScriptedActivityComponent* comp = static_cast(scriptedAct->GetComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY)); if (!comp) continue; @@ -6001,43 +5721,43 @@ void GameMessages::HandleGetHotPropertyData(RakNet::BitStream* inStream, Entity* void GameMessages::SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { CBITSTREAM - CMSGHEADER - /** - * [u32] - Number of properties - * [objid] - property id - * [objid] - property owner id - * [wstring] - property owner name - * [u64] - total reputation - * [i32] - property template id - * [wstring] - property name - * [wstring] - property description - * [float] - performance cost - * [timestamp] - time last published - * [cloneid] - clone id - * - */ - // TODO This needs to be implemented when reputation is implemented for getting hot properties. - /** - bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_SEND_HOT_PROPERTY_DATA); - std::vector t = {25166, 25188, 25191, 25194}; - bitStream.Write(4); - for (uint8_t i = 0; i < 4; i++) { - bitStream.Write(entity->GetObjectID()); - bitStream.Write(entity->GetObjectID()); - bitStream.Write(1); - bitStream.Write('c'); - bitStream.Write(42069); - bitStream.Write(t[i]); - bitStream.Write(1); - bitStream.Write('c'); - bitStream.Write(1); - bitStream.Write('c'); - bitStream.Write(420.69f); - bitStream.Write(1658376385); - bitStream.Write(25166); - } - SEND_PACKET*/ + CMSGHEADER + /** + * [u32] - Number of properties + * [objid] - property id + * [objid] - property owner id + * [wstring] - property owner name + * [u64] - total reputation + * [i32] - property template id + * [wstring] - property name + * [wstring] - property description + * [float] - performance cost + * [timestamp] - time last published + * [cloneid] - clone id + * + */ + // TODO This needs to be implemented when reputation is implemented for getting hot properties. + /** + bitStream.Write(entity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_SEND_HOT_PROPERTY_DATA); + std::vector t = {25166, 25188, 25191, 25194}; + bitStream.Write(4); + for (uint8_t i = 0; i < 4; i++) { + bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(42069); + bitStream.Write(t[i]); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(420.69f); + bitStream.Write(1658376385); + bitStream.Write(25166); + } + SEND_PACKET*/ } void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) { @@ -6097,14 +5817,13 @@ void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) insertBug->setInt(5, reporterID); insertBug->execute(); delete insertBug; - } - catch (sql::SQLException& e) { + } catch (sql::SQLException& e) { Game::logger->Log("HandleReportBug", "Couldn't save bug report! (%s)", e.what()); } } void -GameMessages::HandleClientRailMovementReady(RakNet::BitStream *inStream, Entity *entity, const SystemAddress &sysAddr) { +GameMessages::HandleClientRailMovementReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); for (const auto* possibleRail : possibleRails) { const auto* rail = possibleRail->GetComponent(); @@ -6114,7 +5833,7 @@ GameMessages::HandleClientRailMovementReady(RakNet::BitStream *inStream, Entity } } -void GameMessages::HandleCancelRailMovement(RakNet::BitStream *inStream, Entity *entity, const SystemAddress &sysAddr) { +void GameMessages::HandleCancelRailMovement(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { const auto immediate = inStream->ReadBit(); const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); @@ -6126,8 +5845,8 @@ void GameMessages::HandleCancelRailMovement(RakNet::BitStream *inStream, Entity } } -void GameMessages::HandlePlayerRailArrivedNotification(RakNet::BitStream *inStream, Entity *entity, - const SystemAddress &sysAddr) { +void GameMessages::HandlePlayerRailArrivedNotification(RakNet::BitStream* inStream, Entity* entity, + const SystemAddress& sysAddr) { uint32_t pathNameLength; inStream->Read(pathNameLength); @@ -6149,7 +5868,7 @@ void GameMessages::HandlePlayerRailArrivedNotification(RakNet::BitStream *inStre } } -void GameMessages::HandleModifyPlayerZoneStatistic(RakNet::BitStream *inStream, Entity *entity) { +void GameMessages::HandleModifyPlayerZoneStatistic(RakNet::BitStream* inStream, Entity* entity) { const auto set = inStream->ReadBit(); const auto statisticsName = GeneralUtils::ReadWString(inStream); @@ -6187,6 +5906,6 @@ void GameMessages::HandleUpdatePlayerStatistic(RakNet::BitStream* inStream, Enti auto* characterComponent = entity->GetComponent(); if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic((StatisticID) updateID, (uint64_t) std::max(updateValue, int64_t(0))); + characterComponent->UpdatePlayerStatistic((StatisticID)updateID, (uint64_t)std::max(updateValue, int64_t(0))); } } diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index c5b7888d..47e5f41c 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -25,9 +25,9 @@ namespace GameMessages { void SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender); void SendTeleport(const LWOOBJID& objectID, const NiPoint3& pos, const NiQuaternion& rot, const SystemAddress& sysAddr, bool bSetRotation = false, bool noGravTeleport = true); void SendPlayAnimation(Entity* entity, const std::u16string& animationName, float fPriority = 0.0f, float fScale = 1.0f); - void SendPlayerReady(Entity * entity, const SystemAddress& sysAddr); + void SendPlayerReady(Entity* entity, const SystemAddress& sysAddr); void SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptRespawn, const SystemAddress& systemAddress); - void SendInvalidZoneTransferList(Entity * entity, const SystemAddress& sysAddr, const std::u16string& feedbackURL, const std::u16string& invalidMapTransferList, bool feedbackOnExit, bool feedbackOnInvalidTransfer); + void SendInvalidZoneTransferList(Entity* entity, const SystemAddress& sysAddr, const std::u16string& feedbackURL, const std::u16string& invalidMapTransferList, bool feedbackOnExit, bool feedbackOnInvalidTransfer); void SendKnockback(const LWOOBJID& objectID, const LWOOBJID& caster, const LWOOBJID& originator, int knockBackTimeMS, const NiPoint3& vector); void SendStartArrangingWithItem( @@ -47,27 +47,27 @@ namespace GameMessages { ); void SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, const SystemAddress& sysAddr, - bool bAllowCyclingWhileDeadOnly = true, eCyclingMode cyclingMode = ALLOW_CYCLE_TEAMMATES); + bool bAllowCyclingWhileDeadOnly = true, eCyclingMode cyclingMode = ALLOW_CYCLE_TEAMMATES); void SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& sysAddr, std::string audioGUID); void SendStartPathing(Entity* entity); void SendPlatformResync(Entity* entity, const SystemAddress& sysAddr, bool bStopAtDesiredWaypoint = false, - int iIndex = 0, int iDesiredWaypointIndex = 1, int nextIndex = 1, - MovementPlatformState movementState = MovementPlatformState::Moving); - - void SendRestoreToPostLoadStats(Entity * entity, const SystemAddress& sysAddr); - void SendServerDoneLoadingAllObjects(Entity * entity, const SystemAddress& sysAddr); + int iIndex = 0, int iDesiredWaypointIndex = 1, int nextIndex = 1, + MovementPlatformState movementState = MovementPlatformState::Moving); + + void SendRestoreToPostLoadStats(Entity* entity, const SystemAddress& sysAddr); + void SendServerDoneLoadingAllObjects(Entity* entity, const SystemAddress& sysAddr); void SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level); void SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level); - + void SendAddItemToInventoryClientSync(Entity* entity, const SystemAddress& sysAddr, Item* item, const LWOOBJID& objectID, bool showFlyingLoot, int itemCount, LWOOBJID subKey = LWOOBJID_EMPTY, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); void SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFlagID, bool bFlag, const SystemAddress& sysAddr); void SendChangeObjectWorldState(const LWOOBJID& objectID, int state, const SystemAddress& sysAddr); - + void SendOfferMission(const LWOOBJID& entity, const SystemAddress& sysAddr, int32_t missionID, const LWOOBJID& offererID); - void SendNotifyMission(Entity * entity, const SystemAddress& sysAddr, int missionID, int missionState, bool sendingRewards); - void SendNotifyMissionTask(Entity * entity, const SystemAddress& sysAddr, int missionID, int taskMask, std::vector updates); + void SendNotifyMission(Entity* entity, const SystemAddress& sysAddr, int missionID, int missionState, bool sendingRewards); + void SendNotifyMissionTask(Entity* entity, const SystemAddress& sysAddr, int missionID, int taskMask, std::vector updates); void NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sysAddr, int level, bool sending_rewards); void SendModifyLEGOScore(Entity* entity, const SystemAddress& sysAddr, int64_t score, eLootSourceType sourceType); @@ -90,7 +90,7 @@ namespace GameMessages { void SendDie(Entity* entity, const LWOOBJID& killerID, const LWOOBJID& lootOwnerID, bool bDieAccepted, eKillType killType, std::u16string deathType, float directionRelative_AngleY, float directionRelative_AngleXZ, float directionRelative_Force, bool bClientDeath, bool bSpawnLoot, float coinSpawnTime); void SendSetInventorySize(Entity* entity, int invType, int size); - + void SendSetEmoteLockState(Entity* entity, bool bLock, int emoteID); void SendSetJetPackMode(Entity* entity, bool use, bool bypassChecks = false, bool doHover = false, int effectID = -1, float airspeed = 10, float maxAirspeed = 15, float verticalVelocity = 1, int warningEffectID = -1); void SendResurrect(Entity* entity); @@ -124,7 +124,7 @@ namespace GameMessages { /** * Sends a message to an Entity to smash itself, but not delete or destroy itself from the world - * + * * @param entity The Entity that will smash itself into bricks * @param force The force the Entity will be smashed with * @param ghostOpacity The ghosting opacity of the smashed Entity @@ -135,7 +135,7 @@ namespace GameMessages { /** * Sends a message to an Entity to UnSmash itself (aka rebuild itself over a duration) - * + * * @param entity The Entity that will UnSmash itself * @param builderID The Entity that invoked the build (LWOOBJID_EMPTY if none exists or invoked the rebuild) * @param duration The duration for the Entity to rebuild over. 3 seconds by default @@ -144,11 +144,11 @@ namespace GameMessages { /** * @brief This GameMessage is the one that handles all of the property behavior incoming messages from the client. - * + * * The GameMessage struct can be located here https://lcdruniverse.org/lu_packets/lu_packets/world/gm/server/struct.ControlBehaviors.html * For information on the AMF3 format can be found here https://rtmp.veriskope.com/pdf/amf3-file-format-spec.pdf * For any questions regarding AMF3 you can contact EmosewaMC on GitHub - * + * * @param inStream The incoming data sent from the client * @param entity The Entity that sent the message * @param sysAddr The SystemAddress that sent the message @@ -157,15 +157,15 @@ namespace GameMessages { // Rails stuff void SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForward, std::u16string pathName, uint32_t pathStart, - const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, - int32_t railActivatorComponentID = -1, LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); + const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, + int32_t railActivatorComponentID = -1, LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); void SendStartRailMovement(const LWOOBJID& objectID, std::u16string pathName, std::u16string startSound, - std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, - uint32_t pathStart = 0, bool goForward = true, bool damageImmune = true, bool noAggro = true, - bool notifyActor = false, bool showNameBillboard = true, bool cameraLocked = true, - bool collisionEnabled = true, bool useDB = true, int32_t railComponentID = -1, - LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); + std::u16string loopSound, std::u16string stopSound, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, + uint32_t pathStart = 0, bool goForward = true, bool damageImmune = true, bool noAggro = true, + bool notifyActor = false, bool showNameBillboard = true, bool cameraLocked = true, + bool collisionEnabled = true, bool useDB = true, int32_t railComponentID = -1, + LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); void HandleClientRailMovementReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleCancelRailMovement(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -175,14 +175,14 @@ namespace GameMessages { void SendNotifyClientZoneObject(const LWOOBJID& objectID, const std::u16string& name, int param1, int param2, const LWOOBJID& paramObj, const std::string& paramStr, const SystemAddress& sysAddr); void SendNotifyClientFailedPrecondition(LWOOBJID objectId, const SystemAddress& sysAddr, const std::u16string& failedReason, int preconditionID); - + // The success or failure response sent back to the client will preserve the same value for localID. void SendBBBSaveResponse(const LWOOBJID& objectId, const LWOOBJID& localID, unsigned char* buffer, uint32_t bufferSize, const SystemAddress& sysAddr); void SendAddBuff(LWOOBJID& objectID, const LWOOBJID& casterID, uint32_t buffID, uint32_t msDuration, - bool addImmunity = false, bool cancelOnDamaged = false, bool cancelOnDeath = true, - bool cancelOnLogout = false, bool cancelOnRemoveBuff = true, bool cancelOnUi = false, - bool cancelOnUnequip = false, bool cancelOnZone = false, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); + bool addImmunity = false, bool cancelOnDamaged = false, bool cancelOnDeath = true, + bool cancelOnLogout = false, bool cancelOnRemoveBuff = true, bool cancelOnUi = false, + bool cancelOnUnequip = false, bool cancelOnZone = false, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void SendToggleGMInvis(LWOOBJID objectId, bool enabled, const SystemAddress& sysAddr); @@ -209,7 +209,7 @@ namespace GameMessages { void SendPlaceModelResponse(LWOOBJID objectId, const SystemAddress& sysAddr, NiPoint3 position, LWOOBJID plaque, int32_t response, NiQuaternion rotation); void SendUGCEquipPreCreateBasedOnEditMode(LWOOBJID objectId, const SystemAddress& sysAddr, int modelCount, LWOOBJID model); - + void SendUGCEquipPostDeleteBasedOnEditMode(LWOOBJID objectId, const SystemAddress& sysAddr, LWOOBJID inventoryItem, int itemTotal); void HandleSetPropertyAccess(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -219,11 +219,11 @@ namespace GameMessages { void HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - + void HandleStartBuildingWithItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandlePropertyEditorBegin(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - + void HandlePropertyEditorEnd(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandlePropertyContentsFromClient(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -246,13 +246,13 @@ namespace GameMessages { void HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, + void SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, bool allowGhostUpdates = true, bool bCloseMultiInteract = true, bool bSendServerNotify = false, bool bUseControlledObjectForAudioListener = false, int endBehavior = 0, bool hidePlayerDuringCine = false, float leadIn = -1, bool leavePlayerLockedWhenFinished = false, bool lockPlayer = true, bool result = false, bool skipIfSamePath = false, float startTimeAdvance = 0); void SendEndCinematic(LWOOBJID objectID, std::u16string pathName, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, - float leadOut = -1.0f, bool leavePlayerLocked = false); + float leadOut = -1.0f, bool leavePlayerLocked = false); void HandleCinematicUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, const SystemAddress& sysAddr, @@ -392,7 +392,7 @@ namespace GameMessages { /** * @brief A request from a client to get the hot properties that would appear on the news feed * This incoming message has NO DATA and is simply a request that expects to send a reply to the sender. - * + * * @param inStream packet of data * @param entity The Entity that sent the request * @param sysAddr The SystemAddress of the Entity that sent the request @@ -402,7 +402,7 @@ namespace GameMessages { /** * @brief A request from a client to get the hot properties that would appear on the news feed * The struct of data to send is as follows - * + * * [u32] - Number of properties * [objid] - property id * [objid] - property owner id @@ -414,7 +414,7 @@ namespace GameMessages { * [float] - performance cost * [timestamp] - time last published * [cloneid] - clone id - * + * * @param inStream packet of data * @param entity The Entity that sent the request * @param sysAddr The SystemAddress of the Entity that sent the request @@ -493,12 +493,12 @@ namespace GameMessages { // Leaderboards void SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, - const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); + const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, const SystemAddress& sysAddr); void SendRequestActivitySummaryLeaderboardData(const LWOOBJID& objectID, const LWOOBJID& targetID, - const SystemAddress& sysAddr, const int32_t& gameID = 0, - const int32_t& queryType = 1, const int32_t& resultsEnd = 10, - const int32_t& resultsStart = 0, bool weekly = false); + const SystemAddress& sysAddr, const int32_t& gameID = 0, + const int32_t& queryType = 1, const int32_t& resultsEnd = 10, + const int32_t& resultsStart = 0, bool weekly = false); void HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleActivityStateChangeRequest(RakNet::BitStream* inStream, Entity* entity); @@ -509,13 +509,13 @@ namespace GameMessages { void SendVehicleNotifyFinishedRace(LWOOBJID objectId, const SystemAddress& sysAddr); //NT: - + void HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditionalSound, bool bPlayCountdownSound, std::u16string sndName, int32_t stateToPlaySoundOn, const SystemAddress& sysAddr); //Handlers: - + void HandleToggleGhostReferenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleSetGhostReferencePosition(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); @@ -558,555 +558,555 @@ namespace GameMessages { void HandlePopEquippedItemsState(RakNet::BitStream* inStream, Entity* entity); void HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* entity); - + void HandleUseNonEquipmentItem(RakNet::BitStream* inStream, Entity* entity); void HandleMatchRequest(RakNet::BitStream* inStream, Entity* entity); void HandleReportBug(RakNet::BitStream* inStream, Entity* entity); - /* Message to synchronize a skill cast */ - class EchoSyncSkill { - static const GAME_MSG MsgID = GAME_MSG_ECHO_SYNC_SKILL; + /* Message to synchronize a skill cast */ + class EchoSyncSkill { + static const GAME_MSG MsgID = GAME_MSG_ECHO_SYNC_SKILL; - public: - EchoSyncSkill() { - bDone = false; - } + public: + EchoSyncSkill() { + bDone = false; + } - EchoSyncSkill(std::string _sBitStream, unsigned int _uiBehaviorHandle, unsigned int _uiSkillHandle, bool _bDone = false) { - bDone = _bDone; - sBitStream = _sBitStream; - uiBehaviorHandle = _uiBehaviorHandle; - uiSkillHandle = _uiSkillHandle; - } + EchoSyncSkill(std::string _sBitStream, unsigned int _uiBehaviorHandle, unsigned int _uiSkillHandle, bool _bDone = false) { + bDone = _bDone; + sBitStream = _sBitStream; + uiBehaviorHandle = _uiBehaviorHandle; + uiSkillHandle = _uiSkillHandle; + } - EchoSyncSkill(RakNet::BitStream* stream) { - bDone = false; + EchoSyncSkill(RakNet::BitStream* stream) { + bDone = false; - Deserialize(stream); - } + Deserialize(stream); + } - ~EchoSyncSkill() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); + ~EchoSyncSkill() { + } - stream->Write(bDone); - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } + void Serialize(RakNet::BitStream* stream) { + stream->Write((unsigned short)MsgID); - stream->Write(uiBehaviorHandle); - stream->Write(uiSkillHandle); - } - - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bDone); - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } + stream->Write(bDone); + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } - stream->Read(uiBehaviorHandle); - stream->Read(uiSkillHandle); + stream->Write(uiBehaviorHandle); + stream->Write(uiSkillHandle); + } - return true; - } + bool Deserialize(RakNet::BitStream* stream) { + stream->Read(bDone); + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } - bool bDone{}; - std::string sBitStream{}; - unsigned int uiBehaviorHandle{}; - unsigned int uiSkillHandle{}; - }; + stream->Read(uiBehaviorHandle); + stream->Read(uiSkillHandle); + + return true; + } + + bool bDone{}; + std::string sBitStream{}; + unsigned int uiBehaviorHandle{}; + unsigned int uiSkillHandle{}; + }; /* Message to synchronize a skill cast */ - class SyncSkill { - static const GAME_MSG MsgID = GAME_MSG_SYNC_SKILL; + class SyncSkill { + static const GAME_MSG MsgID = GAME_MSG_SYNC_SKILL; - public: - SyncSkill() { - bDone = false; - } + public: + SyncSkill() { + bDone = false; + } - SyncSkill(std::string _sBitStream, unsigned int _uiBehaviorHandle, unsigned int _uiSkillHandle, bool _bDone = false) { - bDone = _bDone; - sBitStream = _sBitStream; - uiBehaviorHandle = _uiBehaviorHandle; - uiSkillHandle = _uiSkillHandle; - } + SyncSkill(std::string _sBitStream, unsigned int _uiBehaviorHandle, unsigned int _uiSkillHandle, bool _bDone = false) { + bDone = _bDone; + sBitStream = _sBitStream; + uiBehaviorHandle = _uiBehaviorHandle; + uiSkillHandle = _uiSkillHandle; + } - SyncSkill(RakNet::BitStream* stream) { - bDone = false; - Deserialize(stream); - } + SyncSkill(RakNet::BitStream* stream) { + bDone = false; + Deserialize(stream); + } - ~SyncSkill() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); + ~SyncSkill() { + } - stream->Write(bDone); - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } + void Serialize(RakNet::BitStream* stream) { + stream->Write((unsigned short)MsgID); - stream->Write(uiBehaviorHandle); - stream->Write(uiSkillHandle); - } - - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bDone); - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } + stream->Write(bDone); + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } - stream->Read(uiBehaviorHandle); - stream->Read(uiSkillHandle); + stream->Write(uiBehaviorHandle); + stream->Write(uiSkillHandle); + } - return true; - } + bool Deserialize(RakNet::BitStream* stream) { + stream->Read(bDone); + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } - bool bDone{}; - std::string sBitStream{}; - unsigned int uiBehaviorHandle{}; - unsigned int uiSkillHandle{}; - }; + stream->Read(uiBehaviorHandle); + stream->Read(uiSkillHandle); + + return true; + } + + bool bDone{}; + std::string sBitStream{}; + unsigned int uiBehaviorHandle{}; + unsigned int uiSkillHandle{}; + }; /* Notifying the server that a locally owned projectil impacted. Sent to the caster of the projectile should always be the local char. */ - class RequestServerProjectileImpact { - static const GAME_MSG MsgID = GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT; + class RequestServerProjectileImpact { + static const GAME_MSG MsgID = GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT; - public: - RequestServerProjectileImpact() { - i64LocalID = LWOOBJID_EMPTY; - i64TargetID = LWOOBJID_EMPTY; - } + public: + RequestServerProjectileImpact() { + i64LocalID = LWOOBJID_EMPTY; + i64TargetID = LWOOBJID_EMPTY; + } - RequestServerProjectileImpact(std::string _sBitStream, LWOOBJID _i64LocalID = LWOOBJID_EMPTY, LWOOBJID _i64TargetID = LWOOBJID_EMPTY) { - i64LocalID = _i64LocalID; - i64TargetID = _i64TargetID; - sBitStream = _sBitStream; - } + RequestServerProjectileImpact(std::string _sBitStream, LWOOBJID _i64LocalID = LWOOBJID_EMPTY, LWOOBJID _i64TargetID = LWOOBJID_EMPTY) { + i64LocalID = _i64LocalID; + i64TargetID = _i64TargetID; + sBitStream = _sBitStream; + } - RequestServerProjectileImpact(RakNet::BitStream* stream) { - i64LocalID = LWOOBJID_EMPTY; - i64TargetID = LWOOBJID_EMPTY; + RequestServerProjectileImpact(RakNet::BitStream* stream) { + i64LocalID = LWOOBJID_EMPTY; + i64TargetID = LWOOBJID_EMPTY; - Deserialize(stream); - } + Deserialize(stream); + } - ~RequestServerProjectileImpact() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); + ~RequestServerProjectileImpact() { + } - stream->Write(i64LocalID != LWOOBJID_EMPTY); - if (i64LocalID != LWOOBJID_EMPTY) stream->Write(i64LocalID); + void Serialize(RakNet::BitStream* stream) { + stream->Write((unsigned short)MsgID); - stream->Write(i64TargetID != LWOOBJID_EMPTY); - if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); + stream->Write(i64LocalID != LWOOBJID_EMPTY); + if (i64LocalID != LWOOBJID_EMPTY) stream->Write(i64LocalID); - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } + stream->Write(i64TargetID != LWOOBJID_EMPTY); + if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); - } - - bool Deserialize(RakNet::BitStream* stream) { - bool i64LocalIDIsDefault{}; - stream->Read(i64LocalIDIsDefault); - if (i64LocalIDIsDefault != 0) stream->Read(i64LocalID); + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } - bool i64TargetIDIsDefault{}; - stream->Read(i64TargetIDIsDefault); - if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); + } - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } + bool Deserialize(RakNet::BitStream* stream) { + bool i64LocalIDIsDefault{}; + stream->Read(i64LocalIDIsDefault); + if (i64LocalIDIsDefault != 0) stream->Read(i64LocalID); + + bool i64TargetIDIsDefault{}; + stream->Read(i64TargetIDIsDefault); + if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); + + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } - return true; - } + return true; + } - LWOOBJID i64LocalID; - LWOOBJID i64TargetID; - std::string sBitStream; - }; + LWOOBJID i64LocalID; + LWOOBJID i64TargetID; + std::string sBitStream; + }; /* Tell a client local projectile to impact */ - class DoClientProjectileImpact { - static const GAME_MSG MsgID = GAME_MSG_DO_CLIENT_PROJECTILE_IMPACT; + class DoClientProjectileImpact { + static const GAME_MSG MsgID = GAME_MSG_DO_CLIENT_PROJECTILE_IMPACT; - public: - DoClientProjectileImpact() { - i64OrgID = LWOOBJID_EMPTY; - i64OwnerID = LWOOBJID_EMPTY; - i64TargetID = LWOOBJID_EMPTY; - } + public: + DoClientProjectileImpact() { + i64OrgID = LWOOBJID_EMPTY; + i64OwnerID = LWOOBJID_EMPTY; + i64TargetID = LWOOBJID_EMPTY; + } - DoClientProjectileImpact(std::string _sBitStream, LWOOBJID _i64OrgID = LWOOBJID_EMPTY, LWOOBJID _i64OwnerID = LWOOBJID_EMPTY, LWOOBJID _i64TargetID = LWOOBJID_EMPTY) { - i64OrgID = _i64OrgID; - i64OwnerID = _i64OwnerID; - i64TargetID = _i64TargetID; - sBitStream = _sBitStream; - } + DoClientProjectileImpact(std::string _sBitStream, LWOOBJID _i64OrgID = LWOOBJID_EMPTY, LWOOBJID _i64OwnerID = LWOOBJID_EMPTY, LWOOBJID _i64TargetID = LWOOBJID_EMPTY) { + i64OrgID = _i64OrgID; + i64OwnerID = _i64OwnerID; + i64TargetID = _i64TargetID; + sBitStream = _sBitStream; + } - DoClientProjectileImpact(RakNet::BitStream* stream) { - i64OrgID = LWOOBJID_EMPTY; - i64OwnerID = LWOOBJID_EMPTY; - i64TargetID = LWOOBJID_EMPTY; + DoClientProjectileImpact(RakNet::BitStream* stream) { + i64OrgID = LWOOBJID_EMPTY; + i64OwnerID = LWOOBJID_EMPTY; + i64TargetID = LWOOBJID_EMPTY; - Deserialize(stream); - } + Deserialize(stream); + } - ~DoClientProjectileImpact() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); + ~DoClientProjectileImpact() { + } - stream->Write(i64OrgID != LWOOBJID_EMPTY); - if (i64OrgID != LWOOBJID_EMPTY) stream->Write(i64OrgID); + void Serialize(RakNet::BitStream* stream) { + stream->Write((unsigned short)MsgID); - stream->Write(i64OwnerID != LWOOBJID_EMPTY); - if (i64OwnerID != LWOOBJID_EMPTY) stream->Write(i64OwnerID); + stream->Write(i64OrgID != LWOOBJID_EMPTY); + if (i64OrgID != LWOOBJID_EMPTY) stream->Write(i64OrgID); - stream->Write(i64TargetID != LWOOBJID_EMPTY); - if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); + stream->Write(i64OwnerID != LWOOBJID_EMPTY); + if (i64OwnerID != LWOOBJID_EMPTY) stream->Write(i64OwnerID); - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } + stream->Write(i64TargetID != LWOOBJID_EMPTY); + if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); - } - - bool Deserialize(RakNet::BitStream* stream) { - bool i64OrgIDIsDefault{}; - stream->Read(i64OrgIDIsDefault); - if (i64OrgIDIsDefault != 0) stream->Read(i64OrgID); + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } - bool i64OwnerIDIsDefault{}; - stream->Read(i64OwnerIDIsDefault); - if (i64OwnerIDIsDefault != 0) stream->Read(i64OwnerID); + } - bool i64TargetIDIsDefault{}; - stream->Read(i64TargetIDIsDefault); - if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); + bool Deserialize(RakNet::BitStream* stream) { + bool i64OrgIDIsDefault{}; + stream->Read(i64OrgIDIsDefault); + if (i64OrgIDIsDefault != 0) stream->Read(i64OrgID); - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } + bool i64OwnerIDIsDefault{}; + stream->Read(i64OwnerIDIsDefault); + if (i64OwnerIDIsDefault != 0) stream->Read(i64OwnerID); + + bool i64TargetIDIsDefault{}; + stream->Read(i64TargetIDIsDefault); + if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); + + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } - return true; - } + return true; + } + + LWOOBJID i64OrgID; + LWOOBJID i64OwnerID; + LWOOBJID i64TargetID; + std::string sBitStream; + }; - LWOOBJID i64OrgID; - LWOOBJID i64OwnerID; - LWOOBJID i64TargetID; - std::string sBitStream; - }; - /* Same as start skill but with different network options. An echo down to other clients that need to play the skill. */ class EchoStartSkill { static const GAME_MSG MsgID = GAME_MSG_ECHO_START_SKILL; - public: - EchoStartSkill() { - bUsedMouse = false; - fCasterLatency = 0.0f; - iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; - optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; - uiSkillHandle = 0; + public: + EchoStartSkill() { + bUsedMouse = false; + fCasterLatency = 0.0f; + iCastType = 0; + lastClickedPosit = NiPoint3::ZERO; + optionalTargetID = LWOOBJID_EMPTY; + originatorRot = NiQuaternion::IDENTITY; + uiSkillHandle = 0; + } + + EchoStartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, float _fCasterLatency = 0.0f, int _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, unsigned int _uiSkillHandle = 0) { + bUsedMouse = _bUsedMouse; + fCasterLatency = _fCasterLatency; + iCastType = _iCastType; + lastClickedPosit = _lastClickedPosit; + optionalOriginatorID = _optionalOriginatorID; + optionalTargetID = _optionalTargetID; + originatorRot = _originatorRot; + sBitStream = _sBitStream; + skillID = _skillID; + uiSkillHandle = _uiSkillHandle; + } + + EchoStartSkill(RakNet::BitStream* stream) { + bUsedMouse = false; + fCasterLatency = 0.0f; + iCastType = 0; + lastClickedPosit = NiPoint3::ZERO; + optionalTargetID = LWOOBJID_EMPTY; + originatorRot = NiQuaternion::IDENTITY; + uiSkillHandle = 0; + + Deserialize(stream); + } + + ~EchoStartSkill() { + } + + void Serialize(RakNet::BitStream* stream) { + stream->Write((unsigned short)MsgID); + + stream->Write(bUsedMouse); + + stream->Write(fCasterLatency != 0.0f); + if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); + + stream->Write(iCastType != 0); + if (iCastType != 0) stream->Write(iCastType); + + stream->Write(lastClickedPosit != NiPoint3::ZERO); + if (lastClickedPosit != NiPoint3::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); + + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); } - EchoStartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, float _fCasterLatency = 0.0f, int _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, unsigned int _uiSkillHandle = 0) { - bUsedMouse = _bUsedMouse; - fCasterLatency = _fCasterLatency; - iCastType = _iCastType; - lastClickedPosit = _lastClickedPosit; - optionalOriginatorID = _optionalOriginatorID; - optionalTargetID = _optionalTargetID; - originatorRot = _originatorRot; - sBitStream = _sBitStream; - skillID = _skillID; - uiSkillHandle = _uiSkillHandle; + stream->Write(skillID); + + stream->Write(uiSkillHandle != 0); + if (uiSkillHandle != 0) stream->Write(uiSkillHandle); + } + + bool Deserialize(RakNet::BitStream* stream) { + stream->Read(bUsedMouse); + + bool fCasterLatencyIsDefault{}; + stream->Read(fCasterLatencyIsDefault); + if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); + + bool iCastTypeIsDefault{}; + stream->Read(iCastTypeIsDefault); + if (iCastTypeIsDefault != 0) stream->Read(iCastType); + + bool lastClickedPositIsDefault{}; + stream->Read(lastClickedPositIsDefault); + if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); + + stream->Read(optionalOriginatorID); + + bool optionalTargetIDIsDefault{}; + stream->Read(optionalTargetIDIsDefault); + if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); + + bool originatorRotIsDefault{}; + stream->Read(originatorRotIsDefault); + if (originatorRotIsDefault != 0) stream->Read(originatorRot); + + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); } - EchoStartSkill(RakNet::BitStream* stream) { - bUsedMouse = false; - fCasterLatency = 0.0f; - iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; - optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; - uiSkillHandle = 0; + stream->Read(skillID); - Deserialize(stream); - } + bool uiSkillHandleIsDefault{}; + stream->Read(uiSkillHandleIsDefault); + if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); - ~EchoStartSkill() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); + return true; + } - stream->Write(bUsedMouse); - - stream->Write(fCasterLatency != 0.0f); - if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); - - stream->Write(iCastType != 0); - if (iCastType != 0) stream->Write(iCastType); - - stream->Write(lastClickedPosit != NiPoint3::ZERO); - if (lastClickedPosit != NiPoint3::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); - - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } - - stream->Write(skillID); - - stream->Write(uiSkillHandle != 0); - if (uiSkillHandle != 0) stream->Write(uiSkillHandle); - } - - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bUsedMouse); - - bool fCasterLatencyIsDefault{}; - stream->Read(fCasterLatencyIsDefault); - if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); - - bool iCastTypeIsDefault{}; - stream->Read(iCastTypeIsDefault); - if (iCastTypeIsDefault != 0) stream->Read(iCastType); - - bool lastClickedPositIsDefault{}; - stream->Read(lastClickedPositIsDefault); - if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); - - stream->Read(optionalOriginatorID); - - bool optionalTargetIDIsDefault{}; - stream->Read(optionalTargetIDIsDefault); - if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); - - bool originatorRotIsDefault{}; - stream->Read(originatorRotIsDefault); - if (originatorRotIsDefault != 0) stream->Read(originatorRot); - - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } - - stream->Read(skillID); - - bool uiSkillHandleIsDefault{}; - stream->Read(uiSkillHandleIsDefault); - if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); - - return true; - } - - bool bUsedMouse; - float fCasterLatency; - int iCastType; - NiPoint3 lastClickedPosit; - LWOOBJID optionalOriginatorID; - LWOOBJID optionalTargetID; - NiQuaternion originatorRot; - std::string sBitStream; - TSkillID skillID; - unsigned int uiSkillHandle; + bool bUsedMouse; + float fCasterLatency; + int iCastType; + NiPoint3 lastClickedPosit; + LWOOBJID optionalOriginatorID; + LWOOBJID optionalTargetID; + NiQuaternion originatorRot; + std::string sBitStream; + TSkillID skillID; + unsigned int uiSkillHandle; }; /* Same as sync skill but with different network options. An echo down to other clients that need to play the skill. */ class StartSkill { static const GAME_MSG MsgID = GAME_MSG_START_SKILL; - public: - StartSkill() { - bUsedMouse = false; - consumableItemID = LWOOBJID_EMPTY; - fCasterLatency = 0.0f; - iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; - optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; - uiSkillHandle = 0; + public: + StartSkill() { + bUsedMouse = false; + consumableItemID = LWOOBJID_EMPTY; + fCasterLatency = 0.0f; + iCastType = 0; + lastClickedPosit = NiPoint3::ZERO; + optionalTargetID = LWOOBJID_EMPTY; + originatorRot = NiQuaternion::IDENTITY; + uiSkillHandle = 0; + } + + StartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, LWOOBJID _consumableItemID = LWOOBJID_EMPTY, float _fCasterLatency = 0.0f, int _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, unsigned int _uiSkillHandle = 0) { + bUsedMouse = _bUsedMouse; + consumableItemID = _consumableItemID; + fCasterLatency = _fCasterLatency; + iCastType = _iCastType; + lastClickedPosit = _lastClickedPosit; + optionalOriginatorID = _optionalOriginatorID; + optionalTargetID = _optionalTargetID; + originatorRot = _originatorRot; + sBitStream = _sBitStream; + skillID = _skillID; + uiSkillHandle = _uiSkillHandle; + } + + StartSkill(RakNet::BitStream* stream) { + bUsedMouse = false; + consumableItemID = LWOOBJID_EMPTY; + fCasterLatency = 0.0f; + iCastType = 0; + lastClickedPosit = NiPoint3::ZERO; + optionalTargetID = LWOOBJID_EMPTY; + originatorRot = NiQuaternion::IDENTITY; + uiSkillHandle = 0; + + Deserialize(stream); + } + + ~StartSkill() { + } + + void Serialize(RakNet::BitStream* stream) { + stream->Write((unsigned short)MsgID); + + stream->Write(bUsedMouse); + + stream->Write(consumableItemID != LWOOBJID_EMPTY); + if (consumableItemID != LWOOBJID_EMPTY) stream->Write(consumableItemID); + + stream->Write(fCasterLatency != 0.0f); + if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); + + stream->Write(iCastType != 0); + if (iCastType != 0) stream->Write(iCastType); + + stream->Write(lastClickedPosit != NiPoint3::ZERO); + if (lastClickedPosit != NiPoint3::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); + + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); } - StartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, LWOOBJID _consumableItemID = LWOOBJID_EMPTY, float _fCasterLatency = 0.0f, int _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, unsigned int _uiSkillHandle = 0) { - bUsedMouse = _bUsedMouse; - consumableItemID = _consumableItemID; - fCasterLatency = _fCasterLatency; - iCastType = _iCastType; - lastClickedPosit = _lastClickedPosit; - optionalOriginatorID = _optionalOriginatorID; - optionalTargetID = _optionalTargetID; - originatorRot = _originatorRot; - sBitStream = _sBitStream; - skillID = _skillID; - uiSkillHandle = _uiSkillHandle; + stream->Write(skillID); + + stream->Write(uiSkillHandle != 0); + if (uiSkillHandle != 0) stream->Write(uiSkillHandle); + } + + bool Deserialize(RakNet::BitStream* stream) { + stream->Read(bUsedMouse); + + bool consumableItemIDIsDefault{}; + stream->Read(consumableItemIDIsDefault); + if (consumableItemIDIsDefault != 0) stream->Read(consumableItemID); + + bool fCasterLatencyIsDefault{}; + stream->Read(fCasterLatencyIsDefault); + if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); + + bool iCastTypeIsDefault{}; + stream->Read(iCastTypeIsDefault); + if (iCastTypeIsDefault != 0) stream->Read(iCastType); + + bool lastClickedPositIsDefault{}; + stream->Read(lastClickedPositIsDefault); + if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); + + stream->Read(optionalOriginatorID); + + bool optionalTargetIDIsDefault{}; + stream->Read(optionalTargetIDIsDefault); + if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); + + bool originatorRotIsDefault{}; + stream->Read(originatorRotIsDefault); + if (originatorRotIsDefault != 0) stream->Read(originatorRot); + + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); } - StartSkill(RakNet::BitStream* stream) { - bUsedMouse = false; - consumableItemID = LWOOBJID_EMPTY; - fCasterLatency = 0.0f; - iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; - optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; - uiSkillHandle = 0; + stream->Read(skillID); - Deserialize(stream); - } + bool uiSkillHandleIsDefault{}; + stream->Read(uiSkillHandleIsDefault); + if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); - ~StartSkill() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); + return true; + } - stream->Write(bUsedMouse); - - stream->Write(consumableItemID != LWOOBJID_EMPTY); - if (consumableItemID != LWOOBJID_EMPTY) stream->Write(consumableItemID); - - stream->Write(fCasterLatency != 0.0f); - if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); - - stream->Write(iCastType != 0); - if (iCastType != 0) stream->Write(iCastType); - - stream->Write(lastClickedPosit != NiPoint3::ZERO); - if (lastClickedPosit != NiPoint3::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); - - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } - - stream->Write(skillID); - - stream->Write(uiSkillHandle != 0); - if (uiSkillHandle != 0) stream->Write(uiSkillHandle); - } - - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bUsedMouse); - - bool consumableItemIDIsDefault{}; - stream->Read(consumableItemIDIsDefault); - if (consumableItemIDIsDefault != 0) stream->Read(consumableItemID); - - bool fCasterLatencyIsDefault{}; - stream->Read(fCasterLatencyIsDefault); - if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); - - bool iCastTypeIsDefault{}; - stream->Read(iCastTypeIsDefault); - if (iCastTypeIsDefault != 0) stream->Read(iCastType); - - bool lastClickedPositIsDefault{}; - stream->Read(lastClickedPositIsDefault); - if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); - - stream->Read(optionalOriginatorID); - - bool optionalTargetIDIsDefault{}; - stream->Read(optionalTargetIDIsDefault); - if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); - - bool originatorRotIsDefault{}; - stream->Read(originatorRotIsDefault); - if (originatorRotIsDefault != 0) stream->Read(originatorRot); - - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } - - stream->Read(skillID); - - bool uiSkillHandleIsDefault{}; - stream->Read(uiSkillHandleIsDefault); - if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); - - return true; - } - - bool bUsedMouse = false; - LWOOBJID consumableItemID{}; - float fCasterLatency{}; - int iCastType{}; - NiPoint3 lastClickedPosit{}; - LWOOBJID optionalOriginatorID{}; - LWOOBJID optionalTargetID{}; - NiQuaternion originatorRot{}; - std::string sBitStream = ""; - TSkillID skillID = 0; - unsigned int uiSkillHandle = 0; + bool bUsedMouse = false; + LWOOBJID consumableItemID{}; + float fCasterLatency{}; + int iCastType{}; + NiPoint3 lastClickedPosit{}; + LWOOBJID optionalOriginatorID{}; + LWOOBJID optionalTargetID{}; + NiQuaternion originatorRot{}; + std::string sBitStream = ""; + TSkillID skillID = 0; + unsigned int uiSkillHandle = 0; }; }; diff --git a/dGame/dGameMessages/PropertyDataMessage.cpp b/dGame/dGameMessages/PropertyDataMessage.cpp index 85eb54cb..853151c9 100644 --- a/dGame/dGameMessages/PropertyDataMessage.cpp +++ b/dGame/dGameMessages/PropertyDataMessage.cpp @@ -6,8 +6,7 @@ #include "dLogger.h" #include "CDClientManager.h" -void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) const -{ +void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) const { stream.Write(0); // - property id stream.Write(TemplateID); // - template id @@ -39,9 +38,9 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con stream.Write(0); // - zone code stream.Write(0); // - minimum price stream.Write(1); // - rent duration - + stream.Write(LastUpdatedTime); // - timestamp - + stream.Write(1); stream.Write(reputation); // Reputation @@ -52,7 +51,7 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con for (uint32_t i = 0; i < spawn.size(); ++i) { stream.Write(uint16_t(spawn[i])); } - + stream.Write(0); // String length stream.Write(0); // String length @@ -89,13 +88,12 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con stream.Write(MaxBuildHeight); stream.Write(ClaimedTime); // - timestamp - + stream.Write(PrivacyOption); stream.Write(uint32_t(Paths.size())); - for (const auto& path : Paths) - { + for (const auto& path : Paths) { stream.Write(path.x); stream.Write(path.y); stream.Write(path.z); @@ -103,11 +101,11 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con } GameMessages::PropertyDataMessage::PropertyDataMessage(uint32_t mapID) { - const auto propertyTemplate = CDClientManager::Instance()-> - GetTable("PropertyTemplate")->GetByMapID(mapID); + const auto propertyTemplate = CDClientManager::Instance()-> + GetTable("PropertyTemplate")->GetByMapID(mapID); - TemplateID = propertyTemplate.id; - ZoneId = propertyTemplate.mapID; - VendorMapId = propertyTemplate.vendorMapID; - SpawnName = propertyTemplate.spawnName; + TemplateID = propertyTemplate.id; + ZoneId = propertyTemplate.mapID; + VendorMapId = propertyTemplate.vendorMapID; + SpawnName = propertyTemplate.spawnName; } diff --git a/dGame/dGameMessages/PropertyDataMessage.h b/dGame/dGameMessages/PropertyDataMessage.h index 5b5d7d0f..819c5dbb 100644 --- a/dGame/dGameMessages/PropertyDataMessage.h +++ b/dGame/dGameMessages/PropertyDataMessage.h @@ -8,12 +8,11 @@ #include "NiPoint3.h" #include "dCommonVars.h" -namespace GameMessages -{ +namespace GameMessages { class PropertyDataMessage final { public: - explicit PropertyDataMessage(uint32_t mapID); + explicit PropertyDataMessage(uint32_t mapID); void Serialize(RakNet::BitStream& stream) const; @@ -47,4 +46,4 @@ namespace GameMessages REJECTION_STATUS_REJECTED = 2 }; }; -} \ No newline at end of file +} diff --git a/dGame/dGameMessages/PropertySelectQueryProperty.cpp b/dGame/dGameMessages/PropertySelectQueryProperty.cpp index 38e7cea2..18d23d2b 100644 --- a/dGame/dGameMessages/PropertySelectQueryProperty.cpp +++ b/dGame/dGameMessages/PropertySelectQueryProperty.cpp @@ -1,8 +1,7 @@ #include "PropertySelectQueryProperty.h" -void PropertySelectQueryProperty::Serialize(RakNet::BitStream& stream) const -{ - stream.Write(CloneId); +void PropertySelectQueryProperty::Serialize(RakNet::BitStream& stream) const { + stream.Write(CloneId); const auto& owner = GeneralUtils::ASCIIToUTF16(OwnerName); stream.Write(uint32_t(owner.size())); @@ -34,7 +33,6 @@ void PropertySelectQueryProperty::Serialize(RakNet::BitStream& stream) const stream.Write(PerformanceCost); } -void PropertySelectQueryProperty::Deserialize(RakNet::BitStream& stream) const -{ - // Do we need this? +void PropertySelectQueryProperty::Deserialize(RakNet::BitStream& stream) const { + // Do we need this? } diff --git a/dGame/dGameMessages/PropertySelectQueryProperty.h b/dGame/dGameMessages/PropertySelectQueryProperty.h index e633f41b..7826900d 100644 --- a/dGame/dGameMessages/PropertySelectQueryProperty.h +++ b/dGame/dGameMessages/PropertySelectQueryProperty.h @@ -12,20 +12,20 @@ public: void Deserialize(RakNet::BitStream& stream) const; - LWOCLONEID CloneId = LWOCLONEID_INVALID; // The cloneID of the property - std::string OwnerName = ""; // The property owners name - std::string Name = ""; // The property name - std::string Description = ""; // The property description - float Reputation = 0; // The reputation of the property - bool IsBestFriend = false; // Whether or not the property belongs to a best friend - bool IsFriend = false; // Whether or not the property belongs to a friend - bool IsModeratorApproved = false; // Whether or not a moderator has approved this property - bool IsAlt = false; // Whether or not the property is owned by an alt of the account owner - bool IsOwned = false; // Whether or not the property is owned - uint32_t AccessType = 0; // The privacy option of the property - uint32_t DateLastPublished = 0; // The last day the property was published - float PerformanceCost = 0; // The performance cost of the property - uint32_t PerformanceIndex = 0; // The performance index of the property? Always 0? + LWOCLONEID CloneId = LWOCLONEID_INVALID; // The cloneID of the property + std::string OwnerName = ""; // The property owners name + std::string Name = ""; // The property name + std::string Description = ""; // The property description + float Reputation = 0; // The reputation of the property + bool IsBestFriend = false; // Whether or not the property belongs to a best friend + bool IsFriend = false; // Whether or not the property belongs to a friend + bool IsModeratorApproved = false; // Whether or not a moderator has approved this property + bool IsAlt = false; // Whether or not the property is owned by an alt of the account owner + bool IsOwned = false; // Whether or not the property is owned + uint32_t AccessType = 0; // The privacy option of the property + uint32_t DateLastPublished = 0; // The last day the property was published + float PerformanceCost = 0; // The performance cost of the property + uint32_t PerformanceIndex = 0; // The performance index of the property? Always 0? }; #endif diff --git a/dGame/dInventory/DatabasePet.h b/dGame/dInventory/DatabasePet.h index 068c6195..2dd8649a 100644 --- a/dGame/dInventory/DatabasePet.h +++ b/dGame/dInventory/DatabasePet.h @@ -7,20 +7,20 @@ */ struct DatabasePet { - /** - * The lot of this pet - */ - LOT lot = LOT_NULL; + /** + * The lot of this pet + */ + LOT lot = LOT_NULL; - /** - * The name of the pet - */ - std::string name; + /** + * The name of the pet + */ + std::string name; - /** - * The current moderation state, see PetComponent for more info - */ - int32_t moderationState = 0; + /** + * The current moderation state, see PetComponent for more info + */ + int32_t moderationState = 0; }; const DatabasePet DATABASE_PET_INVALID; diff --git a/dGame/dInventory/EquippedItem.h b/dGame/dInventory/EquippedItem.h index cf5ba253..78da9e8d 100644 --- a/dGame/dInventory/EquippedItem.h +++ b/dGame/dInventory/EquippedItem.h @@ -8,24 +8,24 @@ */ struct EquippedItem { - /** - * The object ID of the equipped item - */ + /** + * The object ID of the equipped item + */ LWOOBJID id = LWOOBJID_EMPTY; - /** - * The LOT of this equipped item - */ + /** + * The LOT of this equipped item + */ LOT lot = LOT_NULL; - /** - * The number of items that are stored in this slot - */ + /** + * The number of items that are stored in this slot + */ uint32_t count = 0; - /** - * The slot this item is stored in - */ + /** + * The slot this item is stored in + */ uint32_t slot = 0; /** diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index 012bcacf..151e3164 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -14,40 +14,33 @@ std::vector Inventory::m_GameMasterRestrictedItems = { 14442 // The jamesster jetpack }; -Inventory::Inventory(const eInventoryType type, const uint32_t size, const std::vector& items, InventoryComponent* component) -{ +Inventory::Inventory(const eInventoryType type, const uint32_t size, const std::vector& items, InventoryComponent* component) { this->type = type; this->size = size; this->free = size; this->component = component; - for (auto* item : items) - { + for (auto* item : items) { AddManagedItem(item); } } -eInventoryType Inventory::GetType() const -{ +eInventoryType Inventory::GetType() const { return type; } -uint32_t Inventory::GetSize() const -{ +uint32_t Inventory::GetSize() const { return size; } -std::map& Inventory::GetItems() -{ +std::map& Inventory::GetItems() { return items; } -std::map Inventory::GetSlots() const -{ +std::map Inventory::GetSlots() const { std::map slots; - for (const auto& pair : items) - { + for (const auto& pair : items) { auto* item = pair.second; slots.insert_or_assign(item->GetSlot(), item); @@ -56,21 +49,17 @@ std::map Inventory::GetSlots() const return slots; } -InventoryComponent* Inventory::GetComponent() const -{ +InventoryComponent* Inventory::GetComponent() const { return component; } -uint32_t Inventory::GetLotCount(const LOT lot) const -{ +uint32_t Inventory::GetLotCount(const LOT lot) const { uint32_t count = 0; - for (const auto& pair : items) - { + for (const auto& pair : items) { const auto* item = pair.second; - if (item->GetLot() == lot) - { + if (item->GetLot() == lot) { count += item->GetCount(); } } @@ -78,8 +67,7 @@ uint32_t Inventory::GetLotCount(const LOT lot) const return count; } -void Inventory::SetSize(const uint32_t value) -{ +void Inventory::SetSize(const uint32_t value) { free += static_cast(value) - static_cast(size); size = value; @@ -87,45 +75,34 @@ void Inventory::SetSize(const uint32_t value) GameMessages::SendSetInventorySize(component->GetParent(), type, static_cast(size)); } -int32_t Inventory::FindEmptySlot() -{ +int32_t Inventory::FindEmptySlot() { if (free <= 6) // Up from 1 { - if (type != ITEMS && type != VAULT_ITEMS && type != eInventoryType::VAULT_MODELS) - { + if (type != ITEMS && type != VAULT_ITEMS && type != eInventoryType::VAULT_MODELS) { uint32_t newSize = size; - if (type == MODELS) - { + if (type == MODELS) { newSize = 240; - } - else if (type == eInventoryType::VENDOR_BUYBACK) - { + } else if (type == eInventoryType::VENDOR_BUYBACK) { newSize += 9u; - } - else - { + } else { newSize += 10u; } - if (newSize > GetSize()) - { + if (newSize > GetSize()) { SetSize(newSize); } } } - if (free == 0) - { + if (free == 0) { return -1; } const auto slots = GetSlots(); - for (auto i = 0u; i < size; ++i) - { - if (slots.find(i) == slots.end()) - { + for (auto i = 0u; i < size; ++i) { + if (slots.find(i) == slots.end()) { return i; } } @@ -133,13 +110,11 @@ int32_t Inventory::FindEmptySlot() return -1; } -int32_t Inventory::GetEmptySlots() -{ +int32_t Inventory::GetEmptySlots() { return free; } -bool Inventory::IsSlotEmpty(int32_t slot) -{ +bool Inventory::IsSlotEmpty(int32_t slot) { const auto slots = GetSlots(); const auto& index = slots.find(slot); @@ -147,50 +122,41 @@ bool Inventory::IsSlotEmpty(int32_t slot) return index == slots.end(); } -Item* Inventory::FindItemById(const LWOOBJID id) const -{ +Item* Inventory::FindItemById(const LWOOBJID id) const { const auto& index = items.find(id); - if (index == items.end()) - { + if (index == items.end()) { return nullptr; } return index->second; } -Item* Inventory::FindItemByLot(const LOT lot, const bool ignoreEquipped, const bool ignoreBound) const -{ +Item* Inventory::FindItemByLot(const LOT lot, const bool ignoreEquipped, const bool ignoreBound) const { Item* smallest = nullptr; - for (const auto& pair : items) - { + for (const auto& pair : items) { auto* item = pair.second; - if (item->GetLot() != lot) - { + if (item->GetLot() != lot) { continue; } - if (ignoreEquipped && item->IsEquipped()) - { + if (ignoreEquipped && item->IsEquipped()) { continue; } - if (ignoreBound && item->GetBound()) - { + if (ignoreBound && item->GetBound()) { continue; } - if (smallest == nullptr) - { + if (smallest == nullptr) { smallest = item; continue; } - if (smallest->GetCount() > item->GetCount()) - { + if (smallest->GetCount() > item->GetCount()) { smallest = item; } } @@ -198,26 +164,21 @@ Item* Inventory::FindItemByLot(const LOT lot, const bool ignoreEquipped, const b return smallest; } -Item* Inventory::FindItemBySlot(const uint32_t slot) const -{ +Item* Inventory::FindItemBySlot(const uint32_t slot) const { const auto slots = GetSlots(); const auto index = slots.find(slot); - if (index == slots.end()) - { + if (index == slots.end()) { return nullptr; } return index->second; } -Item* Inventory::FindItemBySubKey(LWOOBJID id) const -{ - for (const auto& item : items) - { - if (item.second->GetSubKey() == id) - { +Item* Inventory::FindItemBySubKey(LWOOBJID id) const { + for (const auto& item : items) { + if (item.second->GetSubKey() == id) { return item.second; } } @@ -225,12 +186,10 @@ Item* Inventory::FindItemBySubKey(LWOOBJID id) const return nullptr; } -void Inventory::AddManagedItem(Item* item) -{ +void Inventory::AddManagedItem(Item* item) { const auto id = item->GetId(); - if (items.find(id) != items.end()) - { + if (items.find(id) != items.end()) { Game::logger->Log("Inventory", "Attempting to add an item with an already present id (%llu)!", id); return; @@ -240,8 +199,7 @@ void Inventory::AddManagedItem(Item* item) const auto slot = item->GetSlot(); - if (slots.find(slot) != slots.end()) - { + if (slots.find(slot) != slots.end()) { Game::logger->Log("Inventory", "Attempting to add an item with an already present slot (%i)!", slot); return; @@ -252,12 +210,10 @@ void Inventory::AddManagedItem(Item* item) free--; } -void Inventory::RemoveManagedItem(Item* item) -{ +void Inventory::RemoveManagedItem(Item* item) { const auto id = item->GetId(); - if (items.find(id) == items.end()) - { + if (items.find(id) == items.end()) { Game::logger->Log("Inventory", "Attempting to remove an item with an invalid id (%llu), lot (%i)!", id, item->GetLot()); return; @@ -268,8 +224,7 @@ void Inventory::RemoveManagedItem(Item* item) free++; } -eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) -{ +eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) { auto itemComponent = FindItemComponent(lot); const auto itemType = static_cast(itemComponent.itemType); @@ -315,16 +270,14 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) } } -const CDItemComponent& Inventory::FindItemComponent(const LOT lot) -{ +const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { auto* registry = CDClientManager::Instance()->GetTable("ComponentsRegistry"); auto* itemComponents = CDClientManager::Instance()->GetTable("ItemComponent"); const auto componentId = registry->GetByIDAndType(lot, COMPONENT_TYPE_ITEM); - if (componentId == 0) - { + if (componentId == 0) { Game::logger->Log("Inventory", "Failed to find item component for (%i)!", lot); return CDItemComponentTable::Default; @@ -335,8 +288,7 @@ const CDItemComponent& Inventory::FindItemComponent(const LOT lot) return itemComponent; } -bool Inventory::IsValidItem(const LOT lot) -{ +bool Inventory::IsValidItem(const LOT lot) { auto* registry = CDClientManager::Instance()->GetTable("ComponentsRegistry"); const auto componentId = registry->GetByIDAndType(lot, COMPONENT_TYPE_ITEM); @@ -344,15 +296,12 @@ bool Inventory::IsValidItem(const LOT lot) return componentId != 0; } -const std::vector& Inventory::GetAllGMItems() -{ +const std::vector& Inventory::GetAllGMItems() { return m_GameMasterRestrictedItems; } -Inventory::~Inventory() -{ - for (auto item : items) - { +Inventory::~Inventory() { + for (auto item : items) { delete item.second; } diff --git a/dGame/dInventory/Inventory.h b/dGame/dInventory/Inventory.h index b65a2040..1f7bb425 100644 --- a/dGame/dInventory/Inventory.h +++ b/dGame/dInventory/Inventory.h @@ -21,168 +21,168 @@ class Inventory final public: explicit Inventory(eInventoryType type, uint32_t size, const std::vector& items, InventoryComponent* component); - /** - * Returns the type of this inventory - * @return the type of this inventory - */ + /** + * Returns the type of this inventory + * @return the type of this inventory + */ eInventoryType GetType() const; - /** - * Returns the maximum amount of items this inventory can contain - * @return the maximum amount of items this inventory can contain - */ + /** + * Returns the maximum amount of items this inventory can contain + * @return the maximum amount of items this inventory can contain + */ uint32_t GetSize() const; - /** - * Returns all the items that are currently in this inventory, mapped by object ID - * @return all the items that are currently in this inventory, mapped by object ID - */ + /** + * Returns all the items that are currently in this inventory, mapped by object ID + * @return all the items that are currently in this inventory, mapped by object ID + */ std::map& GetItems(); - /** - * Returns all the items that are currently in this inventory, mapped by slot - * @return all the items that are currently in this inventory, mapped by slot - */ + /** + * Returns all the items that are currently in this inventory, mapped by slot + * @return all the items that are currently in this inventory, mapped by slot + */ std::map GetSlots() const; - /** - * Returns the inventory component that this inventory is part of - * @return the inventory component that this inventory is part of - */ + /** + * Returns the inventory component that this inventory is part of + * @return the inventory component that this inventory is part of + */ InventoryComponent* GetComponent() const; - /** - * Returns the amount of items this inventory contains of the specified LOT - * @param lot the lot to find items for - * @return the amount of items this inventory contains of the specified LOT - */ + /** + * Returns the amount of items this inventory contains of the specified LOT + * @param lot the lot to find items for + * @return the amount of items this inventory contains of the specified LOT + */ uint32_t GetLotCount(LOT lot) const; - /** - * Updates the max size of this inventory - * @param value the size to set - */ + /** + * Updates the max size of this inventory + * @param value the size to set + */ void SetSize(uint32_t value); - /** - * Returns the first slot in this inventory that does not contain an item - * @return the first slot in this inventory that does not contain an item - */ + /** + * Returns the first slot in this inventory that does not contain an item + * @return the first slot in this inventory that does not contain an item + */ int32_t FindEmptySlot(); - /** - * Returns the number of empty slots this inventory has left - * @return the number of empty slots this inventory has left - */ + /** + * Returns the number of empty slots this inventory has left + * @return the number of empty slots this inventory has left + */ int32_t GetEmptySlots(); - /** - * Returns if the slot for the specified index is empty - * @param slot the index to check occupation for - * @return if the slot for the specified index is empty - */ + /** + * Returns if the slot for the specified index is empty + * @param slot the index to check occupation for + * @return if the slot for the specified index is empty + */ bool IsSlotEmpty(int32_t slot); - /** - * Finds an item in this inventory by the provided id - * @param id the object ID of the item to find - * @return item in this inventory by the provided id - */ + /** + * Finds an item in this inventory by the provided id + * @param id the object ID of the item to find + * @return item in this inventory by the provided id + */ Item* FindItemById(LWOOBJID id) const; - /** - * Finds an item in the inventory for the provided LOT - * @param lot the lot to find items for - * @param ignoreEquipped ignores equipped items - * @param ignoreBound ignores bound items - * @return item in the inventory for the provided LOT - */ + /** + * Finds an item in the inventory for the provided LOT + * @param lot the lot to find items for + * @param ignoreEquipped ignores equipped items + * @param ignoreBound ignores bound items + * @return item in the inventory for the provided LOT + */ Item* FindItemByLot(LOT lot, bool ignoreEquipped = false, bool ignoreBound = false) const; - /** - * Finds an item in the inventory stored on the provied slot - * @param slot to slot to find an item for - * @return item in the inventory stored on the provied slot - */ + /** + * Finds an item in the inventory stored on the provied slot + * @param slot to slot to find an item for + * @return item in the inventory stored on the provied slot + */ Item* FindItemBySlot(uint32_t slot) const; - /** - * Finds an item based on a specified subkey (useful for pets) - * @param id the subkey to look for in the items - * @return item based on a specified subkey - */ + /** + * Finds an item based on a specified subkey (useful for pets) + * @param id the subkey to look for in the items + * @return item based on a specified subkey + */ Item* FindItemBySubKey(LWOOBJID id) const; - /** - * Adds an item to the inventory, finding a slot to place it in - * @param item item to add to the inventory - */ + /** + * Adds an item to the inventory, finding a slot to place it in + * @param item item to add to the inventory + */ void AddManagedItem(Item* item); - /** - * Removes an item from the inventory, clearing its slot - * @param item - */ + /** + * Removes an item from the inventory, clearing its slot + * @param item + */ void RemoveManagedItem(Item* item); - /** - * Returns the inventory type an item of the specified lot should be placed in - * @param lot the lot to find the inventory type for - * @return the inventory type an item of the specified lot should be placed in - */ + /** + * Returns the inventory type an item of the specified lot should be placed in + * @param lot the lot to find the inventory type for + * @return the inventory type an item of the specified lot should be placed in + */ static eInventoryType FindInventoryTypeForLot(LOT lot); - /** - * Finds the database item component for a item of a certain LOT - * @param lot the LOT of the item to get the database item component for - * @return the database item component for a item of a certain LOT - */ + /** + * Finds the database item component for a item of a certain LOT + * @param lot the LOT of the item to get the database item component for + * @return the database item component for a item of a certain LOT + */ static const CDItemComponent& FindItemComponent(LOT lot); - /** - * Cheks if the provided lot has a database item component - * @param lot the LOT to check item validity for - * @return if the provided lot has a database item component - */ + /** + * Cheks if the provided lot has a database item component + * @param lot the LOT to check item validity for + * @return if the provided lot has a database item component + */ static bool IsValidItem(LOT lot); - /** - * Returns all the items that are restricted to GMs - * @return all the items that are restricted to GMs - */ + /** + * Returns all the items that are restricted to GMs + * @return all the items that are restricted to GMs + */ static const std::vector& GetAllGMItems(); - + ~Inventory(); private: - /** - * The type of this inventory - */ + /** + * The type of this inventory + */ eInventoryType type; - /** - * The max size of this inventory - */ + /** + * The max size of this inventory + */ uint32_t size; - /** - * The amount of items that can still be stored in this inventroy - */ + /** + * The amount of items that can still be stored in this inventroy + */ uint32_t free; - /** - * The items stored in this inventory - */ + /** + * The items stored in this inventory + */ std::map items; - /** - * The inventory component this inventory belongs to - */ + /** + * The inventory component this inventory belongs to + */ InventoryComponent* component; - /** - * List of items that are GM restricted - */ + /** + * List of items that are GM restricted + */ static std::vector m_GameMasterRestrictedItems; }; diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 71ded509..b502d5eb 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -14,10 +14,8 @@ class Inventory; -Item::Item(const LWOOBJID id, const LOT lot, Inventory* inventory, const uint32_t slot, const uint32_t count, const bool bound, const std::vector& config, const LWOOBJID parent, LWOOBJID subKey, eLootSourceType lootSourceType) -{ - if (!Inventory::IsValidItem(lot)) - { +Item::Item(const LWOOBJID id, const LOT lot, Inventory* inventory, const uint32_t slot, const uint32_t count, const bool bound, const std::vector& config, const LWOOBJID parent, LWOOBJID subKey, eLootSourceType lootSourceType) { + if (!Inventory::IsValidItem(lot)) { return; } @@ -47,15 +45,12 @@ Item::Item( bool isModMoveAndEquip, LWOOBJID subKey, bool bound, - eLootSourceType lootSourceType) -{ - if (!Inventory::IsValidItem(lot)) - { + eLootSourceType lootSourceType) { + if (!Inventory::IsValidItem(lot)) { return; } - if (isModMoveAndEquip) - { + if (isModMoveAndEquip) { showFlyingLoot = false; } @@ -83,8 +78,7 @@ Item::Item( auto* entity = inventory->GetComponent()->GetParent(); GameMessages::SendAddItemToInventoryClientSync(entity, entity->GetSystemAddress(), this, id, showFlyingLoot, static_cast(this->count), subKey, lootSourceType); - if (isModMoveAndEquip) - { + if (isModMoveAndEquip) { Equip(); Game::logger->Log("Item", "Move and equipped (%i) from (%i)", this->lot, this->inventory->GetType()); @@ -93,65 +87,52 @@ Item::Item( } } -LWOOBJID Item::GetId() const -{ +LWOOBJID Item::GetId() const { return id; } -LOT Item::GetLot() const -{ +LOT Item::GetLot() const { return lot; } -uint32_t Item::GetCount() const -{ +uint32_t Item::GetCount() const { return count; } -uint32_t Item::GetSlot() const -{ +uint32_t Item::GetSlot() const { return slot; } -std::vector& Item::GetConfig() -{ +std::vector& Item::GetConfig() { return config; } -const CDItemComponent& Item::GetInfo() const -{ +const CDItemComponent& Item::GetInfo() const { return *info; } -bool Item::GetBound() const -{ +bool Item::GetBound() const { return bound; } -Inventory* Item::GetInventory() const -{ +Inventory* Item::GetInventory() const { return inventory; } -LWOOBJID Item::GetParent() const -{ +LWOOBJID Item::GetParent() const { return parent; } -LWOOBJID Item::GetSubKey() const -{ +LWOOBJID Item::GetSubKey() const { return subKey; } -PreconditionExpression* Item::GetPreconditionExpression() const -{ +PreconditionExpression* Item::GetPreconditionExpression() const { return preconditions; } -void Item::SetCount(const uint32_t value, const bool silent, const bool disassemble, const bool showFlyingLoot, eLootSourceType lootSourceType) -{ - if (value == count) - { +void Item::SetCount(const uint32_t value, const bool silent, const bool disassemble, const bool showFlyingLoot, eLootSourceType lootSourceType) { + if (value == count) { return; } @@ -159,52 +140,40 @@ void Item::SetCount(const uint32_t value, const bool silent, const bool disassem const auto type = static_cast(info->itemType); - if (disassemble) - { - if (value < count) - { - for (auto i = 0; i < delta; ++i) - { + if (disassemble) { + if (value < count) { + for (auto i = 0; i < delta; ++i) { Disassemble(); } } } - if (!silent) - { + if (!silent) { auto* entity = inventory->GetComponent()->GetParent(); - if (value > count) - { + if (value > count) { GameMessages::SendAddItemToInventoryClientSync(entity, entity->GetSystemAddress(), this, id, showFlyingLoot, delta, LWOOBJID_EMPTY, lootSourceType); - } - else - { + } else { GameMessages::SendRemoveItemFromInventory(entity, entity->GetSystemAddress(), id, lot, inventory->GetType(), delta, value); } } count = value; - if (count == 0) - { + if (count == 0) { RemoveFromInventory(); } } -void Item::SetSlot(const uint32_t value) -{ - if (slot == value) - { +void Item::SetSlot(const uint32_t value) { + if (slot == value) { return; } - for (const auto& pair : inventory->GetItems()) - { + for (const auto& pair : inventory->GetItems()) { auto* item = pair.second; - if (item->slot == value) - { + if (item->slot == value) { item->slot = slot; } } @@ -212,18 +181,15 @@ void Item::SetSlot(const uint32_t value) slot = value; } -void Item::SetBound(const bool value) -{ +void Item::SetBound(const bool value) { bound = value; } -void Item::SetSubKey(LWOOBJID value) -{ +void Item::SetSubKey(LWOOBJID value) { subKey = value; } -void Item::SetInventory(Inventory* value) -{ +void Item::SetInventory(Inventory* value) { inventory->RemoveManagedItem(this); inventory = value; @@ -231,36 +197,29 @@ void Item::SetInventory(Inventory* value) inventory->AddManagedItem(this); } -void Item::Equip(const bool skipChecks) -{ - if (IsEquipped()) - { +void Item::Equip(const bool skipChecks) { + if (IsEquipped()) { return; } inventory->GetComponent()->EquipItem(this, skipChecks); } -void Item::UnEquip() -{ - if (!IsEquipped()) - { +void Item::UnEquip() { + if (!IsEquipped()) { return; } inventory->GetComponent()->UnEquipItem(this); } -bool Item::IsEquipped() const -{ +bool Item::IsEquipped() const { auto* component = inventory->GetComponent(); - for (const auto& pair : component->GetEquippedItems()) - { + for (const auto& pair : component->GetEquippedItems()) { const auto item = pair.second; - if (item.id == id) - { + if (item.id == id) { return true; } } @@ -268,19 +227,16 @@ bool Item::IsEquipped() const return false; } -bool Item::Consume() -{ +bool Item::Consume() { auto* skillsTable = CDClientManager::Instance()->GetTable("ObjectSkills"); - auto skills = skillsTable->Query([=](const CDObjectSkills entry) - { + auto skills = skillsTable->Query([=](const CDObjectSkills entry) { return entry.objectTemplate == static_cast(lot); - }); + }); auto success = false; - for (auto& skill : skills) - { + for (auto& skill : skills) { if (skill.castOnType == 3) // Consumable type { success = true; @@ -291,16 +247,14 @@ bool Item::Consume() GameMessages::SendUseItemResult(inventory->GetComponent()->GetParent(), lot, success); - if (success) - { + if (success) { inventory->GetComponent()->RemoveItem(lot, 1); } return success; } -bool Item::UseNonEquip() -{ +bool Item::UseNonEquip() { auto* compRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_PACKAGE); @@ -315,29 +269,24 @@ bool Item::UseNonEquip() auto playerEntity = inventoryComponent->GetParent(); - if (subKey != LWOOBJID_EMPTY) - { + if (subKey != LWOOBJID_EMPTY) { const auto& databasePet = GetInventory()->GetComponent()->GetDatabasePet(subKey); - if (databasePet.lot != LOT_NULL) - { + if (databasePet.lot != LOT_NULL) { GetInventory()->GetComponent()->SpawnPet(this); return true; } } - if (success && (playerEntity->GetGMLevel() >= eGameMasterLevel::GAME_MASTER_LEVEL_JUNIOR_DEVELOPER || this->GetPreconditionExpression()->Check(playerEntity))) - { + if (success && (playerEntity->GetGMLevel() >= eGameMasterLevel::GAME_MASTER_LEVEL_JUNIOR_DEVELOPER || this->GetPreconditionExpression()->Check(playerEntity))) { auto* entityParent = inventory->GetComponent()->GetParent(); - for (auto& pack : packages) - { - std::unordered_map result {}; + for (auto& pack : packages) { + std::unordered_map result{}; result = LootGenerator::Instance().RollLootMatrix(entityParent, pack.LootMatrixIndex); - if (!inventory->GetComponent()->HasSpaceForLoot(result)) - { + if (!inventory->GetComponent()->HasSpaceForLoot(result)) { return false; } @@ -350,12 +299,9 @@ bool Item::UseNonEquip() return success; } -void Item::Disassemble(const eInventoryType inventoryType) -{ - for (auto* data : config) - { - if (data->GetKey() == u"assemblyPartLOTs") - { +void Item::Disassemble(const eInventoryType inventoryType) { + for (auto* data : config) { + if (data->GetKey() == u"assemblyPartLOTs") { auto modStr = data->GetValueAsString(); std::vector modArray; @@ -366,35 +312,31 @@ void Item::Disassemble(const eInventoryType inventoryType) const auto deliminator = '+'; - while (std::getline(ssData, token, deliminator)) - { + while (std::getline(ssData, token, deliminator)) { const auto modLot = std::stoi(token.substr(2, token.size() - 1)); modArray.push_back(modLot); } - for (const auto mod : modArray) - { + for (const auto mod : modArray) { inventory->GetComponent()->AddItem(mod, 1, eLootSourceType::LOOT_SOURCE_DELETION, inventoryType); } } } } -void Item::DisassembleModel() -{ +void Item::DisassembleModel() { auto* table = CDClientManager::Instance()->GetTable("ComponentsRegistry"); const auto componentId = table->GetByIDAndType(GetLot(), COMPONENT_TYPE_RENDER); auto query = CDClientDatabase::CreatePreppedStmt( "SELECT render_asset FROM RenderComponent WHERE id = ?;"); - query.bind(1, (int) componentId); + query.bind(1, (int)componentId); auto result = query.execQuery(); - if (result.eof()) - { + if (result.eof()) { return; } @@ -406,28 +348,24 @@ void Item::DisassembleModel() result.finalize(); - if (!file.good()) - { + if (!file.good()) { return; } std::stringstream data; data << file.rdbuf(); - if (data.str().empty()) - { + if (data.str().empty()) { return; } auto* doc = new tinyxml2::XMLDocument(); - if (!doc) - { + if (!doc) { return; } - if (doc->Parse(data.str().c_str(), data.str().size()) != 0) - { + if (doc->Parse(data.str().c_str(), data.str().size()) != 0) { return; } @@ -437,22 +375,18 @@ void Item::DisassembleModel() auto* bricks = lxfml->FirstChildElement("Bricks"); std::string searchTerm = "Brick"; - if (!bricks) - { + if (!bricks) { searchTerm = "Part"; bricks = lxfml->FirstChildElement("Scene")->FirstChildElement("Model")->FirstChildElement("Group"); - if (!bricks) - { + if (!bricks) { return; } } auto* currentBrick = bricks->FirstChildElement(searchTerm.c_str()); - while (currentBrick) - { - if (currentBrick->Attribute("designID") != nullptr) - { + while (currentBrick) { + if (currentBrick->Attribute("designID") != nullptr) { parts.push_back(std::stoi(currentBrick->Attribute("designID"))); } @@ -461,15 +395,12 @@ void Item::DisassembleModel() auto* brickIDTable = CDClientManager::Instance()->GetTable("BrickIDTable"); - for (unsigned int part : parts) - { - const auto brickID = brickIDTable->Query([=](const CDBrickIDTable& entry) - { + for (unsigned int part : parts) { + const auto brickID = brickIDTable->Query([=](const CDBrickIDTable& entry) { return entry.LEGOBrickID == part; - }); + }); - if (brickID.empty()) - { + if (brickID.empty()) { continue; } @@ -477,8 +408,7 @@ void Item::DisassembleModel() } } -void Item::RemoveFromInventory() -{ +void Item::RemoveFromInventory() { UnEquip(); count = 0; @@ -488,12 +418,10 @@ void Item::RemoveFromInventory() delete this; } -Item::~Item() -{ +Item::~Item() { delete preconditions; - for (auto* value : config) - { + for (auto* value : config) { delete value; } diff --git a/dGame/dInventory/Item.h b/dGame/dInventory/Item.h index 0be9449a..3987471c 100644 --- a/dGame/dInventory/Item.h +++ b/dGame/dInventory/Item.h @@ -15,18 +15,18 @@ class Item final { public: - /** - * Creates an item, should be used if the item is not picked up but already exists - * @param id the object ID of the item to create - * @param lot the LOT of the item - * @param inventory the inventory to add this item to - * @param slot the slot in the inventory to add this item to - * @param count the amount of items to add to the inventory - * @param bound if the item should be bound - * @param config config data for this item, e.g. for rockets - * @param parent optional parent of this item, e.g. for proxy items - * @param subKey optional subkey for this item, e.g. for pets - */ + /** + * Creates an item, should be used if the item is not picked up but already exists + * @param id the object ID of the item to create + * @param lot the LOT of the item + * @param inventory the inventory to add this item to + * @param slot the slot in the inventory to add this item to + * @param count the amount of items to add to the inventory + * @param bound if the item should be bound + * @param config config data for this item, e.g. for rockets + * @param parent optional parent of this item, e.g. for proxy items + * @param subKey optional subkey for this item, e.g. for pets + */ explicit Item( LWOOBJID id, LOT lot, @@ -37,22 +37,22 @@ public: const std::vector& config, LWOOBJID parent, LWOOBJID subKey, - eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE + eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE ); - /** - * Creates an item, should be used if the item is picked up / added to the inventory after load - * @param lot the LOT of the item - * @param inventory the inventory to add this item to - * @param slot the slot in the inventory to add this item to - * @param count the amount of items to add to the inventory - * @param config config data for this item, e.g. for rockets - * @param parent optional parent of this item, e.g. for proxy items - * @param showFlyingLoot show UI animation of the item being added - * @param isModMoveAndEquip equips the item - * @param subKey optional subkey for this item, e.g. for pets - * @param bound if the item should be bound - */ + /** + * Creates an item, should be used if the item is picked up / added to the inventory after load + * @param lot the LOT of the item + * @param inventory the inventory to add this item to + * @param slot the slot in the inventory to add this item to + * @param count the amount of items to add to the inventory + * @param config config data for this item, e.g. for rockets + * @param parent optional parent of this item, e.g. for proxy items + * @param showFlyingLoot show UI animation of the item being added + * @param isModMoveAndEquip equips the item + * @param subKey optional subkey for this item, e.g. for pets + * @param bound if the item should be bound + */ explicit Item( LOT lot, Inventory* inventory, @@ -64,209 +64,208 @@ public: bool isModMoveAndEquip = false, LWOOBJID subKey = LWOOBJID_EMPTY, bool bound = false, - eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE + eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE ); - ~Item(); + ~Item(); - /** - * Returns the object ID of this item - * @return the object ID of this item - */ + /** + * Returns the object ID of this item + * @return the object ID of this item + */ LWOOBJID GetId() const; - /** - * Returns the lot of this item - * @return the lot of this item - */ + /** + * Returns the lot of this item + * @return the lot of this item + */ LOT GetLot() const; - /** - * Sets the number of items this item represents - * @param value the number to update by - * @param silent if true, the client will not be notified of the change with GMs - * @param disassemble if items were removed, this returns all the sub parts of the item individually if it had assembly part lots - * @param showFlyingLoot shows flying loot to the client, if not silent - */ - void SetCount(uint32_t value, bool silent = false, bool disassemble = true, bool showFlyingLoot = true, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); + /** + * Sets the number of items this item represents + * @param value the number to update by + * @param silent if true, the client will not be notified of the change with GMs + * @param disassemble if items were removed, this returns all the sub parts of the item individually if it had assembly part lots + * @param showFlyingLoot shows flying loot to the client, if not silent + */ + void SetCount(uint32_t value, bool silent = false, bool disassemble = true, bool showFlyingLoot = true, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); - /** - * Returns the number of items this item represents (e.g. for stacks) - * @return the number of items this item represents - */ + /** + * Returns the number of items this item represents (e.g. for stacks) + * @return the number of items this item represents + */ uint32_t GetCount() const; - /** - * Sets the slot this item is stored in - * @param value the slot this item is stored in - */ - void SetSlot(uint32_t value); + /** + * Sets the slot this item is stored in + * @param value the slot this item is stored in + */ + void SetSlot(uint32_t value); - /** - * Returns the slot this item is in - * @return the slot this item is in - */ + /** + * Returns the slot this item is in + * @return the slot this item is in + */ uint32_t GetSlot() const; - /** - * Returns current config info for this item, e.g. for rockets - * @return current config info for this item - */ + /** + * Returns current config info for this item, e.g. for rockets + * @return current config info for this item + */ std::vector& GetConfig(); - /** - * Returns the database info for this item - * @return the database info for this item - */ + /** + * Returns the database info for this item + * @return the database info for this item + */ const CDItemComponent& GetInfo() const; - /** - * Sets if the item is bound - * @param value if the item is bound - */ - void SetBound(bool value); + /** + * Sets if the item is bound + * @param value if the item is bound + */ + void SetBound(bool value); - /** - * Returns if the item is bound - * @return if the item is bound - */ + /** + * Returns if the item is bound + * @return if the item is bound + */ bool GetBound() const; - /** - * Sets the inventory this item belongs to - * @param value the inventory this item belongs to - */ - void SetInventory(Inventory* value); + /** + * Sets the inventory this item belongs to + * @param value the inventory this item belongs to + */ + void SetInventory(Inventory* value); - /** - * Returns the inventory this item belongs to - * @return the inventory this item belongs to - */ + /** + * Returns the inventory this item belongs to + * @return the inventory this item belongs to + */ Inventory* GetInventory() const; - /** - * Returns the parent of this item, e.g. for proxy items - * @return the parent of this item - */ + /** + * Returns the parent of this item, e.g. for proxy items + * @return the parent of this item + */ LWOOBJID GetParent() const; - /** - * Sets the subkey for this item, e.g. for pets - * @param value the subkey for this item - */ - void SetSubKey(LWOOBJID value); + /** + * Sets the subkey for this item, e.g. for pets + * @param value the subkey for this item + */ + void SetSubKey(LWOOBJID value); - /** - * Returns the sub key this item has, e.g. for pets - * @return the sub key this item has - */ + /** + * Returns the sub key this item has, e.g. for pets + * @return the sub key this item has + */ LWOOBJID GetSubKey() const; - /** - * Returns the preconditions that must be met before this item may be used - * @return the preconditions that must be met before this item may be used - */ + /** + * Returns the preconditions that must be met before this item may be used + * @return the preconditions that must be met before this item may be used + */ PreconditionExpression* GetPreconditionExpression() const; - /** - * Equips this item into the linked inventory - * @param skipChecks skips equip checks for special items like rockets and cars - */ + /** + * Equips this item into the linked inventory + * @param skipChecks skips equip checks for special items like rockets and cars + */ void Equip(bool skipChecks = false); - /** - * Unequps the item from the linked inventory - */ + /** + * Unequps the item from the linked inventory + */ void UnEquip(); - /** - * Returns if the item is equipped in the linked inventory - * @return if the item is equipped - */ + /** + * Returns if the item is equipped in the linked inventory + * @return if the item is equipped + */ bool IsEquipped() const; - /** - * Attempts to consume one of this item, applying its skills - * @return whether the consumption was successful, e.g. the skill was cast - */ + /** + * Attempts to consume one of this item, applying its skills + * @return whether the consumption was successful, e.g. the skill was cast + */ bool Consume(); - /** - * Uses this item if its non equip, essentially an interface for the linked GM - * @return whether the use was successful, e.g. the skill was cast - */ + /** + * Uses this item if its non equip, essentially an interface for the linked GM + * @return whether the use was successful, e.g. the skill was cast + */ bool UseNonEquip(); - /** - * Disassembles the part LOTs of this item back into the inventory, if it has any - * @param inventoryType the inventory to dissassemble into - */ + /** + * Disassembles the part LOTs of this item back into the inventory, if it has any + * @param inventoryType the inventory to dissassemble into + */ void Disassemble(eInventoryType inventoryType = INVALID); - /** - * Disassembles this item into bricks - */ + /** + * Disassembles this item into bricks + */ void DisassembleModel(); - /** - * Removes the item from the linked inventory - */ + /** + * Removes the item from the linked inventory + */ void RemoveFromInventory(); private: - /** - * The object ID of this item - */ + /** + * The object ID of this item + */ LWOOBJID id; - /** - * The LOT of this item - */ + /** + * The LOT of this item + */ LOT lot; - /** - * The number of items this represents - */ + /** + * The number of items this represents + */ uint32_t count; - /** - * The slot this item is stored in - */ + /** + * The slot this item is stored in + */ uint32_t slot; - /** - * If this item is bound - */ + /** + * If this item is bound + */ bool bound; - /** - * A potential parent of this item, if this item is a subitem - */ + /** + * A potential parent of this item, if this item is a subitem + */ LWOOBJID parent; - /** - * A potential subkey of this item, e.g. for pets - */ + /** + * A potential subkey of this item, e.g. for pets + */ LWOOBJID subKey; - /** - * Config data for this item, e.g. for rocket parts and car parts - */ + /** + * Config data for this item, e.g. for rocket parts and car parts + */ std::vector config; - /** - * The inventory this item belongs to - */ + /** + * The inventory this item belongs to + */ Inventory* inventory; - /** - * The database information of this item - */ + /** + * The database information of this item + */ const CDItemComponent* info; - /** - * A precondition to using this item - */ + /** + * A precondition to using this item + */ PreconditionExpression* preconditions = nullptr; }; - \ No newline at end of file diff --git a/dGame/dInventory/ItemSet.cpp b/dGame/dInventory/ItemSet.cpp index feddd757..5d8ea226 100644 --- a/dGame/dInventory/ItemSet.cpp +++ b/dGame/dInventory/ItemSet.cpp @@ -8,8 +8,7 @@ #include "MissionComponent.h" #include -ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) -{ +ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) { this->m_ID = id; this->m_InventoryComponent = inventoryComponent; @@ -17,19 +16,16 @@ ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) auto query = CDClientDatabase::CreatePreppedStmt( "SELECT skillSetWith2, skillSetWith3, skillSetWith4, skillSetWith5, skillSetWith6, itemIDs FROM ItemSets WHERE setID = ?;"); - query.bind(1, (int) id); + query.bind(1, (int)id); auto result = query.execQuery(); - if (result.eof()) - { + if (result.eof()) { return; } - for (auto i = 0; i < 5; ++i) - { - if (result.fieldIsNull(i)) - { + for (auto i = 0; i < 5; ++i) { + if (result.fieldIsNull(i)) { continue; } @@ -39,15 +35,12 @@ ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) auto skillResult = skillQuery.execQuery(); - if (skillResult.eof()) - { + if (skillResult.eof()) { return; } - while (!skillResult.eof()) - { - if (skillResult.fieldIsNull(0)) - { + while (!skillResult.eof()) { + if (skillResult.fieldIsNull(0)) { skillResult.nextRow(); continue; @@ -55,8 +48,7 @@ ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) const auto skillId = skillResult.getIntField(0); - switch (i) - { + switch (i) { case 0: m_SkillsWith2.push_back(skillId); break; @@ -91,42 +83,34 @@ ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) m_Items = {}; - while (std::getline(stream, token, ',')) - { + while (std::getline(stream, token, ',')) { int32_t value; - if (GeneralUtils::TryParse(token, value)) - { + if (GeneralUtils::TryParse(token, value)) { m_Items.push_back(value); } } m_Equipped = {}; - for (const auto item : m_Items) - { - if (inventoryComponent->IsEquipped(item)) - { + for (const auto item : m_Items) { + if (inventoryComponent->IsEquipped(item)) { m_Equipped.push_back(item); } } } -bool ItemSet::Contains(const LOT lot) -{ +bool ItemSet::Contains(const LOT lot) { return std::find(m_Items.begin(), m_Items.end(), lot) != m_Items.end(); } -void ItemSet::OnEquip(const LOT lot) -{ - if (!Contains(lot)) - { +void ItemSet::OnEquip(const LOT lot) { + if (!Contains(lot)) { return; } const auto& index = std::find(m_Equipped.begin(), m_Equipped.end(), lot); - if (index != m_Equipped.end()) - { + if (index != m_Equipped.end()) { return; } @@ -134,16 +118,14 @@ void ItemSet::OnEquip(const LOT lot) const auto& skillSet = GetSkillSet(m_Equipped.size()); - if (skillSet.empty()) - { + if (skillSet.empty()) { return; } auto* skillComponent = m_InventoryComponent->GetParent()->GetComponent(); auto* missionComponent = m_InventoryComponent->GetParent()->GetComponent(); - for (const auto skill : skillSet) - { + for (const auto skill : skillSet) { auto* skillTable = CDClientManager::Instance()->GetTable("SkillBehavior"); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; @@ -154,17 +136,14 @@ void ItemSet::OnEquip(const LOT lot) } } -void ItemSet::OnUnEquip(const LOT lot) -{ - if (!Contains(lot)) - { +void ItemSet::OnUnEquip(const LOT lot) { + if (!Contains(lot)) { return; } const auto& index = std::find(m_Equipped.begin(), m_Equipped.end(), lot); - if (index == m_Equipped.end()) - { + if (index == m_Equipped.end()) { return; } @@ -172,15 +151,13 @@ void ItemSet::OnUnEquip(const LOT lot) m_Equipped.erase(index); - if (skillSet.empty()) - { + if (skillSet.empty()) { return; } const auto& skillComponent = m_InventoryComponent->GetParent()->GetComponent(); - for (const auto skill : skillSet) - { + for (const auto skill : skillSet) { auto* skillTable = CDClientManager::Instance()->GetTable("SkillBehavior"); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; @@ -189,36 +166,28 @@ void ItemSet::OnUnEquip(const LOT lot) } } -uint32_t ItemSet::GetEquippedCount() const -{ +uint32_t ItemSet::GetEquippedCount() const { return m_Equipped.size(); } -uint32_t ItemSet::GetID() const -{ +uint32_t ItemSet::GetID() const { return m_ID; } -void ItemSet::Update(float deltaTime) -{ - for (auto& passiveAbility : m_PassiveAbilities) - { +void ItemSet::Update(float deltaTime) { + for (auto& passiveAbility : m_PassiveAbilities) { passiveAbility.Update(deltaTime); } } -void ItemSet::TriggerPassiveAbility(PassiveAbilityTrigger trigger) -{ - for (auto& passiveAbility : m_PassiveAbilities) - { +void ItemSet::TriggerPassiveAbility(PassiveAbilityTrigger trigger) { + for (auto& passiveAbility : m_PassiveAbilities) { passiveAbility.Trigger(trigger); } } -std::vector ItemSet::GetSkillSet(const uint32_t itemCount) const -{ - switch (itemCount) - { +std::vector ItemSet::GetSkillSet(const uint32_t itemCount) const { + switch (itemCount) { case 2: return m_SkillsWith2; case 3: diff --git a/dGame/dInventory/ItemSet.h b/dGame/dInventory/ItemSet.h index d443ca06..2ed3be14 100644 --- a/dGame/dInventory/ItemSet.h +++ b/dGame/dInventory/ItemSet.h @@ -15,100 +15,100 @@ class ItemSet { public: explicit ItemSet(uint32_t id, InventoryComponent* inventoryComponent); - void Update(float deltaTime); + void Update(float deltaTime); - /** - * Returns if this item set contains the LOT specified - * @param lot the lot to check for - * @return if this item set contains the LOT specified - */ + /** + * Returns if this item set contains the LOT specified + * @param lot the lot to check for + * @return if this item set contains the LOT specified + */ bool Contains(LOT lot); - /** - * Equips the item set skill for this LOT (if it's in the item set) - * @param lot the LOT of the item to equip skills for - */ + /** + * Equips the item set skill for this LOT (if it's in the item set) + * @param lot the LOT of the item to equip skills for + */ void OnEquip(LOT lot); - /** - * Unequips the item set skill for this LOT (if it's in the item set) - * @param lot the LOT of the item to unequip skills for - */ + /** + * Unequips the item set skill for this LOT (if it's in the item set) + * @param lot the LOT of the item to unequip skills for + */ void OnUnEquip(LOT lot); - /** - * Returns the number of items in the item set that are currently equipped - * @return the number of items in the item set that are currently equipped - */ + /** + * Returns the number of items in the item set that are currently equipped + * @return the number of items in the item set that are currently equipped + */ uint32_t GetEquippedCount() const; - /** - * Returns the ID of this item set - * @return the ID of this item set - */ + /** + * Returns the ID of this item set + * @return the ID of this item set + */ uint32_t GetID() const; - /** - * Triggers all the passive abilities in this item set that match this trigger - * @param trigger the trigger to use to trigger passive abilities - */ - void TriggerPassiveAbility(PassiveAbilityTrigger trigger); + /** + * Triggers all the passive abilities in this item set that match this trigger + * @param trigger the trigger to use to trigger passive abilities + */ + void TriggerPassiveAbility(PassiveAbilityTrigger trigger); - /** - * Returns the skills that can be equipped for a specified amount of equipped items - * @param itemCount the amount of items equipped to check for - * @return the skills that can be equipped for a specified amount of equipped items - */ + /** + * Returns the skills that can be equipped for a specified amount of equipped items + * @param itemCount the amount of items equipped to check for + * @return the skills that can be equipped for a specified amount of equipped items + */ std::vector GetSkillSet(uint32_t itemCount) const; private: - /** - * The ID of this skill set - */ + /** + * The ID of this skill set + */ uint32_t m_ID; - /** - * The inventory this skill set belongs to - */ + /** + * The inventory this skill set belongs to + */ InventoryComponent* m_InventoryComponent; - /** - * The items in the skill set that are currently equipped - */ + /** + * The items in the skill set that are currently equipped + */ std::vector m_Equipped; - /** - * The total list of items in this skill set - */ + /** + * The total list of items in this skill set + */ std::vector m_Items; - /** - * The skills that can be triggered when 2 items are equipped - */ + /** + * The skills that can be triggered when 2 items are equipped + */ std::vector m_SkillsWith2; - /** - * The skills that can be triggered when 3 items are equipped - */ + /** + * The skills that can be triggered when 3 items are equipped + */ std::vector m_SkillsWith3; - /** - * The skills that can be triggered when 4 items are equipped - */ + /** + * The skills that can be triggered when 4 items are equipped + */ std::vector m_SkillsWith4; - /** - * The skills that can be triggered when 5 items are equipped - */ + /** + * The skills that can be triggered when 5 items are equipped + */ std::vector m_SkillsWith5; - /** - * The skills that can be triggered when 6 items are equipped - */ + /** + * The skills that can be triggered when 6 items are equipped + */ std::vector m_SkillsWith6; - /** - * The passive abilities associated with this skill set - */ + /** + * The passive abilities associated with this skill set + */ std::vector m_PassiveAbilities; -}; \ No newline at end of file +}; diff --git a/dGame/dInventory/ItemSetPassiveAbility.cpp b/dGame/dInventory/ItemSetPassiveAbility.cpp index 9edb671b..d90f6e4e 100644 --- a/dGame/dInventory/ItemSetPassiveAbility.cpp +++ b/dGame/dInventory/ItemSetPassiveAbility.cpp @@ -5,330 +5,316 @@ #include "ItemSet.h" #include "ItemSetPassiveAbilityID.h" -ItemSetPassiveAbility::ItemSetPassiveAbility(PassiveAbilityTrigger trigger, Entity* parent, ItemSet* itemSet) -{ - m_Trigger = trigger; - m_Parent = parent; - m_ItemSet = itemSet; +ItemSetPassiveAbility::ItemSetPassiveAbility(PassiveAbilityTrigger trigger, Entity* parent, ItemSet* itemSet) { + m_Trigger = trigger; + m_Parent = parent; + m_ItemSet = itemSet; - m_Cooldown = 0.0f; + m_Cooldown = 0.0f; } -ItemSetPassiveAbility::~ItemSetPassiveAbility() -{ +ItemSetPassiveAbility::~ItemSetPassiveAbility() { } -void ItemSetPassiveAbility::Trigger(PassiveAbilityTrigger trigger) -{ - if (m_Trigger != trigger || m_Cooldown > 0.0f) - { - return; - } +void ItemSetPassiveAbility::Trigger(PassiveAbilityTrigger trigger) { + if (m_Trigger != trigger || m_Cooldown > 0.0f) { + return; + } - Activate(); + Activate(); } -void ItemSetPassiveAbility::Update(float deltaTime) -{ - if (m_Cooldown > 0.0f) - { - m_Cooldown -= deltaTime; - } +void ItemSetPassiveAbility::Update(float deltaTime) { + if (m_Cooldown > 0.0f) { + m_Cooldown -= deltaTime; + } } -void ItemSetPassiveAbility::Activate() -{ - if (m_Trigger == PassiveAbilityTrigger::EnemySmashed) - { - OnEnemySmshed(); +void ItemSetPassiveAbility::Activate() { + if (m_Trigger == PassiveAbilityTrigger::EnemySmashed) { + OnEnemySmshed(); - return; - } + return; + } - auto* destroyableComponent = m_Parent->GetComponent(); - auto* skillComponent = m_Parent->GetComponent(); + auto* destroyableComponent = m_Parent->GetComponent(); + auto* skillComponent = m_Parent->GetComponent(); - if (destroyableComponent == nullptr || skillComponent == nullptr) - { - return; - } + if (destroyableComponent == nullptr || skillComponent == nullptr) { + return; + } - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - const auto id = static_cast(m_ItemSet->GetID()); - const auto parentID = m_Parent->GetObjectID(); - const auto equippedCount = m_ItemSet->GetEquippedCount(); + const auto id = static_cast(m_ItemSet->GetID()); + const auto parentID = m_Parent->GetObjectID(); + const auto equippedCount = m_ItemSet->GetEquippedCount(); - switch (id) - { - // Assembly - case ItemSetPassiveAbilityID::InventorRank1: - case ItemSetPassiveAbilityID::SummonerRank1: - case ItemSetPassiveAbilityID::EngineerRank1: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(394, 4401, parentID); - break; - } - case ItemSetPassiveAbilityID::InventorRank2: - case ItemSetPassiveAbilityID::SummonerRank2: - case ItemSetPassiveAbilityID::EngineerRank2: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(581, 9433, parentID); - break; - } - case ItemSetPassiveAbilityID::InventorRank3: - case ItemSetPassiveAbilityID::SummonerRank3: - case ItemSetPassiveAbilityID::EngineerRank3: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(582, 9435, parentID); - break; - } + switch (id) { + // Assembly + case ItemSetPassiveAbilityID::InventorRank1: + case ItemSetPassiveAbilityID::SummonerRank1: + case ItemSetPassiveAbilityID::EngineerRank1: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(394, 4401, parentID); + break; + } + case ItemSetPassiveAbilityID::InventorRank2: + case ItemSetPassiveAbilityID::SummonerRank2: + case ItemSetPassiveAbilityID::EngineerRank2: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(581, 9433, parentID); + break; + } + case ItemSetPassiveAbilityID::InventorRank3: + case ItemSetPassiveAbilityID::SummonerRank3: + case ItemSetPassiveAbilityID::EngineerRank3: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(582, 9435, parentID); + break; + } - // Sentinel - case ItemSetPassiveAbilityID::KnightRank1: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(559, 8884, parentID); - break; - } - case ItemSetPassiveAbilityID::KnightRank2: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(560, 8885, parentID); - break; - } - case ItemSetPassiveAbilityID::KnightRank3: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(561, 8890, parentID); - break; - } + // Sentinel + case ItemSetPassiveAbilityID::KnightRank1: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(559, 8884, parentID); + break; + } + case ItemSetPassiveAbilityID::KnightRank2: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(560, 8885, parentID); + break; + } + case ItemSetPassiveAbilityID::KnightRank3: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(561, 8890, parentID); + break; + } - case ItemSetPassiveAbilityID::SpaceRangerRank1: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(1101, 24612, parentID); - break; - } - case ItemSetPassiveAbilityID::SpaceRangerRank2: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(1102, 24617, parentID); - break; - } - case ItemSetPassiveAbilityID::SpaceRangerRank3: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(1103, 24622, parentID); - break; - } + case ItemSetPassiveAbilityID::SpaceRangerRank1: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(1101, 24612, parentID); + break; + } + case ItemSetPassiveAbilityID::SpaceRangerRank2: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(1102, 24617, parentID); + break; + } + case ItemSetPassiveAbilityID::SpaceRangerRank3: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(1103, 24622, parentID); + break; + } - case ItemSetPassiveAbilityID::SamuraiRank1: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(562, 8899, parentID); - break; - } - case ItemSetPassiveAbilityID::SamuraiRank2: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(563, 8904, parentID); - break; - } - case ItemSetPassiveAbilityID::SamuraiRank3: { - if (equippedCount < 4) return; - m_Cooldown = 11.0f; - skillComponent->CalculateBehavior(564, 8909, parentID); - break; - } + case ItemSetPassiveAbilityID::SamuraiRank1: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(562, 8899, parentID); + break; + } + case ItemSetPassiveAbilityID::SamuraiRank2: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(563, 8904, parentID); + break; + } + case ItemSetPassiveAbilityID::SamuraiRank3: { + if (equippedCount < 4) return; + m_Cooldown = 11.0f; + skillComponent->CalculateBehavior(564, 8909, parentID); + break; + } - default: - break; - } + default: + break; + } } -std::vector ItemSetPassiveAbility::FindAbilities(uint32_t itemSetID, Entity* parent, ItemSet* itemSet) -{ - std::vector abilities; +std::vector ItemSetPassiveAbility::FindAbilities(uint32_t itemSetID, Entity* parent, ItemSet* itemSet) { + std::vector abilities; - switch (static_cast(itemSetID)) { - // Assembly - case ItemSetPassiveAbilityID::SummonerRank1: - case ItemSetPassiveAbilityID::SummonerRank2: - case ItemSetPassiveAbilityID::SummonerRank3: - case ItemSetPassiveAbilityID::InventorRank1: - case ItemSetPassiveAbilityID::InventorRank2: - case ItemSetPassiveAbilityID::InventorRank3: - case ItemSetPassiveAbilityID::EngineerRank1: - case ItemSetPassiveAbilityID::EngineerRank2: - case ItemSetPassiveAbilityID::EngineerRank3: { - abilities.emplace_back(PassiveAbilityTrigger::AssemblyImagination, parent, itemSet); + switch (static_cast(itemSetID)) { + // Assembly + case ItemSetPassiveAbilityID::SummonerRank1: + case ItemSetPassiveAbilityID::SummonerRank2: + case ItemSetPassiveAbilityID::SummonerRank3: + case ItemSetPassiveAbilityID::InventorRank1: + case ItemSetPassiveAbilityID::InventorRank2: + case ItemSetPassiveAbilityID::InventorRank3: + case ItemSetPassiveAbilityID::EngineerRank1: + case ItemSetPassiveAbilityID::EngineerRank2: + case ItemSetPassiveAbilityID::EngineerRank3: { + abilities.emplace_back(PassiveAbilityTrigger::AssemblyImagination, parent, itemSet); - break; - } - // Sentinel - case ItemSetPassiveAbilityID::KnightRank1: - case ItemSetPassiveAbilityID::KnightRank2: - case ItemSetPassiveAbilityID::KnightRank3: - case ItemSetPassiveAbilityID::SpaceRangerRank1: - case ItemSetPassiveAbilityID::SpaceRangerRank2: - case ItemSetPassiveAbilityID::SpaceRangerRank3: - case ItemSetPassiveAbilityID::SamuraiRank1: - case ItemSetPassiveAbilityID::SamuraiRank2: - case ItemSetPassiveAbilityID::SamuraiRank3: { - abilities.emplace_back(PassiveAbilityTrigger::SentinelArmor, parent, itemSet); - abilities.emplace_back(PassiveAbilityTrigger::EnemySmashed, parent, itemSet); + break; + } + // Sentinel + case ItemSetPassiveAbilityID::KnightRank1: + case ItemSetPassiveAbilityID::KnightRank2: + case ItemSetPassiveAbilityID::KnightRank3: + case ItemSetPassiveAbilityID::SpaceRangerRank1: + case ItemSetPassiveAbilityID::SpaceRangerRank2: + case ItemSetPassiveAbilityID::SpaceRangerRank3: + case ItemSetPassiveAbilityID::SamuraiRank1: + case ItemSetPassiveAbilityID::SamuraiRank2: + case ItemSetPassiveAbilityID::SamuraiRank3: { + abilities.emplace_back(PassiveAbilityTrigger::SentinelArmor, parent, itemSet); + abilities.emplace_back(PassiveAbilityTrigger::EnemySmashed, parent, itemSet); - break; - } - // Paradox - case ItemSetPassiveAbilityID::BatLord: - case ItemSetPassiveAbilityID::SpaceMarauderRank1: - case ItemSetPassiveAbilityID::SpaceMarauderRank2: - case ItemSetPassiveAbilityID::SpaceMarauderRank3: - case ItemSetPassiveAbilityID::SorcererRank1: - case ItemSetPassiveAbilityID::SorcererRank2: - case ItemSetPassiveAbilityID::SorcererRank3: - case ItemSetPassiveAbilityID::ShinobiRank1: - case ItemSetPassiveAbilityID::ShinobiRank2: - case ItemSetPassiveAbilityID::ShinobiRank3: { - abilities.emplace_back(PassiveAbilityTrigger::EnemySmashed, parent, itemSet); + break; + } + // Paradox + case ItemSetPassiveAbilityID::BatLord: + case ItemSetPassiveAbilityID::SpaceMarauderRank1: + case ItemSetPassiveAbilityID::SpaceMarauderRank2: + case ItemSetPassiveAbilityID::SpaceMarauderRank3: + case ItemSetPassiveAbilityID::SorcererRank1: + case ItemSetPassiveAbilityID::SorcererRank2: + case ItemSetPassiveAbilityID::SorcererRank3: + case ItemSetPassiveAbilityID::ShinobiRank1: + case ItemSetPassiveAbilityID::ShinobiRank2: + case ItemSetPassiveAbilityID::ShinobiRank3: { + abilities.emplace_back(PassiveAbilityTrigger::EnemySmashed, parent, itemSet); - break; - } - default: - break; - } - - return abilities; + break; + } + default: + break; + } + + return abilities; } -void ItemSetPassiveAbility::OnEnemySmshed() -{ - auto* destroyableComponent = m_Parent->GetComponent(); - auto* skillComponent = m_Parent->GetComponent(); +void ItemSetPassiveAbility::OnEnemySmshed() { + auto* destroyableComponent = m_Parent->GetComponent(); + auto* skillComponent = m_Parent->GetComponent(); - if (destroyableComponent == nullptr || skillComponent == nullptr) - { - return; - } + if (destroyableComponent == nullptr || skillComponent == nullptr) { + return; + } - EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(m_Parent); - const auto id = static_cast(m_ItemSet->GetID()); - const auto parentID = m_Parent->GetObjectID(); - const auto equippedCount = m_ItemSet->GetEquippedCount(); + const auto id = static_cast(m_ItemSet->GetID()); + const auto parentID = m_Parent->GetObjectID(); + const auto equippedCount = m_ItemSet->GetEquippedCount(); - switch (id) - { - // Bat Lord - case ItemSetPassiveAbilityID::BatLord: { - if(equippedCount < 5) return; - destroyableComponent->Heal(3); - break; - } - // Sentinel - case ItemSetPassiveAbilityID::KnightRank1: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } - case ItemSetPassiveAbilityID::KnightRank2: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } - case ItemSetPassiveAbilityID::KnightRank3: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } + switch (id) { + // Bat Lord + case ItemSetPassiveAbilityID::BatLord: { + if (equippedCount < 5) return; + destroyableComponent->Heal(3); + break; + } + // Sentinel + case ItemSetPassiveAbilityID::KnightRank1: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } + case ItemSetPassiveAbilityID::KnightRank2: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } + case ItemSetPassiveAbilityID::KnightRank3: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } - case ItemSetPassiveAbilityID::SpaceRangerRank1: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } - case ItemSetPassiveAbilityID::SpaceRangerRank2: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } - case ItemSetPassiveAbilityID::SpaceRangerRank3: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } + case ItemSetPassiveAbilityID::SpaceRangerRank1: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } + case ItemSetPassiveAbilityID::SpaceRangerRank2: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } + case ItemSetPassiveAbilityID::SpaceRangerRank3: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } - case ItemSetPassiveAbilityID::SamuraiRank1: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } - case ItemSetPassiveAbilityID::SamuraiRank2: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } - case ItemSetPassiveAbilityID::SamuraiRank3: { - if (equippedCount < 5) return; - destroyableComponent->Repair(1); - break; - } + case ItemSetPassiveAbilityID::SamuraiRank1: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } + case ItemSetPassiveAbilityID::SamuraiRank2: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } + case ItemSetPassiveAbilityID::SamuraiRank3: { + if (equippedCount < 5) return; + destroyableComponent->Repair(1); + break; + } - // Paradox - case ItemSetPassiveAbilityID::SpaceMarauderRank1: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(1); - break; - } - case ItemSetPassiveAbilityID::SpaceMarauderRank2: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(2); - break; - } - case ItemSetPassiveAbilityID::SpaceMarauderRank3: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(3); - break; - } - - case ItemSetPassiveAbilityID::ShinobiRank1: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(1); - break; - } - case ItemSetPassiveAbilityID::ShinobiRank2: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(2); - break; - } - case ItemSetPassiveAbilityID::ShinobiRank3: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(3); - break; - } + // Paradox + case ItemSetPassiveAbilityID::SpaceMarauderRank1: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(1); + break; + } + case ItemSetPassiveAbilityID::SpaceMarauderRank2: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(2); + break; + } + case ItemSetPassiveAbilityID::SpaceMarauderRank3: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(3); + break; + } - case ItemSetPassiveAbilityID::SorcererRank1: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(1); - break; - } - case ItemSetPassiveAbilityID::SorcererRank2: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(2); - break; - } - case ItemSetPassiveAbilityID::SorcererRank3: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(3); - break; - } + case ItemSetPassiveAbilityID::ShinobiRank1: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(1); + break; + } + case ItemSetPassiveAbilityID::ShinobiRank2: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(2); + break; + } + case ItemSetPassiveAbilityID::ShinobiRank3: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(3); + break; + } - default: - break; - } + case ItemSetPassiveAbilityID::SorcererRank1: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(1); + break; + } + case ItemSetPassiveAbilityID::SorcererRank2: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(2); + break; + } + case ItemSetPassiveAbilityID::SorcererRank3: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(3); + break; + } + + default: + break; + } } diff --git a/dGame/dInventory/ItemSetPassiveAbility.h b/dGame/dInventory/ItemSetPassiveAbility.h index 151ce341..ff945df2 100644 --- a/dGame/dInventory/ItemSetPassiveAbility.h +++ b/dGame/dInventory/ItemSetPassiveAbility.h @@ -9,11 +9,11 @@ class ItemSet; enum class PassiveAbilityTrigger { - AssemblyImagination, // Less than 1 imagination - ParadoxHealth, // Less or equal to 1 health - SentinelArmor, // Less than 1 armor - VentureHealth, // Less than 3 health - EnemySmashed, // Enemy is smashed + AssemblyImagination, // Less than 1 imagination + ParadoxHealth, // Less or equal to 1 health + SentinelArmor, // Less than 1 armor + VentureHealth, // Less than 3 health + EnemySmashed, // Enemy is smashed }; /** @@ -22,50 +22,50 @@ enum class PassiveAbilityTrigger class ItemSetPassiveAbility { public: - ItemSetPassiveAbility(PassiveAbilityTrigger trigger, Entity* parent, ItemSet* itemSet); - ~ItemSetPassiveAbility(); - void Update(float deltaTime); + ItemSetPassiveAbility(PassiveAbilityTrigger trigger, Entity* parent, ItemSet* itemSet); + ~ItemSetPassiveAbility(); + void Update(float deltaTime); - /** - * Attempts to trigger a passive ability for this item set, if this is the wrong trigger this is a no-op - * @param trigger the trigger to attempt to fire - */ - void Trigger(PassiveAbilityTrigger trigger); + /** + * Attempts to trigger a passive ability for this item set, if this is the wrong trigger this is a no-op + * @param trigger the trigger to attempt to fire + */ + void Trigger(PassiveAbilityTrigger trigger); - /** - * Activates the passive ability - */ - void Activate(); + /** + * Activates the passive ability + */ + void Activate(); - /** - * Finds all the passive abilities associated with a certain item set - * @param itemSetID the item set to find abilities for - * @param parent the parent to add to the passive abilities - * @param itemSet the item set to add to the passive abilities - * @return the passive abilities for the provided item set - */ - static std::vector FindAbilities(uint32_t itemSetID, Entity* parent, ItemSet* itemSet); + /** + * Finds all the passive abilities associated with a certain item set + * @param itemSetID the item set to find abilities for + * @param parent the parent to add to the passive abilities + * @param itemSet the item set to add to the passive abilities + * @return the passive abilities for the provided item set + */ + static std::vector FindAbilities(uint32_t itemSetID, Entity* parent, ItemSet* itemSet); private: - void OnEnemySmshed(); + void OnEnemySmshed(); - /** - * The means of triggering this ability - */ - PassiveAbilityTrigger m_Trigger; + /** + * The means of triggering this ability + */ + PassiveAbilityTrigger m_Trigger; - /** - * The owner of this ability - */ - Entity* m_Parent; + /** + * The owner of this ability + */ + Entity* m_Parent; - /** - * The item set this ability belongs to - */ - ItemSet* m_ItemSet; + /** + * The item set this ability belongs to + */ + ItemSet* m_ItemSet; - /** - * The cooldown on this ability until it can be activated again - */ - float m_Cooldown; + /** + * The cooldown on this ability until it can be activated again + */ + float m_Cooldown; }; diff --git a/dGame/dInventory/ItemSetPassiveAbilityID.h b/dGame/dInventory/ItemSetPassiveAbilityID.h index 12ba8409..92caea19 100644 --- a/dGame/dInventory/ItemSetPassiveAbilityID.h +++ b/dGame/dInventory/ItemSetPassiveAbilityID.h @@ -49,57 +49,57 @@ 49 [Unnamed] Item Set 50 Fire Spinjitzu Item Set 51 Ice Spinjitzu Item Set -52 Lightning Spinjitzu Item Set +52 Lightning Spinjitzu Item Set */ enum class ItemSetPassiveAbilityID { - EngineerRank1 = 2, - EngineerRank2 = 3, - EngineerRank3 = 4, - KnightRank1 = 7, - KnightRank2 = 8, - KnightRank3 = 9, - SpaceRangerRank1 = 10, - SpaceRangerRank2 = 11, - SpaceRangerRank3 = 12, - SamuraiRank1 = 13, - SamuraiRank2 = 14, - SamuraiRank3 = 15, - SorcererRank1 = 16, - SorcererRank2 = 17, - SorcererRank3 = 18, - SpaceMarauderRank1 = 19, - SpaceMarauderRank2 = 20, - SpaceMarauderRank3 = 21, - ShinobiRank1 = 22, - ShinobiRank2 = 23, - ShinobiRank3 = 24, - InventorRank1 = 25, - InventorRank2 = 26, - InventorRank3 = 27, - SummonerRank1 = 28, - SummonerRank2 = 29, - SummonerRank3 = 30, - AdventurerRank1 = 31, - AdventurerRank2 = 32, - AdventurerRank3 = 33, - DaredevilRank1 = 34, - DaredevilRank2 = 35, - DaredevilRank3 = 36, - BuccaneerRank1 = 37, - BuccaneerRank2 = 38, - BuccaneerRank3 = 39, - BoneSuit = 40, - ImaginationSpinjitzu = 41, - BatLord = 42, - MosaicJester = 43, - ExplorienBot = 44, - Unnamed1 = 45, - Unnamed2 = 46, - Unnamed3 = 47, - EarthSpinjitzu = 48, - Unnamed4 = 49, - FireSpinjitzu = 50, - IceSpinjitzu = 51, - LightningSpinjitzu = 52 + EngineerRank1 = 2, + EngineerRank2 = 3, + EngineerRank3 = 4, + KnightRank1 = 7, + KnightRank2 = 8, + KnightRank3 = 9, + SpaceRangerRank1 = 10, + SpaceRangerRank2 = 11, + SpaceRangerRank3 = 12, + SamuraiRank1 = 13, + SamuraiRank2 = 14, + SamuraiRank3 = 15, + SorcererRank1 = 16, + SorcererRank2 = 17, + SorcererRank3 = 18, + SpaceMarauderRank1 = 19, + SpaceMarauderRank2 = 20, + SpaceMarauderRank3 = 21, + ShinobiRank1 = 22, + ShinobiRank2 = 23, + ShinobiRank3 = 24, + InventorRank1 = 25, + InventorRank2 = 26, + InventorRank3 = 27, + SummonerRank1 = 28, + SummonerRank2 = 29, + SummonerRank3 = 30, + AdventurerRank1 = 31, + AdventurerRank2 = 32, + AdventurerRank3 = 33, + DaredevilRank1 = 34, + DaredevilRank2 = 35, + DaredevilRank3 = 36, + BuccaneerRank1 = 37, + BuccaneerRank2 = 38, + BuccaneerRank3 = 39, + BoneSuit = 40, + ImaginationSpinjitzu = 41, + BatLord = 42, + MosaicJester = 43, + ExplorienBot = 44, + Unnamed1 = 45, + Unnamed2 = 46, + Unnamed3 = 47, + EarthSpinjitzu = 48, + Unnamed4 = 49, + FireSpinjitzu = 50, + IceSpinjitzu = 51, + LightningSpinjitzu = 52 }; diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index 4e7a5826..bb02c4c8 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -20,596 +20,596 @@ #include "Database.h" Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { - m_MissionComponent = missionComponent; + m_MissionComponent = missionComponent; - m_Completions = 0; + m_Completions = 0; - m_Timestamp = 0; + m_Timestamp = 0; - m_Reward = 0; + m_Reward = 0; - m_State = MissionState::MISSION_STATE_UNKNOWN; + m_State = MissionState::MISSION_STATE_UNKNOWN; - auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); + auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); - info = missionsTable->GetPtrByMissionID(missionId); + info = missionsTable->GetPtrByMissionID(missionId); - if (info == &CDMissionsTable::Default) { - Game::logger->Log("Missions", "Failed to find mission (%i)!", missionId); + if (info == &CDMissionsTable::Default) { + Game::logger->Log("Missions", "Failed to find mission (%i)!", missionId); - return; - } + return; + } - auto* tasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); + auto* tasksTable = CDClientManager::Instance()->GetTable("MissionTasks"); - auto tasks = tasksTable->GetByMissionID(missionId); + auto tasks = tasksTable->GetByMissionID(missionId); - for (auto i = 0U; i < tasks.size(); ++i) { - auto* info = tasks[i]; + for (auto i = 0U; i < tasks.size(); ++i) { + auto* info = tasks[i]; - auto* task = new MissionTask(this, info, i); + auto* task = new MissionTask(this, info, i); - m_Tasks.push_back(task); - } + m_Tasks.push_back(task); + } } void Mission::LoadFromXml(tinyxml2::XMLElement* element) { - // Start custom XML - if (element->Attribute("state") != nullptr) { - m_State = static_cast(std::stoul(element->Attribute("state"))); - } - // End custom XML + // Start custom XML + if (element->Attribute("state") != nullptr) { + m_State = static_cast(std::stoul(element->Attribute("state"))); + } + // End custom XML - if (element->Attribute("cct") != nullptr) { - m_Completions = std::stoul(element->Attribute("cct")); + if (element->Attribute("cct") != nullptr) { + m_Completions = std::stoul(element->Attribute("cct")); - m_Timestamp = std::stoul(element->Attribute("cts")); + m_Timestamp = std::stoul(element->Attribute("cts")); - if (IsComplete()) { - return; - } - } + if (IsComplete()) { + return; + } + } - auto* task = element->FirstChildElement(); + auto* task = element->FirstChildElement(); - auto index = 0U; + auto index = 0U; - while (task != nullptr) { - if (index >= m_Tasks.size()) { - break; - } + while (task != nullptr) { + if (index >= m_Tasks.size()) { + break; + } - const auto type = m_Tasks[index]->GetType(); + const auto type = m_Tasks[index]->GetType(); - if (type == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT || - type == MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY) { - std::vector uniques; + if (type == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT || + type == MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY) { + std::vector uniques; - const auto value = std::stoul(task->Attribute("v")); + const auto value = std::stoul(task->Attribute("v")); - m_Tasks[index]->SetProgress(value, false); + m_Tasks[index]->SetProgress(value, false); - task = task->NextSiblingElement(); + task = task->NextSiblingElement(); - while (task != nullptr) { - const auto unique = std::stoul(task->Attribute("v")); + while (task != nullptr) { + const auto unique = std::stoul(task->Attribute("v")); - uniques.push_back(unique); + uniques.push_back(unique); - if (m_MissionComponent != nullptr && type == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT) { - m_MissionComponent->AddCollectible(unique); - } + if (m_MissionComponent != nullptr && type == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT) { + m_MissionComponent->AddCollectible(unique); + } - task = task->NextSiblingElement(); - } + task = task->NextSiblingElement(); + } - m_Tasks[index]->SetUnique(uniques); + m_Tasks[index]->SetUnique(uniques); - m_Tasks[index]->SetProgress(uniques.size(), false); + m_Tasks[index]->SetProgress(uniques.size(), false); - break; - } else { - const auto value = std::stoul(task->Attribute("v")); + break; + } else { + const auto value = std::stoul(task->Attribute("v")); - m_Tasks[index]->SetProgress(value, false); + m_Tasks[index]->SetProgress(value, false); - task = task->NextSiblingElement(); - } + task = task->NextSiblingElement(); + } - index++; - } + index++; + } } void Mission::UpdateXml(tinyxml2::XMLElement* element) { - // Start custom XML - element->SetAttribute("state", static_cast(m_State)); - // End custom XML + // Start custom XML + element->SetAttribute("state", static_cast(m_State)); + // End custom XML - element->DeleteChildren(); + element->DeleteChildren(); - element->SetAttribute("id", static_cast(info->id)); + element->SetAttribute("id", static_cast(info->id)); - if (m_Completions > 0) { - element->SetAttribute("cct", static_cast(m_Completions)); + if (m_Completions > 0) { + element->SetAttribute("cct", static_cast(m_Completions)); - element->SetAttribute("cts", static_cast(m_Timestamp)); + element->SetAttribute("cts", static_cast(m_Timestamp)); - if (IsComplete()) { - return; - } - } + if (IsComplete()) { + return; + } + } - for (auto* task : m_Tasks) { - if (task->GetType() == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT || - task->GetType() == MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY) { + for (auto* task : m_Tasks) { + if (task->GetType() == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT || + task->GetType() == MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY) { - auto* child = element->GetDocument()->NewElement("sv"); + auto* child = element->GetDocument()->NewElement("sv"); - child->SetAttribute("v", static_cast(task->GetProgress())); + child->SetAttribute("v", static_cast(task->GetProgress())); - element->LinkEndChild(child); + element->LinkEndChild(child); - for (auto unique : task->GetUnique()) { - auto* uniqueElement = element->GetDocument()->NewElement("sv"); + for (auto unique : task->GetUnique()) { + auto* uniqueElement = element->GetDocument()->NewElement("sv"); - uniqueElement->SetAttribute("v", static_cast(unique)); + uniqueElement->SetAttribute("v", static_cast(unique)); - element->LinkEndChild(uniqueElement); - } + element->LinkEndChild(uniqueElement); + } - break; - } - auto* child = element->GetDocument()->NewElement("sv"); + break; + } + auto* child = element->GetDocument()->NewElement("sv"); - child->SetAttribute("v", static_cast(task->GetProgress())); + child->SetAttribute("v", static_cast(task->GetProgress())); - element->LinkEndChild(child); - } + element->LinkEndChild(child); + } } bool Mission::IsValidMission(const uint32_t missionId) { - auto* table = CDClientManager::Instance()->GetTable("Missions"); + auto* table = CDClientManager::Instance()->GetTable("Missions"); - const auto missions = table->Query([=](const CDMissions& entry) { - return entry.id == static_cast(missionId); - }); + const auto missions = table->Query([=](const CDMissions& entry) { + return entry.id == static_cast(missionId); + }); - return !missions.empty(); + return !missions.empty(); } bool Mission::IsValidMission(const uint32_t missionId, CDMissions& info) { - auto* table = CDClientManager::Instance()->GetTable("Missions"); + auto* table = CDClientManager::Instance()->GetTable("Missions"); - const auto missions = table->Query([=](const CDMissions& entry) { - return entry.id == static_cast(missionId); - }); + const auto missions = table->Query([=](const CDMissions& entry) { + return entry.id == static_cast(missionId); + }); - if (missions.empty()) { - return false; - } + if (missions.empty()) { + return false; + } - info = missions[0]; + info = missions[0]; - return true; + return true; } Entity* Mission::GetAssociate() const { - return m_MissionComponent->GetParent(); + return m_MissionComponent->GetParent(); } User* Mission::GetUser() const { - return GetAssociate()->GetParentUser(); + return GetAssociate()->GetParentUser(); } uint32_t Mission::GetMissionId() const { - return info->id; + return info->id; } const CDMissions& Mission::GetClientInfo() const { - return *info; + return *info; } uint32_t Mission::GetCompletions() const { - return m_Completions; + return m_Completions; } uint32_t Mission::GetTimestamp() const { - return m_Timestamp; + return m_Timestamp; } LOT Mission::GetReward() const { - return m_Reward; + return m_Reward; } std::vector Mission::GetTasks() const { - return m_Tasks; + return m_Tasks; } MissionState Mission::GetMissionState() const { - return m_State; + return m_State; } bool Mission::IsAchievement() const { - return !info->isMission; + return !info->isMission; } bool Mission::IsMission() const { - return info->isMission; + return info->isMission; } bool Mission::IsRepeatable() const { - return info->repeatable; + return info->repeatable; } bool Mission::IsComplete() const { - return m_State == MissionState::MISSION_STATE_COMPLETE; + return m_State == MissionState::MISSION_STATE_COMPLETE; } bool Mission::IsActive() const { - return m_State == MissionState::MISSION_STATE_ACTIVE || m_State == MissionState::MISSION_STATE_COMPLETE_AVAILABLE; + return m_State == MissionState::MISSION_STATE_ACTIVE || m_State == MissionState::MISSION_STATE_COMPLETE_AVAILABLE; } void Mission::MakeActive() { - SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_ACTIVE : MissionState::MISSION_STATE_COMPLETE_ACTIVE); + SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_ACTIVE : MissionState::MISSION_STATE_COMPLETE_ACTIVE); } bool Mission::IsReadyToComplete() const { - return m_State == MissionState::MISSION_STATE_READY_TO_COMPLETE || m_State == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE; + return m_State == MissionState::MISSION_STATE_READY_TO_COMPLETE || m_State == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE; } void Mission::MakeReadyToComplete() { - SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_READY_TO_COMPLETE : MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE); + SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_READY_TO_COMPLETE : MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE); } bool Mission::IsAvalible() const { - return m_State == MissionState::MISSION_STATE_AVAILABLE || m_State == MissionState::MISSION_STATE_COMPLETE_AVAILABLE; + return m_State == MissionState::MISSION_STATE_AVAILABLE || m_State == MissionState::MISSION_STATE_COMPLETE_AVAILABLE; } bool Mission::IsFetchMission() const { - return m_Tasks.size() == 1 && m_Tasks[0]->GetType() == MissionTaskType::MISSION_TASK_TYPE_MISSION_INTERACTION; + return m_Tasks.size() == 1 && m_Tasks[0]->GetType() == MissionTaskType::MISSION_TASK_TYPE_MISSION_INTERACTION; } void Mission::MakeAvalible() { - SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_AVAILABLE : MissionState::MISSION_STATE_COMPLETE_AVAILABLE); + SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_AVAILABLE : MissionState::MISSION_STATE_COMPLETE_AVAILABLE); } void Mission::Accept() { - SetMissionTypeState(MissionLockState::MISSION_LOCK_NEW, info->defined_type, info->defined_subtype); + SetMissionTypeState(MissionLockState::MISSION_LOCK_NEW, info->defined_type, info->defined_subtype); - SetMissionState(m_Completions > 0 ? MissionState::MISSION_STATE_COMPLETE_ACTIVE : MissionState::MISSION_STATE_ACTIVE); + SetMissionState(m_Completions > 0 ? MissionState::MISSION_STATE_COMPLETE_ACTIVE : MissionState::MISSION_STATE_ACTIVE); - Catchup(); + Catchup(); } void Mission::Complete(const bool yieldRewards) { - if (m_State != MissionState::MISSION_STATE_ACTIVE && m_State != MissionState::MISSION_STATE_COMPLETE_ACTIVE) { - Accept(); - } + if (m_State != MissionState::MISSION_STATE_ACTIVE && m_State != MissionState::MISSION_STATE_COMPLETE_ACTIVE) { + Accept(); + } - for (auto* task : m_Tasks) { - task->Complete(); - } + for (auto* task : m_Tasks) { + task->Complete(); + } - SetMissionState(MissionState::MISSION_STATE_REWARDING, true); + SetMissionState(MissionState::MISSION_STATE_REWARDING, true); - if (yieldRewards) { - YieldRewards(); - } + if (yieldRewards) { + YieldRewards(); + } - SetMissionState(MissionState::MISSION_STATE_COMPLETE); + SetMissionState(MissionState::MISSION_STATE_COMPLETE); - m_Completions++; + m_Completions++; - m_Timestamp = std::time(nullptr); + m_Timestamp = std::time(nullptr); - auto* entity = GetAssociate(); + auto* entity = GetAssociate(); - if (entity == nullptr) { - return; - } + if (entity == nullptr) { + return; + } - auto* characterComponent = entity->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->TrackMissionCompletion(!info->isMission); - } + auto* characterComponent = entity->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->TrackMissionCompletion(!info->isMission); + } - auto* missionComponent = entity->GetComponent(); + auto* missionComponent = entity->GetComponent(); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MISSION_COMPLETE, info->id); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MISSION_COMPLETE, info->id); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, info->id, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPLETE_ANY_RACING_TASK); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, info->id, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPLETE_ANY_RACING_TASK); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, info->id, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPLETE_TRACK_TASKS); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, info->id, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPLETE_TRACK_TASKS); - auto* missionEmailTable = CDClientManager::Instance()->GetTable("MissionEmail"); + auto* missionEmailTable = CDClientManager::Instance()->GetTable("MissionEmail"); - const auto missionId = GetMissionId(); + const auto missionId = GetMissionId(); - const auto missionEmails = missionEmailTable->Query([missionId](const CDMissionEmail& entry) { - return entry.missionID == missionId; - }); + const auto missionEmails = missionEmailTable->Query([missionId](const CDMissionEmail& entry) { + return entry.missionID == missionId; + }); - for (const auto& email : missionEmails) { - const auto missionEmailBase = "MissionEmail_" + std::to_string(email.ID) + "_"; + for (const auto& email : missionEmails) { + const auto missionEmailBase = "MissionEmail_" + std::to_string(email.ID) + "_"; - const auto senderLocale = missionEmailBase + "senderName"; - const auto announceLocale = missionEmailBase + "announceText"; + const auto senderLocale = missionEmailBase + "senderName"; + const auto announceLocale = missionEmailBase + "announceText"; - if (email.messageType == 1 && Game::locale->HasPhrase(senderLocale)) { - const auto subject = dLocale::GetTemplate(missionEmailBase + "subjectText"); - const auto body = dLocale::GetTemplate(missionEmailBase + "bodyText"); - const auto sender = dLocale::GetTemplate(senderLocale); + if (email.messageType == 1 && Game::locale->HasPhrase(senderLocale)) { + const auto subject = dLocale::GetTemplate(missionEmailBase + "subjectText"); + const auto body = dLocale::GetTemplate(missionEmailBase + "bodyText"); + const auto sender = dLocale::GetTemplate(senderLocale); - Mail::SendMail(LWOOBJID_EMPTY, sender, GetAssociate(), subject, body, email.attachmentLOT, 1); - } - } + Mail::SendMail(LWOOBJID_EMPTY, sender, GetAssociate(), subject, body, email.attachmentLOT, 1); + } + } } void Mission::CheckCompletion() { - for (auto* task : m_Tasks) { - if (!task->IsComplete()) { - return; - } - } + for (auto* task : m_Tasks) { + if (!task->IsComplete()) { + return; + } + } - if (IsAchievement()) { - Complete(); + if (IsAchievement()) { + Complete(); - return; - } + return; + } - MakeReadyToComplete(); + MakeReadyToComplete(); } void Mission::Catchup() { - auto* entity = GetAssociate(); + auto* entity = GetAssociate(); - auto* inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + auto* inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); - for (auto* task : m_Tasks) { - const auto type = task->GetType(); + for (auto* task : m_Tasks) { + const auto type = task->GetType(); - if (type == MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { - for (auto target : task->GetAllTargets()) { - const auto count = inventory->GetLotCountNonTransfer(target); + if (type == MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { + for (auto target : task->GetAllTargets()) { + const auto count = inventory->GetLotCountNonTransfer(target); - for (auto i = 0U; i < count; ++i) { - task->Progress(target); - } - } - } + for (auto i = 0U; i < count; ++i) { + task->Progress(target); + } + } + } - if (type == MissionTaskType::MISSION_TASK_TYPE_PLAYER_FLAG) { - for (auto target : task->GetAllTargets()) { - const auto flag = GetUser()->GetLastUsedChar()->GetPlayerFlag(target); + if (type == MissionTaskType::MISSION_TASK_TYPE_PLAYER_FLAG) { + for (auto target : task->GetAllTargets()) { + const auto flag = GetUser()->GetLastUsedChar()->GetPlayerFlag(target); - if (!flag) { - continue; - } + if (!flag) { + continue; + } - task->Progress(target); + task->Progress(target); - if (task->IsComplete()) { - break; - } - } - } - } + if (task->IsComplete()) { + break; + } + } + } + } } void Mission::YieldRewards() { - auto* entity = GetAssociate(); + auto* entity = GetAssociate(); - if (entity == nullptr) { - return; - } + if (entity == nullptr) { + return; + } - auto* character = GetUser()->GetLastUsedChar(); + auto* character = GetUser()->GetLastUsedChar(); - auto* inventoryComponent = entity->GetComponent(); - auto* levelComponent = entity->GetComponent(); - auto* characterComponent = entity->GetComponent(); - auto* destroyableComponent = entity->GetComponent(); - auto* missionComponent = entity->GetComponent(); + auto* inventoryComponent = entity->GetComponent(); + auto* levelComponent = entity->GetComponent(); + auto* characterComponent = entity->GetComponent(); + auto* destroyableComponent = entity->GetComponent(); + auto* missionComponent = entity->GetComponent(); - // Remove mission items - for (auto* task : m_Tasks) { - if (task->GetType() != MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { - continue; - } + // Remove mission items + for (auto* task : m_Tasks) { + if (task->GetType() != MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { + continue; + } - const auto& param = task->GetParameters(); + const auto& param = task->GetParameters(); - if (param.empty() || (param[0] & 1) == 0) // Should items be removed? - { - for (const auto target : task->GetAllTargets()) { - // This is how live did it. ONLY remove item collection items from the items and hidden inventories and none of the others. - inventoryComponent->RemoveItem(target, task->GetClientInfo().targetValue, eInventoryType::ITEMS); - inventoryComponent->RemoveItem(target, task->GetClientInfo().targetValue, eInventoryType::HIDDEN); + if (param.empty() || (param[0] & 1) == 0) // Should items be removed? + { + for (const auto target : task->GetAllTargets()) { + // This is how live did it. ONLY remove item collection items from the items and hidden inventories and none of the others. + inventoryComponent->RemoveItem(target, task->GetClientInfo().targetValue, eInventoryType::ITEMS); + inventoryComponent->RemoveItem(target, task->GetClientInfo().targetValue, eInventoryType::HIDDEN); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, target, LWOOBJID_EMPTY, "", -task->GetClientInfo().targetValue); - } - } - } + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, target, LWOOBJID_EMPTY, "", -task->GetClientInfo().targetValue); + } + } + } - int32_t coinsToSend = 0; - if (info->LegoScore > 0) { - eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; - if(levelComponent->GetLevel() >= dZoneManager::Instance()->GetMaxLevel()) { - // Since the character is at the level cap we reward them with coins instead of UScore. - coinsToSend += info->LegoScore * dZoneManager::Instance()->GetLevelCapCurrencyConversion(); - } else { - characterComponent->SetUScore(characterComponent->GetUScore() + info->LegoScore); - GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), info->LegoScore, lootSource); - } - } + int32_t coinsToSend = 0; + if (info->LegoScore > 0) { + eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; + if (levelComponent->GetLevel() >= dZoneManager::Instance()->GetMaxLevel()) { + // Since the character is at the level cap we reward them with coins instead of UScore. + coinsToSend += info->LegoScore * dZoneManager::Instance()->GetLevelCapCurrencyConversion(); + } else { + characterComponent->SetUScore(characterComponent->GetUScore() + info->LegoScore); + GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), info->LegoScore, lootSource); + } + } - if (m_Completions > 0) { - std::vector> items; + if (m_Completions > 0) { + std::vector> items; - items.emplace_back(info->reward_item1_repeatable, info->reward_item1_repeat_count); - items.emplace_back(info->reward_item2_repeatable, info->reward_item2_repeat_count); - items.emplace_back(info->reward_item3_repeatable, info->reward_item3_repeat_count); - items.emplace_back(info->reward_item4_repeatable, info->reward_item4_repeat_count); + items.emplace_back(info->reward_item1_repeatable, info->reward_item1_repeat_count); + items.emplace_back(info->reward_item2_repeatable, info->reward_item2_repeat_count); + items.emplace_back(info->reward_item3_repeatable, info->reward_item3_repeat_count); + items.emplace_back(info->reward_item4_repeatable, info->reward_item4_repeat_count); - for (const auto& pair : items) { - // Some missions reward zero of an item and so they must be allowed through this clause, - // hence pair.second < 0 instead of pair.second <= 0. - if (pair.second < 0 || (m_Reward > 0 && pair.first != m_Reward)) { - continue; - } + for (const auto& pair : items) { + // Some missions reward zero of an item and so they must be allowed through this clause, + // hence pair.second < 0 instead of pair.second <= 0. + if (pair.second < 0 || (m_Reward > 0 && pair.first != m_Reward)) { + continue; + } - // If a mission rewards zero of an item, make it reward 1. - auto count = pair.second > 0 ? pair.second : 1; + // If a mission rewards zero of an item, make it reward 1. + auto count = pair.second > 0 ? pair.second : 1; - // Sanity check, 6 is the max any mission yields - if (count > 6) { - count = 0; - } + // Sanity check, 6 is the max any mission yields + if (count > 6) { + count = 0; + } - inventoryComponent->AddItem(pair.first, count, IsMission() ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT); - } + inventoryComponent->AddItem(pair.first, count, IsMission() ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT); + } - if (info->reward_currency_repeatable > 0 || coinsToSend > 0) { - eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; - character->SetCoins(character->GetCoins() + info->reward_currency_repeatable + coinsToSend, lootSource); - } + if (info->reward_currency_repeatable > 0 || coinsToSend > 0) { + eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; + character->SetCoins(character->GetCoins() + info->reward_currency_repeatable + coinsToSend, lootSource); + } - return; - } + return; + } - std::vector> items; + std::vector> items; - items.emplace_back(info->reward_item1, info->reward_item1_count); - items.emplace_back(info->reward_item2, info->reward_item2_count); - items.emplace_back(info->reward_item3, info->reward_item3_count); - items.emplace_back(info->reward_item4, info->reward_item4_count); + items.emplace_back(info->reward_item1, info->reward_item1_count); + items.emplace_back(info->reward_item2, info->reward_item2_count); + items.emplace_back(info->reward_item3, info->reward_item3_count); + items.emplace_back(info->reward_item4, info->reward_item4_count); - for (const auto& pair : items) { - // Some missions reward zero of an item and so they must be allowed through this clause, - // hence pair.second < 0 instead of pair.second <= 0. - if (pair.second < 0 || (m_Reward > 0 && pair.first != m_Reward)) { - continue; - } + for (const auto& pair : items) { + // Some missions reward zero of an item and so they must be allowed through this clause, + // hence pair.second < 0 instead of pair.second <= 0. + if (pair.second < 0 || (m_Reward > 0 && pair.first != m_Reward)) { + continue; + } - // If a mission rewards zero of an item, make it reward 1. - auto count = pair.second > 0 ? pair.second : 1; + // If a mission rewards zero of an item, make it reward 1. + auto count = pair.second > 0 ? pair.second : 1; - // Sanity check, 6 is the max any mission yields - if (count > 6) { - count = 0; - } + // Sanity check, 6 is the max any mission yields + if (count > 6) { + count = 0; + } - inventoryComponent->AddItem(pair.first, count, IsMission() ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT); - } + inventoryComponent->AddItem(pair.first, count, IsMission() ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT); + } - if (info->reward_currency > 0 || coinsToSend > 0) { - eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; - character->SetCoins(character->GetCoins() + info->reward_currency + coinsToSend, lootSource); - } + if (info->reward_currency > 0 || coinsToSend > 0) { + eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; + character->SetCoins(character->GetCoins() + info->reward_currency + coinsToSend, lootSource); + } - if (info->reward_maxinventory > 0) { - auto* inventory = inventoryComponent->GetInventory(ITEMS); + if (info->reward_maxinventory > 0) { + auto* inventory = inventoryComponent->GetInventory(ITEMS); - inventory->SetSize(inventory->GetSize() + info->reward_maxinventory); - } + inventory->SetSize(inventory->GetSize() + info->reward_maxinventory); + } - if (info->reward_bankinventory > 0) { - auto* inventory = inventoryComponent->GetInventory(eInventoryType::VAULT_ITEMS); - auto modelInventory = inventoryComponent->GetInventory(eInventoryType::VAULT_MODELS); + if (info->reward_bankinventory > 0) { + auto* inventory = inventoryComponent->GetInventory(eInventoryType::VAULT_ITEMS); + auto modelInventory = inventoryComponent->GetInventory(eInventoryType::VAULT_MODELS); - inventory->SetSize(inventory->GetSize() + info->reward_bankinventory); - modelInventory->SetSize(modelInventory->GetSize() + info->reward_bankinventory); - } + inventory->SetSize(inventory->GetSize() + info->reward_bankinventory); + modelInventory->SetSize(modelInventory->GetSize() + info->reward_bankinventory); + } - if (info->reward_reputation > 0) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_EARN_REPUTATION, 0, 0L, "", info->reward_reputation); - auto character = entity->GetComponent(); - if (character) { - character->SetReputation(character->GetReputation() + info->reward_reputation); - GameMessages::SendUpdateReputation(entity->GetObjectID(), character->GetReputation(), entity->GetSystemAddress()); - } - } + if (info->reward_reputation > 0) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_EARN_REPUTATION, 0, 0L, "", info->reward_reputation); + auto character = entity->GetComponent(); + if (character) { + character->SetReputation(character->GetReputation() + info->reward_reputation); + GameMessages::SendUpdateReputation(entity->GetObjectID(), character->GetReputation(), entity->GetSystemAddress()); + } + } - if (info->reward_maxhealth > 0) { - destroyableComponent->SetMaxHealth(destroyableComponent->GetMaxHealth() + static_cast(info->reward_maxhealth), true); - } + if (info->reward_maxhealth > 0) { + destroyableComponent->SetMaxHealth(destroyableComponent->GetMaxHealth() + static_cast(info->reward_maxhealth), true); + } - if (info->reward_maximagination > 0) { - destroyableComponent->SetMaxImagination(destroyableComponent->GetMaxImagination() + static_cast(info->reward_maximagination), true); - } + if (info->reward_maximagination > 0) { + destroyableComponent->SetMaxImagination(destroyableComponent->GetMaxImagination() + static_cast(info->reward_maximagination), true); + } - EntityManager::Instance()->SerializeEntity(entity); + EntityManager::Instance()->SerializeEntity(entity); - if (info->reward_emote > 0) { - character->UnlockEmote(info->reward_emote); - } + if (info->reward_emote > 0) { + character->UnlockEmote(info->reward_emote); + } - if (info->reward_emote2 > 0) { - character->UnlockEmote(info->reward_emote2); - } + if (info->reward_emote2 > 0) { + character->UnlockEmote(info->reward_emote2); + } - if (info->reward_emote3 > 0) { - character->UnlockEmote(info->reward_emote3); - } + if (info->reward_emote3 > 0) { + character->UnlockEmote(info->reward_emote3); + } - if (info->reward_emote4 > 0) { - character->UnlockEmote(info->reward_emote4); - } + if (info->reward_emote4 > 0) { + character->UnlockEmote(info->reward_emote4); + } } void Mission::Progress(MissionTaskType type, int32_t value, LWOOBJID associate, const std::string& targets, int32_t count) { - const auto isRemoval = count < 0; + const auto isRemoval = count < 0; - if (isRemoval && (IsComplete() || IsAchievement())) { - return; - } + if (isRemoval && (IsComplete() || IsAchievement())) { + return; + } - for (auto* task : m_Tasks) { - if (task->IsComplete() && !isRemoval) { - continue; - } + for (auto* task : m_Tasks) { + if (task->IsComplete() && !isRemoval) { + continue; + } - if (task->GetType() != type) { - continue; - } + if (task->GetType() != type) { + continue; + } - if (isRemoval && !task->InAllTargets(value)) { - continue; - } + if (isRemoval && !task->InAllTargets(value)) { + continue; + } - task->Progress(value, associate, targets, count); - } + task->Progress(value, associate, targets, count); + } } void Mission::SetMissionState(const MissionState state, const bool sendingRewards) { - this->m_State = state; + this->m_State = state; - auto* entity = GetAssociate(); + auto* entity = GetAssociate(); - if (entity == nullptr) { - return; - } + if (entity == nullptr) { + return; + } - GameMessages::SendNotifyMission(entity, entity->GetParentUser()->GetSystemAddress(), info->id, static_cast(state), sendingRewards); + GameMessages::SendNotifyMission(entity, entity->GetParentUser()->GetSystemAddress(), info->id, static_cast(state), sendingRewards); } void Mission::SetMissionTypeState(MissionLockState state, const std::string& type, const std::string& subType) { - // TODO + // TODO } void Mission::SetCompletions(const uint32_t value) { - m_Completions = value; + m_Completions = value; } void Mission::SetReward(const LOT lot) { - m_Reward = lot; + m_Reward = lot; } Mission::~Mission() { - for (auto* task : m_Tasks) { - delete task; - } + for (auto* task : m_Tasks) { + delete task; + } - m_Tasks.clear(); -} \ No newline at end of file + m_Tasks.clear(); +} diff --git a/dGame/dMission/Mission.h b/dGame/dMission/Mission.h index 4fb6c60f..94920cba 100644 --- a/dGame/dMission/Mission.h +++ b/dGame/dMission/Mission.h @@ -22,244 +22,244 @@ class Mission final { public: Mission(MissionComponent* missionComponent, uint32_t missionId); - ~Mission(); + ~Mission(); - void LoadFromXml(tinyxml2::XMLElement* element); - void UpdateXml(tinyxml2::XMLElement* element); + void LoadFromXml(tinyxml2::XMLElement* element); + void UpdateXml(tinyxml2::XMLElement* element); - /** - * Returns the ID of this mission - * @return the ID of this mission - */ + /** + * Returns the ID of this mission + * @return the ID of this mission + */ uint32_t GetMissionId() const; - /** - * Returns the entity that is currently progressing this mission - * @return the entity that is currently progressing this mission - */ + /** + * Returns the entity that is currently progressing this mission + * @return the entity that is currently progressing this mission + */ Entity* GetAssociate() const; - /** - * Returns the account owns the entity that is currently progressing this mission - * @return the account owns the entity that is currently progressing this mission - */ + /** + * 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; - /** - * Returns the current state of this mission - * @return the current state of this mission - */ + /** + * Returns the current state of this mission + * @return the current state of this mission + */ MissionState GetMissionState() const; - /** - * Returns the database information that represents to this mission. - * @return the database information that represents to this mission. - */ + /** + * Returns the database information that represents to this mission. + * @return the database information that represents to this mission. + */ const CDMissions& GetClientInfo() const; - /** - * Returns the number of times the entity has completed this mission, can only be > 0 for dailies. - * @return the number of thimes the entity has completed this mission - */ + /** + * Returns the number of times the entity has completed this mission, can only be > 0 for dailies. + * @return the number of thimes the entity has completed this mission + */ uint32_t GetCompletions() const; - /** - * Sets the number of times this mission has been completed - * @param value the number of times this mission should be completed - */ - void SetCompletions(uint32_t value); + /** + * Sets the number of times this mission has been completed + * @param value the number of times this mission should be completed + */ + void SetCompletions(uint32_t value); - /** - * Returns the last timestamp at which the entity completed this mission - * @return the last timestamp at which the entity completed this mission - */ + /** + * Returns the last timestamp at which the entity completed this mission + * @return the last timestamp at which the entity completed this mission + */ uint32_t GetTimestamp() const; - /** - * Returns some specific reward that should be returned from the possible rewards indicated by the client - * @return some specific reward that should be returned from the possible rewards indicated by the client - */ + /** + * Returns some specific reward that should be returned from the possible rewards indicated by the client + * @return some specific reward that should be returned from the possible rewards indicated by the client + */ LOT GetReward() const; - /** - * Sets an some specific reward that should be returned from the possible rewards indicated by the client - * @param lot the reward to set - */ - void SetReward(LOT lot); + /** + * Sets an some specific reward that should be returned from the possible rewards indicated by the client + * @param lot the reward to set + */ + void SetReward(LOT lot); - /** - * Returns all the tasks that must be completed to mark this mission as complete - * @return all the tasks that must be completed to mark this mission as complete - */ + /** + * Returns all the tasks that must be completed to mark this mission as complete + * @return all the tasks that must be completed to mark this mission as complete + */ std::vector GetTasks() const; - /** - * Updates the mission state to the one provided - * @param state the mission state to set - * @param sendingRewards a flag indicating to the client that rewards wil lfollow - */ + /** + * Updates the mission state to the one provided + * @param state the mission state to set + * @param sendingRewards a flag indicating to the client that rewards wil lfollow + */ void SetMissionState(MissionState state, bool sendingRewards = false); - /** - * Currently unimplemented - */ + /** + * Currently unimplemented + */ void SetMissionTypeState(MissionLockState state, const std::string& type, const std::string& subType); - /** - * Returns whether this mission is an achievement - * @return true if this mission is an achievement, false otherwise - */ + /** + * Returns whether this mission is an achievement + * @return true if this mission is an achievement, false otherwise + */ bool IsAchievement() const; - /** - * Returns whether this mission is a mission (e.g.: not an achievement) - * @return true if this mission is not an achievement, false otherwise - */ + /** + * Returns whether this mission is a mission (e.g.: not an achievement) + * @return true if this mission is not an achievement, false otherwise + */ bool IsMission() const; - /** - * Returns whether this mission can be repeated (mostly used for dailies) - * @return true if this mission can be repeated, false otherwise - */ + /** + * Returns whether this mission can be repeated (mostly used for dailies) + * @return true if this mission can be repeated, false otherwise + */ bool IsRepeatable() const; - /** - * Returns whether the entity has completed this mission before - * @return true if the mission has been completed before, false otherwise - */ + /** + * Returns whether the entity has completed this mission before + * @return true if the mission has been completed before, false otherwise + */ bool IsComplete() const; - /** - * Returns whether the mission is currently active - * @return true if the mission is currently active, false otherwise - */ + /** + * Returns whether the mission is currently active + * @return true if the mission is currently active, false otherwise + */ bool IsActive() const; - /** - * Sets the mission state to active, takes into account if this is a repeatable mission. - */ + /** + * Sets the mission state to active, takes into account if this is a repeatable mission. + */ void MakeActive(); - /** - * Returns whether the entity has completed all tasks and can hand the mission in for rewards. - * @return true if the entity can hand the mission in, false otherwise - */ + /** + * Returns whether the entity has completed all tasks and can hand the mission in for rewards. + * @return true if the entity can hand the mission in, false otherwise + */ bool IsReadyToComplete() const; - /** - * Sets the mission state to ready to complete, takes into account if this is a repeatable mission - */ + /** + * Sets the mission state to ready to complete, takes into account if this is a repeatable mission + */ void MakeReadyToComplete(); - /** - * Returns whether this mission can be accepted by the entity - * @return true if the mission can be accepted by the entity, false otherwise - */ + /** + * Returns whether this mission can be accepted by the entity + * @return true if the mission can be accepted by the entity, false otherwise + */ bool IsAvalible() const; - /** - * Sets the mission state to available, takes into account if this mission is repeatable - */ - void MakeAvalible(); + /** + * Sets the mission state to available, takes into account if this mission is repeatable + */ + void MakeAvalible(); - /** - * Returns whether this mission is one where an entity simply has to go somewhere, but doesn't have to turn in the - * mission tasks at the original mission giver (called a fetch mission). - * @return true if this is a fetch mission, false otherwise - */ + /** + * Returns whether this mission is one where an entity simply has to go somewhere, but doesn't have to turn in the + * mission tasks at the original mission giver (called a fetch mission). + * @return true if this is a fetch mission, false otherwise + */ bool IsFetchMission() const; - /** - * Accepts this mission, setting it to available. Also progresses any of the tasks if the entity has already - * progressed for them (for example "collect X bricks", will fast track for the amount of bricks the entity - * already has). - */ + /** + * Accepts this mission, setting it to available. Also progresses any of the tasks if the entity has already + * progressed for them (for example "collect X bricks", will fast track for the amount of bricks the entity + * already has). + */ void Accept(); - /** - * Completes the mission and handles all logistics regarding that: checking all tasks, handing out rewards, - * emailing them if the inventory is full, etc. If the mission tasks have not all been completed this is a no-op. - * @param yieldRewards if true, rewards will be given to the entity - */ + /** + * Completes the mission and handles all logistics regarding that: checking all tasks, handing out rewards, + * emailing them if the inventory is full, etc. If the mission tasks have not all been completed this is a no-op. + * @param yieldRewards if true, rewards will be given to the entity + */ void Complete(bool yieldRewards = true); - /** - * Checks if this mission is ready to be completed and updates the state if so. If this is an achievement, the - * state will automatically be updated to completed as there's nobody to hand achievements in to. - */ + /** + * Checks if this mission is ready to be completed and updates the state if so. If this is an achievement, the + * state will automatically be updated to completed as there's nobody to hand achievements in to. + */ void CheckCompletion(); - /** - * Gives all the rewards (items, score, stats, etc.) to the entity. Takes into account if the entity has completed - * the mission before. - */ + /** + * Gives all the rewards (items, score, stats, etc.) to the entity. Takes into account if the entity has completed + * the mission before. + */ void YieldRewards(); - /** - * Attempts to progress tasks of a certain type for this mission. Note that the interpretation of any of these - * arguments is up to the mission task at hand. - * @param type the mission task type to progress - * @param value the value to progress the mission task with - * @param associate optional object ID that was related to the progression - * @param targets optional multiple targets that need to be met for progression - * @param count optional count to progress with - */ + /** + * Attempts to progress tasks of a certain type for this mission. Note that the interpretation of any of these + * arguments is up to the mission task at hand. + * @param type the mission task type to progress + * @param value the value to progress the mission task with + * @param associate optional object ID that was related to the progression + * @param targets optional multiple targets that need to be met for progression + * @param count optional count to progress with + */ void Progress(MissionTaskType type, int32_t value, LWOOBJID associate = 0, const std::string& targets = "", int32_t count = 1); - /** - * Returns if the mission ID that's given belongs to an existing mission - * @param missionId the mission ID to check for - * @return true if the mission exists, false otherwise - */ + /** + * Returns if the mission ID that's given belongs to an existing mission + * @param missionId the mission ID to check for + * @return true if the mission exists, false otherwise + */ static bool IsValidMission(uint32_t missionId); - /** - * Returns if the mission ID that's given belongs to an existing mission - * @param missionId the mission ID to check for - * @param info variable to store the queried mission information in - * @return true if the mission exists, false otherwise - */ + /** + * Returns if the mission ID that's given belongs to an existing mission + * @param missionId the mission ID to check for + * @param info variable to store the queried mission information in + * @return true if the mission exists, false otherwise + */ static bool IsValidMission(uint32_t missionId, CDMissions& info); private: - /** - * Progresses all the newly accepted tasks for this mission after it has been accepted to reflect the state of the - * inventory of the entity. - */ + /** + * Progresses all the newly accepted tasks for this mission after it has been accepted to reflect the state of the + * inventory of the entity. + */ void Catchup(); - /** - * The database information that corresponds to this mission - */ + /** + * The database information that corresponds to this mission + */ const CDMissions* info; - /** - * The current state this mission is in - */ + /** + * The current state this mission is in + */ MissionState m_State; - /** - * The number of times the entity has completed this mission - */ + /** + * The number of times the entity has completed this mission + */ uint32_t m_Completions; - /** - * The last time the entity completed this mission - */ + /** + * The last time the entity completed this mission + */ uint32_t m_Timestamp; - /** - * The mission component of the entity that owns this mission - */ + /** + * The mission component of the entity that owns this mission + */ MissionComponent* m_MissionComponent; - /** - * Optionally specific reward that should be returned from the possible rewards indicated by the client - */ + /** + * Optionally specific reward that should be returned from the possible rewards indicated by the client + */ LOT m_Reward; - /** - * All the tasks that can be progressed for this mission - */ + /** + * All the tasks that can be progressed for this mission + */ std::vector m_Tasks; }; diff --git a/dGame/dMission/MissionPrerequisites.cpp b/dGame/dMission/MissionPrerequisites.cpp index 93d55437..3d4e6355 100644 --- a/dGame/dMission/MissionPrerequisites.cpp +++ b/dGame/dMission/MissionPrerequisites.cpp @@ -52,8 +52,7 @@ PrerequisiteExpression::PrerequisiteExpression(const std::string& str) { case '9': if (sub) { s << character; - } - else { + } else { a << character; } break; @@ -71,8 +70,7 @@ PrerequisiteExpression::PrerequisiteExpression(const std::string& str) { if (!aString.empty()) { this->a = std::stoul(a.str()); - } - else { + } else { this->a = 0; } @@ -80,8 +78,7 @@ PrerequisiteExpression::PrerequisiteExpression(const std::string& str) { if (!subString.empty()) { this->sub = std::stoul(s.str()); - } - else { + } else { this->sub = 0; } @@ -89,8 +86,7 @@ PrerequisiteExpression::PrerequisiteExpression(const std::string& str) { if (!bString.empty()) { this->b = new PrerequisiteExpression(bString); - } - else { + } else { this->b = nullptr; } } @@ -109,11 +105,10 @@ bool PrerequisiteExpression::Execute(const std::unordered_mapsub != 0) { // Special case for one Wisp Lee repeatable mission. - a = mission->GetClientInfo().id == 1883 ? - mission->GetMissionState() == static_cast(this->sub) : + a = mission->GetClientInfo().id == 1883 ? + mission->GetMissionState() == static_cast(this->sub) : mission->GetMissionState() >= static_cast(this->sub); - } - else if (mission->IsComplete()) { + } else if (mission->IsComplete()) { a = true; } } @@ -144,42 +139,42 @@ bool MissionPrerequisites::CanAccept(const uint32_t missionId, const std::unorde const auto& info = mission->GetClientInfo(); if (info.repeatable) { - const auto prerequisitesMet = CheckPrerequisites(missionId, missions); + const auto prerequisitesMet = CheckPrerequisites(missionId, missions); - // Checked by client + // Checked by client const time_t time = std::time(nullptr); const time_t lock = mission->GetTimestamp() + info.cooldownTime * 60; - // If there's no time limit, just check the prerequisites, otherwise make sure both conditions are met + // If there's no time limit, just check the prerequisites, otherwise make sure both conditions are met return (info.cooldownTime == -1 ? prerequisitesMet : (lock - time < 0)) && prerequisitesMet; } - // Mission is already accepted and cannot be repeatedly accepted + // Mission is already accepted and cannot be repeatedly accepted return false; } - // Mission is not yet accepted, check the prerequisites + // Mission is not yet accepted, check the prerequisites return CheckPrerequisites(missionId, missions); } bool MissionPrerequisites::CheckPrerequisites(uint32_t missionId, const std::unordered_map& missions) { - const auto& index = expressions.find(missionId); - if (index != expressions.end()) { - return index->second->Execute(missions); - } + const auto& index = expressions.find(missionId); + if (index != expressions.end()) { + return index->second->Execute(missions); + } - auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); - const auto missionEntries = missionsTable->Query([=](const CDMissions& entry) { - return entry.id == static_cast(missionId); - }); + auto* missionsTable = CDClientManager::Instance()->GetTable("Missions"); + const auto missionEntries = missionsTable->Query([=](const CDMissions& entry) { + return entry.id == static_cast(missionId); + }); - if (missionEntries.empty()) - return false; + if (missionEntries.empty()) + return false; - auto* expression = new PrerequisiteExpression(missionEntries[0].prereqMissionID); - expressions.insert_or_assign(missionId, expression); + auto* expression = new PrerequisiteExpression(missionEntries[0].prereqMissionID); + expressions.insert_or_assign(missionId, expression); - return expression->Execute(missions); + return expression->Execute(missions); } std::unordered_map MissionPrerequisites::expressions = {}; diff --git a/dGame/dMission/MissionPrerequisites.h b/dGame/dMission/MissionPrerequisites.h index f426e916..dd349cb1 100644 --- a/dGame/dMission/MissionPrerequisites.h +++ b/dGame/dMission/MissionPrerequisites.h @@ -16,11 +16,11 @@ class PrerequisiteExpression final PrerequisiteExpression* b; public: - /** - * Executes the prerequisite, checking its contents and returning whether or not the mission may be accepted - * @param missions the list of missions to check the prerequisites against (f.e. whether they're completed) - * @return whether or not all the prerequisites are met - */ + /** + * Executes the prerequisite, checking its contents and returning whether or not the mission may be accepted + * @param missions the list of missions to check the prerequisites against (f.e. whether they're completed) + * @return whether or not all the prerequisites are met + */ bool Execute(const std::unordered_map& missions) const; explicit PrerequisiteExpression(const std::string& str); @@ -33,26 +33,26 @@ public: class MissionPrerequisites final { public: - /** - * Checks whether or not the mission identified by the specified ID can be accepted based on the mission inventory passed. - * Also performs checks for daily missions (e.g. if the time out is valid). - * @param missionId the mission ID to check prerequisites for - * @param missions the mission inventory to check the prerequisites against - * @return whether or not the mission identified by the specified ID can be accepted - */ + /** + * Checks whether or not the mission identified by the specified ID can be accepted based on the mission inventory passed. + * Also performs checks for daily missions (e.g. if the time out is valid). + * @param missionId the mission ID to check prerequisites for + * @param missions the mission inventory to check the prerequisites against + * @return whether or not the mission identified by the specified ID can be accepted + */ static bool CanAccept(uint32_t missionId, const std::unordered_map& missions); private: - /** - * Cache of all the executed prerequisites - */ + /** + * Cache of all the executed prerequisites + */ static std::unordered_map expressions; - /** - * Checks the prerequisites for a mission - * @param missionId the mission ID to check prerequisites for - * @param missions the mission inventory to check the prerequisites against - * @return whether or not the mission identified by the specified ID can be accepted - */ - static bool CheckPrerequisites(uint32_t missionId, const std::unordered_map& missions); + /** + * Checks the prerequisites for a mission + * @param missionId the mission ID to check prerequisites for + * @param missions the mission inventory to check the prerequisites against + * @return whether or not the mission identified by the specified ID can be accepted + */ + static bool CheckPrerequisites(uint32_t missionId, const std::unordered_map& missions); }; diff --git a/dGame/dMission/MissionState.h b/dGame/dMission/MissionState.h index c189c708..5ee480da 100644 --- a/dGame/dMission/MissionState.h +++ b/dGame/dMission/MissionState.h @@ -7,50 +7,50 @@ * Represents the possible states a mission can be in */ enum class MissionState : int { - /** - * The mission state is unknown - */ - MISSION_STATE_UNKNOWN = -1, + /** + * The mission state is unknown + */ + MISSION_STATE_UNKNOWN = -1, - /** - * The mission is yielding rewards - */ - MISSION_STATE_REWARDING = 0, + /** + * The mission is yielding rewards + */ + MISSION_STATE_REWARDING = 0, - /** - * The mission can be accepted - */ - MISSION_STATE_AVAILABLE = 1, + /** + * The mission can be accepted + */ + MISSION_STATE_AVAILABLE = 1, - /** - * The mission has been accepted but not yet completed - */ - MISSION_STATE_ACTIVE = 2, + /** + * The mission has been accepted but not yet completed + */ + MISSION_STATE_ACTIVE = 2, - /** - * All the tasks for the mission have been completed and the entity can turn the mission in to complete it - */ - MISSION_STATE_READY_TO_COMPLETE = 4, //!< The mission is ready to complete + /** + * All the tasks for the mission have been completed and the entity can turn the mission in to complete it + */ + MISSION_STATE_READY_TO_COMPLETE = 4, //!< The mission is ready to complete - /** - * The mission has been completed - */ - MISSION_STATE_COMPLETE = 8, + /** + * The mission has been completed + */ + MISSION_STATE_COMPLETE = 8, - /** - * The mission is available again and has been completed before. Used for daily missions. - */ - MISSION_STATE_COMPLETE_AVAILABLE = 9, + /** + * The mission is available again and has been completed before. Used for daily missions. + */ + MISSION_STATE_COMPLETE_AVAILABLE = 9, - /** - * The mission is active and has been completed before. Used for daily missions. - */ - MISSION_STATE_COMPLETE_ACTIVE = 10, + /** + * The mission is active and has been completed before. Used for daily missions. + */ + MISSION_STATE_COMPLETE_ACTIVE = 10, - /** - * The mission has been completed before and has now been completed again. Used for daily missions. - */ - MISSION_STATE_COMPLETE_READY_TO_COMPLETE = 12 + /** + * The mission has been completed before and has now been completed again. Used for daily missions. + */ + MISSION_STATE_COMPLETE_READY_TO_COMPLETE = 12 }; #endif //!__MISSIONSTATE__H__ diff --git a/dGame/dMission/MissionTask.cpp b/dGame/dMission/MissionTask.cpp index 36051305..e08dc146 100644 --- a/dGame/dMission/MissionTask.cpp +++ b/dGame/dMission/MissionTask.cpp @@ -14,8 +14,7 @@ #include "MissionComponent.h" -MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) -{ +MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) { this->info = info; this->mission = mission; this->mask = mask; @@ -43,36 +42,30 @@ MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) } -MissionTaskType MissionTask::GetType() const -{ +MissionTaskType MissionTask::GetType() const { return static_cast(info->taskType); } -uint32_t MissionTask::GetProgress() const -{ +uint32_t MissionTask::GetProgress() const { return progress; } -void MissionTask::SetProgress(const uint32_t value, const bool echo) -{ - if (progress == value) - { +void MissionTask::SetProgress(const uint32_t value, const bool echo) { + if (progress == value) { return; } progress = value; - if (!echo) - { + if (!echo) { return; } auto* entity = mission->GetAssociate(); - if (entity == nullptr) - { + if (entity == nullptr) { return; } @@ -82,23 +75,19 @@ void MissionTask::SetProgress(const uint32_t value, const bool echo) } -void MissionTask::SetUnique(const std::vector& value) -{ +void MissionTask::SetUnique(const std::vector& value) { unique = value; } -void MissionTask::AddProgress(int32_t value) -{ +void MissionTask::AddProgress(int32_t value) { value += progress; - if (value > info->targetValue) - { + if (value > info->targetValue) { value = info->targetValue; } - if (value < 0) - { + if (value < 0) { value = 0; } @@ -106,50 +95,42 @@ void MissionTask::AddProgress(int32_t value) } -Mission* MissionTask::GetMission() const -{ +Mission* MissionTask::GetMission() const { return mission; } -uint32_t MissionTask::GetTarget() const -{ +uint32_t MissionTask::GetTarget() const { return info->target; } -const CDMissionTasks& MissionTask::GetClientInfo() const -{ +const CDMissionTasks& MissionTask::GetClientInfo() const { return *info; } -uint32_t MissionTask::GetMask() const -{ +uint32_t MissionTask::GetMask() const { return mask; } -const std::vector& MissionTask::GetUnique() const -{ +const std::vector& MissionTask::GetUnique() const { return unique; } -const std::vector& MissionTask::GetTargets() const -{ +const std::vector& MissionTask::GetTargets() const { return targets; } -const std::vector& MissionTask::GetParameters() const -{ +const std::vector& MissionTask::GetParameters() const { return parameters; } -std::vector MissionTask::GetAllTargets() const -{ +std::vector MissionTask::GetAllTargets() const { auto targets = GetTargets(); targets.push_back(GetTarget()); @@ -158,83 +139,68 @@ std::vector MissionTask::GetAllTargets() const } -bool MissionTask::InTargets(const uint32_t value) const -{ +bool MissionTask::InTargets(const uint32_t value) const { auto targets = GetTargets(); return std::find(targets.begin(), targets.end(), value) != targets.end(); } -bool MissionTask::InAllTargets(const uint32_t value) const -{ +bool MissionTask::InAllTargets(const uint32_t value) const { auto targets = GetAllTargets(); return std::find(targets.begin(), targets.end(), value) != targets.end(); } -bool MissionTask::InParameters(const uint32_t value) const -{ +bool MissionTask::InParameters(const uint32_t value) const { auto parameters = GetParameters(); return std::find(parameters.begin(), parameters.end(), value) != parameters.end(); } -bool MissionTask::IsComplete() const -{ +bool MissionTask::IsComplete() const { // Mission 668 has task uid 984 which is a bit mask. Its completion value is 3. if (info->uid == 984) { return progress >= 3; - } - else { + } else { return progress >= info->targetValue; } } -void MissionTask::Complete() -{ +void MissionTask::Complete() { SetProgress(info->targetValue); } -void MissionTask::CheckCompletion() const -{ - if (IsComplete()) - { +void MissionTask::CheckCompletion() const { + if (IsComplete()) { mission->CheckCompletion(); } } -void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& targets, int32_t count) -{ +void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& targets, int32_t count) { if (IsComplete() && count > 0) return; const auto type = GetType(); - if (count < 0) - { - if (mission->IsMission() && type == MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION && InAllTargets(value)) - { - if (parameters.size() > 0 && (parameters[0] & 1) != 0) - { + if (count < 0) { + if (mission->IsMission() && type == MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION && InAllTargets(value)) { + if (parameters.size() > 0 && (parameters[0] & 1) != 0) { return; } auto* inventoryComponent = mission->GetAssociate()->GetComponent(); - if (inventoryComponent != nullptr) - { + if (inventoryComponent != nullptr) { int32_t itemCount = inventoryComponent->GetLotCountNonTransfer(value); - if (itemCount < info->targetValue) - { + if (itemCount < info->targetValue) { SetProgress(itemCount); - if (mission->IsReadyToComplete()) - { + if (mission->IsReadyToComplete()) { mission->MakeActive(); } } @@ -271,8 +237,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& } activity = static_cast(entity->GetComponent(COMPONENT_TYPE_REBUILD)); - if (activity == nullptr) - { + if (activity == nullptr) { break; } @@ -280,8 +245,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& const auto activityIdOverride = entity->GetVar(u"activityID"); - if (activityIdOverride != 0) - { + if (activityIdOverride != 0) { activityId = activityIdOverride; } @@ -308,8 +272,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& entity = EntityManager::Instance()->GetEntity(associate); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!", associate); break; @@ -335,11 +298,11 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } - case MissionTaskType::MISSION_TASK_TYPE_MINIGAME: + case MissionTaskType::MISSION_TASK_TYPE_MINIGAME: { auto* minigameManager = EntityManager::Instance()->GetEntity(associate); if (minigameManager == nullptr) - break; + break; int32_t gameID = minigameManager->GetLOT(); @@ -353,11 +316,11 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& } // This special case is for shooting gallery missions that want their // progress value set to 1 instead of being set to the target value. - if(info->targetGroup == targets && value >= info->targetValue && GetMission()->IsMission() && info->target == 1864 && info->targetGroup == "performact_score") { + if (info->targetGroup == targets && value >= info->targetValue && GetMission()->IsMission() && info->target == 1864 && info->targetGroup == "performact_score") { SetProgress(1); break; } - if(info->targetGroup == targets && value >= info->targetValue) { + if (info->targetGroup == targets && value >= info->targetValue) { SetProgress(info->targetValue); break; } @@ -383,8 +346,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& entity = EntityManager::Instance()->GetEntity(associate); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("MissionTask", "Failed to find associated entity (%llu)!", associate); break; @@ -431,8 +393,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& if (parameters[0] != associate) break; - if (associate == 1 || associate == 2 || associate == 3) - { + if (associate == 1 || associate == 2 || associate == 3) { if (value > info->targetValue) break; AddProgress(info->targetValue); @@ -447,26 +408,18 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& // If we won at Gnarled Forest, set bit 1 else if (value == 1303) SetProgress(tempProgress |= 1 << 1); // If both bits are set, then the client sees the mission as complete. - } - else if (associate == 10) - { + } else if (associate == 10) { // If the player did not crash during the race, progress this task by count. if (value != 0) break; AddProgress(count); - } - else if (associate == 4 || associate == 5 || associate == 14) - { + } else if (associate == 4 || associate == 5 || associate == 14) { if (!InAllTargets(value)) break; AddProgress(count); - } - else if (associate == 17) - { + } else if (associate == 17) { if (!InAllTargets(value)) break; AddProgress(count); - } - else - { + } else { AddProgress(count); } @@ -503,8 +456,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& } -MissionTask::~MissionTask() -{ +MissionTask::~MissionTask() { targets.clear(); parameters.clear(); diff --git a/dGame/dMission/MissionTask.h b/dGame/dMission/MissionTask.h index 3fcbbe3d..14d885c3 100644 --- a/dGame/dMission/MissionTask.h +++ b/dGame/dMission/MissionTask.h @@ -16,172 +16,172 @@ class MissionTask final { public: MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask); - ~MissionTask(); + ~MissionTask(); - /** - * Attempts to progress this task using the provided parameters. Note that the behavior of this method is different - * for each mission task type. - * @param value the value to progress by - * @param associate optional object ID of an entity that was related to the progression - * @param targets optional multiple targets that need to be met to progress - * @param count a number that indicates the times to progress - */ + /** + * Attempts to progress this task using the provided parameters. Note that the behavior of this method is different + * for each mission task type. + * @param value the value to progress by + * @param associate optional object ID of an entity that was related to the progression + * @param targets optional multiple targets that need to be met to progress + * @param count a number that indicates the times to progress + */ void Progress(int32_t value, LWOOBJID associate = 0, const std::string& targets = "", int32_t count = 1); - /** - * Returns the current progression of this task - * @return the current progression of this task - */ + /** + * Returns the current progression of this task + * @return the current progression of this task + */ uint32_t GetProgress() const; - /** - * Progresses the progress of this task by the provided value. Does not exceed the target progress. - * @param value the value to progress by - */ - void AddProgress(int32_t value); + /** + * Progresses the progress of this task by the provided value. Does not exceed the target progress. + * @param value the value to progress by + */ + void AddProgress(int32_t value); - /** - * Sets the progress of the task and optionally notifies the client - * @param value the value to set for the progress - * @param echo if true, this will notify the client of the change - */ - void SetProgress(uint32_t value, bool echo = true); + /** + * Sets the progress of the task and optionally notifies the client + * @param value the value to set for the progress + * @param echo if true, this will notify the client of the change + */ + void SetProgress(uint32_t value, bool echo = true); - /** - * Returns the mission this task belongs to - * @return the mission this task belongs to - */ + /** + * Returns the mission this task belongs to + * @return the mission this task belongs to + */ Mission* GetMission() const; - /** - * Returns the type of this task - * @return the type of this task - */ + /** + * Returns the type of this task + * @return the type of this task + */ MissionTaskType GetType() const; - /** - * Returns the value that should be progressed to, to complete the mission (the target value) - * @return the target value - */ + /** + * Returns the value that should be progressed to, to complete the mission (the target value) + * @return the target value + */ uint32_t GetTarget() const; - /** - * Returns the database information for this mission - * @return the database information for this mission - */ + /** + * Returns the database information for this mission + * @return the database information for this mission + */ const CDMissionTasks& GetClientInfo() const; - /** - * Returns the mask for this mission, used for communicating updates - * @return the mask for this mission, used for communicating updates - */ + /** + * Returns the mask for this mission, used for communicating updates + * @return the mask for this mission, used for communicating updates + */ uint32_t GetMask() const; - /** - * Returns the currently visited list of unique locations (only used for visiting mission types) - * @return the currently visited list of unique locations - */ + /** + * Returns the currently visited list of unique locations (only used for visiting mission types) + * @return the currently visited list of unique locations + */ const std::vector& GetUnique() const; - /** - * Sets the uniquely visited list of locations - * @param value the uniquely visited list of locations - */ - void SetUnique(const std::vector& value); + /** + * Sets the uniquely visited list of locations + * @param value the uniquely visited list of locations + */ + void SetUnique(const std::vector& value); - /** - * Returns the possibly target values for this mission task for progression - * @return the possibly target values for this mission task for progression - */ + /** + * Returns the possibly target values for this mission task for progression + * @return the possibly target values for this mission task for progression + */ const std::vector& GetTargets() const; - /** - * Returns the parameters for this task: meta information that determines if the task can be progressed. Note: - * not used by all task types. - * @return the parameters for this task - */ + /** + * Returns the parameters for this task: meta information that determines if the task can be progressed. Note: + * not used by all task types. + * @return the parameters for this task + */ const std::vector& GetParameters() const; - /** - * Returns all the target values for this mission, including the target value concatenated by the optional list of - * targets parsed as ints. - * @return all the targets for this task - */ + /** + * Returns all the target values for this mission, including the target value concatenated by the optional list of + * targets parsed as ints. + * @return all the targets for this task + */ std::vector GetAllTargets() const; - /** - * Returns whether the value is in the list of target values of this task - * @param value the value to check for - * @return true if the value is in the target list, false otherwise - */ + /** + * Returns whether the value is in the list of target values of this task + * @param value the value to check for + * @return true if the value is in the target list, false otherwise + */ bool InTargets(uint32_t value) const; - /** - * Returns whether the value is in one of the target values or equals the individual target value of this task - * @param value the value to check for - * @return true if the value is one of the targets, false otherwise - */ + /** + * Returns whether the value is in one of the target values or equals the individual target value of this task + * @param value the value to check for + * @return true if the value is one of the targets, false otherwise + */ bool InAllTargets(uint32_t value) const; - /** - * Checks if the provided is one of the parameters for this task - * @param value the value to check for - * @return true if the value is one of the parameters, false otherwise - */ + /** + * Checks if the provided is one of the parameters for this task + * @param value the value to check for + * @return true if the value is one of the parameters, false otherwise + */ bool InParameters(uint32_t value) const; - /** - * Checks if this task has been completed by comparing its progress against the target value - * @return true if the task has been completed, false otherwise - */ + /** + * Checks if this task has been completed by comparing its progress against the target value + * @return true if the task has been completed, false otherwise + */ bool IsComplete() const; - /** - * Completes the mission by setting the progress to the required value - */ + /** + * Completes the mission by setting the progress to the required value + */ void Complete(); private: - /** - * Datbase information about this task - */ + /** + * Datbase information about this task + */ CDMissionTasks* info; - /** - * The mission this task belongs to - */ + /** + * The mission this task belongs to + */ Mission* mission; - /** - * Mask used for communicating mission updates - */ + /** + * Mask used for communicating mission updates + */ uint32_t mask; - /** - * The current progression towards the target - */ + /** + * The current progression towards the target + */ uint32_t progress; - /** - * The list of target values for progressing this task - */ + /** + * The list of target values for progressing this task + */ std::vector targets; - /** - * The list of parameters for progressing this task (not used by all task types) - */ + /** + * The list of parameters for progressing this task (not used by all task types) + */ std::vector parameters; - /** - * The unique places visited for progression (not used by all task types) - */ + /** + * The unique places visited for progression (not used by all task types) + */ std::vector unique; - /** - * Checks if the task is complete, and if so checks if the parent mission is complete - */ + /** + * Checks if the task is complete, and if so checks if the parent mission is complete + */ void CheckCompletion() const; }; -#endif +#endif diff --git a/dGame/dMission/MissionTaskType.h b/dGame/dMission/MissionTaskType.h index 345f8fff..08f1bff9 100644 --- a/dGame/dMission/MissionTaskType.h +++ b/dGame/dMission/MissionTaskType.h @@ -5,27 +5,27 @@ //! An enum for mission task types enum class MissionTaskType : int { - MISSION_TASK_TYPE_UNKNOWN = -1, //!< The task type is unknown - MISSION_TASK_TYPE_SMASH = 0, //!< A task for smashing something - MISSION_TASK_TYPE_SCRIPT = 1, //!< A task handled by a server LUA script - MISSION_TASK_TYPE_ACTIVITY = 2, //!< A task for completing a quickbuild - MISSION_TASK_TYPE_ENVIRONMENT = 3, //!< A task for something in the environment - MISSION_TASK_TYPE_MISSION_INTERACTION = 4, //!< A task for interacting with a mission - MISSION_TASK_TYPE_EMOTE = 5, //!< A task for playing an emote - MISSION_TASK_TYPE_FOOD = 9, //!< A task for eating food - MISSION_TASK_TYPE_SKILL = 10, //!< A task for performing a skill - MISSION_TASK_TYPE_ITEM_COLLECTION = 11, //!< A task for collecting an item - MISSION_TASK_TYPE_LOCATION = 12, //!< A task for finding a location - MISSION_TASK_TYPE_MINIGAME = 14, //!< A task for doing something in a minigame - MISSION_TASK_TYPE_NON_MISSION_INTERACTION = 15, //!< A task for interacting with a non-mission - MISSION_TASK_TYPE_MISSION_COMPLETE = 16, //!< A task for completing a mission - MISSION_TASK_TYPE_EARN_REPUTATION = 17, //!< A task for earning reputation - MISSION_TASK_TYPE_POWERUP = 21, //!< A task for collecting a powerup - MISSION_TASK_TYPE_PET_TAMING = 22, //!< A task for taming a pet - MISSION_TASK_TYPE_RACING = 23, //!< A task for racing - MISSION_TASK_TYPE_PLAYER_FLAG = 24, //!< A task for setting a player flag - MISSION_TASK_TYPE_PLACE_MODEL = 25, //!< A task for picking up a model - MISSION_TASK_TYPE_VISIT_PROPERTY = 30 //!< A task for visiting a property + MISSION_TASK_TYPE_UNKNOWN = -1, //!< The task type is unknown + MISSION_TASK_TYPE_SMASH = 0, //!< A task for smashing something + MISSION_TASK_TYPE_SCRIPT = 1, //!< A task handled by a server LUA script + MISSION_TASK_TYPE_ACTIVITY = 2, //!< A task for completing a quickbuild + MISSION_TASK_TYPE_ENVIRONMENT = 3, //!< A task for something in the environment + MISSION_TASK_TYPE_MISSION_INTERACTION = 4, //!< A task for interacting with a mission + MISSION_TASK_TYPE_EMOTE = 5, //!< A task for playing an emote + MISSION_TASK_TYPE_FOOD = 9, //!< A task for eating food + MISSION_TASK_TYPE_SKILL = 10, //!< A task for performing a skill + MISSION_TASK_TYPE_ITEM_COLLECTION = 11, //!< A task for collecting an item + MISSION_TASK_TYPE_LOCATION = 12, //!< A task for finding a location + MISSION_TASK_TYPE_MINIGAME = 14, //!< A task for doing something in a minigame + MISSION_TASK_TYPE_NON_MISSION_INTERACTION = 15, //!< A task for interacting with a non-mission + MISSION_TASK_TYPE_MISSION_COMPLETE = 16, //!< A task for completing a mission + MISSION_TASK_TYPE_EARN_REPUTATION = 17, //!< A task for earning reputation + MISSION_TASK_TYPE_POWERUP = 21, //!< A task for collecting a powerup + MISSION_TASK_TYPE_PET_TAMING = 22, //!< A task for taming a pet + MISSION_TASK_TYPE_RACING = 23, //!< A task for racing + MISSION_TASK_TYPE_PLAYER_FLAG = 24, //!< A task for setting a player flag + MISSION_TASK_TYPE_PLACE_MODEL = 25, //!< A task for picking up a model + MISSION_TASK_TYPE_VISIT_PROPERTY = 30 //!< A task for visiting a property }; #endif diff --git a/dGame/dMission/RacingTaskParam.h b/dGame/dMission/RacingTaskParam.h index 38f8dd8e..5958cb5a 100644 --- a/dGame/dMission/RacingTaskParam.h +++ b/dGame/dMission/RacingTaskParam.h @@ -3,18 +3,18 @@ #include enum class RacingTaskParam : int32_t { - RACING_TASK_PARAM_FINISH_WITH_PLACEMENT = 1, // BrickDatabase::emptyCache {}; +std::vector BrickDatabase::emptyCache{}; BrickDatabase* BrickDatabase::m_Address = nullptr; BrickDatabase::BrickDatabase() = default; BrickDatabase::~BrickDatabase() = default; -std::vector& BrickDatabase::GetBricks(const std::string& lxfmlPath) -{ - const auto cached = m_Cache.find(lxfmlPath); +std::vector& BrickDatabase::GetBricks(const std::string& lxfmlPath) { + const auto cached = m_Cache.find(lxfmlPath); - if (cached != m_Cache.end()) { - return cached->second; - } + if (cached != m_Cache.end()) { + return cached->second; + } - std::ifstream file(lxfmlPath); + std::ifstream file(lxfmlPath); if (!file.good()) { return emptyCache; } - + std::stringstream data; data << file.rdbuf(); if (data.str().empty()) { @@ -40,53 +39,53 @@ std::vector& BrickDatabase::GetBricks(const std::string& lxfmlPath) auto* lxfml = doc->FirstChildElement("LXFML"); auto* bricks = lxfml->FirstChildElement("Bricks"); std::string searchTerm = "Brick"; - + if (!bricks) { searchTerm = "Part"; bricks = lxfml->FirstChildElement("Scene")->FirstChildElement("Model")->FirstChildElement("Group"); - + if (!bricks) { - return emptyCache; + return emptyCache; } } - + auto* currentBrick = bricks->FirstChildElement(searchTerm.c_str()); while (currentBrick != nullptr) { - auto* part = currentBrick->FirstChildElement("Part"); + auto* part = currentBrick->FirstChildElement("Part"); if (part == nullptr) part = currentBrick; if (part->Attribute("designID") != nullptr) { - Brick brick { static_cast(part->IntAttribute("designID")) }; + Brick brick{ static_cast(part->IntAttribute("designID")) }; - // Depends on the file, some don't specify a list but just a single material - const auto* materialList = part->Attribute("materials"); - const auto* materialID = part->Attribute("materialID"); + // Depends on the file, some don't specify a list but just a single material + const auto* materialList = part->Attribute("materials"); + const auto* materialID = part->Attribute("materialID"); - if (materialList != nullptr) { - std::string materialString(materialList); - const auto materials = GeneralUtils::SplitString(materialString, ','); + if (materialList != nullptr) { + std::string materialString(materialList); + const auto materials = GeneralUtils::SplitString(materialString, ','); - if (!materials.empty()) { - brick.materialID = std::stoi(materials[0]); - } else { - brick.materialID = 0; - } - } else if (materialID != nullptr) { - brick.materialID = std::stoi(materialID); - } else { - brick.materialID = 0; // This is bad, makes it so the minigame can't be played - } + if (!materials.empty()) { + brick.materialID = std::stoi(materials[0]); + } else { + brick.materialID = 0; + } + } else if (materialID != nullptr) { + brick.materialID = std::stoi(materialID); + } else { + brick.materialID = 0; // This is bad, makes it so the minigame can't be played + } parts.push_back(brick); } - + currentBrick = currentBrick->NextSiblingElement(searchTerm.c_str()); } - m_Cache[lxfmlPath] = parts; + m_Cache[lxfmlPath] = parts; delete doc; - return m_Cache[lxfmlPath]; + return m_Cache[lxfmlPath]; } diff --git a/dGame/dUtilities/BrickDatabase.h b/dGame/dUtilities/BrickDatabase.h index 7e16c2ea..589d46ae 100644 --- a/dGame/dUtilities/BrickDatabase.h +++ b/dGame/dUtilities/BrickDatabase.h @@ -4,28 +4,26 @@ class BrickDatabase { public: - static BrickDatabase* Instance() - { - if (m_Address == nullptr) - { - m_Address = new BrickDatabase(); - } + static BrickDatabase* Instance() { + if (m_Address == nullptr) { + m_Address = new BrickDatabase(); + } - return m_Address; - } + return m_Address; + } - std::vector& GetBricks(const std::string& lxfmlPath); + std::vector& GetBricks(const std::string& lxfmlPath); - explicit BrickDatabase(); + explicit BrickDatabase(); + + ~BrickDatabase(); - ~BrickDatabase(); - private: - std::unordered_map> m_Cache; + std::unordered_map> m_Cache; - static std::vector emptyCache; + static std::vector emptyCache; - static BrickDatabase* m_Address; //For singleton method + static BrickDatabase* m_Address; //For singleton method - /* data */ + /* data */ }; diff --git a/dGame/dUtilities/GUID.cpp b/dGame/dUtilities/GUID.cpp index fb87139a..57f76a81 100644 --- a/dGame/dUtilities/GUID.cpp +++ b/dGame/dUtilities/GUID.cpp @@ -1,27 +1,27 @@ #include "GUID.h" -GUID::GUID(const std::string &guid) { - sscanf(guid.c_str(), - "{%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx}", - &this->data1, &this->data2, &this->data3, - &this->data4[0], &this->data4[1], &this->data4[2], &this->data4[3], - &this->data4[4], &this->data4[5], &this->data4[6], &this->data4[7]); +GUID::GUID(const std::string& guid) { + sscanf(guid.c_str(), + "{%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx}", + &this->data1, &this->data2, &this->data3, + &this->data4[0], &this->data4[1], &this->data4[2], &this->data4[3], + &this->data4[4], &this->data4[5], &this->data4[6], &this->data4[7]); } uint32_t GUID::GetData1() const { - return data1; + return data1; } uint16_t GUID::GetData2() const { - return data2; + return data2; } uint16_t GUID::GetData3() const { - return data3; + return data3; } std::array GUID::GetData4() const { - return data4; + return data4; } GUID::GUID() = default; diff --git a/dGame/dUtilities/GUID.h b/dGame/dUtilities/GUID.h index 24518785..2d958c10 100644 --- a/dGame/dUtilities/GUID.h +++ b/dGame/dUtilities/GUID.h @@ -5,15 +5,15 @@ class GUID { public: - explicit GUID(); - explicit GUID(const std::string& guid); - uint32_t GetData1() const; - uint16_t GetData2() const; - uint16_t GetData3() const; - std::array GetData4() const; + explicit GUID(); + explicit GUID(const std::string& guid); + uint32_t GetData1() const; + uint16_t GetData2() const; + uint16_t GetData3() const; + std::array GetData4() const; private: - uint32_t data1 = 0; - uint16_t data2 = 0; - uint16_t data3 = 0; - std::array data4 = { 0, 0, 0, 0, 0, 0, 0, 0}; + uint32_t data1 = 0; + uint16_t data2 = 0; + uint16_t data3 = 0; + std::array data4 = { 0, 0, 0, 0, 0, 0, 0, 0 }; }; diff --git a/dGame/dUtilities/GameConfig.cpp b/dGame/dUtilities/GameConfig.cpp index bd57ee65..ad201e6f 100644 --- a/dGame/dUtilities/GameConfig.cpp +++ b/dGame/dUtilities/GameConfig.cpp @@ -1,8 +1,8 @@ #include "GameConfig.h" #include -std::map GameConfig::m_Config {}; -std::string GameConfig::m_EmptyString {}; +std::map GameConfig::m_Config{}; +std::string GameConfig::m_EmptyString{}; void GameConfig::Load(const std::string& filepath) { m_EmptyString = ""; @@ -15,7 +15,7 @@ void GameConfig::Load(const std::string& filepath) { if (line[0] != '#') ProcessLine(line); } } -} +} const std::string& GameConfig::GetValue(const std::string& key) { const auto& it = m_Config.find(key); @@ -37,14 +37,14 @@ void GameConfig::ProcessLine(const std::string& line) { std::vector seglist; while (std::getline(ss, segment, '=')) { - seglist.push_back(segment); + seglist.push_back(segment); } if (seglist.size() != 2) return; //Make sure that on Linux, we remove special characters: if (!seglist[1].empty() && seglist[1][seglist[1].size() - 1] == '\r') - seglist[1].erase(seglist[1].size() - 1); + seglist[1].erase(seglist[1].size() - 1); m_Config.insert_or_assign(seglist[0], seglist[1]); -} \ No newline at end of file +} diff --git a/dGame/dUtilities/GameConfig.h b/dGame/dUtilities/GameConfig.h index e5fc3987..55089f89 100644 --- a/dGame/dUtilities/GameConfig.h +++ b/dGame/dUtilities/GameConfig.h @@ -35,4 +35,4 @@ private: static std::map m_Config; static std::string m_EmptyString; -}; \ No newline at end of file +}; diff --git a/dGame/dUtilities/Loot.cpp b/dGame/dUtilities/Loot.cpp index 8305e152..784d873f 100644 --- a/dGame/dUtilities/Loot.cpp +++ b/dGame/dUtilities/Loot.cpp @@ -15,375 +15,375 @@ #include "MissionComponent.h" LootGenerator::LootGenerator() { - CDLootTableTable* lootTableTable = CDClientManager::Instance()->GetTable("LootTable"); - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance()->GetTable("ItemComponent"); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance()->GetTable("LootMatrix"); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance()->GetTable("RarityTable"); + CDLootTableTable* lootTableTable = CDClientManager::Instance()->GetTable("LootTable"); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance()->GetTable("ComponentsRegistry"); + CDItemComponentTable* itemComponentTable = CDClientManager::Instance()->GetTable("ItemComponent"); + CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance()->GetTable("LootMatrix"); + CDRarityTableTable* rarityTableTable = CDClientManager::Instance()->GetTable("RarityTable"); - // ============================== - // Cache Item Rarities - // ============================== + // ============================== + // Cache Item Rarities + // ============================== - std::vector uniqueItems; + std::vector uniqueItems; - for (const CDLootTable& loot : lootTableTable->GetEntries()) { - uniqueItems.push_back(loot.itemid); - } + for (const CDLootTable& loot : lootTableTable->GetEntries()) { + uniqueItems.push_back(loot.itemid); + } - // filter out duplicates - std::sort(uniqueItems.begin(), uniqueItems.end()); - uniqueItems.erase(std::unique(uniqueItems.begin(), uniqueItems.end()), uniqueItems.end()); + // filter out duplicates + std::sort(uniqueItems.begin(), uniqueItems.end()); + uniqueItems.erase(std::unique(uniqueItems.begin(), uniqueItems.end()), uniqueItems.end()); - for (const uint32_t itemID : uniqueItems) { - uint32_t itemComponentID = componentsRegistryTable->GetByIDAndType(itemID, COMPONENT_TYPE_ITEM); - const CDItemComponent& item = itemComponentTable->GetItemComponentByID(itemComponentID); + for (const uint32_t itemID : uniqueItems) { + uint32_t itemComponentID = componentsRegistryTable->GetByIDAndType(itemID, COMPONENT_TYPE_ITEM); + const CDItemComponent& item = itemComponentTable->GetItemComponentByID(itemComponentID); - m_ItemRarities.insert({itemID, item.rarity}); - } + m_ItemRarities.insert({ itemID, item.rarity }); + } - // ============================== - // Cache Rarity Tables - // ============================== + // ============================== + // Cache Rarity Tables + // ============================== - std::vector uniqueRarityIndices; + std::vector uniqueRarityIndices; - for (const CDRarityTable& rarity : rarityTableTable->GetEntries()) { - uniqueRarityIndices.push_back(rarity.RarityTableIndex); - } + for (const CDRarityTable& rarity : rarityTableTable->GetEntries()) { + uniqueRarityIndices.push_back(rarity.RarityTableIndex); + } - // filter out duplicates - std::sort(uniqueRarityIndices.begin(), uniqueRarityIndices.end()); - uniqueRarityIndices.erase(std::unique(uniqueRarityIndices.begin(), uniqueRarityIndices.end()), uniqueRarityIndices.end()); + // filter out duplicates + std::sort(uniqueRarityIndices.begin(), uniqueRarityIndices.end()); + uniqueRarityIndices.erase(std::unique(uniqueRarityIndices.begin(), uniqueRarityIndices.end()), uniqueRarityIndices.end()); - for (const uint32_t index : uniqueRarityIndices) { - std::vector table = rarityTableTable->Query([index](const CDRarityTable& entry) { return entry.RarityTableIndex == index; }); + for (const uint32_t index : uniqueRarityIndices) { + std::vector table = rarityTableTable->Query([index](const CDRarityTable& entry) { return entry.RarityTableIndex == index; }); - RarityTable rarityTable; + RarityTable rarityTable; - for (const CDRarityTable& entry : table) { - RarityTableEntry rarity{entry.rarity, entry.randmax}; - rarityTable.push_back(rarity); - } + for (const CDRarityTable& entry : table) { + RarityTableEntry rarity{ entry.rarity, entry.randmax }; + rarityTable.push_back(rarity); + } - // sort in descending order based on randMax - std::sort(rarityTable.begin(), rarityTable.end(), [](const RarityTableEntry& x, const RarityTableEntry& y) { return x.randMax > y.randMax; }); + // sort in descending order based on randMax + std::sort(rarityTable.begin(), rarityTable.end(), [](const RarityTableEntry& x, const RarityTableEntry& y) { return x.randMax > y.randMax; }); - m_RarityTables.insert({index, rarityTable}); - } + m_RarityTables.insert({ index, rarityTable }); + } - // ============================== - // Cache Loot Matrices - // ============================== + // ============================== + // Cache Loot Matrices + // ============================== - std::vector uniqueMatrixIndices; + std::vector uniqueMatrixIndices; - for (const CDLootMatrix& matrix : lootMatrixTable->GetEntries()) { - uniqueMatrixIndices.push_back(matrix.LootMatrixIndex); - } + for (const CDLootMatrix& matrix : lootMatrixTable->GetEntries()) { + uniqueMatrixIndices.push_back(matrix.LootMatrixIndex); + } - // filter out duplicates - std::sort(uniqueMatrixIndices.begin(), uniqueMatrixIndices.end()); - uniqueMatrixIndices.erase(std::unique(uniqueMatrixIndices.begin(), uniqueMatrixIndices.end()), uniqueMatrixIndices.end()); + // filter out duplicates + std::sort(uniqueMatrixIndices.begin(), uniqueMatrixIndices.end()); + uniqueMatrixIndices.erase(std::unique(uniqueMatrixIndices.begin(), uniqueMatrixIndices.end()), uniqueMatrixIndices.end()); - for (const uint32_t index : uniqueMatrixIndices) { - std::vector matrix = lootMatrixTable->Query([index](const CDLootMatrix& entry) { return entry.LootMatrixIndex == index; }); + for (const uint32_t index : uniqueMatrixIndices) { + std::vector matrix = lootMatrixTable->Query([index](const CDLootMatrix& entry) { return entry.LootMatrixIndex == index; }); - LootMatrix lootMatrix; + LootMatrix lootMatrix; - for (const CDLootMatrix& entry : matrix) { - LootMatrixEntry matrixEntry{entry.LootTableIndex, entry.RarityTableIndex, entry.percent, entry.minToDrop, entry.maxToDrop}; - lootMatrix.push_back(matrixEntry); - } + for (const CDLootMatrix& entry : matrix) { + LootMatrixEntry matrixEntry{ entry.LootTableIndex, entry.RarityTableIndex, entry.percent, entry.minToDrop, entry.maxToDrop }; + lootMatrix.push_back(matrixEntry); + } - m_LootMatrices.insert({index, lootMatrix}); - } + m_LootMatrices.insert({ index, lootMatrix }); + } - // ============================== - // Cache Loot Tables - // ============================== + // ============================== + // Cache Loot Tables + // ============================== - std::vector uniqueTableIndices; + std::vector uniqueTableIndices; - for (const CDLootTable& entry : lootTableTable->GetEntries()) { - uniqueTableIndices.push_back(entry.LootTableIndex); - } + for (const CDLootTable& entry : lootTableTable->GetEntries()) { + uniqueTableIndices.push_back(entry.LootTableIndex); + } - // filter out duplicates - std::sort(uniqueTableIndices.begin(), uniqueTableIndices.end()); - uniqueTableIndices.erase(std::unique(uniqueTableIndices.begin(), uniqueTableIndices.end()), uniqueTableIndices.end()); + // filter out duplicates + std::sort(uniqueTableIndices.begin(), uniqueTableIndices.end()); + uniqueTableIndices.erase(std::unique(uniqueTableIndices.begin(), uniqueTableIndices.end()), uniqueTableIndices.end()); - for (const uint32_t index : uniqueTableIndices) { - std::vector entries = lootTableTable->Query([index](const CDLootTable& entry) { return entry.LootTableIndex == index; }); + for (const uint32_t index : uniqueTableIndices) { + std::vector entries = lootTableTable->Query([index](const CDLootTable& entry) { return entry.LootTableIndex == index; }); - LootTable lootTable; + LootTable lootTable; - for (const CDLootTable& entry : entries) { - LootTableEntry tableEntry{(LOT)entry.itemid, entry.MissionDrop}; - lootTable.push_back(tableEntry); - } + for (const CDLootTable& entry : entries) { + LootTableEntry tableEntry{ (LOT)entry.itemid, entry.MissionDrop }; + lootTable.push_back(tableEntry); + } - // sort by item rarity descending - std::sort(lootTable.begin(), lootTable.end(), [&](const LootTableEntry& x, const LootTableEntry& y) { - return m_ItemRarities[x.itemID] > m_ItemRarities[y.itemID]; - }); + // sort by item rarity descending + std::sort(lootTable.begin(), lootTable.end(), [&](const LootTableEntry& x, const LootTableEntry& y) { + return m_ItemRarities[x.itemID] > m_ItemRarities[y.itemID]; + }); - m_LootTables.insert({index, lootTable}); - } + m_LootTables.insert({ index, lootTable }); + } } std::unordered_map LootGenerator::RollLootMatrix(Entity* player, uint32_t matrixIndex) { - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - std::unordered_map drops; + std::unordered_map drops; - if (missionComponent == nullptr) { - return drops; - } + if (missionComponent == nullptr) { + return drops; + } - const LootMatrix& matrix = m_LootMatrices[matrixIndex]; + const LootMatrix& matrix = m_LootMatrices[matrixIndex]; - for (const LootMatrixEntry& entry : matrix) { - if (GeneralUtils::GenerateRandomNumber(0, 1) < entry.percent) { - const LootTable& lootTable = m_LootTables[entry.lootTableIndex]; - const RarityTable& rarityTable = m_RarityTables[entry.rarityTableIndex]; + for (const LootMatrixEntry& entry : matrix) { + if (GeneralUtils::GenerateRandomNumber(0, 1) < entry.percent) { + const LootTable& lootTable = m_LootTables[entry.lootTableIndex]; + const RarityTable& rarityTable = m_RarityTables[entry.rarityTableIndex]; - uint32_t dropCount = GeneralUtils::GenerateRandomNumber(entry.minDrop, entry.maxDrop); - for (uint32_t i = 0; i < dropCount; ++i) { - uint32_t maxRarity = 1; + uint32_t dropCount = GeneralUtils::GenerateRandomNumber(entry.minDrop, entry.maxDrop); + for (uint32_t i = 0; i < dropCount; ++i) { + uint32_t maxRarity = 1; - float rarityRoll = GeneralUtils::GenerateRandomNumber(0, 1); + float rarityRoll = GeneralUtils::GenerateRandomNumber(0, 1); - for (const RarityTableEntry& rarity : rarityTable) { - if (rarity.randMax >= rarityRoll) { - maxRarity = rarity.rarity; - } else { - break; - } - } + for (const RarityTableEntry& rarity : rarityTable) { + if (rarity.randMax >= rarityRoll) { + maxRarity = rarity.rarity; + } else { + break; + } + } - bool rarityFound = false; - std::vector possibleDrops; + bool rarityFound = false; + std::vector possibleDrops; - for (const LootTableEntry& loot : lootTable) { - uint32_t rarity = m_ItemRarities[loot.itemID]; + for (const LootTableEntry& loot : lootTable) { + uint32_t rarity = m_ItemRarities[loot.itemID]; - if (rarity == maxRarity) { - possibleDrops.push_back(loot); - rarityFound = true; - } else if (rarity < maxRarity && !rarityFound) { - possibleDrops.push_back(loot); - maxRarity = rarity; - } - } + if (rarity == maxRarity) { + possibleDrops.push_back(loot); + rarityFound = true; + } else if (rarity < maxRarity && !rarityFound) { + possibleDrops.push_back(loot); + maxRarity = rarity; + } + } - if (possibleDrops.size() > 0) { - LootTableEntry drop = possibleDrops[GeneralUtils::GenerateRandomNumber(0, possibleDrops.size() - 1)]; + if (possibleDrops.size() > 0) { + LootTableEntry drop = possibleDrops[GeneralUtils::GenerateRandomNumber(0, possibleDrops.size() - 1)]; - // filter out uneeded mission items - if (drop.isMissionDrop && !missionComponent->RequiresItem(drop.itemID)) - continue; + // filter out uneeded mission items + if (drop.isMissionDrop && !missionComponent->RequiresItem(drop.itemID)) + continue; - // convert faction token proxy - if (drop.itemID == 13763) { - if (missionComponent->GetMissionState(545) == MissionState::MISSION_STATE_COMPLETE) - drop.itemID = 8318; // "Assembly Token" - else if (missionComponent->GetMissionState(556) == MissionState::MISSION_STATE_COMPLETE) - drop.itemID = 8321; // "Venture League Token" - else if (missionComponent->GetMissionState(567) == MissionState::MISSION_STATE_COMPLETE) - drop.itemID = 8319; // "Sentinels Token" - else if (missionComponent->GetMissionState(578) == MissionState::MISSION_STATE_COMPLETE) - drop.itemID = 8320; // "Paradox Token" - } + // convert faction token proxy + if (drop.itemID == 13763) { + if (missionComponent->GetMissionState(545) == MissionState::MISSION_STATE_COMPLETE) + drop.itemID = 8318; // "Assembly Token" + else if (missionComponent->GetMissionState(556) == MissionState::MISSION_STATE_COMPLETE) + drop.itemID = 8321; // "Venture League Token" + else if (missionComponent->GetMissionState(567) == MissionState::MISSION_STATE_COMPLETE) + drop.itemID = 8319; // "Sentinels Token" + else if (missionComponent->GetMissionState(578) == MissionState::MISSION_STATE_COMPLETE) + drop.itemID = 8320; // "Paradox Token" + } - if (drop.itemID == 13763) { - continue; - } // check if we aren't in faction + if (drop.itemID == 13763) { + continue; + } // check if we aren't in faction - if (drops.find(drop.itemID) == drops.end()) { - drops.insert({drop.itemID, 1}); - } else { - ++drops[drop.itemID]; - } - } - } - } - } + if (drops.find(drop.itemID) == drops.end()) { + drops.insert({ drop.itemID, 1 }); + } else { + ++drops[drop.itemID]; + } + } + } + } + } - return drops; + return drops; } std::unordered_map LootGenerator::RollLootMatrix(uint32_t matrixIndex) { - std::unordered_map drops; + std::unordered_map drops; - const LootMatrix& matrix = m_LootMatrices[matrixIndex]; + const LootMatrix& matrix = m_LootMatrices[matrixIndex]; - for (const LootMatrixEntry& entry : matrix) { - if (GeneralUtils::GenerateRandomNumber(0, 1) < entry.percent) { - const LootTable& lootTable = m_LootTables[entry.lootTableIndex]; - const RarityTable& rarityTable = m_RarityTables[entry.rarityTableIndex]; + for (const LootMatrixEntry& entry : matrix) { + if (GeneralUtils::GenerateRandomNumber(0, 1) < entry.percent) { + const LootTable& lootTable = m_LootTables[entry.lootTableIndex]; + const RarityTable& rarityTable = m_RarityTables[entry.rarityTableIndex]; - uint32_t dropCount = GeneralUtils::GenerateRandomNumber(entry.minDrop, entry.maxDrop); - for (uint32_t i = 0; i < dropCount; ++i) { - uint32_t maxRarity = 1; + uint32_t dropCount = GeneralUtils::GenerateRandomNumber(entry.minDrop, entry.maxDrop); + for (uint32_t i = 0; i < dropCount; ++i) { + uint32_t maxRarity = 1; - float rarityRoll = GeneralUtils::GenerateRandomNumber(0, 1); + float rarityRoll = GeneralUtils::GenerateRandomNumber(0, 1); - for (const RarityTableEntry& rarity : rarityTable) { - if (rarity.randMax >= rarityRoll) { - maxRarity = rarity.rarity; - } else { - break; - } - } + for (const RarityTableEntry& rarity : rarityTable) { + if (rarity.randMax >= rarityRoll) { + maxRarity = rarity.rarity; + } else { + break; + } + } - bool rarityFound = false; - std::vector possibleDrops; + bool rarityFound = false; + std::vector possibleDrops; - for (const LootTableEntry& loot : lootTable) { - uint32_t rarity = m_ItemRarities[loot.itemID]; + for (const LootTableEntry& loot : lootTable) { + uint32_t rarity = m_ItemRarities[loot.itemID]; - if (rarity == maxRarity) { - possibleDrops.push_back(loot); - rarityFound = true; - } else if (rarity < maxRarity && !rarityFound) { - possibleDrops.push_back(loot); - maxRarity = rarity; - } - } + if (rarity == maxRarity) { + possibleDrops.push_back(loot); + rarityFound = true; + } else if (rarity < maxRarity && !rarityFound) { + possibleDrops.push_back(loot); + maxRarity = rarity; + } + } - if (possibleDrops.size() > 0) { - const LootTableEntry& drop = possibleDrops[GeneralUtils::GenerateRandomNumber(0, possibleDrops.size() - 1)]; + if (possibleDrops.size() > 0) { + const LootTableEntry& drop = possibleDrops[GeneralUtils::GenerateRandomNumber(0, possibleDrops.size() - 1)]; - if (drops.find(drop.itemID) == drops.end()) { - drops.insert({drop.itemID, 1}); - } else { - ++drops[drop.itemID]; - } - } - } - } - } + if (drops.find(drop.itemID) == drops.end()) { + drops.insert({ drop.itemID, 1 }); + } else { + ++drops[drop.itemID]; + } + } + } + } + } - return drops; + return drops; } void LootGenerator::GiveLoot(Entity* player, uint32_t matrixIndex, eLootSourceType lootSourceType) { - player = player->GetOwner(); // If the owner is overwritten, we collect that here + player = player->GetOwner(); // If the owner is overwritten, we collect that here - std::unordered_map result = RollLootMatrix(player, matrixIndex); + std::unordered_map result = RollLootMatrix(player, matrixIndex); - GiveLoot(player, result, lootSourceType); + GiveLoot(player, result, lootSourceType); } void LootGenerator::GiveLoot(Entity* player, std::unordered_map& result, eLootSourceType lootSourceType) { - player = player->GetOwner(); // if the owner is overwritten, we collect that here + player = player->GetOwner(); // if the owner is overwritten, we collect that here - auto* inventoryComponent = player->GetComponent(); + auto* inventoryComponent = player->GetComponent(); - if (!inventoryComponent) - return; + if (!inventoryComponent) + return; - for (const auto& pair : result) { - inventoryComponent->AddItem(pair.first, pair.second, lootSourceType); - } + for (const auto& pair : result) { + inventoryComponent->AddItem(pair.first, pair.second, lootSourceType); + } } void LootGenerator::GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating) { - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable("ActivityRewards"); - std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable("ActivityRewards"); + std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); - const CDActivityRewards* selectedReward = nullptr; - for (const auto& activityReward : activityRewards) { - if (activityReward.activityRating <= rating && (selectedReward == nullptr || activityReward.activityRating > selectedReward->activityRating)) { - selectedReward = &activityReward; - } - } + const CDActivityRewards* selectedReward = nullptr; + for (const auto& activityReward : activityRewards) { + if (activityReward.activityRating <= rating && (selectedReward == nullptr || activityReward.activityRating > selectedReward->activityRating)) { + selectedReward = &activityReward; + } + } - if (!selectedReward) - return; + if (!selectedReward) + return; - uint32_t minCoins = 0; - uint32_t maxCoins = 0; + uint32_t minCoins = 0; + uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable("CurrencyTable"); - std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); + CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable("CurrencyTable"); + std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); - if (currencyTable.size() > 0) { - minCoins = currencyTable[0].minvalue; - maxCoins = currencyTable[0].maxvalue; - } + if (currencyTable.size() > 0) { + minCoins = currencyTable[0].minvalue; + maxCoins = currencyTable[0].maxvalue; + } - GiveLoot(player, selectedReward->LootMatrixIndex, eLootSourceType::LOOT_SOURCE_ACTIVITY); + GiveLoot(player, selectedReward->LootMatrixIndex, eLootSourceType::LOOT_SOURCE_ACTIVITY); - uint32_t coins = (int)(minCoins + GeneralUtils::GenerateRandomNumber(0, 1) * (maxCoins - minCoins)); + uint32_t coins = (int)(minCoins + GeneralUtils::GenerateRandomNumber(0, 1) * (maxCoins - minCoins)); - auto* character = player->GetCharacter(); + auto* character = player->GetCharacter(); - character->SetCoins(character->GetCoins() + coins, eLootSourceType::LOOT_SOURCE_ACTIVITY); + character->SetCoins(character->GetCoins() + coins, eLootSourceType::LOOT_SOURCE_ACTIVITY); } void LootGenerator::DropLoot(Entity* player, Entity* killedObject, uint32_t matrixIndex, uint32_t minCoins, uint32_t maxCoins) { - player = player->GetOwner(); // if the owner is overwritten, we collect that here + player = player->GetOwner(); // if the owner is overwritten, we collect that here - auto* inventoryComponent = player->GetComponent(); + auto* inventoryComponent = player->GetComponent(); - if (!inventoryComponent) - return; + if (!inventoryComponent) + return; - std::unordered_map result = RollLootMatrix(player, matrixIndex); + std::unordered_map result = RollLootMatrix(player, matrixIndex); - DropLoot(player, killedObject, result, minCoins, maxCoins); + DropLoot(player, killedObject, result, minCoins, maxCoins); } void LootGenerator::DropLoot(Entity* player, Entity* killedObject, std::unordered_map& result, uint32_t minCoins, uint32_t maxCoins) { - player = player->GetOwner(); // if the owner is overwritten, we collect that here + player = player->GetOwner(); // if the owner is overwritten, we collect that here - auto* inventoryComponent = player->GetComponent(); + auto* inventoryComponent = player->GetComponent(); - if (!inventoryComponent) - return; + if (!inventoryComponent) + return; - const auto spawnPosition = killedObject->GetPosition(); + const auto spawnPosition = killedObject->GetPosition(); - const auto source = killedObject->GetObjectID(); + const auto source = killedObject->GetObjectID(); - for (const auto& pair : result) { - for (int i = 0; i < pair.second; ++i) { - GameMessages::SendDropClientLoot(player, source, pair.first, 0, spawnPosition, 1); - } - } + for (const auto& pair : result) { + for (int i = 0; i < pair.second; ++i) { + GameMessages::SendDropClientLoot(player, source, pair.first, 0, spawnPosition, 1); + } + } - uint32_t coins = (int)(minCoins + GeneralUtils::GenerateRandomNumber(0, 1) * (maxCoins - minCoins)); + uint32_t coins = (int)(minCoins + GeneralUtils::GenerateRandomNumber(0, 1) * (maxCoins - minCoins)); - GameMessages::SendDropClientLoot(player, source, LOT_NULL, coins, spawnPosition); + GameMessages::SendDropClientLoot(player, source, LOT_NULL, coins, spawnPosition); } void LootGenerator::DropActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating) { - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable("ActivityRewards"); - std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable("ActivityRewards"); + std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); - const CDActivityRewards* selectedReward = nullptr; - for (const auto& activityReward : activityRewards) { - if (activityReward.activityRating <= rating && (selectedReward == nullptr || activityReward.activityRating > selectedReward->activityRating)) { - selectedReward = &activityReward; - } - } + const CDActivityRewards* selectedReward = nullptr; + for (const auto& activityReward : activityRewards) { + if (activityReward.activityRating <= rating && (selectedReward == nullptr || activityReward.activityRating > selectedReward->activityRating)) { + selectedReward = &activityReward; + } + } - if (selectedReward == nullptr) { - return; - } + if (selectedReward == nullptr) { + return; + } - uint32_t minCoins = 0; - uint32_t maxCoins = 0; + uint32_t minCoins = 0; + uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable("CurrencyTable"); - std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); + CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable("CurrencyTable"); + std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); - if (currencyTable.size() > 0) { - minCoins = currencyTable[0].minvalue; - maxCoins = currencyTable[0].maxvalue; - } + if (currencyTable.size() > 0) { + minCoins = currencyTable[0].minvalue; + maxCoins = currencyTable[0].maxvalue; + } - DropLoot(player, source, selectedReward->LootMatrixIndex, minCoins, maxCoins); + DropLoot(player, source, selectedReward->LootMatrixIndex, minCoins, maxCoins); } diff --git a/dGame/dUtilities/Loot.h b/dGame/dUtilities/Loot.h index b16c834a..7ecc22b8 100644 --- a/dGame/dUtilities/Loot.h +++ b/dGame/dUtilities/Loot.h @@ -8,55 +8,55 @@ class Entity; struct RarityTableEntry { - uint32_t rarity; - float randMax; + uint32_t rarity; + float randMax; }; typedef std::vector RarityTable; struct LootMatrixEntry { - uint32_t lootTableIndex; - uint32_t rarityTableIndex; - float percent; - uint32_t minDrop; - uint32_t maxDrop; + uint32_t lootTableIndex; + uint32_t rarityTableIndex; + float percent; + uint32_t minDrop; + uint32_t maxDrop; }; typedef std::vector LootMatrix; struct LootTableEntry { - LOT itemID; - bool isMissionDrop; + LOT itemID; + bool isMissionDrop; }; typedef std::vector LootTable; // used for glue code with Entity and Player classes namespace Loot { - struct Info { - LWOOBJID id; - LOT lot; - uint32_t count; - }; + struct Info { + LWOOBJID id; + LOT lot; + uint32_t count; + }; } class LootGenerator : public Singleton { - public: - LootGenerator(); +public: + LootGenerator(); - std::unordered_map RollLootMatrix(Entity* player, uint32_t matrixIndex); - std::unordered_map RollLootMatrix(uint32_t matrixIndex); - void GiveLoot(Entity* player, uint32_t matrixIndex, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); - void GiveLoot(Entity* player, std::unordered_map& result, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); - void GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating = 0); - void DropLoot(Entity* player, Entity* killedObject, uint32_t matrixIndex, uint32_t minCoins, uint32_t maxCoins); - void DropLoot(Entity* player, Entity* killedObject, std::unordered_map& result, uint32_t minCoins, uint32_t maxCoins); - void DropActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating = 0); + std::unordered_map RollLootMatrix(Entity* player, uint32_t matrixIndex); + std::unordered_map RollLootMatrix(uint32_t matrixIndex); + void GiveLoot(Entity* player, uint32_t matrixIndex, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); + void GiveLoot(Entity* player, std::unordered_map& result, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); + void GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating = 0); + void DropLoot(Entity* player, Entity* killedObject, uint32_t matrixIndex, uint32_t minCoins, uint32_t maxCoins); + void DropLoot(Entity* player, Entity* killedObject, std::unordered_map& result, uint32_t minCoins, uint32_t maxCoins); + void DropActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating = 0); - private: - std::unordered_map m_ItemRarities; - std::unordered_map m_RarityTables; - std::unordered_map m_LootMatrices; - std::unordered_map m_LootTables; +private: + std::unordered_map m_ItemRarities; + std::unordered_map m_RarityTables; + std::unordered_map m_LootMatrices; + std::unordered_map m_LootTables; }; diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index b15d3bb6..59ce8444 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -24,8 +24,7 @@ #include "Character.h" void Mail::SendMail(const Entity* recipient, const std::string& subject, const std::string& body, const LOT attachment, - const uint16_t attachmentCount) -{ + const uint16_t attachmentCount) { SendMail( LWOOBJID_EMPTY, ServerName, @@ -40,8 +39,7 @@ void Mail::SendMail(const Entity* recipient, const std::string& subject, const s } void Mail::SendMail(const LWOOBJID recipient, const std::string& recipientName, const std::string& subject, - const std::string& body, const LOT attachment, const uint16_t attachmentCount, const SystemAddress& sysAddr) -{ + const std::string& body, const LOT attachment, const uint16_t attachmentCount, const SystemAddress& sysAddr) { SendMail( LWOOBJID_EMPTY, ServerName, @@ -56,8 +54,7 @@ void Mail::SendMail(const LWOOBJID recipient, const std::string& recipientName, } void Mail::SendMail(const LWOOBJID sender, const std::string& senderName, const Entity* recipient, const std::string& subject, - const std::string& body, const LOT attachment, const uint16_t attachmentCount) -{ + const std::string& body, const LOT attachment, const uint16_t attachmentCount) { SendMail( sender, senderName, @@ -72,9 +69,8 @@ void Mail::SendMail(const LWOOBJID sender, const std::string& senderName, const } void Mail::SendMail(const LWOOBJID sender, const std::string& senderName, LWOOBJID recipient, - const std::string& recipientName, const std::string& subject, const std::string& body, const LOT attachment, - const uint16_t attachmentCount, const SystemAddress& sysAddr) -{ + const std::string& recipientName, const std::string& subject, const std::string& body, const LOT attachment, + const uint16_t attachmentCount, const SystemAddress& sysAddr) { auto* ins = Database::CreatePreppedStmt("INSERT INTO `mail`(`sender_id`, `sender_name`, `receiver_id`, `receiver_name`, `time_sent`, `subject`, `body`, `attachment_id`, `attachment_lot`, `attachment_subkey`, `attachment_count`, `was_read`) VALUES (?,?,?,?,?,?,?,?,?,?,?,0)"); ins->setUInt(1, sender); @@ -154,7 +150,7 @@ void Mail::HandleMailStuff(RakNet::BitStream* packet, const SystemAddress& sysAd default: Game::logger->Log("Mail", "Unhandled and possibly undefined MailStuffID: %i", int(stuffID)); } - }); + }); } void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAddr, Entity* entity) { @@ -167,8 +163,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd if (!character) return; - if (character->HasPermission(PermissionMap::RestrictedMailAccess)) - { + if (character->HasPermission(PermissionMap::RestrictedMailAccess)) { // Send a message to the player ChatPackets::SendSystemMessage( sysAddr, @@ -227,8 +222,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd if (res->rowsCount() > 0) { while (res->next()) receiverID = res->getUInt(1); - } - else { + } else { Mail::SendSendResponse(sysAddr, Mail::MailSendResponse::RecipientNotFound); delete stmt; delete res; @@ -242,8 +236,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd if (GeneralUtils::CaseInsensitiveStringCompare(recipient, character->GetName()) || receiverID == character->GetObjectID()) { Mail::SendSendResponse(sysAddr, Mail::MailSendResponse::CannotMailSelf); return; - } - else { + } else { uint64_t currentTime = time(NULL); sql::PreparedStatement* ins = Database::CreatePreppedStmt("INSERT INTO `mail`(`sender_id`, `sender_name`, `receiver_id`, `receiver_name`, `time_sent`, `subject`, `body`, `attachment_id`, `attachment_lot`, `attachment_subkey`, `attachment_count`, `was_read`) VALUES (?,?,?,?,?,?,?,?,?,?,?,0)"); ins->setUInt(1, character->GetObjectID()); @@ -272,8 +265,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd auto* missionCompoent = entity->GetComponent(); - if (missionCompoent != nullptr) - { + if (missionCompoent != nullptr) { missionCompoent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, itemLOT, LWOOBJID_EMPTY, "", -attachmentCount); } } @@ -405,7 +397,7 @@ void Mail::HandleNotificationRequest(const SystemAddress& sysAddr, uint32_t obje if (res->rowsCount() > 0) Mail::SendNotification(sysAddr, res->rowsCount()); delete res; delete stmt; - }); + }); } void Mail::SendSendResponse(const SystemAddress& sysAddr, MailSendResponse response) { diff --git a/dGame/dUtilities/Mail.h b/dGame/dUtilities/Mail.h index 4853db18..c8eabe6b 100644 --- a/dGame/dUtilities/Mail.h +++ b/dGame/dUtilities/Mail.h @@ -56,7 +56,7 @@ namespace Mail { uint16_t attachmentCount, const SystemAddress& sysAddr ); - + void SendMail( LWOOBJID sender, const std::string& senderName, @@ -92,4 +92,4 @@ namespace Mail { void SendAttachmentRemoveConfirm(const SystemAddress& sysAddr, uint64_t mailID); void SendDeleteConfirm(const SystemAddress& sysAddr, uint64_t mailID, LWOOBJID playerID); void SendReadConfirm(const SystemAddress& sysAddr, uint64_t mailID); -}; \ No newline at end of file +}; diff --git a/dGame/dUtilities/Preconditions.cpp b/dGame/dUtilities/Preconditions.cpp index 1b442f49..1f719433 100644 --- a/dGame/dUtilities/Preconditions.cpp +++ b/dGame/dUtilities/Preconditions.cpp @@ -19,12 +19,11 @@ std::map Preconditions::cache = {}; Precondition::Precondition(const uint32_t condition) { auto query = CDClientDatabase::CreatePreppedStmt( "SELECT type, targetLOT, targetCount FROM Preconditions WHERE id = ?;"); - query.bind(1, (int) condition); + query.bind(1, (int)condition); auto result = query.execQuery(); - if (result.eof()) - { + if (result.eof()) { this->type = PreconditionType::ItemEquipped; this->count = 1; this->values = { 0 }; @@ -36,16 +35,13 @@ Precondition::Precondition(const uint32_t condition) { this->type = static_cast(result.fieldIsNull(0) ? 0 : result.getIntField(0)); - if (!result.fieldIsNull(1)) - { + if (!result.fieldIsNull(1)) { std::istringstream stream(result.getStringField(1)); std::string token; - while (std::getline(stream, token, ',')) - { + while (std::getline(stream, token, ',')) { uint32_t value; - if (GeneralUtils::TryParse(token, value)) - { + if (GeneralUtils::TryParse(token, value)) { this->values.push_back(value); } } @@ -57,10 +53,8 @@ Precondition::Precondition(const uint32_t condition) { } -bool Precondition::Check(Entity* player, bool evaluateCosts) const -{ - if (values.empty()) - { +bool Precondition::Check(Entity* player, bool evaluateCosts) const { + if (values.empty()) { return true; // There are very few of these } @@ -100,22 +94,18 @@ bool Precondition::Check(Entity* player, bool evaluateCosts) const auto passedAny = false; - for (const auto value : values) - { + for (const auto value : values) { const auto passed = CheckValue(player, value, evaluateCosts); - if (passed && any) - { + if (passed && any) { return true; } - if (!passed && !any) - { + if (!passed && !any) { return false; } - if (passed) - { + if (passed) { passedAny = true; } } @@ -124,8 +114,7 @@ bool Precondition::Check(Entity* player, bool evaluateCosts) const } -bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluateCosts) const -{ +bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluateCosts) const { auto* missionComponent = player->GetComponent(); auto* inventoryComponent = player->GetComponent(); auto* destroyableComponent = player->GetComponent(); @@ -134,8 +123,7 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluat Mission* mission; - switch (type) - { + switch (type) { case PreconditionType::ItemEquipped: return inventoryComponent->IsEquipped(value); case PreconditionType::ItemNotEquipped: @@ -180,20 +168,16 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluat case PreconditionType::IsPetTaming: return false; // TODO case PreconditionType::HasFaction: - for (const auto faction : destroyableComponent->GetFactionIDs()) - { - if (faction == static_cast(value)) - { + for (const auto faction : destroyableComponent->GetFactionIDs()) { + if (faction == static_cast(value)) { return true; } } return false; case PreconditionType::DoesNotHaveFaction: - for (const auto faction : destroyableComponent->GetFactionIDs()) - { - if (faction == static_cast(value)) - { + for (const auto faction : destroyableComponent->GetFactionIDs()) { + if (faction == static_cast(value)) { return false; } } @@ -214,10 +198,8 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluat } } -PreconditionExpression::PreconditionExpression(const std::string& conditions) -{ - if (conditions.empty()) - { +PreconditionExpression::PreconditionExpression(const std::string& conditions) { + if (conditions.empty()) { empty = true; return; @@ -230,17 +212,14 @@ PreconditionExpression::PreconditionExpression(const std::string& conditions) auto done = false; - for (auto i = 0u; i < conditions.size(); ++i) - { - if (done) - { + for (auto i = 0u; i < conditions.size(); ++i) { + if (done) { break; } const auto character = conditions[i]; - switch (character) - { + switch (character) { case '|': bor = true; b << conditions.substr(i + 1); @@ -277,32 +256,24 @@ PreconditionExpression::PreconditionExpression(const std::string& conditions) const auto aString = a.str(); - if (!aString.empty()) - { + if (!aString.empty()) { this->condition = std::stoul(a.str()); - } - else - { + } else { this->condition = 0; } const auto bString = b.str(); - if (!bString.empty()) - { + if (!bString.empty()) { this->next = new PreconditionExpression(bString); - } - else - { + } else { this->next = nullptr; } } -bool PreconditionExpression::Check(Entity* player, bool evaluateCosts) const -{ - if (empty) - { +bool PreconditionExpression::Check(Entity* player, bool evaluateCosts) const { + if (empty) { return true; } @@ -313,8 +284,7 @@ bool PreconditionExpression::Check(Entity* player, bool evaluateCosts) const const auto a = Preconditions::Check(player, condition, evaluateCosts); - if (!a) - { + if (!a) { GameMessages::SendNotifyClientFailedPrecondition(player->GetObjectID(), player->GetSystemAddress(), u"", condition); } @@ -323,24 +293,19 @@ bool PreconditionExpression::Check(Entity* player, bool evaluateCosts) const return m_or ? a || b : a && b; } -PreconditionExpression::~PreconditionExpression() -{ +PreconditionExpression::~PreconditionExpression() { delete next; } -bool Preconditions::Check(Entity* player, const uint32_t condition, bool evaluateCosts) -{ +bool Preconditions::Check(Entity* player, const uint32_t condition, bool evaluateCosts) { Precondition* precondition; const auto& index = cache.find(condition); - if (index != cache.end()) - { + if (index != cache.end()) { precondition = index->second; - } - else - { + } else { precondition = new Precondition(condition); cache.insert_or_assign(condition, precondition); @@ -350,16 +315,13 @@ bool Preconditions::Check(Entity* player, const uint32_t condition, bool evaluat } -PreconditionExpression Preconditions::CreateExpression(const std::string& conditions) -{ +PreconditionExpression Preconditions::CreateExpression(const std::string& conditions) { return PreconditionExpression(conditions); } -Preconditions::~Preconditions() -{ - for (const auto& condition : cache) - { +Preconditions::~Preconditions() { + for (const auto& condition : cache) { delete condition.second; } diff --git a/dGame/dUtilities/Preconditions.h b/dGame/dUtilities/Preconditions.h index 0ceeb32a..08e564bf 100644 --- a/dGame/dUtilities/Preconditions.h +++ b/dGame/dUtilities/Preconditions.h @@ -6,26 +6,26 @@ enum class PreconditionType { - ItemEquipped, - ItemNotEquipped, - HasItem, - DoesNotHaveItem, - HasAchievement, - MissionAvailable, - OnMission, - MissionComplete, - PetDeployed, - HasFlag, - WithinShape, - InBuild, - TeamCheck, - IsPetTaming, - HasFaction, - DoesNotHaveFaction, - HasRacingLicence, - DoesNotHaveRacingLicence, - LegoClubMember, - NoInteraction, + ItemEquipped, + ItemNotEquipped, + HasItem, + DoesNotHaveItem, + HasAchievement, + MissionAvailable, + OnMission, + MissionComplete, + PetDeployed, + HasFlag, + WithinShape, + InBuild, + TeamCheck, + IsPetTaming, + HasFaction, + DoesNotHaveFaction, + HasRacingLicence, + DoesNotHaveRacingLicence, + LegoClubMember, + NoInteraction, HasLevel = 22 }; @@ -33,49 +33,49 @@ enum class PreconditionType class Precondition final { public: - explicit Precondition(uint32_t condition); - - bool Check(Entity* player, bool evaluateCosts = false) const; - + explicit Precondition(uint32_t condition); + + bool Check(Entity* player, bool evaluateCosts = false) const; + private: - bool CheckValue(Entity* player, uint32_t value, bool evaluateCosts = false) const; - - PreconditionType type; + bool CheckValue(Entity* player, uint32_t value, bool evaluateCosts = false) const; - std::vector values; + PreconditionType type; - uint32_t count; + std::vector values; + + uint32_t count; }; class PreconditionExpression final { public: - explicit PreconditionExpression(const std::string& conditions); + explicit PreconditionExpression(const std::string& conditions); + + bool Check(Entity* player, bool evaluateCosts = false) const; + + ~PreconditionExpression(); - bool Check(Entity* player, bool evaluateCosts = false) const; - - ~PreconditionExpression(); - private: - uint32_t condition = 0; + uint32_t condition = 0; - bool m_or = false; + bool m_or = false; - bool empty = false; + bool empty = false; - PreconditionExpression* next = nullptr; + PreconditionExpression* next = nullptr; }; class Preconditions final { public: - static bool Check(Entity* player, uint32_t condition, bool evaluateCosts = false); + static bool Check(Entity* player, uint32_t condition, bool evaluateCosts = false); - static PreconditionExpression CreateExpression(const std::string& conditions); + static PreconditionExpression CreateExpression(const std::string& conditions); ~Preconditions(); - + private: - static std::map cache; + static std::map cache; }; diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index ecb3bbda..16cdddbb 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -65,80 +65,74 @@ #include "LevelProgressionComponent.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { - std::string chatCommand; - std::vector args; + std::string chatCommand; + std::vector args; - uint32_t breakIndex = 0; - for (uint32_t i = 1; i < command.size(); ++i) { - if (command[i] == L' ') { - breakIndex = i; - break; - } + uint32_t breakIndex = 0; + for (uint32_t i = 1; i < command.size(); ++i) { + if (command[i] == L' ') { + breakIndex = i; + break; + } - chatCommand.push_back(static_cast(command[i])); - breakIndex++; - } + chatCommand.push_back(static_cast(command[i])); + breakIndex++; + } - uint32_t index = ++breakIndex; - while (true) { - std::string arg; + uint32_t index = ++breakIndex; + while (true) { + std::string arg; - while (index < command.size()) { - if (command[index] == L' ') { - args.push_back(arg); - arg = ""; - index++; - continue; - } + while (index < command.size()) { + if (command[index] == L' ') { + args.push_back(arg); + arg = ""; + index++; + continue; + } - arg.push_back(static_cast(command[index])); - index++; - } + arg.push_back(static_cast(command[index])); + index++; + } - if (arg != "") { - args.push_back(arg); - } + if (arg != "") { + args.push_back(arg); + } - break; - } + break; + } - //Game::logger->Log("SlashCommandHandler", "Received chat command \"%s\"", GeneralUtils::UTF16ToWTF8(command).c_str()); + //Game::logger->Log("SlashCommandHandler", "Received chat command \"%s\"", GeneralUtils::UTF16ToWTF8(command).c_str()); - User* user = UserManager::Instance()->GetUser(sysAddr); - if ((chatCommand == "setgmlevel" || chatCommand == "makegm" || chatCommand == "gmlevel") && user->GetMaxGMLevel() > GAME_MASTER_LEVEL_CIVILIAN) { - if (args.size() != 1) return; + User* user = UserManager::Instance()->GetUser(sysAddr); + if ((chatCommand == "setgmlevel" || chatCommand == "makegm" || chatCommand == "gmlevel") && user->GetMaxGMLevel() > GAME_MASTER_LEVEL_CIVILIAN) { + if (args.size() != 1) return; uint32_t level; - if (!GeneralUtils::TryParse(args[0], level)) - { + if (!GeneralUtils::TryParse(args[0], level)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid gm level."); return; } #ifndef DEVELOPER_SERVER - if (user->GetMaxGMLevel() == GAME_MASTER_LEVEL_JUNIOR_DEVELOPER) - { + if (user->GetMaxGMLevel() == GAME_MASTER_LEVEL_JUNIOR_DEVELOPER) { level = GAME_MASTER_LEVEL_CIVILIAN; } #endif - if (level > user->GetMaxGMLevel()) - { + if (level > user->GetMaxGMLevel()) { level = user->GetMaxGMLevel(); } - if (level == entity->GetGMLevel()) return; - bool success = user->GetMaxGMLevel() >= level; + if (level == entity->GetGMLevel()) return; + bool success = user->GetMaxGMLevel() >= level; - if (success) { + if (success) { - if (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN && level == GAME_MASTER_LEVEL_CIVILIAN) - { + if (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN && level == GAME_MASTER_LEVEL_CIVILIAN) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); - } - else if (entity->GetGMLevel() == GAME_MASTER_LEVEL_CIVILIAN && level > GAME_MASTER_LEVEL_CIVILIAN) - { + } else if (entity->GetGMLevel() == GAME_MASTER_LEVEL_CIVILIAN && level > GAME_MASTER_LEVEL_CIVILIAN) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); } @@ -150,8 +144,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } #ifndef DEVELOPER_SERVER - if ((entity->GetGMLevel() > user->GetMaxGMLevel()) || (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN && user->GetMaxGMLevel() == GAME_MASTER_LEVEL_JUNIOR_DEVELOPER)) - { + if ((entity->GetGMLevel() > user->GetMaxGMLevel()) || (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN && user->GetMaxGMLevel() == GAME_MASTER_LEVEL_JUNIOR_DEVELOPER)) { WorldPackets::SendGMLevelChange(sysAddr, true, user->GetMaxGMLevel(), entity->GetGMLevel(), GAME_MASTER_LEVEL_CIVILIAN); GameMessages::SendChatModeUpdate(entity->GetObjectID(), GAME_MASTER_LEVEL_CIVILIAN); entity->SetGMLevel(GAME_MASTER_LEVEL_CIVILIAN); @@ -185,15 +178,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "who") - { + if (chatCommand == "who") { ChatPackets::SendSystemMessage( sysAddr, u"Players in this instance: (" + GeneralUtils::to_u16string(Player::GetAllPlayers().size()) + u")" ); - for (auto* player : Player::GetAllPlayers()) - { + for (auto* player : Player::GetAllPlayers()) { const auto& name = player->GetCharacter()->GetName(); ChatPackets::SendSystemMessage( @@ -204,15 +195,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "ping") { - if (!args.empty() && args[0] == "-l") - { + if (!args.empty() && args[0] == "-l") { std::stringstream message; message << "Your latest ping: " << std::to_string(Game::server->GetLatestPing(sysAddr)) << "ms"; ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(message.str())); - } - else - { + } else { std::stringstream message; message << "Your average ping: " << std::to_string(Game::server->GetPing(sysAddr)) << "ms"; @@ -221,36 +209,30 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "skip-ags") - { + if (chatCommand == "skip-ags") { auto* missionComponent = entity->GetComponent(); - if (missionComponent != nullptr && missionComponent->HasMission(479)) - { + if (missionComponent != nullptr && missionComponent->HasMission(479)) { missionComponent->CompleteMission(479); } } - if (chatCommand == "skip-sg") - { + if (chatCommand == "skip-sg") { auto* missionComponent = entity->GetComponent(); - if (missionComponent != nullptr && missionComponent->HasMission(229)) - { + if (missionComponent != nullptr && missionComponent->HasMission(229)) { missionComponent->CompleteMission(229); } } - if (chatCommand == "fix-stats") - { + if (chatCommand == "fix-stats") { // Reset skill component and buff component auto* skillComponent = entity->GetComponent(); auto* buffComponent = entity->GetComponent(); auto* destroyableComponent = entity->GetComponent(); // If any of the components are nullptr, return - if (skillComponent == nullptr || buffComponent == nullptr || destroyableComponent == nullptr) - { + if (skillComponent == nullptr || buffComponent == nullptr || destroyableComponent == nullptr) { return; } @@ -264,8 +246,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit destroyableComponent->FixStats(); } - if (chatCommand == "credits" || chatCommand == "info") - { + if (chatCommand == "credits" || chatCommand == "info") { const auto& customText = chatCommand == "credits" ? VanityUtilities::ParseMarkdown("./vanity/CREDITS.md") : VanityUtilities::ParseMarkdown("./vanity/INFO.md"); { @@ -279,8 +260,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "pushGameState", &args); } - entity->AddCallbackTimer(0.5f, [customText, entity] () - { + entity->AddCallbackTimer(0.5f, [customText, entity]() { AMFArrayValue args; auto* text = new AMFStringValue(); @@ -292,7 +272,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit Game::logger->Log("SlashCommandHandler", "Sending %s", customText.c_str()); GameMessages::SendUIMessageServerToSingleClient(entity, entity->GetSystemAddress(), "ToggleStoryBox", &args); - }); + }); return; } @@ -314,27 +294,26 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit const auto objid = entity->GetObjectID(); - ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, newZone, 0, false, [objid](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) - { - auto* entity = EntityManager::Instance()->GetEntity(objid); + ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, newZone, 0, false, [objid](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { + auto* entity = EntityManager::Instance()->GetEntity(objid); - if (entity == nullptr) { - return; - } + if (entity == nullptr) { + return; + } - const auto sysAddr = entity->GetSystemAddress(); + const auto sysAddr = entity->GetSystemAddress(); - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", entity->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", entity->GetCharacter()->GetName().c_str(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); - if (entity->GetCharacter()) { - entity->GetCharacter()->SetZoneID(zoneID); - entity->GetCharacter()->SetZoneInstance(zoneInstance); - entity->GetCharacter()->SetZoneClone(zoneClone); - } + if (entity->GetCharacter()) { + entity->GetCharacter()->SetZoneID(zoneID); + entity->GetCharacter()->SetZoneInstance(zoneInstance); + entity->GetCharacter()->SetZoneClone(zoneClone); + } - entity->GetCharacter()->SaveXMLToDatabase(); + entity->GetCharacter()->SaveXMLToDatabase(); - WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); + WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); }); } @@ -342,19 +321,18 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Requesting private map..."); const auto& password = args[0]; - ZoneInstanceManager::Instance()->RequestPrivateZone(Game::server, false, password, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) - { - Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + ZoneInstanceManager::Instance()->RequestPrivateZone(Game::server, false, password, [=](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { + Game::logger->Log("UserManager", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); - if (entity->GetCharacter()) { - entity->GetCharacter()->SetZoneID(zoneID); - entity->GetCharacter()->SetZoneInstance(zoneInstance); - entity->GetCharacter()->SetZoneClone(zoneClone); - } + if (entity->GetCharacter()) { + entity->GetCharacter()->SetZoneID(zoneID); + entity->GetCharacter()->SetZoneInstance(zoneInstance); + entity->GetCharacter()->SetZoneClone(zoneClone); + } - entity->GetCharacter()->SaveXMLToDatabase(); + entity->GetCharacter()->SaveXMLToDatabase(); - WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); + WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); }); } @@ -391,8 +369,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto stmt = Database::CreatePreppedStmt("INSERT INTO command_log (character_id, command) VALUES (?, ?);"); stmt->setInt(1, entity->GetCharacter()->GetID()); stmt->setString(2, GeneralUtils::UTF16ToWTF8(command).c_str()); - stmt->execute(); - delete stmt; + stmt->execute(); + delete stmt; if (chatCommand == "setminifig" && args.size() == 2 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_FORUM_MODERATOR) { // could break characters so only allow if GM > 0 int32_t minifigItemId; @@ -456,8 +434,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "unlock-emote" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { int32_t emoteID; - if (!GeneralUtils::TryParse(args[0], emoteID)) - { + if (!GeneralUtils::TryParse(args[0], emoteID)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid emote ID."); return; } @@ -484,20 +461,17 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "speedboost" && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "speedboost" && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { float boost; - if (!GeneralUtils::TryParse(args[0], boost)) - { + if (!GeneralUtils::TryParse(args[0], boost)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid boost."); return; } auto* controllablePhysicsComponent = entity->GetComponent(); - if (controllablePhysicsComponent == nullptr) - { + if (controllablePhysicsComponent == nullptr) { return; } @@ -519,8 +493,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "setcontrolscheme" && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { uint32_t scheme; - if (!GeneralUtils::TryParse(args[0], scheme)) - { + if (!GeneralUtils::TryParse(args[0], scheme)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid control scheme."); return; } @@ -533,8 +506,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "approveproperty" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_LEAD_MODERATOR) { - if (PropertyManagementComponent::Instance() != nullptr) - { + if (PropertyManagementComponent::Instance() != nullptr) { PropertyManagementComponent::Instance()->UpdateApprovedStatus(true); } @@ -571,15 +543,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t size; - if (!GeneralUtils::TryParse(args[0], size)) - { + if (!GeneralUtils::TryParse(args[0], size)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid size."); return; } InventoryComponent* inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); - if (inventory) - { + if (inventory) { auto* items = inventory->GetInventory(ITEMS); items->SetSize(size); @@ -602,8 +572,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit while (std::getline(infile, line)) { SlashCommandHandler::HandleChatCommand(GeneralUtils::ASCIIToUTF16(line), entity, sysAddr); } - } - else { + } else { ChatPackets::SendSystemMessage(sysAddr, u"Unknown macro! Is the filename right?"); } @@ -615,8 +584,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t missionID; - if (!GeneralUtils::TryParse(args[0], missionID)) - { + if (!GeneralUtils::TryParse(args[0], missionID)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } @@ -631,8 +599,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t missionID; - if (!GeneralUtils::TryParse(args[0], missionID)) - { + if (!GeneralUtils::TryParse(args[0], missionID)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } @@ -642,12 +609,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "setflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) - { + if (chatCommand == "setflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) { uint32_t flagId; - if (!GeneralUtils::TryParse(args[0], flagId)) - { + if (!GeneralUtils::TryParse(args[0], flagId)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } @@ -655,12 +620,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit entity->GetCharacter()->SetPlayerFlag(flagId, true); } - if (chatCommand == "setflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 2) - { + if (chatCommand == "setflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 2) { uint32_t flagId; std::string onOffFlag = args[0]; - if (!GeneralUtils::TryParse(args[1], flagId)) - { + if (!GeneralUtils::TryParse(args[1], flagId)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } @@ -670,12 +633,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } entity->GetCharacter()->SetPlayerFlag(flagId, onOffFlag == "on"); } - if (chatCommand == "clearflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) - { + if (chatCommand == "clearflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) { uint32_t flagId; - if (!GeneralUtils::TryParse(args[0], flagId)) - { + if (!GeneralUtils::TryParse(args[0], flagId)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } @@ -688,8 +649,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t missionID; - if (!GeneralUtils::TryParse(args[0], missionID)) - { + if (!GeneralUtils::TryParse(args[0], missionID)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } @@ -782,28 +742,25 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (args.size() == 1) { uint32_t itemLOT; - if (!GeneralUtils::TryParse(args[0], itemLOT)) - { + if (!GeneralUtils::TryParse(args[0], itemLOT)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item LOT."); return; } - InventoryComponent * inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); inventory->AddItem(itemLOT, 1, eLootSourceType::LOOT_SOURCE_MODERATION); - } else if(args.size() == 2) { + } else if (args.size() == 2) { uint32_t itemLOT; - if (!GeneralUtils::TryParse(args[0], itemLOT)) - { + if (!GeneralUtils::TryParse(args[0], itemLOT)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item LOT."); return; } uint32_t count; - if (!GeneralUtils::TryParse(args[1], count)) - { + if (!GeneralUtils::TryParse(args[1], count)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item count."); return; } @@ -811,8 +768,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit InventoryComponent* inventory = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); inventory->AddItem(itemLOT, count, eLootSourceType::LOOT_SOURCE_MODERATION); - } - else { + } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /gmadditem "); } } @@ -832,8 +788,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit delete stmt; delete res; - if (receiverID == 0) - { + if (receiverID == 0) { ChatPackets::SendSystemMessage(sysAddr, u"Failed to find that player"); return; @@ -841,8 +796,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t lot; - if (!GeneralUtils::TryParse(args[1], lot)) - { + if (!GeneralUtils::TryParse(args[1], lot)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item lot."); return; } @@ -868,24 +822,20 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "setname" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "setname" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { std::string name = ""; - for (const auto& arg : args) - { + for (const auto& arg : args) { name += arg + " "; } GameMessages::SendSetName(entity->GetObjectID(), GeneralUtils::ASCIIToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); } - if (chatCommand == "title" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "title" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { std::string name = entity->GetCharacter()->GetName() + " - "; - for (const auto& arg : args) - { + for (const auto& arg : args) { name += arg + " "; } @@ -893,47 +843,42 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "teleport" || chatCommand == "tele") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_JUNIOR_MODERATOR) { - NiPoint3 pos {}; + NiPoint3 pos{}; if (args.size() == 3) { float x, y, z; - if (!GeneralUtils::TryParse(args[0], x)) - { + if (!GeneralUtils::TryParse(args[0], x)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid x."); return; } - if (!GeneralUtils::TryParse(args[1], y)) - { + if (!GeneralUtils::TryParse(args[1], y)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid y."); return; } - if (!GeneralUtils::TryParse(args[2], z)) - { + if (!GeneralUtils::TryParse(args[2], z)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid z."); return; } - pos.SetX(x); - pos.SetY(y); - pos.SetZ(z); + pos.SetX(x); + pos.SetY(y); + pos.SetZ(z); - Game::logger->Log("SlashCommandHandler", "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) { + Game::logger->Log("SlashCommandHandler", "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)) - { + if (!GeneralUtils::TryParse(args[0], x)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid x."); return; } - if (!GeneralUtils::TryParse(args[1], z)) - { + if (!GeneralUtils::TryParse(args[1], z)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid z."); return; } @@ -942,24 +887,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit pos.SetY(0.0f); pos.SetZ(z); - Game::logger->Log("SlashCommandHandler", "Teleporting objectID: %llu to X: %f, Z: %f", entity->GetObjectID(), pos.x, pos.z); - GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); - } else { - ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /teleport () - if no Y given, will teleport to the height of the terrain (or any physics object)."); - } + Game::logger->Log("SlashCommandHandler", "Teleporting objectID: %llu to X: %f, Z: %f", entity->GetObjectID(), pos.x, pos.z); + GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); + } else { + ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /teleport () - if no Y given, will teleport to the height of the terrain (or any physics object)."); + } auto* possessorComponent = entity->GetComponent(); - if (possessorComponent != nullptr) - { + if (possessorComponent != nullptr) { auto* possassableEntity = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); - if (possassableEntity != nullptr) - { + if (possassableEntity != nullptr) { auto* vehiclePhysicsComponent = possassableEntity->GetComponent(); - if (vehiclePhysicsComponent != nullptr) - { + if (vehiclePhysicsComponent != nullptr) { vehiclePhysicsComponent->SetPosition(pos); EntityManager::Instance()->SerializeEntity(possassableEntity); @@ -970,22 +912,19 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "tpall" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "tpall" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { const auto pos = entity->GetPosition(); const auto characters = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER); - for (auto* character : characters) - { + for (auto* character : characters) { GameMessages::SendTeleport(character->GetObjectID(), pos, NiQuaternion(), character->GetSystemAddress()); } return; } - if (chatCommand == "dismount" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "dismount" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { PossessorComponent* possessorComponent; if (entity->TryGetComponent(COMPONENT_TYPE_POSSESSOR, possessorComponent)) { Entity* vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); @@ -1011,16 +950,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t accountId = 0; LWOOBJID characterId = 0; - if (player == nullptr) - { + if (player == nullptr) { auto* accountQuery = Database::CreatePreppedStmt("SELECT account_id, id FROM charinfo WHERE name=? LIMIT 1;"); accountQuery->setString(1, args[0]); auto result = accountQuery->executeQuery(); - if (result->rowsCount() > 0) - { + if (result->rowsCount() > 0) { while (result->next()) { accountId = result->getUInt(1); characterId = result->getUInt64(2); @@ -1033,15 +970,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit delete accountQuery; delete result; - if (accountId == 0) - { + if (accountId == 0) { ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::ASCIIToUTF16(args[0])); return; } - } - else - { + } else { accountId = player->GetParentUser()->GetAccountID(); characterId = player->GetCharacter()->GetID(); } @@ -1050,21 +984,17 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit time_t expire = 1; // Default to indefinate mute - if (args.size() >= 2) - { + if (args.size() >= 2) { uint32_t days = 0; uint32_t hours = 0; - if (!GeneralUtils::TryParse(args[1], days)) - { + if (!GeneralUtils::TryParse(args[1], days)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid days."); return; } - if (args.size() >= 3) - { - if (!GeneralUtils::TryParse(args[2], hours)) - { + if (args.size() >= 3) { + if (!GeneralUtils::TryParse(args[2], hours)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid hours."); return; @@ -1085,9 +1015,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit char buffer[32] = "brought up for review.\0"; - if (expire != 1) - { - std::tm * ptm = std::localtime(&expire); + if (expire != 1) { + std::tm* ptm = std::localtime(&expire); // Format: Mo, 15.06.2009 20:20:00 std::strftime(buffer, 32, "%a, %d.%m.%Y %H:%M:%S", ptm); } @@ -1104,8 +1033,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit bitStream.Write(expire); Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); - } - else { + } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /mute "); } } @@ -1114,8 +1042,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (args.size() == 1) { auto* player = Player::GetPlayer(args[0]); - if (player == nullptr) - { + if (player == nullptr) { ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::ASCIIToUTF16(args[0])); return; @@ -1124,8 +1051,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit Game::server->Disconnect(player->GetSystemAddress(), SERVER_DISCON_KICK); ChatPackets::SendSystemMessage(sysAddr, u"Kicked: " + GeneralUtils::ASCIIToUTF16(args[0])); - } - else { + } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /kick "); } } @@ -1136,31 +1062,26 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t accountId = 0; - if (player == nullptr) - { + if (player == nullptr) { auto* accountQuery = Database::CreatePreppedStmt("SELECT account_id FROM charinfo WHERE name=? LIMIT 1;"); accountQuery->setString(1, args[0]); auto result = accountQuery->executeQuery(); - if (result->rowsCount() > 0) - { + if (result->rowsCount() > 0) { while (result->next()) accountId = result->getUInt(1); } delete accountQuery; delete result; - if (accountId == 0) - { + if (accountId == 0) { ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::ASCIIToUTF16(args[0])); return; } - } - else - { + } else { accountId = player->GetParentUser()->GetAccountID(); } @@ -1172,21 +1093,19 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit delete userUpdate; - if (player != nullptr) - { + if (player != nullptr) { Game::server->Disconnect(player->GetSystemAddress(), SERVER_DISCON_KICK); } ChatPackets::SendSystemMessage(sysAddr, u"Banned: " + GeneralUtils::ASCIIToUTF16(args[0])); - } - else { + } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /ban "); } } //------------------------------------------------- - if (chatCommand == "buffme" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "buffme" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { auto dest = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); if (dest) { dest->SetHealth(999); @@ -1196,14 +1115,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit dest->SetImagination(999); dest->SetMaxImagination(999.0f); } - EntityManager::Instance()->SerializeEntity(entity); - } + EntityManager::Instance()->SerializeEntity(entity); + } if (chatCommand == "startcelebration" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) { int32_t celebration; - if (!GeneralUtils::TryParse(args[0], celebration)) - { + if (!GeneralUtils::TryParse(args[0], celebration)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid celebration."); return; } @@ -1211,7 +1129,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameMessages::SendStartCelebrationEffect(entity, entity->GetSystemAddress(), celebration); } - if (chatCommand == "buffmed" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "buffmed" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { auto dest = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); if (dest) { dest->SetHealth(9); @@ -1221,10 +1139,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit dest->SetImagination(9); dest->SetMaxImagination(9.0f); } - EntityManager::Instance()->SerializeEntity(entity); - } + EntityManager::Instance()->SerializeEntity(entity); + } - if (chatCommand == "refillstats" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "refillstats" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { auto dest = static_cast(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); if (dest) { @@ -1233,8 +1151,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit dest->SetImagination((int)dest->GetMaxImagination()); } - EntityManager::Instance()->SerializeEntity(entity); - } + EntityManager::Instance()->SerializeEntity(entity); + } if (chatCommand == "lookup" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) { auto query = CDClientDatabase::CreatePreppedStmt( @@ -1245,21 +1163,20 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto tables = query.execQuery(); - while (!tables.eof()) { - std::string message = std::to_string(tables.getIntField(0)) + " - " + tables.getStringField(1); - ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(message, message.size())); - tables.nextRow(); - } - } + while (!tables.eof()) { + std::string message = std::to_string(tables.getIntField(0)) + " - " + tables.getStringField(1); + ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(message, message.size())); + tables.nextRow(); + } + } - if (chatCommand == "spawn" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { - ControllablePhysicsComponent* comp = static_cast(entity->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); - if (!comp) return; + if (chatCommand == "spawn" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { + ControllablePhysicsComponent* comp = static_cast(entity->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); + if (!comp) return; uint32_t lot; - if (!GeneralUtils::TryParse(args[0], lot)) - { + if (!GeneralUtils::TryParse(args[0], lot)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid lot."); return; } @@ -1285,8 +1202,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "giveuscore") && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { int32_t uscore; - if (!GeneralUtils::TryParse(args[0], uscore)) - { + if (!GeneralUtils::TryParse(args[0], uscore)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid uscore."); return; } @@ -1297,8 +1213,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), uscore, eLootSourceType::LOOT_SOURCE_MODERATION); } - if ((chatCommand == "setlevel") && args.size() >= 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if ((chatCommand == "setlevel") && args.size() >= 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { // We may be trying to set a specific players level to a level. If so override the entity with the requested players. std::string requestedPlayerToSetLevelOf = ""; if (args.size() > 1) { @@ -1322,8 +1237,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit uint32_t oldLevel; // first check the level is valid - if (!GeneralUtils::TryParse(args[0], requestedLevel)) - { + if (!GeneralUtils::TryParse(args[0], requestedLevel)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid level."); return; } @@ -1345,7 +1259,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit // handle level up for each level we have passed if we set our level to be higher than the current one. if (oldLevel < requestedLevel) { while (oldLevel < requestedLevel) { - oldLevel+=1; + oldLevel += 1; levelComponent->SetLevel(oldLevel); levelComponent->HandleLevelUp(); } @@ -1354,15 +1268,15 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (requestedPlayerToSetLevelOf != "") { - ChatPackets::SendSystemMessage( - sysAddr, u"Set " + GeneralUtils::ASCIIToUTF16(requestedPlayerToSetLevelOf) + u"'s level to " + GeneralUtils::to_u16string(requestedLevel) + - u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + - u". Relog to see changes."); + ChatPackets::SendSystemMessage( + sysAddr, u"Set " + GeneralUtils::ASCIIToUTF16(requestedPlayerToSetLevelOf) + u"'s level to " + GeneralUtils::to_u16string(requestedLevel) + + u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + + u". Relog to see changes."); } else { - ChatPackets::SendSystemMessage( - sysAddr, u"Set your level to " + GeneralUtils::to_u16string(requestedLevel) + - u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + - u". Relog to see changes."); + ChatPackets::SendSystemMessage( + sysAddr, u"Set your level to " + GeneralUtils::to_u16string(requestedLevel) + + u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + + u". Relog to see changes."); } return; } @@ -1370,7 +1284,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "pos" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { const auto position = entity->GetPosition(); - ChatPackets::SendSystemMessage(sysAddr, u"<" + (GeneralUtils::to_u16string(position.x)) + u", " + (GeneralUtils::to_u16string(position.y)) + u", " + (GeneralUtils::to_u16string(position.z)) + u">"); + ChatPackets::SendSystemMessage(sysAddr, u"<" + (GeneralUtils::to_u16string(position.x)) + u", " + (GeneralUtils::to_u16string(position.y)) + u", " + (GeneralUtils::to_u16string(position.z)) + u">"); std::cout << position.x << ", " << position.y << ", " << position.z << std::endl; } @@ -1378,7 +1292,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "rot" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { const auto rotation = entity->GetRotation(); - ChatPackets::SendSystemMessage(sysAddr, u"<" + (GeneralUtils::to_u16string(rotation.w)) + u", " + (GeneralUtils::to_u16string(rotation.x)) + u", " + (GeneralUtils::to_u16string(rotation.y)) + u", " + (GeneralUtils::to_u16string(rotation.z)) + u">"); + ChatPackets::SendSystemMessage(sysAddr, u"<" + (GeneralUtils::to_u16string(rotation.w)) + u", " + (GeneralUtils::to_u16string(rotation.x)) + u", " + (GeneralUtils::to_u16string(rotation.y)) + u", " + (GeneralUtils::to_u16string(rotation.z)) + u">"); std::cout << rotation.w << ", " << rotation.x << ", " << rotation.y << ", " << rotation.z << std::endl; } @@ -1401,8 +1315,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "freemoney" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) && args.size() == 1) { int32_t money; - if (!GeneralUtils::TryParse(args[0], money)) - { + if (!GeneralUtils::TryParse(args[0], money)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid money."); return; } @@ -1414,8 +1327,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "setcurrency") && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { int32_t money; - if (!GeneralUtils::TryParse(args[0], money)) - { + if (!GeneralUtils::TryParse(args[0], money)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid money."); return; } @@ -1425,54 +1337,46 @@ 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() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "gminvis" && entity->GetParentUser()->GetMaxGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); return; } - if (chatCommand == "gmimmune" && args.size() >= 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "gmimmune" && args.size() >= 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { auto* destroyableComponent = entity->GetComponent(); int32_t state = false; - if (!GeneralUtils::TryParse(args[0], state)) - { + if (!GeneralUtils::TryParse(args[0], state)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid state."); return; } - if (destroyableComponent != nullptr) - { + if (destroyableComponent != nullptr) { destroyableComponent->SetIsGMImmune(state); } return; } - if (chatCommand == "buff" && args.size() >= 2 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { + if (chatCommand == "buff" && args.size() >= 2 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { auto* buffComponent = entity->GetComponent(); int32_t id = 0; int32_t duration = 0; - if (!GeneralUtils::TryParse(args[0], id)) - { + if (!GeneralUtils::TryParse(args[0], id)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid buff id."); return; } - if (!GeneralUtils::TryParse(args[1], duration)) - { + if (!GeneralUtils::TryParse(args[1], duration)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid buff duration."); return; } - if (buffComponent != nullptr) - { + if (buffComponent != nullptr) { buffComponent->ApplyBuff(id, duration, entity->GetObjectID()); } @@ -1485,25 +1389,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit LWOCLONEID cloneId = 0; bool force = false; - if (!GeneralUtils::TryParse(args[0], reqZone)) - { + if (!GeneralUtils::TryParse(args[0], reqZone)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid zone."); return; } - if (args.size() > 1) - { + if (args.size() > 1) { auto index = 1; - if (args[index] == "force") - { + if (args[index] == "force") { index++; force = true; } - if (args.size() > index && !GeneralUtils::TryParse(args[index], cloneId)) - { + if (args.size() > index && !GeneralUtils::TryParse(args[index], cloneId)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone id."); return; } @@ -1534,7 +1434,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); return; - }); + }); } else { std::string msg = "ZoneID not found or allowed: "; msg.append(args[0]); @@ -1542,20 +1442,17 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "createprivate" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 3) - { + if (chatCommand == "createprivate" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 3) { uint32_t zone; - if (!GeneralUtils::TryParse(args[0], zone)) - { + if (!GeneralUtils::TryParse(args[0], zone)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid zone."); return; } uint32_t clone; - if (!GeneralUtils::TryParse(args[1], clone)) - { + if (!GeneralUtils::TryParse(args[1], clone)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone."); return; } @@ -1578,34 +1475,29 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "boost") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { auto* possessorComponent = entity->GetComponent(); - if (possessorComponent == nullptr) - { + if (possessorComponent == nullptr) { return; } auto* vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); - if (vehicle == nullptr) - { + if (vehicle == nullptr) { return; } GameMessages::SendVehicleAddPassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); } - if (chatCommand == "activatespawner" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) - { + if (chatCommand == "activatespawner" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { auto spawners = dZoneManager::Instance()->GetSpawnersByName(args[0]); - for (auto* spawner : spawners) - { + for (auto* spawner : spawners) { spawner->Activate(); } spawners = dZoneManager::Instance()->GetSpawnersInGroup(args[0]); - for (auto* spawner : spawners) - { + for (auto* spawner : spawners) { spawner->Activate(); } } @@ -1636,25 +1528,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "triggerspawner" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) - { + if (chatCommand == "triggerspawner" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { auto spawners = dZoneManager::Instance()->GetSpawnersByName(args[0]); - for (auto* spawner : spawners) - { + for (auto* spawner : spawners) { spawner->Spawn(); } spawners = dZoneManager::Instance()->GetSpawnersInGroup(args[0]); - for (auto* spawner : spawners) - { + for (auto* spawner : spawners) { spawner->Spawn(); } } - if (chatCommand == "reforge" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 2) - { + if (chatCommand == "reforge" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 2) { LOT baseItem; LOT reforgedItem; @@ -1665,14 +1553,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (inventoryComponent == nullptr) return; - std::vector data {}; + std::vector data{}; data.push_back(new LDFData(u"reforgedLOT", reforgedItem)); inventoryComponent->AddItem(baseItem, 1, eLootSourceType::LOOT_SOURCE_MODERATION, eInventoryType::INVALID, data); } - if (chatCommand == "crash" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR) - { + if (chatCommand == "crash" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR) { ChatPackets::SendSystemMessage(sysAddr, u"Crashing..."); int* badPtr = nullptr; @@ -1681,8 +1568,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "config-set" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 2) - { + if (chatCommand == "config-set" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 2) { GameConfig::SetValue(args[0], args[1]); ChatPackets::SendSystemMessage( @@ -1690,28 +1576,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ); } - if (chatCommand == "config-get" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) - { + if (chatCommand == "config-get" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { const auto& value = GameConfig::GetValue(args[0]); - if (value.empty()) - { + if (value.empty()) { ChatPackets::SendSystemMessage(sysAddr, u"No value found for " + GeneralUtils::ASCIIToUTF16(args[0])); - } - else - { + } else { ChatPackets::SendSystemMessage(sysAddr, u"Value for " + GeneralUtils::ASCIIToUTF16(args[0]) + u": " + GeneralUtils::ASCIIToUTF16(value)); } } - if (chatCommand == "metrics" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) - { - for (const auto variable : Metrics::GetAllMetrics()) - { + if (chatCommand == "metrics" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + for (const auto variable : Metrics::GetAllMetrics()) { auto* metric = Metrics::GetMetric(variable); - if (metric == nullptr) - { + if (metric == nullptr) { continue; } @@ -1726,13 +1605,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage( sysAddr, - u"Peak RSS: " + GeneralUtils::to_u16string((float) ((double) Metrics::GetPeakRSS() / 1.024e6)) + + u"Peak RSS: " + GeneralUtils::to_u16string((float)((double)Metrics::GetPeakRSS() / 1.024e6)) + u"MB" ); ChatPackets::SendSystemMessage( sysAddr, - u"Current RSS: " + GeneralUtils::to_u16string((float) ((double) Metrics::GetCurrentRSS() / 1.024e6)) + + u"Current RSS: " + GeneralUtils::to_u16string((float)((double)Metrics::GetCurrentRSS() / 1.024e6)) + u"MB" ); @@ -1776,13 +1655,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit + u" times. It ran " + GeneralUtils::to_u16string(totalRuns) + u" times. Averaging out at " - + GeneralUtils::to_u16string((float) totalRuns / loops); + + GeneralUtils::to_u16string((float)totalRuns / loops); ChatPackets::SendSystemMessage(sysAddr, message); } - if (chatCommand == "inspect" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) - { + if (chatCommand == "inspect" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { Entity* closest = nullptr; int32_t component; @@ -1791,8 +1669,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit bool isLDF = false; - if (!GeneralUtils::TryParse(args[0], component)) - { + if (!GeneralUtils::TryParse(args[0], component)) { component = -1; ldf = GeneralUtils::ASCIIToUTF16(args[0]); @@ -1806,20 +1683,16 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit const auto candidates = EntityManager::Instance()->GetEntitiesByComponent(component); - for (auto* candidate : candidates) - { - if (candidate->GetLOT() == 1 || candidate->GetLOT() == 8092) - { + for (auto* candidate : candidates) { + if (candidate->GetLOT() == 1 || candidate->GetLOT() == 8092) { continue; } - if (isLDF && !candidate->HasVar(ldf)) - { + if (isLDF && !candidate->HasVar(ldf)) { continue; } - if (closest == nullptr) - { + if (closest == nullptr) { closest = candidate; closestDistance = NiPoint3::Distance(candidate->GetPosition(), reference); @@ -1829,16 +1702,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit const auto distance = NiPoint3::Distance(candidate->GetPosition(), reference); - if (distance < closestDistance) - { + if (distance < closestDistance) { closest = candidate; closestDistance = distance; } } - if (closest == nullptr) - { + if (closest == nullptr) { return; } @@ -1854,8 +1725,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(header.str())); - for (const auto& pair : closest->GetComponents()) - { + for (const auto& pair : closest->GetComponents()) { auto id = pair.first; std::stringstream stream; @@ -1865,61 +1735,45 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(stream.str())); } - if (args.size() >= 2) - { - if (args[1] == "-m" && args.size() >= 3) - { + if (args.size() >= 2) { + if (args[1] == "-m" && args.size() >= 3) { auto* movingPlatformComponent = closest->GetComponent(); int32_t value = 0; - if (movingPlatformComponent == nullptr || !GeneralUtils::TryParse(args[2], value)) - { + if (movingPlatformComponent == nullptr || !GeneralUtils::TryParse(args[2], value)) { return; } movingPlatformComponent->SetSerialized(true); - if (value == -1) - { + if (value == -1) { movingPlatformComponent->StopPathing(); - } - else - { + } else { movingPlatformComponent->GotoWaypoint(value); } EntityManager::Instance()->SerializeEntity(closest); - } - else if (args[1] == "-a" && args.size() >= 3) - { + } else if (args[1] == "-a" && args.size() >= 3) { GameMessages::SendPlayAnimation(closest, GeneralUtils::ASCIIToUTF16(args[2])); - } - else if (args[1] == "-s") - { - for (auto* entry : closest->GetSettings()) - { + } else if (args[1] == "-s") { + for (auto* entry : closest->GetSettings()) { ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(entry->GetString())); } ChatPackets::SendSystemMessage(sysAddr, u"------"); ChatPackets::SendSystemMessage(sysAddr, u"Spawner ID: " + GeneralUtils::to_u16string(closest->GetSpawnerID())); - } - else if (args[1] == "-p") - { + } else if (args[1] == "-p") { const auto postion = closest->GetPosition(); ChatPackets::SendSystemMessage( sysAddr, GeneralUtils::ASCIIToUTF16("< " + std::to_string(postion.x) + ", " + std::to_string(postion.y) + ", " + std::to_string(postion.z) + " >") ); - } - else if (args[1] == "-f") - { + } else if (args[1] == "-f") { auto* destuctable = closest->GetComponent(); - if (destuctable == nullptr) - { + if (destuctable == nullptr) { ChatPackets::SendSystemMessage(sysAddr, u"No destroyable component on this entity!"); return; } @@ -1927,44 +1781,36 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Smashable: " + (GeneralUtils::to_u16string(destuctable->GetIsSmashable()))); ChatPackets::SendSystemMessage(sysAddr, u"Friendly factions:"); - for (const auto entry : destuctable->GetFactionIDs()) - { + for (const auto entry : destuctable->GetFactionIDs()) { ChatPackets::SendSystemMessage(sysAddr, (GeneralUtils::to_u16string(entry))); } ChatPackets::SendSystemMessage(sysAddr, u"Enemy factions:"); - for (const auto entry : destuctable->GetEnemyFactionsIDs()) - { + for (const auto entry : destuctable->GetEnemyFactionsIDs()) { ChatPackets::SendSystemMessage(sysAddr, (GeneralUtils::to_u16string(entry))); } - if (args.size() >= 3) - { + if (args.size() >= 3) { int32_t faction; - if (!GeneralUtils::TryParse(args[2], faction)) - { + if (!GeneralUtils::TryParse(args[2], faction)) { return; } destuctable->SetFaction(-1); destuctable->AddFaction(faction, true); } - } - else if (args[1] == "-t") - { + } else if (args[1] == "-t") { auto* phantomPhysicsComponent = closest->GetComponent(); - if (phantomPhysicsComponent != nullptr) - { + if (phantomPhysicsComponent != nullptr) { ChatPackets::SendSystemMessage(sysAddr, u"Type: " + (GeneralUtils::to_u16string(phantomPhysicsComponent->GetEffectType()))); const auto dir = phantomPhysicsComponent->GetDirection(); - ChatPackets::SendSystemMessage(sysAddr, u"Direction: <" + (GeneralUtils::to_u16string(dir.x)) + u", " + (GeneralUtils::to_u16string(dir.y)) + u", "+ (GeneralUtils::to_u16string(dir.z)) + u">"); + ChatPackets::SendSystemMessage(sysAddr, u"Direction: <" + (GeneralUtils::to_u16string(dir.x)) + u", " + (GeneralUtils::to_u16string(dir.y)) + u", " + (GeneralUtils::to_u16string(dir.z)) + u">"); ChatPackets::SendSystemMessage(sysAddr, u"Multiplier: " + (GeneralUtils::to_u16string(phantomPhysicsComponent->GetDirectionalMultiplier()))); ChatPackets::SendSystemMessage(sysAddr, u"Active: " + (GeneralUtils::to_u16string(phantomPhysicsComponent->GetPhysicsEffectActive()))); } - if (closest->GetTrigger() != nullptr) - { + if (closest->GetTrigger() != nullptr) { ChatPackets::SendSystemMessage(sysAddr, u"Trigger: " + (GeneralUtils::to_u16string(closest->GetTrigger()->id))); } } @@ -1974,7 +1820,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit bool SlashCommandHandler::CheckIfAccessibleZone(const unsigned int zoneID) { //We're gonna go ahead and presume we've got the db loaded already: - CDZoneTableTable * zoneTable = CDClientManager::Instance()->GetTable("ZoneTable"); + CDZoneTableTable* zoneTable = CDClientManager::Instance()->GetTable("ZoneTable"); const CDZoneTable* zone = zoneTable->Query(zoneID); if (zone != nullptr) { std::string zonePath = "./res/maps/" + zone->zoneName; diff --git a/dGame/dUtilities/SlashCommandHandler.h b/dGame/dUtilities/SlashCommandHandler.h index 32b267ef..9ef09a2f 100644 --- a/dGame/dUtilities/SlashCommandHandler.h +++ b/dGame/dUtilities/SlashCommandHandler.h @@ -12,10 +12,10 @@ class Entity; namespace SlashCommandHandler { - void HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr); - bool CheckIfAccessibleZone(const unsigned int zoneID); + void HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr); + bool CheckIfAccessibleZone(const unsigned int zoneID); - void SendAnnouncement(const std::string& title, const std::string& message); + void SendAnnouncement(const std::string& title, const std::string& message); }; #endif // SLASHCOMMANDHANDLER_H diff --git a/dGame/dUtilities/VanityUtilities.cpp b/dGame/dUtilities/VanityUtilities.cpp index 1b85077b..733d94c4 100644 --- a/dGame/dUtilities/VanityUtilities.cpp +++ b/dGame/dUtilities/VanityUtilities.cpp @@ -20,520 +20,513 @@ std::vector VanityUtilities::m_NPCs = {}; std::vector VanityUtilities::m_Parties = {}; std::vector VanityUtilities::m_PartyPhrases = {}; -void VanityUtilities::SpawnVanity() -{ - if (Game::config->GetValue("disable_vanity") == "1") { - return; - } +void VanityUtilities::SpawnVanity() { + if (Game::config->GetValue("disable_vanity") == "1") { + return; + } - const uint32_t zoneID = Game::server->GetZoneID(); + const uint32_t zoneID = Game::server->GetZoneID(); - ParseXML("./vanity/NPC.xml"); + ParseXML("./vanity/NPC.xml"); - // Loop through all parties - for (const auto& party : m_Parties) { - const auto chance = party.m_Chance; - const auto zone = party.m_Zone; + // 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; - } + if (zone != Game::server->GetZoneID()) { + continue; + } - float rate = GeneralUtils::GenerateRandomNumber(0, 1); - if (chance < rate) { - 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 = {}; + // Copy m_NPCs into a new vector + std::vector npcList = m_NPCs; + std::vector taken = {}; - Game::logger->Log("VanityUtilities", "Spawning party with %i locations", party.m_Locations.size()); + Game::logger->Log("VanityUtilities", "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; - } + // 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); + // 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); - } + while (std::find(taken.begin(), taken.end(), npcIndex) != taken.end()) { + npcIndex = GeneralUtils::GenerateRandomNumber(0, npcList.size() - 1); + } - const auto& npc = npcList[npcIndex]; + const auto& npc = npcList[npcIndex]; - taken.push_back(npcIndex); + taken.push_back(npcIndex); - // Spawn the NPC - std::vector data = { 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 + std::vector data = { 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 - auto* npcEntity = SpawnNPC(npc.m_LOT, npc.m_Name, location.m_Position, location.m_Rotation, npc.m_Equipment, data); + // Spawn the NPC + auto* npcEntity = SpawnNPC(npc.m_LOT, npc.m_Name, location.m_Position, location.m_Rotation, npc.m_Equipment, data); - npcEntity->SetVar>(u"chats", m_PartyPhrases); + npcEntity->SetVar>(u"chats", m_PartyPhrases); - SetupNPCTalk(npcEntity); - } + SetupNPCTalk(npcEntity); + } - return; - } + return; + } - // Loop through all NPCs - for (const auto& pair : m_NPCs) { - if (pair.m_Locations.find(Game::server->GetZoneID()) == pair.m_Locations.end()) - continue; + // Loop through all NPCs + for (const auto& pair : m_NPCs) { + if (pair.m_Locations.find(Game::server->GetZoneID()) == pair.m_Locations.end()) + continue; - const std::vector& locations = pair.m_Locations.at(Game::server->GetZoneID()); + const std::vector& locations = pair.m_Locations.at(Game::server->GetZoneID()); - // Pick a random location - const auto& location = locations[GeneralUtils::GenerateRandomNumber( - static_cast(0), static_cast(locations.size() - 1))]; + // 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; - } + float rate = GeneralUtils::GenerateRandomNumber(0, 1); + if (location.m_Chance < rate) { + continue; + } - std::vector data = { new LDFData>( - u"syncLDF", { u"custom_script_client" }), - new LDFData(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") }; + std::vector data = { 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 - auto* npc = SpawnNPC(pair.m_LOT, pair.m_Name, location.m_Position, location.m_Rotation, pair.m_Equipment, data); + // Spawn the NPC + auto* npc = SpawnNPC(pair.m_LOT, pair.m_Name, location.m_Position, location.m_Rotation, pair.m_Equipment, data); - npc->SetVar>(u"chats", pair.m_Phrases); + npc->SetVar>(u"chats", pair.m_Phrases); - auto* scriptComponent = npc->GetComponent(); + auto* scriptComponent = npc->GetComponent(); - if (scriptComponent != nullptr) { - scriptComponent->SetScript(pair.m_Script); - scriptComponent->SetSerialized(false); + if (scriptComponent != nullptr) { + scriptComponent->SetScript(pair.m_Script); + scriptComponent->SetSerialized(false); - for (const auto& pair : pair.m_Flags) { - npc->SetVar(GeneralUtils::ASCIIToUTF16(pair.first), pair.second); - } - } + for (const auto& pair : pair.m_Flags) { + npc->SetVar(GeneralUtils::ASCIIToUTF16(pair.first), pair.second); + } + } - SetupNPCTalk(npc); - } + SetupNPCTalk(npc); + } - if (zoneID == 1200) { - { - EntityInfo info; - info.lot = 8139; - info.pos = { 259.5f, 246.4f, -705.2f }; - info.rot = { 0.0f, 0.0f, 1.0f, 0.0f }; - info.spawnerID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); + if (zoneID == 1200) { + { + EntityInfo info; + info.lot = 8139; + info.pos = { 259.5f, 246.4f, -705.2f }; + info.rot = { 0.0f, 0.0f, 1.0f, 0.0f }; + info.spawnerID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); - info.settings = { new LDFData(u"hasCustomText", true), - new LDFData(u"customText", ParseMarkdown("./vanity/TESTAMENT.md")) }; + info.settings = { new LDFData(u"hasCustomText", true), + new LDFData(u"customText", ParseMarkdown("./vanity/TESTAMENT.md")) }; - auto* entity = EntityManager::Instance()->CreateEntity(info); + auto* entity = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(entity); - } - } + EntityManager::Instance()->ConstructEntity(entity); + } + } } Entity* VanityUtilities::SpawnNPC(LOT lot, const std::string& name, const NiPoint3& position, - const NiQuaternion& rotation, const std::vector& inventory, const std::vector& ldf) -{ - EntityInfo info; - info.lot = lot; - info.pos = position; - info.rot = rotation; - info.spawnerID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); - info.settings = ldf; + const NiQuaternion& rotation, const std::vector& inventory, const std::vector& ldf) { + EntityInfo info; + info.lot = lot; + info.pos = position; + info.rot = rotation; + info.spawnerID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); + info.settings = ldf; - auto* entity = EntityManager::Instance()->CreateEntity(info); - entity->SetVar(u"npcName", name); + auto* entity = EntityManager::Instance()->CreateEntity(info); + entity->SetVar(u"npcName", name); - auto* inventoryComponent = entity->GetComponent(); + auto* inventoryComponent = entity->GetComponent(); - if (inventoryComponent != nullptr) { - inventoryComponent->SetNPCItems(inventory); - } + if (inventoryComponent != nullptr) { + inventoryComponent->SetNPCItems(inventory); + } - auto* destroyableComponent = entity->GetComponent(); + auto* destroyableComponent = entity->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetIsGMImmune(true); - destroyableComponent->SetMaxHealth(0); - destroyableComponent->SetHealth(0); - } + if (destroyableComponent != nullptr) { + destroyableComponent->SetIsGMImmune(true); + destroyableComponent->SetMaxHealth(0); + destroyableComponent->SetHealth(0); + } - EntityManager::Instance()->ConstructEntity(entity); + EntityManager::Instance()->ConstructEntity(entity); - return entity; + return entity; } -void VanityUtilities::ParseXML(const std::string& file) -{ - // Read the entire file - std::ifstream xmlFile(file); - std::string xml((std::istreambuf_iterator(xmlFile)), std::istreambuf_iterator()); +void VanityUtilities::ParseXML(const std::string& file) { + // Read the entire file + std::ifstream xmlFile(file); + std::string xml((std::istreambuf_iterator(xmlFile)), std::istreambuf_iterator()); - // Parse the XML - tinyxml2::XMLDocument doc; - doc.Parse(xml.c_str(), xml.size()); + // Parse the XML + tinyxml2::XMLDocument doc; + doc.Parse(xml.c_str(), xml.size()); - // Read the NPCs - auto* npcs = doc.FirstChildElement("npcs"); + // Read the NPCs + auto* npcs = doc.FirstChildElement("npcs"); - if (npcs == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPCs"); - return; - } + if (npcs == nullptr) { + Game::logger->Log("VanityUtilities", "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; + 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("zone") != nullptr) { + zone = std::stoul(party->Attribute("zone")); + } - if (party->Attribute("chance") != nullptr) { - chance = std::stof(party->Attribute("chance")); - } + if (party->Attribute("chance") != nullptr) { + chance = std::stof(party->Attribute("chance")); + } - VanityParty partyInfo; - partyInfo.m_Zone = zone; - partyInfo.m_Chance = chance; + VanityParty partyInfo; + partyInfo.m_Zone = zone; + partyInfo.m_Chance = chance; - auto* locations = party->FirstChildElement("locations"); + auto* locations = party->FirstChildElement("locations"); - if (locations == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party locations"); - continue; - } + if (locations == nullptr) { + Game::logger->Log("VanityUtilities", "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"); + 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) { - Game::logger->Log("VanityUtilities", "Failed to parse party location data"); - continue; - } + if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr + || rz == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse party location data"); + 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; + 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); - } + partyInfo.m_Locations.push_back(locationData); + } - m_Parties.push_back(partyInfo); - } + m_Parties.push_back(partyInfo); + } - auto* partyPhrases = npcs->FirstChildElement("partyphrases"); + auto* partyPhrases = npcs->FirstChildElement("partyphrases"); - if (partyPhrases == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party phrases"); - return; - } + if (partyPhrases == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse party phrases"); + return; + } - for (auto* phrase = partyPhrases->FirstChildElement("phrase"); phrase != nullptr; - phrase = phrase->NextSiblingElement("phrase")) { - // Get the phrase - auto* text = phrase->GetText(); + for (auto* phrase = partyPhrases->FirstChildElement("phrase"); phrase != nullptr; + phrase = phrase->NextSiblingElement("phrase")) { + // Get the phrase + auto* text = phrase->GetText(); - if (text == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse party phrase"); - continue; - } + if (text == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse party phrase"); + continue; + } - m_PartyPhrases.push_back(text); - } + m_PartyPhrases.push_back(text); + } - for (auto* npc = npcs->FirstChildElement("npc"); npc != nullptr; npc = npc->NextSiblingElement("npc")) { - // Get the NPC name - auto* name = npc->Attribute("name"); + for (auto* npc = npcs->FirstChildElement("npc"); npc != nullptr; npc = npc->NextSiblingElement("npc")) { + // Get the NPC name + auto* name = npc->Attribute("name"); - if (name == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC name"); - continue; - } + if (name == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC name"); + continue; + } - // Get the NPC lot - auto* lot = npc->Attribute("lot"); + // Get the NPC lot + auto* lot = npc->Attribute("lot"); - if (lot == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC lot"); - continue; - } + if (lot == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC lot"); + continue; + } - // Get the equipment - auto* equipment = npc->FirstChildElement("equipment"); + // Get the equipment + auto* equipment = npc->FirstChildElement("equipment"); - if (equipment == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC equipment"); - continue; - } + if (equipment == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC equipment"); + continue; + } - auto* text = equipment->GetText(); + auto* text = equipment->GetText(); - std::vector inventory; + std::vector inventory; - if (text != nullptr) { - std::string equipmentString(text); + if (text != nullptr) { + std::string equipmentString(text); - std::vector splitEquipment = GeneralUtils::SplitString(equipmentString, ','); + std::vector splitEquipment = GeneralUtils::SplitString(equipmentString, ','); - for (auto& item : splitEquipment) { - inventory.push_back(std::stoi(item)); - } - } + for (auto& item : splitEquipment) { + inventory.push_back(std::stoi(item)); + } + } - // Get the phrases - auto* phrases = npc->FirstChildElement("phrases"); + // Get the phrases + auto* phrases = npc->FirstChildElement("phrases"); - if (phrases == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC phrases"); - continue; - } + if (phrases == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC phrases"); + continue; + } - std::vector phraseList; + std::vector phraseList; - for (auto* phrase = phrases->FirstChildElement("phrase"); phrase != nullptr; - phrase = phrase->NextSiblingElement("phrase")) { - // Get the phrase - auto* text = phrase->GetText(); + for (auto* phrase = phrases->FirstChildElement("phrase"); phrase != nullptr; + phrase = phrase->NextSiblingElement("phrase")) { + // Get the phrase + auto* text = phrase->GetText(); - if (text == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC phrase"); - continue; - } + if (text == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC phrase"); + continue; + } - phraseList.push_back(text); - } + phraseList.push_back(text); + } - // Get the script - auto* scriptElement = npc->FirstChildElement("script"); + // Get the script + auto* scriptElement = npc->FirstChildElement("script"); - std::string scriptName; + std::string scriptName; - if (scriptElement != nullptr) { - auto* scriptNameAttribute = scriptElement->Attribute("name"); + if (scriptElement != nullptr) { + auto* scriptNameAttribute = scriptElement->Attribute("name"); - if (scriptNameAttribute == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC script name"); - continue; - } + if (scriptNameAttribute == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC script name"); + continue; + } - scriptName = scriptNameAttribute; - } + scriptName = scriptNameAttribute; + } - VanityNPC npcData; - npcData.m_Name = name; - npcData.m_LOT = std::stoi(lot); - npcData.m_Equipment = inventory; - npcData.m_Phrases = phraseList; - npcData.m_Script = scriptName; + VanityNPC npcData; + npcData.m_Name = name; + npcData.m_LOT = std::stoi(lot); + npcData.m_Equipment = inventory; + npcData.m_Phrases = phraseList; + npcData.m_Script = scriptName; - // Get flags - auto* flags = npc->FirstChildElement("flags"); + // 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 (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) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC flag name"); - continue; - } + if (name == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC flag name"); + continue; + } - // Get the flag value - auto* value = flag->Attribute("value"); + // Get the flag value + auto* value = flag->Attribute("value"); - if (value == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC flag value"); - continue; - } + if (value == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC flag value"); + continue; + } - npcData.m_Flags[name] = std::stoi(value); - } - } + 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"); + // 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) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC zone ID"); - continue; - } + if (zoneID == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC zone ID"); + continue; + } - // Get the locations - auto* locations = zone->FirstChildElement("locations"); + // Get the locations + auto* locations = zone->FirstChildElement("locations"); - if (locations == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC locations"); - continue; - } + if (locations == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC 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"); + 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) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC location data"); - continue; - } + if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr + || rz == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC location data"); + 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; + 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; - if (location->Attribute("chance") != nullptr) { - locationData.m_Chance = std::stof(location->Attribute("chance")); - } + if (location->Attribute("chance") != nullptr) { + locationData.m_Chance = std::stof(location->Attribute("chance")); + } - const auto& it = npcData.m_Locations.find(std::stoi(zoneID)); + const auto& it = npcData.m_Locations.find(std::stoi(zoneID)); - if (it != npcData.m_Locations.end()) { - it->second.push_back(locationData); - } else { - std::vector locations; - locations.push_back(locationData); - npcData.m_Locations.insert(std::make_pair(std::stoi(zoneID), locations)); - } - } - } + if (it != npcData.m_Locations.end()) { + it->second.push_back(locationData); + } else { + std::vector locations; + locations.push_back(locationData); + npcData.m_Locations.insert(std::make_pair(std::stoi(zoneID), locations)); + } + } + } - m_NPCs.push_back(npcData); - } + 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]; - } - } +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]; + } + } - return nullptr; + return nullptr; } -std::string VanityUtilities::ParseMarkdown(const std::string& file) -{ - // This function will read the file and return the content formatted as ASCII text. +std::string VanityUtilities::ParseMarkdown(const std::string& file) { + // This function will read the file and return the content formatted as ASCII text. - // Read the file into a string - std::ifstream t(file); + // Read the file into a string + std::ifstream t(file); - // If the file does not exist, return an empty string. - if (!t.good()) { - return ""; - } + // If the file does not exist, return an empty string. + if (!t.good()) { + return ""; + } - std::stringstream buffer; - buffer << t.rdbuf(); - std::string fileContents = buffer.str(); + std::stringstream buffer; + buffer << t.rdbuf(); + std::string fileContents = buffer.str(); - // 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; - while (std::getline(ss, line)) { + // 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; + while (std::getline(ss, line)) { #define TOSTRING(x) #x #define STRINGIFY(x) TOSTRING(x) - // Replace "__TIMESTAMP__" with the __TIMESTAMP__ - GeneralUtils::ReplaceInString(line, "__TIMESTAMP__", __TIMESTAMP__); - // Replace "__VERSION__" wit'h the PROJECT_VERSION - GeneralUtils::ReplaceInString(line, "__VERSION__", STRINGIFY(PROJECT_VERSION)); - // Replace "__SOURCE__" with SOURCE - GeneralUtils::ReplaceInString(line, "__SOURCE__", Game::config->GetValue("source")); - // Replace "__LICENSE__" with LICENSE - GeneralUtils::ReplaceInString(line, "__LICENSE__", STRINGIFY(LICENSE)); + // Replace "__TIMESTAMP__" with the __TIMESTAMP__ + GeneralUtils::ReplaceInString(line, "__TIMESTAMP__", __TIMESTAMP__); + // Replace "__VERSION__" wit'h the PROJECT_VERSION + GeneralUtils::ReplaceInString(line, "__VERSION__", STRINGIFY(PROJECT_VERSION)); + // Replace "__SOURCE__" with SOURCE + GeneralUtils::ReplaceInString(line, "__SOURCE__", Game::config->GetValue("source")); + // Replace "__LICENSE__" with LICENSE + GeneralUtils::ReplaceInString(line, "__LICENSE__", STRINGIFY(LICENSE)); - if (line.find("##") != std::string::npos) { - // Add "<font size='18' color='#000000'>" before the header - output << ""; - // Add the header without the markdown syntax - output << line.substr(3); + if (line.find("##") != std::string::npos) { + // Add "<font size='18' color='#000000'>" before the header + output << ""; + // Add the header without the markdown syntax + output << line.substr(3); - output << ""; - } else if (line.find("#") != std::string::npos) { - // Add "<font size='18' color='#000000'>" before the header - output << ""; - // Add the header without the markdown syntax - output << line.substr(2); + output << ""; + } else if (line.find("#") != std::string::npos) { + // Add "<font size='18' color='#000000'>" before the header + output << ""; + // Add the header without the markdown syntax + output << line.substr(2); - output << ""; - } else { - output << line; - } + output << ""; + } else { + output << line; + } - output << "\n"; - } + output << "\n"; + } - return output.str(); + return output.str(); } -void VanityUtilities::SetupNPCTalk(Entity* npc) -{ - npc->AddCallbackTimer(15.0f, [npc]() { NPCTalk(npc); }); +void VanityUtilities::SetupNPCTalk(Entity* npc) { + npc->AddCallbackTimer(15.0f, [npc]() { NPCTalk(npc); }); - npc->SetProximityRadius(20.0f, "talk"); + npc->SetProximityRadius(20.0f, "talk"); } -void VanityUtilities::NPCTalk(Entity* npc) -{ - auto* proximityMonitorComponent = npc->GetComponent(); +void VanityUtilities::NPCTalk(Entity* npc) { + auto* proximityMonitorComponent = npc->GetComponent(); - if (!proximityMonitorComponent->GetProximityObjects("talk").empty()) { - const auto& chats = npc->GetVar>(u"chats"); + if (!proximityMonitorComponent->GetProximityObjects("talk").empty()) { + const auto& chats = npc->GetVar>(u"chats"); - if (chats.empty()) { - return; - } + if (chats.empty()) { + return; + } - const auto& selected - = chats[GeneralUtils::GenerateRandomNumber(0, static_cast(chats.size() - 1))]; + const auto& selected + = chats[GeneralUtils::GenerateRandomNumber(0, static_cast(chats.size() - 1))]; - GameMessages::SendNotifyClientZoneObject( - npc->GetObjectID(), u"sendToclient_bubble", 0, 0, npc->GetObjectID(), selected, UNASSIGNED_SYSTEM_ADDRESS); - } + GameMessages::SendNotifyClientZoneObject( + npc->GetObjectID(), u"sendToclient_bubble", 0, 0, npc->GetObjectID(), selected, UNASSIGNED_SYSTEM_ADDRESS); + } - EntityManager::Instance()->SerializeEntity(npc); + EntityManager::Instance()->SerializeEntity(npc); - const float nextTime = GeneralUtils::GenerateRandomNumber(15, 60); + const float nextTime = GeneralUtils::GenerateRandomNumber(15, 60); - npc->AddCallbackTimer(nextTime, [npc]() { NPCTalk(npc); }); + npc->AddCallbackTimer(nextTime, [npc]() { NPCTalk(npc); }); } diff --git a/dGame/dUtilities/VanityUtilities.h b/dGame/dUtilities/VanityUtilities.h index b8462421..2f1886ed 100644 --- a/dGame/dUtilities/VanityUtilities.h +++ b/dGame/dUtilities/VanityUtilities.h @@ -6,61 +6,61 @@ struct VanityNPCLocation { - float m_Chance = 1.0f; - NiPoint3 m_Position; - NiQuaternion m_Rotation; + float m_Chance = 1.0f; + NiPoint3 m_Position; + NiQuaternion m_Rotation; }; struct VanityNPC { - std::string m_Name; - LOT m_LOT; - std::vector m_Equipment; - std::vector m_Phrases; - std::string m_Script; - std::map m_Flags; - std::map> m_Locations; + std::string m_Name; + LOT m_LOT; + std::vector m_Equipment; + std::vector m_Phrases; + std::string m_Script; + std::map m_Flags; + std::map> m_Locations; }; struct VanityParty { - uint32_t m_Zone; - float m_Chance = 1.0f; - std::vector m_Locations; + uint32_t m_Zone; + float m_Chance = 1.0f; + std::vector m_Locations; }; class VanityUtilities { public: - static void SpawnVanity(); + 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* SpawnNPC( + LOT lot, + const std::string& name, + const NiPoint3& position, + const NiQuaternion& rotation, + const std::vector& inventory, + const std::vector& ldf + ); - static std::string ParseMarkdown( - const std::string& file - ); + static std::string ParseMarkdown( + const std::string& file + ); - static void ParseXML( - const std::string& file - ); + static void ParseXML( + const std::string& file + ); - static VanityNPC* GetNPC(const std::string& name); + static VanityNPC* GetNPC(const std::string& name); private: - static void SetupNPCTalk(Entity* npc); + static void SetupNPCTalk(Entity* npc); - static void NPCTalk(Entity* npc); + static void NPCTalk(Entity* npc); - static std::vector m_NPCs; + static std::vector m_NPCs; - static std::vector m_Parties; + static std::vector m_Parties; - static std::vector m_PartyPhrases; + static std::vector m_PartyPhrases; }; diff --git a/dGame/dUtilities/dLocale.cpp b/dGame/dUtilities/dLocale.cpp index 5f918fec..65ef3a58 100644 --- a/dGame/dUtilities/dLocale.cpp +++ b/dGame/dUtilities/dLocale.cpp @@ -11,71 +11,71 @@ #include "dConfig.h" dLocale::dLocale() { - if (Game::config->GetValue("locale_enabled") != "1") { - return; - } + if (Game::config->GetValue("locale_enabled") != "1") { + return; + } - std::ifstream file(m_LocalePath); + std::ifstream file(m_LocalePath); - if (!file.good()) { - return; - } + if (!file.good()) { + return; + } - std::stringstream data; - data << file.rdbuf(); + std::stringstream data; + data << file.rdbuf(); - if (data.str().empty()) { - return; - } + if (data.str().empty()) { + return; + } - auto* doc = new tinyxml2::XMLDocument(); + auto* doc = new tinyxml2::XMLDocument(); - if (doc == nullptr) { - return; - } + if (doc == nullptr) { + return; + } - if (doc->Parse(data.str().c_str(), data.str().size()) != 0) { - return; - } + if (doc->Parse(data.str().c_str(), data.str().size()) != 0) { + return; + } - std::hash hash; + std::hash hash; - auto* localization = doc->FirstChildElement("localization"); - auto* phrases = localization->FirstChildElement("phrases"); + auto* localization = doc->FirstChildElement("localization"); + auto* phrases = localization->FirstChildElement("phrases"); - auto* phrase = phrases->FirstChildElement("phrase"); + auto* phrase = phrases->FirstChildElement("phrase"); - while (phrase != nullptr) { - // Add the phrase hash to the vector - m_Phrases.push_back(hash(phrase->Attribute("id"))); - phrase = phrase->NextSiblingElement("phrase"); - } + while (phrase != nullptr) { + // Add the phrase hash to the vector + m_Phrases.push_back(hash(phrase->Attribute("id"))); + phrase = phrase->NextSiblingElement("phrase"); + } - file.close(); + file.close(); - delete doc; + delete doc; } dLocale::~dLocale() = default; std::string dLocale::GetTemplate(const std::string& phraseID) { - return "%[" + phraseID + "]"; + return "%[" + phraseID + "]"; } bool dLocale::HasPhrase(const std::string& phraseID) { - if (Game::config->GetValue("locale_enabled") != "1") { - return true; - } + if (Game::config->GetValue("locale_enabled") != "1") { + return true; + } - // Compute the hash and see if it's in the vector - std::hash hash; - std::size_t hashValue = hash(phraseID); - return std::find(m_Phrases.begin(), m_Phrases.end(), hashValue) != m_Phrases.end(); + // Compute the hash and see if it's in the vector + std::hash hash; + std::size_t hashValue = hash(phraseID); + return std::find(m_Phrases.begin(), m_Phrases.end(), hashValue) != m_Phrases.end(); } /*std::string dLocale::GetPhrase(const std::string& phraseID) { - if (m_Phrases.find(phraseID) == m_Phrases.end()) { - return ""; - } - return m_Phrases[phraseID]; -}*/ \ No newline at end of file + if (m_Phrases.find(phraseID) == m_Phrases.end()) { + return ""; + } + return m_Phrases[phraseID]; +}*/ diff --git a/dGame/dUtilities/dLocale.h b/dGame/dUtilities/dLocale.h index 398f903b..db5d2a4f 100644 --- a/dGame/dUtilities/dLocale.h +++ b/dGame/dUtilities/dLocale.h @@ -6,14 +6,14 @@ class dLocale { public: - dLocale(); - ~dLocale(); - static std::string GetTemplate(const std::string& phraseID); - bool HasPhrase(const std::string& phraseID); - //std::string GetPhrase(const std::string& phraseID); + dLocale(); + ~dLocale(); + static std::string GetTemplate(const std::string& phraseID); + bool HasPhrase(const std::string& phraseID); + //std::string GetPhrase(const std::string& phraseID); private: - std::string m_LocalePath = "./locale/locale.xml"; - std::string m_Locale = "en_US"; // TODO: add to config - std::vector m_Phrases; -}; \ No newline at end of file + std::string m_LocalePath = "./locale/locale.xml"; + std::string m_Locale = "en_US"; // TODO: add to config + std::vector m_Phrases; +}; diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index 2c4c3287..0c605ed6 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -25,65 +25,64 @@ InstanceManager::~InstanceManager() { } } -Instance * InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneID) { - mLogger->Log("InstanceManager", "Searching for an instance for mapID %i/%i", mapID, cloneID); +Instance* InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneID) { + mLogger->Log("InstanceManager", "Searching for an instance for mapID %i/%i", mapID, cloneID); Instance* instance = FindInstance(mapID, isFriendTransfer, cloneID); if (instance) return instance; - //TODO: Update this so that the IP is read from a configuration file instead + //TODO: Update this so that the IP is read from a configuration file instead - int softCap = 8; - int maxPlayers = 12; + int softCap = 8; + int maxPlayers = 12; - if (mapID == 0) { - softCap = 999; - maxPlayers = softCap; - } else { + if (mapID == 0) { + softCap = 999; + maxPlayers = softCap; + } else { softCap = GetSoftCap(mapID); maxPlayers = GetHardCap(mapID); } - uint32_t port = GetFreePort(); - instance = new Instance(mExternalIP, port, mapID, ++m_LastInstanceID, cloneID, softCap, maxPlayers); + uint32_t port = GetFreePort(); + instance = new Instance(mExternalIP, port, mapID, ++m_LastInstanceID, cloneID, softCap, maxPlayers); - //Start the actual process: + //Start the actual process: #ifdef _WIN32 std::string cmd = "start ./WorldServer.exe -zone "; #else std::string cmd; - if (std::atoi(Game::config->GetValue("use_sudo_world").c_str())) { + if (std::atoi(Game::config->GetValue("use_sudo_world").c_str())) { cmd = "sudo ./WorldServer -zone "; } else { cmd = "./WorldServer -zone "; } #endif - cmd.append(std::to_string(mapID)); - cmd.append(" -port "); - cmd.append(std::to_string(port)); - cmd.append(" -instance "); - cmd.append(std::to_string(m_LastInstanceID)); - cmd.append(" -maxclients "); - cmd.append(std::to_string(maxPlayers)); + cmd.append(std::to_string(mapID)); + cmd.append(" -port "); + cmd.append(std::to_string(port)); + cmd.append(" -instance "); + cmd.append(std::to_string(m_LastInstanceID)); + cmd.append(" -maxclients "); + cmd.append(std::to_string(maxPlayers)); - cmd.append(" -clone "); - cmd.append(std::to_string(cloneID)); + cmd.append(" -clone "); + cmd.append(std::to_string(cloneID)); #ifndef _WIN32 - cmd.append("&"); //Sends our next process to the background on Linux + cmd.append("&"); //Sends our next process to the background on Linux #endif - system(cmd.c_str()); + system(cmd.c_str()); - m_Instances.push_back(instance); + m_Instances.push_back(instance); - if (instance) { - mLogger->Log("InstanceManager", "Created new instance: %i/%i/%i with min/max %i/%i", mapID, m_LastInstanceID, cloneID, softCap, maxPlayers); - return instance; - } - else mLogger->Log("InstanceManager", "Failed to create a new instance!"); + if (instance) { + mLogger->Log("InstanceManager", "Created new instance: %i/%i/%i with min/max %i/%i", mapID, m_LastInstanceID, cloneID, softCap, maxPlayers); + return instance; + } else mLogger->Log("InstanceManager", "Failed to create a new instance!"); - return nullptr; + return nullptr; } bool InstanceManager::IsPortInUse(uint32_t port) { @@ -97,22 +96,22 @@ bool InstanceManager::IsPortInUse(uint32_t port) { } uint32_t InstanceManager::GetFreePort() { - uint32_t port = m_LastPort; - std::vector usedPorts; - for (Instance* i : m_Instances) { - usedPorts.push_back(i->GetPort()); - } + uint32_t port = m_LastPort; + std::vector usedPorts; + for (Instance* i : m_Instances) { + usedPorts.push_back(i->GetPort()); + } - std::sort(usedPorts.begin(), usedPorts.end()); + std::sort(usedPorts.begin(), usedPorts.end()); - int portIdx = 0; - while (portIdx < usedPorts.size() && port == usedPorts[portIdx]) { - //increment by 3 since each instance uses 3 ports (instance, world-server, world-chat) - port += 3; - portIdx++; - } + int portIdx = 0; + while (portIdx < usedPorts.size() && port == usedPorts[portIdx]) { + //increment by 3 since each instance uses 3 ports (instance, world-server, world-chat) + port += 3; + portIdx++; + } - return port; + return port; } void InstanceManager::AddPlayer(SystemAddress systemAddr, LWOMAPID mapID, LWOINSTANCEID instanceID) { @@ -135,8 +134,7 @@ void InstanceManager::RemovePlayer(SystemAddress systemAddr, LWOMAPID mapID, LWO } } -std::vector InstanceManager::GetInstances() const -{ +std::vector InstanceManager::GetInstances() const { return m_Instances; } @@ -147,10 +145,8 @@ void InstanceManager::AddInstance(Instance* instance) { } void InstanceManager::RemoveInstance(Instance* instance) { - for (uint32_t i = 0; i < m_Instances.size(); ++i) - { - if (m_Instances[i] == instance) - { + for (uint32_t i = 0; i < m_Instances.size(); ++i) { + if (m_Instances[i] == instance) { instance->SetShutdownComplete(true); RedirectPendingRequests(instance); @@ -164,14 +160,12 @@ void InstanceManager::RemoveInstance(Instance* instance) { } } -void InstanceManager::ReadyInstance(Instance* instance) -{ +void InstanceManager::ReadyInstance(Instance* instance) { instance->SetIsReady(true); auto& pending = instance->GetPendingRequests(); - for (const auto& request : pending) - { + for (const auto& request : pending) { const auto& zoneId = instance->GetZoneID(); Game::logger->Log("InstanceManager", "Responding to pending request %llu -> %i (%i)", request, zoneId.GetMapID(), zoneId.GetCloneID()); @@ -192,8 +186,7 @@ void InstanceManager::ReadyInstance(Instance* instance) pending.clear(); } -void InstanceManager::RequestAffirmation(Instance* instance, const PendingInstanceRequest& request) -{ +void InstanceManager::RequestAffirmation(Instance* instance, const PendingInstanceRequest& request) { instance->GetPendingAffirmations().push_back(request); CBITSTREAM; @@ -210,12 +203,10 @@ void InstanceManager::RequestAffirmation(Instance* instance, const PendingInstan ); } -void InstanceManager::AffirmTransfer(Instance* instance, const uint64_t transferID) -{ +void InstanceManager::AffirmTransfer(Instance* instance, const uint64_t transferID) { auto& pending = instance->GetPendingAffirmations(); - for (auto i = 0u; i < pending.size(); ++i) - { + for (auto i = 0u; i < pending.size(); ++i) { const auto& request = pending[i]; if (request.id != transferID) continue; @@ -240,12 +231,10 @@ void InstanceManager::AffirmTransfer(Instance* instance, const uint64_t transfer } } -void InstanceManager::RedirectPendingRequests(Instance* instance) -{ +void InstanceManager::RedirectPendingRequests(Instance* instance) { const auto& zoneId = instance->GetZoneID(); - for (const auto& request : instance->GetPendingAffirmations()) - { + for (const auto& request : instance->GetPendingAffirmations()) { auto* in = Game::im->GetInstance(zoneId.GetMapID(), false, zoneId.GetCloneID()); if (!in->GetIsReady()) // Instance not ready, make a pending request @@ -278,7 +267,7 @@ bool InstanceManager::IsInstanceFull(Instance* instance, bool isFriendTransfer) return true; } -Instance * InstanceManager::FindInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneId) { +Instance* InstanceManager::FindInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneId) { for (Instance* i : m_Instances) { if (i && i->GetMapID() == mapID && i->GetCloneID() == cloneId && !IsInstanceFull(i, isFriendTransfer) && !i->GetIsPrivate() && !i->GetShutdownComplete() && !i->GetIsShuttingDown()) { return i; @@ -288,9 +277,9 @@ Instance * InstanceManager::FindInstance(LWOMAPID mapID, bool isFriendTransfer, return nullptr; } -Instance * InstanceManager::FindInstance(LWOMAPID mapID, LWOINSTANCEID instanceID) { +Instance* InstanceManager::FindInstance(LWOMAPID mapID, LWOINSTANCEID instanceID) { for (Instance* i : m_Instances) { - if (i && i->GetMapID() == mapID && i->GetInstanceID() == instanceID && !i->GetIsPrivate() && !i->GetShutdownComplete() && !i->GetIsShuttingDown()) { + if (i && i->GetMapID() == mapID && i->GetInstanceID() == instanceID && !i->GetIsPrivate() && !i->GetShutdownComplete() && !i->GetIsShuttingDown()) { return i; } } @@ -298,12 +287,10 @@ Instance * InstanceManager::FindInstance(LWOMAPID mapID, LWOINSTANCEID instanceI return nullptr; } -Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID cloneID, const std::string& password) -{ +Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID cloneID, const std::string& password) { auto* instance = FindPrivateInstance(password); - if (instance != nullptr) - { + if (instance != nullptr) { return instance; } @@ -312,29 +299,29 @@ Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID clon uint32_t port = GetFreePort(); instance = new Instance(mExternalIP, port, mapID, ++m_LastInstanceID, cloneID, maxPlayers, maxPlayers, true, password); - //Start the actual process: - std::string cmd = "start ./WorldServer.exe -zone "; + //Start the actual process: + std::string cmd = "start ./WorldServer.exe -zone "; #ifndef _WIN32 cmd = "./WorldServer -zone "; #endif - cmd.append(std::to_string(mapID)); - cmd.append(" -port "); - cmd.append(std::to_string(port)); - cmd.append(" -instance "); - cmd.append(std::to_string(m_LastInstanceID)); - cmd.append(" -maxclients "); - cmd.append(std::to_string(maxPlayers)); + cmd.append(std::to_string(mapID)); + cmd.append(" -port "); + cmd.append(std::to_string(port)); + cmd.append(" -instance "); + cmd.append(std::to_string(m_LastInstanceID)); + cmd.append(" -maxclients "); + cmd.append(std::to_string(maxPlayers)); - cmd.append(" -clone "); - cmd.append(std::to_string(cloneID)); + cmd.append(" -clone "); + cmd.append(std::to_string(cloneID)); #ifndef WIN32 - cmd.append("&"); //Sends our next process to the background on Linux + cmd.append("&"); //Sends our next process to the background on Linux #endif - system(cmd.c_str()); + system(cmd.c_str()); m_Instances.push_back(instance); @@ -344,21 +331,17 @@ Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID clon return instance; } -Instance* InstanceManager::FindPrivateInstance(const std::string& password) -{ - for (auto* instance : m_Instances) - { +Instance* InstanceManager::FindPrivateInstance(const std::string& password) { + for (auto* instance : m_Instances) { if (!instance) continue; - if (!instance->GetIsPrivate()) - { + if (!instance->GetIsPrivate()) { continue; } mLogger->Log("InstanceManager", "Password: %s == %s => %d", password.c_str(), instance->GetPassword().c_str(), password == instance->GetPassword()); - if (instance->GetPassword() == password) - { + if (instance->GetPassword() == password) { return instance; } } @@ -392,18 +375,15 @@ int InstanceManager::GetHardCap(LWOMAPID mapID) { return 12; } -void Instance::SetShutdownComplete(const bool value) -{ +void Instance::SetShutdownComplete(const bool value) { m_Shutdown = value; } -bool Instance::GetShutdownComplete() const -{ +bool Instance::GetShutdownComplete() const { return m_Shutdown; } -void Instance::Shutdown() -{ +void Instance::Shutdown() { CBITSTREAM; PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SHUTDOWN); diff --git a/dMasterServer/InstanceManager.h b/dMasterServer/InstanceManager.h index ea261343..2c5083d4 100644 --- a/dMasterServer/InstanceManager.h +++ b/dMasterServer/InstanceManager.h @@ -51,7 +51,7 @@ public: void SetIsShuttingDown(bool value) { m_IsShuttingDown = value; } std::vector& GetPendingRequests() { return m_PendingRequests; } std::vector& GetPendingAffirmations() { return m_PendingAffirmations; } - + int GetHardCap() const { return m_MaxClientsHardCap; } int GetSoftCap() const { return m_MaxClientsSoftCap; } int GetCurrentClientCount() const { return m_CurrentClientCount; } @@ -60,10 +60,10 @@ public: uint32_t GetAffirmationTimeout() const { return m_AffirmationTimeout; } void AddPlayer(Player player) { /*m_Players.push_back(player);*/ m_CurrentClientCount++; } - void RemovePlayer(Player player) { + void RemovePlayer(Player player) { m_CurrentClientCount--; if (m_CurrentClientCount < 0) m_CurrentClientCount = 0; - /*for (size_t i = 0; i < m_Players.size(); ++i) + /*for (size_t i = 0; i < m_Players.size(); ++i) if (m_Players[i].addr == player.addr) m_Players.erase(m_Players.begin() + i);*/ } @@ -72,7 +72,7 @@ public: void SetShutdownComplete(bool value); bool GetShutdownComplete() const; - + void Shutdown(); private: @@ -90,7 +90,7 @@ private: std::vector m_PendingAffirmations; uint32_t m_AffirmationTimeout; - + bool m_IsPrivate; std::string m_Password; @@ -107,7 +107,7 @@ public: Instance* GetInstance(LWOMAPID mapID, bool isFriendTransfer, LWOCLONEID cloneID); //Creates an instance if none found bool IsPortInUse(uint32_t port); uint32_t GetFreePort(); - + void AddPlayer(SystemAddress systemAddr, LWOMAPID mapID, LWOINSTANCEID instanceID); void RemovePlayer(SystemAddress systemAddr, LWOMAPID mapID, LWOINSTANCEID instanceID); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index e679940b..a692e826 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -104,8 +104,7 @@ int main(int argc, char** argv) { Game::logger->Log("MigrationRunner", "Finished running migrations"); return EXIT_SUCCESS; - } - else { + } else { //Check CDClient exists const std::string cdclient_path = "./res/CDServer.sqlite"; @@ -229,8 +228,7 @@ int main(int argc, char** argv) { updateStatement->setInt(3, result->getInt("id")); updateStatement->execute(); delete updateStatement; - } - else { + } else { //If we didn't find a server, create one. auto* insertStatement = Database::CreatePreppedStmt("INSERT INTO `servers` (`name`, `ip`, `port`, `state`, `version`) VALUES ('master', ?, ?, 0, 171023)"); insertStatement->setString(1, master_server_ip); @@ -274,8 +272,7 @@ int main(int argc, char** argv) { if (framesSinceLastFlush >= 900) { Game::logger->Flush(); framesSinceLastFlush = 0; - } - else + } else framesSinceLastFlush++; //Every 10 min we ping our sql server to keep it alive hopefully: @@ -294,8 +291,7 @@ int main(int argc, char** argv) { delete stmt; framesSinceLastSQLPing = 0; - } - else + } else framesSinceLastSQLPing++; //10m shutdown for universe kill command @@ -303,8 +299,7 @@ int main(int argc, char** argv) { if (framesSinceKillUniverseCommand >= 40000) { //Break main loop and exit break; - } - else + } else framesSinceKillUniverseCommand++; } @@ -319,8 +314,7 @@ int main(int argc, char** argv) { if (!instance->GetPendingAffirmations().empty()) { affirmTimeout++; - } - else { + } else { affirmTimeout = 0; } @@ -415,7 +409,7 @@ void HandlePacket(Packet* packet) { } case MSG_MASTER_REQUEST_ZONE_TRANSFER: { - Game::logger->Log("MasterServer","Received zone transfer req"); + Game::logger->Log("MasterServer", "Received zone transfer req"); RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); uint64_t requestID = 0; @@ -431,7 +425,7 @@ void HandlePacket(Packet* packet) { Instance* in = Game::im->GetInstance(zoneID, false, zoneClone); for (auto* instance : Game::im->GetInstances()) { - Game::logger->Log("MasterServer", "Instance: %i/%i/%i -> %i",instance->GetMapID(), instance->GetCloneID(),instance->GetInstanceID(), instance == in); + Game::logger->Log("MasterServer", "Instance: %i/%i/%i -> %i", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance == in); } if (!in->GetIsReady()) //Instance not ready, make a pending request @@ -477,8 +471,7 @@ void HandlePacket(Packet* packet) { in->SetSysAddr(copy); Game::im->AddInstance(in); - } - else { + } else { auto instance = Game::im->FindInstance( theirZoneID, static_cast(theirInstanceID)); if (instance) { @@ -562,8 +555,7 @@ void HandlePacket(Packet* packet) { Game::im->FindInstance(theirZoneID, theirInstanceID); if (instance) { instance->AddPlayer(Player()); - } - else { + } else { printf("Instance missing? What?"); } break; @@ -633,7 +625,7 @@ void HandlePacket(Packet* packet) { auto* instance = Game::im->FindPrivateInstance(password.c_str()); - Game::logger->Log( "MasterServer", "Join private zone: %llu %d %s %p", requestID, mythranShift, password.c_str(), instance); + Game::logger->Log("MasterServer", "Join private zone: %llu %d %s %p", requestID, mythranShift, password.c_str(), instance); if (instance == nullptr) { return; @@ -641,7 +633,7 @@ void HandlePacket(Packet* packet) { const auto& zone = instance->GetZoneID(); - MasterPackets::SendZoneTransferResponse(Game::server, packet->systemAddress, requestID,(bool)mythranShift, zone.GetMapID(),instance->GetInstanceID(), zone.GetCloneID(),instance->GetIP(), instance->GetPort()); + MasterPackets::SendZoneTransferResponse(Game::server, packet->systemAddress, requestID, (bool)mythranShift, zone.GetMapID(), instance->GetInstanceID(), zone.GetCloneID(), instance->GetIP(), instance->GetPort()); break; } @@ -656,12 +648,12 @@ void HandlePacket(Packet* packet) { inStream.Read(zoneID); inStream.Read(instanceID); - Game::logger->Log("MasterServer", "Got world ready %i %i",zoneID, instanceID); + Game::logger->Log("MasterServer", "Got world ready %i %i", zoneID, instanceID); auto* instance = Game::im->FindInstance(zoneID, instanceID); if (instance == nullptr) { - Game::logger->Log("MasterServer","Failed to find zone to ready"); + Game::logger->Log("MasterServer", "Failed to find zone to ready"); return; } @@ -690,15 +682,15 @@ void HandlePacket(Packet* packet) { inStream.Read(requestID); - Game::logger->Log("MasterServer","Got affirmation of transfer %llu",requestID); + Game::logger->Log("MasterServer", "Got affirmation of transfer %llu", requestID); - auto* instance =Game::im->GetInstanceBySysAddr(packet->systemAddress); + auto* instance = Game::im->GetInstanceBySysAddr(packet->systemAddress); if (instance == nullptr) return; Game::im->AffirmTransfer(instance, requestID); - Game::logger->Log("MasterServer", "Affirmation complete %llu",requestID); + Game::logger->Log("MasterServer", "Affirmation complete %llu", requestID); break; } @@ -718,45 +710,43 @@ void HandlePacket(Packet* packet) { } case MSG_MASTER_SHUTDOWN_UNIVERSE: { - Game::logger->Log("MasterServer","Received shutdown universe command, shutting down in 10 minutes."); + Game::logger->Log("MasterServer", "Received shutdown universe command, shutting down in 10 minutes."); shouldShutdown = true; break; } default: - Game::logger->Log("MasterServer","Unknown master packet ID from server: %i",packet->data[3]); + Game::logger->Log("MasterServer", "Unknown master packet ID from server: %i", packet->data[3]); } } } void StartChatServer() { #ifdef __APPLE__ - //macOS doesn't need sudo to run on ports < 1024 - system("./ChatServer&"); + //macOS doesn't need sudo to run on ports < 1024 + system("./ChatServer&"); #elif _WIN32 - system("start ./ChatServer.exe"); + system("start ./ChatServer.exe"); #else - if (std::atoi(Game::config->GetValue("use_sudo_chat").c_str())) { - system("sudo ./ChatServer&"); - } - else { - system("./ChatServer&"); - } + if (std::atoi(Game::config->GetValue("use_sudo_chat").c_str())) { + system("sudo ./ChatServer&"); + } else { + system("./ChatServer&"); + } #endif } void StartAuthServer() { #ifdef __APPLE__ - system("./AuthServer&"); + system("./AuthServer&"); #elif _WIN32 - system("start ./AuthServer.exe"); + system("start ./AuthServer.exe"); #else - if (std::atoi(Game::config->GetValue("use_sudo_auth").c_str())) { - system("sudo ./AuthServer&"); - } - else { - system("./AuthServer&"); - } + if (std::atoi(Game::config->GetValue("use_sudo_auth").c_str())) { + system("sudo ./AuthServer&"); + } else { + system("./AuthServer&"); + } #endif } diff --git a/dMasterServer/ObjectIDManager.cpp b/dMasterServer/ObjectIDManager.cpp index 160a3859..0f3b98c9 100644 --- a/dMasterServer/ObjectIDManager.cpp +++ b/dMasterServer/ObjectIDManager.cpp @@ -5,67 +5,67 @@ #include "dLogger.h" // Static Variables -ObjectIDManager *ObjectIDManager::m_Address = nullptr; +ObjectIDManager* ObjectIDManager::m_Address = nullptr; //! Initializes the manager -void ObjectIDManager::Initialize(dLogger *logger) { - this->mLogger = logger; - this->currentPersistentID = 1; +void ObjectIDManager::Initialize(dLogger* logger) { + this->mLogger = logger; + this->currentPersistentID = 1; - try { - sql::PreparedStatement *stmt = Database::CreatePreppedStmt( - "SELECT last_object_id FROM object_id_tracker"); + try { + sql::PreparedStatement* stmt = Database::CreatePreppedStmt( + "SELECT last_object_id FROM object_id_tracker"); - sql::ResultSet *result = stmt->executeQuery(); - auto next = result->next(); + sql::ResultSet* result = stmt->executeQuery(); + auto next = result->next(); - if (!next) { - sql::PreparedStatement *insertStmt = Database::CreatePreppedStmt( - "INSERT INTO object_id_tracker VALUES (1)"); + if (!next) { + sql::PreparedStatement* insertStmt = Database::CreatePreppedStmt( + "INSERT INTO object_id_tracker VALUES (1)"); - insertStmt->execute(); + insertStmt->execute(); - delete insertStmt; + delete insertStmt; - return; - } + return; + } - while (next) { - this->currentPersistentID = - result->getInt(1) > 0 ? result->getInt(1) : 1; - next = result->next(); - } + while (next) { + this->currentPersistentID = + result->getInt(1) > 0 ? result->getInt(1) : 1; + next = result->next(); + } - delete result; - delete stmt; - } catch (sql::SQLException &e) { - mLogger->Log("ObjectIDManager", "Unable to fetch max persistent object " - "ID in use. Defaulting to 1."); - mLogger->Log("ObjectIDManager", "SQL error: %s", e.what()); - this->currentPersistentID = 1; - } + delete result; + delete stmt; + } catch (sql::SQLException& e) { + mLogger->Log("ObjectIDManager", "Unable to fetch max persistent object " + "ID in use. Defaulting to 1."); + mLogger->Log("ObjectIDManager", "SQL error: %s", e.what()); + this->currentPersistentID = 1; + } } //! Generates a new persistent ID uint32_t ObjectIDManager::GeneratePersistentID(void) { - uint32_t toReturn = ++this->currentPersistentID; + uint32_t toReturn = ++this->currentPersistentID; - // So we peroidically save our ObjID to the database: - if (toReturn % 25 == 0) { // TEMP: DISABLED FOR DEBUG / DEVELOPMENT! - sql::PreparedStatement *stmt = Database::CreatePreppedStmt( - "UPDATE object_id_tracker SET last_object_id=?"); - stmt->setUInt(1, toReturn); - stmt->execute(); - delete stmt; - } + // So we peroidically save our ObjID to the database: + if (toReturn % 25 == 0) { // TEMP: DISABLED FOR DEBUG / DEVELOPMENT! + sql::PreparedStatement* stmt = Database::CreatePreppedStmt( + "UPDATE object_id_tracker SET last_object_id=?"); + stmt->setUInt(1, toReturn); + stmt->execute(); + delete stmt; + } - return toReturn; + return toReturn; } void ObjectIDManager::SaveToDatabase() { - sql::PreparedStatement *stmt = Database::CreatePreppedStmt( - "UPDATE object_id_tracker SET last_object_id=?"); - stmt->setUInt(1, currentPersistentID); - stmt->execute(); - delete stmt; + sql::PreparedStatement* stmt = Database::CreatePreppedStmt( + "UPDATE object_id_tracker SET last_object_id=?"); + stmt->setUInt(1, currentPersistentID); + stmt->execute(); + delete stmt; } diff --git a/dMasterServer/ObjectIDManager.h b/dMasterServer/ObjectIDManager.h index fd63434b..b18619bc 100644 --- a/dMasterServer/ObjectIDManager.h +++ b/dMasterServer/ObjectIDManager.h @@ -10,38 +10,38 @@ class dLogger; \brief A manager that handles requests for object IDs */ -//! The Object ID Manager + //! The Object ID Manager class ObjectIDManager { private: dLogger* mLogger; - static ObjectIDManager * m_Address; //!< The singleton instance - - uint32_t currentPersistentID; //!< The highest current persistent ID in use - + static ObjectIDManager* m_Address; //!< The singleton instance + + uint32_t currentPersistentID; //!< The highest current persistent ID in use + public: - - //! Return the singleton if it is initialized - static ObjectIDManager* TryInstance() { - return m_Address; - } - //! The singleton method - static ObjectIDManager * Instance() { - if (m_Address == nullptr) { - m_Address = new ObjectIDManager; - } - - return m_Address; - } - - //! Initializes the manager - void Initialize(dLogger* logger); - - //! Generates a new persistent ID - /*! - \return The new persistent ID - */ - uint32_t GeneratePersistentID(void); + //! Return the singleton if it is initialized + static ObjectIDManager* TryInstance() { + return m_Address; + } - void SaveToDatabase(); + //! The singleton method + static ObjectIDManager* Instance() { + if (m_Address == nullptr) { + m_Address = new ObjectIDManager; + } + + return m_Address; + } + + //! Initializes the manager + void Initialize(dLogger* logger); + + //! Generates a new persistent ID + /*! + \return The new persistent ID + */ + uint32_t GeneratePersistentID(void); + + void SaveToDatabase(); }; diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index 0efce260..60fe13c5 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -119,11 +119,11 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { } if (sqlBanned) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_BANNED, "", "", 2001, username); return; + AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_BANNED, "", "", 2001, username); return; } if (sqlLocked) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_ACCOUNT_LOCKED, "", "", 2001, username); return; + AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_ACCOUNT_LOCKED, "", "", 2001, username); return; } /* @@ -136,18 +136,14 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { int32_t bcryptState = ::bcrypt_checkpw(password.c_str(), sqlPass.c_str()); - if (bcryptState != 0) - { + if (bcryptState != 0) { // Fallback on old method std::string oldPassword = sha512(password + username); - if (sqlPass != oldPassword) - { + if (sqlPass != oldPassword) { loginSuccess = false; - } - else - { + } else { // Generate new hash for bcrypt char salt[BCRYPT_HASHSIZE]; @@ -168,17 +164,14 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { accountUpdate->executeUpdate(); } - } - else - { + } else { // Login success with bcrypt } if (!loginSuccess) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_WRONG_PASS_OR_USER, "", "", 2001, username); + AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_WRONG_PASS_OR_USER, "", "", 2001, username); server->GetLogger()->Log("AuthPackets", "Wrong password used"); - } - else { + } else { SystemAddress system = packet->systemAddress; //Copy the sysAddr before the Packet gets destroyed from main if (!server->GetIsConnectedToMaster()) { @@ -188,74 +181,74 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { ZoneInstanceManager::Instance()->RequestZoneTransfer(server, 0, 0, false, [system, server, username](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string zoneIP, uint16_t zonePort) { AuthPackets::SendLoginResponse(server, system, LOGIN_RESPONSE_SUCCESS, "", zoneIP, zonePort, username); - }); + }); } } void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAddr, eLoginResponse responseCode, const std::string& errorMsg, const std::string& wServerIP, uint16_t wServerPort, std::string username) { - RakNet::BitStream packet; - PacketUtils::WriteHeader(packet, CLIENT, MSG_CLIENT_LOGIN_RESPONSE); + RakNet::BitStream packet; + PacketUtils::WriteHeader(packet, CLIENT, MSG_CLIENT_LOGIN_RESPONSE); - packet.Write(static_cast(responseCode)); + packet.Write(static_cast(responseCode)); - PacketUtils::WritePacketString("Talk_Like_A_Pirate", 33, &packet); + PacketUtils::WritePacketString("Talk_Like_A_Pirate", 33, &packet); - // 7 unknown strings - perhaps other IP addresses? - PacketUtils::WritePacketString("", 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); + // 7 unknown strings - perhaps other IP addresses? + PacketUtils::WritePacketString("", 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); - packet.Write(static_cast(1)); // Version Major - packet.Write(static_cast(10)); // Version Current - packet.Write(static_cast(64)); // Version Minor + packet.Write(static_cast(1)); // Version Major + packet.Write(static_cast(10)); // Version Current + packet.Write(static_cast(64)); // Version Minor - // Writes the user key + // Writes the user key uint32_t sessionKey = rand(); // not mt but whatever std::string userHash = std::to_string(sessionKey); - userHash = md5(userHash); - PacketUtils::WritePacketWString(userHash, 33, &packet); + userHash = md5(userHash); + PacketUtils::WritePacketWString(userHash, 33, &packet); - // Write the Character and Chat IPs - PacketUtils::WritePacketString(wServerIP, 33, &packet); - PacketUtils::WritePacketString("", 33, &packet); + // Write the Character and Chat IPs + PacketUtils::WritePacketString(wServerIP, 33, &packet); + PacketUtils::WritePacketString("", 33, &packet); - // Write the Character and Chat Ports - packet.Write(static_cast(wServerPort)); - packet.Write(static_cast(0)); + // Write the Character and Chat Ports + packet.Write(static_cast(wServerPort)); + packet.Write(static_cast(0)); - // Write another IP - PacketUtils::WritePacketString("", 33, &packet); + // Write another IP + PacketUtils::WritePacketString("", 33, &packet); - // Write a GUID or something... - PacketUtils::WritePacketString("00000000-0000-0000-0000-000000000000", 37, &packet); + // Write a GUID or something... + PacketUtils::WritePacketString("00000000-0000-0000-0000-000000000000", 37, &packet); - packet.Write(static_cast(0)); // ??? + packet.Write(static_cast(0)); // ??? - // Write the localization - PacketUtils::WritePacketString("US", 3, &packet); + // Write the localization + PacketUtils::WritePacketString("US", 3, &packet); - packet.Write(static_cast(false)); // User first logged in? - packet.Write(static_cast(false)); // User is F2P? - packet.Write(static_cast(0)); // ??? + packet.Write(static_cast(false)); // User first logged in? + packet.Write(static_cast(false)); // User is F2P? + packet.Write(static_cast(0)); // ??? - // Write custom error message - packet.Write(static_cast(errorMsg.length())); - PacketUtils::WritePacketWString(errorMsg, static_cast(errorMsg.length()), &packet); + // Write custom error message + packet.Write(static_cast(errorMsg.length())); + PacketUtils::WritePacketWString(errorMsg, static_cast(errorMsg.length()), &packet); - // Here write auth logs - packet.Write(static_cast(20)); - for (uint32_t i = 0; i < 20; ++i) { - packet.Write(static_cast(8)); - packet.Write(static_cast(44)); - packet.Write(static_cast(14000)); - packet.Write(static_cast(0)); - } + // Here write auth logs + packet.Write(static_cast(20)); + for (uint32_t i = 0; i < 20; ++i) { + packet.Write(static_cast(8)); + packet.Write(static_cast(44)); + packet.Write(static_cast(14000)); + packet.Write(static_cast(0)); + } - server->Send(&packet, sysAddr, false); + server->Send(&packet, sysAddr, false); //Inform the master server that we've created a session for this user: { diff --git a/dNet/AuthPackets.h b/dNet/AuthPackets.h index 2830480f..e972d2f7 100644 --- a/dNet/AuthPackets.h +++ b/dNet/AuthPackets.h @@ -10,9 +10,9 @@ class dServer; namespace AuthPackets { void HandleHandshake(dServer* server, Packet* packet); void SendHandshake(dServer* server, const SystemAddress& sysAddr, const std::string& nextServerIP, uint16_t nextServerPort); - + void HandleLoginRequest(dServer* server, Packet* packet); void SendLoginResponse(dServer* server, const SystemAddress& sysAddr, eLoginResponse responseCode, const std::string& errorMsg, const std::string& wServerIP, uint16_t wServerPort, std::string username); } -#endif // AUTHPACKETS_H \ No newline at end of file +#endif // AUTHPACKETS_H diff --git a/dNet/ChatPackets.cpp b/dNet/ChatPackets.cpp index db90bcfe..eb3bda71 100644 --- a/dNet/ChatPackets.cpp +++ b/dNet/ChatPackets.cpp @@ -12,63 +12,63 @@ #include "dServer.h" void ChatPackets::SendChatMessage(const SystemAddress& sysAddr, char chatChannel, const std::string& senderName, LWOOBJID playerObjectID, bool senderMythran, const std::u16string& message) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); - - bitStream.Write(static_cast(0)); - bitStream.Write(chatChannel); - - bitStream.Write(static_cast(message.size())); - PacketUtils::WriteWString(bitStream, senderName, 33); + CBITSTREAM + PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); - bitStream.Write(playerObjectID); - bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(0)); + bitStream.Write(chatChannel); - for (uint32_t i = 0; i < message.size(); ++i) { - bitStream.Write(static_cast(message[i])); - } - bitStream.Write(static_cast(0)); - - SEND_PACKET_BROADCAST + bitStream.Write(static_cast(message.size())); + PacketUtils::WriteWString(bitStream, senderName, 33); + + bitStream.Write(playerObjectID); + bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(0)); + + for (uint32_t i = 0; i < message.size(); ++i) { + bitStream.Write(static_cast(message[i])); + } + bitStream.Write(static_cast(0)); + + SEND_PACKET_BROADCAST } void ChatPackets::SendSystemMessage(const SystemAddress& sysAddr, const std::u16string& message, const bool broadcast) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); - - bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(4)); + CBITSTREAM + PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); - bitStream.Write(static_cast(message.size())); - PacketUtils::WriteWString(bitStream, "", 33); + bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(4)); - bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(message.size())); + PacketUtils::WriteWString(bitStream, "", 33); - for (uint32_t i = 0; i < message.size(); ++i) { - bitStream.Write(static_cast(message[i])); - } + bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(0)); + + for (uint32_t i = 0; i < message.size(); ++i) { + bitStream.Write(static_cast(message[i])); + } + + bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(0)); - //This is so Wincent's announcement works: if (sysAddr != UNASSIGNED_SYSTEM_ADDRESS) { SEND_PACKET; return; } - + SEND_PACKET_BROADCAST; } void ChatPackets::SendMessageFail(const SystemAddress& sysAddr) { - //0x00 - "Chat is currently disabled." - //0x01 - "Upgrade to a full LEGO Universe Membership to chat with other players." + //0x00 - "Chat is currently disabled." + //0x01 - "Upgrade to a full LEGO Universe Membership to chat with other players." - CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_SEND_CANNED_TEXT); - bitStream.Write(0); //response type, options above ^ - //docs say there's a wstring here-- no idea what it's for, or if it's even needed so leaving it as is for now. - SEND_PACKET; + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_SEND_CANNED_TEXT); + bitStream.Write(0); //response type, options above ^ + //docs say there's a wstring here-- no idea what it's for, or if it's even needed so leaving it as is for now. + SEND_PACKET; } diff --git a/dNet/ChatPackets.h b/dNet/ChatPackets.h index aa58977c..8f6de175 100644 --- a/dNet/ChatPackets.h +++ b/dNet/ChatPackets.h @@ -12,9 +12,9 @@ struct SystemAddress; #include "dCommonVars.h" namespace ChatPackets { - void SendChatMessage(const SystemAddress& sysAddr, char chatChannel, const std::string& senderName, LWOOBJID playerObjectID, bool senderMythran, const std::u16string& message); - void SendSystemMessage(const SystemAddress& sysAddr, const std::u16string& message, bool broadcast = false); - void SendMessageFail(const SystemAddress& sysAddr); + void SendChatMessage(const SystemAddress& sysAddr, char chatChannel, const std::string& senderName, LWOOBJID playerObjectID, bool senderMythran, const std::u16string& message); + void SendSystemMessage(const SystemAddress& sysAddr, const std::u16string& message, bool broadcast = false); + void SendMessageFail(const SystemAddress& sysAddr); }; #endif // CHATPACKETS_H diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index 00c16133..b49801cc 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -176,7 +176,7 @@ void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Pac // Handle statistics auto* characterComponent = entity->GetComponent(); if (characterComponent != nullptr) { - characterComponent->TrackPositionUpdate(position); + characterComponent->TrackPositionUpdate(position); } comp->SetPosition(position); @@ -254,8 +254,7 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa // Check if the player has restricted chat access auto* character = entity->GetCharacter(); - if (character->HasPermission(PermissionMap::RestrictedChatAccess)) - { + if (character->HasPermission(PermissionMap::RestrictedChatAccess)) { // Send a message to the player ChatPackets::SendSystemMessage( sysAddr, @@ -341,8 +340,7 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa delete res; delete stmt; - } - else if (user->GetIsBestFriendMap().find(receiver) != user->GetIsBestFriendMap().end()) { + } else if (user->GetIsBestFriendMap().find(receiver) != user->GetIsBestFriendMap().end()) { isBestFriend = true; } } diff --git a/dNet/ClientPackets.h b/dNet/ClientPackets.h index 236955fc..a36384e2 100644 --- a/dNet/ClientPackets.h +++ b/dNet/ClientPackets.h @@ -9,9 +9,9 @@ #include "RakNetTypes.h" namespace ClientPackets { - void HandleChatMessage(const SystemAddress& sysAddr, Packet* packet); - void HandleClientPositionUpdate(const SystemAddress& sysAddr, Packet* packet); - void HandleChatModerationRequest(const SystemAddress& sysAddr, Packet* packet); + void HandleChatMessage(const SystemAddress& sysAddr, Packet* packet); + void HandleClientPositionUpdate(const SystemAddress& sysAddr, Packet* packet); + void HandleChatModerationRequest(const SystemAddress& sysAddr, Packet* packet); }; #endif // CLIENTPACKETS_H diff --git a/dNet/MasterPackets.cpp b/dNet/MasterPackets.cpp index bf58d71c..6c55b7dc 100644 --- a/dNet/MasterPackets.cpp +++ b/dNet/MasterPackets.cpp @@ -9,30 +9,30 @@ void MasterPackets::SendPersistentIDRequest(dServer* server, uint64_t requestID) { CBITSTREAM - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_PERSISTENT_ID); - bitStream.Write(requestID); + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_PERSISTENT_ID); + bitStream.Write(requestID); server->SendToMaster(&bitStream); } void MasterPackets::SendPersistentIDResponse(dServer* server, const SystemAddress& sysAddr, uint64_t requestID, uint32_t objID) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_PERSISTENT_ID_RESPONSE); - + bitStream.Write(requestID); bitStream.Write(objID); - + server->Send(&bitStream, sysAddr, false); } void MasterPackets::SendZoneTransferRequest(dServer* server, uint64_t requestID, bool mythranShift, uint32_t zoneID, uint32_t cloneID) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_ZONE_TRANSFER); - - bitStream.Write(requestID); - bitStream.Write(static_cast(mythranShift)); - bitStream.Write(zoneID); - bitStream.Write(cloneID); - + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_ZONE_TRANSFER); + + bitStream.Write(requestID); + bitStream.Write(static_cast(mythranShift)); + bitStream.Write(zoneID); + bitStream.Write(cloneID); + server->SendToMaster(&bitStream); } @@ -66,58 +66,57 @@ void MasterPackets::SendZoneRequestPrivate(dServer* server, uint64_t requestID, server->SendToMaster(&bitStream); } -void MasterPackets::SendWorldReady(dServer* server, LWOMAPID zoneId, LWOINSTANCEID instanceId) -{ +void MasterPackets::SendWorldReady(dServer* server, LWOMAPID zoneId, LWOINSTANCEID instanceId) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_WORLD_READY); bitStream.Write(zoneId); bitStream.Write(instanceId); - + server->SendToMaster(&bitStream); } void MasterPackets::SendZoneTransferResponse(dServer* server, const SystemAddress& sysAddr, uint64_t requestID, bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, const std::string& serverIP, uint32_t serverPort) { - RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE); - - bitStream.Write(requestID); - bitStream.Write(static_cast(mythranShift)); - bitStream.Write(zoneID); - bitStream.Write(zoneInstance); - bitStream.Write(zoneClone); - bitStream.Write(static_cast(serverPort)); - PacketUtils::WriteString(bitStream, serverIP, static_cast(serverIP.size() + 1)); - - server->Send(&bitStream, sysAddr, false); + RakNet::BitStream bitStream; + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE); + + bitStream.Write(requestID); + bitStream.Write(static_cast(mythranShift)); + bitStream.Write(zoneID); + bitStream.Write(zoneInstance); + bitStream.Write(zoneClone); + bitStream.Write(static_cast(serverPort)); + PacketUtils::WriteString(bitStream, serverIP, static_cast(serverIP.size() + 1)); + + server->Send(&bitStream, sysAddr, false); } void MasterPackets::HandleServerInfo(Packet* packet) { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); - + uint32_t theirPort = 0; uint32_t theirZoneID = 0; uint32_t theirInstanceID = 0; std::string theirIP = ""; - + inStream.Read(theirPort); inStream.Read(theirZoneID); inStream.Read(theirInstanceID); theirIP = PacketUtils::ReadString(inStream.GetReadOffset(), packet, false); //20 is the current offset - + //TODO: Actually mark this server as an available server in the manager } void MasterPackets::SendServerInfo(dServer* server, Packet* packet) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SERVER_INFO); - + bitStream.Write(server->GetPort()); bitStream.Write(server->GetZoneID()); bitStream.Write(server->GetInstanceID()); bitStream.Write(server->GetServerType()); PacketUtils::WriteString(bitStream, server->GetIP(), server->GetIP().size()); - + server->SendToMaster(&bitStream); } diff --git a/dNet/MasterPackets.h b/dNet/MasterPackets.h index 19979092..93fd158e 100644 --- a/dNet/MasterPackets.h +++ b/dNet/MasterPackets.h @@ -8,21 +8,21 @@ class dServer; namespace MasterPackets { - void SendPersistentIDRequest(dServer* server, uint64_t requestID); //Called from the World server + void SendPersistentIDRequest(dServer* server, uint64_t requestID); //Called from the World server void SendPersistentIDResponse(dServer* server, const SystemAddress& sysAddr, uint64_t requestID, uint32_t objID); - + void SendZoneTransferRequest(dServer* server, uint64_t requestID, bool mythranShift, uint32_t zoneID, uint32_t cloneID); void SendZoneTransferResponse(dServer* server, const SystemAddress& sysAddr, uint64_t requestID, bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, const std::string& serverIP, uint32_t serverPort); - + void HandleServerInfo(Packet* packet); void SendServerInfo(dServer* server, Packet* packet); - + void SendZoneCreatePrivate(dServer* server, uint32_t zoneID, uint32_t cloneID, const std::string& password); - + void SendZoneRequestPrivate(dServer* server, uint64_t requestID, bool mythranShift, const std::string& password); void SendWorldReady(dServer* server, LWOMAPID zoneId, LWOINSTANCEID instanceId); - + void HandleSetSessionKey(Packet* packet); } diff --git a/dNet/PacketUtils.cpp b/dNet/PacketUtils.cpp index 352f54b9..307ff633 100644 --- a/dNet/PacketUtils.cpp +++ b/dNet/PacketUtils.cpp @@ -12,75 +12,74 @@ void PacketUtils::WriteHeader(RakNet::BitStream& bitStream, uint16_t connectionT bitStream.Write(uint8_t(0)); } -uint16_t PacketUtils::ReadPacketU16(uint32_t startLoc, Packet * packet) { - if (startLoc + 2 > packet->length) return 0; - - std::vector t; - for (uint32_t i = startLoc; i < startLoc + 2; i++) t.push_back(packet->data[i]); - return *(uint16_t*)t.data(); +uint16_t PacketUtils::ReadPacketU16(uint32_t startLoc, Packet* packet) { + if (startLoc + 2 > packet->length) return 0; + + std::vector t; + for (uint32_t i = startLoc; i < startLoc + 2; i++) t.push_back(packet->data[i]); + return *(uint16_t*)t.data(); } -uint32_t PacketUtils::ReadPacketU32(uint32_t startLoc, Packet * packet) { - if (startLoc + 4 > packet->length) return 0; - - std::vector t; - for (uint32_t i = startLoc; i < startLoc + 4; i++) { - t.push_back(packet->data[i]); - } - return *(uint32_t*)t.data(); +uint32_t PacketUtils::ReadPacketU32(uint32_t startLoc, Packet* packet) { + if (startLoc + 4 > packet->length) return 0; + + std::vector t; + for (uint32_t i = startLoc; i < startLoc + 4; i++) { + t.push_back(packet->data[i]); + } + return *(uint32_t*)t.data(); } -uint64_t PacketUtils::ReadPacketU64(uint32_t startLoc, Packet * packet) { - if (startLoc + 8 > packet->length) return 0; - - std::vector t; - for (uint32_t i = startLoc; i < startLoc + 8; i++) t.push_back(packet->data[i]); - return *(uint64_t*)t.data(); +uint64_t PacketUtils::ReadPacketU64(uint32_t startLoc, Packet* packet) { + if (startLoc + 8 > packet->length) return 0; + + std::vector t; + for (uint32_t i = startLoc; i < startLoc + 8; i++) t.push_back(packet->data[i]); + return *(uint64_t*)t.data(); } -int64_t PacketUtils::ReadPacketS64(uint32_t startLoc, Packet * packet) { - if (startLoc + 8 > packet->length) return 0; - - std::vector t; - for (size_t i = startLoc; i < startLoc + 8; i++) t.push_back(packet->data[i]); - return *(int64_t*)t.data(); +int64_t PacketUtils::ReadPacketS64(uint32_t startLoc, Packet* packet) { + if (startLoc + 8 > packet->length) return 0; + + std::vector t; + for (size_t i = startLoc; i < startLoc + 8; i++) t.push_back(packet->data[i]); + return *(int64_t*)t.data(); } std::string PacketUtils::ReadString(uint32_t startLoc, Packet* packet, bool wide, uint32_t maxLen) { - std::string readString = ""; + std::string readString = ""; - if (wide) maxLen *= 2; + if (wide) maxLen *= 2; - if (packet->length > startLoc) { - uint32_t i = 0; - while (packet->data[startLoc + i] != '\0' && packet->length > (uint32_t)(startLoc + i) && maxLen > i) { - readString.push_back(packet->data[startLoc + i]); + if (packet->length > startLoc) { + uint32_t i = 0; + while (packet->data[startLoc + i] != '\0' && packet->length > (uint32_t)(startLoc + i) && maxLen > i) { + readString.push_back(packet->data[startLoc + i]); - if (wide) { - i += 2; // Wide-char string - } - else { - i++; // Regular string - } - } - } + if (wide) { + i += 2; // Wide-char string + } else { + i++; // Regular string + } + } + } - return readString; + return readString; } -void PacketUtils::WritePacketString(const std::string& string, uint32_t maxSize, RakNet::BitStream * bitStream) { - uint32_t size = static_cast(string.size()); - uint32_t remSize = static_cast(maxSize - size); - - if (size > maxSize) size = maxSize; - - for (uint32_t i = 0; i < size; ++i) { - bitStream->Write(static_cast(string[i])); - } - - for (uint32_t j = 0; j < remSize; ++j) { - bitStream->Write(static_cast(0)); - } +void PacketUtils::WritePacketString(const std::string& string, uint32_t maxSize, RakNet::BitStream* bitStream) { + uint32_t size = static_cast(string.size()); + uint32_t remSize = static_cast(maxSize - size); + + if (size > maxSize) size = maxSize; + + for (uint32_t i = 0; i < size; ++i) { + bitStream->Write(static_cast(string[i])); + } + + for (uint32_t j = 0; j < remSize; ++j) { + bitStream->Write(static_cast(0)); + } } void PacketUtils::WriteString(RakNet::BitStream& bitStream, const std::string& s, uint32_t maxSize) { @@ -99,60 +98,60 @@ void PacketUtils::WriteString(RakNet::BitStream& bitStream, const std::string& s } void PacketUtils::WriteWString(RakNet::BitStream& bitStream, const std::string& string, uint32_t maxSize) { - uint32_t size = static_cast(string.length()); - uint32_t remSize = static_cast(maxSize - size); - - if (size > maxSize) size = maxSize; - - for (uint32_t i = 0; i < size; ++i) { - bitStream.Write(static_cast(string[i])); - } - - for (uint32_t j = 0; j < remSize; ++j) { - bitStream.Write(static_cast(0)); - } + uint32_t size = static_cast(string.length()); + uint32_t remSize = static_cast(maxSize - size); + + if (size > maxSize) size = maxSize; + + for (uint32_t i = 0; i < size; ++i) { + bitStream.Write(static_cast(string[i])); + } + + for (uint32_t j = 0; j < remSize; ++j) { + bitStream.Write(static_cast(0)); + } } void PacketUtils::WriteWString(RakNet::BitStream& bitStream, const std::u16string& string, uint32_t maxSize) { - uint32_t size = static_cast(string.length()); - uint32_t remSize = static_cast(maxSize - size); - - if (size > maxSize) size = maxSize; - - for (uint32_t i = 0; i < size; ++i) { - bitStream.Write(static_cast(string[i])); - } - - for (uint32_t j = 0; j < remSize; ++j) { - bitStream.Write(static_cast(0)); - } + uint32_t size = static_cast(string.length()); + uint32_t remSize = static_cast(maxSize - size); + + if (size > maxSize) size = maxSize; + + for (uint32_t i = 0; i < size; ++i) { + bitStream.Write(static_cast(string[i])); + } + + for (uint32_t j = 0; j < remSize; ++j) { + bitStream.Write(static_cast(0)); + } } -void PacketUtils::WritePacketWString(const std::string& string, uint32_t maxSize, RakNet::BitStream * bitStream) { - uint32_t size = static_cast(string.length()); - uint32_t remSize = static_cast(maxSize - size); - - if (size > maxSize) size = maxSize; - - for (uint32_t i = 0; i < size; ++i) { - bitStream->Write(static_cast(string[i])); - } - - for (uint32_t j = 0; j < remSize; ++j) { - bitStream->Write(static_cast(0)); - } +void PacketUtils::WritePacketWString(const std::string& string, uint32_t maxSize, RakNet::BitStream* bitStream) { + uint32_t size = static_cast(string.length()); + uint32_t remSize = static_cast(maxSize - size); + + if (size > maxSize) size = maxSize; + + for (uint32_t i = 0; i < size; ++i) { + bitStream->Write(static_cast(string[i])); + } + + for (uint32_t j = 0; j < remSize; ++j) { + bitStream->Write(static_cast(0)); + } } //! Saves a packet to the filesystem -void PacketUtils::SavePacket(const std::string& filename, const char * data, size_t length) { +void PacketUtils::SavePacket(const std::string& filename, const char* data, size_t length) { //If we don't log to the console, don't save the bin files either. This takes up a lot of time. if (!Game::logger->GetIsLoggingToConsole()) return; - std::string path = "packets/" + filename; - - std::ofstream file(path, std::ios::binary); - if (!file.is_open()) return; - - file.write(data, length); - file.close(); + std::string path = "packets/" + filename; + + std::ofstream file(path, std::ios::binary); + if (!file.is_open()) return; + + file.write(data, length); + file.close(); } diff --git a/dNet/PacketUtils.h b/dNet/PacketUtils.h index 61517ccf..fbbd1839 100644 --- a/dNet/PacketUtils.h +++ b/dNet/PacketUtils.h @@ -6,20 +6,20 @@ namespace PacketUtils { void WriteHeader(RakNet::BitStream& bitStream, uint16_t connectionType, uint32_t internalPacketID); - - uint16_t ReadPacketU16(uint32_t startLoc, Packet * packet); - uint32_t ReadPacketU32(uint32_t startLoc, Packet * packet); - uint64_t ReadPacketU64(uint32_t startLoc, Packet * packet); - int64_t ReadPacketS64(uint32_t startLoc, Packet * packet); - std::string ReadString(uint32_t startLoc, Packet * packet, bool wide, uint32_t maxLen = 33); - - void WritePacketString(const std::string& string, uint32_t maxSize, RakNet::BitStream * bitStream); + + uint16_t ReadPacketU16(uint32_t startLoc, Packet* packet); + uint32_t ReadPacketU32(uint32_t startLoc, Packet* packet); + uint64_t ReadPacketU64(uint32_t startLoc, Packet* packet); + int64_t ReadPacketS64(uint32_t startLoc, Packet* packet); + std::string ReadString(uint32_t startLoc, Packet* packet, bool wide, uint32_t maxLen = 33); + + void WritePacketString(const std::string& string, uint32_t maxSize, RakNet::BitStream* bitStream); void WriteString(RakNet::BitStream& bitStream, const std::string& s, uint32_t maxSize); void WriteWString(RakNet::BitStream& bitStream, const std::string& string, uint32_t maxSize); void WriteWString(RakNet::BitStream& bitStream, const std::u16string& string, uint32_t maxSize); - void WritePacketWString(const std::string& string, uint32_t maxSize, RakNet::BitStream * bitStream); - - void SavePacket(const std::string& filename, const char * data, size_t length); + void WritePacketWString(const std::string& string, uint32_t maxSize, RakNet::BitStream* bitStream); + + void SavePacket(const std::string& filename, const char* data, size_t length); }; #endif // PACKETUTILS_H diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index f7a15c7f..04a7940c 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -16,8 +16,8 @@ #include "ZCompression.h" void WorldPackets::SendLoadStaticZone(const SystemAddress& sysAddr, float x, float y, float z, uint32_t checksum) { - RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_LOAD_STATIC_ZONE); + RakNet::BitStream bitStream; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_LOAD_STATIC_ZONE); auto zone = dZoneManager::Instance()->GetZone()->GetZoneID(); bitStream.Write(static_cast(zone.GetMapID())); @@ -25,19 +25,19 @@ void WorldPackets::SendLoadStaticZone(const SystemAddress& sysAddr, float x, flo //bitStream.Write(static_cast(zone.GetCloneID())); bitStream.Write(0); - bitStream.Write(checksum); - bitStream.Write(static_cast(0)); // ?? + bitStream.Write(checksum); + bitStream.Write(static_cast(0)); // ?? - bitStream.Write(x); - bitStream.Write(y); - bitStream.Write(z); + bitStream.Write(x); + bitStream.Write(y); + bitStream.Write(z); - bitStream.Write(static_cast(0)); // Change this to eventually use 4 on activity worlds + bitStream.Write(static_cast(0)); // Change this to eventually use 4 on activity worlds - SEND_PACKET + SEND_PACKET } -void WorldPackets::SendCharacterList ( const SystemAddress& sysAddr, User* user ) { +void WorldPackets::SendCharacterList(const SystemAddress& sysAddr, User* user) { if (!user) return; RakNet::BitStream bitStream; @@ -45,57 +45,57 @@ void WorldPackets::SendCharacterList ( const SystemAddress& sysAddr, User* user std::vector characters = user->GetCharacters(); bitStream.Write(static_cast(characters.size())); - bitStream.Write(static_cast(0)); //character index in front, just picking 0 + bitStream.Write(static_cast(0)); //character index in front, just picking 0 for (uint32_t i = 0; i < characters.size(); ++i) { bitStream.Write(characters[i]->GetObjectID()); - bitStream.Write(static_cast(0)); + bitStream.Write(static_cast(0)); PacketUtils::WriteWString(bitStream, characters[i]->GetName(), 33); - PacketUtils::WriteWString(bitStream, characters[i]->GetUnapprovedName(), 33); + PacketUtils::WriteWString(bitStream, characters[i]->GetUnapprovedName(), 33); bitStream.Write(static_cast(characters[i]->GetNameRejected())); - bitStream.Write(static_cast(false)); + bitStream.Write(static_cast(false)); PacketUtils::WriteString(bitStream, "", 10); bitStream.Write(characters[i]->GetShirtColor()); - bitStream.Write(characters[i]->GetShirtStyle()); - bitStream.Write(characters[i]->GetPantsColor()); - bitStream.Write(characters[i]->GetHairStyle()); - bitStream.Write(characters[i]->GetHairColor()); - bitStream.Write(characters[i]->GetLeftHand()); - bitStream.Write(characters[i]->GetRightHand()); - bitStream.Write(characters[i]->GetEyebrows()); - bitStream.Write(characters[i]->GetEyes()); - bitStream.Write(characters[i]->GetMouth()); - bitStream.Write(static_cast(0)); + bitStream.Write(characters[i]->GetShirtStyle()); + bitStream.Write(characters[i]->GetPantsColor()); + bitStream.Write(characters[i]->GetHairStyle()); + bitStream.Write(characters[i]->GetHairColor()); + bitStream.Write(characters[i]->GetLeftHand()); + bitStream.Write(characters[i]->GetRightHand()); + bitStream.Write(characters[i]->GetEyebrows()); + bitStream.Write(characters[i]->GetEyes()); + bitStream.Write(characters[i]->GetMouth()); + bitStream.Write(static_cast(0)); - bitStream.Write(static_cast(characters[i]->GetZoneID())); - bitStream.Write(static_cast(characters[i]->GetZoneInstance())); - bitStream.Write(characters[i]->GetZoneClone()); + bitStream.Write(static_cast(characters[i]->GetZoneID())); + bitStream.Write(static_cast(characters[i]->GetZoneInstance())); + bitStream.Write(characters[i]->GetZoneClone()); - bitStream.Write(characters[i]->GetLastLogin()); + bitStream.Write(characters[i]->GetLastLogin()); - const auto& equippedItems = characters[i]->GetEquippedItems(); - bitStream.Write(static_cast(equippedItems.size())); + const auto& equippedItems = characters[i]->GetEquippedItems(); + bitStream.Write(static_cast(equippedItems.size())); - for (uint32_t j = 0; j < equippedItems.size(); ++j) { - bitStream.Write(equippedItems[j]); - } + for (uint32_t j = 0; j < equippedItems.size(); ++j) { + bitStream.Write(equippedItems[j]); + } } SEND_PACKET } -void WorldPackets::SendCharacterCreationResponse ( const SystemAddress& sysAddr, eCreationResponse response ) { +void WorldPackets::SendCharacterCreationResponse(const SystemAddress& sysAddr, eCreationResponse response) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_CREATE_RESPONSE); bitStream.Write(response); SEND_PACKET } -void WorldPackets::SendCharacterRenameResponse ( const SystemAddress& sysAddr, eRenameResponse response ) { +void WorldPackets::SendCharacterRenameResponse(const SystemAddress& sysAddr, eRenameResponse response) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_RENAME_RESPONSE); bitStream.Write(response); @@ -103,13 +103,13 @@ void WorldPackets::SendCharacterRenameResponse ( const SystemAddress& sysAddr, e } void WorldPackets::SendCharacterDeleteResponse(const SystemAddress& sysAddr, bool response) { - RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_DELETE_CHARACTER_RESPONSE); - bitStream.Write(static_cast(response)); - SEND_PACKET + RakNet::BitStream bitStream; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_DELETE_CHARACTER_RESPONSE); + bitStream.Write(static_cast(response)); + SEND_PACKET } -void WorldPackets::SendTransferToWorld ( const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift ) { +void WorldPackets::SendTransferToWorld(const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_TRANSFER_TO_WORLD); @@ -120,7 +120,7 @@ void WorldPackets::SendTransferToWorld ( const SystemAddress& sysAddr, const std SEND_PACKET } -void WorldPackets::SendServerState ( const SystemAddress& sysAddr ) { +void WorldPackets::SendServerState(const SystemAddress& sysAddr) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_SERVER_STATES); bitStream.Write(static_cast(1)); //If the server is receiving this request, it probably is ready anyway. @@ -128,98 +128,98 @@ void WorldPackets::SendServerState ( const SystemAddress& sysAddr ) { } void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm) { - RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CREATE_CHARACTER); + RakNet::BitStream bitStream; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CREATE_CHARACTER); - RakNet::BitStream data; - data.Write(7); //LDF key count + RakNet::BitStream data; + data.Write(7); //LDF key count - auto character = entity->GetComponent(); - if (!character) { - Game::logger->Log("WorldPackets", "Entity is not a character?? what??"); - return; - } + auto character = entity->GetComponent(); + if (!character) { + Game::logger->Log("WorldPackets", "Entity is not a character?? what??"); + return; + } - LDFData* objid = new LDFData(u"objid", entity->GetObjectID()); - LDFData* lot = new LDFData(u"template", 1); - LDFData * xmlConfigData = new LDFData(u"xmlData", xmlData); - LDFData* name = new LDFData(u"name", username); - LDFData* gmlevel = new LDFData(u"gmlevel", gm); - LDFData* chatmode = new LDFData(u"chatmode", gm); - LDFData* reputation = new LDFData(u"reputation", character->GetReputation()); + LDFData* objid = new LDFData(u"objid", entity->GetObjectID()); + LDFData* lot = new LDFData(u"template", 1); + LDFData* xmlConfigData = new LDFData(u"xmlData", xmlData); + LDFData* name = new LDFData(u"name", username); + LDFData* gmlevel = new LDFData(u"gmlevel", gm); + LDFData* chatmode = new LDFData(u"chatmode", gm); + LDFData* reputation = new LDFData(u"reputation", character->GetReputation()); - objid->WriteToPacket(&data); - lot->WriteToPacket(&data); - name->WriteToPacket(&data); - gmlevel->WriteToPacket(&data); - chatmode->WriteToPacket(&data); - xmlConfigData->WriteToPacket(&data); - reputation->WriteToPacket(&data); + objid->WriteToPacket(&data); + lot->WriteToPacket(&data); + name->WriteToPacket(&data); + gmlevel->WriteToPacket(&data); + chatmode->WriteToPacket(&data); + xmlConfigData->WriteToPacket(&data); + reputation->WriteToPacket(&data); - delete objid; - delete lot; - delete xmlConfigData; - delete gmlevel; - delete chatmode; - delete name; - delete reputation; + delete objid; + delete lot; + delete xmlConfigData; + delete gmlevel; + delete chatmode; + delete name; + delete reputation; #ifdef _WIN32 - bitStream.Write(data.GetNumberOfBytesUsed() + 1); - bitStream.Write(0); - bitStream.Write((char*)data.GetData(), data.GetNumberOfBytesUsed()); + bitStream.Write(data.GetNumberOfBytesUsed() + 1); + bitStream.Write(0); + bitStream.Write((char*)data.GetData(), data.GetNumberOfBytesUsed()); #else - //Compress the data before sending: - const int reservedSize = 5 * 1024 * 1024; - uint8_t compressedData[reservedSize]; - size_t size = ZCompression::Compress(data.GetData(), data.GetNumberOfBytesUsed(), compressedData, reservedSize); + //Compress the data before sending: + const int reservedSize = 5 * 1024 * 1024; + uint8_t compressedData[reservedSize]; + size_t size = ZCompression::Compress(data.GetData(), data.GetNumberOfBytesUsed(), compressedData, reservedSize); - bitStream.Write(size + 9); //size of data + header bytes (8) - bitStream.Write(1); //compressed boolean, true - bitStream.Write(data.GetNumberOfBytesUsed()); - bitStream.Write(size); + bitStream.Write(size + 9); //size of data + header bytes (8) + bitStream.Write(1); //compressed boolean, true + bitStream.Write(data.GetNumberOfBytesUsed()); + bitStream.Write(size); - for (size_t i = 0; i < size; i++) - bitStream.Write(compressedData[i]); + for (size_t i = 0; i < size; i++) + bitStream.Write(compressedData[i]); #endif - PacketUtils::SavePacket("chardata.bin", (const char *)bitStream.GetData(), static_cast(bitStream.GetNumberOfBytesUsed())); - SEND_PACKET - Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu", entity->GetObjectID()); + PacketUtils::SavePacket("chardata.bin", (const char*)bitStream.GetData(), static_cast(bitStream.GetNumberOfBytesUsed())); + SEND_PACKET + Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu", entity->GetObjectID()); } void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector> unacceptedItems) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); + CBITSTREAM + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); - bitStream.Write(unacceptedItems.empty()); // Is sentence ok? - bitStream.Write(0x16); // Source ID, unknown + bitStream.Write(unacceptedItems.empty()); // Is sentence ok? + bitStream.Write(0x16); // Source ID, unknown - bitStream.Write(static_cast(requestID)); // request ID - bitStream.Write(static_cast(0)); // chat mode + bitStream.Write(static_cast(requestID)); // request ID + bitStream.Write(static_cast(0)); // chat mode - PacketUtils::WritePacketWString(receiver, 42, &bitStream); // receiver name + PacketUtils::WritePacketWString(receiver, 42, &bitStream); // receiver name - for (auto it : unacceptedItems) { - bitStream.Write(it.first); // start index - bitStream.Write(it.second); // length - } + for (auto it : unacceptedItems) { + bitStream.Write(it.first); // start index + bitStream.Write(it.second); // length + } - for (int i = unacceptedItems.size(); 64 > i; i++) { - bitStream.Write(0); - } + for (int i = unacceptedItems.size(); 64 > i; i++) { + bitStream.Write(0); + } - SEND_PACKET + SEND_PACKET } void WorldPackets::SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAKE_GM_RESPONSE); + CBITSTREAM + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAKE_GM_RESPONSE); - bitStream.Write(success); - bitStream.Write(highestLevel); - bitStream.Write(prevLevel); - bitStream.Write(newLevel); + bitStream.Write(success); + bitStream.Write(highestLevel); + bitStream.Write(prevLevel); + bitStream.Write(newLevel); - SEND_PACKET + SEND_PACKET } diff --git a/dNet/WorldPackets.h b/dNet/WorldPackets.h index b88602a4..d9951941 100644 --- a/dNet/WorldPackets.h +++ b/dNet/WorldPackets.h @@ -10,16 +10,16 @@ class User; struct SystemAddress; namespace WorldPackets { - void SendLoadStaticZone(const SystemAddress& sysAddr, float x, float y, float z, uint32_t checksum); - void SendCharacterList(const SystemAddress& sysAddr, User * user); + void SendLoadStaticZone(const SystemAddress& sysAddr, float x, float y, float z, uint32_t checksum); + void SendCharacterList(const SystemAddress& sysAddr, User* user); void SendCharacterCreationResponse(const SystemAddress& sysAddr, eCreationResponse response); void SendCharacterRenameResponse(const SystemAddress& sysAddr, eRenameResponse response); - void SendCharacterDeleteResponse(const SystemAddress& sysAddr, bool response); + void SendCharacterDeleteResponse(const SystemAddress& sysAddr, bool response); void SendTransferToWorld(const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift); void SendServerState(const SystemAddress& sysAddr); - void SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm); + void SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm); void SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector> unacceptedItems); - void SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel); + void SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel); } #endif // WORLDPACKETS_H diff --git a/dNet/ZoneInstanceManager.cpp b/dNet/ZoneInstanceManager.cpp index 9e7653a6..b57bb634 100644 --- a/dNet/ZoneInstanceManager.cpp +++ b/dNet/ZoneInstanceManager.cpp @@ -10,60 +10,58 @@ #include // Static Variables -ZoneInstanceManager * ZoneInstanceManager::m_Address = nullptr; +ZoneInstanceManager* ZoneInstanceManager::m_Address = nullptr; //! Requests a zone transfer void ZoneInstanceManager::RequestZoneTransfer(dServer* server, uint32_t zoneID, uint32_t zoneClone, bool mythranShift, std::function callback) { - - ZoneTransferRequest * request = new ZoneTransferRequest(); - request->requestID = ++currentRequestID; - request->callback = callback; - - this->requests.push_back(request); - - MasterPackets::SendZoneTransferRequest(server, request->requestID, mythranShift, zoneID, zoneClone); + + ZoneTransferRequest* request = new ZoneTransferRequest(); + request->requestID = ++currentRequestID; + request->callback = callback; + + this->requests.push_back(request); + + MasterPackets::SendZoneTransferRequest(server, request->requestID, mythranShift, zoneID, zoneClone); } //! Handles a zone transfer response -void ZoneInstanceManager::HandleRequestZoneTransferResponse(uint64_t requestID, Packet * packet) { - - bool mythranShift = static_cast(packet->data[16]); - uint32_t zoneID = PacketUtils::ReadPacketU32(17, packet); - uint32_t zoneInstance = PacketUtils::ReadPacketU32(21, packet); - uint32_t zoneClone = PacketUtils::ReadPacketU32(25, packet); - uint16_t serverPort = PacketUtils::ReadPacketU16(29, packet); - std::string serverIP = PacketUtils::ReadString(31, packet, false); - - for (uint32_t i = 0; i < this->requests.size(); ++i) { - if (this->requests[i]->requestID == requestID) { - - // Call the request callback - this->requests[i]->callback(mythranShift, zoneID, zoneInstance, zoneClone, serverIP, serverPort); - - delete this->requests[i]; - this->requests.erase(this->requests.begin() + i); - return; - } - } - +void ZoneInstanceManager::HandleRequestZoneTransferResponse(uint64_t requestID, Packet* packet) { + + bool mythranShift = static_cast(packet->data[16]); + uint32_t zoneID = PacketUtils::ReadPacketU32(17, packet); + uint32_t zoneInstance = PacketUtils::ReadPacketU32(21, packet); + uint32_t zoneClone = PacketUtils::ReadPacketU32(25, packet); + uint16_t serverPort = PacketUtils::ReadPacketU16(29, packet); + std::string serverIP = PacketUtils::ReadString(31, packet, false); + + for (uint32_t i = 0; i < this->requests.size(); ++i) { + if (this->requests[i]->requestID == requestID) { + + // Call the request callback + this->requests[i]->callback(mythranShift, zoneID, zoneInstance, zoneClone, serverIP, serverPort); + + delete this->requests[i]; + this->requests.erase(this->requests.begin() + i); + return; + } + } + } -void ZoneInstanceManager::CreatePrivateZone(dServer* server, uint32_t zoneID, uint32_t zoneClone, const std::string& password) -{ - MasterPackets::SendZoneCreatePrivate(server, zoneID, zoneClone, password); +void ZoneInstanceManager::CreatePrivateZone(dServer* server, uint32_t zoneID, uint32_t zoneClone, const std::string& password) { + MasterPackets::SendZoneCreatePrivate(server, zoneID, zoneClone, password); } void ZoneInstanceManager::RequestPrivateZone( - dServer* server, - bool mythranShift, + dServer* server, + bool mythranShift, const std::string& password, - std::function callback) -{ - ZoneTransferRequest* request = new ZoneTransferRequest(); - request->requestID = ++currentRequestID; - request->callback = callback; + std::function callback) { + ZoneTransferRequest* request = new ZoneTransferRequest(); + request->requestID = ++currentRequestID; + request->callback = callback; - this->requests.push_back(request); + this->requests.push_back(request); - MasterPackets::SendZoneRequestPrivate(server, request->requestID, mythranShift, password); + MasterPackets::SendZoneRequestPrivate(server, request->requestID, mythranShift, password); } diff --git a/dNet/ZoneInstanceManager.h b/dNet/ZoneInstanceManager.h index d81fe3c3..a8e32c4e 100644 --- a/dNet/ZoneInstanceManager.h +++ b/dNet/ZoneInstanceManager.h @@ -16,50 +16,50 @@ class dServer; \brief A class for handling zone transfers and zone-related functions */ -//! The zone request + //! The zone request struct ZoneTransferRequest { - uint64_t requestID; - std::function callback; + uint64_t requestID; + std::function callback; }; //! The zone manager class ZoneInstanceManager { private: - static ZoneInstanceManager * m_Address; //!< The singleton instance - - std::vector requests; //!< The zone transfer requests - uint64_t currentRequestID; //!< The current request ID - -public: - - //! The singleton method - static ZoneInstanceManager * Instance() { - if (m_Address == 0) { - m_Address = new ZoneInstanceManager; - m_Address->currentRequestID = 0; - } - - return m_Address; - } - - //! Requests a zone transfer - /*! - \param zoneID The zone ID - \param zoneClone The zone clone - \param mythranShift Whether or not this is a mythran shift - \param callback The callback function - */ - void RequestZoneTransfer(dServer* server, uint32_t zoneID, uint32_t zoneClone, bool mythranShift, std::function callback); - - //! Handles a zone transfer response - /*! - \param requestID The request ID - \param packet The packet - */ - void HandleRequestZoneTransferResponse(uint64_t requestID, Packet * packet); + static ZoneInstanceManager* m_Address; //!< The singleton instance - void CreatePrivateZone(dServer* server, uint32_t zoneID, uint32_t zoneClone, const std::string& password); - - void RequestPrivateZone(dServer* server, bool mythranShift, const std::string& password, std::function callback); + std::vector requests; //!< The zone transfer requests + uint64_t currentRequestID; //!< The current request ID + +public: + + //! The singleton method + static ZoneInstanceManager* Instance() { + if (m_Address == 0) { + m_Address = new ZoneInstanceManager; + m_Address->currentRequestID = 0; + } + + return m_Address; + } + + //! Requests a zone transfer + /*! + \param zoneID The zone ID + \param zoneClone The zone clone + \param mythranShift Whether or not this is a mythran shift + \param callback The callback function + */ + void RequestZoneTransfer(dServer* server, uint32_t zoneID, uint32_t zoneClone, bool mythranShift, std::function callback); + + //! Handles a zone transfer response + /*! + \param requestID The request ID + \param packet The packet + */ + void HandleRequestZoneTransferResponse(uint64_t requestID, Packet* packet); + + void CreatePrivateZone(dServer* server, uint32_t zoneID, uint32_t zoneClone, const std::string& password); + + void RequestPrivateZone(dServer* server, bool mythranShift, const std::string& password, std::function callback); }; diff --git a/dNet/dMessageIdentifiers.h b/dNet/dMessageIdentifiers.h index 4e88a9af..7dc08711 100644 --- a/dNet/dMessageIdentifiers.h +++ b/dNet/dMessageIdentifiers.h @@ -252,7 +252,7 @@ enum MASTER { MSG_MASTER_WORLD_READY, MSG_MASTER_PREP_ZONE, - + MSG_MASTER_SHUTDOWN, MSG_MASTER_SHUTDOWN_RESPONSE, MSG_MASTER_SHUTDOWN_IMMEDIATE, diff --git a/dNet/dNetCommon.h b/dNet/dNetCommon.h index 10103f3b..73a90bc0 100644 --- a/dNet/dNetCommon.h +++ b/dNet/dNetCommon.h @@ -3,4 +3,4 @@ #include "RakPeer.h" #define NET_PASSWORD_EXTERNAL "3.25 ND1" -#define NET_PASSWORD_INTERNAL "3.25 DARKFLAME1" \ No newline at end of file +#define NET_PASSWORD_INTERNAL "3.25 DARKFLAME1" diff --git a/dNet/dServer.cpp b/dNet/dServer.cpp index 56a73c1f..4c032f33 100644 --- a/dNet/dServer.cpp +++ b/dNet/dServer.cpp @@ -14,25 +14,25 @@ //! Replica Constructor class class ReplicaConstructor : public ReceiveConstructionInterface { public: - ReplicaReturnResult ReceiveConstruction(RakNet::BitStream *inBitStream, RakNetTime timestamp, NetworkID networkID, NetworkIDObject *existingObject, SystemAddress senderId, ReplicaManager *caller) { - return REPLICA_PROCESSING_DONE; - } + ReplicaReturnResult ReceiveConstruction(RakNet::BitStream* inBitStream, RakNetTime timestamp, NetworkID networkID, NetworkIDObject* existingObject, SystemAddress senderId, ReplicaManager* caller) { + return REPLICA_PROCESSING_DONE; + } } ConstructionCB; //! Replica Download Sender class class ReplicaSender : public SendDownloadCompleteInterface { public: - ReplicaReturnResult SendDownloadComplete(RakNet::BitStream *outBitStream, RakNetTime currentTime, SystemAddress senderId, ReplicaManager *caller) { - return REPLICA_PROCESSING_DONE; - } + ReplicaReturnResult SendDownloadComplete(RakNet::BitStream* outBitStream, RakNetTime currentTime, SystemAddress senderId, ReplicaManager* caller) { + return REPLICA_PROCESSING_DONE; + } } SendDownloadCompleteCB; //! Replica Download Receiver class class ReplicaReceiever : public ReceiveDownloadCompleteInterface { public: - ReplicaReturnResult ReceiveDownloadComplete(RakNet::BitStream *inBitStream, SystemAddress senderId, ReplicaManager *caller) { - return REPLICA_PROCESSING_DONE; - } + ReplicaReturnResult ReceiveDownloadComplete(RakNet::BitStream* inBitStream, SystemAddress senderId, ReplicaManager* caller) { + return REPLICA_PROCESSING_DONE; + } } ReceiveDownloadCompleteCB; dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnections, bool isInternal, bool useEncryption, dLogger* logger, const std::string masterIP, int masterPort, ServerType serverType, unsigned int zoneID) { @@ -63,8 +63,7 @@ dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnect mLogger->Log("dServer", "Server is listening on %s:%i with encryption: %i", ip.c_str(), port, int(useEncryption)); else mLogger->Log("dServer", "Server is listening on %s:%i with encryption: %i, running zone %i / %i", ip.c_str(), port, int(useEncryption), zoneID, instanceID); - } - else { mLogger->Log("dServer", "FAILED TO START SERVER ON IP/PORT: %s:%i", ip.c_str(), port); return; } + } else { mLogger->Log("dServer", "FAILED TO START SERVER ON IP/PORT: %s:%i", ip.c_str(), port); return; } mLogger->SetLogToConsole(prevLogSetting); @@ -110,7 +109,7 @@ Packet* dServer::ReceiveFromMaster() { } if (packet->data[0] == ID_CONNECTION_REQUEST_ACCEPTED) { - mLogger->Log("dServer", "Established connection to master, zone (%i), instance (%i)",this->GetZoneID(), this->GetInstanceID()); + mLogger->Log("dServer", "Established connection to master, zone (%i), instance (%i)", this->GetZoneID(), this->GetInstanceID()); mMasterConnectionActive = true; mMasterSystemAddress = packet->systemAddress; MasterPackets::SendServerInfo(this, packet); @@ -119,16 +118,16 @@ Packet* dServer::ReceiveFromMaster() { if (packet->data[0] == ID_USER_PACKET_ENUM) { if (packet->data[1] == MASTER) { switch (packet->data[3]) { - case MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE: { - uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); - ZoneInstanceManager::Instance()->HandleRequestZoneTransferResponse(requestID, packet); - break; - } + case MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE: { + uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); + ZoneInstanceManager::Instance()->HandleRequestZoneTransferResponse(requestID, packet); + break; + } - //When we handle these packets in World instead dServer, we just return the packet's pointer. - default: + //When we handle these packets in World instead dServer, we just return the packet's pointer. + default: - return packet; + return packet; } } } @@ -143,15 +142,15 @@ Packet* dServer::Receive() { return mPeer->Receive(); } -void dServer::DeallocatePacket(Packet * packet) { +void dServer::DeallocatePacket(Packet* packet) { mPeer->DeallocatePacket(packet); } -void dServer::DeallocateMasterPacket(Packet * packet) { +void dServer::DeallocateMasterPacket(Packet* packet) { mMasterPeer->DeallocatePacket(packet); } -void dServer::Send(RakNet::BitStream * bitStream, const SystemAddress & sysAddr, bool broadcast) { +void dServer::Send(RakNet::BitStream* bitStream, const SystemAddress& sysAddr, bool broadcast) { mPeer->Send(bitStream, SYSTEM_PRIORITY, RELIABLE_ORDERED, 0, sysAddr, broadcast); } @@ -182,8 +181,7 @@ bool dServer::Startup() { if (mIsInternal) { mPeer->SetIncomingPassword("3.25 DARKFLAME1", 15); - } - else { + } else { //mPeer->SetPerConnectionOutgoingBandwidthLimit(800000); //100Kb/s mPeer->SetIncomingPassword("3.25 ND1", 8); } @@ -228,12 +226,10 @@ void dServer::UpdateReplica() { mReplicaManager->Update(mPeer); } -int dServer::GetPing(const SystemAddress& sysAddr) const -{ +int dServer::GetPing(const SystemAddress& sysAddr) const { return mPeer->GetAveragePing(sysAddr); } -int dServer::GetLatestPing(const SystemAddress& sysAddr) const -{ +int dServer::GetLatestPing(const SystemAddress& sysAddr) const { return mPeer->GetLastPing(sysAddr); } diff --git a/dNet/dServer.h b/dNet/dServer.h index 3ac6700a..bd052f86 100644 --- a/dNet/dServer.h +++ b/dNet/dServer.h @@ -61,7 +61,7 @@ private: NetworkIDManager* mNetIDManager; SocketDescriptor mSocketDescriptor; std::string mIP; - int mPort; + int mPort; int mMaxConnections; unsigned int mZoneID; int mInstanceID; @@ -76,4 +76,4 @@ private: SystemAddress mMasterSystemAddress; std::string mMasterIP; int mMasterPort; -}; \ No newline at end of file +}; diff --git a/dPhysics/Singleton.h b/dPhysics/Singleton.h index b923202f..750a4996 100644 --- a/dPhysics/Singleton.h +++ b/dPhysics/Singleton.h @@ -16,4 +16,4 @@ public: protected: Singleton() = default; -}; \ No newline at end of file +}; diff --git a/dPhysics/dpCollisionChecks.cpp b/dPhysics/dpCollisionChecks.cpp index 5e18f894..c2efee90 100644 --- a/dPhysics/dpCollisionChecks.cpp +++ b/dPhysics/dpCollisionChecks.cpp @@ -54,7 +54,7 @@ bool dpCollisionChecks::CheckBoxes(dpEntity* a, dpEntity* b) { /*//Check if we're overlapping on X/Z: if ((boxA->GetMaxWidth() >= boxB->GetMinWidth()) && //If our max width is greater than starting X of b (boxA->GetMinWidth() <= boxB->GetMaxWidth()) && //If our start x is less than b's max width - (boxA->GetMaxDepth() >= boxB->GetMinDepth()) && + (boxA->GetMaxDepth() >= boxB->GetMinDepth()) && (boxA->GetMinDepth() <= boxB->GetMaxDepth())) { //Check if we're in the right height @@ -93,8 +93,7 @@ bool dpCollisionChecks::CheckSphereBox(dpEntity* a, dpEntity* b) { sphere = static_cast(b->GetShape()); boxPos = a->GetPosition(); spherePos = b->GetPosition(); - } - else { + } else { box = static_cast(b->GetShape()); sphere = static_cast(a->GetShape()); boxPos = b->GetPosition(); @@ -110,8 +109,8 @@ bool dpCollisionChecks::CheckSphereBox(dpEntity* a, dpEntity* b) { float dX = x - spherePos.x; float dY = y - spherePos.y; float dZ = z - spherePos.z; - float distanceSquared = (dX * dX) + (dY * dY) + (dZ * dZ); + float distanceSquared = (dX * dX) + (dY * dY) + (dZ * dZ); const float radius = sphere->GetRadius(); - return distanceSquared < radius * radius; + return distanceSquared < radius* radius; } diff --git a/dPhysics/dpCollisionChecks.h b/dPhysics/dpCollisionChecks.h index ed51bbe4..069832f9 100644 --- a/dPhysics/dpCollisionChecks.h +++ b/dPhysics/dpCollisionChecks.h @@ -9,4 +9,4 @@ namespace dpCollisionChecks { bool CheckBoxes(dpEntity* a, dpEntity* b); bool CheckSphereBox(dpEntity* a, dpEntity* b); -}; \ No newline at end of file +}; diff --git a/dPhysics/dpCollisionGroups.h b/dPhysics/dpCollisionGroups.h index 5853070f..ad9807b9 100644 --- a/dPhysics/dpCollisionGroups.h +++ b/dPhysics/dpCollisionGroups.h @@ -8,9 +8,9 @@ enum eCollisionGroup : uint8_t { - COLLISION_GROUP_ALL = 0 << 0, - COLLISION_GROUP_NEUTRAL = 1 << 0, - COLLISION_GROUP_FRIENDLY = 1 << 1, - COLLISION_GROUP_ENEMY = 1 << 2, - COLLISION_GROUP_DYNAMIC = 1 << 3, + COLLISION_GROUP_ALL = 0 << 0, + COLLISION_GROUP_NEUTRAL = 1 << 0, + COLLISION_GROUP_FRIENDLY = 1 << 1, + COLLISION_GROUP_ENEMY = 1 << 2, + COLLISION_GROUP_DYNAMIC = 1 << 3, }; diff --git a/dPhysics/dpCommon.h b/dPhysics/dpCommon.h index 344ad9c0..51583048 100644 --- a/dPhysics/dpCommon.h +++ b/dPhysics/dpCommon.h @@ -4,4 +4,4 @@ enum class dpShapeType : unsigned short { Invalid = 0, Sphere, Box -}; \ No newline at end of file +}; diff --git a/dPhysics/dpEntity.cpp b/dPhysics/dpEntity.cpp index 78920807..42c195f2 100644 --- a/dPhysics/dpEntity.cpp +++ b/dPhysics/dpEntity.cpp @@ -89,8 +89,7 @@ void dpEntity::CheckCollision(dpEntity* other) { //if (m_CollisionShape->GetShapeType() == dpShapeType::Sphere && other->GetShape()->GetShapeType() == dpShapeType::Sphere) //std::cout << "started sphere col at: " << other->GetPosition().x << ", " << other->GetPosition().y << ", " << other->GetPosition().z << std::endl; - } - else if (!isColliding && wasFound) { + } else if (!isColliding && wasFound) { m_CurrentlyCollidingObjects.erase(other->GetObjectID()); m_RemovedObjects.push_back(other); diff --git a/dPhysics/dpEntity.h b/dPhysics/dpEntity.h index cc363f8b..ea7a49b2 100644 --- a/dPhysics/dpEntity.h +++ b/dPhysics/dpEntity.h @@ -83,4 +83,4 @@ private: std::vector m_NewObjects; std::vector m_RemovedObjects; std::map m_CurrentlyCollidingObjects; -}; \ No newline at end of file +}; diff --git a/dPhysics/dpGrid.h b/dPhysics/dpGrid.h index 532ee02f..a10f165e 100644 --- a/dPhysics/dpGrid.h +++ b/dPhysics/dpGrid.h @@ -9,26 +9,26 @@ class dpEntity; class dpGrid { public: - //LU has a chunk size of 64x64, with each chunk unit being 3.2 ingame units. - int NUM_CELLS = 12; //Most worlds consist of 10 or 11 chunks, so I'm picking 12 to be safe. - int CELL_SIZE = 205; //64 * 3.2 = 204.8 rounded up + //LU has a chunk size of 64x64, with each chunk unit being 3.2 ingame units. + int NUM_CELLS = 12; //Most worlds consist of 10 or 11 chunks, so I'm picking 12 to be safe. + int CELL_SIZE = 205; //64 * 3.2 = 204.8 rounded up public: - dpGrid(int numCells, int cellSize); - ~dpGrid(); + dpGrid(int numCells, int cellSize); + ~dpGrid(); - void Add(dpEntity* entity); - void Move(dpEntity* entity, float x, float z); - void Delete(dpEntity* entity); + void Add(dpEntity* entity); + void Move(dpEntity* entity, float x, float z); + void Delete(dpEntity* entity); - void Update(float deltaTime); + void Update(float deltaTime); private: - void HandleEntity(dpEntity* entity, dpEntity* other); - void HandleCell(int x, int z, float deltaTime); + void HandleEntity(dpEntity* entity, dpEntity* other); + void HandleCell(int x, int z, float deltaTime); 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::map m_GargantuanObjects; + //cells on X, cells on Y for that X, then another vector that contains the entities within that cell. + std::vector>> m_Cells; + std::map m_GargantuanObjects; }; diff --git a/dPhysics/dpShapeBase.cpp b/dPhysics/dpShapeBase.cpp index c6562e71..54575159 100644 --- a/dPhysics/dpShapeBase.cpp +++ b/dPhysics/dpShapeBase.cpp @@ -3,8 +3,7 @@ #include dpShapeBase::dpShapeBase(dpEntity* parentEntity) : - m_ParentEntity(parentEntity) -{ + m_ParentEntity(parentEntity) { } dpShapeBase::~dpShapeBase() { @@ -14,4 +13,4 @@ bool dpShapeBase::IsColliding(dpShapeBase* other) { std::cout << "Base shapes do not have any *shape* to them, and thus cannot be overlapping." << std::endl; std::cout << "You should be using a shape class inherited from this base class." << std::endl; return false; -} \ No newline at end of file +} diff --git a/dPhysics/dpShapeBase.h b/dPhysics/dpShapeBase.h index 3bf52f50..60d908c9 100644 --- a/dPhysics/dpShapeBase.h +++ b/dPhysics/dpShapeBase.h @@ -17,4 +17,4 @@ public: protected: dpEntity* m_ParentEntity; dpShapeType m_ShapeType = dpShapeType::Invalid; -}; \ No newline at end of file +}; diff --git a/dPhysics/dpShapeBox.cpp b/dPhysics/dpShapeBox.cpp index 766ffb35..b40be6af 100644 --- a/dPhysics/dpShapeBox.cpp +++ b/dPhysics/dpShapeBox.cpp @@ -11,11 +11,10 @@ dpShapeBox::dpShapeBox(dpEntity* parentEntity, float width, float height, float depth) : dpShapeBase(parentEntity), - m_Width(width/2), - m_Height(height/2), - m_Depth(depth/2), - m_Scale(1.0f) -{ + m_Width(width / 2), + m_Height(height / 2), + m_Depth(depth / 2), + m_Scale(1.0f) { m_ShapeType = dpShapeType::Box; InitVertices(); diff --git a/dPhysics/dpShapeBox.h b/dPhysics/dpShapeBox.h index ec80012b..4af0396e 100644 --- a/dPhysics/dpShapeBox.h +++ b/dPhysics/dpShapeBox.h @@ -69,4 +69,4 @@ private: bool isTransformed = false; void InsertVertices(); -}; \ No newline at end of file +}; diff --git a/dPhysics/dpShapeSphere.cpp b/dPhysics/dpShapeSphere.cpp index bc1ceef5..168a3b21 100644 --- a/dPhysics/dpShapeSphere.cpp +++ b/dPhysics/dpShapeSphere.cpp @@ -4,8 +4,7 @@ dpShapeSphere::dpShapeSphere(dpEntity* parentEntity, float radius) : dpShapeBase(parentEntity), - m_Radius(radius) -{ + m_Radius(radius) { m_ShapeType = dpShapeType::Sphere; } diff --git a/dPhysics/dpShapeSphere.h b/dPhysics/dpShapeSphere.h index 3b23673a..a5d8142b 100644 --- a/dPhysics/dpShapeSphere.h +++ b/dPhysics/dpShapeSphere.h @@ -14,4 +14,4 @@ public: private: float m_Radius; -}; \ No newline at end of file +}; diff --git a/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index 4caaab40..666171c0 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -77,8 +77,7 @@ void dpWorld::RemoveEntity(dpEntity* entity) { if (m_Grid) { m_Grid->Delete(entity); - } - else { + } else { if (entity->GetIsStatic()) { for (size_t i = 0; i < m_StaticEntities.size(); ++i) { if (m_StaticEntities[i] == entity) { @@ -87,8 +86,7 @@ void dpWorld::RemoveEntity(dpEntity* entity) { break; } } - } - else { + } else { for (size_t i = 0; i < m_DynamicEntites.size(); ++i) { if (m_DynamicEntites[i] == entity) { delete m_DynamicEntites[i]; @@ -127,8 +125,7 @@ bool dpWorld::LoadNavmeshByZoneID(unsigned int zoneID) { std::string path = "./res/maps/navmeshes/" + std::to_string(zoneID) + ".bin"; m_navMesh = LoadNavmesh(path.c_str()); - if (m_navMesh) { m_navQuery = dtAllocNavMeshQuery(); m_navQuery->init(m_navMesh, 2048); } - else return false; + if (m_navMesh) { m_navQuery = dtAllocNavMeshQuery(); m_navQuery->init(m_navMesh, 2048); } else return false; return true; } @@ -136,14 +133,14 @@ bool dpWorld::LoadNavmeshByZoneID(unsigned int zoneID) { dtNavMesh* dpWorld::LoadNavmesh(const char* path) { FILE* fp; - #ifdef _WIN32 - fopen_s(&fp, path, "rb"); - #elif __APPLE__ - // macOS has 64bit file IO by default - fp = fopen(path, "rb"); - #else - fp = fopen64(path, "rb"); - #endif +#ifdef _WIN32 + fopen_s(&fp, path, "rb"); +#elif __APPLE__ + // macOS has 64bit file IO by default + fp = fopen(path, "rb"); +#else + fp = fopen64(path, "rb"); +#endif if (!fp) { return 0; @@ -347,8 +344,7 @@ std::vector dpWorld::GetPath(const NiPoint3& startPos, const NiPoint3& path.push_back(newPoint); } } - } - else { + } else { m_npolys = 0; m_nstraightPath = 0; } diff --git a/dPhysics/dpWorld.h b/dPhysics/dpWorld.h index 5897a7cd..5362803f 100644 --- a/dPhysics/dpWorld.h +++ b/dPhysics/dpWorld.h @@ -77,4 +77,4 @@ private: class dtNavMeshQuery* m_navQuery; unsigned char m_navMeshDrawFlags; rcContext* m_ctx; -}; \ No newline at end of file +}; diff --git a/dPhysics/main.cpp b/dPhysics/main.cpp index a4c303a3..7de1555a 100644 --- a/dPhysics/main.cpp +++ b/dPhysics/main.cpp @@ -32,4 +32,4 @@ int main() { } return 0; -}*/ \ No newline at end of file +}*/ diff --git a/dScripts/ActMine.cpp b/dScripts/ActMine.cpp index 9cc116b1..637bd805 100644 --- a/dScripts/ActMine.cpp +++ b/dScripts/ActMine.cpp @@ -8,8 +8,7 @@ void ActMine::OnStartup(Entity* self) { self->SetProximityRadius(MINE_RADIUS, "mineRadius"); } -void ActMine::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ +void ActMine::OnRebuildNotifyState(Entity* self, eRebuildState state) { if (state == eRebuildState::REBUILD_COMPLETED) { auto* rebuild = self->GetComponent(); if (rebuild) { @@ -35,7 +34,7 @@ void ActMine::OnProximityUpdate(Entity* self, Entity* entering, std::string name void ActMine::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "Tick") { - if (self->GetVar(u"NumWarnings") >= MAX_WARNINGS){ + if (self->GetVar(u"NumWarnings") >= MAX_WARNINGS) { auto* skill = self->GetComponent(); if (!skill) return; skill->CalculateBehavior(SKILL_ID, BEHAVIOR_ID, LWOOBJID_EMPTY); @@ -50,4 +49,4 @@ void ActMine::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "BlowedUp") { self->Kill(self); } -} \ No newline at end of file +} diff --git a/dScripts/ActMine.h b/dScripts/ActMine.h index ae6ef17e..fb222f2e 100644 --- a/dScripts/ActMine.h +++ b/dScripts/ActMine.h @@ -2,17 +2,17 @@ #include "CppScripts.h" class ActMine : public CppScripts::Script { - public: - void OnStartup(Entity* self) override; - void OnRebuildNotifyState(Entity* self, eRebuildState state) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnTimerDone(Entity* self, std::string timerName) override; - private: - int MAX_WARNINGS = 3; - float MINE_RADIUS = 10.0; - float TICK_TIME = 0.25; - float BLOWED_UP_TIME = 0.1; - uint32_t SKILL_ID = 317; - uint32_t BEHAVIOR_ID = 3719; +public: + void OnStartup(Entity* self) override; + void OnRebuildNotifyState(Entity* self, eRebuildState state) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnTimerDone(Entity* self, std::string timerName) override; +private: + int MAX_WARNINGS = 3; + float MINE_RADIUS = 10.0; + float TICK_TIME = 0.25; + float BLOWED_UP_TIME = 0.1; + uint32_t SKILL_ID = 317; + uint32_t BEHAVIOR_ID = 3719; }; diff --git a/dScripts/ActNinjaTurret.cpp b/dScripts/ActNinjaTurret.cpp index 8c361ad7..79e502b4 100644 --- a/dScripts/ActNinjaTurret.cpp +++ b/dScripts/ActNinjaTurret.cpp @@ -1,23 +1,17 @@ #include "ActNinjaTurret.h" -void ActNinjaTurret::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state == eRebuildState::REBUILD_COMPLETED) - { - self->SetVar(u"AmBuilt", true); - } - else if (state == eRebuildState::REBUILD_RESETTING) - { - self->SetVar(u"AmBuilt", false); - } +void ActNinjaTurret::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == eRebuildState::REBUILD_COMPLETED) { + self->SetVar(u"AmBuilt", true); + } else if (state == eRebuildState::REBUILD_RESETTING) { + self->SetVar(u"AmBuilt", false); + } } void -ActNinjaTurret::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) -{ - if (args == "ISpawned" && self->GetVar(u"AmBuilt")) - { - sender->Smash(); - } +ActNinjaTurret::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "ISpawned" && self->GetVar(u"AmBuilt")) { + sender->Smash(); + } } diff --git a/dScripts/ActNinjaTurret.h b/dScripts/ActNinjaTurret.h index 5251750a..d06e6afd 100644 --- a/dScripts/ActNinjaTurret.h +++ b/dScripts/ActNinjaTurret.h @@ -5,7 +5,7 @@ class ActNinjaTurret : public CppScripts::Script { public: void OnRebuildNotifyState(Entity* self, eRebuildState state) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/ActParadoxPipeFix.cpp b/dScripts/ActParadoxPipeFix.cpp index 2b592512..1dddde64 100644 --- a/dScripts/ActParadoxPipeFix.cpp +++ b/dScripts/ActParadoxPipeFix.cpp @@ -4,70 +4,58 @@ #include "GameMessages.h" #include "MissionComponent.h" -void ActParadoxPipeFix::OnRebuildComplete(Entity* self, Entity* target) -{ - const auto myGroup = "AllPipes"; +void ActParadoxPipeFix::OnRebuildComplete(Entity* self, Entity* target) { + const auto myGroup = "AllPipes"; - const auto groupObjs = EntityManager::Instance()->GetEntitiesInGroup(myGroup); + const auto groupObjs = EntityManager::Instance()->GetEntitiesInGroup(myGroup); - auto indexCount = 0; + auto indexCount = 0; - self->SetVar(u"PlayerID", target->GetObjectID()); + self->SetVar(u"PlayerID", target->GetObjectID()); - for (auto* object : groupObjs) - { - if (object == self) - { - continue; - } + for (auto* object : groupObjs) { + if (object == self) { + continue; + } - auto* rebuildComponent = object->GetComponent(); + auto* rebuildComponent = object->GetComponent(); - if (rebuildComponent->GetState() == REBUILD_COMPLETED) - { - indexCount++; - } - } + if (rebuildComponent->GetState() == REBUILD_COMPLETED) { + indexCount++; + } + } - if (indexCount >= 2) - { - const auto refinery = EntityManager::Instance()->GetEntitiesInGroup("Paradox"); + if (indexCount >= 2) { + const auto refinery = EntityManager::Instance()->GetEntitiesInGroup("Paradox"); - if (!refinery.empty()) - { - GameMessages::SendPlayFXEffect(refinery[0]->GetObjectID(), 3999, u"create", "pipeFX"); - } + if (!refinery.empty()) { + GameMessages::SendPlayFXEffect(refinery[0]->GetObjectID(), 3999, u"create", "pipeFX"); + } - for (auto* object : groupObjs) - { - auto* player = EntityManager::Instance()->GetEntity(object->GetVar(u"PlayerID")); + for (auto* object : groupObjs) { + auto* player = EntityManager::Instance()->GetEntity(object->GetVar(u"PlayerID")); - if (player != nullptr) - { - auto* missionComponent = player->GetComponent(); + if (player != nullptr) { + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->ForceProgressTaskType(769, 1, 1, false); - } + if (missionComponent != nullptr) { + missionComponent->ForceProgressTaskType(769, 1, 1, false); + } - GameMessages::SendPlayCinematic(player->GetObjectID(), u"ParadoxPipeFinish", player->GetSystemAddress(), true, true, false, false, 0, false, 2.0f); - } - - object->SetVar(u"PlayerID", LWOOBJID_EMPTY); - } - } + GameMessages::SendPlayCinematic(player->GetObjectID(), u"ParadoxPipeFinish", player->GetSystemAddress(), true, true, false, false, 0, false, 2.0f); + } + + object->SetVar(u"PlayerID", LWOOBJID_EMPTY); + } + } } -void ActParadoxPipeFix::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state == REBUILD_RESETTING) - { - const auto refinery = EntityManager::Instance()->GetEntitiesInGroup("Paradox"); +void ActParadoxPipeFix::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == REBUILD_RESETTING) { + const auto refinery = EntityManager::Instance()->GetEntitiesInGroup("Paradox"); - if (!refinery.empty()) - { - GameMessages::SendStopFXEffect(refinery[0], true, "pipeFX"); - } - } + if (!refinery.empty()) { + GameMessages::SendStopFXEffect(refinery[0], true, "pipeFX"); + } + } } diff --git a/dScripts/ActParadoxPipeFix.h b/dScripts/ActParadoxPipeFix.h index b8b19cc2..df323b00 100644 --- a/dScripts/ActParadoxPipeFix.h +++ b/dScripts/ActParadoxPipeFix.h @@ -4,7 +4,7 @@ class ActParadoxPipeFix : public CppScripts::Script { public: - void OnRebuildComplete(Entity* self, Entity* target) override; + void OnRebuildComplete(Entity* self, Entity* target) override; void OnRebuildNotifyState(Entity* self, eRebuildState state) override; }; diff --git a/dScripts/ActPlayerDeathTrigger.cpp b/dScripts/ActPlayerDeathTrigger.cpp index 0601e25d..28f1ef43 100644 --- a/dScripts/ActPlayerDeathTrigger.cpp +++ b/dScripts/ActPlayerDeathTrigger.cpp @@ -1,8 +1,7 @@ #include "ActPlayerDeathTrigger.h" -void ActPlayerDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) -{ +void ActPlayerDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) { if (!target->IsPlayer() || target->GetIsDead() || !target->GetPlayerReadyForUpdates()) return; //Don't kill already dead players or players not ready - - target->Smash(self->GetObjectID(), eKillType::SILENT); + + target->Smash(self->GetObjectID(), eKillType::SILENT); } diff --git a/dScripts/ActSharkPlayerDeathTrigger.cpp b/dScripts/ActSharkPlayerDeathTrigger.cpp index a8aaac8b..420fc4d7 100644 --- a/dScripts/ActSharkPlayerDeathTrigger.cpp +++ b/dScripts/ActSharkPlayerDeathTrigger.cpp @@ -3,8 +3,8 @@ #include "MissionTaskType.h" #include "Entity.h" -void ActSharkPlayerDeathTrigger::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { +void ActSharkPlayerDeathTrigger::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { if (args == "achieve") { auto missionComponent = sender->GetComponent(); if (!missionComponent) return; diff --git a/dScripts/ActSharkPlayerDeathTrigger.h b/dScripts/ActSharkPlayerDeathTrigger.h index cbd3c960..d76ae5be 100644 --- a/dScripts/ActSharkPlayerDeathTrigger.h +++ b/dScripts/ActSharkPlayerDeathTrigger.h @@ -4,7 +4,7 @@ class ActSharkPlayerDeathTrigger : public CppScripts::Script { public: - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/ActVehicleDeathTrigger.cpp b/dScripts/ActVehicleDeathTrigger.cpp index 9a970a35..77a3b65a 100644 --- a/dScripts/ActVehicleDeathTrigger.cpp +++ b/dScripts/ActVehicleDeathTrigger.cpp @@ -7,56 +7,46 @@ #include "PossessorComponent.h" -void ActVehicleDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) -{ - auto* possessableComponent = target->GetComponent(); +void ActVehicleDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) { + auto* possessableComponent = target->GetComponent(); - Entity* vehicle; - Entity* player; + Entity* vehicle; + Entity* player; - if (possessableComponent != nullptr) - { - auto* player = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); + if (possessableComponent != nullptr) { + auto* player = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - return; - } - else if (target->IsPlayer()) - { - auto* possessorComponent = target->GetComponent(); + return; + } else if (target->IsPlayer()) { + auto* possessorComponent = target->GetComponent(); - if (possessorComponent == nullptr) - { - return; - } + if (possessorComponent == nullptr) { + return; + } - vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); - if (vehicle == nullptr) - { - return; - } + if (vehicle == nullptr) { + return; + } - player = target; - } - else - { - return; - } - + player = target; + } else { + return; + } - GameMessages::SendDie(vehicle, self->GetObjectID(), LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, true, false, 0); - auto* zoneController = dZoneManager::Instance()->GetZoneControlObject(); + GameMessages::SendDie(vehicle, self->GetObjectID(), LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, true, false, 0); - auto* racingControlComponent = zoneController->GetComponent(); + auto* zoneController = dZoneManager::Instance()->GetZoneControlObject(); - if (racingControlComponent != nullptr) - { - racingControlComponent->OnRequestDie(player); - } + auto* racingControlComponent = zoneController->GetComponent(); + + if (racingControlComponent != nullptr) { + racingControlComponent->OnRequestDie(player); + } } diff --git a/dScripts/ActivityManager.cpp b/dScripts/ActivityManager.cpp index 56766482..18d72311 100644 --- a/dScripts/ActivityManager.cpp +++ b/dScripts/ActivityManager.cpp @@ -6,215 +6,212 @@ #include #include "dLogger.h" -bool ActivityManager::IsPlayerInActivity(Entity *self, LWOOBJID playerID) { - const auto* sac = self->GetComponent(); - return sac != nullptr && sac->IsPlayedBy(playerID); +bool ActivityManager::IsPlayerInActivity(Entity* self, LWOOBJID playerID) { + const auto* sac = self->GetComponent(); + return sac != nullptr && sac->IsPlayedBy(playerID); } -void ActivityManager::UpdatePlayer(Entity *self, LWOOBJID playerID, const bool remove) { - auto* sac = self->GetComponent(); - if (sac == nullptr) - return; +void ActivityManager::UpdatePlayer(Entity* self, LWOOBJID playerID, const bool remove) { + auto* sac = self->GetComponent(); + if (sac == nullptr) + return; - if (remove) { - sac->PlayerRemove(playerID); - } else { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - sac->PlayerJoin(player); - SetActivityScore(self, playerID, 0); - } - } + if (remove) { + sac->PlayerRemove(playerID); + } else { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + sac->PlayerJoin(player); + SetActivityScore(self, playerID, 0); + } + } } -void ActivityManager::SetActivityScore(Entity *self, LWOOBJID playerID, uint32_t score) { - SetActivityValue(self, playerID, 0, score); +void ActivityManager::SetActivityScore(Entity* self, LWOOBJID playerID, uint32_t score) { + SetActivityValue(self, playerID, 0, score); } -void ActivityManager::SetActivityValue(Entity *self, const LWOOBJID playerID, const uint32_t valueIndex, - const float_t value) { - auto* sac = self->GetComponent(); - if (sac == nullptr) - return; +void ActivityManager::SetActivityValue(Entity* self, const LWOOBJID playerID, const uint32_t valueIndex, + const float_t value) { + auto* sac = self->GetComponent(); + if (sac == nullptr) + return; - sac->SetActivityValue(playerID, valueIndex, value); + sac->SetActivityValue(playerID, valueIndex, value); } -float_t ActivityManager::GetActivityValue(Entity *self, const LWOOBJID playerID, const uint32_t valueIndex) { - auto* sac = self->GetComponent(); - if (sac == nullptr) - return -1.0f; +float_t ActivityManager::GetActivityValue(Entity* self, const LWOOBJID playerID, const uint32_t valueIndex) { + auto* sac = self->GetComponent(); + if (sac == nullptr) + return -1.0f; - return sac->GetActivityValue(playerID, valueIndex); + return sac->GetActivityValue(playerID, valueIndex); } -void ActivityManager::StopActivity(Entity *self, const LWOOBJID playerID, const uint32_t score, - const uint32_t value1, const uint32_t value2, bool quit) { - int32_t gameID = 0; +void ActivityManager::StopActivity(Entity* self, const LWOOBJID playerID, const uint32_t score, + const uint32_t value1, const uint32_t value2, bool quit) { + int32_t gameID = 0; - auto* sac = self->GetComponent(); - if (sac == nullptr) { - gameID = self->GetLOT(); - } - else { - gameID = sac->GetActivityID(); - } + auto* sac = self->GetComponent(); + if (sac == nullptr) { + gameID = self->GetLOT(); + } else { + gameID = sac->GetActivityID(); + } - if (quit) { - UpdatePlayer(self, playerID, true); - } else { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - return; + if (quit) { + UpdatePlayer(self, playerID, true); + } else { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + return; - SetActivityScore(self, playerID, score); - SetActivityValue(self, playerID, 1, value1); - SetActivityValue(self, playerID, 2, value2); + SetActivityScore(self, playerID, score); + SetActivityValue(self, playerID, 1, value1); + SetActivityValue(self, playerID, 2, value2); - LootGenerator::Instance().GiveActivityLoot(player, self, gameID, CalculateActivityRating(self, playerID)); + LootGenerator::Instance().GiveActivityLoot(player, self, gameID, CalculateActivityRating(self, playerID)); - // Save the new score to the leaderboard and show the leaderboard to the player - LeaderboardManager::SaveScore(playerID, gameID, score, value1); - const auto* leaderboard = LeaderboardManager::GetLeaderboard(gameID, InfoType::Standings, - false, player->GetObjectID()); - GameMessages::SendActivitySummaryLeaderboardData(self->GetObjectID(), leaderboard, player->GetSystemAddress()); - delete leaderboard; + // Save the new score to the leaderboard and show the leaderboard to the player + LeaderboardManager::SaveScore(playerID, gameID, score, value1); + const auto* leaderboard = LeaderboardManager::GetLeaderboard(gameID, InfoType::Standings, + false, player->GetObjectID()); + GameMessages::SendActivitySummaryLeaderboardData(self->GetObjectID(), leaderboard, player->GetSystemAddress()); + delete leaderboard; - // Makes the leaderboard show up for the player - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"ToggleLeaderBoard", - gameID,0, playerID, "", - player->GetSystemAddress()); + // Makes the leaderboard show up for the player + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"ToggleLeaderBoard", + gameID, 0, playerID, "", + player->GetSystemAddress()); - if (sac != nullptr) { - sac->PlayerRemove(player->GetObjectID()); - } - } + if (sac != nullptr) { + sac->PlayerRemove(player->GetObjectID()); + } + } } -bool ActivityManager::TakeActivityCost(const Entity *self, const LWOOBJID playerID) { - auto* sac = self->GetComponent(); - if (sac == nullptr) - return false; +bool ActivityManager::TakeActivityCost(const Entity* self, const LWOOBJID playerID) { + auto* sac = self->GetComponent(); + if (sac == nullptr) + return false; - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - return false; + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + return false; - return sac->TakeCost(player); + return sac->TakeCost(player); } -uint32_t ActivityManager::CalculateActivityRating(Entity *self, const LWOOBJID playerID) { - auto* sac = self->GetComponent(); - if (sac == nullptr) - return 0; +uint32_t ActivityManager::CalculateActivityRating(Entity* self, const LWOOBJID playerID) { + auto* sac = self->GetComponent(); + if (sac == nullptr) + return 0; - return sac->GetInstance(playerID)->GetParticipants().size(); + return sac->GetInstance(playerID)->GetParticipants().size(); } uint32_t ActivityManager::GetActivityID(const Entity* self) { - auto* sac = self->GetComponent(); - return sac != nullptr ? sac->GetActivityID() : 0; + auto* sac = self->GetComponent(); + return sac != nullptr ? sac->GetActivityID() : 0; } -void ActivityManager::GetLeaderboardData(Entity *self, const LWOOBJID playerID, const uint32_t activityID, uint32_t numResults) { - LeaderboardManager::SendLeaderboard(activityID, Standings, false, self->GetObjectID(), playerID); +void ActivityManager::GetLeaderboardData(Entity* self, const LWOOBJID playerID, const uint32_t activityID, uint32_t numResults) { + LeaderboardManager::SendLeaderboard(activityID, Standings, false, self->GetObjectID(), playerID); } -void ActivityManager::ActivityTimerStart(Entity *self, const std::string& timerName, const float_t updateInterval, - const float_t stopTime) { - auto* timer = new ActivityTimer { timerName, updateInterval, stopTime }; - activeTimers.push_back(timer); +void ActivityManager::ActivityTimerStart(Entity* self, const std::string& timerName, const float_t updateInterval, + const float_t stopTime) { + auto* timer = new ActivityTimer{ timerName, updateInterval, stopTime }; + activeTimers.push_back(timer); - Game::logger->Log("ActivityManager", "Starting timer '%s', %f, %f", timerName.c_str(), updateInterval, stopTime); + Game::logger->Log("ActivityManager", "Starting timer '%s', %f, %f", timerName.c_str(), updateInterval, stopTime); - self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); + self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); } void ActivityManager::ActivityTimerStopAllTimers(Entity* self) { - for (auto* timer : activeTimers) { - self->CancelTimer(GetPrefixedName(timer->name)); - delete timer; - } + for (auto* timer : activeTimers) { + self->CancelTimer(GetPrefixedName(timer->name)); + delete timer; + } - activeTimers.clear(); + activeTimers.clear(); } -float_t ActivityManager::ActivityTimerGetCurrentTime(Entity *self, const std::string &timerName) const { - auto* timer = GetTimer(timerName); - return timer != nullptr ? timer->runTime : 0.0f; +float_t ActivityManager::ActivityTimerGetCurrentTime(Entity* self, const std::string& timerName) const { + auto* timer = GetTimer(timerName); + return timer != nullptr ? timer->runTime : 0.0f; } -int32_t ActivityManager::GetGameID(Entity *self) const -{ - int32_t gameID = 0; +int32_t ActivityManager::GetGameID(Entity* self) const { + int32_t gameID = 0; - auto* sac = self->GetComponent(); - if (sac == nullptr) { - gameID = self->GetLOT(); - } - else { - gameID = sac->GetActivityID(); - } + auto* sac = self->GetComponent(); + if (sac == nullptr) { + gameID = self->GetLOT(); + } else { + gameID = sac->GetActivityID(); + } - return gameID; + return gameID; } -float_t ActivityManager::ActivityTimerGetRemainingTime(Entity *self, const std::string &timerName) const { - auto* timer = GetTimer(timerName); - return timer != nullptr ? std::min(timer->stopTime - timer->runTime, 0.0f) : 0.0f; +float_t ActivityManager::ActivityTimerGetRemainingTime(Entity* self, const std::string& timerName) const { + auto* timer = GetTimer(timerName); + return timer != nullptr ? std::min(timer->stopTime - timer->runTime, 0.0f) : 0.0f; } -void ActivityManager::ActivityTimerReset(Entity *self, const std::string &timerName) { - auto* timer = GetTimer(timerName); - if (timer != nullptr) { - timer->runTime = 0.0f; - } +void ActivityManager::ActivityTimerReset(Entity* self, const std::string& timerName) { + auto* timer = GetTimer(timerName); + if (timer != nullptr) { + timer->runTime = 0.0f; + } } -ActivityTimer* ActivityManager::GetTimer(const std::string &name) const { - for (auto* timer : activeTimers) { - if (timer->name == name) - return timer; - } +ActivityTimer* ActivityManager::GetTimer(const std::string& name) const { + for (auto* timer : activeTimers) { + if (timer->name == name) + return timer; + } - return nullptr; + return nullptr; } -void ActivityManager::ActivityTimerStop(Entity *self, const std::string &timerName) { - auto* timer = GetTimer(timerName); - if (timer != nullptr) { - self->CancelTimer(GetPrefixedName(timer->name)); +void ActivityManager::ActivityTimerStop(Entity* self, const std::string& timerName) { + auto* timer = GetTimer(timerName); + if (timer != nullptr) { + self->CancelTimer(GetPrefixedName(timer->name)); - activeTimers.erase(std::remove(activeTimers.begin(), activeTimers.end(), timer), - activeTimers.end()); - delete timer; - } + activeTimers.erase(std::remove(activeTimers.begin(), activeTimers.end(), timer), + activeTimers.end()); + delete timer; + } } -std::string ActivityManager::GetPrefixedName(const std::string &name) const { - return TimerPrefix + "_" + name; +std::string ActivityManager::GetPrefixedName(const std::string& name) const { + return TimerPrefix + "_" + name; } -void ActivityManager::OnTimerDone(Entity *self, std::string timerName) { - auto nameSplit = GeneralUtils::SplitString(timerName, '_'); - if (nameSplit.size() > 1 && nameSplit.at(0) == TimerPrefix) { - const auto& activityTimerName = nameSplit.at(1); - auto* timer = GetTimer(activityTimerName); +void ActivityManager::OnTimerDone(Entity* self, std::string timerName) { + auto nameSplit = GeneralUtils::SplitString(timerName, '_'); + if (nameSplit.size() > 1 && nameSplit.at(0) == TimerPrefix) { + const auto& activityTimerName = nameSplit.at(1); + auto* timer = GetTimer(activityTimerName); - if (timer != nullptr) { - timer->runTime += timer->updateInterval; + if (timer != nullptr) { + timer->runTime += timer->updateInterval; - if (timer->stopTime != -1.0f && timer->runTime >= timer->stopTime) { - activeTimers.erase(std::remove(activeTimers.begin(), activeTimers.end(), timer), - activeTimers.end()); - delete timer; - Game::logger->Log("ActivityManager", "Executing timer '%s'", activityTimerName.c_str()); - OnActivityTimerDone(self, activityTimerName); - } else { - Game::logger->Log("ActivityManager", "Updating timer '%s'", activityTimerName.c_str()); - OnActivityTimerUpdate(self, timer->name, timer->stopTime - timer->runTime, timer->runTime); - self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); - } - } - } + if (timer->stopTime != -1.0f && timer->runTime >= timer->stopTime) { + activeTimers.erase(std::remove(activeTimers.begin(), activeTimers.end(), timer), + activeTimers.end()); + delete timer; + Game::logger->Log("ActivityManager", "Executing timer '%s'", activityTimerName.c_str()); + OnActivityTimerDone(self, activityTimerName); + } else { + Game::logger->Log("ActivityManager", "Updating timer '%s'", activityTimerName.c_str()); + OnActivityTimerUpdate(self, timer->name, timer->stopTime - timer->runTime, timer->runTime); + self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); + } + } + } } diff --git a/dScripts/ActivityManager.h b/dScripts/ActivityManager.h index 3b5783ad..640cf4bf 100644 --- a/dScripts/ActivityManager.h +++ b/dScripts/ActivityManager.h @@ -2,41 +2,41 @@ #include "CppScripts.h" struct ActivityTimer { - std::string name; - float_t updateInterval; - float_t stopTime; - float_t runTime = 0; + std::string name; + float_t updateInterval; + float_t stopTime; + float_t runTime = 0; }; class ActivityManager : public CppScripts::Script { public: - static bool IsPlayerInActivity(Entity *self, LWOOBJID playerID); - static void UpdatePlayer(Entity *self, LWOOBJID playerID, bool remove = false); - static void SetActivityScore(Entity *self, LWOOBJID playerID, uint32_t score); - static void SetActivityValue(Entity *self, LWOOBJID playerID, uint32_t valueIndex, float_t value); - static float_t GetActivityValue(Entity *self, LWOOBJID playerID, uint32_t valueIndex) ; - static bool TakeActivityCost(const Entity* self, LWOOBJID playerID); - static uint32_t GetActivityID(const Entity* self); - void StopActivity(Entity *self, LWOOBJID playerID, uint32_t score, uint32_t value1 = 0, uint32_t value2 = 0, bool quit = false); - virtual uint32_t CalculateActivityRating(Entity* self, LWOOBJID playerID); - static void GetLeaderboardData(Entity *self, LWOOBJID playerID, uint32_t activityID, uint32_t numResults = 0); -// void FreezePlayer(Entity *self, const LWOOBJID playerID, const bool state) const; + static bool IsPlayerInActivity(Entity* self, LWOOBJID playerID); + static void UpdatePlayer(Entity* self, LWOOBJID playerID, bool remove = false); + static void SetActivityScore(Entity* self, LWOOBJID playerID, uint32_t score); + static void SetActivityValue(Entity* self, LWOOBJID playerID, uint32_t valueIndex, float_t value); + static float_t GetActivityValue(Entity* self, LWOOBJID playerID, uint32_t valueIndex); + static bool TakeActivityCost(const Entity* self, LWOOBJID playerID); + static uint32_t GetActivityID(const Entity* self); + void StopActivity(Entity* self, LWOOBJID playerID, uint32_t score, uint32_t value1 = 0, uint32_t value2 = 0, bool quit = false); + virtual uint32_t CalculateActivityRating(Entity* self, LWOOBJID playerID); + static void GetLeaderboardData(Entity* self, LWOOBJID playerID, uint32_t activityID, uint32_t numResults = 0); + // void FreezePlayer(Entity *self, const LWOOBJID playerID, const bool state) const; - // Activity timer - void OnTimerDone(Entity *self, std::string timerName) override; - virtual void OnActivityTimerDone(Entity* self, const std::string& name) {}; - virtual void OnActivityTimerUpdate(Entity* self, const std::string& name, float_t timeRemaining, float_t elapsedTime) {}; - void ActivityTimerStart(Entity *self, const std::string& timerName, float_t updateInterval, float_t stopTime = -1.0f); - void ActivityTimerReset(Entity *self, const std::string& timerName); - void ActivityTimerStop(Entity* self, const std::string& timerName); - void ActivityTimerStopAllTimers(Entity* self); - float_t ActivityTimerGetRemainingTime(Entity *self, const std::string& timerName) const; - float_t ActivityTimerGetCurrentTime(Entity *self, const std::string& timerName) const; - int32_t GetGameID(Entity* self) const; + // Activity timer + void OnTimerDone(Entity* self, std::string timerName) override; + virtual void OnActivityTimerDone(Entity* self, const std::string& name) {}; + virtual void OnActivityTimerUpdate(Entity* self, const std::string& name, float_t timeRemaining, float_t elapsedTime) {}; + void ActivityTimerStart(Entity* self, const std::string& timerName, float_t updateInterval, float_t stopTime = -1.0f); + void ActivityTimerReset(Entity* self, const std::string& timerName); + void ActivityTimerStop(Entity* self, const std::string& timerName); + void ActivityTimerStopAllTimers(Entity* self); + float_t ActivityTimerGetRemainingTime(Entity* self, const std::string& timerName) const; + float_t ActivityTimerGetCurrentTime(Entity* self, const std::string& timerName) const; + int32_t GetGameID(Entity* self) const; private: - std::string GetPrefixedName(const std::string& name) const; - [[nodiscard]] ActivityTimer* GetTimer(const std::string& name) const; - std::vector activeTimers {}; + std::string GetPrefixedName(const std::string& name) const; + [[nodiscard]] ActivityTimer* GetTimer(const std::string& name) const; + std::vector activeTimers{}; - std::string TimerPrefix = "ActivityTimer"; + std::string TimerPrefix = "ActivityTimer"; }; diff --git a/dScripts/AgBugsprayer.cpp b/dScripts/AgBugsprayer.cpp index cfea5cf4..d4ab7aa3 100644 --- a/dScripts/AgBugsprayer.cpp +++ b/dScripts/AgBugsprayer.cpp @@ -1,20 +1,17 @@ #include "AgBugsprayer.h" #include "SkillComponent.h" -void AgBugsprayer::OnRebuildComplete(Entity* self, Entity* target) -{ - self->AddTimer("castSkill", 1); - self->SetOwnerOverride(target->GetObjectID()); +void AgBugsprayer::OnRebuildComplete(Entity* self, Entity* target) { + self->AddTimer("castSkill", 1); + self->SetOwnerOverride(target->GetObjectID()); } -void AgBugsprayer::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "castSkill") - { - auto* skillComponent = self->GetComponent(); - - if (skillComponent == nullptr) return; +void AgBugsprayer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "castSkill") { + auto* skillComponent = self->GetComponent(); - skillComponent->CalculateBehavior(1435, 36581, LWOOBJID_EMPTY); - } -} \ No newline at end of file + if (skillComponent == nullptr) return; + + skillComponent->CalculateBehavior(1435, 36581, LWOOBJID_EMPTY); + } +} diff --git a/dScripts/AgBugsprayer.h b/dScripts/AgBugsprayer.h index 711fe708..055feb36 100644 --- a/dScripts/AgBugsprayer.h +++ b/dScripts/AgBugsprayer.h @@ -5,6 +5,6 @@ class AgBugsprayer : public CppScripts::Script { public: void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/AgBusDoor.cpp b/dScripts/AgBusDoor.cpp index 4453fcad..4910d0c5 100644 --- a/dScripts/AgBusDoor.cpp +++ b/dScripts/AgBusDoor.cpp @@ -23,14 +23,12 @@ void AgBusDoor::OnProximityUpdate(Entity* self, Entity* entering, std::string na m_Counter = 0; m_OuterCounter = 0; - for (const auto& pair : proximityMonitorComponent->GetProximityObjects("busDoor")) - { + for (const auto& pair : proximityMonitorComponent->GetProximityObjects("busDoor")) { auto* entity = EntityManager::Instance()->GetEntity(pair.first); if (entity != nullptr && entity->IsPlayer()) m_Counter++; } - for (const auto& pair : proximityMonitorComponent->GetProximityObjects("busDoorOuter")) - { + for (const auto& pair : proximityMonitorComponent->GetProximityObjects("busDoorOuter")) { auto* entity = EntityManager::Instance()->GetEntity(pair.first); if (entity != nullptr && entity->IsPlayer()) m_OuterCounter++; } @@ -40,8 +38,7 @@ void AgBusDoor::OnProximityUpdate(Entity* self, Entity* entering, std::string na if (m_Counter > 0) { MoveDoor(self, true); } - } - else if (status == "LEAVE") { + } else if (status == "LEAVE") { // move down when no players are inside either radii if (m_Counter <= 0) { MoveDoor(self, false); @@ -52,13 +49,12 @@ void AgBusDoor::OnProximityUpdate(Entity* self, Entity* entering, std::string na void AgBusDoor::MoveDoor(Entity* self, bool bOpen) { if (bOpen) { GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 1, 0); - } - else { + } else { GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, 1); self->AddTimer("dustTimer", 2.0f); } - //This is currently commented out because it might be the reason that people's audio is cutting out. + //This is currently commented out because it might be the reason that people's audio is cutting out. GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, "{9a24f1fa-3177-4745-a2df-fbd996d6e1e3}"); } @@ -66,4 +62,4 @@ void AgBusDoor::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "dustTimer") { GameMessages::SendPlayFXEffect(self->GetObjectID(), 642, u"create", "busDust", LWOOBJID_EMPTY, 1.0f, 1.0f, true); } -} \ No newline at end of file +} diff --git a/dScripts/AgCagedBricksServer.cpp b/dScripts/AgCagedBricksServer.cpp index ec9f5306..6d1360de 100644 --- a/dScripts/AgCagedBricksServer.cpp +++ b/dScripts/AgCagedBricksServer.cpp @@ -20,9 +20,8 @@ void AgCagedBricksServer::OnUse(Entity* self, Entity* user) { //Remove the maelstrom cube: auto inv = static_cast(user->GetComponent(COMPONENT_TYPE_INVENTORY)); - - if (inv) - { + + if (inv) { inv->RemoveItem(14553, 1); } } diff --git a/dScripts/AgCagedBricksServer.h b/dScripts/AgCagedBricksServer.h index 4ec128ac..27ce9e70 100644 --- a/dScripts/AgCagedBricksServer.h +++ b/dScripts/AgCagedBricksServer.h @@ -3,4 +3,4 @@ class AgCagedBricksServer : public CppScripts::Script { void OnUse(Entity* self, Entity* user); -}; \ No newline at end of file +}; diff --git a/dScripts/AgDarkSpiderling.cpp b/dScripts/AgDarkSpiderling.cpp index 55ef62ec..5dbd350a 100644 --- a/dScripts/AgDarkSpiderling.cpp +++ b/dScripts/AgDarkSpiderling.cpp @@ -1,9 +1,9 @@ #include "AgDarkSpiderling.h" #include "BaseCombatAIComponent.h" -void AgDarkSpiderling::OnStartup(Entity *self) { - auto* combatAI = self->GetComponent(); - if (combatAI != nullptr) { - combatAI->SetStunImmune(true); - } +void AgDarkSpiderling::OnStartup(Entity* self) { + auto* combatAI = self->GetComponent(); + if (combatAI != nullptr) { + combatAI->SetStunImmune(true); + } } diff --git a/dScripts/AgDarkSpiderling.h b/dScripts/AgDarkSpiderling.h index fe680f9c..8797812c 100644 --- a/dScripts/AgDarkSpiderling.h +++ b/dScripts/AgDarkSpiderling.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class AgDarkSpiderling : public CppScripts::Script { - void OnStartup(Entity *self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/AgFans.cpp b/dScripts/AgFans.cpp index dbc09547..27d3b940 100644 --- a/dScripts/AgFans.cpp +++ b/dScripts/AgFans.cpp @@ -29,7 +29,7 @@ void AgFans::ToggleFX(Entity* self, bool hit) { if (renderComponent == nullptr) { return; } - + if (fanVolumes.size() == 0 || !self->GetVar(u"alive")) return; if (self->GetVar(u"on")) { @@ -37,7 +37,7 @@ void AgFans::ToggleFX(Entity* self, bool hit) { renderComponent->StopEffect("fanOn"); self->SetVar(u"on", false); - + for (Entity* volume : fanVolumes) { PhantomPhysicsComponent* volumePhys = static_cast(volume->GetComponent(COMPONENT_TYPE_PHANTOM_PHYSICS)); if (!volumePhys) continue; @@ -48,8 +48,7 @@ void AgFans::ToggleFX(Entity* self, bool hit) { GameMessages::SendPlayAnimation(fxObj, u"trigger"); } } - } - else if (!self->GetVar(u"on") && self->GetVar(u"alive")) { + } else if (!self->GetVar(u"on") && self->GetVar(u"alive")) { GameMessages::SendPlayAnimation(self, u"fan-on"); renderComponent->PlayEffect(495, u"fanOn", "fanOn"); @@ -68,8 +67,8 @@ void AgFans::ToggleFX(Entity* self, bool hit) { } } -void AgFans::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { +void AgFans::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { if (args.length() == 0 || !self->GetVar(u"alive")) return; if ((args == "turnOn" && self->GetVar(u"on")) || (args == "turnOff" && !self->GetVar(u"on"))) return; @@ -81,4 +80,4 @@ void AgFans::OnDie(Entity* self, Entity* killer) { ToggleFX(self, true); } self->SetVar(u"alive", false); -} \ No newline at end of file +} diff --git a/dScripts/AgFans.h b/dScripts/AgFans.h index 800267af..01f919d1 100644 --- a/dScripts/AgFans.h +++ b/dScripts/AgFans.h @@ -7,8 +7,8 @@ public: void OnStartup(Entity* self) override; void OnDie(Entity* self, Entity* killer) override; void OnFireEventServerSide( - Entity *self, - Entity *sender, + Entity* self, + Entity* sender, std::string args, int32_t param1, int32_t param2, diff --git a/dScripts/AgImagSmashable.h b/dScripts/AgImagSmashable.h index fd047c34..1cea25b9 100644 --- a/dScripts/AgImagSmashable.h +++ b/dScripts/AgImagSmashable.h @@ -6,4 +6,4 @@ public: void OnDie(Entity* self, Entity* killer); private: void CrateAnimal(Entity* self); -}; \ No newline at end of file +}; diff --git a/dScripts/AgJetEffectServer.cpp b/dScripts/AgJetEffectServer.cpp index 7336c8b8..748b947b 100644 --- a/dScripts/AgJetEffectServer.cpp +++ b/dScripts/AgJetEffectServer.cpp @@ -3,10 +3,8 @@ #include "EntityManager.h" #include "SkillComponent.h" -void AgJetEffectServer::OnUse(Entity* self, Entity* user) -{ - if (inUse) - { +void AgJetEffectServer::OnUse(Entity* self, Entity* user) { + if (inUse) { return; } @@ -24,8 +22,7 @@ void AgJetEffectServer::OnUse(Entity* self, Entity* user) auto entities = EntityManager::Instance()->GetEntitiesInGroup("Jet_FX"); - if (entities.empty()) - { + if (entities.empty()) { return; } @@ -37,12 +34,10 @@ void AgJetEffectServer::OnUse(Entity* self, Entity* user) self->AddTimer("CineDone", 9); } -void AgJetEffectServer::OnRebuildComplete(Entity* self, Entity* target) -{ +void AgJetEffectServer::OnRebuildComplete(Entity* self, Entity* target) { auto entities = EntityManager::Instance()->GetEntitiesInGroup("Jet_FX"); - if (entities.empty()) - { + if (entities.empty()) { return; } @@ -50,8 +45,7 @@ void AgJetEffectServer::OnRebuildComplete(Entity* self, Entity* target) auto groups = self->GetGroups(); - if (groups.empty()) - { + if (groups.empty()) { return; } @@ -63,34 +57,28 @@ void AgJetEffectServer::OnRebuildComplete(Entity* self, Entity* target) self->AddTimer("PlayEffect", 2.5f); - if (group == "Base_Radar") - { + if (group == "Base_Radar") { self->AddTimer("CineDone", 5); } } -void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "radarDish") - { +void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "radarDish") { GameMessages::SendStopFXEffect(self, true, "radarDish"); return; } - if (timerName == "PlayEffect") - { + if (timerName == "PlayEffect") { auto entities = EntityManager::Instance()->GetEntitiesInGroup("mortarMain"); - if (entities.empty()) - { + if (entities.empty()) { return; } const auto size = entities.size(); - if (size == 0) - { + if (size == 0) { return; } @@ -103,8 +91,7 @@ void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) mortar->SetOwnerOverride(builder); SkillComponent* skillComponent; - if (!mortar->TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) - { + if (!mortar->TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) { return; } @@ -113,8 +100,7 @@ void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) return; } - if (timerName == "CineDone") - { + if (timerName == "CineDone") { GameMessages::SendNotifyClientObject( self->GetObjectID(), u"toggleInUse", diff --git a/dScripts/AgLaserSensorServer.cpp b/dScripts/AgLaserSensorServer.cpp index 342cc7e1..9efae1ca 100644 --- a/dScripts/AgLaserSensorServer.cpp +++ b/dScripts/AgLaserSensorServer.cpp @@ -13,7 +13,7 @@ void AgLaserSensorServer::OnStartup(Entity* self) { physComp->SetEffectType(2); // repulse (prolly should make definitions of these are in Entity.cpp) physComp->SetDirectionalMultiplier(static_cast(m_RepelForce)); physComp->SetDirection(NiPoint3::UNIT_Y); - + m_Skill = self->GetComponent(); } @@ -36,16 +36,13 @@ void AgLaserSensorServer::OnCollisionPhantom(Entity* self, Entity* target) { if (obj == 76690936093053 && Vector3::DistanceSquared(source, NiPoint3(149.007f, 417.083f, 218.346f)) <= 1.0f) { laser = script; break; - } - else if (obj == 75866302318824 && Vector3::DistanceSquared(source, NiPoint3(48.6403f, 403.803f, 196.711f)) <= 1.0f) { + } else if (obj == 75866302318824 && Vector3::DistanceSquared(source, NiPoint3(48.6403f, 403.803f, 196.711f)) <= 1.0f) { laser = script; break; - } - else if (obj == 75866302318822 && Vector3::DistanceSquared(source, NiPoint3(19.2155f, 420.083f, 249.226f)) <= 1.0f) { + } else if (obj == 75866302318822 && Vector3::DistanceSquared(source, NiPoint3(19.2155f, 420.083f, 249.226f)) <= 1.0f) { laser = script; break; - } - else if (obj == 75866302318823 && Vector3::DistanceSquared(source, NiPoint3(-6.61596f, 404.633f, 274.323f)) <= 1.0f) { + } else if (obj == 75866302318823 && Vector3::DistanceSquared(source, NiPoint3(-6.61596f, 404.633f, 274.323f)) <= 1.0f) { laser = script; break; } diff --git a/dScripts/AgMonumentBirds.cpp b/dScripts/AgMonumentBirds.cpp index 5870cfff..ad3417a4 100644 --- a/dScripts/AgMonumentBirds.cpp +++ b/dScripts/AgMonumentBirds.cpp @@ -28,6 +28,6 @@ void AgMonumentBirds::OnTimerDone(Entity* self, std::string timerName) { auto* player = EntityManager::Instance()->GetEntity(self->GetVar(u"PlayerID")); if (player == nullptr) return; - + self->ScheduleKillAfterUpdate(player); } diff --git a/dScripts/AgMonumentLaserServer.cpp b/dScripts/AgMonumentLaserServer.cpp index 646ca998..6efda89e 100644 --- a/dScripts/AgMonumentLaserServer.cpp +++ b/dScripts/AgMonumentLaserServer.cpp @@ -3,7 +3,7 @@ void AgMonumentLaserServer::OnStartup(Entity* self) { /* self->SetProximityRadius(m_Radius, "MonumentLaser"); - + std::cout << "Monument Laser " << self->GetObjectID() << " is at " << self->GetPosition().GetX() << ","<< self->GetPosition().GetY() << "," << self->GetPosition().GetZ() << std::endl; */ diff --git a/dScripts/AgMonumentRaceCancel.cpp b/dScripts/AgMonumentRaceCancel.cpp index 205aee57..2e744434 100644 --- a/dScripts/AgMonumentRaceCancel.cpp +++ b/dScripts/AgMonumentRaceCancel.cpp @@ -1,9 +1,9 @@ #include "AgMonumentRaceCancel.h" #include "EntityManager.h" -void AgMonumentRaceCancel::OnCollisionPhantom(Entity *self, Entity *target) { - auto managers = EntityManager::Instance()->GetEntitiesInGroup("race_manager"); - if (!managers.empty()) { - managers[0]->OnFireEventServerSide(target, "course_cancel"); - } +void AgMonumentRaceCancel::OnCollisionPhantom(Entity* self, Entity* target) { + auto managers = EntityManager::Instance()->GetEntitiesInGroup("race_manager"); + if (!managers.empty()) { + managers[0]->OnFireEventServerSide(target, "course_cancel"); + } } diff --git a/dScripts/AgMonumentRaceCancel.h b/dScripts/AgMonumentRaceCancel.h index fd324d25..8ddbc5b1 100644 --- a/dScripts/AgMonumentRaceCancel.h +++ b/dScripts/AgMonumentRaceCancel.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class AgMonumentRaceCancel : public CppScripts::Script { - void OnCollisionPhantom(Entity *self, Entity *target) override; + void OnCollisionPhantom(Entity* self, Entity* target) override; }; diff --git a/dScripts/AgMonumentRaceGoal.cpp b/dScripts/AgMonumentRaceGoal.cpp index 13122695..78bbaee5 100644 --- a/dScripts/AgMonumentRaceGoal.cpp +++ b/dScripts/AgMonumentRaceGoal.cpp @@ -2,17 +2,14 @@ #include "EntityManager.h" -void AgMonumentRaceGoal::OnStartup(Entity* self) -{ - self->SetProximityRadius(15, "RaceGoal"); +void AgMonumentRaceGoal::OnStartup(Entity* self) { + self->SetProximityRadius(15, "RaceGoal"); } -void AgMonumentRaceGoal::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (name == "RaceGoal" && entering->IsPlayer() && status == "ENTER") - { - auto* manager = EntityManager::Instance()->GetEntitiesInGroup("race_manager")[0]; +void AgMonumentRaceGoal::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (name == "RaceGoal" && entering->IsPlayer() && status == "ENTER") { + auto* manager = EntityManager::Instance()->GetEntitiesInGroup("race_manager")[0]; - manager->OnFireEventServerSide(entering, "course_finish"); - } + manager->OnFireEventServerSide(entering, "course_finish"); + } } diff --git a/dScripts/AgPicnicBlanket.cpp b/dScripts/AgPicnicBlanket.cpp index 3d13cb40..30fb2950 100644 --- a/dScripts/AgPicnicBlanket.cpp +++ b/dScripts/AgPicnicBlanket.cpp @@ -1,16 +1,16 @@ #include "AgPicnicBlanket.h" #include "GameMessages.h" -void AgPicnicBlanket::OnUse(Entity *self, Entity *user) { - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); - if (self->GetVar(u"active")) - return; - self->SetVar(u"active", true); +void AgPicnicBlanket::OnUse(Entity* self, Entity* user) { + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + if (self->GetVar(u"active")) + return; + self->SetVar(u"active", true); - auto lootTable = std::unordered_map {{935, 3}}; - LootGenerator::Instance().DropLoot(user, self, lootTable, 0, 0); + auto lootTable = std::unordered_map{ {935, 3} }; + LootGenerator::Instance().DropLoot(user, self, lootTable, 0, 0); - self->AddCallbackTimer(5.0f, [self]() { - self->SetVar(u"active", false); - }); + self->AddCallbackTimer(5.0f, [self]() { + self->SetVar(u"active", false); + }); } diff --git a/dScripts/AgPicnicBlanket.h b/dScripts/AgPicnicBlanket.h index af603dd7..2a5a0d7a 100644 --- a/dScripts/AgPicnicBlanket.h +++ b/dScripts/AgPicnicBlanket.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class AgPicnicBlanket : public CppScripts::Script { - void OnUse(Entity *self, Entity *user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/AgPropGuard.cpp b/dScripts/AgPropGuard.cpp index b05eef4f..c8376b3e 100644 --- a/dScripts/AgPropGuard.cpp +++ b/dScripts/AgPropGuard.cpp @@ -6,43 +6,34 @@ #include "MissionComponent.h" #include "Item.h" -void AgPropGuard::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) -{ - auto* character = target->GetCharacter(); - auto* missionComponent = target->GetComponent(); - auto* inventoryComponent = target->GetComponent(); +void AgPropGuard::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + auto* character = target->GetCharacter(); + auto* missionComponent = target->GetComponent(); + auto* inventoryComponent = target->GetComponent(); - const auto state = missionComponent->GetMissionState(320); - if (missionID == 768 && missionState == MissionState::MISSION_STATE_AVAILABLE) - { - if (!character->GetPlayerFlag(71)) - { - // TODO: Cinematic "MissionCam" - } - } - else if (missionID == 768 && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) - { + const auto state = missionComponent->GetMissionState(320); + if (missionID == 768 && missionState == MissionState::MISSION_STATE_AVAILABLE) { + if (!character->GetPlayerFlag(71)) { + // TODO: Cinematic "MissionCam" + } + } else if (missionID == 768 && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { //remove the inventory items - for (int item : gearSets) - { + for (int item : gearSets) { auto* id = inventoryComponent->FindItemByLot(item); - if (id) - { + if (id) { inventoryComponent->UnEquipItem(id); inventoryComponent->RemoveItem(id->GetLot(), id->GetCount()); } } - } - else if ( - (missionID == 320 && state == MissionState::MISSION_STATE_AVAILABLE) /*|| - (state == MissionState::MISSION_STATE_COMPLETE && missionID == 891 && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE)*/ - ) - { - //GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), u"GuardChat", target->GetObjectID(), 0, target->GetObjectID(), "", target->GetSystemAddress()); + } else if ( + (missionID == 320 && state == MissionState::MISSION_STATE_AVAILABLE) /*|| + (state == MissionState::MISSION_STATE_COMPLETE && missionID == 891 && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE)*/ + ) { + //GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), u"GuardChat", target->GetObjectID(), 0, target->GetObjectID(), "", target->GetSystemAddress()); - target->GetCharacter()->SetPlayerFlag(113, true); + target->GetCharacter()->SetPlayerFlag(113, true); - EntityManager::Instance()->GetZoneControlEntity()->AddTimer("GuardFlyAway", 1.0f); - } + EntityManager::Instance()->GetZoneControlEntity()->AddTimer("GuardFlyAway", 1.0f); + } } diff --git a/dScripts/AgPropguards.cpp b/dScripts/AgPropguards.cpp index 4170defe..674c4bdd 100644 --- a/dScripts/AgPropguards.cpp +++ b/dScripts/AgPropguards.cpp @@ -4,53 +4,53 @@ #include "EntityManager.h" #include "dZoneManager.h" -void AgPropguards::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - auto* character = target->GetCharacter(); - if (character == nullptr) - return; +void AgPropguards::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + auto* character = target->GetCharacter(); + if (character == nullptr) + return; - const auto flag = GetFlagForMission(missionID); - if (flag == 0) - return; + const auto flag = GetFlagForMission(missionID); + if (flag == 0) + return; - if ((missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_ACTIVE) - && !character->GetPlayerFlag(flag)) { - // If the player just started the mission, play a cinematic highlighting the target - GameMessages::SendPlayCinematic(target->GetObjectID(), u"MissionCam", target->GetSystemAddress()); - } else if (missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { - // Makes the guard disappear once the mission has been completed - const auto zoneControlID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); - GameMessages::SendNotifyClientObject(zoneControlID, u"GuardChat", 0, 0, self->GetObjectID(), - "", UNASSIGNED_SYSTEM_ADDRESS); + if ((missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_ACTIVE) + && !character->GetPlayerFlag(flag)) { + // If the player just started the mission, play a cinematic highlighting the target + GameMessages::SendPlayCinematic(target->GetObjectID(), u"MissionCam", target->GetSystemAddress()); + } else if (missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + // Makes the guard disappear once the mission has been completed + const auto zoneControlID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); + GameMessages::SendNotifyClientObject(zoneControlID, u"GuardChat", 0, 0, self->GetObjectID(), + "", UNASSIGNED_SYSTEM_ADDRESS); - self->AddCallbackTimer(5.0f, [self]() { - auto spawnerName = self->GetVar(u"spawner_name"); - if (spawnerName.empty()) - spawnerName = "Guard"; + self->AddCallbackTimer(5.0f, [self]() { + auto spawnerName = self->GetVar(u"spawner_name"); + if (spawnerName.empty()) + spawnerName = "Guard"; - auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); - for (auto* spawner : spawners) { - spawner->Deactivate(); - } + auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); + for (auto* spawner : spawners) { + spawner->Deactivate(); + } - self->Smash(); - }); - } + self->Smash(); + }); + } } uint32_t AgPropguards::GetFlagForMission(uint32_t missionID) { - switch (missionID) { - case 872: - return 97; - case 873: - return 98; - case 874: - return 99; - case 1293: - return 118; - case 1322: - return 122; - default: - return 0; - } + switch (missionID) { + case 872: + return 97; + case 873: + return 98; + case 874: + return 99; + case 1293: + return 118; + case 1322: + return 122; + default: + return 0; + } } diff --git a/dScripts/AgPropguards.h b/dScripts/AgPropguards.h index 710096ce..511b7b6a 100644 --- a/dScripts/AgPropguards.h +++ b/dScripts/AgPropguards.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class AgPropguards : public CppScripts::Script { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; private: - static uint32_t GetFlagForMission(uint32_t missionID); + static uint32_t GetFlagForMission(uint32_t missionID); }; diff --git a/dScripts/AgQbElevator.cpp b/dScripts/AgQbElevator.cpp index 3ef0cf0b..ccb4d3b1 100644 --- a/dScripts/AgQbElevator.cpp +++ b/dScripts/AgQbElevator.cpp @@ -3,7 +3,7 @@ #include "GameMessages.h" void AgQbElevator::OnStartup(Entity* self) { - + } //when the QB is finished being built by a player @@ -15,7 +15,7 @@ void AgQbElevator::OnRebuildComplete(Entity* self, Entity* target) { if (delayTime < 1) delayTime = 1; GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 0, 0, MovementPlatformState::Stationary); + 0, 0, MovementPlatformState::Stationary); //add a timer that will kill the QB if no players get on in the killTime self->AddTimer("startKillTimer", killTime); @@ -33,9 +33,8 @@ void AgQbElevator::OnProximityUpdate(Entity* self, Entity* entering, std::string self->CancelTimer("StartElevator"); GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 1, 1, MovementPlatformState::Moving); - } - else if (!self->GetBoolean(u"StartTimer")) { + 1, 1, MovementPlatformState::Moving); + } else if (!self->GetBoolean(u"StartTimer")) { self->SetBoolean(u"StartTimer", true); self->AddTimer("StartElevator", startTime); } @@ -46,9 +45,8 @@ void AgQbElevator::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "StartElevator") { GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 1, 1, MovementPlatformState::Moving); - } - else if (timerName == "startKillTimer") { + 1, 1, MovementPlatformState::Moving); + } else if (timerName == "startKillTimer") { killTimerStartup(self); } else if (timerName == "KillTimer") { self->Smash(self->GetObjectID(), VIOLENT); diff --git a/dScripts/AgQbElevator.h b/dScripts/AgQbElevator.h index ab4f9a6d..4d07b8a2 100644 --- a/dScripts/AgQbElevator.h +++ b/dScripts/AgQbElevator.h @@ -16,4 +16,4 @@ private: float startTime = 8.0f; float killTime = 10.0f; float proxRadius = 5.0f; -}; \ No newline at end of file +}; diff --git a/dScripts/AgSalutingNpcs.cpp b/dScripts/AgSalutingNpcs.cpp index 618dc631..28495f58 100644 --- a/dScripts/AgSalutingNpcs.cpp +++ b/dScripts/AgSalutingNpcs.cpp @@ -2,10 +2,8 @@ #include "GameMessages.h" -void AgSalutingNpcs::OnEmoteReceived(Entity* self, const int32_t emote, Entity* target) -{ - if (emote != 356) - { +void AgSalutingNpcs::OnEmoteReceived(Entity* self, const int32_t emote, Entity* target) { + if (emote != 356) { return; } diff --git a/dScripts/AgShipPlayerDeathTrigger.cpp b/dScripts/AgShipPlayerDeathTrigger.cpp index d20edee7..a580be6e 100644 --- a/dScripts/AgShipPlayerDeathTrigger.cpp +++ b/dScripts/AgShipPlayerDeathTrigger.cpp @@ -5,4 +5,4 @@ void AgShipPlayerDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) if (target->GetLOT() == 1 && !target->GetIsDead()) { target->Smash(self->GetObjectID(), eKillType::VIOLENT, u"electro-shock-death"); } -} \ No newline at end of file +} diff --git a/dScripts/AgShipPlayerShockServer.cpp b/dScripts/AgShipPlayerShockServer.cpp index 628f0bb4..2bed8152 100644 --- a/dScripts/AgShipPlayerShockServer.cpp +++ b/dScripts/AgShipPlayerShockServer.cpp @@ -1,8 +1,7 @@ #include "AgShipPlayerShockServer.h" #include "GameMessages.h" -void AgShipPlayerShockServer::OnUse(Entity* self, Entity* user) -{ +void AgShipPlayerShockServer::OnUse(Entity* self, Entity* user) { GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); if (active) { return; @@ -15,8 +14,7 @@ void AgShipPlayerShockServer::OnUse(Entity* self, Entity* user) self->AddTimer("FXTime", fxTime); } -void AgShipPlayerShockServer::OnTimerDone(Entity* self, std::string timerName) -{ +void AgShipPlayerShockServer::OnTimerDone(Entity* self, std::string timerName) { GameMessages::SendStopFXEffect(self, true, "console_sparks"); active = false; } diff --git a/dScripts/AgSpaceStuff.cpp b/dScripts/AgSpaceStuff.cpp index 18e4eb47..80a87e70 100644 --- a/dScripts/AgSpaceStuff.cpp +++ b/dScripts/AgSpaceStuff.cpp @@ -28,18 +28,15 @@ void AgSpaceStuff::OnTimerDone(Entity* self, std::string timerName) { GameMessages::SendPlayAnimation(self, u"scale_0" + GeneralUtils::to_u16string(scaleType)); self->AddTimer("FloaterPath", 0.4); - } - else if (timerName == "FloaterPath") { + } else if (timerName == "FloaterPath") { int pathType = GeneralUtils::GenerateRandomNumber(1, 4); int randTime = GeneralUtils::GenerateRandomNumber(20, 25); GameMessages::SendPlayAnimation(self, u"path_0" + (GeneralUtils::to_u16string(pathType))); self->AddTimer("FloaterScale", randTime); - } - else if (timerName == "ShipShakeExplode") { + } else if (timerName == "ShipShakeExplode") { DoShake(self, true); - } - else if (timerName == "ShipShakeIdle") { + } else if (timerName == "ShipShakeIdle") { DoShake(self, false); } } @@ -79,8 +76,7 @@ void AgSpaceStuff::DoShake(Entity* self, bool explodeIdle) { auto* shipFxObject2 = GetEntityInGroup(ShipFX2); if (shipFxObject2) GameMessages::SendPlayAnimation(shipFxObject2, u"explosion"); - } - else { + } else { auto* shipFxObject = GetEntityInGroup(ShipFX); auto* shipFxObject2 = GetEntityInGroup(ShipFX2); diff --git a/dScripts/AgStagePlatforms.cpp b/dScripts/AgStagePlatforms.cpp index cb401647..9ba4c4b7 100644 --- a/dScripts/AgStagePlatforms.cpp +++ b/dScripts/AgStagePlatforms.cpp @@ -1,16 +1,16 @@ #include "AgStagePlatforms.h" #include "MovingPlatformComponent.h" -void AgStagePlatforms::OnStartup(Entity *self) { - auto* component = self->GetComponent(); - if (component) { - component->SetNoAutoStart(true); - component->StopPathing(); - } +void AgStagePlatforms::OnStartup(Entity* self) { + auto* component = self->GetComponent(); + if (component) { + component->SetNoAutoStart(true); + component->StopPathing(); + } } void AgStagePlatforms::OnWaypointReached(Entity* self, uint32_t waypointIndex) { - auto* component = self->GetComponent(); - if (waypointIndex == 0 && component) - component->StopPathing(); + auto* component = self->GetComponent(); + if (waypointIndex == 0 && component) + component->StopPathing(); } diff --git a/dScripts/AgStagePlatforms.h b/dScripts/AgStagePlatforms.h index e315664a..62c6bc91 100644 --- a/dScripts/AgStagePlatforms.h +++ b/dScripts/AgStagePlatforms.h @@ -3,6 +3,6 @@ class AgStagePlatforms : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnWaypointReached(Entity* self, uint32_t waypointIndex) override; + void OnStartup(Entity* self) override; + void OnWaypointReached(Entity* self, uint32_t waypointIndex) override; }; diff --git a/dScripts/AgStromlingProperty.cpp b/dScripts/AgStromlingProperty.cpp index b1b8d45f..36d8d378 100644 --- a/dScripts/AgStromlingProperty.cpp +++ b/dScripts/AgStromlingProperty.cpp @@ -1,16 +1,16 @@ #include "AgStromlingProperty.h" #include "MovementAIComponent.h" -void AgStromlingProperty::OnStartup(Entity *self) { - auto movementInfo = MovementAIInfo { - "Wander", - 71, - 3, - 100, - 1, - 4 - }; +void AgStromlingProperty::OnStartup(Entity* self) { + auto movementInfo = MovementAIInfo{ + "Wander", + 71, + 3, + 100, + 1, + 4 + }; - auto* movementAIComponent = new MovementAIComponent(self, movementInfo); - self->AddComponent(COMPONENT_TYPE_MOVEMENT_AI, movementAIComponent); + auto* movementAIComponent = new MovementAIComponent(self, movementInfo); + self->AddComponent(COMPONENT_TYPE_MOVEMENT_AI, movementAIComponent); } diff --git a/dScripts/AgStromlingProperty.h b/dScripts/AgStromlingProperty.h index 92a179f5..12128b03 100644 --- a/dScripts/AgStromlingProperty.h +++ b/dScripts/AgStromlingProperty.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class AgStromlingProperty : public CppScripts::Script { - void OnStartup(Entity *self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/AgSurvivalBuffStation.cpp b/dScripts/AgSurvivalBuffStation.cpp index 8a6cfb05..4d3482c4 100644 --- a/dScripts/AgSurvivalBuffStation.cpp +++ b/dScripts/AgSurvivalBuffStation.cpp @@ -6,60 +6,60 @@ #include "TeamManager.h" void AgSurvivalBuffStation::OnRebuildComplete(Entity* self, Entity* target) { - auto destroyableComponent = self->GetComponent(); - // We set the faction to 1 so that the buff station sees players as friendly targets to buff - if (destroyableComponent != nullptr) destroyableComponent->SetFaction(1); + auto destroyableComponent = self->GetComponent(); + // We set the faction to 1 so that the buff station sees players as friendly targets to buff + if (destroyableComponent != nullptr) destroyableComponent->SetFaction(1); - auto skillComponent = self->GetComponent(); + auto skillComponent = self->GetComponent(); - if (skillComponent != nullptr) skillComponent->CalculateBehavior(skillIdForBuffStation, behaviorIdForBuffStation, self->GetObjectID()); + if (skillComponent != nullptr) skillComponent->CalculateBehavior(skillIdForBuffStation, behaviorIdForBuffStation, self->GetObjectID()); - self->AddCallbackTimer(smashTimer, [self]() { - self->Smash(); - }); - self->AddTimer("DropArmor", dropArmorTimer); - self->AddTimer("DropLife", dropLifeTimer); - self->AddTimer("Dropimagination", dropImaginationTimer); - // Since all survival players should be on the same team, we get the team. - auto team = TeamManager::Instance()->GetTeam(target->GetObjectID()); + self->AddCallbackTimer(smashTimer, [self]() { + self->Smash(); + }); + self->AddTimer("DropArmor", dropArmorTimer); + self->AddTimer("DropLife", dropLifeTimer); + self->AddTimer("Dropimagination", dropImaginationTimer); + // Since all survival players should be on the same team, we get the team. + auto team = TeamManager::Instance()->GetTeam(target->GetObjectID()); - std::vector builderTeam; - // Not on a team - if (team == nullptr) { - builderTeam.push_back(target->GetObjectID()); - self->SetVar>(u"BuilderTeam", builderTeam); - return; - } + std::vector builderTeam; + // Not on a team + if (team == nullptr) { + builderTeam.push_back(target->GetObjectID()); + self->SetVar>(u"BuilderTeam", builderTeam); + return; + } - for (auto memberID : team->members) { - builderTeam.push_back(memberID); - } - self->SetVar>(u"BuilderTeam", builderTeam); + for (auto memberID : team->members) { + builderTeam.push_back(memberID); + } + self->SetVar>(u"BuilderTeam", builderTeam); } void AgSurvivalBuffStation::OnTimerDone(Entity* self, std::string timerName) { - uint32_t powerupToDrop = lifePowerup; - if (timerName == "DropArmor") { - powerupToDrop = armorPowerup; - self->AddTimer("DropArmor", dropArmorTimer); - } - if (timerName == "DropLife") { - powerupToDrop = lifePowerup; - self->AddTimer("DropLife", dropLifeTimer); - } - if (timerName == "Dropimagination") { - powerupToDrop = imaginationPowerup; - self->AddTimer("Dropimagination", dropImaginationTimer); - } - auto team = self->GetVar>(u"BuilderTeam"); - for (auto memberID : team) { - auto member = EntityManager::Instance()->GetEntity(memberID); - if (member != nullptr && !member->GetIsDead()) { - GameMessages::SendDropClientLoot(member, self->GetObjectID(), powerupToDrop, 0, self->GetPosition()); - } else { - // If player left the team or left early erase them from the team variable. - team.erase(std::find(team.begin(), team.end(), memberID)); - self->SetVar>(u"BuilderTeam", team); - } - } + uint32_t powerupToDrop = lifePowerup; + if (timerName == "DropArmor") { + powerupToDrop = armorPowerup; + self->AddTimer("DropArmor", dropArmorTimer); + } + if (timerName == "DropLife") { + powerupToDrop = lifePowerup; + self->AddTimer("DropLife", dropLifeTimer); + } + if (timerName == "Dropimagination") { + powerupToDrop = imaginationPowerup; + self->AddTimer("Dropimagination", dropImaginationTimer); + } + auto team = self->GetVar>(u"BuilderTeam"); + for (auto memberID : team) { + auto member = EntityManager::Instance()->GetEntity(memberID); + if (member != nullptr && !member->GetIsDead()) { + GameMessages::SendDropClientLoot(member, self->GetObjectID(), powerupToDrop, 0, self->GetPosition()); + } else { + // If player left the team or left early erase them from the team variable. + team.erase(std::find(team.begin(), team.end(), memberID)); + self->SetVar>(u"BuilderTeam", team); + } + } } diff --git a/dScripts/AgSurvivalBuffStation.h b/dScripts/AgSurvivalBuffStation.h index b2beaba6..5434b0cd 100644 --- a/dScripts/AgSurvivalBuffStation.h +++ b/dScripts/AgSurvivalBuffStation.h @@ -4,49 +4,49 @@ class AgSurvivalBuffStation : public CppScripts::Script { public: - /** - * @brief When the rebuild of self is complete, we calculate the behavior that is assigned to self in the database. - * - * @param self The Entity that called this script. - * @param target The target of the self that called this script. - */ - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string timerName) override; + /** + * @brief When the rebuild of self is complete, we calculate the behavior that is assigned to self in the database. + * + * @param self The Entity that called this script. + * @param target The target of the self that called this script. + */ + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - /** - * Skill ID for the buff station. - */ - uint32_t skillIdForBuffStation = 201; - /** - * Behavior ID for the buff station. - */ - uint32_t behaviorIdForBuffStation = 1784; - /** - * Timer for dropping armor. - */ - float dropArmorTimer = 6.0f; - /** - * Timer for dropping life. - */ - float dropLifeTimer = 3.0f; - /** - * Timer for dropping imagination. - */ - float dropImaginationTimer = 4.0f; - /** - * Timer for smashing. - */ - float smashTimer = 25.0f; - /** - * LOT for armor powerup. - */ - LOT armorPowerup = 6431; - /** - * LOT for life powerup. - */ - LOT lifePowerup = 177; - /** - * LOT for imagination powerup. - */ - LOT imaginationPowerup = 935; -}; \ No newline at end of file + /** + * Skill ID for the buff station. + */ + uint32_t skillIdForBuffStation = 201; + /** + * Behavior ID for the buff station. + */ + uint32_t behaviorIdForBuffStation = 1784; + /** + * Timer for dropping armor. + */ + float dropArmorTimer = 6.0f; + /** + * Timer for dropping life. + */ + float dropLifeTimer = 3.0f; + /** + * Timer for dropping imagination. + */ + float dropImaginationTimer = 4.0f; + /** + * Timer for smashing. + */ + float smashTimer = 25.0f; + /** + * LOT for armor powerup. + */ + LOT armorPowerup = 6431; + /** + * LOT for life powerup. + */ + LOT lifePowerup = 177; + /** + * LOT for imagination powerup. + */ + LOT imaginationPowerup = 935; +}; diff --git a/dScripts/AgSurvivalMech.cpp b/dScripts/AgSurvivalMech.cpp index e31c8aba..99f40b8b 100644 --- a/dScripts/AgSurvivalMech.cpp +++ b/dScripts/AgSurvivalMech.cpp @@ -1,15 +1,15 @@ #include "AgSurvivalMech.h" #include "DestroyableComponent.h" -void AgSurvivalMech::OnStartup(Entity *self) { - BaseWavesGenericEnemy::OnStartup(self); +void AgSurvivalMech::OnStartup(Entity* self) { + BaseWavesGenericEnemy::OnStartup(self); - auto* destroyable = self->GetComponent(); - if (destroyable != nullptr) { - destroyable->SetFaction(4); - } + auto* destroyable = self->GetComponent(); + if (destroyable != nullptr) { + destroyable->SetFaction(4); + } } uint32_t AgSurvivalMech::GetPoints() { - return 200; + return 200; } diff --git a/dScripts/AgSurvivalMech.h b/dScripts/AgSurvivalMech.h index 8d6ba270..cc972b67 100644 --- a/dScripts/AgSurvivalMech.h +++ b/dScripts/AgSurvivalMech.h @@ -2,6 +2,6 @@ #include "BaseWavesGenericEnemy.h" class AgSurvivalMech : public BaseWavesGenericEnemy { - void OnStartup(Entity *self) override; - uint32_t GetPoints() override; + void OnStartup(Entity* self) override; + uint32_t GetPoints() override; }; diff --git a/dScripts/AgSurvivalSpiderling.cpp b/dScripts/AgSurvivalSpiderling.cpp index d44455d8..8e2c173c 100644 --- a/dScripts/AgSurvivalSpiderling.cpp +++ b/dScripts/AgSurvivalSpiderling.cpp @@ -1,15 +1,15 @@ #include "AgSurvivalSpiderling.h" #include "BaseCombatAIComponent.h" -void AgSurvivalSpiderling::OnStartup(Entity *self) { - BaseWavesGenericEnemy::OnStartup(self); +void AgSurvivalSpiderling::OnStartup(Entity* self) { + BaseWavesGenericEnemy::OnStartup(self); - auto* combatAI = self->GetComponent(); - if (combatAI != nullptr) { - combatAI->SetStunImmune(true); - } + auto* combatAI = self->GetComponent(); + if (combatAI != nullptr) { + combatAI->SetStunImmune(true); + } } uint32_t AgSurvivalSpiderling::GetPoints() { - return 300; + return 300; } diff --git a/dScripts/AgSurvivalSpiderling.h b/dScripts/AgSurvivalSpiderling.h index 2f374563..4aa51024 100644 --- a/dScripts/AgSurvivalSpiderling.h +++ b/dScripts/AgSurvivalSpiderling.h @@ -2,6 +2,6 @@ #include "BaseWavesGenericEnemy.h" class AgSurvivalSpiderling : public BaseWavesGenericEnemy { - void OnStartup(Entity *self) override; - uint32_t GetPoints() override; + void OnStartup(Entity* self) override; + uint32_t GetPoints() override; }; diff --git a/dScripts/AgSurvivalStromling.cpp b/dScripts/AgSurvivalStromling.cpp index bc6a6c74..2f4c6623 100644 --- a/dScripts/AgSurvivalStromling.cpp +++ b/dScripts/AgSurvivalStromling.cpp @@ -1,5 +1,5 @@ #include "AgSurvivalStromling.h" uint32_t AgSurvivalStromling::GetPoints() { - return 100; + return 100; } diff --git a/dScripts/AgSurvivalStromling.h b/dScripts/AgSurvivalStromling.h index cfd46a63..e43a603d 100644 --- a/dScripts/AgSurvivalStromling.h +++ b/dScripts/AgSurvivalStromling.h @@ -2,5 +2,5 @@ #include "BaseWavesGenericEnemy.h" class AgSurvivalStromling : public BaseWavesGenericEnemy { - uint32_t GetPoints() override; + uint32_t GetPoints() override; }; diff --git a/dScripts/AgTurret.h b/dScripts/AgTurret.h index 2aa12432..1cbba31a 100644 --- a/dScripts/AgTurret.h +++ b/dScripts/AgTurret.h @@ -5,4 +5,4 @@ class AgTurret : public CppScripts::Script { void OnStartup(Entity* self); void OnTimerDone(Entity* self, std::string timerName); void OnRebuildStart(Entity* self, Entity* user); -}; \ No newline at end of file +}; diff --git a/dScripts/AmBlueX.cpp b/dScripts/AmBlueX.cpp index db464186..97f80e77 100644 --- a/dScripts/AmBlueX.cpp +++ b/dScripts/AmBlueX.cpp @@ -3,53 +3,53 @@ #include "EntityManager.h" #include "Character.h" -void AmBlueX::OnUse(Entity *self, Entity *user) { - auto* skillComponent = user->GetComponent(); - if (skillComponent != nullptr) { - skillComponent->CalculateBehavior(m_SwordSkill, m_SwordBehavior, self->GetObjectID()); - } +void AmBlueX::OnUse(Entity* self, Entity* user) { + auto* skillComponent = user->GetComponent(); + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(m_SwordSkill, m_SwordBehavior, self->GetObjectID()); + } } -void AmBlueX::OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) { - if (message == "FireDukesStrike") { - self->SetNetworkVar(m_XUsedVariable, true); - self->SetNetworkVar(m_StartEffectVariable, true); +void AmBlueX::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message == "FireDukesStrike") { + self->SetNetworkVar(m_XUsedVariable, true); + self->SetNetworkVar(m_StartEffectVariable, true); - auto* character = caster->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(self->GetVar(m_FlagVariable), true); - } + auto* character = caster->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(self->GetVar(m_FlagVariable), true); + } - EntityInfo info {}; - info.lot = m_FXObject; - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = m_FXObject; + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.spawnerID = self->GetObjectID(); - auto* fxObject = EntityManager::Instance()->CreateEntity(info, nullptr, self); - EntityManager::Instance()->ConstructEntity(fxObject); + auto* fxObject = EntityManager::Instance()->CreateEntity(info, nullptr, self); + EntityManager::Instance()->ConstructEntity(fxObject); - auto fxObjectID = fxObject->GetObjectID(); - auto playerID = caster->GetObjectID(); + auto fxObjectID = fxObject->GetObjectID(); + auto playerID = caster->GetObjectID(); - // Add a callback for the bomb to explode - self->AddCallbackTimer(m_BombTime, [this, self, fxObjectID, playerID]() { - auto* fxObject = EntityManager::Instance()->GetEntity(fxObjectID); - auto* player = EntityManager::Instance()->GetEntity(playerID); - auto* skillComponent = self->GetComponent(); + // Add a callback for the bomb to explode + self->AddCallbackTimer(m_BombTime, [this, self, fxObjectID, playerID]() { + auto* fxObject = EntityManager::Instance()->GetEntity(fxObjectID); + auto* player = EntityManager::Instance()->GetEntity(playerID); + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - return; + if (skillComponent == nullptr) + return; - // Cast the skill that destroys the object - if (player != nullptr) { - skillComponent->CalculateBehavior(m_AOESkill, m_AOEBehavior, LWOOBJID_EMPTY, false, false, playerID); - } else { - skillComponent->CalculateBehavior(m_AOESkill, m_AOEBehavior, LWOOBJID_EMPTY); - } + // Cast the skill that destroys the object + if (player != nullptr) { + skillComponent->CalculateBehavior(m_AOESkill, m_AOEBehavior, LWOOBJID_EMPTY, false, false, playerID); + } else { + skillComponent->CalculateBehavior(m_AOESkill, m_AOEBehavior, LWOOBJID_EMPTY); + } - fxObject->Smash(); - self->Smash(); - }); - } + fxObject->Smash(); + self->Smash(); + }); + } } diff --git a/dScripts/AmBlueX.h b/dScripts/AmBlueX.h index 99f6ede4..79428514 100644 --- a/dScripts/AmBlueX.h +++ b/dScripts/AmBlueX.h @@ -2,19 +2,19 @@ #include "CppScripts.h" class AmBlueX : public CppScripts::Script { - void OnUse(Entity *self, Entity *user) override; - void OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) override; + void OnUse(Entity* self, Entity* user) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; private: - const float_t m_BombTime = 3.3f; - const uint32_t m_MissionID = 1448; - const uint32_t m_SwordSkill = 1259; - const uint32_t m_SwordBehavior = 29305; - const uint32_t m_AOESkill = 1258; - const uint32_t m_AOEBehavior = 29301; - const LOT m_FXObject = 13808; + const float_t m_BombTime = 3.3f; + const uint32_t m_MissionID = 1448; + const uint32_t m_SwordSkill = 1259; + const uint32_t m_SwordBehavior = 29305; + const uint32_t m_AOESkill = 1258; + const uint32_t m_AOEBehavior = 29301; + const LOT m_FXObject = 13808; - // Variables - const std::u16string m_XUsedVariable = u"XUsed"; - const std::u16string m_FlagVariable = u"flag"; - const std::u16string m_StartEffectVariable = u"startEffect"; + // Variables + const std::u16string m_XUsedVariable = u"XUsed"; + const std::u16string m_FlagVariable = u"flag"; + const std::u16string m_StartEffectVariable = u"startEffect"; }; diff --git a/dScripts/AmBridge.cpp b/dScripts/AmBridge.cpp index e2e21033..88f30642 100644 --- a/dScripts/AmBridge.cpp +++ b/dScripts/AmBridge.cpp @@ -1,33 +1,28 @@ #include "AmBridge.h" #include "EntityManager.h" -void AmBridge::OnStartup(Entity* self) -{ - +void AmBridge::OnStartup(Entity* self) { + } -void AmBridge::OnRebuildComplete(Entity* self, Entity* target) -{ - const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console" + GeneralUtils::UTF16ToWTF8(self->GetVar(u"bridge"))); +void AmBridge::OnRebuildComplete(Entity* self, Entity* target) { + const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console" + GeneralUtils::UTF16ToWTF8(self->GetVar(u"bridge"))); - if (consoles.empty()) - { - return; - } + if (consoles.empty()) { + return; + } - auto* console = consoles[0]; + auto* console = consoles[0]; - console->NotifyObject(self, "BridgeBuilt"); + console->NotifyObject(self, "BridgeBuilt"); - self->AddTimer("SmashBridge", 50); + self->AddTimer("SmashBridge", 50); } -void AmBridge::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName != "SmashBridge") - { - return; - } +void AmBridge::OnTimerDone(Entity* self, std::string timerName) { + if (timerName != "SmashBridge") { + return; + } - self->Smash(self->GetObjectID(), VIOLENT); + self->Smash(self->GetObjectID(), VIOLENT); } diff --git a/dScripts/AmBridge.h b/dScripts/AmBridge.h index bae35624..0dc025f9 100644 --- a/dScripts/AmBridge.h +++ b/dScripts/AmBridge.h @@ -4,7 +4,7 @@ class AmBridge : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/AmConsoleTeleportServer.cpp b/dScripts/AmConsoleTeleportServer.cpp index 5087aae2..f3931e0d 100644 --- a/dScripts/AmConsoleTeleportServer.cpp +++ b/dScripts/AmConsoleTeleportServer.cpp @@ -2,35 +2,29 @@ #include "ChooseYourDestinationNsToNt.h" #include "AMFFormat.h" -void AmConsoleTeleportServer::OnStartup(Entity* self) -{ - self->SetVar(u"teleportAnim", m_TeleportAnim); - self->SetVar(u"teleportString", m_TeleportString); - self->SetVar(u"teleportEffectID", m_TeleportEffectID); - self->SetVar(u"teleportEffectTypes", m_TeleportEffectTypes); +void AmConsoleTeleportServer::OnStartup(Entity* self) { + self->SetVar(u"teleportAnim", m_TeleportAnim); + self->SetVar(u"teleportString", m_TeleportString); + self->SetVar(u"teleportEffectID", m_TeleportEffectID); + self->SetVar(u"teleportEffectTypes", m_TeleportEffectTypes); } -void AmConsoleTeleportServer::OnUse(Entity* self, Entity* user) -{ - BaseOnUse(self, user); +void AmConsoleTeleportServer::OnUse(Entity* self, Entity* user) { + BaseOnUse(self, user); } -void AmConsoleTeleportServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - BaseOnMessageBoxResponse(self, sender, button, identifier, userData); +void AmConsoleTeleportServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + BaseOnMessageBoxResponse(self, sender, button, identifier, userData); } -void AmConsoleTeleportServer::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) -{ - +void AmConsoleTeleportServer::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { + } -void AmConsoleTeleportServer::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void AmConsoleTeleportServer::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } -void AmConsoleTeleportServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); +void AmConsoleTeleportServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); } diff --git a/dScripts/AmConsoleTeleportServer.h b/dScripts/AmConsoleTeleportServer.h index 8236e67e..6206f22c 100644 --- a/dScripts/AmConsoleTeleportServer.h +++ b/dScripts/AmConsoleTeleportServer.h @@ -5,18 +5,18 @@ class AmConsoleTeleportServer : public CppScripts::Script, BaseConsoleTeleportServer { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; - void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; + void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; private: - int32_t m_ChoiceZoneID = 1900; - std::string m_SpawnPoint = "NS_LW"; - std::u16string m_TeleportAnim = u"nexus-teleport"; - std::u16string m_TeleportString = u"UI_TRAVEL_TO_NEXUS_TOWER"; - int32_t m_TeleportEffectID = 6478; - std::vector m_TeleportEffectTypes = {u"teleportRings", u"teleportBeam"}; + int32_t m_ChoiceZoneID = 1900; + std::string m_SpawnPoint = "NS_LW"; + std::u16string m_TeleportAnim = u"nexus-teleport"; + std::u16string m_TeleportString = u"UI_TRAVEL_TO_NEXUS_TOWER"; + int32_t m_TeleportEffectID = 6478; + std::vector m_TeleportEffectTypes = { u"teleportRings", u"teleportBeam" }; }; diff --git a/dScripts/AmDarklingDragon.cpp b/dScripts/AmDarklingDragon.cpp index 94066167..8ec49d3e 100644 --- a/dScripts/AmDarklingDragon.cpp +++ b/dScripts/AmDarklingDragon.cpp @@ -7,153 +7,146 @@ #include "BaseCombatAIComponent.h" void AmDarklingDragon::OnStartup(Entity* self) { - self->SetVar(u"weakspot", 0); + self->SetVar(u"weakspot", 0); - auto* baseCombatAIComponent = self->GetComponent(); + auto* baseCombatAIComponent = self->GetComponent(); - if (baseCombatAIComponent != nullptr) { - baseCombatAIComponent->SetStunImmune(true); - } + if (baseCombatAIComponent != nullptr) { + baseCombatAIComponent->SetStunImmune(true); + } } void AmDarklingDragon::OnDie(Entity* self, Entity* killer) { - if (self->GetVar(u"bDied")) { - return; - } + if (self->GetVar(u"bDied")) { + return; + } - self->SetVar(u"bDied", true); - - auto golemId = self->GetVar(u"Golem"); + self->SetVar(u"bDied", true); - auto* golem = EntityManager::Instance()->GetEntity(golemId); + auto golemId = self->GetVar(u"Golem"); - if (golem != nullptr) { - golem->Smash(self->GetObjectID()); - } + auto* golem = EntityManager::Instance()->GetEntity(golemId); + + if (golem != nullptr) { + golem->Smash(self->GetObjectID()); + } } void AmDarklingDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { - GameMessages::SendPlayFXEffect(self, -1, u"gothit", "", LWOOBJID_EMPTY, 1, 1, true); + GameMessages::SendPlayFXEffect(self, -1, u"gothit", "", LWOOBJID_EMPTY, 1, 1, true); - if (true) { - auto weakpoint = self->GetVar(u"weakspot"); + if (true) { + auto weakpoint = self->GetVar(u"weakspot"); - if (weakpoint == 1) - { - self->Smash(attacker->GetObjectID()); - } - } + if (weakpoint == 1) { + self->Smash(attacker->GetObjectID()); + } + } - auto* destroyableComponent = self->GetComponent(); + auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr) { - if (destroyableComponent->GetArmor() > 0) return; + if (destroyableComponent != nullptr) { + if (destroyableComponent->GetArmor() > 0) return; - auto weakpoint = self->GetVar(u"weakpoint"); + auto weakpoint = self->GetVar(u"weakpoint"); - if (weakpoint == 0) { - self->AddTimer("ReviveTimer", 12); + if (weakpoint == 0) { + self->AddTimer("ReviveTimer", 12); - auto* baseCombatAIComponent = self->GetComponent(); - auto* skillComponent = self->GetComponent(); + auto* baseCombatAIComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (baseCombatAIComponent != nullptr) { - baseCombatAIComponent->SetDisabled(true); - baseCombatAIComponent->SetStunned(true); - } + if (baseCombatAIComponent != nullptr) { + baseCombatAIComponent->SetDisabled(true); + baseCombatAIComponent->SetStunned(true); + } - if (skillComponent != nullptr) { - skillComponent->Interrupt(); - } + if (skillComponent != nullptr) { + skillComponent->Interrupt(); + } - self->SetVar(u"weakpoint", 2); + self->SetVar(u"weakpoint", 2); - GameMessages::SendPlayAnimation(self, u"stunstart", 1.7f); + GameMessages::SendPlayAnimation(self, u"stunstart", 1.7f); - self->AddTimer("timeToStunLoop", 1); + self->AddTimer("timeToStunLoop", 1); - auto position = self->GetPosition(); - auto forward = self->GetRotation().GetForwardVector(); - auto backwards = forward * -1; + auto position = self->GetPosition(); + auto forward = self->GetRotation().GetForwardVector(); + auto backwards = forward * -1; - forward.x *= 10; - forward.z *= 10; + forward.x *= 10; + forward.z *= 10; - auto rotation = self->GetRotation(); + auto rotation = self->GetRotation(); - auto objectPosition = NiPoint3(); + auto objectPosition = NiPoint3(); - objectPosition.y = position.y; - objectPosition.x = position.x - (backwards.x * 8); - objectPosition.z = position.z - (backwards.z * 8); + objectPosition.y = position.y; + objectPosition.x = position.x - (backwards.x * 8); + objectPosition.z = position.z - (backwards.z * 8); - auto golem = self->GetVar(u"DragonSmashingGolem"); + auto golem = self->GetVar(u"DragonSmashingGolem"); - EntityInfo info {}; - info.lot = golem != 0 ? golem : 8340; - info.pos = objectPosition; - info.rot = rotation; - info.spawnerID = self->GetObjectID(); - info.settings = { - new LDFData(u"rebuild_activators", - std::to_string(objectPosition.x + forward.x) + "\x1f" + - std::to_string(objectPosition.y) + "\x1f" + - std::to_string(objectPosition.z + forward.z) - ), - new LDFData(u"respawn", 100000), - new LDFData(u"rebuild_reset_time", 15), - new LDFData(u"no_timed_spawn", true), - new LDFData(u"Dragon", self->GetObjectID()) - }; + EntityInfo info{}; + info.lot = golem != 0 ? golem : 8340; + info.pos = objectPosition; + info.rot = rotation; + info.spawnerID = self->GetObjectID(); + info.settings = { + new LDFData(u"rebuild_activators", + std::to_string(objectPosition.x + forward.x) + "\x1f" + + std::to_string(objectPosition.y) + "\x1f" + + std::to_string(objectPosition.z + forward.z) + ), + new LDFData(u"respawn", 100000), + new LDFData(u"rebuild_reset_time", 15), + new LDFData(u"no_timed_spawn", true), + new LDFData(u"Dragon", self->GetObjectID()) + }; - auto* golemObject = EntityManager::Instance()->CreateEntity(info); + auto* golemObject = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(golemObject); - } - } + EntityManager::Instance()->ConstructEntity(golemObject); + } + } } -void AmDarklingDragon::OnTimerDone(Entity* self, std::string timerName) { - if (timerName == "ReviveHeldTimer") { - self->AddTimer("backToAttack", 2.5); - } - else if (timerName == "ExposeWeakSpotTimer") { - self->SetVar(u"weakspot", 1); - } - else if (timerName == "timeToStunLoop") { - GameMessages::SendPlayAnimation(self, u"stunloop", 1.8f); - } - else if (timerName == "ReviveTimer") { - GameMessages::SendPlayAnimation(self, u"stunend", 2.0f); - self->AddTimer("backToAttack", 1); - } - else if (timerName == "backToAttack") { - auto* baseCombatAIComponent = self->GetComponent(); - auto* skillComponent = self->GetComponent(); - if (baseCombatAIComponent != nullptr) - { - baseCombatAIComponent->SetDisabled(false); - baseCombatAIComponent->SetStunned(false); - } - if (skillComponent != nullptr) - { - skillComponent->Interrupt(); - } - self->SetVar(u"weakspot", -1); - GameMessages::SendNotifyObject(self->GetObjectID(), self->GetObjectID(), u"DragonRevive", UNASSIGNED_SYSTEM_ADDRESS); - } +void AmDarklingDragon::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "ReviveHeldTimer") { + self->AddTimer("backToAttack", 2.5); + } else if (timerName == "ExposeWeakSpotTimer") { + self->SetVar(u"weakspot", 1); + } else if (timerName == "timeToStunLoop") { + GameMessages::SendPlayAnimation(self, u"stunloop", 1.8f); + } else if (timerName == "ReviveTimer") { + GameMessages::SendPlayAnimation(self, u"stunend", 2.0f); + self->AddTimer("backToAttack", 1); + } else if (timerName == "backToAttack") { + auto* baseCombatAIComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); + if (baseCombatAIComponent != nullptr) { + baseCombatAIComponent->SetDisabled(false); + baseCombatAIComponent->SetStunned(false); + } + if (skillComponent != nullptr) { + skillComponent->Interrupt(); + } + self->SetVar(u"weakspot", -1); + GameMessages::SendNotifyObject(self->GetObjectID(), self->GetObjectID(), u"DragonRevive", UNASSIGNED_SYSTEM_ADDRESS); + } } -void AmDarklingDragon::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { - if (args != "rebuildDone") return; +void AmDarklingDragon::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args != "rebuildDone") return; - self->AddTimer("ExposeWeakSpotTimer", 3.8f); + self->AddTimer("ExposeWeakSpotTimer", 3.8f); - self->CancelTimer("ReviveTimer"); + self->CancelTimer("ReviveTimer"); - self->AddTimer("ReviveHeldTimer", 10.5f); + self->AddTimer("ReviveHeldTimer", 10.5f); - self->SetVar(u"Golem", sender->GetObjectID()); + self->SetVar(u"Golem", sender->GetObjectID()); - GameMessages::SendPlayAnimation(self, u"quickbuildhold", 1.9f); -} \ No newline at end of file + GameMessages::SendPlayAnimation(self, u"quickbuildhold", 1.9f); +} diff --git a/dScripts/AmDarklingDragon.h b/dScripts/AmDarklingDragon.h index ea4c2a19..5a85e329 100644 --- a/dScripts/AmDarklingDragon.h +++ b/dScripts/AmDarklingDragon.h @@ -4,45 +4,45 @@ class AmDarklingDragon : public CppScripts::Script { public: - /** - * @brief When called, this function will make self immune to stuns and initialize a weakspot boolean to false. - * - * @param self The Entity that called this function. - */ - void OnStartup(Entity* self) override; - /** - * @brief When called, this function will destroy the golem if it was alive, otherwise returns immediately. - * - * @param self The Entity that called this function. - * @param killer The Entity that killed self. - */ - void OnDie(Entity* self, Entity* killer) override; - /** - * @brief When self is hit or healed, this function will check if self is at zero armor. If self is at zero armor, a golem Entity Quick Build - * is spawned that, when built, will reveal a weakpoint on the dragon that if hit will smash the dragon instantly. If at more than zero armor, - * this function returns early. - * - * @param self The Entity that was hit. - * @param attacker The Entity that attacked self. - * @param damage The amount of damage attacker did to self. - */ - void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; - /** - * @brief Called when self has a timer that ended. - * - * @param self The Entity who owns a timer that finished. - * @param timerName The name of a timer attacked to self that has ended. - */ - void OnTimerDone(Entity* self, std::string timerName) override; - /** - * @brief When the Client has finished rebuilding the Golem for the dragon, this function exposes the weak spot for a set amount of time. - * - * @param self The Entity that called this script. - * @param sender The Entity that sent a fired event. - * @param args The argument that tells us what event has been fired off. - * @param param1 Unused in this script. - * @param param2 Unused in this script. - * @param param3 Unused in this script. - */ - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + /** + * @brief When called, this function will make self immune to stuns and initialize a weakspot boolean to false. + * + * @param self The Entity that called this function. + */ + void OnStartup(Entity* self) override; + /** + * @brief When called, this function will destroy the golem if it was alive, otherwise returns immediately. + * + * @param self The Entity that called this function. + * @param killer The Entity that killed self. + */ + void OnDie(Entity* self, Entity* killer) override; + /** + * @brief When self is hit or healed, this function will check if self is at zero armor. If self is at zero armor, a golem Entity Quick Build + * is spawned that, when built, will reveal a weakpoint on the dragon that if hit will smash the dragon instantly. If at more than zero armor, + * this function returns early. + * + * @param self The Entity that was hit. + * @param attacker The Entity that attacked self. + * @param damage The amount of damage attacker did to self. + */ + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; + /** + * @brief Called when self has a timer that ended. + * + * @param self The Entity who owns a timer that finished. + * @param timerName The name of a timer attacked to self that has ended. + */ + void OnTimerDone(Entity* self, std::string timerName) override; + /** + * @brief When the Client has finished rebuilding the Golem for the dragon, this function exposes the weak spot for a set amount of time. + * + * @param self The Entity that called this script. + * @param sender The Entity that sent a fired event. + * @param args The argument that tells us what event has been fired off. + * @param param1 Unused in this script. + * @param param2 Unused in this script. + * @param param3 Unused in this script. + */ + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; }; diff --git a/dScripts/AmDarklingMech.cpp b/dScripts/AmDarklingMech.cpp index 33c3fcbf..922296c2 100644 --- a/dScripts/AmDarklingMech.cpp +++ b/dScripts/AmDarklingMech.cpp @@ -1,7 +1,6 @@ #include "AmDarklingMech.h" -void AmDarklingMech::OnStartup(Entity* self) -{ - BaseEnemyMech::OnStartup(self); - qbTurretLOT = 13171; +void AmDarklingMech::OnStartup(Entity* self) { + BaseEnemyMech::OnStartup(self); + qbTurretLOT = 13171; } diff --git a/dScripts/AmDarklingMech.h b/dScripts/AmDarklingMech.h index cc179795..0f54ba7f 100644 --- a/dScripts/AmDarklingMech.h +++ b/dScripts/AmDarklingMech.h @@ -5,5 +5,5 @@ class AmDarklingMech : public BaseEnemyMech { public: - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/AmDrawBridge.cpp b/dScripts/AmDrawBridge.cpp index 8e52e3e4..20636b13 100644 --- a/dScripts/AmDrawBridge.cpp +++ b/dScripts/AmDrawBridge.cpp @@ -3,141 +3,119 @@ #include "GameMessages.h" #include "SimplePhysicsComponent.h" -void AmDrawBridge::OnStartup(Entity* self) -{ - self->SetNetworkVar(u"InUse", false); - self->SetVar(u"BridgeDown", false); +void AmDrawBridge::OnStartup(Entity* self) { + self->SetNetworkVar(u"InUse", false); + self->SetVar(u"BridgeDown", false); } -void AmDrawBridge::OnUse(Entity* self, Entity* user) -{ - auto* bridge = GetBridge(self); +void AmDrawBridge::OnUse(Entity* self, Entity* user) { + auto* bridge = GetBridge(self); - if (bridge == nullptr) - { - return; - } + if (bridge == nullptr) { + return; + } - if (!self->GetNetworkVar(u"InUse")) - { - self->SetNetworkVar(u"startEffect", 5); + if (!self->GetNetworkVar(u"InUse")) { + self->SetNetworkVar(u"startEffect", 5); - self->AddTimer("ChangeBridge", 5); + self->AddTimer("ChangeBridge", 5); - self->SetNetworkVar(u"InUse", true); - } + self->SetNetworkVar(u"InUse", true); + } - auto* player = user; + auto* player = user; - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } -void AmDrawBridge::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "ChangeBridge") - { - auto* bridge = GetBridge(self); +void AmDrawBridge::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "ChangeBridge") { + auto* bridge = GetBridge(self); - if (bridge == nullptr) - { - return; - } + if (bridge == nullptr) { + return; + } - if (!self->GetVar(u"BridgeDown")) - { - self->SetVar(u"BridgeDown", true); + if (!self->GetVar(u"BridgeDown")) { + self->SetVar(u"BridgeDown", true); - MoveBridgeDown(self, bridge, true); - } - else - { - self->SetVar(u"BridgeDown", false); + MoveBridgeDown(self, bridge, true); + } else { + self->SetVar(u"BridgeDown", false); - MoveBridgeDown(self, bridge, false); - } + MoveBridgeDown(self, bridge, false); + } - self->SetNetworkVar(u"BridgeLeaving", true); - self->SetVar(u"BridgeDown", false); - } - else if (timerName == "SmashEffectBridge") - { - self->SetNetworkVar(u"SmashBridge", 5); - } - else if (timerName == "rotateBridgeDown") - { - auto* bridge = GetBridge(self); + self->SetNetworkVar(u"BridgeLeaving", true); + self->SetVar(u"BridgeDown", false); + } else if (timerName == "SmashEffectBridge") { + self->SetNetworkVar(u"SmashBridge", 5); + } else if (timerName == "rotateBridgeDown") { + auto* bridge = GetBridge(self); - if (bridge == nullptr) - { - return; - } + if (bridge == nullptr) { + return; + } - self->SetNetworkVar(u"BridgeLeaving", false); + self->SetNetworkVar(u"BridgeLeaving", false); - auto* simplePhysicsComponent = bridge->GetComponent(); + auto* simplePhysicsComponent = bridge->GetComponent(); - if (simplePhysicsComponent == nullptr) - { - return; - } + if (simplePhysicsComponent == nullptr) { + return; + } - simplePhysicsComponent->SetAngularVelocity(NiPoint3::ZERO); + simplePhysicsComponent->SetAngularVelocity(NiPoint3::ZERO); - EntityManager::Instance()->SerializeEntity(bridge); - } + EntityManager::Instance()->SerializeEntity(bridge); + } } -void AmDrawBridge::OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1, int32_t param2) -{ - if (name == "BridgeBuilt") - { - self->SetVar(u"BridgeID", sender->GetObjectID()); +void AmDrawBridge::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) { + if (name == "BridgeBuilt") { + self->SetVar(u"BridgeID", sender->GetObjectID()); - self->AddTimer("SmashEffectBridge", 45); + self->AddTimer("SmashEffectBridge", 45); - self->SetNetworkVar(u"BridgeDead", true); + self->SetNetworkVar(u"BridgeDead", true); - sender->AddDieCallback([this, self, sender] () { - NotifyDie(self, sender); - }); - } + sender->AddDieCallback([this, self, sender]() { + NotifyDie(self, sender); + }); + } } -void AmDrawBridge::MoveBridgeDown(Entity* self, Entity* bridge, bool down) -{ - auto* simplePhysicsComponent = bridge->GetComponent(); +void AmDrawBridge::MoveBridgeDown(Entity* self, Entity* bridge, bool down) { + auto* simplePhysicsComponent = bridge->GetComponent(); - if (simplePhysicsComponent == nullptr) - { - return; - } + if (simplePhysicsComponent == nullptr) { + return; + } - auto forwardVect = simplePhysicsComponent->GetRotation().GetForwardVector(); + auto forwardVect = simplePhysicsComponent->GetRotation().GetForwardVector(); - auto degrees = down ? 90.0f : -90.0f; + auto degrees = down ? 90.0f : -90.0f; - const auto travelTime = 2.0f; + const auto travelTime = 2.0f; - forwardVect = forwardVect * (float) ((degrees / travelTime) * (3.14f / 180.0f)); + forwardVect = forwardVect * (float)((degrees / travelTime) * (3.14f / 180.0f)); - simplePhysicsComponent->SetAngularVelocity(forwardVect); + simplePhysicsComponent->SetAngularVelocity(forwardVect); - EntityManager::Instance()->SerializeEntity(bridge); + EntityManager::Instance()->SerializeEntity(bridge); - self->AddTimer("rotateBridgeDown", travelTime); + self->AddTimer("rotateBridgeDown", travelTime); } -void AmDrawBridge::NotifyDie(Entity* self, Entity* other) -{ - self->SetNetworkVar(u"InUse", false); - self->SetVar(u"BridgeDown", false); +void AmDrawBridge::NotifyDie(Entity* self, Entity* other) { + self->SetNetworkVar(u"InUse", false); + self->SetVar(u"BridgeDown", false); - self->CancelAllTimers(); + self->CancelAllTimers(); } -Entity* AmDrawBridge::GetBridge(Entity* self) -{ - const auto bridgeID = self->GetVar(u"BridgeID"); +Entity* AmDrawBridge::GetBridge(Entity* self) { + const auto bridgeID = self->GetVar(u"BridgeID"); - return EntityManager::Instance()->GetEntity(bridgeID); + return EntityManager::Instance()->GetEntity(bridgeID); } diff --git a/dScripts/AmDrawBridge.h b/dScripts/AmDrawBridge.h index e7b801df..86237b7f 100644 --- a/dScripts/AmDrawBridge.h +++ b/dScripts/AmDrawBridge.h @@ -4,13 +4,13 @@ class AmDrawBridge : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; - void MoveBridgeDown(Entity* self, Entity* bridge, bool down); - void NotifyDie(Entity* self, Entity* other); + void MoveBridgeDown(Entity* self, Entity* bridge, bool down); + void NotifyDie(Entity* self, Entity* other); - Entity* GetBridge(Entity* self); + Entity* GetBridge(Entity* self); }; diff --git a/dScripts/AmDropshipComputer.cpp b/dScripts/AmDropshipComputer.cpp index d25bd4f2..909beaaf 100644 --- a/dScripts/AmDropshipComputer.cpp +++ b/dScripts/AmDropshipComputer.cpp @@ -4,94 +4,78 @@ #include "InventoryComponent.h" #include "dZoneManager.h" -void AmDropshipComputer::OnStartup(Entity* self) -{ - self->AddTimer("reset", 45.0f); +void AmDropshipComputer::OnStartup(Entity* self) { + self->AddTimer("reset", 45.0f); } -void AmDropshipComputer::OnUse(Entity* self, Entity* user) -{ - auto* rebuildComponent = self->GetComponent(); +void AmDropshipComputer::OnUse(Entity* self, Entity* user) { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent == nullptr || rebuildComponent->GetState() != REBUILD_COMPLETED) - { - return; - } + if (rebuildComponent == nullptr || rebuildComponent->GetState() != REBUILD_COMPLETED) { + return; + } - auto* missionComponent = user->GetComponent(); - auto* inventoryComponent = user->GetComponent(); - - if (missionComponent == nullptr || inventoryComponent == nullptr) - { - return; - } + auto* missionComponent = user->GetComponent(); + auto* inventoryComponent = user->GetComponent(); - if (inventoryComponent->GetLotCount(m_NexusTalonDataCard) != 0 || missionComponent->GetMission(979)->GetMissionState() == MissionState::MISSION_STATE_COMPLETE) - { - return; - } + if (missionComponent == nullptr || inventoryComponent == nullptr) { + return; + } - inventoryComponent->AddItem(m_NexusTalonDataCard, 1, eLootSourceType::LOOT_SOURCE_NONE); + if (inventoryComponent->GetLotCount(m_NexusTalonDataCard) != 0 || missionComponent->GetMission(979)->GetMissionState() == MissionState::MISSION_STATE_COMPLETE) { + return; + } + + inventoryComponent->AddItem(m_NexusTalonDataCard, 1, eLootSourceType::LOOT_SOURCE_NONE); } -void AmDropshipComputer::OnDie(Entity* self, Entity* killer) -{ - const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); +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; - } + int32_t pipeNum = 0; + if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { + return; + } - const auto pipeGroup = myGroup.substr(0, 10); + const auto pipeGroup = myGroup.substr(0, 10); - const auto nextPipeNum = pipeNum + 1; + const auto nextPipeNum = pipeNum + 1; - const auto samePipeSpawners = dZoneManager::Instance()->GetSpawnersByName(myGroup); + const auto samePipeSpawners = dZoneManager::Instance()->GetSpawnersByName(myGroup); - if (!samePipeSpawners.empty()) - { - samePipeSpawners[0]->SoftReset(); + if (!samePipeSpawners.empty()) { + samePipeSpawners[0]->SoftReset(); - samePipeSpawners[0]->Deactivate(); - } + samePipeSpawners[0]->Deactivate(); + } - if (killer != nullptr && killer->IsPlayer()) - { - const auto nextPipe = pipeGroup + std::to_string(nextPipeNum); + if (killer != nullptr && killer->IsPlayer()) { + const auto nextPipe = pipeGroup + std::to_string(nextPipeNum); - const auto nextPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); + const auto nextPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); - if (!nextPipeSpawners.empty()) - { - nextPipeSpawners[0]->Activate(); - } - } - else - { - const auto nextPipe = pipeGroup + "1"; + if (!nextPipeSpawners.empty()) { + nextPipeSpawners[0]->Activate(); + } + } else { + const auto nextPipe = pipeGroup + "1"; - const auto firstPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); + const auto firstPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); - if (!firstPipeSpawners.empty()) - { - firstPipeSpawners[0]->Activate(); - } - } + if (!firstPipeSpawners.empty()) { + firstPipeSpawners[0]->Activate(); + } + } } -void AmDropshipComputer::OnTimerDone(Entity* self, std::string timerName) -{ - auto* rebuildComponent = self->GetComponent(); +void AmDropshipComputer::OnTimerDone(Entity* self, std::string timerName) { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent == nullptr) - { - return; - } + if (rebuildComponent == nullptr) { + return; + } - if (timerName == "reset" && rebuildComponent->GetState() == REBUILD_OPEN) - { - self->Smash(self->GetObjectID(), SILENT); - } + if (timerName == "reset" && rebuildComponent->GetState() == REBUILD_OPEN) { + self->Smash(self->GetObjectID(), SILENT); + } } diff --git a/dScripts/AmDropshipComputer.h b/dScripts/AmDropshipComputer.h index 620770af..730f2222 100644 --- a/dScripts/AmDropshipComputer.h +++ b/dScripts/AmDropshipComputer.h @@ -4,10 +4,10 @@ class AmDropshipComputer : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void OnDie(Entity* self, Entity* killer) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void OnDie(Entity* self, Entity* killer) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - const LOT m_NexusTalonDataCard = 12323; + const LOT m_NexusTalonDataCard = 12323; }; diff --git a/dScripts/AmScrollReaderServer.cpp b/dScripts/AmScrollReaderServer.cpp index 280833c2..cb8a7dba 100644 --- a/dScripts/AmScrollReaderServer.cpp +++ b/dScripts/AmScrollReaderServer.cpp @@ -1,17 +1,14 @@ #include "AmScrollReaderServer.h" #include "MissionComponent.h" -void AmScrollReaderServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - if (identifier == u"story_end") - { - auto* missionComponent = sender->GetComponent(); +void AmScrollReaderServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + if (identifier == u"story_end") { + auto* missionComponent = sender->GetComponent(); - if (missionComponent == nullptr) - { - return; - } + if (missionComponent == nullptr) { + return; + } - missionComponent->ForceProgressTaskType(969, 1, 1, false); - } + missionComponent->ForceProgressTaskType(969, 1, 1, false); + } } diff --git a/dScripts/AmScrollReaderServer.h b/dScripts/AmScrollReaderServer.h index b9e5943d..f00e29e0 100644 --- a/dScripts/AmScrollReaderServer.h +++ b/dScripts/AmScrollReaderServer.h @@ -4,5 +4,5 @@ class AmScrollReaderServer : public CppScripts::Script { public: - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; }; diff --git a/dScripts/AmShieldGenerator.cpp b/dScripts/AmShieldGenerator.cpp index 0e942612..d16acb87 100644 --- a/dScripts/AmShieldGenerator.cpp +++ b/dScripts/AmShieldGenerator.cpp @@ -6,167 +6,139 @@ #include "BaseCombatAIComponent.h" #include "SkillComponent.h" -void AmShieldGenerator::OnStartup(Entity* self) -{ - self->SetProximityRadius(20, "shield"); - self->SetProximityRadius(21, "buffer"); - - StartShield(self); +void AmShieldGenerator::OnStartup(Entity* self) { + self->SetProximityRadius(20, "shield"); + self->SetProximityRadius(21, "buffer"); + + StartShield(self); } -void AmShieldGenerator::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - auto* destroyableComponent = entering->GetComponent(); +void AmShieldGenerator::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + auto* destroyableComponent = entering->GetComponent(); - if (status == "ENTER" && name == "shield") - { - if (destroyableComponent->HasFaction(4)) - { - EnemyEnteredShield(self, entering); - } - } - - if (name != "buffer" || !entering->IsPlayer()) - { - return; - } + if (status == "ENTER" && name == "shield") { + if (destroyableComponent->HasFaction(4)) { + EnemyEnteredShield(self, entering); + } + } - auto entitiesInProximity = self->GetVar>(u"Players"); + if (name != "buffer" || !entering->IsPlayer()) { + return; + } - if (status == "ENTER") - { - const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); + auto entitiesInProximity = self->GetVar>(u"Players"); - if (iter == entitiesInProximity.end()) - { - entitiesInProximity.push_back(entering->GetObjectID()); - } - } - else if (status == "LEAVE") - { - const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); + if (status == "ENTER") { + const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); - if (iter != entitiesInProximity.end()) - { - entitiesInProximity.erase(iter); - } - } + if (iter == entitiesInProximity.end()) { + entitiesInProximity.push_back(entering->GetObjectID()); + } + } else if (status == "LEAVE") { + const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); - self->SetVar>(u"Players", entitiesInProximity); + if (iter != entitiesInProximity.end()) { + entitiesInProximity.erase(iter); + } + } + + self->SetVar>(u"Players", entitiesInProximity); } -void AmShieldGenerator::OnDie(Entity* self, Entity* killer) -{ - self->CancelAllTimers(); +void AmShieldGenerator::OnDie(Entity* self, Entity* killer) { + self->CancelAllTimers(); - auto* child = EntityManager::Instance()->GetEntity(self->GetVar(u"Child")); + auto* child = EntityManager::Instance()->GetEntity(self->GetVar(u"Child")); - if (child != nullptr) - { - child->Kill(); - } + if (child != nullptr) { + child->Kill(); + } } -void AmShieldGenerator::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "BuffPlayers") - { - BuffPlayers(self); +void AmShieldGenerator::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "BuffPlayers") { + BuffPlayers(self); - self->AddTimer("BuffPlayers", 3.0f); - } - else if (timerName == "PlayFX") - { - GameMessages::SendPlayFXEffect(self->GetObjectID(), 5351, u"generatorOn", "generatorOn"); + self->AddTimer("BuffPlayers", 3.0f); + } else if (timerName == "PlayFX") { + GameMessages::SendPlayFXEffect(self->GetObjectID(), 5351, u"generatorOn", "generatorOn"); - self->AddTimer("PlayFX", 1.5f); - } - else if (timerName == "RefreshEnemies") - { - auto enemiesInProximity = self->GetVar>(u"Enemies"); + self->AddTimer("PlayFX", 1.5f); + } else if (timerName == "RefreshEnemies") { + auto enemiesInProximity = self->GetVar>(u"Enemies"); - for (const auto enemyID : enemiesInProximity) - { - auto* enemy = EntityManager::Instance()->GetEntity(enemyID); + for (const auto enemyID : enemiesInProximity) { + auto* enemy = EntityManager::Instance()->GetEntity(enemyID); - if (enemy != nullptr) - { - EnemyEnteredShield(self, enemy); - } - } + if (enemy != nullptr) { + EnemyEnteredShield(self, enemy); + } + } - self->AddTimer("RefreshEnemies", 1.5f); - } + self->AddTimer("RefreshEnemies", 1.5f); + } } -void AmShieldGenerator::StartShield(Entity* self) -{ - self->AddTimer("PlayFX", 1.5f); - self->AddTimer("BuffPlayers", 3.0f); - self->AddTimer("RefreshEnemies", 1.5f); +void AmShieldGenerator::StartShield(Entity* self) { + self->AddTimer("PlayFX", 1.5f); + self->AddTimer("BuffPlayers", 3.0f); + self->AddTimer("RefreshEnemies", 1.5f); - const auto myPos = self->GetPosition(); - const auto myRot = self->GetRotation(); + const auto myPos = self->GetPosition(); + const auto myRot = self->GetRotation(); - EntityInfo info {}; - info.lot = 13111; - info.pos = myPos; - info.rot = myRot; - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = 13111; + info.pos = myPos; + info.rot = myRot; + info.spawnerID = self->GetObjectID(); - auto* child = EntityManager::Instance()->CreateEntity(info); + auto* child = EntityManager::Instance()->CreateEntity(info); - self->SetVar(u"Child", child->GetObjectID()); + self->SetVar(u"Child", child->GetObjectID()); - BuffPlayers(self); + BuffPlayers(self); } -void AmShieldGenerator::BuffPlayers(Entity* self) -{ - auto* skillComponent = self->GetComponent(); +void AmShieldGenerator::BuffPlayers(Entity* self) { + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - auto entitiesInProximity = self->GetVar>(u"Players"); + auto entitiesInProximity = self->GetVar>(u"Players"); - for (const auto playerID : entitiesInProximity) - { - auto* player = EntityManager::Instance()->GetEntity(playerID); + for (const auto playerID : entitiesInProximity) { + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - skillComponent->CalculateBehavior(1200, 27024, playerID, true); - } + skillComponent->CalculateBehavior(1200, 27024, playerID, true); + } } -void AmShieldGenerator::EnemyEnteredShield(Entity* self, Entity* intruder) -{ - auto* baseCombatAIComponent = intruder->GetComponent(); - auto* movementAIComponent = intruder->GetComponent(); +void AmShieldGenerator::EnemyEnteredShield(Entity* self, Entity* intruder) { + auto* baseCombatAIComponent = intruder->GetComponent(); + auto* movementAIComponent = intruder->GetComponent(); - if (baseCombatAIComponent == nullptr || movementAIComponent == nullptr) - { - return; - } + if (baseCombatAIComponent == nullptr || movementAIComponent == nullptr) { + return; + } - auto dir = intruder->GetRotation().GetForwardVector() * -1; - dir.y += 15; - dir.x *= 50; - dir.z *= 50; + auto dir = intruder->GetRotation().GetForwardVector() * -1; + dir.y += 15; + dir.x *= 50; + dir.z *= 50; - // TODO: Figure out how todo knockback, I'll stun them for now + // TODO: Figure out how todo knockback, I'll stun them for now - if (NiPoint3::DistanceSquared(self->GetPosition(), movementAIComponent->GetCurrentPosition()) < 20 * 20) - { - baseCombatAIComponent->Stun(2.0f); - movementAIComponent->SetDestination(baseCombatAIComponent->GetStartPosition()); - } + if (NiPoint3::DistanceSquared(self->GetPosition(), movementAIComponent->GetCurrentPosition()) < 20 * 20) { + baseCombatAIComponent->Stun(2.0f); + movementAIComponent->SetDestination(baseCombatAIComponent->GetStartPosition()); + } - baseCombatAIComponent->ClearThreat(); + baseCombatAIComponent->ClearThreat(); } diff --git a/dScripts/AmShieldGenerator.h b/dScripts/AmShieldGenerator.h index b88a89cb..9b46f021 100644 --- a/dScripts/AmShieldGenerator.h +++ b/dScripts/AmShieldGenerator.h @@ -4,12 +4,12 @@ class AmShieldGenerator : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnDie(Entity* self, Entity* killer) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnDie(Entity* self, Entity* killer) override; + void OnTimerDone(Entity* self, std::string timerName) override; - void StartShield(Entity* self); - void BuffPlayers(Entity* self); - void EnemyEnteredShield(Entity* self, Entity* intruder); + void StartShield(Entity* self); + void BuffPlayers(Entity* self); + void EnemyEnteredShield(Entity* self, Entity* intruder); }; diff --git a/dScripts/AmShieldGeneratorQuickbuild.cpp b/dScripts/AmShieldGeneratorQuickbuild.cpp index aa80148c..9f27b904 100644 --- a/dScripts/AmShieldGeneratorQuickbuild.cpp +++ b/dScripts/AmShieldGeneratorQuickbuild.cpp @@ -8,235 +8,195 @@ #include "RebuildComponent.h" #include "MissionComponent.h" -void AmShieldGeneratorQuickbuild::OnStartup(Entity* self) -{ - self->SetProximityRadius(20, "shield"); - self->SetProximityRadius(21, "buffer"); +void AmShieldGeneratorQuickbuild::OnStartup(Entity* self) { + self->SetProximityRadius(20, "shield"); + self->SetProximityRadius(21, "buffer"); } -void AmShieldGeneratorQuickbuild::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - auto* destroyableComponent = entering->GetComponent(); +void AmShieldGeneratorQuickbuild::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + auto* destroyableComponent = entering->GetComponent(); - if (name == "shield") - { - if (!destroyableComponent->HasFaction(4) || entering->IsPlayer()) - { - return; - } + if (name == "shield") { + if (!destroyableComponent->HasFaction(4) || entering->IsPlayer()) { + return; + } - auto enemiesInProximity = self->GetVar>(u"Enemies"); + auto enemiesInProximity = self->GetVar>(u"Enemies"); - if (status == "ENTER") - { - EnemyEnteredShield(self, entering); + if (status == "ENTER") { + EnemyEnteredShield(self, entering); - const auto& iter = std::find(enemiesInProximity.begin(), enemiesInProximity.end(), entering->GetObjectID()); + const auto& iter = std::find(enemiesInProximity.begin(), enemiesInProximity.end(), entering->GetObjectID()); - if (iter == enemiesInProximity.end()) - { - enemiesInProximity.push_back(entering->GetObjectID()); - } - } - else if (status == "LEAVE") - { - const auto& iter = std::find(enemiesInProximity.begin(), enemiesInProximity.end(), entering->GetObjectID()); + if (iter == enemiesInProximity.end()) { + enemiesInProximity.push_back(entering->GetObjectID()); + } + } else if (status == "LEAVE") { + const auto& iter = std::find(enemiesInProximity.begin(), enemiesInProximity.end(), entering->GetObjectID()); - if (iter != enemiesInProximity.end()) - { - enemiesInProximity.erase(iter); - } - } + if (iter != enemiesInProximity.end()) { + enemiesInProximity.erase(iter); + } + } - self->SetVar>(u"Enemies", enemiesInProximity); - } + self->SetVar>(u"Enemies", enemiesInProximity); + } - if (name != "buffer" || !entering->IsPlayer()) - { - return; - } + if (name != "buffer" || !entering->IsPlayer()) { + return; + } - auto entitiesInProximity = self->GetVar>(u"Players"); + auto entitiesInProximity = self->GetVar>(u"Players"); - if (status == "ENTER") - { - const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); + if (status == "ENTER") { + const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); - if (iter == entitiesInProximity.end()) - { - entitiesInProximity.push_back(entering->GetObjectID()); - } - } - else if (status == "LEAVE") - { - const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); + if (iter == entitiesInProximity.end()) { + entitiesInProximity.push_back(entering->GetObjectID()); + } + } else if (status == "LEAVE") { + const auto& iter = std::find(entitiesInProximity.begin(), entitiesInProximity.end(), entering->GetObjectID()); - if (iter != entitiesInProximity.end()) - { - entitiesInProximity.erase(iter); - } - } + if (iter != entitiesInProximity.end()) { + entitiesInProximity.erase(iter); + } + } - self->SetVar>(u"Players", entitiesInProximity); + self->SetVar>(u"Players", entitiesInProximity); } -void AmShieldGeneratorQuickbuild::OnDie(Entity* self, Entity* killer) -{ - self->CancelAllTimers(); +void AmShieldGeneratorQuickbuild::OnDie(Entity* self, Entity* killer) { + self->CancelAllTimers(); - auto* child = EntityManager::Instance()->GetEntity(self->GetVar(u"Child")); + auto* child = EntityManager::Instance()->GetEntity(self->GetVar(u"Child")); - if (child != nullptr) - { - child->Kill(); - } + if (child != nullptr) { + child->Kill(); + } } -void AmShieldGeneratorQuickbuild::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "BuffPlayers") - { - BuffPlayers(self); +void AmShieldGeneratorQuickbuild::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "BuffPlayers") { + BuffPlayers(self); - self->AddTimer("BuffPlayers", 3.0f); - } - else if (timerName == "PlayFX") - { - GameMessages::SendPlayFXEffect(self->GetObjectID(), 5351, u"generatorOn", "generatorOn"); + self->AddTimer("BuffPlayers", 3.0f); + } else if (timerName == "PlayFX") { + GameMessages::SendPlayFXEffect(self->GetObjectID(), 5351, u"generatorOn", "generatorOn"); - self->AddTimer("PlayFX", 1.5f); - } - else if (timerName == "RefreshEnemies") - { - auto enemiesInProximity = self->GetVar>(u"Enemies"); + self->AddTimer("PlayFX", 1.5f); + } else if (timerName == "RefreshEnemies") { + auto enemiesInProximity = self->GetVar>(u"Enemies"); - for (const auto enemyID : enemiesInProximity) - { - auto* enemy = EntityManager::Instance()->GetEntity(enemyID); + for (const auto enemyID : enemiesInProximity) { + auto* enemy = EntityManager::Instance()->GetEntity(enemyID); - if (enemy != nullptr) - { - EnemyEnteredShield(self, enemy); - } - } + if (enemy != nullptr) { + EnemyEnteredShield(self, enemy); + } + } - self->AddTimer("RefreshEnemies", 1.5f); - } + self->AddTimer("RefreshEnemies", 1.5f); + } } -void AmShieldGeneratorQuickbuild::OnRebuildComplete(Entity* self, Entity* target) -{ - StartShield(self); +void AmShieldGeneratorQuickbuild::OnRebuildComplete(Entity* self, Entity* target) { + StartShield(self); - auto enemiesInProximity = self->GetVar>(u"Enemies"); + auto enemiesInProximity = self->GetVar>(u"Enemies"); - for (const auto enemyID : enemiesInProximity) - { - auto* enemy = EntityManager::Instance()->GetEntity(enemyID); + for (const auto enemyID : enemiesInProximity) { + auto* enemy = EntityManager::Instance()->GetEntity(enemyID); - if (enemy != nullptr) - { - enemy->Smash(); - } - } + if (enemy != nullptr) { + enemy->Smash(); + } + } - auto entitiesInProximity = self->GetVar>(u"Players"); + auto entitiesInProximity = self->GetVar>(u"Players"); - for (const auto playerID : entitiesInProximity) - { - auto* player = EntityManager::Instance()->GetEntity(playerID); + for (const auto playerID : entitiesInProximity) { + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - continue; - } - - auto* missionComponent = player->GetComponent(); + if (player == nullptr) { + continue; + } - if (missionComponent == nullptr) - { - return; - } + auto* missionComponent = player->GetComponent(); - missionComponent->ForceProgressTaskType(987, 1, 1, false); - } + if (missionComponent == nullptr) { + return; + } + + missionComponent->ForceProgressTaskType(987, 1, 1, false); + } } -void AmShieldGeneratorQuickbuild::StartShield(Entity* self) -{ - self->AddTimer("PlayFX", 1.5f); - self->AddTimer("BuffPlayers", 3.0f); - self->AddTimer("RefreshEnemies", 1.5f); +void AmShieldGeneratorQuickbuild::StartShield(Entity* self) { + self->AddTimer("PlayFX", 1.5f); + self->AddTimer("BuffPlayers", 3.0f); + self->AddTimer("RefreshEnemies", 1.5f); - const auto myPos = self->GetPosition(); - const auto myRot = self->GetRotation(); + const auto myPos = self->GetPosition(); + const auto myRot = self->GetRotation(); - EntityInfo info {}; - info.lot = 13111; - info.pos = myPos; - info.rot = myRot; - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = 13111; + info.pos = myPos; + info.rot = myRot; + info.spawnerID = self->GetObjectID(); - auto* child = EntityManager::Instance()->CreateEntity(info); + auto* child = EntityManager::Instance()->CreateEntity(info); - self->SetVar(u"Child", child->GetObjectID()); + self->SetVar(u"Child", child->GetObjectID()); - BuffPlayers(self); + BuffPlayers(self); } -void AmShieldGeneratorQuickbuild::BuffPlayers(Entity* self) -{ - auto* skillComponent = self->GetComponent(); +void AmShieldGeneratorQuickbuild::BuffPlayers(Entity* self) { + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - auto entitiesInProximity = self->GetVar>(u"Players"); + auto entitiesInProximity = self->GetVar>(u"Players"); - for (const auto playerID : entitiesInProximity) - { - auto* player = EntityManager::Instance()->GetEntity(playerID); + for (const auto playerID : entitiesInProximity) { + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - skillComponent->CalculateBehavior(1200, 27024, playerID, true); - } + skillComponent->CalculateBehavior(1200, 27024, playerID, true); + } } -void AmShieldGeneratorQuickbuild::EnemyEnteredShield(Entity* self, Entity* intruder) -{ - auto* rebuildComponent = self->GetComponent(); +void AmShieldGeneratorQuickbuild::EnemyEnteredShield(Entity* self, Entity* intruder) { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent == nullptr || rebuildComponent->GetState() != REBUILD_COMPLETED) - { - return; - } + if (rebuildComponent == nullptr || rebuildComponent->GetState() != REBUILD_COMPLETED) { + return; + } - auto* baseCombatAIComponent = intruder->GetComponent(); - auto* movementAIComponent = intruder->GetComponent(); + auto* baseCombatAIComponent = intruder->GetComponent(); + auto* movementAIComponent = intruder->GetComponent(); - if (baseCombatAIComponent == nullptr || movementAIComponent == nullptr) - { - return; - } + if (baseCombatAIComponent == nullptr || movementAIComponent == nullptr) { + return; + } - auto dir = intruder->GetRotation().GetForwardVector() * -1; - dir.y += 15; - dir.x *= 50; - dir.z *= 50; + auto dir = intruder->GetRotation().GetForwardVector() * -1; + dir.y += 15; + dir.x *= 50; + dir.z *= 50; - // TODO: Figure out how todo knockback, I'll stun them for now + // TODO: Figure out how todo knockback, I'll stun them for now - if (NiPoint3::DistanceSquared(self->GetPosition(), movementAIComponent->GetCurrentPosition()) < 20 * 20) - { - baseCombatAIComponent->Stun(2.0f); - movementAIComponent->SetDestination(baseCombatAIComponent->GetStartPosition()); - } + if (NiPoint3::DistanceSquared(self->GetPosition(), movementAIComponent->GetCurrentPosition()) < 20 * 20) { + baseCombatAIComponent->Stun(2.0f); + movementAIComponent->SetDestination(baseCombatAIComponent->GetStartPosition()); + } - baseCombatAIComponent->ClearThreat(); + baseCombatAIComponent->ClearThreat(); } diff --git a/dScripts/AmShieldGeneratorQuickbuild.h b/dScripts/AmShieldGeneratorQuickbuild.h index 3a8ab61e..2aef6926 100644 --- a/dScripts/AmShieldGeneratorQuickbuild.h +++ b/dScripts/AmShieldGeneratorQuickbuild.h @@ -4,13 +4,13 @@ class AmShieldGeneratorQuickbuild : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnDie(Entity* self, Entity* killer) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnRebuildComplete(Entity* self, Entity* target) override; + void OnStartup(Entity* self) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnDie(Entity* self, Entity* killer) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnRebuildComplete(Entity* self, Entity* target) override; - void StartShield(Entity* self); - void BuffPlayers(Entity* self); - void EnemyEnteredShield(Entity* self, Entity* intruder); + void StartShield(Entity* self); + void BuffPlayers(Entity* self); + void EnemyEnteredShield(Entity* self, Entity* intruder); }; diff --git a/dScripts/AmSkeletonEngineer.cpp b/dScripts/AmSkeletonEngineer.cpp index 9ef27d75..a4972729 100644 --- a/dScripts/AmSkeletonEngineer.cpp +++ b/dScripts/AmSkeletonEngineer.cpp @@ -2,26 +2,23 @@ #include "DestroyableComponent.h" #include "SkillComponent.h" -void AmSkeletonEngineer::OnHit(Entity* self, Entity* attacker) -{ - auto* destroyableComponent = self->GetComponent(); - auto* skillComponent = self->GetComponent(); +void AmSkeletonEngineer::OnHit(Entity* self, Entity* attacker) { + auto* destroyableComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (destroyableComponent == nullptr || skillComponent == nullptr) - { - return; - } + if (destroyableComponent == nullptr || skillComponent == nullptr) { + return; + } - if (destroyableComponent->GetHealth() < 12 && !self->GetVar(u"injured")) - { - self->SetVar(u"injured", true); + if (destroyableComponent->GetHealth() < 12 && !self->GetVar(u"injured")) { + self->SetVar(u"injured", true); - skillComponent->CalculateBehavior(953, 19864, self->GetObjectID(), true); + skillComponent->CalculateBehavior(953, 19864, self->GetObjectID(), true); - const auto attackerID = attacker->GetObjectID(); + const auto attackerID = attacker->GetObjectID(); - self->AddCallbackTimer(4.5f, [this, self, attackerID] () { - self->Smash(attackerID); - }); - } + self->AddCallbackTimer(4.5f, [this, self, attackerID]() { + self->Smash(attackerID); + }); + } } diff --git a/dScripts/AmSkeletonEngineer.h b/dScripts/AmSkeletonEngineer.h index d4f6f36e..77a14d88 100644 --- a/dScripts/AmSkeletonEngineer.h +++ b/dScripts/AmSkeletonEngineer.h @@ -5,5 +5,5 @@ class AmSkeletonEngineer : public EnemyNjBuff { public: - void OnHit(Entity* self, Entity* attacker) override; + void OnHit(Entity* self, Entity* attacker) override; }; diff --git a/dScripts/AmSkullkinDrill.cpp b/dScripts/AmSkullkinDrill.cpp index d5b7e7e6..321660e2 100644 --- a/dScripts/AmSkullkinDrill.cpp +++ b/dScripts/AmSkullkinDrill.cpp @@ -5,372 +5,319 @@ #include "ProximityMonitorComponent.h" #include "MissionComponent.h" -void AmSkullkinDrill::OnStartup(Entity* self) -{ - self->SetNetworkVar(u"bIsInUse", false); - self->SetVar(u"bActive", true); +void AmSkullkinDrill::OnStartup(Entity* self) { + self->SetNetworkVar(u"bIsInUse", false); + self->SetVar(u"bActive", true); - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"spin", "active"); - - auto* movingPlatformComponent = self->GetComponent(); + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"spin", "active"); - if (movingPlatformComponent == nullptr) - { - return; - } + auto* movingPlatformComponent = self->GetComponent(); - movingPlatformComponent->SetSerialized(true); + if (movingPlatformComponent == nullptr) { + return; + } - movingPlatformComponent->GotoWaypoint(0); + movingPlatformComponent->SetSerialized(true); - auto* standObj = GetStandObj(self); + movingPlatformComponent->GotoWaypoint(0); - if (standObj != nullptr) - { - standObj->SetVar(u"bActive", true); - } + auto* standObj = GetStandObj(self); - self->SetProximityRadius(5, "spin_distance"); + if (standObj != nullptr) { + standObj->SetVar(u"bActive", true); + } + + self->SetProximityRadius(5, "spin_distance"); } -Entity* AmSkullkinDrill::GetStandObj(Entity* self) -{ - const auto& myGroup = self->GetGroups(); +Entity* AmSkullkinDrill::GetStandObj(Entity* self) { + const auto& myGroup = self->GetGroups(); - if (myGroup.empty()) - { - return nullptr; - } + if (myGroup.empty()) { + return nullptr; + } - std::string groupName = "Drill_Stand_"; + std::string groupName = "Drill_Stand_"; - groupName.push_back(myGroup[0][myGroup[0].size() - 1]); + groupName.push_back(myGroup[0][myGroup[0].size() - 1]); - const auto standObjs = EntityManager::Instance()->GetEntitiesInGroup(groupName); + const auto standObjs = EntityManager::Instance()->GetEntitiesInGroup(groupName); - if (standObjs.empty()) - { - return nullptr; - } + if (standObjs.empty()) { + return nullptr; + } - return standObjs[0]; + return standObjs[0]; } -void AmSkullkinDrill::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) -{ - if (message != "NinjagoSpinEvent" || self->GetNetworkVar(u"bIsInUse")) - { - return; - } +void AmSkullkinDrill::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message != "NinjagoSpinEvent" || self->GetNetworkVar(u"bIsInUse")) { + return; + } - auto* proximityMonitorComponent = self->GetComponent(); + auto* proximityMonitorComponent = self->GetComponent(); - if (proximityMonitorComponent == nullptr || !proximityMonitorComponent->IsInProximity("spin_distance", caster->GetObjectID())) - { - return; - } + if (proximityMonitorComponent == nullptr || !proximityMonitorComponent->IsInProximity("spin_distance", caster->GetObjectID())) { + return; + } - self->SetVar(u"activaterID", caster->GetObjectID()); + self->SetVar(u"activaterID", caster->GetObjectID()); - self->SetNetworkVar(u"bIsInUse", true); + self->SetNetworkVar(u"bIsInUse", true); - TriggerDrill(self); + TriggerDrill(self); } -void AmSkullkinDrill::TriggerDrill(Entity* self) -{ - GameMessages::SendPlayAnimation(self, u"slowdown"); +void AmSkullkinDrill::TriggerDrill(Entity* self) { + GameMessages::SendPlayAnimation(self, u"slowdown"); - self->AddTimer("killDrill", 10.0f); - - auto* standObj = GetStandObj(self); + self->AddTimer("killDrill", 10.0f); - if (standObj != nullptr) - { - standObj->SetVar(u"bActive", false); - } + auto* standObj = GetStandObj(self); - auto* movingPlatformComponent = self->GetComponent(); + if (standObj != nullptr) { + standObj->SetVar(u"bActive", false); + } - if (movingPlatformComponent == nullptr) - { - return; - } + auto* movingPlatformComponent = self->GetComponent(); - movingPlatformComponent->GotoWaypoint(1); + if (movingPlatformComponent == nullptr) { + return; + } + + movingPlatformComponent->GotoWaypoint(1); } -void AmSkullkinDrill::OnWaypointReached(Entity* self, uint32_t waypointIndex) -{ - if (waypointIndex == 1) - { - auto myPos = self->GetPosition(); - auto myRot = self->GetRotation(); +void AmSkullkinDrill::OnWaypointReached(Entity* self, uint32_t waypointIndex) { + if (waypointIndex == 1) { + auto myPos = self->GetPosition(); + auto myRot = self->GetRotation(); - myPos.y -= 21; + myPos.y -= 21; - EntityInfo info = {}; - info.lot = 12346; - info.pos = myPos; - info.rot = myRot; - info.scale = 3; // Needs the scale, otherwise attacks fail - info.spawnerID = self->GetObjectID(); + EntityInfo info = {}; + info.lot = 12346; + info.pos = myPos; + info.rot = myRot; + info.scale = 3; // Needs the scale, otherwise attacks fail + info.spawnerID = self->GetObjectID(); - auto* child = EntityManager::Instance()->CreateEntity(info); + auto* child = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(child); + EntityManager::Instance()->ConstructEntity(child); - self->SetVar(u"ChildSmash", child->GetObjectID()); + self->SetVar(u"ChildSmash", child->GetObjectID()); - child->AddDieCallback([this, self] () { - const auto& userID = self->GetVar(u"activaterID"); + child->AddDieCallback([this, self]() { + const auto& userID = self->GetVar(u"activaterID"); - auto* player = EntityManager::Instance()->GetEntity(userID); + auto* player = EntityManager::Instance()->GetEntity(userID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - OnHitOrHealResult(self, player, 1); - }); - } - - OnArrived(self, waypointIndex); + OnHitOrHealResult(self, player, 1); + }); + } + + OnArrived(self, waypointIndex); } -void AmSkullkinDrill::OnUse(Entity* self, Entity* user) -{ - if (self->GetNetworkVar(u"bIsInUse")) - { - return; - } +void AmSkullkinDrill::OnUse(Entity* self, Entity* user) { + if (self->GetNetworkVar(u"bIsInUse")) { + return; + } - self->SetNetworkVar(u"bIsInUse", true); + self->SetNetworkVar(u"bIsInUse", true); - GameMessages::SendPlayFXEffect(user->GetObjectID(), 5499, u"on-anim", "tornado"); - GameMessages::SendPlayFXEffect(user->GetObjectID(), 5502, u"on-anim", "staff"); + GameMessages::SendPlayFXEffect(user->GetObjectID(), 5499, u"on-anim", "tornado"); + GameMessages::SendPlayFXEffect(user->GetObjectID(), 5502, u"on-anim", "staff"); - const auto userID = user->GetObjectID(); + const auto userID = user->GetObjectID(); - self->SetVar(u"userID", userID); - self->SetVar(u"activaterID", userID); + self->SetVar(u"userID", userID); + self->SetVar(u"activaterID", userID); - PlayAnim(self, user, "spinjitzu-staff-windup"); - PlayCinematic(self); + PlayAnim(self, user, "spinjitzu-staff-windup"); + PlayCinematic(self); - FreezePlayer(self, user, true); + FreezePlayer(self, user, true); } -void AmSkullkinDrill::FreezePlayer(Entity* self, Entity* player, bool bFreeze) -{ - eStunState eChangeType = POP; +void AmSkullkinDrill::FreezePlayer(Entity* self, Entity* player, bool bFreeze) { + eStunState eChangeType = POP; - if (bFreeze) - { - if (player->GetIsDead()) - { - return; - } + if (bFreeze) { + if (player->GetIsDead()) { + return; + } - eChangeType = PUSH; - } - else - { - if (player->GetIsDead()) - { - // - } - } - - GameMessages::SendSetStunned(player->GetObjectID(), eChangeType, player->GetSystemAddress(), self->GetObjectID(), - true, false, true, false, true, false, true - ); + eChangeType = PUSH; + } else { + if (player->GetIsDead()) { + // + } + } + + GameMessages::SendSetStunned(player->GetObjectID(), eChangeType, player->GetSystemAddress(), self->GetObjectID(), + true, false, true, false, true, false, true + ); } -void AmSkullkinDrill::OnArrived(Entity* self, uint32_t waypointIndex) -{ - auto* standObj = GetStandObj(self); +void AmSkullkinDrill::OnArrived(Entity* self, uint32_t waypointIndex) { + auto* standObj = GetStandObj(self); - if (waypointIndex == 1) - { - GameMessages::SendPlayAnimation(self, u"no-spin"); - GameMessages::SendStopFXEffect(self, true, "active"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"indicator", "indicator"); + if (waypointIndex == 1) { + GameMessages::SendPlayAnimation(self, u"no-spin"); + GameMessages::SendStopFXEffect(self, true, "active"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"indicator", "indicator"); - self->SetVar(u"bActive", false); - - const auto playerID = self->GetVar(u"userID"); + self->SetVar(u"bActive", false); - auto* player = EntityManager::Instance()->GetEntity(playerID); + const auto playerID = self->GetVar(u"userID"); - if (player != nullptr) - { - PlayAnim(self, player, "spinjitzu-staff-end"); - } + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (standObj != nullptr) - { - standObj->SetVar(u"bActive", false); - } + if (player != nullptr) { + PlayAnim(self, player, "spinjitzu-staff-end"); + } - return; - } - else - { - GameMessages::SendPlayAnimation(self, u"idle"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"spin", "active"); - GameMessages::SendStopFXEffect(self, true, "indicator"); - } + if (standObj != nullptr) { + standObj->SetVar(u"bActive", false); + } + + return; + } else { + GameMessages::SendPlayAnimation(self, u"idle"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"spin", "active"); + GameMessages::SendStopFXEffect(self, true, "indicator"); + } } -void AmSkullkinDrill::PlayCinematic(Entity* self) -{ - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(u"userID")); +void AmSkullkinDrill::PlayCinematic(Entity* self) { + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(u"userID")); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - const auto& cine = self->GetVar(u"cinematic"); + const auto& cine = self->GetVar(u"cinematic"); - if (cine.empty()) - { - return; - } + if (cine.empty()) { + return; + } - GameMessages::SendPlayCinematic(player->GetObjectID(), cine, player->GetSystemAddress()); + GameMessages::SendPlayCinematic(player->GetObjectID(), cine, player->GetSystemAddress()); } -void AmSkullkinDrill::PlayAnim(Entity* self, Entity* player, const std::string& animName) -{ - const auto animTime = animName == "spinjitzu-staff-end" ? 0.5f : 1.0f; +void AmSkullkinDrill::PlayAnim(Entity* self, Entity* player, const std::string& animName) { + const auto animTime = animName == "spinjitzu-staff-end" ? 0.5f : 1.0f; - GameMessages::SendPlayAnimation(player, GeneralUtils::ASCIIToUTF16(animName)); + GameMessages::SendPlayAnimation(player, GeneralUtils::ASCIIToUTF16(animName)); - self->AddTimer("AnimDone_" + animName, animTime); + self->AddTimer("AnimDone_" + animName, animTime); } -void AmSkullkinDrill::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) -{ - auto* destroyableComponent = self->GetComponent(); +void AmSkullkinDrill::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { + auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent == nullptr || !attacker->IsPlayer()) - { - return; - } + if (destroyableComponent == nullptr || !attacker->IsPlayer()) { + return; + } - if (self->GetVar(u"bActive")) - { - return; - } + if (self->GetVar(u"bActive")) { + return; + } - const auto activaterID = self->GetVar(u"activaterID"); + const auto activaterID = self->GetVar(u"activaterID"); - auto* activator = EntityManager::Instance()->GetEntity(activaterID); + auto* activator = EntityManager::Instance()->GetEntity(activaterID); - // TODO: Missions - if (activator != nullptr) - { - auto* missionComponent = activator->GetComponent(); + // TODO: Missions + if (activator != nullptr) { + auto* missionComponent = activator->GetComponent(); - if (missionComponent != nullptr) - { - for (const auto missionID : m_MissionsToUpdate) - { - missionComponent->ForceProgressValue(missionID, 1, self->GetLOT()); - } - } - } + if (missionComponent != nullptr) { + for (const auto missionID : m_MissionsToUpdate) { + missionComponent->ForceProgressValue(missionID, 1, self->GetLOT()); + } + } + } - self->Smash(attacker->GetObjectID(), SILENT); + self->Smash(attacker->GetObjectID(), SILENT); - self->CancelAllTimers(); + self->CancelAllTimers(); - auto* standObj = GetStandObj(self); + auto* standObj = GetStandObj(self); - if (standObj != nullptr) - { - GameMessages::SendPlayFXEffect(standObj->GetObjectID(), 4946, u"explode", "explode"); - } + if (standObj != nullptr) { + GameMessages::SendPlayFXEffect(standObj->GetObjectID(), 4946, u"explode", "explode"); + } } -void AmSkullkinDrill::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "killDrill") - { - const auto childID = self->GetVar(u"ChildSmash"); +void AmSkullkinDrill::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "killDrill") { + const auto childID = self->GetVar(u"ChildSmash"); - auto* child = EntityManager::Instance()->GetEntity(childID); + auto* child = EntityManager::Instance()->GetEntity(childID); - if (child != nullptr) - { - child->Smash(self->GetObjectID(), SILENT); - } + if (child != nullptr) { + child->Smash(self->GetObjectID(), SILENT); + } - self->SetNetworkVar(u"bIsInUse", false); - self->SetVar(u"bActive", true); - self->SetVar(u"activaterID", LWOOBJID_EMPTY); + self->SetNetworkVar(u"bIsInUse", false); + self->SetVar(u"bActive", true); + self->SetVar(u"activaterID", LWOOBJID_EMPTY); - auto* standObj = GetStandObj(self); + auto* standObj = GetStandObj(self); - if (standObj != nullptr) - { - standObj->SetVar(u"bActive", true); - } + if (standObj != nullptr) { + standObj->SetVar(u"bActive", true); + } - auto* movingPlatformComponent = self->GetComponent(); + auto* movingPlatformComponent = self->GetComponent(); - if (movingPlatformComponent == nullptr) - { - return; - } + if (movingPlatformComponent == nullptr) { + return; + } - movingPlatformComponent->GotoWaypoint(0); + movingPlatformComponent->GotoWaypoint(0); - return; - } + return; + } - const auto& data = GeneralUtils::SplitString(timerName, '_'); + const auto& data = GeneralUtils::SplitString(timerName, '_'); - if (data.empty()) - { - return; - } + if (data.empty()) { + return; + } - if (data[0] == "AnimDone") - { - const auto& animName = data[1]; + if (data[0] == "AnimDone") { + const auto& animName = data[1]; - const auto playerID = self->GetVar(u"userID"); + const auto playerID = self->GetVar(u"userID"); - auto* player = EntityManager::Instance()->GetEntity(playerID); + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - if (animName == "spinjitzu-staff-windup") - { - TriggerDrill(self); + if (animName == "spinjitzu-staff-windup") { + TriggerDrill(self); - GameMessages::SendPlayAnimation(player, u"spinjitzu-staff-loop"); - } - else if (animName == "spinjitzu-staff-end") - { - FreezePlayer(self, player, false); + GameMessages::SendPlayAnimation(player, u"spinjitzu-staff-loop"); + } else if (animName == "spinjitzu-staff-end") { + FreezePlayer(self, player, false); - self->SetVar(u"userID", LWOOBJID_EMPTY); + self->SetVar(u"userID", LWOOBJID_EMPTY); - GameMessages::SendStopFXEffect(player, true, "tornado"); - GameMessages::SendStopFXEffect(player, true, "staff"); - } + GameMessages::SendStopFXEffect(player, true, "tornado"); + GameMessages::SendStopFXEffect(player, true, "staff"); + } - } - else if (data[0] == "TryUnFreezeAgain") - { + } else if (data[0] == "TryUnFreezeAgain") { - } + } } diff --git a/dScripts/AmSkullkinDrill.h b/dScripts/AmSkullkinDrill.h index a996cefd..5e6c3179 100644 --- a/dScripts/AmSkullkinDrill.h +++ b/dScripts/AmSkullkinDrill.h @@ -4,30 +4,30 @@ class AmSkullkinDrill : public CppScripts::Script { public: - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; - Entity* GetStandObj(Entity* self); + Entity* GetStandObj(Entity* self); - void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; - void TriggerDrill(Entity* self); + void TriggerDrill(Entity* self); - void OnWaypointReached(Entity* self, uint32_t waypointIndex) override; + void OnWaypointReached(Entity* self, uint32_t waypointIndex) override; - void OnUse(Entity* self, Entity* user) override; + void OnUse(Entity* self, Entity* user) override; - void FreezePlayer(Entity* self, Entity* player, bool bFreeze); + void FreezePlayer(Entity* self, Entity* player, bool bFreeze); - void OnArrived(Entity* self, uint32_t waypointIndex); + void OnArrived(Entity* self, uint32_t waypointIndex); - void PlayCinematic(Entity* self); + void PlayCinematic(Entity* self); - void PlayAnim(Entity* self, Entity* player, const std::string& animName); + void PlayAnim(Entity* self, Entity* player, const std::string& animName); - void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - std::vector m_MissionsToUpdate = {972, 1305, 1308}; + std::vector m_MissionsToUpdate = { 972, 1305, 1308 }; }; diff --git a/dScripts/AmSkullkinDrillStand.cpp b/dScripts/AmSkullkinDrillStand.cpp index ddae2f60..628d616a 100644 --- a/dScripts/AmSkullkinDrillStand.cpp +++ b/dScripts/AmSkullkinDrillStand.cpp @@ -2,39 +2,34 @@ #include "GameMessages.h" #include "dpEntity.h" -void AmSkullkinDrillStand::OnStartup(Entity* self) -{ - self->SetVar(u"bActive", true); +void AmSkullkinDrillStand::OnStartup(Entity* self) { + self->SetVar(u"bActive", true); - self->SetProximityRadius(new dpEntity(self->GetObjectID(), {6, 14, 6}), "knockback"); + self->SetProximityRadius(new dpEntity(self->GetObjectID(), { 6, 14, 6 }), "knockback"); } -void AmSkullkinDrillStand::OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1, int32_t param2) -{ - +void AmSkullkinDrillStand::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) { + } -void AmSkullkinDrillStand::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (!self->GetVar(u"bActive")) - { - return; - } +void AmSkullkinDrillStand::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (!self->GetVar(u"bActive")) { + return; + } - if (!entering->IsPlayer() || status != "ENTER" || name != "knockback") - { - return; - } + if (!entering->IsPlayer() || status != "ENTER" || name != "knockback") { + return; + } - auto myPos = self->GetPosition(); + auto myPos = self->GetPosition(); - auto objPos = entering->GetPosition(); + auto objPos = entering->GetPosition(); - NiPoint3 newVec = {(objPos.x - myPos.x) * 4.5f, 15, (objPos.z - myPos.z) * 4.5f}; + NiPoint3 newVec = { (objPos.x - myPos.x) * 4.5f, 15, (objPos.z - myPos.z) * 4.5f }; - GameMessages::SendKnockback(entering->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 0, newVec); + GameMessages::SendKnockback(entering->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 0, newVec); - GameMessages::SendPlayFXEffect(entering->GetObjectID(), 1378, u"create", "pushBack"); - - GameMessages::SendPlayAnimation(entering, u"knockback-recovery"); + GameMessages::SendPlayFXEffect(entering->GetObjectID(), 1378, u"create", "pushBack"); + + GameMessages::SendPlayAnimation(entering, u"knockback-recovery"); } diff --git a/dScripts/AmSkullkinDrillStand.h b/dScripts/AmSkullkinDrillStand.h index 3879b3b4..673dee05 100644 --- a/dScripts/AmSkullkinDrillStand.h +++ b/dScripts/AmSkullkinDrillStand.h @@ -4,9 +4,9 @@ class AmSkullkinDrillStand : public CppScripts::Script { public: - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; - void OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; + void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; }; diff --git a/dScripts/AmSkullkinTower.cpp b/dScripts/AmSkullkinTower.cpp index 1b9e8c6d..180bbdac 100644 --- a/dScripts/AmSkullkinTower.cpp +++ b/dScripts/AmSkullkinTower.cpp @@ -5,278 +5,239 @@ #include "GameMessages.h" #include "MissionComponent.h" -void AmSkullkinTower::OnStartup(Entity* self) -{ - self->SetProximityRadius(20, "Tower"); +void AmSkullkinTower::OnStartup(Entity* self) { + self->SetProximityRadius(20, "Tower"); - // onPhysicsComponentReady + // onPhysicsComponentReady - auto* movingPlatformComponent = self->GetComponent(); + auto* movingPlatformComponent = self->GetComponent(); - if (movingPlatformComponent != nullptr) - { - movingPlatformComponent->StopPathing(); - } + if (movingPlatformComponent != nullptr) { + movingPlatformComponent->StopPathing(); + } - SpawnLegs(self, "Left"); - SpawnLegs(self, "Right"); - SpawnLegs(self, "Rear"); + SpawnLegs(self, "Left"); + SpawnLegs(self, "Right"); + SpawnLegs(self, "Rear"); } -void AmSkullkinTower::SpawnLegs(Entity* self, const std::string& loc) -{ - auto pos = self->GetPosition(); - auto rot = self->GetRotation(); - pos.y += self->GetVarAs(u"vert_offset"); +void AmSkullkinTower::SpawnLegs(Entity* self, const std::string& loc) { + auto pos = self->GetPosition(); + auto rot = self->GetRotation(); + pos.y += self->GetVarAs(u"vert_offset"); - auto newRot = rot; - auto offset = self->GetVarAs(u"hort_offset"); + auto newRot = rot; + auto offset = self->GetVarAs(u"hort_offset"); - auto legLOT = self->GetVar(u"legLOT"); + auto legLOT = self->GetVar(u"legLOT"); - if (legLOT == 0) - { - return; - } + if (legLOT == 0) { + return; + } - std::vector config = { new LDFData(u"Leg", loc) }; + std::vector config = { new LDFData(u"Leg", loc) }; - EntityInfo info {}; - info.lot = legLOT; - info.spawnerID = self->GetObjectID(); - info.settings = config; - info.rot = newRot; + EntityInfo info{}; + info.lot = legLOT; + info.spawnerID = self->GetObjectID(); + info.settings = config; + info.rot = newRot; - if (loc == "Right") - { - const auto dir = rot.GetForwardVector(); - pos.x += dir.x * offset; - pos.z += dir.z * offset; - info.pos = pos; - } - else if (loc == "Rear") - { - const auto dir = rot.GetRightVector(); - pos.x += dir.x * offset; - pos.z += dir.z * offset; - info.pos = pos; - } - else if (loc == "Left") - { - const auto dir = rot.GetForwardVector() * -1; - pos.x += dir.x * offset; - pos.z += dir.z * offset; - info.pos = pos; - } + if (loc == "Right") { + const auto dir = rot.GetForwardVector(); + pos.x += dir.x * offset; + pos.z += dir.z * offset; + info.pos = pos; + } else if (loc == "Rear") { + const auto dir = rot.GetRightVector(); + pos.x += dir.x * offset; + pos.z += dir.z * offset; + info.pos = pos; + } else if (loc == "Left") { + const auto dir = rot.GetForwardVector() * -1; + pos.x += dir.x * offset; + pos.z += dir.z * offset; + info.pos = pos; + } - info.rot = NiQuaternion::LookAt(info.pos, self->GetPosition()); + info.rot = NiQuaternion::LookAt(info.pos, self->GetPosition()); - auto* entity = EntityManager::Instance()->CreateEntity(info); + auto* entity = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(entity); + EntityManager::Instance()->ConstructEntity(entity); - OnChildLoaded(self, entity); + OnChildLoaded(self, entity); } -void AmSkullkinTower::OnChildLoaded(Entity* self, Entity* child) -{ - auto legTable = self->GetVar>(u"legTable"); +void AmSkullkinTower::OnChildLoaded(Entity* self, Entity* child) { + auto legTable = self->GetVar>(u"legTable"); - legTable.push_back(child->GetObjectID()); + legTable.push_back(child->GetObjectID()); - self->SetVar(u"legTable", legTable); + self->SetVar(u"legTable", legTable); - const auto selfID = self->GetObjectID(); + const auto selfID = self->GetObjectID(); - child->AddDieCallback([this, selfID, child] () { - auto* self = EntityManager::Instance()->GetEntity(selfID); - auto* destroyableComponent = child->GetComponent(); + child->AddDieCallback([this, selfID, child]() { + auto* self = EntityManager::Instance()->GetEntity(selfID); + auto* destroyableComponent = child->GetComponent(); - if (destroyableComponent == nullptr || self == nullptr) - { - return; - } + if (destroyableComponent == nullptr || self == nullptr) { + return; + } - NotifyDie(self, child, destroyableComponent->GetKiller()); - }); + NotifyDie(self, child, destroyableComponent->GetKiller()); + }); } -void AmSkullkinTower::NotifyDie(Entity* self, Entity* other, Entity* killer) -{ - auto players = self->GetVar>(u"Players"); +void AmSkullkinTower::NotifyDie(Entity* self, Entity* other, Entity* killer) { + auto players = self->GetVar>(u"Players"); - const auto& iter = std::find(players.begin(), players.end(), killer->GetObjectID()); + const auto& iter = std::find(players.begin(), players.end(), killer->GetObjectID()); - if (iter == players.end()) - { - players.push_back(killer->GetObjectID()); - } + if (iter == players.end()) { + players.push_back(killer->GetObjectID()); + } - self->SetVar(u"Players", players); + self->SetVar(u"Players", players); - OnChildRemoved(self, other); + OnChildRemoved(self, other); } -void AmSkullkinTower::OnChildRemoved(Entity* self, Entity* child) -{ - auto legTable = self->GetVar>(u"legTable"); +void AmSkullkinTower::OnChildRemoved(Entity* self, Entity* child) { + auto legTable = self->GetVar>(u"legTable"); - const auto& iter = std::find(legTable.begin(), legTable.end(), child->GetObjectID()); + const auto& iter = std::find(legTable.begin(), legTable.end(), child->GetObjectID()); - if (iter != legTable.end()) - { - legTable.erase(iter); - } + if (iter != legTable.end()) { + legTable.erase(iter); + } - self->SetVar(u"legTable", legTable); + self->SetVar(u"legTable", legTable); - if (legTable.size() == 2) - { - GameMessages::SendPlayAnimation(self, u"wobble-1"); - } - else if (legTable.size() == 1) - { - GameMessages::SendPlayAnimation(self, u"wobble-2"); - } - else if (legTable.empty()) - { - const auto animTime = 2.5f; + if (legTable.size() == 2) { + GameMessages::SendPlayAnimation(self, u"wobble-1"); + } else if (legTable.size() == 1) { + GameMessages::SendPlayAnimation(self, u"wobble-2"); + } else if (legTable.empty()) { + const auto animTime = 2.5f; - GameMessages::SendPlayAnimation(self, u"fall"); + GameMessages::SendPlayAnimation(self, u"fall"); - self->AddTimer("spawnGuys", animTime - 0.2f); + self->AddTimer("spawnGuys", animTime - 0.2f); - self->CancelTimer("RespawnLeg"); - self->CancelTimer("RespawnLeg"); - self->CancelTimer("RespawnLeg"); + self->CancelTimer("RespawnLeg"); + self->CancelTimer("RespawnLeg"); + self->CancelTimer("RespawnLeg"); - std::vector missionIDs; + std::vector missionIDs; - auto missionsString = self->GetVar(u"missions"); + auto missionsString = self->GetVar(u"missions"); - if (!missionsString.empty()) - { - // Split the missions string by '_' - const auto missions = GeneralUtils::SplitString( - GeneralUtils::UTF16ToWTF8(missionsString), - '_' - ); + if (!missionsString.empty()) { + // Split the missions string by '_' + const auto missions = GeneralUtils::SplitString( + GeneralUtils::UTF16ToWTF8(missionsString), + '_' + ); - for (const auto& mission : missions) - { - int32_t missionID = 0; + for (const auto& mission : missions) { + int32_t missionID = 0; - if (!GeneralUtils::TryParse(mission, missionID)) - { - continue; - } + if (!GeneralUtils::TryParse(mission, missionID)) { + continue; + } - missionIDs.push_back(missionID); - } - } + missionIDs.push_back(missionID); + } + } - const auto& players = self->GetVar>(u"Players"); + const auto& players = self->GetVar>(u"Players"); - for (const auto& playerID : players) - { - auto* player = EntityManager::Instance()->GetEntity(playerID); - - if (player == nullptr) - { - continue; - } + for (const auto& playerID : players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); - auto* missionComponent = player->GetComponent(); + if (player == nullptr) { + continue; + } - if (missionComponent == nullptr) - { - continue; - } + auto* missionComponent = player->GetComponent(); - for (const auto missionID : missionIDs) - { - missionComponent->ForceProgressValue(missionID, 1, self->GetLOT()); - } + if (missionComponent == nullptr) { + continue; + } - //missionComponent->ForceProgressValue(1305, 1, self->GetLOT()); - } - } + for (const auto missionID : missionIDs) { + missionComponent->ForceProgressValue(missionID, 1, self->GetLOT()); + } - auto deadLegs = self->GetVar>(u"DeadLegs"); + //missionComponent->ForceProgressValue(1305, 1, self->GetLOT()); + } + } - const auto& leg = child->GetVar(u"Leg"); + auto deadLegs = self->GetVar>(u"DeadLegs"); - const auto& legIter = std::find(deadLegs.begin(), deadLegs.end(), leg); + const auto& leg = child->GetVar(u"Leg"); - if (legIter == deadLegs.end()) - { - deadLegs.push_back(leg); - } + const auto& legIter = std::find(deadLegs.begin(), deadLegs.end(), leg); - self->SetVar(u"DeadLegs", deadLegs); + if (legIter == deadLegs.end()) { + deadLegs.push_back(leg); + } - self->AddTimer("RespawnLeg", 20); + self->SetVar(u"DeadLegs", deadLegs); + + self->AddTimer("RespawnLeg", 20); } -void AmSkullkinTower::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (status != "LEAVE") - { - return; - } +void AmSkullkinTower::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (status != "LEAVE") { + return; + } - auto players = self->GetVar>(u"Players"); + auto players = self->GetVar>(u"Players"); - const auto& iter = std::find(players.begin(), players.end(), entering->GetObjectID()); + const auto& iter = std::find(players.begin(), players.end(), entering->GetObjectID()); - if (iter != players.end()) - { - players.erase(iter); - } + if (iter != players.end()) { + players.erase(iter); + } - self->SetVar(u"Players", players); + self->SetVar(u"Players", players); } -void AmSkullkinTower::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "RespawnLeg") - { - auto deadLegs = self->GetVar>(u"DeadLegs"); +void AmSkullkinTower::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "RespawnLeg") { + auto deadLegs = self->GetVar>(u"DeadLegs"); - if (deadLegs.empty()) - { - return; - } + if (deadLegs.empty()) { + return; + } - SpawnLegs(self, deadLegs[0]); + SpawnLegs(self, deadLegs[0]); - deadLegs.erase(deadLegs.begin()); + deadLegs.erase(deadLegs.begin()); - self->SetVar>(u"DeadLegs", deadLegs); - } - else if (timerName == "spawnGuys") - { - EntityInfo info {}; - info.lot = self->GetVar(u"enemyToSpawn"); - auto pos = self->GetPosition(); - pos.y += 7; - info.pos = pos; - info.rot = self->GetRotation(); - info.spawnerID = self->GetObjectID(); - - for (size_t i = 0; i < 2; i++) - { - info.pos.x += i * 2; // Just to set the apart a bit + self->SetVar>(u"DeadLegs", deadLegs); + } else if (timerName == "spawnGuys") { + EntityInfo info{}; + info.lot = self->GetVar(u"enemyToSpawn"); + auto pos = self->GetPosition(); + pos.y += 7; + info.pos = pos; + info.rot = self->GetRotation(); + info.spawnerID = self->GetObjectID(); - auto* entity = EntityManager::Instance()->CreateEntity(info); + for (size_t i = 0; i < 2; i++) { + info.pos.x += i * 2; // Just to set the apart a bit - EntityManager::Instance()->ConstructEntity(entity); - } + auto* entity = EntityManager::Instance()->CreateEntity(info); - self->AddTimer("killTower", 0.7f); - } - else if (timerName == "killTower") - { - self->Smash(self->GetObjectID()); - } + EntityManager::Instance()->ConstructEntity(entity); + } + + self->AddTimer("killTower", 0.7f); + } else if (timerName == "killTower") { + self->Smash(self->GetObjectID()); + } } diff --git a/dScripts/AmSkullkinTower.h b/dScripts/AmSkullkinTower.h index c7d6a732..495641de 100644 --- a/dScripts/AmSkullkinTower.h +++ b/dScripts/AmSkullkinTower.h @@ -4,17 +4,17 @@ class AmSkullkinTower : public CppScripts::Script { public: - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; - void SpawnLegs(Entity* self, const std::string& loc); + void SpawnLegs(Entity* self, const std::string& loc); - void OnChildLoaded(Entity* self, Entity* child); + void OnChildLoaded(Entity* self, Entity* child); - void NotifyDie(Entity* self, Entity* other, Entity* killer); + void NotifyDie(Entity* self, Entity* other, Entity* killer); - void OnChildRemoved(Entity* self, Entity* child); + void OnChildRemoved(Entity* self, Entity* child); - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/AmTeapotServer.cpp b/dScripts/AmTeapotServer.cpp index 17b95eeb..32abafd6 100644 --- a/dScripts/AmTeapotServer.cpp +++ b/dScripts/AmTeapotServer.cpp @@ -7,7 +7,7 @@ void AmTeapotServer::OnUse(Entity* self, Entity* user) { auto* inventoryComponent = user->GetComponent(); if (!inventoryComponent) return; - if (inventoryComponent->GetLotCount(BLUE_FLOWER_LEAVES) >= 10){ + if (inventoryComponent->GetLotCount(BLUE_FLOWER_LEAVES) >= 10) { inventoryComponent->RemoveItem(BLUE_FLOWER_LEAVES, 10); inventoryComponent->AddItem(WU_S_IMAGINATION_TEA, 1); } diff --git a/dScripts/AmTeapotServer.h b/dScripts/AmTeapotServer.h index 19cb5639..3ba2e331 100644 --- a/dScripts/AmTeapotServer.h +++ b/dScripts/AmTeapotServer.h @@ -2,9 +2,9 @@ #include "CppScripts.h" class AmTeapotServer : public CppScripts::Script { - public: - void OnUse(Entity* self, Entity* user) override; - private: - LOT BLUE_FLOWER_LEAVES = 12317; - LOT WU_S_IMAGINATION_TEA = 12109; +public: + void OnUse(Entity* self, Entity* user) override; +private: + LOT BLUE_FLOWER_LEAVES = 12317; + LOT WU_S_IMAGINATION_TEA = 12109; }; diff --git a/dScripts/AmTemplateSkillVolume.cpp b/dScripts/AmTemplateSkillVolume.cpp index a0d2a95e..3acc9063 100644 --- a/dScripts/AmTemplateSkillVolume.cpp +++ b/dScripts/AmTemplateSkillVolume.cpp @@ -1,27 +1,23 @@ #include "AmTemplateSkillVolume.h" #include "MissionComponent.h" -void AmTemplateSkillVolume::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) -{ - if (message != "NinjagoSpinAttackEvent") - { - return; - } +void AmTemplateSkillVolume::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message != "NinjagoSpinAttackEvent") { + return; + } - auto* missionComponent = caster->GetComponent(); + auto* missionComponent = caster->GetComponent(); - const auto missionIDsVariable = GeneralUtils::UTF16ToWTF8(self->GetVar(u"missions")); - const auto missionIDs = GeneralUtils::SplitString(missionIDsVariable, '_'); + const auto missionIDsVariable = GeneralUtils::UTF16ToWTF8(self->GetVar(u"missions")); + const auto missionIDs = GeneralUtils::SplitString(missionIDsVariable, '_'); - for (const auto& missionIDStr : missionIDs) - { - int32_t missionID = 0; + for (const auto& missionIDStr : missionIDs) { + int32_t missionID = 0; - if (!GeneralUtils::TryParse(missionIDStr, missionID)) - { - continue; - } + if (!GeneralUtils::TryParse(missionIDStr, missionID)) { + continue; + } - missionComponent->ForceProgressTaskType(missionID, 1, 1, false); - } + missionComponent->ForceProgressTaskType(missionID, 1, 1, false); + } } diff --git a/dScripts/AmTemplateSkillVolume.h b/dScripts/AmTemplateSkillVolume.h index ab912f4d..f4002213 100644 --- a/dScripts/AmTemplateSkillVolume.h +++ b/dScripts/AmTemplateSkillVolume.h @@ -4,5 +4,5 @@ class AmTemplateSkillVolume : public CppScripts::Script { public: - void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; }; diff --git a/dScripts/AnvilOfArmor.cpp b/dScripts/AnvilOfArmor.cpp index f3712ff2..3704cb00 100644 --- a/dScripts/AnvilOfArmor.cpp +++ b/dScripts/AnvilOfArmor.cpp @@ -1,13 +1,13 @@ #include "AnvilOfArmor.h" -void AnvilOfArmor::OnStartup(Entity *self) { - self->SetVar(u"numCycles", 8); - self->SetVar(u"secPerCycle", 25.0f); - self->SetVar(u"delayToFirstCycle", 1.5f); - self->SetVar(u"deathDelay", 25.0f); - self->SetVar(u"numberOfPowerups", 4); - self->SetVar(u"lootLOT", 6431); +void AnvilOfArmor::OnStartup(Entity* self) { + self->SetVar(u"numCycles", 8); + self->SetVar(u"secPerCycle", 25.0f); + self->SetVar(u"delayToFirstCycle", 1.5f); + self->SetVar(u"deathDelay", 25.0f); + self->SetVar(u"numberOfPowerups", 4); + self->SetVar(u"lootLOT", 6431); - // Initiate the actual script - OnTemplateStartup(self); + // Initiate the actual script + OnTemplateStartup(self); } diff --git a/dScripts/AnvilOfArmor.h b/dScripts/AnvilOfArmor.h index 64c95216..2ff568aa 100644 --- a/dScripts/AnvilOfArmor.h +++ b/dScripts/AnvilOfArmor.h @@ -2,5 +2,5 @@ #include "ScriptedPowerupSpawner.h" class AnvilOfArmor : public ScriptedPowerupSpawner { - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/BankInteractServer.cpp b/dScripts/BankInteractServer.cpp index dc119056..db5ebb98 100644 --- a/dScripts/BankInteractServer.cpp +++ b/dScripts/BankInteractServer.cpp @@ -1,26 +1,23 @@ #include "BankInteractServer.h" #include "GameMessages.h" -void BankInteractServer::OnUse(Entity* self, Entity* user) -{ - AMFArrayValue args; - AMFStringValue* bank = new AMFStringValue(); - bank->SetStringValue("bank"); - args.InsertValue("state", bank); +void BankInteractServer::OnUse(Entity* self, Entity* user) { + AMFArrayValue args; + AMFStringValue* bank = new AMFStringValue(); + bank->SetStringValue("bank"); + args.InsertValue("state", bank); - GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); + GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); } -void BankInteractServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) -{ - if (args == "ToggleBank") - { - AMFArrayValue args; +void BankInteractServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (args == "ToggleBank") { + AMFArrayValue args; args.InsertValue("visible", new AMFFalseValue()); - GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleBank", &args); + GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleBank", &args); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"CloseBank", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); - } + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"CloseBank", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); + } } diff --git a/dScripts/BankInteractServer.h b/dScripts/BankInteractServer.h index 45a40fe0..3fe4d25c 100644 --- a/dScripts/BankInteractServer.h +++ b/dScripts/BankInteractServer.h @@ -4,7 +4,7 @@ class BankInteractServer : public CppScripts::Script { public: - void OnUse(Entity* self, Entity* user) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnUse(Entity* self, Entity* user) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/BaseConsoleTeleportServer.cpp b/dScripts/BaseConsoleTeleportServer.cpp index 6475e025..a8538de5 100644 --- a/dScripts/BaseConsoleTeleportServer.cpp +++ b/dScripts/BaseConsoleTeleportServer.cpp @@ -2,120 +2,101 @@ #include "GameMessages.h" #include "Player.h" -void BaseConsoleTeleportServer::BaseOnUse(Entity* self, Entity* user) -{ - auto* player = user; +void BaseConsoleTeleportServer::BaseOnUse(Entity* self, Entity* user) { + auto* player = user; - const auto& teleportLocString = self->GetVar(u"teleportString"); + const auto& teleportLocString = self->GetVar(u"teleportString"); - GameMessages::SendDisplayMessageBox(player->GetObjectID(), true, self->GetObjectID(), u"TransferBox", 0, teleportLocString, u"", player->GetSystemAddress()); + GameMessages::SendDisplayMessageBox(player->GetObjectID(), true, self->GetObjectID(), u"TransferBox", 0, teleportLocString, u"", player->GetSystemAddress()); } -void BaseConsoleTeleportServer::BaseOnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - auto* player = sender; +void BaseConsoleTeleportServer::BaseOnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + auto* player = sender; - if (button == 1) - { + if (button == 1) { - GameMessages::SendSetStunned(player->GetObjectID(), PUSH, player->GetSystemAddress(), player->GetObjectID(), - true, true, true, true, true, true, true - ); + GameMessages::SendSetStunned(player->GetObjectID(), PUSH, player->GetSystemAddress(), player->GetObjectID(), + true, true, true, true, true, true, true + ); - const auto teleportFXID = self->GetVar(u"teleportEffectID"); + const auto teleportFXID = self->GetVar(u"teleportEffectID"); - if (teleportFXID != 0) - { - const auto& teleportFXs = self->GetVar>(u"teleportEffectTypes"); + if (teleportFXID != 0) { + const auto& teleportFXs = self->GetVar>(u"teleportEffectTypes"); - for (const auto& type : teleportFXs) - { - GameMessages::SendPlayFXEffect(player->GetObjectID(), teleportFXID, type, "FX" + GeneralUtils::UTF16ToWTF8(type)); - } - } + for (const auto& type : teleportFXs) { + GameMessages::SendPlayFXEffect(player->GetObjectID(), teleportFXID, type, "FX" + GeneralUtils::UTF16ToWTF8(type)); + } + } - const auto& teleIntroAnim = self->GetVar(u"teleportAnim"); + const auto& teleIntroAnim = self->GetVar(u"teleportAnim"); - if (!teleIntroAnim.empty()) - { - GameMessages::SendPlayAnimation(player, teleIntroAnim); - } + if (!teleIntroAnim.empty()) { + GameMessages::SendPlayAnimation(player, teleIntroAnim); + } - const auto animTime = 3.32999992370605f; + const auto animTime = 3.32999992370605f; - UpdatePlayerTable(self, player, true); + UpdatePlayerTable(self, player, true); - const auto playerID = player->GetObjectID(); + const auto playerID = player->GetObjectID(); - self->AddCallbackTimer(animTime, [playerID, self] () { - auto* player = EntityManager::Instance()->GetEntity(playerID); + self->AddCallbackTimer(animTime, [playerID, self]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - GameMessages::SendDisplayZoneSummary(playerID, player->GetSystemAddress(), false, false, self->GetObjectID()); - }); - } - else if (button == -1 || button == 0) - { - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, player->GetObjectID()); - } + GameMessages::SendDisplayZoneSummary(playerID, player->GetSystemAddress(), false, false, self->GetObjectID()); + }); + } else if (button == -1 || button == 0) { + GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, player->GetObjectID()); + } } -void BaseConsoleTeleportServer::UpdatePlayerTable(Entity* self, Entity* player, bool bAdd) -{ - const auto iter = std::find(m_Players.begin(), m_Players.end(), player->GetObjectID()); +void BaseConsoleTeleportServer::UpdatePlayerTable(Entity* self, Entity* player, bool bAdd) { + const auto iter = std::find(m_Players.begin(), m_Players.end(), player->GetObjectID()); - if (iter == m_Players.end() && bAdd) - { - m_Players.push_back(player->GetObjectID()); - } - else if (iter != m_Players.end() && !bAdd) - { - m_Players.erase(iter); - } + if (iter == m_Players.end() && bAdd) { + m_Players.push_back(player->GetObjectID()); + } else if (iter != m_Players.end() && !bAdd) { + m_Players.erase(iter); + } } -bool BaseConsoleTeleportServer::CheckPlayerTable(Entity* self, Entity* player) -{ - const auto iter = std::find(m_Players.begin(), m_Players.end(), player->GetObjectID()); +bool BaseConsoleTeleportServer::CheckPlayerTable(Entity* self, Entity* player) { + const auto iter = std::find(m_Players.begin(), m_Players.end(), player->GetObjectID()); - return iter != m_Players.end(); + return iter != m_Players.end(); } -void BaseConsoleTeleportServer::BaseOnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - if (args == "summaryComplete") - { - TransferPlayer(self, sender, 0); - } +void BaseConsoleTeleportServer::BaseOnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args == "summaryComplete") { + TransferPlayer(self, sender, 0); + } } -void BaseConsoleTeleportServer::TransferPlayer(Entity* self, Entity* player, int32_t altMapID) -{ - if (player == nullptr || !CheckPlayerTable(self, player)) - { - return; - } +void BaseConsoleTeleportServer::TransferPlayer(Entity* self, Entity* player, int32_t altMapID) { + if (player == nullptr || !CheckPlayerTable(self, player)) { + return; + } - // Ignoring extra effects for now + // Ignoring extra effects for now - /*GameMessages::SendSetStunned(player->GetObjectID(), POP, player->GetSystemAddress(), player->GetObjectID(), - true, true, true, true, true, true, true - );*/ + /*GameMessages::SendSetStunned(player->GetObjectID(), POP, player->GetSystemAddress(), player->GetObjectID(), + true, true, true, true, true, true, true + );*/ - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, player->GetObjectID()); + GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, player->GetObjectID()); - const auto& teleportZone = self->GetVar(u"transferZoneID"); + const auto& teleportZone = self->GetVar(u"transferZoneID"); - static_cast(player)->SendToZone(std::stoi(GeneralUtils::UTF16ToWTF8(teleportZone))); + static_cast(player)->SendToZone(std::stoi(GeneralUtils::UTF16ToWTF8(teleportZone))); - UpdatePlayerTable(self, player, false); + UpdatePlayerTable(self, player, false); } -void BaseConsoleTeleportServer::BaseOnTimerDone(Entity* self, const std::string& timerName) -{ - +void BaseConsoleTeleportServer::BaseOnTimerDone(Entity* self, const std::string& timerName) { + } diff --git a/dScripts/BaseConsoleTeleportServer.h b/dScripts/BaseConsoleTeleportServer.h index 086586e3..60c70d75 100644 --- a/dScripts/BaseConsoleTeleportServer.h +++ b/dScripts/BaseConsoleTeleportServer.h @@ -4,14 +4,14 @@ class BaseConsoleTeleportServer { public: - void BaseOnUse(Entity* self, Entity* user); - void BaseOnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData); - void UpdatePlayerTable(Entity* self, Entity* player, bool bAdd); - bool CheckPlayerTable(Entity* self, Entity* player); - void BaseOnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3); - void TransferPlayer(Entity* self, Entity* player, int32_t altMapID); - void BaseOnTimerDone(Entity* self, const std::string& timerName); + void BaseOnUse(Entity* self, Entity* user); + void BaseOnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData); + void UpdatePlayerTable(Entity* self, Entity* player, bool bAdd); + bool CheckPlayerTable(Entity* self, Entity* player); + void BaseOnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3); + void TransferPlayer(Entity* self, Entity* player, int32_t altMapID); + void BaseOnTimerDone(Entity* self, const std::string& timerName); private: - std::vector m_Players = {}; + std::vector m_Players = {}; }; diff --git a/dScripts/BaseEnemyApe.cpp b/dScripts/BaseEnemyApe.cpp index 9aa391d1..3d0b8e25 100644 --- a/dScripts/BaseEnemyApe.cpp +++ b/dScripts/BaseEnemyApe.cpp @@ -5,130 +5,130 @@ #include "EntityManager.h" #include "SkillComponent.h" -void BaseEnemyApe::OnStartup(Entity *self) { - self->SetVar(u"timesStunned", 2); - self->SetVar(u"knockedOut", false); +void BaseEnemyApe::OnStartup(Entity* self) { + self->SetVar(u"timesStunned", 2); + self->SetVar(u"knockedOut", false); } -void BaseEnemyApe::OnDie(Entity *self, Entity *killer) { - auto* anchor = EntityManager::Instance()->GetEntity(self->GetVar(u"QB")); - if (anchor != nullptr && !anchor->GetIsDead()) { - anchor->Smash(self->GetObjectID(), SILENT); - } +void BaseEnemyApe::OnDie(Entity* self, Entity* killer) { + auto* anchor = EntityManager::Instance()->GetEntity(self->GetVar(u"QB")); + if (anchor != nullptr && !anchor->GetIsDead()) { + anchor->Smash(self->GetObjectID(), SILENT); + } } -void BaseEnemyApe::OnSkillCast(Entity *self, uint32_t skillID) { - const auto groundPoundSkill = self->GetVar(u"GroundPoundSkill") != 0 ? self->GetVar(u"GroundPoundSkill") : 725; - const auto spawnQuickBuildTime = self->GetVar(u"spawnQBTime") != 0.0f ? self->GetVar(u"spawnQBTime") : 5.0f; +void BaseEnemyApe::OnSkillCast(Entity* self, uint32_t skillID) { + const auto groundPoundSkill = self->GetVar(u"GroundPoundSkill") != 0 ? self->GetVar(u"GroundPoundSkill") : 725; + const auto spawnQuickBuildTime = self->GetVar(u"spawnQBTime") != 0.0f ? self->GetVar(u"spawnQBTime") : 5.0f; - if (skillID == groundPoundSkill && self->GetVar(u"QB") == LWOOBJID_EMPTY) { - self->AddTimer("spawnQBTime", spawnQuickBuildTime); - } + if (skillID == groundPoundSkill && self->GetVar(u"QB") == LWOOBJID_EMPTY) { + self->AddTimer("spawnQBTime", spawnQuickBuildTime); + } } -void BaseEnemyApe::OnHit(Entity *self, Entity *attacker) { - auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr && destroyableComponent->GetArmor() < 1 && !self->GetBoolean(u"knockedOut")) { - StunApe(self, true); - self->CancelTimer("spawnQBTime"); +void BaseEnemyApe::OnHit(Entity* self, Entity* attacker) { + auto* destroyableComponent = self->GetComponent(); + if (destroyableComponent != nullptr && destroyableComponent->GetArmor() < 1 && !self->GetBoolean(u"knockedOut")) { + StunApe(self, true); + self->CancelTimer("spawnQBTime"); - GameMessages::SendPlayAnimation(self, u"disable", 1.7f); + GameMessages::SendPlayAnimation(self, u"disable", 1.7f); - const auto reviveTime = self->GetVar(u"reviveTime") != 0.0f - ? self->GetVar(u"reviveTime") : 12.0f; - self->AddTimer("reviveTime", reviveTime); - } + const auto reviveTime = self->GetVar(u"reviveTime") != 0.0f + ? self->GetVar(u"reviveTime") : 12.0f; + self->AddTimer("reviveTime", reviveTime); + } } -void BaseEnemyApe::OnTimerDone(Entity *self, std::string timerName) { - if (timerName == "reviveTime") { +void BaseEnemyApe::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "reviveTime") { - // Revives the ape, giving it back some armor - const auto timesStunned = self->GetVar(u"timesStunned"); - auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetArmor(destroyableComponent->GetMaxArmor() / timesStunned); - } - EntityManager::Instance()->SerializeEntity(self); - self->SetVar(u"timesStunned", timesStunned + 1); - StunApe(self, false); + // Revives the ape, giving it back some armor + const auto timesStunned = self->GetVar(u"timesStunned"); + auto* destroyableComponent = self->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetArmor(destroyableComponent->GetMaxArmor() / timesStunned); + } + EntityManager::Instance()->SerializeEntity(self); + self->SetVar(u"timesStunned", timesStunned + 1); + StunApe(self, false); - } else if (timerName == "spawnQBTime" && self->GetVar(u"QB") == LWOOBJID_EMPTY) { - // Spawn QB in front of ape. - const auto position = self->GetPosition(); - const auto rotation = self->GetRotation(); + } else if (timerName == "spawnQBTime" && self->GetVar(u"QB") == LWOOBJID_EMPTY) { + // Spawn QB in front of ape. + const auto position = self->GetPosition(); + const auto rotation = self->GetRotation(); - const auto backwardVector = rotation.GetForwardVector() * -1; - const auto objectPosition = NiPoint3( - position.GetX() - (backwardVector.GetX() * 8), - position.GetY(), - position.GetZ() - (backwardVector.GetZ() * 8) - ); + const auto backwardVector = rotation.GetForwardVector() * -1; + const auto objectPosition = NiPoint3( + position.GetX() - (backwardVector.GetX() * 8), + position.GetY(), + position.GetZ() - (backwardVector.GetZ() * 8) + ); - EntityInfo entityInfo {}; + EntityInfo entityInfo{}; - entityInfo.pos = position; - entityInfo.rot = rotation; - entityInfo.pos.SetY(entityInfo.pos.GetY() + 13.0f); + entityInfo.pos = position; + entityInfo.rot = rotation; + entityInfo.pos.SetY(entityInfo.pos.GetY() + 13.0f); - entityInfo.spawnerID = self->GetObjectID(); - entityInfo.lot = self->GetVar(u"QuickbuildAnchorLOT") != 0 - ? self->GetVar(u"QuickbuildAnchorLOT") : 7549; - entityInfo.settings = { - new LDFData(u"rebuild_activators", - std::to_string(objectPosition.GetX()) + "\x1f" + - std::to_string(objectPosition.GetY()) + "\x1f" + - std::to_string(objectPosition.GetZ()) - ), - new LDFData(u"no_timed_spawn", true), - new LDFData(u"ape", self->GetObjectID()) - }; + entityInfo.spawnerID = self->GetObjectID(); + entityInfo.lot = self->GetVar(u"QuickbuildAnchorLOT") != 0 + ? self->GetVar(u"QuickbuildAnchorLOT") : 7549; + entityInfo.settings = { + new LDFData(u"rebuild_activators", + std::to_string(objectPosition.GetX()) + "\x1f" + + std::to_string(objectPosition.GetY()) + "\x1f" + + std::to_string(objectPosition.GetZ()) + ), + new LDFData(u"no_timed_spawn", true), + new LDFData(u"ape", self->GetObjectID()) + }; - auto* anchor = EntityManager::Instance()->CreateEntity(entityInfo); - EntityManager::Instance()->ConstructEntity(anchor); - self->SetVar(u"QB", anchor->GetObjectID()); + auto* anchor = EntityManager::Instance()->CreateEntity(entityInfo); + EntityManager::Instance()->ConstructEntity(anchor); + self->SetVar(u"QB", anchor->GetObjectID()); - } else if (timerName == "anchorDamageTimer") { + } else if (timerName == "anchorDamageTimer") { - // Attacks the ape with some god skill - const auto* player = EntityManager::Instance()->GetEntity(self->GetVar(u"smasher")); - if (player == nullptr) { - return; - } + // Attacks the ape with some god skill + const auto* player = EntityManager::Instance()->GetEntity(self->GetVar(u"smasher")); + if (player == nullptr) { + return; + } - auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) { - skillComponent->CalculateBehavior(1273, 29446, self->GetObjectID(), true, false, player->GetObjectID()); - } + auto* skillComponent = self->GetComponent(); + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(1273, 29446, self->GetObjectID(), true, false, player->GetObjectID()); + } - self->SetVar(u"QB", LWOOBJID_EMPTY); - } + self->SetVar(u"QB", LWOOBJID_EMPTY); + } } -void BaseEnemyApe::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "rebuildDone" && sender != nullptr) { - self->SetVar(u"smasher", sender->GetObjectID()); - const auto anchorDamageDelayTime = self->GetVar(u"AnchorDamageDelayTime") != 0.0f ? self->GetVar(u"AnchorDamageDelayTime") : 0.5f; - self->AddTimer("anchorDamageTimer", anchorDamageDelayTime); - } +void BaseEnemyApe::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "rebuildDone" && sender != nullptr) { + self->SetVar(u"smasher", sender->GetObjectID()); + const auto anchorDamageDelayTime = self->GetVar(u"AnchorDamageDelayTime") != 0.0f ? self->GetVar(u"AnchorDamageDelayTime") : 0.5f; + self->AddTimer("anchorDamageTimer", anchorDamageDelayTime); + } } -void BaseEnemyApe::StunApe(Entity *self, bool stunState) { - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(stunState); - combatAIComponent->SetStunned(stunState); +void BaseEnemyApe::StunApe(Entity* self, bool stunState) { + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(stunState); + combatAIComponent->SetStunned(stunState); - auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) { - skillComponent->Interrupt(); - } + auto* skillComponent = self->GetComponent(); + if (skillComponent != nullptr) { + skillComponent->Interrupt(); + } - GameMessages::SendSetStunned(self->GetObjectID(), stunState ? PUSH : POP, UNASSIGNED_SYSTEM_ADDRESS, self->GetObjectID(), - true, true, true, true, true, - true, true, true, true); + GameMessages::SendSetStunned(self->GetObjectID(), stunState ? PUSH : POP, UNASSIGNED_SYSTEM_ADDRESS, self->GetObjectID(), + true, true, true, true, true, + true, true, true, true); - self->SetBoolean(u"knockedOut", stunState); - } + self->SetBoolean(u"knockedOut", stunState); + } } diff --git a/dScripts/BaseEnemyApe.h b/dScripts/BaseEnemyApe.h index 1553d3ae..938312b6 100644 --- a/dScripts/BaseEnemyApe.h +++ b/dScripts/BaseEnemyApe.h @@ -3,13 +3,13 @@ class BaseEnemyApe : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - void OnDie(Entity *self, Entity *killer) override; - void OnSkillCast(Entity *self, uint32_t skillID) override; - void OnHit(Entity *self, Entity *attacker) override; - void OnTimerDone(Entity *self, std::string timerName) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnStartup(Entity* self) override; + void OnDie(Entity* self, Entity* killer) override; + void OnSkillCast(Entity* self, uint32_t skillID) override; + void OnHit(Entity* self, Entity* attacker) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; private: - static void StunApe(Entity* self, bool stunState); + static void StunApe(Entity* self, bool stunState); }; diff --git a/dScripts/BaseEnemyMech.cpp b/dScripts/BaseEnemyMech.cpp index 17c7a347..32dc38dd 100644 --- a/dScripts/BaseEnemyMech.cpp +++ b/dScripts/BaseEnemyMech.cpp @@ -7,17 +7,17 @@ #include "DestroyableComponent.h" void BaseEnemyMech::OnStartup(Entity* self) { - auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetFaction(4); - } + auto* destroyableComponent = self->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetFaction(4); + } } void BaseEnemyMech::OnDie(Entity* self, Entity* killer) { ControllablePhysicsComponent* controlPhys = static_cast(self->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); if (!controlPhys) return; - NiPoint3 newLoc = {controlPhys->GetPosition().x, dpWorld::Instance().GetHeightAtPoint(controlPhys->GetPosition()), controlPhys->GetPosition().z }; + NiPoint3 newLoc = { controlPhys->GetPosition().x, dpWorld::Instance().GetHeightAtPoint(controlPhys->GetPosition()), controlPhys->GetPosition().z }; EntityInfo info = EntityInfo(); std::vector cfg; diff --git a/dScripts/BaseEnemyMech.h b/dScripts/BaseEnemyMech.h index a8955061..133b855e 100644 --- a/dScripts/BaseEnemyMech.h +++ b/dScripts/BaseEnemyMech.h @@ -4,7 +4,7 @@ class BaseEnemyMech : public CppScripts::Script { public: - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; void OnDie(Entity* self, Entity* killer) override; protected: LOT qbTurretLOT = 6254; diff --git a/dScripts/BaseFootRaceManager.cpp b/dScripts/BaseFootRaceManager.cpp index 0da51bc5..699ee096 100644 --- a/dScripts/BaseFootRaceManager.cpp +++ b/dScripts/BaseFootRaceManager.cpp @@ -2,47 +2,47 @@ #include "EntityManager.h" #include "Character.h" -void BaseFootRaceManager::OnStartup(Entity *self) { - // TODO: Add to FootRaceStarter group +void BaseFootRaceManager::OnStartup(Entity* self) { + // TODO: Add to FootRaceStarter group } -void BaseFootRaceManager::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { - const auto splitArguments = GeneralUtils::SplitString(args, '_'); - if (splitArguments.size() > 1) { +void BaseFootRaceManager::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + const auto splitArguments = GeneralUtils::SplitString(args, '_'); + if (splitArguments.size() > 1) { - const auto eventName = splitArguments[0]; - const auto player = EntityManager::Instance()->GetEntity(std::stoull(splitArguments[1])); + const auto eventName = splitArguments[0]; + const auto player = EntityManager::Instance()->GetEntity(std::stoull(splitArguments[1])); - if (player != nullptr) { - if (eventName == "updatePlayer") { - UpdatePlayer(self, player->GetObjectID()); - } else if (IsPlayerInActivity(self, player->GetObjectID())) { - if (eventName == "initialActivityScore") { - auto* character = player->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(115, true); - } + if (player != nullptr) { + if (eventName == "updatePlayer") { + UpdatePlayer(self, player->GetObjectID()); + } else if (IsPlayerInActivity(self, player->GetObjectID())) { + if (eventName == "initialActivityScore") { + auto* character = player->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(115, true); + } - SetActivityScore(self, player->GetObjectID(), 1); - } else if (eventName == "updatePlayerTrue") { - auto* character = player->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(115, false); - } + SetActivityScore(self, player->GetObjectID(), 1); + } else if (eventName == "updatePlayerTrue") { + auto* character = player->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(115, false); + } - UpdatePlayer(self, player->GetObjectID(), true); - } else if (eventName == "PlayerWon") { - auto* character = player->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(115, false); - if (param2 != -1) // Certain footraces set a flag - character->SetPlayerFlag(param2, true); - } + UpdatePlayer(self, player->GetObjectID(), true); + } else if (eventName == "PlayerWon") { + auto* character = player->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(115, false); + if (param2 != -1) // Certain footraces set a flag + character->SetPlayerFlag(param2, true); + } - StopActivity(self, player->GetObjectID(), 0, param1); - } - } - } - } + StopActivity(self, player->GetObjectID(), 0, param1); + } + } + } + } } diff --git a/dScripts/BaseFootRaceManager.h b/dScripts/BaseFootRaceManager.h index 1a76cf19..477a6eb9 100644 --- a/dScripts/BaseFootRaceManager.h +++ b/dScripts/BaseFootRaceManager.h @@ -3,7 +3,7 @@ #include "CppScripts.h" class BaseFootRaceManager : public ActivityManager { - void OnStartup(Entity* self) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnStartup(Entity* self) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/BaseInteractDropLootServer.cpp b/dScripts/BaseInteractDropLootServer.cpp index 0dbce047..44698956 100644 --- a/dScripts/BaseInteractDropLootServer.cpp +++ b/dScripts/BaseInteractDropLootServer.cpp @@ -2,32 +2,29 @@ #include "Loot.h" #include "GameMessages.h" -void BaseInteractDropLootServer::OnUse(Entity* self, Entity* user) -{ - BaseUse(self, user); +void BaseInteractDropLootServer::OnUse(Entity* self, Entity* user) { + BaseUse(self, user); } -void BaseInteractDropLootServer::BaseUse(Entity* self, Entity* user) -{ - auto cooldownTime = self->GetVar(u"cooldownTime"); - if (cooldownTime == 0) cooldownTime = 5; +void BaseInteractDropLootServer::BaseUse(Entity* self, Entity* user) { + auto cooldownTime = self->GetVar(u"cooldownTime"); + if (cooldownTime == 0) cooldownTime = 5; - uint32_t lootMatrix = self->GetVar(u"UseLootMatrix"); - if (lootMatrix == 0) lootMatrix = self->GetVar(u"smashable_loot_matrix"); - if (lootMatrix == 0) lootMatrix = 715; + uint32_t lootMatrix = self->GetVar(u"UseLootMatrix"); + if (lootMatrix == 0) lootMatrix = self->GetVar(u"smashable_loot_matrix"); + if (lootMatrix == 0) lootMatrix = 715; - auto useSound = self->GetVar(u"sound1"); + auto useSound = self->GetVar(u"sound1"); - if (!useSound.empty()) - { - GameMessages::SendPlayNDAudioEmitter(self, user->GetSystemAddress(), useSound); - } + if (!useSound.empty()) { + GameMessages::SendPlayNDAudioEmitter(self, user->GetSystemAddress(), useSound); + } - self->SetNetworkVar(u"bInUse", true); + self->SetNetworkVar(u"bInUse", true); - LootGenerator::Instance().DropLoot(user, self, lootMatrix, 0, 0); + LootGenerator::Instance().DropLoot(user, self, lootMatrix, 0, 0); - self->AddCallbackTimer(cooldownTime, [this, self] () { - self->SetNetworkVar(u"bInUse", false); - }); + self->AddCallbackTimer(cooldownTime, [this, self]() { + self->SetNetworkVar(u"bInUse", false); + }); } diff --git a/dScripts/BaseInteractDropLootServer.h b/dScripts/BaseInteractDropLootServer.h index d2e9b600..f2a084f5 100644 --- a/dScripts/BaseInteractDropLootServer.h +++ b/dScripts/BaseInteractDropLootServer.h @@ -4,7 +4,7 @@ class BaseInteractDropLootServer : public CppScripts::Script { public: - virtual void OnUse(Entity* self, Entity* user) override; - void BaseUse(Entity* self, Entity* user); + virtual void OnUse(Entity* self, Entity* user) override; + void BaseUse(Entity* self, Entity* user); }; diff --git a/dScripts/BasePropertyServer.cpp b/dScripts/BasePropertyServer.cpp index ce36caa9..a182c9c1 100644 --- a/dScripts/BasePropertyServer.cpp +++ b/dScripts/BasePropertyServer.cpp @@ -9,61 +9,61 @@ #include "PropertyManagementComponent.h" #include "MissionComponent.h" -void BasePropertyServer::SetGameVariables(Entity *self) { - self->SetVar(ClaimMarkerGroup, ""); - self->SetVar(GeneratorGroup, ""); - self->SetVar(GuardGroup, ""); - self->SetVar(PropertyPlaqueGroup, ""); - self->SetVar(PropertyVendorGroup, ""); - self->SetVar(SpotsGroup, ""); - self->SetVar(MSCloudsGroup, ""); - self->SetVar(EnemiesGroup, ""); - self->SetVar(FXManagerGroup, ""); - self->SetVar(ImagOrbGroup, ""); - self->SetVar(GeneratorFXGroup, ""); +void BasePropertyServer::SetGameVariables(Entity* self) { + self->SetVar(ClaimMarkerGroup, ""); + self->SetVar(GeneratorGroup, ""); + self->SetVar(GuardGroup, ""); + self->SetVar(PropertyPlaqueGroup, ""); + self->SetVar(PropertyVendorGroup, ""); + self->SetVar(SpotsGroup, ""); + self->SetVar(MSCloudsGroup, ""); + self->SetVar(EnemiesGroup, ""); + self->SetVar(FXManagerGroup, ""); + self->SetVar(ImagOrbGroup, ""); + self->SetVar(GeneratorFXGroup, ""); - self->SetVar>(EnemiesSpawner, {}); - self->SetVar(ClaimMarkerSpawner, ""); - self->SetVar(GeneratorSpawner, ""); - self->SetVar(DamageFXSpawner, ""); - self->SetVar(FXSpotsSpawner, ""); - self->SetVar(PropertyMGSpawner, ""); - self->SetVar(ImageOrbSpawner, ""); - self->SetVar(GeneratorFXSpawner, ""); - self->SetVar(SmashablesSpawner, ""); - self->SetVar(FXManagerSpawner, ""); - self->SetVar(PropObjsSpawner, ""); - self->SetVar>(AmbientFXSpawner, {}); - self->SetVar>(BehaviorObjsSpawner, {}); + self->SetVar>(EnemiesSpawner, {}); + self->SetVar(ClaimMarkerSpawner, ""); + self->SetVar(GeneratorSpawner, ""); + self->SetVar(DamageFXSpawner, ""); + self->SetVar(FXSpotsSpawner, ""); + self->SetVar(PropertyMGSpawner, ""); + self->SetVar(ImageOrbSpawner, ""); + self->SetVar(GeneratorFXSpawner, ""); + self->SetVar(SmashablesSpawner, ""); + self->SetVar(FXManagerSpawner, ""); + self->SetVar(PropObjsSpawner, ""); + self->SetVar>(AmbientFXSpawner, {}); + self->SetVar>(BehaviorObjsSpawner, {}); - self->SetVar(defeatedProperyFlag, 0); - self->SetVar(placedModelFlag, 0); - self->SetVar(guardMissionFlag, 0); - self->SetVar(brickLinkMissionIDFlag, 0); - self->SetVar(passwordFlag, "s3kratK1ttN"); - self->SetVar(generatorIdFlag, 0); - self->SetVar(orbIDFlag, 0); - self->SetVar(behaviorQBID, 0); + self->SetVar(defeatedProperyFlag, 0); + self->SetVar(placedModelFlag, 0); + self->SetVar(guardMissionFlag, 0); + self->SetVar(brickLinkMissionIDFlag, 0); + self->SetVar(passwordFlag, "s3kratK1ttN"); + self->SetVar(generatorIdFlag, 0); + self->SetVar(orbIDFlag, 0); + self->SetVar(behaviorQBID, 0); } void BasePropertyServer::CheckForOwner(Entity* self) { - if (EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(PropertyPlaqueGroup)).empty()) { - self->AddTimer(RunPlayerLoadedAgainTimer, 0.5f); - return; - } + if (EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(PropertyPlaqueGroup)).empty()) { + self->AddTimer(RunPlayerLoadedAgainTimer, 0.5f); + return; + } self->SetI64(PropertyOwnerVariable, GetOwner()); } -void BasePropertyServer::OnStartup(Entity *self) { - SetGameVariables(self); +void BasePropertyServer::OnStartup(Entity* self) { + SetGameVariables(self); } -void BasePropertyServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { - if (args == CheckForPropertyOwnerEvent) { - sender->SetNetworkVar(PropertyOwnerIDVariable, std::to_string(self->GetVar(PropertyOwnerVariable))); - } +void BasePropertyServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (args == CheckForPropertyOwnerEvent) { + sender->SetNetworkVar(PropertyOwnerIDVariable, std::to_string(self->GetVar(PropertyOwnerVariable))); + } } void BasePropertyServer::BasePlayerLoaded(Entity* self, Entity* player) { @@ -73,7 +73,7 @@ void BasePropertyServer::BasePlayerLoaded(Entity* self, Entity* player) { auto propertyOwner = PropertyManagementComponent::Instance()->GetOwnerId(); self->OnFireEventServerSide(self, CheckForPropertyOwnerEvent); - + if (propertyOwner > 0) { rented = true; } @@ -85,19 +85,17 @@ void BasePropertyServer::BasePlayerLoaded(Entity* self, Entity* player) { self->SetNetworkVar(PropertyOwnerIDVariable, propertyOwner); if (rented) { - auto plaques = EntityManager::Instance()->GetEntitiesInGroup("PropertyVendor"); - for (auto* plaque : plaques) { - EntityManager::Instance()->DestructEntity(plaque); - } + auto plaques = EntityManager::Instance()->GetEntitiesInGroup("PropertyVendor"); + for (auto* plaque : plaques) { + EntityManager::Instance()->DestructEntity(plaque); + } const auto& mapID = dZoneManager::Instance()->GetZone()->GetZoneID(); - if (propertyOwner > 0) - { + if (propertyOwner > 0) { auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { + if (missionComponent != nullptr) { missionComponent->Progress( MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY, mapID.GetMapID(), @@ -115,7 +113,7 @@ void BasePropertyServer::BasePlayerLoaded(Entity* self, Entity* player) { if (!self->GetBoolean(FXObjectsGoneVariable)) { self->AddTimer(KillFXObjectTimer, 1.0f); } - + GameMessages::SendPlay2DAmbientSound(player, GUIDPeaceful); // activate property safe spawner network @@ -130,7 +128,7 @@ void BasePropertyServer::BasePlayerLoaded(Entity* self, Entity* player) { const auto defeatedFlag = player->GetCharacter()->GetPlayerFlag(self->GetVar(defeatedProperyFlag)); self->SetNetworkVar(UnclaimedVariable, true); - self->SetVar(PlayerIDVariable, player->GetObjectID()); + self->SetVar(PlayerIDVariable, player->GetObjectID()); if (!defeatedFlag) { StartMaelstrom(self, player); @@ -152,27 +150,27 @@ void BasePropertyServer::PropGuardCheck(Entity* self, Entity* player) { auto* missionComponent = player->GetComponent(); if (missionComponent != nullptr - && missionComponent->GetMissionState(self->GetVar(guardMissionFlag)) != MissionState::MISSION_STATE_COMPLETE) { - ActivateSpawner(self->GetVar(PropertyMGSpawner)); + && missionComponent->GetMissionState(self->GetVar(guardMissionFlag)) != MissionState::MISSION_STATE_COMPLETE) { + ActivateSpawner(self->GetVar(PropertyMGSpawner)); } } void BasePropertyServer::BaseZonePropertyRented(Entity* self, Entity* player) const { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayCinematic", 0, 0, LWOOBJID_EMPTY, "ShowProperty", - UNASSIGNED_SYSTEM_ADDRESS); + UNASSIGNED_SYSTEM_ADDRESS); self->AddTimer(BoundsVisOnTimer, 2); self->SetVar(PropertyOwnerVariable, player->GetObjectID()); - - auto plaques = EntityManager::Instance()->GetEntitiesInGroup("PropertyVendor"); - for (auto* plaque : plaques) { - EntityManager::Instance()->DestructEntity(plaque); - } - auto brickLinkMissionID = self->GetVar(brickLinkMissionIDFlag); + auto plaques = EntityManager::Instance()->GetEntitiesInGroup("PropertyVendor"); + for (auto* plaque : plaques) { + EntityManager::Instance()->DestructEntity(plaque); + } + + auto brickLinkMissionID = self->GetVar(brickLinkMissionIDFlag); if (brickLinkMissionID != 0) { - auto missionComponent = player->GetComponent(); - if (missionComponent) missionComponent->CompleteMission(brickLinkMissionID, true); + auto missionComponent = player->GetComponent(); + if (missionComponent) missionComponent->CompleteMission(brickLinkMissionID, true); } ActivateSpawner(self->GetVar(PropObjsSpawner)); @@ -185,7 +183,7 @@ void BasePropertyServer::BaseZonePropertyModelPlaced(Entity* self, Entity* playe auto flag = self->GetVar(placedModelFlag); if (flag) - character->SetPlayerFlag(flag, true); + character->SetPlayerFlag(flag, true); } void BasePropertyServer::KillClouds(Entity* self) { @@ -203,13 +201,13 @@ void BasePropertyServer::KillSpots(Entity* self) { } void BasePropertyServer::StartMaelstrom(Entity* self, Entity* player) { - for (const auto& enemySpawner : self->GetVar>(EnemiesSpawner)) { - ActivateSpawner(enemySpawner); - } + for (const auto& enemySpawner : self->GetVar>(EnemiesSpawner)) { + ActivateSpawner(enemySpawner); + } - for (const auto& behaviorObjectSpawner : self->GetVar>(BehaviorObjsSpawner)) { - ActivateSpawner(behaviorObjectSpawner); - } + for (const auto& behaviorObjectSpawner : self->GetVar>(BehaviorObjsSpawner)) { + ActivateSpawner(behaviorObjectSpawner); + } ActivateSpawner(self->GetVar(DamageFXSpawner)); ActivateSpawner(self->GetVar(GeneratorSpawner)); @@ -221,13 +219,13 @@ void BasePropertyServer::StartMaelstrom(Entity* self, Entity* player) { DestroySpawner(self->GetVar(ClaimMarkerSpawner)); for (const auto& ambientFXSpawner : self->GetVar>(AmbientFXSpawner)) { - DestroySpawner(ambientFXSpawner); + DestroySpawner(ambientFXSpawner); } StartTornadoFx(self); GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, LWOOBJID_EMPTY, - "", player->GetSystemAddress()); + "", player->GetSystemAddress()); self->AddTimer(StartGeneratorTimer, 0.0f); self->AddTimer(StartOrbTimer, 0.0f); @@ -241,20 +239,20 @@ void BasePropertyServer::StartTornadoFx(Entity* self) const { } for (auto* entity : entities) { - auto* renderComponent = entity->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->PlayEffect(-1, u"debrisOn", "TornadoDebris"); - renderComponent->PlayEffect(-1, u"VortexOn", "TornadoVortex"); - renderComponent->PlayEffect(-1, u"onSilhouette", "silhouette"); - } + auto* renderComponent = entity->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->PlayEffect(-1, u"debrisOn", "TornadoDebris"); + renderComponent->PlayEffect(-1, u"VortexOn", "TornadoVortex"); + renderComponent->PlayEffect(-1, u"onSilhouette", "silhouette"); + } } } -void BasePropertyServer::BasePlayerExit(Entity *self, Entity *player) { +void BasePropertyServer::BasePlayerExit(Entity* self, Entity* player) { if (self->GetBoolean(UnclaimedVariable)) { - if (player->GetObjectID() == self->GetVar(PlayerIDVariable)) { - // Destroy all spawners - } + if (player->GetObjectID() == self->GetVar(PlayerIDVariable)) { + // Destroy all spawners + } } } @@ -284,9 +282,9 @@ void BasePropertyServer::ActivateSpawner(const std::string& spawnerName) { } void BasePropertyServer::DeactivateSpawner(const std::string& spawnerName) { - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { - spawner->Deactivate(); - } + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { + spawner->Deactivate(); + } } void BasePropertyServer::TriggerSpawner(const std::string& spawnerName) { @@ -296,27 +294,27 @@ void BasePropertyServer::TriggerSpawner(const std::string& spawnerName) { } void BasePropertyServer::ResetSpawner(const std::string& spawnerName) { - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { - spawner->Reset(); - } + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { + spawner->Reset(); + } } void BasePropertyServer::DestroySpawner(const std::string& spawnerName) { - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { - for (auto* node : spawner->m_Info.nodes) { - for (const auto& element : node->entities) { - auto* entity = EntityManager::Instance()->GetEntity(element); - if (entity == nullptr) - continue; + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { + for (auto* node : spawner->m_Info.nodes) { + for (const auto& element : node->entities) { + auto* entity = EntityManager::Instance()->GetEntity(element); + if (entity == nullptr) + continue; - entity->Kill(); - } + entity->Kill(); + } - node->entities.clear(); - } + node->entities.clear(); + } - spawner->Deactivate(); - } + spawner->Deactivate(); + } } LWOOBJID BasePropertyServer::GetOwner() { @@ -325,194 +323,194 @@ LWOOBJID BasePropertyServer::GetOwner() { } void BasePropertyServer::BaseTimerDone(Entity* self, const std::string& timerName) { - if (timerName == StartGeneratorTimer) { - HandleGeneratorTimer(self); - } else if (timerName == StartOrbTimer) { - HandleOrbsTimer(self); - } else if (timerName == StartQuickbuildTimer) { - HandleQuickBuildTimer(self); - } else if (timerName == "GuardFlyAway") { - const auto zoneId = dZoneManager::Instance()->GetZone()->GetWorldID(); + if (timerName == StartGeneratorTimer) { + HandleGeneratorTimer(self); + } else if (timerName == StartOrbTimer) { + HandleOrbsTimer(self); + } else if (timerName == StartQuickbuildTimer) { + HandleQuickBuildTimer(self); + } else if (timerName == "GuardFlyAway") { + const auto zoneId = dZoneManager::Instance()->GetZone()->GetWorldID(); - // No guard for the spider instance fight - if (dZoneManager::Instance()->GetZoneID().GetMapID() == 1150) - return; + // No guard for the spider instance fight + if (dZoneManager::Instance()->GetZoneID().GetMapID() == 1150) + return; - const auto entities = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(GuardGroup)); - if (entities.empty()) - return; + const auto entities = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(GuardGroup)); + if (entities.empty()) + return; - auto* guard = entities[0]; - GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), - u"GuardChat", 0, 0, guard->GetObjectID(), - "", UNASSIGNED_SYSTEM_ADDRESS); + auto* guard = entities[0]; + GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), + u"GuardChat", 0, 0, guard->GetObjectID(), + "", UNASSIGNED_SYSTEM_ADDRESS); - self->AddTimer(KillGuardTimer, 5.0f); - } else if (timerName == KillGuardTimer) { - KillGuard(self); - } else if (timerName == TornadoOffTimer) { - auto fxManagers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup)); + self->AddTimer(KillGuardTimer, 5.0f); + } else if (timerName == KillGuardTimer) { + KillGuard(self); + } else if (timerName == TornadoOffTimer) { + auto fxManagers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup)); - for (auto *fxManager : fxManagers) { - auto *renderComponent = fxManager->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("TornadoDebris", false); - renderComponent->StopEffect("TornadoVortex", false); - renderComponent->StopEffect("silhouette", false); - } - } + for (auto* fxManager : fxManagers) { + auto* renderComponent = fxManager->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("TornadoDebris", false); + renderComponent->StopEffect("TornadoVortex", false); + renderComponent->StopEffect("silhouette", false); + } + } - self->AddTimer(ShowClearEffectsTimer, 2); - } else if (timerName == ShowClearEffectsTimer) { - auto fxManagers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup)); + self->AddTimer(ShowClearEffectsTimer, 2); + } else if (timerName == ShowClearEffectsTimer) { + auto fxManagers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup)); - for (auto *fxManager : fxManagers) { - auto *renderComponent = fxManager->GetComponent(); - if (renderComponent != nullptr) - renderComponent->PlayEffect(-1, u"beamOn", "beam"); - } + for (auto* fxManager : fxManagers) { + auto* renderComponent = fxManager->GetComponent(); + if (renderComponent != nullptr) + renderComponent->PlayEffect(-1, u"beamOn", "beam"); + } - self->AddTimer(KillStrombiesTimer, 2.0f); - self->AddTimer(TurnSkyOffTimer, 1.5f); - self->AddTimer(KillFXObjectTimer, 8.0f); - } else if (timerName == TurnSkyOffTimer) { - auto* controller = dZoneManager::Instance()->GetZoneControlObject(); - GameMessages::SendNotifyClientObject(controller->GetObjectID(), u"SkyOff", 0, 0, - LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - } else if (timerName == KillStrombiesTimer) { - const auto enemies = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(EnemiesGroup)); - for (auto* enemy : enemies) { - RequestDie(self, enemy); - } + self->AddTimer(KillStrombiesTimer, 2.0f); + self->AddTimer(TurnSkyOffTimer, 1.5f); + self->AddTimer(KillFXObjectTimer, 8.0f); + } else if (timerName == TurnSkyOffTimer) { + auto* controller = dZoneManager::Instance()->GetZoneControlObject(); + GameMessages::SendNotifyClientObject(controller->GetObjectID(), u"SkyOff", 0, 0, + LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + } else if (timerName == KillStrombiesTimer) { + const auto enemies = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(EnemiesGroup)); + for (auto* enemy : enemies) { + RequestDie(self, enemy); + } - DestroySpawner(self->GetVar(SmashablesSpawner)); - KillSpots(self); + DestroySpawner(self->GetVar(SmashablesSpawner)); + KillSpots(self); - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player == nullptr) - return; + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player == nullptr) + return; - GameMessages::SendStop2DAmbientSound(player, true, GUIDMaelstrom); - GameMessages::SendPlay2DAmbientSound(player, GUIDPeaceful); + GameMessages::SendStop2DAmbientSound(player, true, GUIDMaelstrom); + GameMessages::SendPlay2DAmbientSound(player, GUIDPeaceful); - self->AddTimer(ShowVendorTimer, 5.0f); - } else if (timerName == KillMarkerTimer) { - DestroySpawner(self->GetVar(ClaimMarkerSpawner)); + self->AddTimer(ShowVendorTimer, 5.0f); + } else if (timerName == KillMarkerTimer) { + DestroySpawner(self->GetVar(ClaimMarkerSpawner)); - for (const auto& behaviorObjectSpawner : self->GetVar>(BehaviorObjsSpawner)) { - DestroySpawner(behaviorObjectSpawner); - } + for (const auto& behaviorObjectSpawner : self->GetVar>(BehaviorObjsSpawner)) { + DestroySpawner(behaviorObjectSpawner); + } - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(ImagOrbGroup))) { - entity->Smash(); - } + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(ImagOrbGroup))) { + entity->Smash(); + } - DestroySpawner(self->GetVar(ImageOrbSpawner)); + DestroySpawner(self->GetVar(ImageOrbSpawner)); - self->AddTimer(ShowVendorTimer, 1.0f); - } else if (timerName == ShowVendorTimer) { - GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), - u"vendorOn", 0, 0, LWOOBJID_EMPTY, "", - UNASSIGNED_SYSTEM_ADDRESS); + self->AddTimer(ShowVendorTimer, 1.0f); + } else if (timerName == ShowVendorTimer) { + GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), + u"vendorOn", 0, 0, LWOOBJID_EMPTY, "", + UNASSIGNED_SYSTEM_ADDRESS); - for (const auto& ambientFXSpawner : self->GetVar>(AmbientFXSpawner)) { - ActivateSpawner(ambientFXSpawner); - } - } else if (timerName == BoundsVisOnTimer) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"boundsAnim", 0, 0, - LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - } else if (timerName == RunPlayerLoadedAgainTimer) { - CheckForOwner(self); - } else if (timerName == PollTornadoFXTimer) { - StartTornadoFx(self); - } else if (timerName == KillFXObjectTimer) { - const auto fxManagers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup)); - if (fxManagers.empty()) { - self->AddTimer(KillFXObjectTimer, 1.0f); - return; - } + for (const auto& ambientFXSpawner : self->GetVar>(AmbientFXSpawner)) { + ActivateSpawner(ambientFXSpawner); + } + } else if (timerName == BoundsVisOnTimer) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"boundsAnim", 0, 0, + LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + } else if (timerName == RunPlayerLoadedAgainTimer) { + CheckForOwner(self); + } else if (timerName == PollTornadoFXTimer) { + StartTornadoFx(self); + } else if (timerName == KillFXObjectTimer) { + const auto fxManagers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup)); + if (fxManagers.empty()) { + self->AddTimer(KillFXObjectTimer, 1.0f); + return; + } - for (auto* fxManager : fxManagers) { - auto* renderComponent = fxManager->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("beam"); - } - } + for (auto* fxManager : fxManagers) { + auto* renderComponent = fxManager->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("beam"); + } + } - DestroySpawner(self->GetVar(FXManagerSpawner)); - self->SetVar(u"FXObjectGone", true); - } + DestroySpawner(self->GetVar(FXManagerSpawner)); + self->SetVar(u"FXObjectGone", true); + } } void BasePropertyServer::HandleOrbsTimer(Entity* self) { - self->SetVar(CollidedVariable, false); - auto orbs = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(ImagOrbGroup)); - if (orbs.empty()) { - self->AddTimer(StartOrbTimer, 0.5f); - return; - } + self->SetVar(CollidedVariable, false); + auto orbs = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(ImagOrbGroup)); + if (orbs.empty()) { + self->AddTimer(StartOrbTimer, 0.5f); + return; + } - for (auto* orb : orbs) { - orb->AddCollisionPhantomCallback([self, this](Entity* other) { - if (other != nullptr && other->IsPlayer() && !self->GetVar(CollidedVariable)) { - self->SetVar(CollidedVariable, true); + for (auto* orb : orbs) { + orb->AddCollisionPhantomCallback([self, this](Entity* other) { + if (other != nullptr && other->IsPlayer() && !self->GetVar(CollidedVariable)) { + self->SetVar(CollidedVariable, true); - KillClouds(self); - DeactivateSpawner(self->GetVar(GeneratorSpawner)); + KillClouds(self); + DeactivateSpawner(self->GetVar(GeneratorSpawner)); - for (const auto& enemySpawner : self->GetVar>(EnemiesSpawner)) { - DeactivateSpawner(enemySpawner); - } + for (const auto& enemySpawner : self->GetVar>(EnemiesSpawner)) { + DeactivateSpawner(enemySpawner); + } - DestroySpawner(self->GetVar(GeneratorFXSpawner)); - GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), - u"PlayCinematic", 0, 0, LWOOBJID_EMPTY, - "DestroyMaelstrom", UNASSIGNED_SYSTEM_ADDRESS); + DestroySpawner(self->GetVar(GeneratorFXSpawner)); + GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), + u"PlayCinematic", 0, 0, LWOOBJID_EMPTY, + "DestroyMaelstrom", UNASSIGNED_SYSTEM_ADDRESS); - // Notifies the client that the property has been claimed with a flag, completes missions too - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - auto* character = player->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(self->GetVar(defeatedProperyFlag), true); - } - } + // Notifies the client that the property has been claimed with a flag, completes missions too + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + auto* character = player->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(self->GetVar(defeatedProperyFlag), true); + } + } - self->AddTimer(TornadoOffTimer, 0.5f); - self->AddTimer(KillMarkerTimer, 0.7f); - } - }); - } + self->AddTimer(TornadoOffTimer, 0.5f); + self->AddTimer(KillMarkerTimer, 0.7f); + } + }); + } } void BasePropertyServer::HandleGeneratorTimer(Entity* self) { - auto generators = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(GeneratorGroup)); - if (generators.empty()) { - self->AddTimer(StartGeneratorTimer, 0.5f); - return; - } + auto generators = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(GeneratorGroup)); + if (generators.empty()) { + self->AddTimer(StartGeneratorTimer, 0.5f); + return; + } - for (auto* generator : generators) { - generator->AddDieCallback([self, this]() { - ActivateSpawner(self->GetVar(ClaimMarkerSpawner)); - self->AddTimer(StartQuickbuildTimer, 0.0f); + for (auto* generator : generators) { + generator->AddDieCallback([self, this]() { + ActivateSpawner(self->GetVar(ClaimMarkerSpawner)); + self->AddTimer(StartQuickbuildTimer, 0.0f); - for (const auto& enemySpawner : self->GetVar>(EnemiesSpawner)) { - DeactivateSpawner(enemySpawner); - } - DeactivateSpawner(self->GetVar(GeneratorSpawner)); - }); - } + for (const auto& enemySpawner : self->GetVar>(EnemiesSpawner)) { + DeactivateSpawner(enemySpawner); + } + DeactivateSpawner(self->GetVar(GeneratorSpawner)); + }); + } } void BasePropertyServer::HandleQuickBuildTimer(Entity* self) { - auto claimMarkers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(ClaimMarkerGroup)); - if (claimMarkers.empty()) { - self->AddTimer(StartQuickbuildTimer, 0.5f); - return; - } + auto claimMarkers = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(ClaimMarkerGroup)); + if (claimMarkers.empty()) { + self->AddTimer(StartQuickbuildTimer, 0.5f); + return; + } - for (auto* claimMarker : claimMarkers) { - // TODO: Send password? - } + for (auto* claimMarker : claimMarkers) { + // TODO: Send password? + } } diff --git a/dScripts/BasePropertyServer.h b/dScripts/BasePropertyServer.h index 79a52f54..da2d315b 100644 --- a/dScripts/BasePropertyServer.h +++ b/dScripts/BasePropertyServer.h @@ -4,24 +4,24 @@ class BasePropertyServer : public CppScripts::Script { public: - virtual void SetGameVariables(Entity* self); - virtual void CheckForOwner(Entity* self); - virtual void PropGuardCheck(Entity* self, Entity* player); + virtual void SetGameVariables(Entity* self); + virtual void CheckForOwner(Entity* self); + virtual void PropGuardCheck(Entity* self, Entity* player); - void OnStartup(Entity *self) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; - void OnPlayerLoaded(Entity *self, Entity *player) override { BasePlayerLoaded(self, player); }; - void OnPlayerExit(Entity *self, Entity *player) override { BasePlayerExit(self, player); }; - void OnZonePropertyModelPlaced(Entity *self, Entity *player) override { BaseZonePropertyModelPlaced(self, player); } - void OnZonePropertyRented(Entity *self, Entity* renter) override { BaseZonePropertyRented(self, renter); }; - void OnTimerDone(Entity *self, std::string timerName) override { BaseTimerDone(self, timerName); }; + void OnStartup(Entity* self) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; + void OnPlayerLoaded(Entity* self, Entity* player) override { BasePlayerLoaded(self, player); }; + void OnPlayerExit(Entity* self, Entity* player) override { BasePlayerExit(self, player); }; + void OnZonePropertyModelPlaced(Entity* self, Entity* player) override { BaseZonePropertyModelPlaced(self, player); } + void OnZonePropertyRented(Entity* self, Entity* renter) override { BaseZonePropertyRented(self, renter); }; + void OnTimerDone(Entity* self, std::string timerName) override { BaseTimerDone(self, timerName); }; virtual void BasePlayerLoaded(Entity* self, Entity* player); virtual void BaseZonePropertyRented(Entity* self, Entity* player) const; virtual void BaseZonePropertyModelPlaced(Entity* self, Entity* player) const; - virtual void BasePlayerExit(Entity *self, Entity *player); - virtual void BaseTimerDone(Entity* self, const std::string& timerName); + virtual void BasePlayerExit(Entity* self, Entity* player); + virtual void BaseTimerDone(Entity* self, const std::string& timerName); void KillClouds(Entity* self); virtual void SpawnSpots(Entity* self); @@ -39,79 +39,79 @@ public: static LWOOBJID GetOwner(); protected: - void HandleOrbsTimer(Entity* self); - void HandleGeneratorTimer(Entity* self); - void HandleQuickBuildTimer(Entity* self); + void HandleOrbsTimer(Entity* self); + void HandleGeneratorTimer(Entity* self); + void HandleQuickBuildTimer(Entity* self); - // GUIDs - std::string GUIDMaelstrom = "{7881e0a1-ef6d-420c-8040-f59994aa3357}"; - std::string GUIDPeaceful = "{c5725665-58d0-465f-9e11-aeb1d21842ba}"; + // GUIDs + std::string GUIDMaelstrom = "{7881e0a1-ef6d-420c-8040-f59994aa3357}"; + std::string GUIDPeaceful = "{c5725665-58d0-465f-9e11-aeb1d21842ba}"; - // Groups - std::u16string PropertyPlaqueGroup = u"PropertyPlaqueGroup"; - std::u16string PropertyVendorGroup = u"PropertyVendorGroup"; - std::u16string PropertyBorderGroup = u"PropertyBorderGroup"; - std::u16string SpotsGroup = u"SpotsGroup"; - std::u16string MSCloudsGroup = u"MSCloudsGroup"; - std::u16string GeneratorFXGroup = u"GeneratorFXGroup"; - std::u16string GeneratorGroup = u"GeneratorGroup"; - std::u16string ImagOrbGroup = u"ImagOrbGroup"; - std::u16string FXManagerGroup = u"FXManagerGroup"; - std::u16string ClaimMarkerGroup = u"ClaimMarkerGroup"; - std::u16string GuardGroup = u"GuardGroup"; - std::u16string EnemiesGroup = u"EnemiesGroup"; + // Groups + std::u16string PropertyPlaqueGroup = u"PropertyPlaqueGroup"; + std::u16string PropertyVendorGroup = u"PropertyVendorGroup"; + std::u16string PropertyBorderGroup = u"PropertyBorderGroup"; + std::u16string SpotsGroup = u"SpotsGroup"; + std::u16string MSCloudsGroup = u"MSCloudsGroup"; + std::u16string GeneratorFXGroup = u"GeneratorFXGroup"; + std::u16string GeneratorGroup = u"GeneratorGroup"; + std::u16string ImagOrbGroup = u"ImagOrbGroup"; + std::u16string FXManagerGroup = u"FXManagerGroup"; + std::u16string ClaimMarkerGroup = u"ClaimMarkerGroup"; + std::u16string GuardGroup = u"GuardGroup"; + std::u16string EnemiesGroup = u"EnemiesGroup"; - // Spawners - std::u16string EnemiesSpawner = u"EnemiesSpawner"; - std::u16string PropObjsSpawner = u"PropObjsSpawner"; - std::u16string PropertyMGSpawner = u"PropertyMGSpawner"; - std::u16string DamageFXSpawner = u"DamageFXSpawner"; - std::u16string FXSpotsSpawner = u"FXSpotsSpawner"; - std::u16string GeneratorSpawner = u"GeneratorSpawner"; - std::u16string GeneratorFXSpawner = u"GeneratorFXSpawner"; - std::u16string FXManagerSpawner = u"FXManagerSpawner"; - std::u16string ImageOrbSpawner = u"ImageOrbSpawner"; - std::u16string AmbientFXSpawner = u"AmbientFXSpawners"; - std::u16string SmashablesSpawner = u"SmashablesSpawner"; - std::u16string ClaimMarkerSpawner = u"ClaimMarkerSpawner"; - std::u16string BehaviorObjsSpawner = u"BehaviorObjsSpawner"; + // Spawners + std::u16string EnemiesSpawner = u"EnemiesSpawner"; + std::u16string PropObjsSpawner = u"PropObjsSpawner"; + std::u16string PropertyMGSpawner = u"PropertyMGSpawner"; + std::u16string DamageFXSpawner = u"DamageFXSpawner"; + std::u16string FXSpotsSpawner = u"FXSpotsSpawner"; + std::u16string GeneratorSpawner = u"GeneratorSpawner"; + std::u16string GeneratorFXSpawner = u"GeneratorFXSpawner"; + std::u16string FXManagerSpawner = u"FXManagerSpawner"; + std::u16string ImageOrbSpawner = u"ImageOrbSpawner"; + std::u16string AmbientFXSpawner = u"AmbientFXSpawners"; + std::u16string SmashablesSpawner = u"SmashablesSpawner"; + std::u16string ClaimMarkerSpawner = u"ClaimMarkerSpawner"; + std::u16string BehaviorObjsSpawner = u"BehaviorObjsSpawner"; - //Flags / constants - std::u16string guardFirstMissionFlag = u"guardFirstMissionFlag"; - std::u16string guardMissionFlag = u"guardMissionFlag"; - std::u16string brickLinkMissionIDFlag = u"brickLinkMissionIDFlag"; - std::u16string placedModelFlag = u"placedModelFlag"; - std::u16string generatorIdFlag = u"generatorIdFlag"; - std::u16string defeatedProperyFlag = u"defeatedProperyFlag"; - std::u16string passwordFlag = u"passwordFlag"; - std::u16string orbIDFlag = u"orbIDFlag"; - std::u16string behaviorQBID = u"behaviorQBID"; + //Flags / constants + std::u16string guardFirstMissionFlag = u"guardFirstMissionFlag"; + std::u16string guardMissionFlag = u"guardMissionFlag"; + std::u16string brickLinkMissionIDFlag = u"brickLinkMissionIDFlag"; + std::u16string placedModelFlag = u"placedModelFlag"; + std::u16string generatorIdFlag = u"generatorIdFlag"; + std::u16string defeatedProperyFlag = u"defeatedProperyFlag"; + std::u16string passwordFlag = u"passwordFlag"; + std::u16string orbIDFlag = u"orbIDFlag"; + std::u16string behaviorQBID = u"behaviorQBID"; - // Variables - std::u16string PlayerIDVariable = u"playerID"; - std::u16string CollidedVariable = u"collided"; - std::u16string PropertyOwnerVariable = u"PropertyOwner"; - std::u16string PropertyOwnerIDVariable = u"PropertyOwnerID"; - std::u16string FXObjectsGoneVariable = u"FXObjectGone"; - std::u16string RenterVariable = u"renter"; - std::u16string UnclaimedVariable = u"unclaimed"; + // Variables + std::u16string PlayerIDVariable = u"playerID"; + std::u16string CollidedVariable = u"collided"; + std::u16string PropertyOwnerVariable = u"PropertyOwner"; + std::u16string PropertyOwnerIDVariable = u"PropertyOwnerID"; + std::u16string FXObjectsGoneVariable = u"FXObjectGone"; + std::u16string RenterVariable = u"renter"; + std::u16string UnclaimedVariable = u"unclaimed"; - // Events - std::string CheckForPropertyOwnerEvent = "CheckForPropertyOwner"; + // Events + std::string CheckForPropertyOwnerEvent = "CheckForPropertyOwner"; - // Timers - std::string StartGeneratorTimer = "startGenerator"; - std::string StartOrbTimer = "startOrb"; - std::string StartQuickbuildTimer = "startQuickbuild"; - std::string TornadoOffTimer = "tornadoOff"; - std::string KillMarkerTimer = "killMarker"; - std::string KillGuardTimer = "KillGuard"; - std::string ShowClearEffectsTimer = "ShowClearEffects"; - std::string TurnSkyOffTimer = "turnSkyOff"; - std::string KillStrombiesTimer = "killStrombies"; - std::string KillFXObjectTimer = "killFXObject"; - std::string ShowVendorTimer = "ShowVendor"; - std::string BoundsVisOnTimer = "BoundsVisOn"; - std::string RunPlayerLoadedAgainTimer = "runPlayerLoadedAgain"; - std::string PollTornadoFXTimer = "pollTornadoFX"; + // Timers + std::string StartGeneratorTimer = "startGenerator"; + std::string StartOrbTimer = "startOrb"; + std::string StartQuickbuildTimer = "startQuickbuild"; + std::string TornadoOffTimer = "tornadoOff"; + std::string KillMarkerTimer = "killMarker"; + std::string KillGuardTimer = "KillGuard"; + std::string ShowClearEffectsTimer = "ShowClearEffects"; + std::string TurnSkyOffTimer = "turnSkyOff"; + std::string KillStrombiesTimer = "killStrombies"; + std::string KillFXObjectTimer = "killFXObject"; + std::string ShowVendorTimer = "ShowVendor"; + std::string BoundsVisOnTimer = "BoundsVisOn"; + std::string RunPlayerLoadedAgainTimer = "runPlayerLoadedAgain"; + std::string PollTornadoFXTimer = "pollTornadoFX"; }; diff --git a/dScripts/BaseRandomServer.cpp b/dScripts/BaseRandomServer.cpp index c2d335c4..8cc4f993 100644 --- a/dScripts/BaseRandomServer.cpp +++ b/dScripts/BaseRandomServer.cpp @@ -4,199 +4,169 @@ #include "dLogger.h" #include "Entity.h" -void BaseRandomServer::BaseStartup(Entity* self) -{ - self->SetVar(u"SpawnState", "min"); - self->SetVar(u"JustChanged", false); +void BaseRandomServer::BaseStartup(Entity* self) { + self->SetVar(u"SpawnState", "min"); + self->SetVar(u"JustChanged", false); - CheckEvents(self); - SpawnMapZones(self); + CheckEvents(self); + SpawnMapZones(self); } -void BaseRandomServer::CheckEvents(Entity* self) -{ - // TODO: Add events? +void BaseRandomServer::CheckEvents(Entity* self) { + // TODO: Add events? } -void BaseRandomServer::SpawnMapZones(Entity* self) -{ - for (const auto& pair : sectionMultipliers) - { - const auto sectionName = zonePrefix + "_" + zoneName + "_" + pair.first; +void BaseRandomServer::SpawnMapZones(Entity* self) { + for (const auto& pair : sectionMultipliers) { + const auto sectionName = zonePrefix + "_" + zoneName + "_" + pair.first; - SpawnSection(self, sectionName, pair.second); - } + SpawnSection(self, sectionName, pair.second); + } - if (zoneName == "str") - { - SpawnNamedEnemy(self); - } + if (zoneName == "str") { + SpawnNamedEnemy(self); + } - self->SetVar(u"bInit", true); + self->SetVar(u"bInit", true); } -void BaseRandomServer::SpawnSection(Entity* self, const std::string& sectionName, float iMultiplier) -{ - Zone* spawnLoad = GetRandomLoad(self, sectionName); +void BaseRandomServer::SpawnSection(Entity* self, const std::string& sectionName, float iMultiplier) { + Zone* spawnLoad = GetRandomLoad(self, sectionName); - if (spawnLoad == nullptr) - { - Game::logger->Log("BaseRandomServer", "Failed to find section: %s", sectionName.c_str()); + if (spawnLoad == nullptr) { + Game::logger->Log("BaseRandomServer", "Failed to find section: %s", sectionName.c_str()); - return; - } + return; + } - for (const auto& spawnerData : spawnLoad->entries) - { - if (spawnerData.name.empty()) - { - continue; - } + for (const auto& spawnerData : spawnLoad->entries) { + if (spawnerData.name.empty()) { + continue; + } - const auto spawnNum = std::floor(spawnerData.num * iMultiplier); - const auto spawnerName = sectionName + "_" + spawnerData.name; + const auto spawnNum = std::floor(spawnerData.num * iMultiplier); + const auto spawnerName = sectionName + "_" + spawnerData.name; - SetSpawnerNetwork(self, spawnerName, spawnNum, spawnerData.lot); - } + SetSpawnerNetwork(self, spawnerName, spawnNum, spawnerData.lot); + } } -void BaseRandomServer::SetSpawnerNetwork(Entity* self, const std::string& spawnerName, int32_t spawnNum, LOT spawnLOT) -{ - const auto& spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); +void BaseRandomServer::SetSpawnerNetwork(Entity* self, const std::string& spawnerName, int32_t spawnNum, LOT spawnLOT) { + const auto& spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); - if (spawnLOT == 11217 && spawnNum > 1) - { - spawnNum = 1; - } + if (spawnLOT == 11217 && spawnNum > 1) { + spawnNum = 1; + } - if (spawners.empty()) - { - Game::logger->Log("BaseRandomServer", "Failed to find spawner: %s", spawnerName.c_str()); + if (spawners.empty()) { + Game::logger->Log("BaseRandomServer", "Failed to find spawner: %s", spawnerName.c_str()); - return; - } + return; + } - auto* spawner = spawners[0]; + auto* spawner = spawners[0]; - if (spawnLOT != 0) - { - spawner->SetSpawnLot(spawnLOT); - spawner->SetRespawnTime(respawnTime); - } + if (spawnLOT != 0) { + spawner->SetSpawnLot(spawnLOT); + spawner->SetRespawnTime(respawnTime); + } - if (spawnNum != 0) - { - spawner->SetNumToMaintain(spawnNum); - } + if (spawnNum != 0) { + spawner->SetNumToMaintain(spawnNum); + } - if (spawnerName == "Named_Enemies") - { - spawner->SoftReset(); - } + if (spawnerName == "Named_Enemies") { + spawner->SoftReset(); + } - spawner->Activate(); + spawner->Activate(); - if (std::find(spawnersWatched.begin(), spawnersWatched.end(), spawner) != spawnersWatched.end()) - { - return; - } + if (std::find(spawnersWatched.begin(), spawnersWatched.end(), spawner) != spawnersWatched.end()) { + return; + } - spawner->AddSpawnedEntityDieCallback([this, self, spawner] () { - NotifySpawnerOfDeath(self, spawner); - }); + spawner->AddSpawnedEntityDieCallback([this, self, spawner]() { + NotifySpawnerOfDeath(self, spawner); + }); - spawnersWatched.push_back(spawner); + spawnersWatched.push_back(spawner); } -BaseRandomServer::Zone* BaseRandomServer::GetRandomLoad(Entity* self, const std::string& sectionName) -{ - const auto zoneInfo = GeneralUtils::SplitString(sectionName, '_'); +BaseRandomServer::Zone* BaseRandomServer::GetRandomLoad(Entity* self, const std::string& sectionName) { + const auto zoneInfo = GeneralUtils::SplitString(sectionName, '_'); - int32_t totalWeight = 0; + int32_t totalWeight = 0; - for (const auto& load : zones) - { - totalWeight += load.iChance; - } + for (const auto& load : zones) { + totalWeight += load.iChance; + } - const auto randWeight = GeneralUtils::GenerateRandomNumber(0, totalWeight); + const auto randWeight = GeneralUtils::GenerateRandomNumber(0, totalWeight); - int32_t weight = 0; - for (auto& zone : zones) - { - weight += zone.iChance; + int32_t weight = 0; + for (auto& zone : zones) { + weight += zone.iChance; - if (randWeight <= weight) - { - return &zone; - } - } + if (randWeight <= weight) { + return &zone; + } + } - return nullptr; + return nullptr; } -void BaseRandomServer::NotifySpawnerOfDeath(Entity* self, Spawner* spawner) -{ - const auto& spawnerName = spawner->GetName(); +void BaseRandomServer::NotifySpawnerOfDeath(Entity* self, Spawner* spawner) { + const auto& spawnerName = spawner->GetName(); - if (spawnerName == "Named_Enemies") - { - NamedEnemyDeath(self, spawner); + if (spawnerName == "Named_Enemies") { + NamedEnemyDeath(self, spawner); - return; - } + return; + } - const auto& sectionName = spawnerName.substr(0, spawnerName.size() - 7); + const auto& sectionName = spawnerName.substr(0, spawnerName.size() - 7); - const auto variableName = u"mobsDead" + GeneralUtils::ASCIIToUTF16(sectionName); + const auto variableName = u"mobsDead" + GeneralUtils::ASCIIToUTF16(sectionName); - auto mobDeathCount = self->GetVar(variableName); + auto mobDeathCount = self->GetVar(variableName); - mobDeathCount++; + mobDeathCount++; - if (mobDeathCount >= mobDeathResetNumber) - { - const auto& zoneInfo = GeneralUtils::SplitString(sectionName, '_'); + if (mobDeathCount >= mobDeathResetNumber) { + const auto& zoneInfo = GeneralUtils::SplitString(sectionName, '_'); - SpawnSection(self, sectionName, sectionMultipliers[zoneInfo[sectionIDConst - 1]]); - } + SpawnSection(self, sectionName, sectionMultipliers[zoneInfo[sectionIDConst - 1]]); + } - self->SetVar(variableName, mobDeathCount); + self->SetVar(variableName, mobDeathCount); } -void BaseRandomServer::NamedEnemyDeath(Entity* self, Spawner* spawner) -{ - const auto spawnDelay = GeneralUtils::GenerateRandomNumber(1, 2) * 450; +void BaseRandomServer::NamedEnemyDeath(Entity* self, Spawner* spawner) { + const auto spawnDelay = GeneralUtils::GenerateRandomNumber(1, 2) * 450; - self->AddTimer("SpawnNewEnemy", spawnDelay); + self->AddTimer("SpawnNewEnemy", spawnDelay); } -void BaseRandomServer::SpawnersUp(Entity* self) -{ +void BaseRandomServer::SpawnersUp(Entity* self) { } -void BaseRandomServer::SpawnersDown(Entity* self) -{ +void BaseRandomServer::SpawnersDown(Entity* self) { } -void BaseRandomServer::BaseOnTimerDone(Entity* self, const std::string& timerName) -{ - NamedTimerDone(self, timerName); +void BaseRandomServer::BaseOnTimerDone(Entity* self, const std::string& timerName) { + NamedTimerDone(self, timerName); } -void BaseRandomServer::SpawnNamedEnemy(Entity* self) -{ - const auto enemy = namedMobs[GeneralUtils::GenerateRandomNumber(0, namedMobs.size() - 1)]; +void BaseRandomServer::SpawnNamedEnemy(Entity* self) { + const auto enemy = namedMobs[GeneralUtils::GenerateRandomNumber(0, namedMobs.size() - 1)]; - SetSpawnerNetwork(self, "Named_Enemies", 1, enemy); + SetSpawnerNetwork(self, "Named_Enemies", 1, enemy); } -void BaseRandomServer::NamedTimerDone(Entity* self, const std::string& timerName) -{ - if (timerName == "SpawnNewEnemy") - { - SpawnNamedEnemy(self); - } +void BaseRandomServer::NamedTimerDone(Entity* self, const std::string& timerName) { + if (timerName == "SpawnNewEnemy") { + SpawnNamedEnemy(self); + } } diff --git a/dScripts/BaseRandomServer.h b/dScripts/BaseRandomServer.h index 68aadf30..bc5d6b21 100644 --- a/dScripts/BaseRandomServer.h +++ b/dScripts/BaseRandomServer.h @@ -6,54 +6,54 @@ class Spawner; class BaseRandomServer { public: - struct ZoneEntry - { - LOT lot; - int32_t num; - std::string name; - }; + struct ZoneEntry + { + LOT lot; + int32_t num; + std::string name; + }; - struct Zone - { - std::vector entries; - int32_t iChance; - }; + struct Zone + { + std::vector entries; + int32_t iChance; + }; - void BaseStartup(Entity* self); - void CheckEvents(Entity* self); - void SpawnMapZones(Entity* self); - void SpawnSection(Entity* self, const std::string& sectionName, float iMultiplier); - void SetSpawnerNetwork(Entity* self, const std::string& spawnerName, int32_t spawnNum, LOT spawnLOT); - BaseRandomServer::Zone* GetRandomLoad(Entity* self, const std::string& sectionName); - void SpawnersUp(Entity* self); - void SpawnersDown(Entity* self); - void BaseOnTimerDone(Entity* self, const std::string& timerName); - - void NotifySpawnerOfDeath(Entity* self, Spawner* spawner); - void NamedEnemyDeath(Entity* self, Spawner* spawner); + void BaseStartup(Entity* self); + void CheckEvents(Entity* self); + void SpawnMapZones(Entity* self); + void SpawnSection(Entity* self, const std::string& sectionName, float iMultiplier); + void SetSpawnerNetwork(Entity* self, const std::string& spawnerName, int32_t spawnNum, LOT spawnLOT); + BaseRandomServer::Zone* GetRandomLoad(Entity* self, const std::string& sectionName); + void SpawnersUp(Entity* self); + void SpawnersDown(Entity* self); + void BaseOnTimerDone(Entity* self, const std::string& timerName); - void SpawnNamedEnemy(Entity* self); + void NotifySpawnerOfDeath(Entity* self, Spawner* spawner); + void NamedEnemyDeath(Entity* self, Spawner* spawner); - void NamedTimerDone(Entity* self, const std::string& timerName); + void SpawnNamedEnemy(Entity* self); + + void NamedTimerDone(Entity* self, const std::string& timerName); protected: - std::vector namedMobs = { - 11988, // Ronin - 11984, // Spiderling - 12654, // Horsemen - 11986, // Admiral - 11983, // Mech - 11982, // Stromling - 11985 // Pirate - }; - std::map sectionMultipliers = {}; - int32_t mobDeathResetNumber = 30; - std::string zonePrefix = "em"; - int32_t zoneNameConst = 2; - int32_t sectionIDConst = 3; - std::string zoneName = "fin"; - std::vector zones = {}; - int32_t changeNum = 15; - int32_t respawnTime = 80; - std::vector spawnersWatched; + std::vector namedMobs = { + 11988, // Ronin + 11984, // Spiderling + 12654, // Horsemen + 11986, // Admiral + 11983, // Mech + 11982, // Stromling + 11985 // Pirate + }; + std::map sectionMultipliers = {}; + int32_t mobDeathResetNumber = 30; + std::string zonePrefix = "em"; + int32_t zoneNameConst = 2; + int32_t sectionIDConst = 3; + std::string zoneName = "fin"; + std::vector zones = {}; + int32_t changeNum = 15; + int32_t respawnTime = 80; + std::vector spawnersWatched; }; diff --git a/dScripts/BaseSurvivalServer.cpp b/dScripts/BaseSurvivalServer.cpp index f6a326e8..270b6741 100644 --- a/dScripts/BaseSurvivalServer.cpp +++ b/dScripts/BaseSurvivalServer.cpp @@ -8,570 +8,566 @@ #include "MissionComponent.h" #include "Character.h" -void BaseSurvivalServer::SetGameVariables(Entity *self) { - this->constants = std::move(GetConstants()); - this->mobSets = std::move(GetMobSets()); - this->spawnerNetworks = std::move(GetSpawnerNetworks()); - this->missionsToUpdate = std::move(GetMissionsToUpdate()); +void BaseSurvivalServer::SetGameVariables(Entity* self) { + this->constants = std::move(GetConstants()); + this->mobSets = std::move(GetMobSets()); + this->spawnerNetworks = std::move(GetSpawnerNetworks()); + this->missionsToUpdate = std::move(GetMissionsToUpdate()); } void BaseSurvivalServer::BasePlayerLoaded(Entity* self, Entity* player) { - const auto& waitingIter = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), player->GetObjectID()); - const auto& playersIter = std::find(state.players.begin(), state.players.end(), player->GetObjectID()); + const auto& waitingIter = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), player->GetObjectID()); + const auto& playersIter = std::find(state.players.begin(), state.players.end(), player->GetObjectID()); - if (waitingIter != state.waitingPlayers.end() || playersIter != state.players.end()) - { - static_cast(player)->SendToZone(player->GetCharacter()->GetLastNonInstanceZoneID()); + if (waitingIter != state.waitingPlayers.end() || playersIter != state.players.end()) { + static_cast(player)->SendToZone(player->GetCharacter()->GetLastNonInstanceZoneID()); - return; - } + return; + } - state.waitingPlayers.push_back(player->GetObjectID()); - state.players.push_back(player->GetObjectID()); + state.waitingPlayers.push_back(player->GetObjectID()); + state.players.push_back(player->GetObjectID()); - self->SetNetworkVar(NumberOfPlayersVariable, self->GetNetworkVar(NumberOfPlayersVariable) + 1); - self->SetNetworkVar(DefinePlayerToUIVariable, std::to_string(player->GetObjectID()), player->GetSystemAddress()); + self->SetNetworkVar(NumberOfPlayersVariable, self->GetNetworkVar(NumberOfPlayersVariable) + 1); + self->SetNetworkVar(DefinePlayerToUIVariable, std::to_string(player->GetObjectID()), player->GetSystemAddress()); - // Notify the players of all other players - if (!self->GetNetworkVar(WavesStartedVariable)) { - auto counter = 1; - for (const auto& playerID : state.players) { - self->SetNetworkVar(UpdateScoreboardPlayersVariable + GeneralUtils::to_u16string(counter), std::to_string(playerID)); - counter++; - } + // Notify the players of all other players + if (!self->GetNetworkVar(WavesStartedVariable)) { + auto counter = 1; + for (const auto& playerID : state.players) { + self->SetNetworkVar(UpdateScoreboardPlayersVariable + GeneralUtils::to_u16string(counter), std::to_string(playerID)); + counter++; + } - self->SetNetworkVar(ShowScoreboardVariable, true); - } + self->SetNetworkVar(ShowScoreboardVariable, true); + } - SetPlayerSpawnPoints(); + SetPlayerSpawnPoints(); - if (!self->GetNetworkVar(WavesStartedVariable)) { - PlayerConfirmed(self); - } else { - UpdatePlayer(self, player->GetObjectID()); - GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self), 50); - ResetStats(player->GetObjectID()); - } + if (!self->GetNetworkVar(WavesStartedVariable)) { + PlayerConfirmed(self); + } else { + UpdatePlayer(self, player->GetObjectID()); + GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self), 50); + ResetStats(player->GetObjectID()); + } - player->AddCallbackTimer(5.0f, [this, self, player] () { - self->SetNetworkVar(NumberOfPlayersVariable, self->GetNetworkVar(NumberOfPlayersVariable)); - self->SetNetworkVar(DefinePlayerToUIVariable, std::to_string(player->GetObjectID()), player->GetSystemAddress()); - if (!self->GetNetworkVar(WavesStartedVariable)) { - auto counter = 1; - for (const auto& playerID : state.players) { - self->SetNetworkVar(UpdateScoreboardPlayersVariable + GeneralUtils::to_u16string(counter), std::to_string(playerID)); - counter++; - } + player->AddCallbackTimer(5.0f, [this, self, player]() { + self->SetNetworkVar(NumberOfPlayersVariable, self->GetNetworkVar(NumberOfPlayersVariable)); + self->SetNetworkVar(DefinePlayerToUIVariable, std::to_string(player->GetObjectID()), player->GetSystemAddress()); + if (!self->GetNetworkVar(WavesStartedVariable)) { + auto counter = 1; + for (const auto& playerID : state.players) { + self->SetNetworkVar(UpdateScoreboardPlayersVariable + GeneralUtils::to_u16string(counter), std::to_string(playerID)); + counter++; + } - self->SetNetworkVar(ShowScoreboardVariable, true); - } - }); + self->SetNetworkVar(ShowScoreboardVariable, true); + } + }); } void BaseSurvivalServer::BaseStartup(Entity* self) { - self->SetVar(PlayersAcceptedVariable, 0); - self->SetVar(PlayersReadyVariable, false); + self->SetVar(PlayersAcceptedVariable, 0); + self->SetVar(PlayersReadyVariable, false); } void BaseSurvivalServer::BasePlayerExit(Entity* self, Entity* player) { - const auto& waitingIter = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), player->GetObjectID()); - const auto& playersIter = std::find(state.players.begin(), state.players.end(), player->GetObjectID()); + const auto& waitingIter = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), player->GetObjectID()); + const auto& playersIter = std::find(state.players.begin(), state.players.end(), player->GetObjectID()); - if (waitingIter != state.waitingPlayers.end()) - { - state.waitingPlayers.erase(waitingIter); - } + if (waitingIter != state.waitingPlayers.end()) { + state.waitingPlayers.erase(waitingIter); + } - if (playersIter != state.players.end()) - { - state.players.erase(playersIter); - } + if (playersIter != state.players.end()) { + state.players.erase(playersIter); + } - if (waitingIter == state.waitingPlayers.end() && playersIter == state.players.end()) - { - return; - } + if (waitingIter == state.waitingPlayers.end() && playersIter == state.players.end()) { + return; + } - if (!self->GetNetworkVar(WavesStartedVariable)) { - PlayerConfirmed(self); + if (!self->GetNetworkVar(WavesStartedVariable)) { + PlayerConfirmed(self); - if (state.players.empty()) - return; + if (state.players.empty()) + return; - if (state.waitingPlayers.empty()) { - ActivityTimerStopAllTimers(self); - ActivityTimerStart(self, AllAcceptedDelayTimer, 1.0f, constants.startDelay); - } else if (state.players.size() > state.waitingPlayers.size()) { - if (!self->GetVar(AcceptedDelayStartedVariable)) { - self->SetVar(AcceptedDelayStartedVariable, true); - ActivityTimerStart(self, AcceptedDelayTimer, 1.0f, constants.acceptedDelay); - } - } - } else { - UpdatePlayer(self, player->GetObjectID(), true); - if (CheckAllPlayersDead()) { - GameOver(self); - } - } + if (state.waitingPlayers.empty()) { + ActivityTimerStopAllTimers(self); + ActivityTimerStart(self, AllAcceptedDelayTimer, 1.0f, constants.startDelay); + } else if (state.players.size() > state.waitingPlayers.size()) { + if (!self->GetVar(AcceptedDelayStartedVariable)) { + self->SetVar(AcceptedDelayStartedVariable, true); + ActivityTimerStart(self, AcceptedDelayTimer, 1.0f, constants.acceptedDelay); + } + } + } else { + UpdatePlayer(self, player->GetObjectID(), true); + if (CheckAllPlayersDead()) { + GameOver(self); + } + } - SetActivityValue(self, player->GetObjectID(), 1, 0); - self->SetNetworkVar(NumberOfPlayersVariable, - std::min((uint32_t) 0, self->GetNetworkVar(NumberOfPlayersVariable) - 1)); + SetActivityValue(self, player->GetObjectID(), 1, 0); + self->SetNetworkVar(NumberOfPlayersVariable, + std::min((uint32_t)0, self->GetNetworkVar(NumberOfPlayersVariable) - 1)); } void BaseSurvivalServer::BaseFireEvent(Entity* self, Entity* sender, const std::string& args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "start") { - StartWaves(self); - } else if (args == "DeactivateRewards") { - SpawnerReset(spawnerNetworks.rewardNetworks); - } else if (sender != nullptr && IsPlayerInActivity(self, sender->GetObjectID())) { - auto currentScore = GetActivityValue(self, sender->GetObjectID(), 0); - SetActivityValue(self, sender->GetObjectID(), 0, currentScore + param1); - } + int32_t param3) { + if (args == "start") { + StartWaves(self); + } else if (args == "DeactivateRewards") { + SpawnerReset(spawnerNetworks.rewardNetworks); + } else if (sender != nullptr && IsPlayerInActivity(self, sender->GetObjectID())) { + auto currentScore = GetActivityValue(self, sender->GetObjectID(), 0); + SetActivityValue(self, sender->GetObjectID(), 0, currentScore + param1); + } } void BaseSurvivalServer::BasePlayerDied(Entity* self, Entity* player) { - if (self->GetNetworkVar(WavesStartedVariable)) { - const auto finalTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); - SetActivityValue(self, player->GetObjectID(), 1, finalTime); + if (self->GetNetworkVar(WavesStartedVariable)) { + const auto finalTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); + SetActivityValue(self, player->GetObjectID(), 1, finalTime); - auto paramString = CheckAllPlayersDead() ? "true" : "false"; - GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Player_Died", finalTime, 0, - player->GetObjectID(), paramString, player->GetSystemAddress()); - GameOver(self); - } else { - player->Resurrect(); - SetPlayerSpawnPoints(); - } + auto paramString = CheckAllPlayersDead() ? "true" : "false"; + GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Player_Died", finalTime, 0, + player->GetObjectID(), paramString, player->GetSystemAddress()); + GameOver(self); + } else { + player->Resurrect(); + SetPlayerSpawnPoints(); + } } -void BaseSurvivalServer::BasePlayerResurrected(Entity *self, Entity *player) { - self->SetNetworkVar(ShowScoreboardVariable, true); +void BaseSurvivalServer::BasePlayerResurrected(Entity* self, Entity* player) { + self->SetNetworkVar(ShowScoreboardVariable, true); } void BaseSurvivalServer::BaseMessageBoxResponse(Entity* self, Entity* sender, int32_t button, - const std::u16string &identifier, const std::u16string &userData) { - if (identifier == u"RePlay") { - PlayerAccepted(self, sender->GetObjectID()); - PlayerConfirmed(self); - } else if (identifier == u"Exit_Question" && button == 1) { - ResetStats(sender->GetObjectID()); - self->SetNetworkVar(ExitWavesVariable, std::to_string(sender->GetObjectID())); + const std::u16string& identifier, const std::u16string& userData) { + if (identifier == u"RePlay") { + PlayerAccepted(self, sender->GetObjectID()); + PlayerConfirmed(self); + } else if (identifier == u"Exit_Question" && button == 1) { + ResetStats(sender->GetObjectID()); + self->SetNetworkVar(ExitWavesVariable, std::to_string(sender->GetObjectID())); - if (sender->IsPlayer()) { - auto* character = sender->GetCharacter(); - if (character != nullptr) { - auto* player = dynamic_cast(sender); - player->SendToZone(character->GetLastNonInstanceZoneID()); - } - } - } + if (sender->IsPlayer()) { + auto* character = sender->GetCharacter(); + if (character != nullptr) { + auto* player = dynamic_cast(sender); + player->SendToZone(character->GetLastNonInstanceZoneID()); + } + } + } } -void BaseSurvivalServer::OnActivityTimerUpdate(Entity *self, const std::string &name, float_t remainingTime, float_t elapsedTime) { - if (name == AcceptedDelayTimer) { - self->SetNetworkVar(UpdateDefaultStartTimerVariable, remainingTime); - } else if (name == ClockTickTimer) { - self->SetNetworkVar(UpdateTimerVariable, elapsedTime); - } else if (name == SpawnTickTimer && !self->GetVar(IsCooldownVariable)) { - SpawnMobs(self); - } +void BaseSurvivalServer::OnActivityTimerUpdate(Entity* self, const std::string& name, float_t remainingTime, float_t elapsedTime) { + if (name == AcceptedDelayTimer) { + self->SetNetworkVar(UpdateDefaultStartTimerVariable, remainingTime); + } else if (name == ClockTickTimer) { + self->SetNetworkVar(UpdateTimerVariable, elapsedTime); + } else if (name == SpawnTickTimer && !self->GetVar(IsCooldownVariable)) { + SpawnMobs(self); + } } -void BaseSurvivalServer::OnActivityTimerDone(Entity *self, const std::string &name) { - auto cooldownTime = constants.rewardInterval * constants.waveTime; +void BaseSurvivalServer::OnActivityTimerDone(Entity* self, const std::string& name) { + auto cooldownTime = constants.rewardInterval * constants.waveTime; - if (name == AcceptedDelayTimer) { - self->SetNetworkVar(UpdateDefaultStartTimerVariable, 0); - ActivityTimerStart(self, AllAcceptedDelayTimer, 1, 1); - } else if (name == AllAcceptedDelayTimer) { - self->SetNetworkVar(ClearScoreboardVariable, true); - ActivityTimerStart(self, StartDelayTimer, 3, 3); + if (name == AcceptedDelayTimer) { + self->SetNetworkVar(UpdateDefaultStartTimerVariable, 0); + ActivityTimerStart(self, AllAcceptedDelayTimer, 1, 1); + } else if (name == AllAcceptedDelayTimer) { + self->SetNetworkVar(ClearScoreboardVariable, true); + ActivityTimerStart(self, StartDelayTimer, 3, 3); - StartWaves(self); - } else if (name == StartDelayTimer) { - ActivityTimerStart(self, ClockTickTimer, 1); - ActivityTimerStart(self, SpawnTickTimer, constants.waveTime); - SpawnMobs(self); - ActivityTimerStart(self, PlaySpawnSoundTimer, 3, 3); - ActivityTimerStart(self, CoolDownStartTimer, cooldownTime, cooldownTime); - } else if (name == CoolDownStartTimer) { - self->SetVar(IsCooldownVariable, true); + StartWaves(self); + } else if (name == StartDelayTimer) { + ActivityTimerStart(self, ClockTickTimer, 1); + ActivityTimerStart(self, SpawnTickTimer, constants.waveTime); + SpawnMobs(self); + ActivityTimerStart(self, PlaySpawnSoundTimer, 3, 3); + ActivityTimerStart(self, CoolDownStartTimer, cooldownTime, cooldownTime); + } else if (name == CoolDownStartTimer) { + self->SetVar(IsCooldownVariable, true); - ActivityTimerStop(self, SpawnTickTimer); - ActivityTimerStart(self, CoolDownStopTimer, 1, constants.coolDownTime); + ActivityTimerStop(self, SpawnTickTimer); + ActivityTimerStart(self, CoolDownStopTimer, 1, constants.coolDownTime); - ActivateSpawnerNetwork(spawnerNetworks.rewardNetworks); - SpawnerReset(spawnerNetworks.baseNetworks, false); - SpawnerReset(spawnerNetworks.randomNetworks, false); - } else if (name == CoolDownStopTimer) { - self->SetVar(IsCooldownVariable, false); + ActivateSpawnerNetwork(spawnerNetworks.rewardNetworks); + SpawnerReset(spawnerNetworks.baseNetworks, false); + SpawnerReset(spawnerNetworks.randomNetworks, false); + } else if (name == CoolDownStopTimer) { + self->SetVar(IsCooldownVariable, false); - ActivityTimerStart(self, SpawnTickTimer, constants.waveTime); - ActivityTimerStart(self, CoolDownStartTimer, cooldownTime, cooldownTime); + ActivityTimerStart(self, SpawnTickTimer, constants.waveTime); + ActivityTimerStart(self, CoolDownStartTimer, cooldownTime, cooldownTime); - SpawnMobs(self); - ActivityTimerStart(self, PlaySpawnSoundTimer, 3, 3); - } else if (name == PlaySpawnSoundTimer) { - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), spawnSoundGUID); - } - } - } + SpawnMobs(self); + ActivityTimerStart(self, PlaySpawnSoundTimer, 3, 3); + } else if (name == PlaySpawnSoundTimer) { + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), spawnSoundGUID); + } + } + } } void BaseSurvivalServer::ResetStats(LWOOBJID playerID) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { - // Boost all the player stats when loading in - auto* destroyableComponent = player->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetHealth(destroyableComponent->GetMaxHealth()); - destroyableComponent->SetArmor(destroyableComponent->GetMaxArmor()); - destroyableComponent->SetImagination(destroyableComponent->GetMaxImagination()); - } - } + // Boost all the player stats when loading in + auto* destroyableComponent = player->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetHealth(destroyableComponent->GetMaxHealth()); + destroyableComponent->SetArmor(destroyableComponent->GetMaxArmor()); + destroyableComponent->SetImagination(destroyableComponent->GetMaxImagination()); + } + } } void BaseSurvivalServer::PlayerConfirmed(Entity* self) { - std::vector confirmedPlayers {}; + std::vector confirmedPlayers{}; - for (const auto& playerID : state.players) { - auto pass = false; - for (const auto& waitingPlayerID : state.waitingPlayers) { - if (waitingPlayerID == playerID) - pass = true; - } + for (const auto& playerID : state.players) { + auto pass = false; + for (const auto& waitingPlayerID : state.waitingPlayers) { + if (waitingPlayerID == playerID) + pass = true; + } - if (!pass) - confirmedPlayers.push_back(playerID); - } + if (!pass) + confirmedPlayers.push_back(playerID); + } - auto playerIndex = 1; - for (const auto& playerID : confirmedPlayers) { - self->SetNetworkVar(PlayerConfirmVariable + GeneralUtils::to_u16string(playerIndex), std::to_string(playerID)); - playerIndex++; - } + auto playerIndex = 1; + for (const auto& playerID : confirmedPlayers) { + self->SetNetworkVar(PlayerConfirmVariable + GeneralUtils::to_u16string(playerIndex), std::to_string(playerID)); + playerIndex++; + } } -void BaseSurvivalServer::PlayerAccepted(Entity *self, LWOOBJID playerID) { - const auto& iter = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), playerID); +void BaseSurvivalServer::PlayerAccepted(Entity* self, LWOOBJID playerID) { + const auto& iter = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), playerID); - if (iter == state.waitingPlayers.end()) { - return; - } + if (iter == state.waitingPlayers.end()) { + return; + } - state.waitingPlayers.erase(iter); + state.waitingPlayers.erase(iter); - if (state.waitingPlayers.empty() && state.players.size() >= self->GetNetworkVar(NumberOfPlayersVariable)) { - ActivityTimerStopAllTimers(self); - ActivityTimerStart(self, AllAcceptedDelayTimer, 1, constants.startDelay); - } else if (!self->GetVar(AcceptedDelayStartedVariable)) { - self->SetVar(AcceptedDelayStartedVariable, true); - ActivityTimerStart(self, AcceptedDelayTimer, 1, constants.acceptedDelay); - } + if (state.waitingPlayers.empty() && state.players.size() >= self->GetNetworkVar(NumberOfPlayersVariable)) { + ActivityTimerStopAllTimers(self); + ActivityTimerStart(self, AllAcceptedDelayTimer, 1, constants.startDelay); + } else if (!self->GetVar(AcceptedDelayStartedVariable)) { + self->SetVar(AcceptedDelayStartedVariable, true); + ActivityTimerStart(self, AcceptedDelayTimer, 1, constants.acceptedDelay); + } } -void BaseSurvivalServer::StartWaves(Entity *self) { - GameMessages::SendActivityStart(self->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); +void BaseSurvivalServer::StartWaves(Entity* self) { + GameMessages::SendActivityStart(self->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - self->SetVar(PlayersReadyVariable, true); - self->SetVar(BaseMobSetIndexVariable, 0); - self->SetVar(RandMobSetIndexVariable, 0); - self->SetVar(AcceptedDelayStartedVariable, false); + self->SetVar(PlayersReadyVariable, true); + self->SetVar(BaseMobSetIndexVariable, 0); + self->SetVar(RandMobSetIndexVariable, 0); + self->SetVar(AcceptedDelayStartedVariable, false); - state.waitingPlayers.clear(); + state.waitingPlayers.clear(); - for (const auto& playerID : state.players) { - const auto player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - state.waitingPlayers.push_back(playerID); - UpdatePlayer(self, playerID); - GetLeaderboardData(self, playerID, GetActivityID(self), 50); - ResetStats(playerID); + for (const auto& playerID : state.players) { + const auto player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + state.waitingPlayers.push_back(playerID); + UpdatePlayer(self, playerID); + GetLeaderboardData(self, playerID, GetActivityID(self), 50); + ResetStats(playerID); - if (!self->GetVar(FirstTimeDoneVariable)) { - TakeActivityCost(self, playerID); - } + if (!self->GetVar(FirstTimeDoneVariable)) { + TakeActivityCost(self, playerID); + } - GameMessages::SendPlayerSetCameraCyclingMode(playerID, player->GetSystemAddress()); - } - } + GameMessages::SendPlayerSetCameraCyclingMode(playerID, player->GetSystemAddress()); + } + } - self->SetVar(FirstTimeDoneVariable, true); - self->SetVar(MissionTypeVariable, state.players.size() == 1 ? "survival_time_solo" : "survival_time_team"); + self->SetVar(FirstTimeDoneVariable, true); + self->SetVar(MissionTypeVariable, state.players.size() == 1 ? "survival_time_solo" : "survival_time_team"); - ActivateSpawnerNetwork(spawnerNetworks.smashNetworks); - self->SetNetworkVar(WavesStartedVariable, true); - self->SetNetworkVar(StartWaveMessageVariable, "Start!"); + ActivateSpawnerNetwork(spawnerNetworks.smashNetworks); + self->SetNetworkVar(WavesStartedVariable, true); + self->SetNetworkVar(StartWaveMessageVariable, "Start!"); } bool BaseSurvivalServer::CheckAllPlayersDead() { - auto deadPlayers = 0; + auto deadPlayers = 0; - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr || player->GetIsDead()) { - deadPlayers++; - } - } + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr || player->GetIsDead()) { + deadPlayers++; + } + } - return deadPlayers >= state.players.size(); + return deadPlayers >= state.players.size(); } void BaseSurvivalServer::SetPlayerSpawnPoints() { - auto spawnerIndex = 1; - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - auto possibleSpawners = EntityManager::Instance()->GetEntitiesInGroup("P" + std::to_string(spawnerIndex) + "_Spawn"); - if (!possibleSpawners.empty()) { - auto* spawner = possibleSpawners.at(0); - GameMessages::SendTeleport(playerID, spawner->GetPosition(), spawner->GetRotation(), player->GetSystemAddress(), true); - } - } + auto spawnerIndex = 1; + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + auto possibleSpawners = EntityManager::Instance()->GetEntitiesInGroup("P" + std::to_string(spawnerIndex) + "_Spawn"); + if (!possibleSpawners.empty()) { + auto* spawner = possibleSpawners.at(0); + GameMessages::SendTeleport(playerID, spawner->GetPosition(), spawner->GetRotation(), player->GetSystemAddress(), true); + } + } - spawnerIndex++; - } + spawnerIndex++; + } } -void BaseSurvivalServer::GameOver(Entity *self) { - if (!CheckAllPlayersDead()) - return; +void BaseSurvivalServer::GameOver(Entity* self) { + if (!CheckAllPlayersDead()) + return; - ActivityTimerStopAllTimers(self); + ActivityTimerStopAllTimers(self); - // Reset all the spawners - SpawnerReset(spawnerNetworks.baseNetworks); - SpawnerReset(spawnerNetworks.randomNetworks); - SpawnerReset(spawnerNetworks.rewardNetworks); + // Reset all the spawners + SpawnerReset(spawnerNetworks.baseNetworks); + SpawnerReset(spawnerNetworks.randomNetworks); + SpawnerReset(spawnerNetworks.rewardNetworks); - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - continue; + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + continue; - const auto score = GetActivityValue(self, playerID, 0); - const auto time = GetActivityValue(self, playerID, 1); + const auto score = GetActivityValue(self, playerID, 0); + const auto time = GetActivityValue(self, playerID, 1); - GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Update_ScoreBoard", time, 0, - playerID, std::to_string(score), UNASSIGNED_SYSTEM_ADDRESS); - player->Resurrect(); + GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Update_ScoreBoard", time, 0, + playerID, std::to_string(score), UNASSIGNED_SYSTEM_ADDRESS); + player->Resurrect(); - // Update all mission progression - auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, time, self->GetObjectID(), - self->GetVar(MissionTypeVariable)); + // Update all mission progression + auto* missionComponent = player->GetComponent(); + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, time, self->GetObjectID(), + self->GetVar(MissionTypeVariable)); - for (const auto& survivalMission : missionsToUpdate) { - auto* mission = missionComponent->GetMission(survivalMission.first); - if (mission != nullptr && (uint32_t) time >= survivalMission.second - && (mission->GetMissionState() == MissionState::MISSION_STATE_ACTIVE - || mission->GetMissionState() == MissionState::MISSION_STATE_COMPLETE_ACTIVE)) { + for (const auto& survivalMission : missionsToUpdate) { + auto* mission = missionComponent->GetMission(survivalMission.first); + if (mission != nullptr && (uint32_t)time >= survivalMission.second + && (mission->GetMissionState() == MissionState::MISSION_STATE_ACTIVE + || mission->GetMissionState() == MissionState::MISSION_STATE_COMPLETE_ACTIVE)) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } - } - } + mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } + } + } - StopActivity(self, playerID, score, time); - } + StopActivity(self, playerID, score, time); + } - state.waveNumber = 1; - state.rewardTick = 1; - state.totalSpawned = 0; + state.waveNumber = 1; + state.rewardTick = 1; + state.totalSpawned = 0; - self->SetNetworkVar(WavesStartedVariable, false); + self->SetNetworkVar(WavesStartedVariable, false); - if (constants.useMobLots) { - constants.lotPhase = 0; - UpdateMobLots(spawnerNetworks.baseNetworks); - UpdateMobLots(spawnerNetworks.randomNetworks); - } + if (constants.useMobLots) { + constants.lotPhase = 0; + UpdateMobLots(spawnerNetworks.baseNetworks); + UpdateMobLots(spawnerNetworks.randomNetworks); + } - SetPlayerSpawnPoints(); + SetPlayerSpawnPoints(); } void BaseSurvivalServer::SpawnerReset(SpawnerNetworkCollection& spawnerNetworkCollection, bool hardReset) { - auto totalSpawned = 0; + auto totalSpawned = 0; - for (auto& spawner : spawnerNetworkCollection.networks) { - for (auto& spawnerName : spawner.names) { - auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName + spawner.number); - if (!spawners.empty()) { - auto* spawnerObject = spawners.at(0); + for (auto& spawner : spawnerNetworkCollection.networks) { + for (auto& spawnerName : spawner.names) { + auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName + spawner.number); + if (!spawners.empty()) { + auto* spawnerObject = spawners.at(0); - auto amountSpawned = spawnerObject->GetAmountSpawned(); - totalSpawned += amountSpawned; + auto amountSpawned = spawnerObject->GetAmountSpawned(); + totalSpawned += amountSpawned; - spawner.isActive = false; - if (hardReset) { - spawnerObject->Reset(); - } else { - spawnerObject->SoftReset(); - } + spawner.isActive = false; + if (hardReset) { + spawnerObject->Reset(); + } else { + spawnerObject->SoftReset(); + } - spawnerObject->Deactivate(); - } - } - } + spawnerObject->Deactivate(); + } + } + } - state.totalSpawned = std::max((uint32_t) totalSpawned, state.totalSpawned); + state.totalSpawned = std::max((uint32_t)totalSpawned, state.totalSpawned); } void BaseSurvivalServer::SpawnerUpdate(Entity* self, SpawnerNetworkCollection& spawnerNetworkCollection, uint32_t amount) { - if (spawnerNetworkCollection.networks.empty()) - return; + if (spawnerNetworkCollection.networks.empty()) + return; - // If we want to spawn something specific now - if (amount != 0) { - auto spawnerNetwork = spawnerNetworkCollection.networks.at(0); - auto possibleSpawners = dZoneManager::Instance()->GetSpawnersByName(spawnerNetwork.names.at(0) + spawnerNetwork.number); - if (!possibleSpawners.empty()) { - SpawnNow(possibleSpawners.at(0), amount); - return; - } - } + // If we want to spawn something specific now + if (amount != 0) { + auto spawnerNetwork = spawnerNetworkCollection.networks.at(0); + auto possibleSpawners = dZoneManager::Instance()->GetSpawnersByName(spawnerNetwork.names.at(0) + spawnerNetwork.number); + if (!possibleSpawners.empty()) { + SpawnNow(possibleSpawners.at(0), amount); + return; + } + } - auto setNumber = self->GetVar(GeneralUtils::ASCIIToUTF16(spawnerNetworkCollection.mobSetName + "Num")); - auto newSet = GetRandomMobSet(spawnerNetworkCollection, setNumber); + auto setNumber = self->GetVar(GeneralUtils::ASCIIToUTF16(spawnerNetworkCollection.mobSetName + "Num")); + auto newSet = GetRandomMobSet(spawnerNetworkCollection, setNumber); - if (!newSet.empty()) { - auto spawnerNetwork = GetRandomSpawner(spawnerNetworkCollection); - for (auto i = 0; i < spawnerNetwork.names.size(); i++) { - const auto& name = spawnerNetwork.names.at(i); - const auto& toSpawn = newSet.at(i); + if (!newSet.empty()) { + auto spawnerNetwork = GetRandomSpawner(spawnerNetworkCollection); + for (auto i = 0; i < spawnerNetwork.names.size(); i++) { + const auto& name = spawnerNetwork.names.at(i); + const auto& toSpawn = newSet.at(i); - auto possibleSpawners = dZoneManager::Instance()->GetSpawnersByName(name + spawnerNetwork.number); - if (!possibleSpawners.empty()) { - SpawnNow(possibleSpawners.front(), toSpawn); - } - } - } + auto possibleSpawners = dZoneManager::Instance()->GetSpawnersByName(name + spawnerNetwork.number); + if (!possibleSpawners.empty()) { + SpawnNow(possibleSpawners.front(), toSpawn); + } + } + } } -void BaseSurvivalServer::SpawnNow(Spawner *spawner, uint32_t amount) { - if (spawner != nullptr) { - if (!spawner->m_Active) { - spawner->m_Info.amountMaintained = amount; - spawner->Activate(); - } else { - spawner->m_Info.amountMaintained = amount; - } - } +void BaseSurvivalServer::SpawnNow(Spawner* spawner, uint32_t amount) { + if (spawner != nullptr) { + if (!spawner->m_Active) { + spawner->m_Info.amountMaintained = amount; + spawner->Activate(); + } else { + spawner->m_Info.amountMaintained = amount; + } + } } std::vector BaseSurvivalServer::GetRandomMobSet(SpawnerNetworkCollection& spawnerNetworkCollection, - uint32_t setNumber) { + uint32_t setNumber) { - if (mobSets.sets.find(spawnerNetworkCollection.mobSetName) != mobSets.sets.end()) { - auto mobSet = mobSets.sets.at(spawnerNetworkCollection.mobSetName); - if (setNumber < mobSet.size()) { - return mobSet.at(setNumber).at(rand() % mobSet.at(setNumber).size()); - } - } + if (mobSets.sets.find(spawnerNetworkCollection.mobSetName) != mobSets.sets.end()) { + auto mobSet = mobSets.sets.at(spawnerNetworkCollection.mobSetName); + if (setNumber < mobSet.size()) { + return mobSet.at(setNumber).at(rand() % mobSet.at(setNumber).size()); + } + } - return {}; + return {}; } SpawnerNetwork BaseSurvivalServer::GetRandomSpawner(SpawnerNetworkCollection& spawnerNetworkCollection) { - std::vector validSpawners {}; - for (const auto& spawner : spawnerNetworkCollection.networks) { - if (!spawner.isLocked) - validSpawners.push_back(spawner); - } + std::vector validSpawners{}; + for (const auto& spawner : spawnerNetworkCollection.networks) { + if (!spawner.isLocked) + validSpawners.push_back(spawner); + } - if (!validSpawners.empty()) { - auto spawner = validSpawners.at(rand() % validSpawners.size()); - spawner.isActive = true; - return spawner; - } + if (!validSpawners.empty()) { + auto spawner = validSpawners.at(rand() % validSpawners.size()); + spawner.isActive = true; + return spawner; + } - return {}; + return {}; } void BaseSurvivalServer::ActivateSpawnerNetwork(SpawnerNetworkCollection& spawnerNetworkCollection) { - for (auto& spawner : spawnerNetworkCollection.networks) { - for (const auto& spawnerName : spawner.names) { - auto possibleSpawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName + spawner.number); - if (!possibleSpawners.empty()) { - auto* spawnerObject = possibleSpawners.at(0); - spawnerObject->Activate(); - spawnerObject->Reset(); - } - } - } + for (auto& spawner : spawnerNetworkCollection.networks) { + for (const auto& spawnerName : spawner.names) { + auto possibleSpawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName + spawner.number); + if (!possibleSpawners.empty()) { + auto* spawnerObject = possibleSpawners.at(0); + spawnerObject->Activate(); + spawnerObject->Reset(); + } + } + } } void BaseSurvivalServer::UpdateMobLots(SpawnerNetworkCollection& spawnerNetworkCollection) { - for (auto& spawner : spawnerNetworkCollection.networks) { - for (auto& spawnerName : spawner.names) { - if (!spawnerName.empty()) { - auto spawnerObjects = dZoneManager::Instance()->GetSpawnersByName(spawnerName + spawner.number); - if (!spawnerObjects.empty()) { - auto splitName = GeneralUtils::SplitString(spawnerName, '_'); - auto cleanName = splitName.size() > 1 ? splitName.at(1) : splitName.at(0); + for (auto& spawner : spawnerNetworkCollection.networks) { + for (auto& spawnerName : spawner.names) { + if (!spawnerName.empty()) { + auto spawnerObjects = dZoneManager::Instance()->GetSpawnersByName(spawnerName + spawner.number); + if (!spawnerObjects.empty()) { + auto splitName = GeneralUtils::SplitString(spawnerName, '_'); + auto cleanName = splitName.size() > 1 ? splitName.at(1) : splitName.at(0); - if (!cleanName.empty()) { - auto spawnerObject = spawnerObjects.at(0); - spawnerObject->SetSpawnLot(mobSets.mobLots.at(cleanName).at(constants.lotPhase)); - } - } - } - } - } + if (!cleanName.empty()) { + auto spawnerObject = spawnerObjects.at(0); + spawnerObject->SetSpawnLot(mobSets.mobLots.at(cleanName).at(constants.lotPhase)); + } + } + } + } + } } -void BaseSurvivalServer::SpawnMobs(Entity *self) { - if (!self->GetNetworkVar(WavesStartedVariable)) - return; +void BaseSurvivalServer::SpawnMobs(Entity* self) { + if (!self->GetNetworkVar(WavesStartedVariable)) + return; - state.waveNumber++; - auto spawnNumber = state.waveNumber > constants.rewardInterval ? state.waveNumber - state.rewardTick - 1 : state.waveNumber; + state.waveNumber++; + auto spawnNumber = state.waveNumber > constants.rewardInterval ? state.waveNumber - state.rewardTick - 1 : state.waveNumber; - for (const auto& tier : constants.baseMobsStartTier) { - if (tier == spawnNumber) - self->SetVar(BaseMobSetIndexVariable, (self->GetVar(BaseMobSetIndexVariable) + 1) - % (constants.baseMobsStartTier.size() - 1)); - } + for (const auto& tier : constants.baseMobsStartTier) { + if (tier == spawnNumber) + self->SetVar(BaseMobSetIndexVariable, (self->GetVar(BaseMobSetIndexVariable) + 1) + % (constants.baseMobsStartTier.size() - 1)); + } - for (const auto& tier : constants.randMobsStartTier) { - if (tier == spawnNumber) - self->SetVar(RandMobSetIndexVariable, (self->GetVar(RandMobSetIndexVariable) + 1) - % (constants.randMobsStartTier.size() - 1)); - } + for (const auto& tier : constants.randMobsStartTier) { + if (tier == spawnNumber) + self->SetVar(RandMobSetIndexVariable, (self->GetVar(RandMobSetIndexVariable) + 1) + % (constants.randMobsStartTier.size() - 1)); + } - if (state.waveNumber == constants.unlockNetwork3) - spawnerNetworks.randomNetworks.networks.at(2).isLocked = false; + if (state.waveNumber == constants.unlockNetwork3) + spawnerNetworks.randomNetworks.networks.at(2).isLocked = false; - SpawnerReset(spawnerNetworks.baseNetworks, false); - SpawnerReset(spawnerNetworks.randomNetworks, false); - SpawnerUpdate(self, spawnerNetworks.baseNetworks); + SpawnerReset(spawnerNetworks.baseNetworks, false); + SpawnerReset(spawnerNetworks.randomNetworks, false); + SpawnerUpdate(self, spawnerNetworks.baseNetworks); - if (spawnNumber >= constants.mobSet2Wave) { - if (spawnNumber == constants.mobSet2Wave) - self->SetNetworkVar(SpawnMobVariable, "2"); - SpawnerUpdate(self, spawnerNetworks.randomNetworks); - } + if (spawnNumber >= constants.mobSet2Wave) { + if (spawnNumber == constants.mobSet2Wave) + self->SetNetworkVar(SpawnMobVariable, "2"); + SpawnerUpdate(self, spawnerNetworks.randomNetworks); + } - if (spawnNumber >= constants.mobSet3Wave) { - if (spawnNumber == constants.mobSet3Wave) - self->SetNetworkVar(SpawnMobVariable, "3"); - SpawnerUpdate(self, spawnerNetworks.randomNetworks); - } + if (spawnNumber >= constants.mobSet3Wave) { + if (spawnNumber == constants.mobSet3Wave) + self->SetNetworkVar(SpawnMobVariable, "3"); + SpawnerUpdate(self, spawnerNetworks.randomNetworks); + } - // If we reached the end of the spawn phase we increase the lost to make it more difficult - if (constants.useMobLots && constants.lotPhase < (mobSets.mobLots.begin()->second.size() - 1) - && spawnNumber >= constants.baseMobsStartTier.back()) { - state.waveNumber = 1; - constants.lotPhase++; + // If we reached the end of the spawn phase we increase the lost to make it more difficult + if (constants.useMobLots && constants.lotPhase < (mobSets.mobLots.begin()->second.size() - 1) + && spawnNumber >= constants.baseMobsStartTier.back()) { + state.waveNumber = 1; + constants.lotPhase++; - UpdateMobLots(spawnerNetworks.baseNetworks); - UpdateMobLots(spawnerNetworks.randomNetworks); - } + UpdateMobLots(spawnerNetworks.baseNetworks); + UpdateMobLots(spawnerNetworks.randomNetworks); + } } diff --git a/dScripts/BaseSurvivalServer.h b/dScripts/BaseSurvivalServer.h index c85f1bbf..a7c9a95a 100644 --- a/dScripts/BaseSurvivalServer.h +++ b/dScripts/BaseSurvivalServer.h @@ -5,149 +5,152 @@ * State for each active game */ struct GameState { - std::vector players {}; - std::vector waitingPlayers {}; - uint32_t totalSpawned = 0; - uint32_t rewardTick = 0; - uint32_t waveNumber = 1; + std::vector players{}; + std::vector waitingPlayers{}; + uint32_t totalSpawned = 0; + uint32_t rewardTick = 0; + uint32_t waveNumber = 1; }; /** * Constants that have to be set for each game */ struct Constants { - uint32_t acceptedDelay = 0; - uint32_t startDelay = 0; - uint32_t waveTime = 0; - uint32_t rewardInterval = 0; - uint32_t coolDownTime = 0; - uint32_t mobSet2Wave = 0; - uint32_t mobSet3Wave = 0; - uint32_t unlockNetwork3 = 0; - uint32_t lotPhase = 0; - bool useMobLots = false; - std::vector baseMobsStartTier {}; - std::vector randMobsStartTier {}; + uint32_t acceptedDelay = 0; + uint32_t startDelay = 0; + uint32_t waveTime = 0; + uint32_t rewardInterval = 0; + uint32_t coolDownTime = 0; + uint32_t mobSet2Wave = 0; + uint32_t mobSet3Wave = 0; + uint32_t unlockNetwork3 = 0; + uint32_t lotPhase = 0; + bool useMobLots = false; + std::vector baseMobsStartTier{}; + std::vector randMobsStartTier{}; }; /** * The lots of the mobs to spawn along with amounts to spawn for each wave */ struct MobSets { - std::map> mobLots {}; - std::map>>> sets {}; + std::map> mobLots{}; + std::map>>> sets{}; }; struct SpawnerNetwork { - std::vector names {}; - std::string number; - bool isLocked = false; - bool isActive = false; + std::vector names{}; + std::string number; + bool isLocked = false; + bool isActive = false; }; struct SpawnerNetworkCollection { - std::string mobSetName; - std::vector networks {}; + std::string mobSetName; + std::vector networks{}; }; struct SpawnerNetworks { - SpawnerNetworkCollection baseNetworks {}; - SpawnerNetworkCollection randomNetworks {}; - SpawnerNetworkCollection rewardNetworks {}; - SpawnerNetworkCollection smashNetworks {}; + SpawnerNetworkCollection baseNetworks{}; + SpawnerNetworkCollection randomNetworks{}; + SpawnerNetworkCollection rewardNetworks{}; + SpawnerNetworkCollection smashNetworks{}; }; class BaseSurvivalServer : public ActivityManager { public: - void OnStartup(Entity* self) override { SetGameVariables(self); BaseStartup(self); }; - void OnPlayerLoaded(Entity* self, Entity* player) override { BasePlayerLoaded(self, player); }; - void OnPlayerExit(Entity* self, Entity* player) override { BasePlayerExit(self, player); }; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override { BaseFireEvent(self, sender, args, param1, param2, param3); }; - void OnPlayerDied(Entity* self, Entity* player) override { BasePlayerDied(self, player); }; - void OnPlayerResurrected(Entity* self, Entity* player) override { BasePlayerResurrected(self, player); }; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, - const std::u16string& userData) override - { BaseMessageBoxResponse(self, sender, button, identifier, userData); }; + void OnStartup(Entity* self) override { SetGameVariables(self); BaseStartup(self); }; + void OnPlayerLoaded(Entity* self, Entity* player) override { BasePlayerLoaded(self, player); }; + void OnPlayerExit(Entity* self, Entity* player) override { BasePlayerExit(self, player); }; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override { + BaseFireEvent(self, sender, args, param1, param2, param3); + }; + void OnPlayerDied(Entity* self, Entity* player) override { BasePlayerDied(self, player); }; + void OnPlayerResurrected(Entity* self, Entity* player) override { BasePlayerResurrected(self, player); }; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, + const std::u16string& userData) override { + BaseMessageBoxResponse(self, sender, button, identifier, userData); + }; - void BasePlayerLoaded(Entity* self, Entity* player); + void BasePlayerLoaded(Entity* self, Entity* player); void BaseStartup(Entity* self); void BasePlayerExit(Entity* self, Entity* player); - void BaseFireEvent(Entity *self, Entity *sender, const std::string& args, int32_t param1, int32_t param2, - int32_t param3); + void BaseFireEvent(Entity* self, Entity* sender, const std::string& args, int32_t param1, int32_t param2, + int32_t param3); void BasePlayerDied(Entity* self, Entity* player); void BasePlayerResurrected(Entity* self, Entity* player); void BaseMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData); - void OnActivityTimerDone(Entity *self, const std::string &name) override; - void OnActivityTimerUpdate(Entity *self, const std::string &name, float_t remainingTime, float_t elapsedTime) override; + void OnActivityTimerDone(Entity* self, const std::string& name) override; + void OnActivityTimerUpdate(Entity* self, const std::string& name, float_t remainingTime, float_t elapsedTime) override; protected: - virtual Constants GetConstants() { return Constants(); }; - virtual MobSets GetMobSets() { return MobSets(); }; - virtual SpawnerNetworks GetSpawnerNetworks() { return SpawnerNetworks(); }; - virtual std::map GetMissionsToUpdate() { return {}; }; - GameState state {}; + virtual Constants GetConstants() { return Constants(); }; + virtual MobSets GetMobSets() { return MobSets(); }; + virtual SpawnerNetworks GetSpawnerNetworks() { return SpawnerNetworks(); }; + virtual std::map GetMissionsToUpdate() { return {}; }; + GameState state{}; - // Mob set default names - std::string BaseMobSet = "baseMobSet"; - std::string RandMobSet = "randMobSet"; + // Mob set default names + std::string BaseMobSet = "baseMobSet"; + std::string RandMobSet = "randMobSet"; - // Variable names - std::u16string WavesStartedVariable = u"wavesStarted"; - std::u16string ShowScoreboardVariable = u"Show_ScoreBoard"; - std::u16string ClearScoreboardVariable = u"Clear_Scoreboard"; - std::u16string DefinePlayerToUIVariable = u"Define_Player_To_UI"; - std::u16string UpdateScoreboardPlayersVariable = u"Update_ScoreBoard_Players."; - std::u16string PlayerConfirmVariable = u"PlayerConfirm_ScoreBoard."; - std::u16string PlayersAcceptedVariable = u"playersAccepted"; - std::u16string PlayersReadyVariable = u"playersReady"; - std::u16string BaseMobSetIndexVariable = u"baseMobSetNum"; - std::u16string RandMobSetIndexVariable = u"randMobSetNum"; - std::u16string AcceptedDelayStartedVariable = u"AcceptedDelayStarted"; - std::u16string NumberOfPlayersVariable = u"NumberOfPlayers"; - std::u16string FirstTimeDoneVariable = u"firstTimeDone"; - std::u16string MissionTypeVariable = u"missionType"; - std::u16string StartWaveMessageVariable = u"Start_Wave_Message"; - std::u16string ExitWavesVariable = u"Exit_waves"; - std::u16string UpdateDefaultStartTimerVariable = u"Update_Default_Start_Timer"; - std::u16string UpdateTimerVariable = u"Update_Timer"; - std::u16string IsCooldownVariable = u"isCoolDown"; - std::u16string SpawnMobVariable = u"Spawn_Mob"; + // Variable names + std::u16string WavesStartedVariable = u"wavesStarted"; + std::u16string ShowScoreboardVariable = u"Show_ScoreBoard"; + std::u16string ClearScoreboardVariable = u"Clear_Scoreboard"; + std::u16string DefinePlayerToUIVariable = u"Define_Player_To_UI"; + std::u16string UpdateScoreboardPlayersVariable = u"Update_ScoreBoard_Players."; + std::u16string PlayerConfirmVariable = u"PlayerConfirm_ScoreBoard."; + std::u16string PlayersAcceptedVariable = u"playersAccepted"; + std::u16string PlayersReadyVariable = u"playersReady"; + std::u16string BaseMobSetIndexVariable = u"baseMobSetNum"; + std::u16string RandMobSetIndexVariable = u"randMobSetNum"; + std::u16string AcceptedDelayStartedVariable = u"AcceptedDelayStarted"; + std::u16string NumberOfPlayersVariable = u"NumberOfPlayers"; + std::u16string FirstTimeDoneVariable = u"firstTimeDone"; + std::u16string MissionTypeVariable = u"missionType"; + std::u16string StartWaveMessageVariable = u"Start_Wave_Message"; + std::u16string ExitWavesVariable = u"Exit_waves"; + std::u16string UpdateDefaultStartTimerVariable = u"Update_Default_Start_Timer"; + std::u16string UpdateTimerVariable = u"Update_Timer"; + std::u16string IsCooldownVariable = u"isCoolDown"; + std::u16string SpawnMobVariable = u"Spawn_Mob"; - // Timer names - std::string SpawnTickTimer = "SpawnTick"; - std::string AllAcceptedDelayTimer = "AllAcceptedDelay"; - std::string AcceptedDelayTimer = "AcceptedDelay"; - std::string StartDelayTimer = "StartDelay"; - std::string ClockTickTimer = "ClockTick"; - std::string CoolDownStartTimer = "CoolDownStart"; - std::string CoolDownStopTimer = "CoolDownStop"; - std::string PlaySpawnSoundTimer = "PlaySpawnSound"; + // Timer names + std::string SpawnTickTimer = "SpawnTick"; + std::string AllAcceptedDelayTimer = "AllAcceptedDelay"; + std::string AcceptedDelayTimer = "AcceptedDelay"; + std::string StartDelayTimer = "StartDelay"; + std::string ClockTickTimer = "ClockTick"; + std::string CoolDownStartTimer = "CoolDownStart"; + std::string CoolDownStopTimer = "CoolDownStop"; + std::string PlaySpawnSoundTimer = "PlaySpawnSound"; - std::string spawnSoundGUID = "{ca36045d-89df-4e96-a317-1e152d226b69}"; + std::string spawnSoundGUID = "{ca36045d-89df-4e96-a317-1e152d226b69}"; private: - void SetGameVariables(Entity* self); - static void ResetStats(LWOOBJID player); - void GameOver(Entity* self); + void SetGameVariables(Entity* self); + static void ResetStats(LWOOBJID player); + void GameOver(Entity* self); - void StartWaves(Entity* self); + void StartWaves(Entity* self); static void ActivateSpawnerNetwork(SpawnerNetworkCollection& spawnerNetworkCollection); - void SpawnerReset(SpawnerNetworkCollection& spawnerNetworkCollection, bool hardReset = true); - void SpawnerUpdate(Entity* self, SpawnerNetworkCollection& spawnerNetworkCollection, uint32_t amount = 0); - void SpawnMobs(Entity* self); - static SpawnerNetwork GetRandomSpawner(SpawnerNetworkCollection& spawnerNetworkCollection); - std::vector GetRandomMobSet(SpawnerNetworkCollection& spawnerNetworkCollection, uint32_t setNumber); + void SpawnerReset(SpawnerNetworkCollection& spawnerNetworkCollection, bool hardReset = true); + void SpawnerUpdate(Entity* self, SpawnerNetworkCollection& spawnerNetworkCollection, uint32_t amount = 0); + void SpawnMobs(Entity* self); + static SpawnerNetwork GetRandomSpawner(SpawnerNetworkCollection& spawnerNetworkCollection); + std::vector GetRandomMobSet(SpawnerNetworkCollection& spawnerNetworkCollection, uint32_t setNumber); - static void SpawnNow(Spawner* spawner, uint32_t amount); + static void SpawnNow(Spawner* spawner, uint32_t amount); - bool CheckAllPlayersDead(); - void SetPlayerSpawnPoints(); + bool CheckAllPlayersDead(); + void SetPlayerSpawnPoints(); void UpdateMobLots(SpawnerNetworkCollection& spawnerNetworkCollection); void PlayerConfirmed(Entity* self); void PlayerAccepted(Entity* self, LWOOBJID playerID); - Constants constants {}; - MobSets mobSets {}; - SpawnerNetworks spawnerNetworks {}; - std::map missionsToUpdate {}; + Constants constants{}; + MobSets mobSets{}; + SpawnerNetworks spawnerNetworks{}; + std::map missionsToUpdate{}; }; diff --git a/dScripts/BaseWavesGenericEnemy.cpp b/dScripts/BaseWavesGenericEnemy.cpp index 7158accb..3270e2d8 100644 --- a/dScripts/BaseWavesGenericEnemy.cpp +++ b/dScripts/BaseWavesGenericEnemy.cpp @@ -1,13 +1,13 @@ #include "BaseWavesGenericEnemy.h" #include "dZoneManager.h" -void BaseWavesGenericEnemy::OnStartup(Entity *self) { - self->SetNetworkVar(u"points", GetPoints()); +void BaseWavesGenericEnemy::OnStartup(Entity* self) { + self->SetNetworkVar(u"points", GetPoints()); } -void BaseWavesGenericEnemy::OnDie(Entity *self, Entity *killer) { - auto* zoneControlObject = dZoneManager::Instance()->GetZoneControlObject(); - if (zoneControlObject != nullptr) { - zoneControlObject->OnFireEventServerSide(killer, "Survival_Update", GetPoints()); - } +void BaseWavesGenericEnemy::OnDie(Entity* self, Entity* killer) { + auto* zoneControlObject = dZoneManager::Instance()->GetZoneControlObject(); + if (zoneControlObject != nullptr) { + zoneControlObject->OnFireEventServerSide(killer, "Survival_Update", GetPoints()); + } } diff --git a/dScripts/BaseWavesGenericEnemy.h b/dScripts/BaseWavesGenericEnemy.h index 718f36e1..3c808b4e 100644 --- a/dScripts/BaseWavesGenericEnemy.h +++ b/dScripts/BaseWavesGenericEnemy.h @@ -3,8 +3,8 @@ class BaseWavesGenericEnemy : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - void OnDie(Entity *self, Entity *killer) override; + void OnStartup(Entity* self) override; + void OnDie(Entity* self, Entity* killer) override; protected: - virtual uint32_t GetPoints() { return 0; }; + virtual uint32_t GetPoints() { return 0; }; }; diff --git a/dScripts/BaseWavesServer.cpp b/dScripts/BaseWavesServer.cpp index 2c8a2edd..8c32f984 100644 --- a/dScripts/BaseWavesServer.cpp +++ b/dScripts/BaseWavesServer.cpp @@ -9,582 +9,582 @@ #include "Character.h" // Done -void BaseWavesServer::SetGameVariables(Entity *self) { - this->constants = std::move(GetConstants()); - this->waves = std::move(GetWaves()); - this->missions = std::move(GetWaveMissions()); - this->spawners = std::move(GetSpawnerNames()); +void BaseWavesServer::SetGameVariables(Entity* self) { + this->constants = std::move(GetConstants()); + this->waves = std::move(GetWaves()); + this->missions = std::move(GetWaveMissions()); + this->spawners = std::move(GetSpawnerNames()); } // Done void BaseWavesServer::BasePlayerLoaded(Entity* self, Entity* player) { - GameMessages::SendPlayerSetCameraCyclingMode(player->GetObjectID(), player->GetSystemAddress()); - GameMessages::SendPlayerAllowedRespawn(player->GetObjectID(), true, player->GetSystemAddress()); + GameMessages::SendPlayerSetCameraCyclingMode(player->GetObjectID(), player->GetSystemAddress()); + GameMessages::SendPlayerAllowedRespawn(player->GetObjectID(), true, player->GetSystemAddress()); - state.waitingPlayers.push_back(player->GetObjectID()); - state.players.push_back(player->GetObjectID()); + state.waitingPlayers.push_back(player->GetObjectID()); + state.players.push_back(player->GetObjectID()); - self->SetNetworkVar(NumberOfPlayersVariable, self->GetNetworkVar(NumberOfPlayersVariable) + 1); - self->SetNetworkVar(DefinePlayerToUIVariable, std::to_string(player->GetObjectID()), player->GetSystemAddress()); + self->SetNetworkVar(NumberOfPlayersVariable, self->GetNetworkVar(NumberOfPlayersVariable) + 1); + self->SetNetworkVar(DefinePlayerToUIVariable, std::to_string(player->GetObjectID()), player->GetSystemAddress()); - // Notify the players of all other players - if (!self->GetNetworkVar(WavesStartedVariable)) { - auto counter = 1; - for (const auto& playerID : state.players) { - self->SetNetworkVar(UpdateScoreboardPlayersVariable + GeneralUtils::to_u16string(counter), std::to_string(playerID)); - counter++; - } + // Notify the players of all other players + if (!self->GetNetworkVar(WavesStartedVariable)) { + auto counter = 1; + for (const auto& playerID : state.players) { + self->SetNetworkVar(UpdateScoreboardPlayersVariable + GeneralUtils::to_u16string(counter), std::to_string(playerID)); + counter++; + } - if (!this->constants.introCelebration.empty()) { - self->SetNetworkVar(WatchingIntroVariable, this->constants.introCelebration + "_" - + std::to_string(player->GetObjectID())); - } else { - self->SetNetworkVar(ShowScoreboardVariable, true); - } - } + if (!this->constants.introCelebration.empty()) { + self->SetNetworkVar(WatchingIntroVariable, this->constants.introCelebration + "_" + + std::to_string(player->GetObjectID())); + } else { + self->SetNetworkVar(ShowScoreboardVariable, true); + } + } - SetPlayerSpawnPoints(); + SetPlayerSpawnPoints(); - if (!self->GetNetworkVar(WavesStartedVariable)) { - PlayerConfirmed(self); - } else { - UpdatePlayer(self, player->GetObjectID()); - GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self), 50); - ResetStats(player->GetObjectID()); - } + if (!self->GetNetworkVar(WavesStartedVariable)) { + PlayerConfirmed(self); + } else { + UpdatePlayer(self, player->GetObjectID()); + GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self), 50); + ResetStats(player->GetObjectID()); + } } // Done void BaseWavesServer::BaseStartup(Entity* self) { - self->SetVar(PlayersAcceptedVariable, 0); - self->SetVar(PlayersReadyVariable, false); + self->SetVar(PlayersAcceptedVariable, 0); + self->SetVar(PlayersReadyVariable, false); } // Done void BaseWavesServer::BasePlayerExit(Entity* self, Entity* player) { - auto waitingPlayerToErase = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), player->GetObjectID()); - if (waitingPlayerToErase != state.waitingPlayers.end()) state.waitingPlayers.erase(waitingPlayerToErase); + auto waitingPlayerToErase = std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), player->GetObjectID()); + if (waitingPlayerToErase != state.waitingPlayers.end()) state.waitingPlayers.erase(waitingPlayerToErase); - auto playerToErase = std::find(state.players.begin(), state.players.end(), player->GetObjectID()); - if (playerToErase != state.players.end()) state.players.erase(playerToErase); + auto playerToErase = std::find(state.players.begin(), state.players.end(), player->GetObjectID()); + if (playerToErase != state.players.end()) state.players.erase(playerToErase); - if (!self->GetNetworkVar(WavesStartedVariable)) { - PlayerConfirmed(self); + if (!self->GetNetworkVar(WavesStartedVariable)) { + PlayerConfirmed(self); - if (state.players.empty()) - return; + if (state.players.empty()) + return; - if (state.waitingPlayers.empty()) { - ActivityTimerStopAllTimers(self); - ActivityTimerStart(self, AllAcceptedDelayTimer, 1.0f, constants.startDelay); - } else if (state.players.size() > state.waitingPlayers.size()) { - if (!self->GetVar(AcceptedDelayStartedVariable)) { - self->SetVar(AcceptedDelayStartedVariable, true); - ActivityTimerStart(self, AcceptedDelayTimer, 1.0f, constants.acceptedDelay); - } - } - } else { - UpdatePlayer(self, player->GetObjectID(), true); - if (CheckAllPlayersDead()) { - GameOver(self); - } - } + if (state.waitingPlayers.empty()) { + ActivityTimerStopAllTimers(self); + ActivityTimerStart(self, AllAcceptedDelayTimer, 1.0f, constants.startDelay); + } else if (state.players.size() > state.waitingPlayers.size()) { + if (!self->GetVar(AcceptedDelayStartedVariable)) { + self->SetVar(AcceptedDelayStartedVariable, true); + ActivityTimerStart(self, AcceptedDelayTimer, 1.0f, constants.acceptedDelay); + } + } + } else { + UpdatePlayer(self, player->GetObjectID(), true); + if (CheckAllPlayersDead()) { + GameOver(self); + } + } - SetActivityValue(self, player->GetObjectID(), 1, 0); - SetActivityValue(self, player->GetObjectID(), 2, 0); + SetActivityValue(self, player->GetObjectID(), 1, 0); + SetActivityValue(self, player->GetObjectID(), 2, 0); - self->SetNetworkVar(NumberOfPlayersVariable, - std::min((uint32_t) 0, self->GetNetworkVar(NumberOfPlayersVariable) - 1)); + self->SetNetworkVar(NumberOfPlayersVariable, + std::min((uint32_t)0, self->GetNetworkVar(NumberOfPlayersVariable) - 1)); } // Done void BaseWavesServer::BaseFireEvent(Entity* self, Entity* sender, const std::string& args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "start") { - StartWaves(self); - } else if (args == "Survival_Update") { - const auto senderID = sender != nullptr ? sender->GetObjectID() : LWOOBJID_EMPTY; - if (UpdateSpawnedEnemies(self, senderID, param1)) { - const auto currentTime = GetActivityValue(self, senderID, 1); - const auto currentWave = GetActivityValue(self, senderID, 2); + int32_t param3) { + if (args == "start") { + StartWaves(self); + } else if (args == "Survival_Update") { + const auto senderID = sender != nullptr ? sender->GetObjectID() : LWOOBJID_EMPTY; + if (UpdateSpawnedEnemies(self, senderID, param1)) { + const auto currentTime = GetActivityValue(self, senderID, 1); + const auto currentWave = GetActivityValue(self, senderID, 2); - for (const auto& mission : this->missions) { - if (currentWave == mission.wave && currentTime <= mission.time) { - UpdateMissionForAllPlayers(self, mission.missionID); - } - } - } - } + for (const auto& mission : this->missions) { + if (currentWave == mission.wave && currentTime <= mission.time) { + UpdateMissionForAllPlayers(self, mission.missionID); + } + } + } + } } // Done void BaseWavesServer::BasePlayerDied(Entity* self, Entity* player) { - const auto currentTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); - const auto finalTime = GetActivityValue(self, player->GetObjectID(), 1); - const auto finalWave = GetActivityValue(self, player->GetObjectID(), 2); + const auto currentTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); + const auto finalTime = GetActivityValue(self, player->GetObjectID(), 1); + const auto finalWave = GetActivityValue(self, player->GetObjectID(), 2); - auto paramString = CheckAllPlayersDead() ? "true" : "false"; + auto paramString = CheckAllPlayersDead() ? "true" : "false"; - GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Player_Died", finalTime, finalWave, - player->GetObjectID(), paramString, player->GetSystemAddress()); + GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Player_Died", finalTime, finalWave, + player->GetObjectID(), paramString, player->GetSystemAddress()); - if (!self->GetNetworkVar(WavesStartedVariable)) { - player->Resurrect(); - return; - } + if (!self->GetNetworkVar(WavesStartedVariable)) { + player->Resurrect(); + return; + } - GameOver(self); + GameOver(self); } // Done -void BaseWavesServer::BasePlayerResurrected(Entity *self, Entity *player) { - GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Player_Res", 0, 0, - player->GetObjectID(), "", player->GetSystemAddress()); +void BaseWavesServer::BasePlayerResurrected(Entity* self, Entity* player) { + GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Player_Res", 0, 0, + player->GetObjectID(), "", player->GetSystemAddress()); - if (self->GetNetworkVar(WavesStartedVariable)) - return; + if (self->GetNetworkVar(WavesStartedVariable)) + return; - self->SetNetworkVar(ShowScoreboardVariable, true); - SetPlayerSpawnPoints(player->GetObjectID()); + self->SetNetworkVar(ShowScoreboardVariable, true); + SetPlayerSpawnPoints(player->GetObjectID()); } // Done void BaseWavesServer::BaseMessageBoxResponse(Entity* self, Entity* sender, int32_t button, - const std::u16string &identifier, const std::u16string &userData) { - if (identifier == u"RePlay") { - PlayerAccepted(self, sender->GetObjectID()); - PlayerConfirmed(self); - } else if (identifier == u"Exit_Question" && button == 1) { - ResetStats(sender->GetObjectID()); - self->SetNetworkVar(ExitWavesVariable, std::to_string(sender->GetObjectID())); + const std::u16string& identifier, const std::u16string& userData) { + if (identifier == u"RePlay") { + PlayerAccepted(self, sender->GetObjectID()); + PlayerConfirmed(self); + } else if (identifier == u"Exit_Question" && button == 1) { + ResetStats(sender->GetObjectID()); + self->SetNetworkVar(ExitWavesVariable, std::to_string(sender->GetObjectID())); - if (sender->IsPlayer()) { - auto* character = sender->GetCharacter(); - if (character != nullptr) { - auto* player = dynamic_cast(sender); - player->SendToZone(character->GetLastNonInstanceZoneID()); - } - } - } + if (sender->IsPlayer()) { + auto* character = sender->GetCharacter(); + if (character != nullptr) { + auto* player = dynamic_cast(sender); + player->SendToZone(character->GetLastNonInstanceZoneID()); + } + } + } } // Done -void BaseWavesServer::OnActivityTimerUpdate(Entity *self, const std::string &name, float_t remainingTime, float_t elapsedTime) { - if (name == AcceptedDelayTimer) { - self->SetNetworkVar(UpdateDefaultStartTimerVariable, remainingTime); - } else if (name == ClockTickTimer) { - self->SetNetworkVar(UpdateTimerVariable, elapsedTime); - } else if (name == NextWaveTickTimer || name == TimedWaveTimer || name == GameOverWinTimer) { - self->SetNetworkVar(UpdateCooldownVariable, remainingTime); - } +void BaseWavesServer::OnActivityTimerUpdate(Entity* self, const std::string& name, float_t remainingTime, float_t elapsedTime) { + if (name == AcceptedDelayTimer) { + self->SetNetworkVar(UpdateDefaultStartTimerVariable, remainingTime); + } else if (name == ClockTickTimer) { + self->SetNetworkVar(UpdateTimerVariable, elapsedTime); + } else if (name == NextWaveTickTimer || name == TimedWaveTimer || name == GameOverWinTimer) { + self->SetNetworkVar(UpdateCooldownVariable, remainingTime); + } } // Done -void BaseWavesServer::OnActivityTimerDone(Entity *self, const std::string &name) { - if (name == AcceptedDelayTimer) { - self->SetNetworkVar(UpdateDefaultStartTimerVariable, 0); - ActivityTimerStart(self, AllAcceptedDelayTimer, 1, 1); - } else if (name == AllAcceptedDelayTimer) { - self->SetNetworkVar(ClearScoreboardVariable, true); - ActivityTimerStart(self, StartDelayTimer, 4, 4); - StartWaves(self); - } else if (name == StartDelayTimer) { - ActivityTimerStart(self, ClockTickTimer, 1); - SpawnWave(self); - ActivityTimerStart(self, PlaySpawnSoundTimer, 3, 3); - } else if (name == PlaySpawnSoundTimer) { - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), spawnSoundGUID); - } - } - } else if (name == NextWaveTickTimer) { - self->SetNetworkVar(StartCooldownVariable, false); - SpawnWave(self); - } else if (name == WaveCompleteDelayTimer) { - self->SetNetworkVar(StartCooldownVariable, constants.waveTime); - ActivityTimerStart(self, NextWaveTickTimer, 1, constants.waveTime); - } else if (name == TimedWaveTimer) { - ActivityTimerStart(self, WaveCompleteDelayTimer, constants.waveCompleteDelay, constants.waveCompleteDelay); +void BaseWavesServer::OnActivityTimerDone(Entity* self, const std::string& name) { + if (name == AcceptedDelayTimer) { + self->SetNetworkVar(UpdateDefaultStartTimerVariable, 0); + ActivityTimerStart(self, AllAcceptedDelayTimer, 1, 1); + } else if (name == AllAcceptedDelayTimer) { + self->SetNetworkVar(ClearScoreboardVariable, true); + ActivityTimerStart(self, StartDelayTimer, 4, 4); + StartWaves(self); + } else if (name == StartDelayTimer) { + ActivityTimerStart(self, ClockTickTimer, 1); + SpawnWave(self); + ActivityTimerStart(self, PlaySpawnSoundTimer, 3, 3); + } else if (name == PlaySpawnSoundTimer) { + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), spawnSoundGUID); + } + } + } else if (name == NextWaveTickTimer) { + self->SetNetworkVar(StartCooldownVariable, false); + SpawnWave(self); + } else if (name == WaveCompleteDelayTimer) { + self->SetNetworkVar(StartCooldownVariable, constants.waveTime); + ActivityTimerStart(self, NextWaveTickTimer, 1, constants.waveTime); + } else if (name == TimedWaveTimer) { + ActivityTimerStart(self, WaveCompleteDelayTimer, constants.waveCompleteDelay, constants.waveCompleteDelay); - const auto currentTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); - const auto currentWave = state.waveNumber; + const auto currentTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); + const auto currentWave = state.waveNumber; - self->SetNetworkVar(WaveCompleteVariable, { currentWave, (uint32_t) currentTime }); - } else if (name == GameOverWinTimer) { - GameOver(self, true); - } else if (name == CinematicDoneTimer) { - for (auto* boss : EntityManager::Instance()->GetEntitiesInGroup("boss")) { - boss->OnFireEventServerSide(self, "startAI"); - } - } + self->SetNetworkVar(WaveCompleteVariable, { currentWave, (uint32_t)currentTime }); + } else if (name == GameOverWinTimer) { + GameOver(self, true); + } else if (name == CinematicDoneTimer) { + for (auto* boss : EntityManager::Instance()->GetEntitiesInGroup("boss")) { + boss->OnFireEventServerSide(self, "startAI"); + } + } } // Done void BaseWavesServer::ResetStats(LWOOBJID playerID) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { - // Boost all the player stats when loading in - auto* destroyableComponent = player->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetHealth(destroyableComponent->GetMaxHealth()); - destroyableComponent->SetArmor(destroyableComponent->GetMaxArmor()); - destroyableComponent->SetImagination(destroyableComponent->GetMaxImagination()); - } - } + // Boost all the player stats when loading in + auto* destroyableComponent = player->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetHealth(destroyableComponent->GetMaxHealth()); + destroyableComponent->SetArmor(destroyableComponent->GetMaxArmor()); + destroyableComponent->SetImagination(destroyableComponent->GetMaxImagination()); + } + } } // Done void BaseWavesServer::PlayerConfirmed(Entity* self) { - std::vector confirmedPlayers {}; + std::vector confirmedPlayers{}; - for (const auto& playerID : state.players) { - auto pass = false; - for (const auto& waitingPlayerID : state.waitingPlayers) { - if (waitingPlayerID == playerID) - pass = true; - } + for (const auto& playerID : state.players) { + auto pass = false; + for (const auto& waitingPlayerID : state.waitingPlayers) { + if (waitingPlayerID == playerID) + pass = true; + } - if (!pass) - confirmedPlayers.push_back(playerID); - } + if (!pass) + confirmedPlayers.push_back(playerID); + } - auto playerIndex = 1; - for (const auto& playerID : confirmedPlayers) { - self->SetNetworkVar(PlayerConfirmVariable + GeneralUtils::to_u16string(playerIndex), std::to_string(playerID)); - playerIndex++; - } + auto playerIndex = 1; + for (const auto& playerID : confirmedPlayers) { + self->SetNetworkVar(PlayerConfirmVariable + GeneralUtils::to_u16string(playerIndex), std::to_string(playerID)); + playerIndex++; + } } // Done -void BaseWavesServer::PlayerAccepted(Entity *self, LWOOBJID playerID) { - state.waitingPlayers.erase(std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), playerID)); - if (state.waitingPlayers.empty() && state.players.size() >= self->GetNetworkVar(NumberOfPlayersVariable)) { - ActivityTimerStopAllTimers(self); - ActivityTimerStart(self, AllAcceptedDelayTimer, 1, constants.startDelay); - } else if (!self->GetVar(AcceptedDelayStartedVariable)) { - self->SetVar(AcceptedDelayStartedVariable, true); - ActivityTimerStart(self, AcceptedDelayTimer, 1, constants.acceptedDelay); - } +void BaseWavesServer::PlayerAccepted(Entity* self, LWOOBJID playerID) { + state.waitingPlayers.erase(std::find(state.waitingPlayers.begin(), state.waitingPlayers.end(), playerID)); + if (state.waitingPlayers.empty() && state.players.size() >= self->GetNetworkVar(NumberOfPlayersVariable)) { + ActivityTimerStopAllTimers(self); + ActivityTimerStart(self, AllAcceptedDelayTimer, 1, constants.startDelay); + } else if (!self->GetVar(AcceptedDelayStartedVariable)) { + self->SetVar(AcceptedDelayStartedVariable, true); + ActivityTimerStart(self, AcceptedDelayTimer, 1, constants.acceptedDelay); + } } // Done -void BaseWavesServer::StartWaves(Entity *self) { - GameMessages::SendActivityStart(self->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); +void BaseWavesServer::StartWaves(Entity* self) { + GameMessages::SendActivityStart(self->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - self->SetNetworkVar(WatchingIntroVariable, ""); - self->SetVar(PlayersReadyVariable, true); - self->SetVar(BaseMobSetIndexVariable, 0); - self->SetVar(RandMobSetIndexVariable, 0); - self->SetVar(AcceptedDelayStartedVariable, false); + self->SetNetworkVar(WatchingIntroVariable, ""); + self->SetVar(PlayersReadyVariable, true); + self->SetVar(BaseMobSetIndexVariable, 0); + self->SetVar(RandMobSetIndexVariable, 0); + self->SetVar(AcceptedDelayStartedVariable, false); - state.waitingPlayers.clear(); + state.waitingPlayers.clear(); - for (const auto& playerID : state.players) { - const auto player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - state.waitingPlayers.push_back(playerID); + for (const auto& playerID : state.players) { + const auto player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + state.waitingPlayers.push_back(playerID); - UpdatePlayer(self, playerID); - GetLeaderboardData(self, playerID, GetActivityID(self), 1); - ResetStats(playerID); + UpdatePlayer(self, playerID); + GetLeaderboardData(self, playerID, GetActivityID(self), 1); + ResetStats(playerID); - if (!self->GetVar(FirstTimeDoneVariable)) { - TakeActivityCost(self, playerID); - } - } - } + if (!self->GetVar(FirstTimeDoneVariable)) { + TakeActivityCost(self, playerID); + } + } + } - self->SetVar(FirstTimeDoneVariable, true); - self->SetVar(MissionTypeVariable, state.players.size() == 1 ? "survival_time_solo" : "survival_time_team"); - self->SetNetworkVar(WavesStartedVariable, true); - self->SetNetworkVar(StartWaveMessageVariable, "Start!"); + self->SetVar(FirstTimeDoneVariable, true); + self->SetVar(MissionTypeVariable, state.players.size() == 1 ? "survival_time_solo" : "survival_time_team"); + self->SetNetworkVar(WavesStartedVariable, true); + self->SetNetworkVar(StartWaveMessageVariable, "Start!"); } // Done bool BaseWavesServer::CheckAllPlayersDead() { - auto deadPlayers = 0; + auto deadPlayers = 0; - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr || player->GetIsDead()) { - deadPlayers++; - } - } + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr || player->GetIsDead()) { + deadPlayers++; + } + } - return deadPlayers >= state.players.size(); + return deadPlayers >= state.players.size(); } // Done void BaseWavesServer::SetPlayerSpawnPoints(const LWOOBJID& specificPlayerID) { - auto spawnerIndex = 1; - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr && (specificPlayerID == LWOOBJID_EMPTY || playerID == specificPlayerID)) { - auto possibleSpawners = EntityManager::Instance()->GetEntitiesInGroup("P" + std::to_string(spawnerIndex) + "_Spawn"); - if (!possibleSpawners.empty()) { - auto* spawner = possibleSpawners.at(0); - GameMessages::SendTeleport(playerID, spawner->GetPosition(), spawner->GetRotation(), player->GetSystemAddress(), true); - } - } + auto spawnerIndex = 1; + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr && (specificPlayerID == LWOOBJID_EMPTY || playerID == specificPlayerID)) { + auto possibleSpawners = EntityManager::Instance()->GetEntitiesInGroup("P" + std::to_string(spawnerIndex) + "_Spawn"); + if (!possibleSpawners.empty()) { + auto* spawner = possibleSpawners.at(0); + GameMessages::SendTeleport(playerID, spawner->GetPosition(), spawner->GetRotation(), player->GetSystemAddress(), true); + } + } - spawnerIndex++; - } + spawnerIndex++; + } } // Done -void BaseWavesServer::GameOver(Entity *self, bool won) { - if (!CheckAllPlayersDead() && !won) - return; +void BaseWavesServer::GameOver(Entity* self, bool won) { + if (!CheckAllPlayersDead() && !won) + return; - ActivityTimerStopAllTimers(self); + ActivityTimerStopAllTimers(self); - // Reset all the spawners - state.waveNumber = 0; - state.totalSpawned = 0; - state.currentSpawned = 0; + // Reset all the spawners + state.waveNumber = 0; + state.totalSpawned = 0; + state.currentSpawned = 0; - self->SetNetworkVar(WavesStartedVariable, false); - self->SetNetworkVar(StartCooldownVariable, 0); - SetPlayerSpawnPoints(); - ClearSpawners(); + self->SetNetworkVar(WavesStartedVariable, false); + self->SetNetworkVar(StartCooldownVariable, 0); + SetPlayerSpawnPoints(); + ClearSpawners(); - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - continue; + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + continue; - const auto score = GetActivityValue(self, playerID, 0); - const auto time = GetActivityValue(self, playerID, 1); - const auto wave = GetActivityValue(self, playerID, 2); + const auto score = GetActivityValue(self, playerID, 0); + const auto time = GetActivityValue(self, playerID, 1); + const auto wave = GetActivityValue(self, playerID, 2); - GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Update_ScoreBoard", time, 0, - playerID, std::to_string(wave), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientZoneObject(self->GetObjectID(), u"Update_ScoreBoard", time, 0, + playerID, std::to_string(wave), UNASSIGNED_SYSTEM_ADDRESS); - if (won) { - SetPlayerSpawnPoints(); - self->SetNetworkVar(ShowScoreboardVariable, true); - } else { - player->Resurrect(); - } + if (won) { + SetPlayerSpawnPoints(); + self->SetNetworkVar(ShowScoreboardVariable, true); + } else { + player->Resurrect(); + } - // Update all mission progression - auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, time, self->GetObjectID(), self->GetVar(MissionTypeVariable)); - } + // Update all mission progression + auto* missionComponent = player->GetComponent(); + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, time, self->GetObjectID(), self->GetVar(MissionTypeVariable)); + } - StopActivity(self, playerID, wave, time, score); - } + StopActivity(self, playerID, wave, time, score); + } } // Done -void BaseWavesServer::GameWon(Entity *self) { - ActivityTimerStopAllTimers(self); +void BaseWavesServer::GameWon(Entity* self) { + ActivityTimerStopAllTimers(self); - const auto winDelay = waves.back().winDelay; - ActivityTimerStart(self, GameOverWinTimer, 1, winDelay); - self->SetNetworkVar(StartTimedWaveVariable, { winDelay, state.waveNumber }); + const auto winDelay = waves.back().winDelay; + ActivityTimerStart(self, GameOverWinTimer, 1, winDelay); + self->SetNetworkVar(StartTimedWaveVariable, { winDelay, state.waveNumber }); } // Done void BaseWavesServer::SpawnNow(const std::string& spawnerName, uint32_t amount, LOT spawnLot) { - const auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); - for (auto* spawner : spawners) { - if (spawnLot != LOT_NULL) { - spawner->SetSpawnLot(spawnLot); - } + const auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); + for (auto* spawner : spawners) { + if (spawnLot != LOT_NULL) { + spawner->SetSpawnLot(spawnLot); + } - spawner->m_Info.amountMaintained = amount; - spawner->m_Info.maxToSpawn = amount; + spawner->m_Info.amountMaintained = amount; + spawner->m_Info.maxToSpawn = amount; - spawner->Reset(); - spawner->Activate(); - } + spawner->Reset(); + spawner->Activate(); + } } // Done -void BaseWavesServer::SpawnWave(Entity *self) { - if (!self->GetNetworkVar(WavesStartedVariable)) - return; +void BaseWavesServer::SpawnWave(Entity* self) { + if (!self->GetNetworkVar(WavesStartedVariable)) + return; - // If there's no wave left - if (state.waveNumber >= waves.size()) { - GameOver(self); - return; - } + // If there's no wave left + if (state.waveNumber >= waves.size()) { + GameOver(self); + return; + } - const auto wave = waves.at(state.waveNumber); + const auto wave = waves.at(state.waveNumber); - // Handles meta info to the client about the current round - if (wave.winDelay != (uint32_t) -1) { - self->SetNetworkVar(WonWaveVariable, true); + // Handles meta info to the client about the current round + if (wave.winDelay != (uint32_t)-1) { + self->SetNetworkVar(WonWaveVariable, true); - // Close the game if we don't expect a notification from an other entity to end it - if (!wave.notifyWin) { - GameWon(self); - } + // Close the game if we don't expect a notification from an other entity to end it + if (!wave.notifyWin) { + GameWon(self); + } - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - player->Resurrect(); - } - } - } else { - if (wave.timeLimit != (uint32_t) -1) { - ActivityTimerStart(self, TimedWaveTimer, 1.0f, wave.timeLimit); - self->SetNetworkVar(StartTimedWaveVariable, { wave.timeLimit, state.waveNumber + 1 } ); - } else { - self->SetNetworkVar(NewWaveVariable, state.waveNumber + 1); - } - } + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + player->Resurrect(); + } + } + } else { + if (wave.timeLimit != (uint32_t)-1) { + ActivityTimerStart(self, TimedWaveTimer, 1.0f, wave.timeLimit); + self->SetNetworkVar(StartTimedWaveVariable, { wave.timeLimit, state.waveNumber + 1 }); + } else { + self->SetNetworkVar(NewWaveVariable, state.waveNumber + 1); + } + } - // NOTE: The script does some stuff with events here, although BONS does not have those + // NOTE: The script does some stuff with events here, although BONS does not have those - // Optional cinematics to play - if (!wave.cinematic.empty()) { - ActivityTimerStart(self, CinematicDoneTimer, wave.cinematicLength, wave.cinematicLength); - self->SetNetworkVar(StartCinematicVariable, wave.cinematic); - } + // Optional cinematics to play + if (!wave.cinematic.empty()) { + ActivityTimerStart(self, CinematicDoneTimer, wave.cinematicLength, wave.cinematicLength); + self->SetNetworkVar(StartCinematicVariable, wave.cinematic); + } - // Spawn the enemies - state.currentSpawned = 0; + // Spawn the enemies + state.currentSpawned = 0; - for (const auto& mobDefinition : wave.waveMobs) { - SpawnNow(mobDefinition.spawnerName, mobDefinition.amountToSpawn, mobDefinition.lot); - state.currentSpawned += mobDefinition.amountToSpawn; - } + for (const auto& mobDefinition : wave.waveMobs) { + SpawnNow(mobDefinition.spawnerName, mobDefinition.amountToSpawn, mobDefinition.lot); + state.currentSpawned += mobDefinition.amountToSpawn; + } - state.waveNumber++; - state.totalSpawned += state.currentSpawned; - self->SetNetworkVar(NumRemainingVariable, state.currentSpawned); + state.waveNumber++; + state.totalSpawned += state.currentSpawned; + self->SetNetworkVar(NumRemainingVariable, state.currentSpawned); } // Done bool BaseWavesServer::UpdateSpawnedEnemies(Entity* self, LWOOBJID enemyID, uint32_t score) { - if (!self->GetNetworkVar(WavesStartedVariable)) - return false; + if (!self->GetNetworkVar(WavesStartedVariable)) + return false; - state.currentSpawned--; + state.currentSpawned--; - auto* enemy = EntityManager::Instance()->GetEntity(enemyID); - if (enemy != nullptr && enemy->IsPlayer() && IsPlayerInActivity(self, enemyID)) { - SetActivityValue(self, enemyID, 0, GetActivityValue(self, enemyID, 0) + score); - } + auto* enemy = EntityManager::Instance()->GetEntity(enemyID); + if (enemy != nullptr && enemy->IsPlayer() && IsPlayerInActivity(self, enemyID)) { + SetActivityValue(self, enemyID, 0, GetActivityValue(self, enemyID, 0) + score); + } - if (state.currentSpawned <= 0) { - const auto currentTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); - const auto completedWave = state.waveNumber - 1; + if (state.currentSpawned <= 0) { + const auto currentTime = ActivityTimerGetCurrentTime(self, ClockTickTimer); + const auto completedWave = state.waveNumber - 1; - // When the last enemy is smashed (e.g. in last wave - 1) - if (state.waveNumber >= waves.size() - 1) { + // When the last enemy is smashed (e.g. in last wave - 1) + if (state.waveNumber >= waves.size() - 1) { - // If there's no more follow up waves, (e.g in last wave), end the game. Generally called by some other script - if (state.waveNumber >= waves.size()) { - GameWon(self); - return false; - } + // If there's no more follow up waves, (e.g in last wave), end the game. Generally called by some other script + if (state.waveNumber >= waves.size()) { + GameWon(self); + return false; + } - ActivityTimerStopAllTimers(self); - self->SetNetworkVar(UpdateTimerVariable, currentTime); - } + ActivityTimerStopAllTimers(self); + self->SetNetworkVar(UpdateTimerVariable, currentTime); + } - ActivityTimerStart(self, WaveCompleteDelayTimer, constants.waveCompleteDelay, constants.waveCompleteDelay); + ActivityTimerStart(self, WaveCompleteDelayTimer, constants.waveCompleteDelay, constants.waveCompleteDelay); - const auto waveMission = waves.at(completedWave).missions; - const auto soloWaveMissions = waves.at(completedWave).soloMissions; + const auto waveMission = waves.at(completedWave).missions; + const auto soloWaveMissions = waves.at(completedWave).soloMissions; - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr && !player->GetIsDead()) { - SetActivityValue(self, playerID, 1, currentTime); - SetActivityValue(self, playerID, 2, state.waveNumber); + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr && !player->GetIsDead()) { + SetActivityValue(self, playerID, 1, currentTime); + SetActivityValue(self, playerID, 2, state.waveNumber); - // Update player missions - auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) { - for (const auto& missionID : waveMission) { - // Get the mission state - auto missionState = missionComponent->GetMissionState(missionID); - // For some reason these achievements are not accepted by default, so we accept them here if they arent already. - if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { - missionComponent->AcceptMission(missionID); - missionState = missionComponent->GetMissionState(missionID); - } + // Update player missions + auto* missionComponent = player->GetComponent(); + if (missionComponent != nullptr) { + for (const auto& missionID : waveMission) { + // Get the mission state + auto missionState = missionComponent->GetMissionState(missionID); + // For some reason these achievements are not accepted by default, so we accept them here if they arent already. + if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { + missionComponent->AcceptMission(missionID); + missionState = missionComponent->GetMissionState(missionID); + } - if (missionState != MissionState::MISSION_STATE_COMPLETE) { - auto mission = missionComponent->GetMission(missionID); - if (mission != nullptr) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } - } - } - // Progress solo missions - if (state.players.size() == 1) { - for (const auto& missionID : soloWaveMissions) { - // Get the mission state - auto missionState = missionComponent->GetMissionState(missionID); - // For some reason these achievements are not accepted by default, so we accept them here if they arent already. - if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { - missionComponent->AcceptMission(missionID); - missionState = missionComponent->GetMissionState(missionID); - } + if (missionState != MissionState::MISSION_STATE_COMPLETE) { + auto mission = missionComponent->GetMission(missionID); + if (mission != nullptr) { + mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } + } + } + // Progress solo missions + if (state.players.size() == 1) { + for (const auto& missionID : soloWaveMissions) { + // Get the mission state + auto missionState = missionComponent->GetMissionState(missionID); + // For some reason these achievements are not accepted by default, so we accept them here if they arent already. + if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { + missionComponent->AcceptMission(missionID); + missionState = missionComponent->GetMissionState(missionID); + } - if (missionState != MissionState::MISSION_STATE_COMPLETE) { - auto mission = missionComponent->GetMission(missionID); - if (mission != nullptr) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } - } - } - } - } - } - } + if (missionState != MissionState::MISSION_STATE_COMPLETE) { + auto mission = missionComponent->GetMission(missionID); + if (mission != nullptr) { + mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } + } + } + } + } + } + } - // Might seem odd to send the next wave but the client isn't 0-indexed so it thinks it completed the correct wave - self->SetNetworkVar(WaveCompleteVariable, { state.waveNumber, (uint32_t) currentTime }); - return true; - } + // Might seem odd to send the next wave but the client isn't 0-indexed so it thinks it completed the correct wave + self->SetNetworkVar(WaveCompleteVariable, { state.waveNumber, (uint32_t)currentTime }); + return true; + } - self->SetNetworkVar(NumRemainingVariable, state.currentSpawned); - return false; + self->SetNetworkVar(NumRemainingVariable, state.currentSpawned); + return false; } // Done void BaseWavesServer::UpdateMissionForAllPlayers(Entity* self, uint32_t missionID) { - for (const auto& playerID : state.players) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { - auto* missionComponent = player->GetComponent(); - if (missionComponent == nullptr) return; - // Get the mission state - auto missionState = missionComponent->GetMissionState(missionID); - // For some reason these achievements are not accepted by default, so we accept them here if they arent already. - if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { - missionComponent->AcceptMission(missionID); - missionState = missionComponent->GetMissionState(missionID); - } - if (missionState != MissionState::MISSION_STATE_COMPLETE) { - auto mission = missionComponent->GetMission(missionID); - if (mission != nullptr) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } - } - } - } + for (const auto& playerID : state.players) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { + auto* missionComponent = player->GetComponent(); + if (missionComponent == nullptr) return; + // Get the mission state + auto missionState = missionComponent->GetMissionState(missionID); + // For some reason these achievements are not accepted by default, so we accept them here if they arent already. + if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { + missionComponent->AcceptMission(missionID); + missionState = missionComponent->GetMissionState(missionID); + } + if (missionState != MissionState::MISSION_STATE_COMPLETE) { + auto mission = missionComponent->GetMission(missionID); + if (mission != nullptr) { + mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } + } + } + } } void BaseWavesServer::ClearSpawners() { - for (const auto& spawnerName : spawners) { - const auto spawnerObjects = dZoneManager::Instance()->GetSpawnersByName(spawnerName); + for (const auto& spawnerName : spawners) { + const auto spawnerObjects = dZoneManager::Instance()->GetSpawnersByName(spawnerName); - for (auto* spawnerObject : spawnerObjects) { - spawnerObject->Reset(); - spawnerObject->Deactivate(); - } - } + for (auto* spawnerObject : spawnerObjects) { + spawnerObject->Reset(); + spawnerObject->Deactivate(); + } + } } diff --git a/dScripts/BaseWavesServer.h b/dScripts/BaseWavesServer.h index 3dc90da8..67eaf39d 100644 --- a/dScripts/BaseWavesServer.h +++ b/dScripts/BaseWavesServer.h @@ -5,151 +5,154 @@ * State for each active game */ struct WavesGameState { - std::vector players {}; - std::vector waitingPlayers {}; - uint32_t totalSpawned = 0; - uint32_t currentSpawned = 0; - uint32_t waveNumber = 0; - std::string introCelebration; + std::vector players{}; + std::vector waitingPlayers{}; + uint32_t totalSpawned = 0; + uint32_t currentSpawned = 0; + uint32_t waveNumber = 0; + std::string introCelebration; }; struct MobDefinition { - LOT lot; - uint32_t amountToSpawn; - std::string spawnerName; + LOT lot; + uint32_t amountToSpawn; + std::string spawnerName; }; struct WaveMission { - uint32_t time; - uint32_t wave; - uint32_t missionID; + uint32_t time; + uint32_t wave; + uint32_t missionID; }; struct Wave { - std::vector waveMobs {}; - std::vector soloMissions {}; - std::vector missions {}; - std::string cinematic; - float_t cinematicLength; - uint32_t timeLimit = UINT32_MAX; - bool notifyWin = false; - uint32_t winDelay = UINT32_MAX; + std::vector waveMobs{}; + std::vector soloMissions{}; + std::vector missions{}; + std::string cinematic; + float_t cinematicLength; + uint32_t timeLimit = UINT32_MAX; + bool notifyWin = false; + uint32_t winDelay = UINT32_MAX; }; /** * WaveConstants that have to be set for each game */ struct WaveConstants { - uint32_t acceptedDelay = 0; - uint32_t startDelay = 0; - uint32_t waveTime = 0; - uint32_t waveCompleteDelay = 0; - std::string eventGroup; - std::string introCelebration; + uint32_t acceptedDelay = 0; + uint32_t startDelay = 0; + uint32_t waveTime = 0; + uint32_t waveCompleteDelay = 0; + std::string eventGroup; + std::string introCelebration; }; class BaseWavesServer : public ActivityManager { public: - void OnStartup(Entity* self) override { SetGameVariables(self); BaseStartup(self); }; - void OnPlayerLoaded(Entity* self, Entity* player) override { BasePlayerLoaded(self, player); }; - void OnPlayerExit(Entity* self, Entity* player) override { BasePlayerExit(self, player); }; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override { BaseFireEvent(self, sender, args, param1, param2, param3); }; - void OnPlayerDied(Entity* self, Entity* player) override { BasePlayerDied(self, player); }; - void OnPlayerResurrected(Entity* self, Entity* player) override { BasePlayerResurrected(self, player); }; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, - const std::u16string& userData) override - { BaseMessageBoxResponse(self, sender, button, identifier, userData); }; + void OnStartup(Entity* self) override { SetGameVariables(self); BaseStartup(self); }; + void OnPlayerLoaded(Entity* self, Entity* player) override { BasePlayerLoaded(self, player); }; + void OnPlayerExit(Entity* self, Entity* player) override { BasePlayerExit(self, player); }; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override { + BaseFireEvent(self, sender, args, param1, param2, param3); + }; + void OnPlayerDied(Entity* self, Entity* player) override { BasePlayerDied(self, player); }; + void OnPlayerResurrected(Entity* self, Entity* player) override { BasePlayerResurrected(self, player); }; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, + const std::u16string& userData) override { + BaseMessageBoxResponse(self, sender, button, identifier, userData); + }; - void BasePlayerLoaded(Entity* self, Entity* player); - void BaseStartup(Entity* self); - void BasePlayerExit(Entity* self, Entity* player); - void BaseFireEvent(Entity *self, Entity *sender, const std::string& args, int32_t param1, int32_t param2, - int32_t param3); - void BasePlayerDied(Entity* self, Entity* player); - void BasePlayerResurrected(Entity* self, Entity* player); - void BaseMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData); + void BasePlayerLoaded(Entity* self, Entity* player); + void BaseStartup(Entity* self); + void BasePlayerExit(Entity* self, Entity* player); + void BaseFireEvent(Entity* self, Entity* sender, const std::string& args, int32_t param1, int32_t param2, + int32_t param3); + void BasePlayerDied(Entity* self, Entity* player); + void BasePlayerResurrected(Entity* self, Entity* player); + void BaseMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData); - void OnActivityTimerDone(Entity *self, const std::string &name) override; - void OnActivityTimerUpdate(Entity *self, const std::string &name, float_t remainingTime, float_t elapsedTime) override; + void OnActivityTimerDone(Entity* self, const std::string& name) override; + void OnActivityTimerUpdate(Entity* self, const std::string& name, float_t remainingTime, float_t elapsedTime) override; protected: - virtual WaveConstants GetConstants() { return WaveConstants(); }; - virtual std::vector GetWaves() { return {}; }; - virtual std::vector GetWaveMissions() { return {}; }; - virtual std::vector GetSpawnerNames() { return {}; } - WavesGameState state {}; + virtual WaveConstants GetConstants() { return WaveConstants(); }; + virtual std::vector GetWaves() { return {}; }; + virtual std::vector GetWaveMissions() { return {}; }; + virtual std::vector GetSpawnerNames() { return {}; } + WavesGameState state{}; - // Mob set default names - std::string BaseMobSet = "baseMobSet"; - std::string RandMobSet = "randMobSet"; + // Mob set default names + std::string BaseMobSet = "baseMobSet"; + std::string RandMobSet = "randMobSet"; - // Variable names - std::u16string WavesStartedVariable = u"wavesStarted"; - std::u16string ShowScoreboardVariable = u"Show_ScoreBoard"; - std::u16string WatchingIntroVariable = u"WatchingIntro"; - std::u16string ClearScoreboardVariable = u"Clear_Scoreboard"; - std::u16string DefinePlayerToUIVariable = u"Define_Player_To_UI"; - std::u16string UpdateScoreboardPlayersVariable = u"Update_ScoreBoard_Players."; - std::u16string PlayerConfirmVariable = u"PlayerConfirm_ScoreBoard."; - std::u16string PlayersAcceptedVariable = u"playersAccepted"; - std::u16string PlayersReadyVariable = u"playersReady"; - std::u16string BaseMobSetIndexVariable = u"baseMobSetNum"; - std::u16string RandMobSetIndexVariable = u"randMobSetNum"; - std::u16string AcceptedDelayStartedVariable = u"AcceptedDelayStarted"; - std::u16string NumberOfPlayersVariable = u"NumberOfPlayers"; - std::u16string FirstTimeDoneVariable = u"firstTimeDone"; - std::u16string MissionTypeVariable = u"missionType"; - std::u16string StartWaveMessageVariable = u"Start_Wave_Message"; - std::u16string ExitWavesVariable = u"Exit_waves"; - std::u16string UpdateDefaultStartTimerVariable = u"Update_Default_Start_Timer"; - std::u16string UpdateTimerVariable = u"Update_Timer"; - std::u16string UpdateCooldownVariable = u"Update_Cool_Down"; - std::u16string IsCooldownVariable = u"isCoolDown"; - std::u16string SpawnMobVariable = u"Spawn_Mob"; - std::u16string WonWaveVariable = u"Won_Wave"; - std::u16string WaveCompleteVariable = u"Wave_Complete"; - std::u16string StartTimedWaveVariable = u"Start_Timed_Wave"; - std::u16string NewWaveVariable = u"New_Wave"; - std::u16string StartCinematicVariable = u"startCinematic"; - std::u16string NumRemainingVariable = u"numRemaining"; - std::u16string StartCooldownVariable = u"Start_Cool_Down"; + // Variable names + std::u16string WavesStartedVariable = u"wavesStarted"; + std::u16string ShowScoreboardVariable = u"Show_ScoreBoard"; + std::u16string WatchingIntroVariable = u"WatchingIntro"; + std::u16string ClearScoreboardVariable = u"Clear_Scoreboard"; + std::u16string DefinePlayerToUIVariable = u"Define_Player_To_UI"; + std::u16string UpdateScoreboardPlayersVariable = u"Update_ScoreBoard_Players."; + std::u16string PlayerConfirmVariable = u"PlayerConfirm_ScoreBoard."; + std::u16string PlayersAcceptedVariable = u"playersAccepted"; + std::u16string PlayersReadyVariable = u"playersReady"; + std::u16string BaseMobSetIndexVariable = u"baseMobSetNum"; + std::u16string RandMobSetIndexVariable = u"randMobSetNum"; + std::u16string AcceptedDelayStartedVariable = u"AcceptedDelayStarted"; + std::u16string NumberOfPlayersVariable = u"NumberOfPlayers"; + std::u16string FirstTimeDoneVariable = u"firstTimeDone"; + std::u16string MissionTypeVariable = u"missionType"; + std::u16string StartWaveMessageVariable = u"Start_Wave_Message"; + std::u16string ExitWavesVariable = u"Exit_waves"; + std::u16string UpdateDefaultStartTimerVariable = u"Update_Default_Start_Timer"; + std::u16string UpdateTimerVariable = u"Update_Timer"; + std::u16string UpdateCooldownVariable = u"Update_Cool_Down"; + std::u16string IsCooldownVariable = u"isCoolDown"; + std::u16string SpawnMobVariable = u"Spawn_Mob"; + std::u16string WonWaveVariable = u"Won_Wave"; + std::u16string WaveCompleteVariable = u"Wave_Complete"; + std::u16string StartTimedWaveVariable = u"Start_Timed_Wave"; + std::u16string NewWaveVariable = u"New_Wave"; + std::u16string StartCinematicVariable = u"startCinematic"; + std::u16string NumRemainingVariable = u"numRemaining"; + std::u16string StartCooldownVariable = u"Start_Cool_Down"; - // Timer names - std::string SpawnTickTimer = "SpawnTick"; - std::string AllAcceptedDelayTimer = "AllAcceptedDelay"; - std::string AcceptedDelayTimer = "AcceptedDelay"; - std::string StartDelayTimer = "StartDelay"; - std::string ClockTickTimer = "ClockTick"; - std::string CoolDownStartTimer = "CoolDownStart"; - std::string CoolDownStopTimer = "CoolDownStop"; - std::string PlaySpawnSoundTimer = "PlaySpawnSound"; - std::string NextWaveTickTimer = "NextWaveTick"; - std::string WaveCompleteDelayTimer = "WaveCompleteDelay"; - std::string TimedWaveTimer = "TimedWave"; - std::string GameOverWinTimer = "GameOverWin"; - std::string CinematicDoneTimer = "CinematicDone"; + // Timer names + std::string SpawnTickTimer = "SpawnTick"; + std::string AllAcceptedDelayTimer = "AllAcceptedDelay"; + std::string AcceptedDelayTimer = "AcceptedDelay"; + std::string StartDelayTimer = "StartDelay"; + std::string ClockTickTimer = "ClockTick"; + std::string CoolDownStartTimer = "CoolDownStart"; + std::string CoolDownStopTimer = "CoolDownStop"; + std::string PlaySpawnSoundTimer = "PlaySpawnSound"; + std::string NextWaveTickTimer = "NextWaveTick"; + std::string WaveCompleteDelayTimer = "WaveCompleteDelay"; + std::string TimedWaveTimer = "TimedWave"; + std::string GameOverWinTimer = "GameOverWin"; + std::string CinematicDoneTimer = "CinematicDone"; - std::string spawnSoundGUID = "{ca36045d-89df-4e96-a317-1e152d226b69}"; + std::string spawnSoundGUID = "{ca36045d-89df-4e96-a317-1e152d226b69}"; private: - void SetGameVariables(Entity* self); - static void ResetStats(LWOOBJID player); - void GameOver(Entity* self, bool won = false); - void GameWon(Entity* self); - void UpdateMissionForAllPlayers(Entity* self, uint32_t missionID); + void SetGameVariables(Entity* self); + static void ResetStats(LWOOBJID player); + void GameOver(Entity* self, bool won = false); + void GameWon(Entity* self); + void UpdateMissionForAllPlayers(Entity* self, uint32_t missionID); - void StartWaves(Entity* self); - void SpawnWave(Entity* self); - static void SpawnNow(const std::string& spawnerName, uint32_t amount, LOT spawnLot); - bool UpdateSpawnedEnemies(Entity* self, LWOOBJID enemyID, uint32_t score); + void StartWaves(Entity* self); + void SpawnWave(Entity* self); + static void SpawnNow(const std::string& spawnerName, uint32_t amount, LOT spawnLot); + bool UpdateSpawnedEnemies(Entity* self, LWOOBJID enemyID, uint32_t score); - bool CheckAllPlayersDead(); - void SetPlayerSpawnPoints(const LWOOBJID& specificPlayerID = LWOOBJID_EMPTY); - void PlayerConfirmed(Entity* self); - void PlayerAccepted(Entity* self, LWOOBJID playerID); - void ClearSpawners(); + bool CheckAllPlayersDead(); + void SetPlayerSpawnPoints(const LWOOBJID& specificPlayerID = LWOOBJID_EMPTY); + void PlayerConfirmed(Entity* self); + void PlayerAccepted(Entity* self, LWOOBJID playerID); + void ClearSpawners(); - WaveConstants constants {}; - std::vector waves {}; - std::vector missions {}; - std::vector spawners {}; + WaveConstants constants{}; + std::vector waves{}; + std::vector missions{}; + std::vector spawners{}; }; diff --git a/dScripts/Binoculars.cpp b/dScripts/Binoculars.cpp index 348b3842..854ccf71 100644 --- a/dScripts/Binoculars.cpp +++ b/dScripts/Binoculars.cpp @@ -12,4 +12,4 @@ void Binoculars::OnUse(Entity* self, Entity* user) { user->GetCharacter()->SetPlayerFlag(flag, true); GameMessages::SendFireEventClientSide(self->GetObjectID(), user->GetSystemAddress(), u"achieve", LWOOBJID_EMPTY, 0, -1, LWOOBJID_EMPTY); } -} \ No newline at end of file +} diff --git a/dScripts/Binoculars.h b/dScripts/Binoculars.h index 141b3fb9..2f446119 100644 --- a/dScripts/Binoculars.h +++ b/dScripts/Binoculars.h @@ -4,4 +4,4 @@ class Binoculars : public CppScripts::Script { public: void OnUse(Entity* self, Entity* user); -}; \ No newline at end of file +}; diff --git a/dScripts/BootyDigServer.cpp b/dScripts/BootyDigServer.cpp index 50d873e0..d38791d8 100644 --- a/dScripts/BootyDigServer.cpp +++ b/dScripts/BootyDigServer.cpp @@ -4,49 +4,49 @@ #include "MissionComponent.h" #include "MissionTaskType.h" -void BootyDigServer::OnStartup(Entity *self) { - auto* zoneControlObject = EntityManager::Instance()->GetZoneControlEntity(); - if (zoneControlObject != nullptr) { - zoneControlObject->OnFireEventServerSide(self, "CheckForPropertyOwner"); - } +void BootyDigServer::OnStartup(Entity* self) { + auto* zoneControlObject = EntityManager::Instance()->GetZoneControlEntity(); + if (zoneControlObject != nullptr) { + zoneControlObject->OnFireEventServerSide(self, "CheckForPropertyOwner"); + } } -void BootyDigServer::OnPlayerLoaded(Entity *self, Entity *player) { - auto* zoneControlObject = EntityManager::Instance()->GetZoneControlEntity(); - if (zoneControlObject != nullptr) { - zoneControlObject->OnFireEventServerSide(self, "CheckForPropertyOwner"); - } +void BootyDigServer::OnPlayerLoaded(Entity* self, Entity* player) { + auto* zoneControlObject = EntityManager::Instance()->GetZoneControlEntity(); + if (zoneControlObject != nullptr) { + zoneControlObject->OnFireEventServerSide(self, "CheckForPropertyOwner"); + } } void -BootyDigServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { +BootyDigServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { - auto propertyOwner = self->GetNetworkVar(u"PropertyOwnerID"); - auto* player = self->GetParentEntity(); - if (player == nullptr) - return; + auto propertyOwner = self->GetNetworkVar(u"PropertyOwnerID"); + auto* player = self->GetParentEntity(); + if (player == nullptr) + return; - if (args == "ChestReady" && (propertyOwner == std::to_string(LWOOBJID_EMPTY) || player->GetVar(u"bootyDug"))) { - self->Smash(self->GetObjectID(), SILENT); - } else if (args == "ChestOpened") { - // Make sure players only dig up one booty per instance - player->SetVar(u"bootyDug", true); + if (args == "ChestReady" && (propertyOwner == std::to_string(LWOOBJID_EMPTY) || player->GetVar(u"bootyDug"))) { + self->Smash(self->GetObjectID(), SILENT); + } else if (args == "ChestOpened") { + // Make sure players only dig up one booty per instance + player->SetVar(u"bootyDug", true); - auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) { - auto* mission = missionComponent->GetMission(1881); - if (mission != nullptr && (mission->GetMissionState() == MissionState::MISSION_STATE_ACTIVE || mission->GetMissionState() == MissionState::MISSION_STATE_COMPLETE_ACTIVE)) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + auto* missionComponent = player->GetComponent(); + if (missionComponent != nullptr) { + auto* mission = missionComponent->GetMission(1881); + if (mission != nullptr && (mission->GetMissionState() == MissionState::MISSION_STATE_ACTIVE || mission->GetMissionState() == MissionState::MISSION_STATE_COMPLETE_ACTIVE)) { + mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) - renderComponent->PlayEffect(7730, u"cast", "bootyshine"); + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) + renderComponent->PlayEffect(7730, u"cast", "bootyshine"); - LootGenerator::Instance().DropLoot(player, self, 231, 75, 75); - } - } - } else if (args == "ChestDead") { - self->Smash(player->GetObjectID(), SILENT); - } + LootGenerator::Instance().DropLoot(player, self, 231, 75, 75); + } + } + } else if (args == "ChestDead") { + self->Smash(player->GetObjectID(), SILENT); + } } diff --git a/dScripts/BootyDigServer.h b/dScripts/BootyDigServer.h index dde41e29..3f73a530 100644 --- a/dScripts/BootyDigServer.h +++ b/dScripts/BootyDigServer.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class BootyDigServer : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnPlayerLoaded(Entity *self, Entity *player) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnStartup(Entity* self) override; + void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; }; diff --git a/dScripts/BossSpiderQueenEnemyServer.cpp b/dScripts/BossSpiderQueenEnemyServer.cpp index 88f05a4b..438493fe 100644 --- a/dScripts/BossSpiderQueenEnemyServer.cpp +++ b/dScripts/BossSpiderQueenEnemyServer.cpp @@ -67,7 +67,7 @@ void BossSpiderQueenEnemyServer::OnDie(Entity* self, Entity* killer) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SetColGroup", 10, 0, 0, "", UNASSIGNED_SYSTEM_ADDRESS); - self->SetPosition({10000, 0, 10000}); + self->SetPosition({ 10000, 0, 10000 }); EntityManager::Instance()->SerializeEntity(self); @@ -119,8 +119,7 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra self->AddTimer("WithdrawComplete", withdrawTime + 1.0f); waitForIdle = true; - } - else { + } else { controllable->SetStatic(false); //Cancel all remaining timers for say idle anims: @@ -131,10 +130,10 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra baseCombatAi->SetDisabled(false); // Move the Spider to its ground location - // preparing its stage attacks, and removing invulnerability + // preparing its stage attacks, and removing invulnerability //destroyable->SetIsImmune(false); - // Run the advance animation and prepare a timer for resuming AI + // Run the advance animation and prepare a timer for resuming AI float animTime = PlayAnimAndReturnTime(self, spiderAdvanceAnim); animTime += 1.f; @@ -143,18 +142,18 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra destroyable->SetFaction(4); destroyable->SetIsImmune(false); - //Advance stage + //Advance stage m_CurrentBossStage++; - //Reset the current wave death counter + //Reset the current wave death counter m_DeathCounter = 0; EntityManager::Instance()->SerializeEntity(self); - // Prepare a timer for post leap attack + // Prepare a timer for post leap attack self->AddTimer("AdvanceAttack", attackPause); - // Prepare a timer for post leap + // Prepare a timer for post leap self->AddTimer("AdvanceComplete", animTime); } @@ -179,7 +178,7 @@ void BossSpiderQueenEnemyServer::SpawnSpiderWave(Entity* self, int spiderCount) Game::logger->Log("SpiderQueen", "Trying to spawn %i spiders", hatchCounter); - // Run the wave manager + // Run the wave manager SpiderWaveManager(self); } @@ -268,8 +267,7 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { // We still have more eggs to hatch, poll the SpiderWaveManager again self->AddTimer("PollSpiderWaveManager", 1.0f); - } - else { + } else { // We have successfully readied a full wave // initiate hatching! for (auto egg : hatchList) { @@ -298,17 +296,14 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { } -void BossSpiderQueenEnemyServer::ToggleForSpecial(Entity* self, const bool state) -{ +void BossSpiderQueenEnemyServer::ToggleForSpecial(Entity* self, const bool state) { self->SetBoolean(u"stoppedFlag", state); combat->SetDisabled(state); } -void BossSpiderQueenEnemyServer::RunRainOfFire(Entity* self) -{ - if (self->GetBoolean(u"stoppedFlag")) - { +void BossSpiderQueenEnemyServer::RunRainOfFire(Entity* self) { + if (self->GetBoolean(u"stoppedFlag")) { self->AddTimer("ROF", GeneralUtils::GenerateRandomNumber(10, 20)); return; @@ -319,26 +314,20 @@ void BossSpiderQueenEnemyServer::RunRainOfFire(Entity* self) impactList.clear(); auto index = 0u; - for (const auto& rofGroup : ROFTargetGroupIDTable) - { + for (const auto& rofGroup : ROFTargetGroupIDTable) { const auto spawners = dZoneManager::Instance()->GetSpawnersInGroup(rofGroup); std::vector spawned; - for (auto* spawner : spawners) - { - for (const auto* node : spawner->m_Info.nodes) - { + for (auto* spawner : spawners) { + for (const auto* node : spawner->m_Info.nodes) { spawned.insert(spawned.end(), node->entities.begin(), node->entities.end()); } } - if (index == 0) - { + if (index == 0) { impactList.insert(impactList.end(), spawned.begin(), spawned.end()); - } - else - { + } else { const auto randomIndex = GeneralUtils::GenerateRandomNumber(0, spawned.size() - 1); impactList.push_back(spawned[randomIndex]); @@ -352,16 +341,13 @@ void BossSpiderQueenEnemyServer::RunRainOfFire(Entity* self) self->AddTimer("StartROF", animTime); } -void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) -{ - if (!impactList.empty()) - { +void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) { + if (!impactList.empty()) { auto* entity = EntityManager::Instance()->GetEntity(impactList[0]); impactList.erase(impactList.begin()); - if (entity == nullptr) - { + if (entity == nullptr) { Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find impact!"); return; @@ -369,8 +355,7 @@ void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) auto* skillComponent = entity->GetComponent(); - if (skillComponent == nullptr) - { + if (skillComponent == nullptr) { Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find impact skill component!"); return; @@ -388,10 +373,8 @@ void BossSpiderQueenEnemyServer::RainOfFireManager(Entity* self) self->AddTimer("ROF", GeneralUtils::GenerateRandomNumber(20, 40)); } -void BossSpiderQueenEnemyServer::RapidFireShooterManager(Entity* self) -{ - if (attackTargetTable.empty()) - { +void BossSpiderQueenEnemyServer::RapidFireShooterManager(Entity* self) { + if (attackTargetTable.empty()) { const auto animationTime = PlayAnimAndReturnTime(self, spiderJeerAnim); self->AddTimer("RFSTauntComplete", animationTime); @@ -412,23 +395,20 @@ void BossSpiderQueenEnemyServer::RapidFireShooterManager(Entity* self) self->AddTimer("PollRFSManager", 0.3f); } -void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) -{ +void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) { /* const auto targets = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER); */ const auto targets = self->GetTargetsInPhantom(); - if (self->GetBoolean(u"stoppedFlag")) - { + if (self->GetBoolean(u"stoppedFlag")) { self->AddTimer("RFS", GeneralUtils::GenerateRandomNumber(5, 10)); return; } - if (targets.empty()) - { + if (targets.empty()) { Game::logger->Log("BossSpiderQueenEnemyServer", "Failed to find RFS targets"); self->AddTimer("RFS", GeneralUtils::GenerateRandomNumber(5, 10)); @@ -459,12 +439,10 @@ void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string timerName) { if (timerName == "PollSpiderWaveManager") { - //Call the manager again to attempt to finish prepping a Spiderling wave - //Run the wave manager + //Call the manager again to attempt to finish prepping a Spiderling wave + //Run the wave manager SpiderWaveManager(self); - } - else if (timerName == "disableWaitForIdle") { waitForIdle = false; } - else if (timerName == "checkForSpiders") { + } else if (timerName == "disableWaitForIdle") { waitForIdle = false; } else if (timerName == "checkForSpiders") { //Don't do anything if we ain't withdrawn: const auto withdrawn = self->GetBoolean(u"isWithdrawn"); if (!withdrawn) return; @@ -491,54 +469,53 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim self->AddTimer("checkForSpiders", time); else WithdrawSpider(self, false); - } - else if (timerName == "PollROFManager") { - //Call the manager again to attempt to initiate an impact on another random location - //Run the ROF Manager + } else if (timerName == "PollROFManager") { + //Call the manager again to attempt to initiate an impact on another random location + //Run the ROF Manager RainOfFireManager(self); - } else if ( timerName == "PollRFSManager") { - //Call the manager again to attempt to initiate a rapid fire shot at the next sequential target - //Run the ROF Manager + } else if (timerName == "PollRFSManager") { + //Call the manager again to attempt to initiate a rapid fire shot at the next sequential target + //Run the ROF Manager RapidFireShooterManager(self); - } else if ( timerName == "StartROF") { - //Re-enable Spider Boss + } else if (timerName == "StartROF") { + //Re-enable Spider Boss //ToggleForSpecial(self, false); RainOfFireManager(self); - } else if ( timerName == "PollSpiderSkillManager") { - //Call the skill manager again to attempt to run the current Spider Boss - //stage's special attack again + } else if (timerName == "PollSpiderSkillManager") { + //Call the skill manager again to attempt to run the current Spider Boss + //stage's special attack again //SpiderSkillManager(self, true); PlayAnimAndReturnTime(self, spiderJeerAnim); - } else if ( timerName == "RFS") { + } else if (timerName == "RFS") { RunRapidFireShooter(self); - } else if ( timerName == "ROF") { + } else if (timerName == "ROF") { RunRainOfFire(self); - } else if ( timerName == "RFSTauntComplete") { - //Determine an appropriate random time to check our manager again - // local spiderCooldownDelay = math.random(s1DelayMin, s1DelayMax) + } else if (timerName == "RFSTauntComplete") { + //Determine an appropriate random time to check our manager again + // local spiderCooldownDelay = math.random(s1DelayMin, s1DelayMax) - //Set a timer based on our random cooldown determination - //to pulse the SpiderSkillManager again + //Set a timer based on our random cooldown determination + //to pulse the SpiderSkillManager again //GAMEOBJ:GetTimer():AddTimerWithCancel(spiderCooldownDelay, "PollSpiderSkillManager", self) - //Re-enable Spider Boss - //ToggleForSpecial(self, false); + //Re-enable Spider Boss + //ToggleForSpecial(self, false); - } else if ( timerName == "WithdrawComplete") { - //Play the Spider Boss' mountain idle anim + } else if (timerName == "WithdrawComplete") { + //Play the Spider Boss' mountain idle anim PlayAnimAndReturnTime(self, spiderWithdrawIdle); - //The Spider Boss has retreated, hatch a wave! + //The Spider Boss has retreated, hatch a wave! int currentStage = m_CurrentBossStage; - //Prepare a Spiderling wave and initiate egg hatch events - //self->SetVar(u"SpiderWaveCount", ) + //Prepare a Spiderling wave and initiate egg hatch events + //self->SetVar(u"SpiderWaveCount", ) //TODO: Actually spawn the spiders here hatchCounter = 2; @@ -546,53 +523,51 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim SpawnSpiderWave(self, spiderWaveCntTable[currentStage - 1]); - } else if ( timerName == "AdvanceAttack") { + } else if (timerName == "AdvanceAttack") { //TODO: Can we even do knockbacks yet? @Wincent01 // Yes ^ - //Fire the melee smash skill to throw players back - /*local landingTarget = self:GetVar("LandingTarget") or false + //Fire the melee smash skill to throw players back + /*local landingTarget = self:GetVar("LandingTarget") or false - if((landingTarget) and (landingTarget:Exists())) { - local advSmashFlag = landingTarget:CastSkill{skillID = bossLandingSkill} - landingTarget:PlayEmbeddedEffectOnAllClientsNearObject{radius = 100, fromObjectID = landingTarget, effectName = "camshake-bridge"} - }*/ + if((landingTarget) and (landingTarget:Exists())) { + local advSmashFlag = landingTarget:CastSkill{skillID = bossLandingSkill} + landingTarget:PlayEmbeddedEffectOnAllClientsNearObject{radius = 100, fromObjectID = landingTarget, effectName = "camshake-bridge"} + }*/ auto landingTarget = self->GetI64(u"LandingTarget"); auto landingEntity = EntityManager::Instance()->GetEntity(landingTarget); auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) - { + if (skillComponent != nullptr) { skillComponent->CalculateBehavior(bossLandingSkill, 37739, LWOOBJID_EMPTY); } if (landingEntity) { auto* landingSkill = landingEntity->GetComponent(); - if (landingSkill != nullptr) - { + if (landingSkill != nullptr) { landingSkill->CalculateBehavior(bossLandingSkill, 37739, LWOOBJID_EMPTY, true); } } GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(self, u"camshake-bridge", self->GetObjectID(), 100.0f); - } else if ( timerName == "AdvanceComplete") { - //Reset faction and collision - /*local SBFactionList = self:GetVar("SBFactionList") - local SBCollisionGroup = self:GetVar("SBCollisionGroup") + } else if (timerName == "AdvanceComplete") { + //Reset faction and collision + /*local SBFactionList = self:GetVar("SBFactionList") + local SBCollisionGroup = self:GetVar("SBCollisionGroup") - for i, fVal in ipairs(SBFactionList) { - if(i == 1) { - //Our first faction - flush and add - self:SetFaction{faction = fVal} - else - //Add - self:ModifyFaction{factionID = fVal, bAddFaction = true} - } - }*/ + for i, fVal in ipairs(SBFactionList) { + if(i == 1) { + //Our first faction - flush and add + self:SetFaction{faction = fVal} + else + //Add + self:ModifyFaction{factionID = fVal, bAddFaction = true} + } + }*/ /* auto SBCollisionGroup = self->GetI32(u"SBCollisionGroup"); @@ -602,71 +577,68 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SetColGroup", 11, 0, 0, "", UNASSIGNED_SYSTEM_ADDRESS); - //Wind up, telegraphing next round + //Wind up, telegraphing next round float animTime = PlayAnimAndReturnTime(self, spiderJeerAnim); self->AddTimer("AdvanceTauntComplete", animTime); - } else if ( timerName == "AdvanceTauntComplete") { + } else if (timerName == "AdvanceTauntComplete") { - //Declare a default special Spider Boss skill cooldown + //Declare a default special Spider Boss skill cooldown int spiderCooldownDelay = 10; - if(m_CurrentBossStage == 2) { + if (m_CurrentBossStage == 2) { spiderCooldownDelay = GeneralUtils::GenerateRandomNumber(s1DelayMin, s1DelayMax); - } else if (m_CurrentBossStage == 3) { - spiderCooldownDelay = GeneralUtils::GenerateRandomNumber(s2DelayMin, s2DelayMax); - } + } else if (m_CurrentBossStage == 3) { + spiderCooldownDelay = GeneralUtils::GenerateRandomNumber(s2DelayMin, s2DelayMax); + } - //Set a timer based on our random cooldown determination - //to pulse the SpiderSkillManager + //Set a timer based on our random cooldown determination + //to pulse the SpiderSkillManager self->AddTimer("PollSpiderSkillManager", spiderCooldownDelay); - //Remove current status immunity - /*self:SetStatusImmunity{ StateChangeType = "POP", bImmuneToSpeed = true, bImmuneToBasicAttack = true, bImmuneToDOT = true} + //Remove current status immunity + /*self:SetStatusImmunity{ StateChangeType = "POP", bImmuneToSpeed = true, bImmuneToBasicAttack = true, bImmuneToDOT = true} - self:SetStunned{StateChangeType = "POP", - bCantMove = true, - bCantJump = true, - bCantTurn = true, - bCantAttack = true, - bCantUseItem = true, - bCantEquip = true, - bCantInteract = true, - bIgnoreImmunity = true}*/ + self:SetStunned{StateChangeType = "POP", + bCantMove = true, + bCantJump = true, + bCantTurn = true, + bCantAttack = true, + bCantUseItem = true, + bCantEquip = true, + bCantInteract = true, + bIgnoreImmunity = true}*/ destroyable->SetIsImmune(false); destroyable->SetFaction(4); EntityManager::Instance()->SerializeEntity(self); - } else if ( timerName == "Clear") { + } else if (timerName == "Clear") { EntityManager::Instance()->FireEventServerSide(self, "ClearProperty"); self->CancelAllTimers(); - } else if ( timerName == "UnlockSpecials") { - //We no longer need to lock specials + } else if (timerName == "UnlockSpecials") { + //We no longer need to lock specials self->SetBoolean(u"bSpecialLock", false); - //Did we queue a spcial attack? - if(self->GetBoolean(u"bSpecialQueued")) { + //Did we queue a spcial attack? + if (self->GetBoolean(u"bSpecialQueued")) { self->SetBoolean(u"bSpecialQueued", false); //SpiderSkillManager(self, true); - } + } } } void BossSpiderQueenEnemyServer::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { - if (m_CurrentBossStage > 0 && !self->HasTimer("RFS")) - { + if (m_CurrentBossStage > 0 && !self->HasTimer("RFS")) { self->AddTimer("RFS", 5.0f); } - if (m_CurrentBossStage > 0 && !self->HasTimer("ROF")) - { + if (m_CurrentBossStage > 0 && !self->HasTimer("ROF")) { self->AddTimer("ROF", 10.0f); } - if (m_CurrentBossStage > ThresholdTable.size()) - { + if (m_CurrentBossStage > ThresholdTable.size()) { return; } @@ -691,8 +663,7 @@ void BossSpiderQueenEnemyServer::OnUpdate(Entity* self) { if (!isWithdrawn) return; - if (controllable->GetRotation() == NiQuaternion::IDENTITY) - { + if (controllable->GetRotation() == NiQuaternion::IDENTITY) { return; } diff --git a/dScripts/BossSpiderQueenEnemyServer.h b/dScripts/BossSpiderQueenEnemyServer.h index f3219cf7..e41b878d 100644 --- a/dScripts/BossSpiderQueenEnemyServer.h +++ b/dScripts/BossSpiderQueenEnemyServer.h @@ -19,25 +19,25 @@ class BaseCombatAIComponent; class BossSpiderQueenEnemyServer final : public CppScripts::Script { public: void OnStartup(Entity* self) override; - + void OnDie(Entity* self, Entity* killer) override; - + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; - + void OnUpdate(Entity* self) override; void WithdrawSpider(Entity* self, bool withdraw); void SpawnSpiderWave(Entity* self, int spiderCount); - + void SpiderWaveManager(Entity* self); void ToggleForSpecial(Entity* self, bool state); - + void RunRainOfFire(Entity* self); void RainOfFireManager(Entity* self); - + void RapidFireShooterManager(Entity* self); void RunRapidFireShooter(Entity* self); @@ -53,7 +53,7 @@ private: BaseCombatAIComponent* combat = nullptr; NiQuaternion originRotation; - + int m_CurrentBossStage = 0; int m_DeathCounter = 0; std::vector ThresholdTable; diff --git a/dScripts/BuccaneerValiantShip.cpp b/dScripts/BuccaneerValiantShip.cpp index 710a0d1a..3db214b5 100644 --- a/dScripts/BuccaneerValiantShip.cpp +++ b/dScripts/BuccaneerValiantShip.cpp @@ -2,17 +2,17 @@ #include "SkillComponent.h" void BuccaneerValiantShip::OnStartup(Entity* self) { - self->AddCallbackTimer(1.0F, [self]() { - auto* skillComponent = self->GetComponent(); - auto* owner = self->GetOwner(); + self->AddCallbackTimer(1.0F, [self]() { + auto* skillComponent = self->GetComponent(); + auto* owner = self->GetOwner(); - if (skillComponent != nullptr && owner != nullptr) { - skillComponent->CalculateBehavior(982, 20577, LWOOBJID_EMPTY, true, false, owner->GetObjectID()); + if (skillComponent != nullptr && owner != nullptr) { + skillComponent->CalculateBehavior(982, 20577, LWOOBJID_EMPTY, true, false, owner->GetObjectID()); - // Kill self if missed - self->AddCallbackTimer(1.1F, [self]() { - self->Kill(); - }); - } - }); + // Kill self if missed + self->AddCallbackTimer(1.1F, [self]() { + self->Kill(); + }); + } + }); } diff --git a/dScripts/BuccaneerValiantShip.h b/dScripts/BuccaneerValiantShip.h index f501d1b9..8ed3f7ad 100644 --- a/dScripts/BuccaneerValiantShip.h +++ b/dScripts/BuccaneerValiantShip.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class BuccaneerValiantShip : public CppScripts::Script { - void OnStartup(Entity *self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/BurningTile.cpp b/dScripts/BurningTile.cpp index b9a05391..8ac3dc5d 100644 --- a/dScripts/BurningTile.cpp +++ b/dScripts/BurningTile.cpp @@ -1,17 +1,14 @@ #include "BurningTile.h" #include "SkillComponent.h" -void BurningTile::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - if (args == "PlayerEntered") - { - auto* skillComponent = sender->GetComponent(); +void BurningTile::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args == "PlayerEntered") { + auto* skillComponent = sender->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - skillComponent->CalculateBehavior(726, 11723, sender->GetObjectID(), true); - } + skillComponent->CalculateBehavior(726, 11723, sender->GetObjectID(), true); + } } diff --git a/dScripts/BurningTile.h b/dScripts/BurningTile.h index 5f43895e..024ec6fc 100644 --- a/dScripts/BurningTile.h +++ b/dScripts/BurningTile.h @@ -4,5 +4,5 @@ class BurningTile : public CppScripts::Script { public: - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; -}; \ No newline at end of file + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; +}; diff --git a/dScripts/CatapultBaseServer.cpp b/dScripts/CatapultBaseServer.cpp index 33539de8..fda103b0 100644 --- a/dScripts/CatapultBaseServer.cpp +++ b/dScripts/CatapultBaseServer.cpp @@ -2,30 +2,25 @@ #include "GameMessages.h" #include "EntityManager.h" -void CatapultBaseServer::OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1, int32_t param2) -{ - if (name == "BouncerBuilt") - { - // start a timer for the arm to player the with bouncer animation - self->AddTimer("PlatAnim", .75); +void CatapultBaseServer::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) { + if (name == "BouncerBuilt") { + // start a timer for the arm to player the with bouncer animation + self->AddTimer("PlatAnim", .75); - // set the bouncer so we can use it later - self->SetVar(u"Bouncer", sender->GetObjectID()); + // set the bouncer so we can use it later + self->SetVar(u"Bouncer", sender->GetObjectID()); GameMessages::SendBouncerActiveStatus(sender->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); } } -void CatapultBaseServer::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "PlatAnim") - { - // get the arm asset - const auto arm = EntityManager::Instance()->GetEntitiesInGroup(self->GetVarAsString(u"ArmGroup")); +void CatapultBaseServer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "PlatAnim") { + // get the arm asset + const auto arm = EntityManager::Instance()->GetEntitiesInGroup(self->GetVarAsString(u"ArmGroup")); // tell the arm to the play the platform animation, which is just the arm laying there but with bouncer - for (auto* obj : arm) - { + for (auto* obj : arm) { GameMessages::SendPlayAnimation(obj, u"idle-platform"); GameMessages::SendPlayNDAudioEmitter(obj, UNASSIGNED_SYSTEM_ADDRESS, "{8cccf912-69e3-4041-a20b-63e4afafc993}"); // set the art so we can use it again @@ -35,9 +30,7 @@ void CatapultBaseServer::OnTimerDone(Entity* self, std::string timerName) // start a timer till the bouncer actually bounces self->AddTimer("bounce", 3); - } - else if (timerName == "launchAnim") - { + } else if (timerName == "launchAnim") { // get the arm asset auto* arm = EntityManager::Instance()->GetEntity(self->GetVar(u"Arm")); if (arm == nullptr) return; @@ -46,9 +39,7 @@ void CatapultBaseServer::OnTimerDone(Entity* self, std::string timerName) auto animTime = 1; self->AddTimer("resetArm", animTime); GameMessages::SendPlayAnimation(arm, u"launch"); - } - else if (timerName == "bounce") - { + } else if (timerName == "bounce") { auto* bouncer = EntityManager::Instance()->GetEntity(self->GetVar(u"Bouncer")); if (bouncer == nullptr) return; @@ -56,9 +47,7 @@ void CatapultBaseServer::OnTimerDone(Entity* self, std::string timerName) bouncer->NotifyObject(bouncer, "bounceAllInProximity"); // Likely to trigger server side bounce, bodging this // add a delay to play the animation self->AddTimer("launchAnim", .3); - } - else if (timerName == "resetArm") - { + } else if (timerName == "resetArm") { auto* arm = EntityManager::Instance()->GetEntity(self->GetVar(u"Arm")); if (arm == nullptr) return; diff --git a/dScripts/CatapultBaseServer.h b/dScripts/CatapultBaseServer.h index a174fcaf..cc5a1907 100644 --- a/dScripts/CatapultBaseServer.h +++ b/dScripts/CatapultBaseServer.h @@ -3,7 +3,7 @@ class CatapultBaseServer : public CppScripts::Script { public: - void OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; - - void OnTimerDone(Entity* self, std::string timerName) override; + void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; + + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/CatapultBouncerServer.cpp b/dScripts/CatapultBouncerServer.cpp index 098f38ac..89faf001 100644 --- a/dScripts/CatapultBouncerServer.cpp +++ b/dScripts/CatapultBouncerServer.cpp @@ -2,16 +2,14 @@ #include "GameMessages.h" #include "EntityManager.h" -void CatapultBouncerServer::OnRebuildComplete(Entity* self, Entity* target) -{ - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"Built", 0, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); +void CatapultBouncerServer::OnRebuildComplete(Entity* self, Entity* target) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"Built", 0, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - self->SetNetworkVar(u"Built", true); + self->SetNetworkVar(u"Built", true); - const auto base = EntityManager::Instance()->GetEntitiesInGroup(self->GetVarAsString(u"BaseGroup")); + const auto base = EntityManager::Instance()->GetEntitiesInGroup(self->GetVarAsString(u"BaseGroup")); - for (auto* obj : base) - { - obj->NotifyObject(self, "BouncerBuilt"); - } + for (auto* obj : base) { + obj->NotifyObject(self, "BouncerBuilt"); + } } diff --git a/dScripts/CatapultBouncerServer.h b/dScripts/CatapultBouncerServer.h index 06f03bf4..46ec20ab 100644 --- a/dScripts/CatapultBouncerServer.h +++ b/dScripts/CatapultBouncerServer.h @@ -3,5 +3,5 @@ class CatapultBouncerServer : public CppScripts::Script { public: - void OnRebuildComplete(Entity* self, Entity* target) override; + void OnRebuildComplete(Entity* self, Entity* target) override; }; diff --git a/dScripts/CauldronOfLife.cpp b/dScripts/CauldronOfLife.cpp index 13e07775..3ddb5c61 100644 --- a/dScripts/CauldronOfLife.cpp +++ b/dScripts/CauldronOfLife.cpp @@ -1,13 +1,13 @@ #include "CauldronOfLife.h" -void CauldronOfLife::OnStartup(Entity *self) { - self->SetVar(u"numCycles", 10); - self->SetVar(u"secPerCycle", 20.0f); - self->SetVar(u"delayToFirstCycle", 1.5f); - self->SetVar(u"deathDelay", 20.0f); - self->SetVar(u"numberOfPowerups", 3); - self->SetVar(u"lootLOT", 177); +void CauldronOfLife::OnStartup(Entity* self) { + self->SetVar(u"numCycles", 10); + self->SetVar(u"secPerCycle", 20.0f); + self->SetVar(u"delayToFirstCycle", 1.5f); + self->SetVar(u"deathDelay", 20.0f); + self->SetVar(u"numberOfPowerups", 3); + self->SetVar(u"lootLOT", 177); - // Initiate the actual script - OnTemplateStartup(self); + // Initiate the actual script + OnTemplateStartup(self); } diff --git a/dScripts/CauldronOfLife.h b/dScripts/CauldronOfLife.h index 3a5892c6..f7b492b5 100644 --- a/dScripts/CauldronOfLife.h +++ b/dScripts/CauldronOfLife.h @@ -2,5 +2,5 @@ #include "ScriptedPowerupSpawner.h" class CauldronOfLife : public ScriptedPowerupSpawner { - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/CavePrisonCage.cpp b/dScripts/CavePrisonCage.cpp index 5fe47f2d..0df91884 100644 --- a/dScripts/CavePrisonCage.cpp +++ b/dScripts/CavePrisonCage.cpp @@ -5,241 +5,211 @@ #include "Character.h" #include "dZoneManager.h" -void CavePrisonCage::OnStartup(Entity *self) -{ - const auto& myNum = self->GetVar(u"myNumber"); +void CavePrisonCage::OnStartup(Entity* self) { + const auto& myNum = self->GetVar(u"myNumber"); - if (myNum.empty()) - { - return; - } + if (myNum.empty()) { + return; + } - auto* spawner = dZoneManager::Instance()->GetSpawnersByName("PrisonCounterweight_0" + GeneralUtils::UTF16ToWTF8(myNum))[0]; + auto* spawner = dZoneManager::Instance()->GetSpawnersByName("PrisonCounterweight_0" + GeneralUtils::UTF16ToWTF8(myNum))[0]; - self->SetVar(u"CWSpawner", spawner); + self->SetVar(u"CWSpawner", spawner); - Setup(self, spawner); + Setup(self, spawner); } -void CavePrisonCage::Setup(Entity *self, Spawner* spawner) -{ - SpawnCounterweight(self, spawner); +void CavePrisonCage::Setup(Entity* self, Spawner* spawner) { + SpawnCounterweight(self, spawner); - NiPoint3 mypos = self->GetPosition(); - NiQuaternion myrot = self->GetRotation(); + NiPoint3 mypos = self->GetPosition(); + NiQuaternion myrot = self->GetRotation(); - mypos.y += 1.5; - mypos.z -= 0.5; + mypos.y += 1.5; + mypos.z -= 0.5; - EntityInfo info {}; - info.lot = m_Villagers[self->GetVarAs(u"myNumber") - 1]; - info.pos = mypos; - info.rot = myrot; - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = m_Villagers[self->GetVarAs(u"myNumber") - 1]; + info.pos = mypos; + info.rot = myrot; + info.spawnerID = self->GetObjectID(); - // Spawn the villager inside the jail - auto* entity = EntityManager::Instance()->CreateEntity(info); + // Spawn the villager inside the jail + auto* entity = EntityManager::Instance()->CreateEntity(info); - // Save the villeger ID - self->SetVar(u"villager", entity->GetObjectID()); + // Save the villeger ID + self->SetVar(u"villager", entity->GetObjectID()); - // Construct the entity - EntityManager::Instance()->ConstructEntity(entity); + // Construct the entity + EntityManager::Instance()->ConstructEntity(entity); } -void CavePrisonCage::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state != eRebuildState::REBUILD_RESETTING) - { - return; - } +void CavePrisonCage::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state != eRebuildState::REBUILD_RESETTING) { + return; + } - auto* spawner = self->GetVar(u"CWSpawner"); + auto* spawner = self->GetVar(u"CWSpawner"); - if (spawner == nullptr) - { - return; - } + if (spawner == nullptr) { + return; + } - spawner->Reset(); + spawner->Reset(); - SpawnCounterweight(self, spawner); + SpawnCounterweight(self, spawner); } -void CavePrisonCage::SpawnCounterweight(Entity* self, Spawner* spawner) -{ - spawner->Reset(); +void CavePrisonCage::SpawnCounterweight(Entity* self, Spawner* spawner) { + spawner->Reset(); - auto* counterweight = spawner->Spawn(); + auto* counterweight = spawner->Spawn(); - self->SetVar(u"Counterweight", counterweight->GetObjectID()); + self->SetVar(u"Counterweight", counterweight->GetObjectID()); - auto* rebuildComponent = counterweight->GetComponent(); + auto* rebuildComponent = counterweight->GetComponent(); - if (rebuildComponent != nullptr) - { - rebuildComponent->AddRebuildStateCallback([this, self] (eRebuildState state) { - OnRebuildNotifyState(self, state); - }); + if (rebuildComponent != nullptr) { + rebuildComponent->AddRebuildStateCallback([this, self](eRebuildState state) { + OnRebuildNotifyState(self, state); + }); - rebuildComponent->AddRebuildCompleteCallback([this, self] (Entity* user) { - // The counterweight is a simple mover, which is not implemented, so we'll just set it's position - auto* counterweight = EntityManager::Instance()->GetEntity(self->GetVar(u"Counterweight")); + rebuildComponent->AddRebuildCompleteCallback([this, self](Entity* user) { + // The counterweight is a simple mover, which is not implemented, so we'll just set it's position + auto* counterweight = EntityManager::Instance()->GetEntity(self->GetVar(u"Counterweight")); - if (counterweight == nullptr) - { - return; - } + if (counterweight == nullptr) { + return; + } - // Move the counterweight down 2 units - counterweight->SetPosition(counterweight->GetPosition() + NiPoint3(0, -2, 0)); + // Move the counterweight down 2 units + counterweight->SetPosition(counterweight->GetPosition() + NiPoint3(0, -2, 0)); - // Serialize the counterweight - EntityManager::Instance()->SerializeEntity(counterweight); + // Serialize the counterweight + EntityManager::Instance()->SerializeEntity(counterweight); - // notifyPlatformAtLastWaypoint - - // Save the userID as Builder - self->SetVar(u"Builder", user->GetObjectID()); + // notifyPlatformAtLastWaypoint - // Get the button and make sure it still exists - auto* button = EntityManager::Instance()->GetEntity(self->GetVar(u"Button")); + // Save the userID as Builder + self->SetVar(u"Builder", user->GetObjectID()); - if (button == nullptr) - { - return; - } + // Get the button and make sure it still exists + auto* button = EntityManager::Instance()->GetEntity(self->GetVar(u"Button")); - // Play the 'down' animation on the button - GameMessages::SendPlayAnimation(button, u"down"); + if (button == nullptr) { + return; + } - // Setup a timer named 'buttonGoingDown' to be triggered in 5 seconds - self->AddTimer("buttonGoingDown", 5.0f); - }); - } + // Play the 'down' animation on the button + GameMessages::SendPlayAnimation(button, u"down"); - if (self->GetVar(u"Button")) - { - return; - } + // Setup a timer named 'buttonGoingDown' to be triggered in 5 seconds + self->AddTimer("buttonGoingDown", 5.0f); + }); + } - GetButton(self); + if (self->GetVar(u"Button")) { + return; + } + + GetButton(self); } -void CavePrisonCage::GetButton(Entity* self) -{ - const auto buttons = EntityManager::Instance()->GetEntitiesInGroup("PrisonButton_0" + std::to_string(self->GetVarAs(u"myNumber"))); +void CavePrisonCage::GetButton(Entity* self) { + const auto buttons = EntityManager::Instance()->GetEntitiesInGroup("PrisonButton_0" + std::to_string(self->GetVarAs(u"myNumber"))); - if (buttons.size() == 0) - { - // Try again in 0.5 seconds - self->AddCallbackTimer(0.5, [this, self] () { - GetButton(self); - }); + if (buttons.size() == 0) { + // Try again in 0.5 seconds + self->AddCallbackTimer(0.5, [this, self]() { + GetButton(self); + }); - return; - } + return; + } - auto* button = buttons[0]; + auto* button = buttons[0]; - self->SetVar(u"Button", button->GetObjectID()); + self->SetVar(u"Button", button->GetObjectID()); } -void CavePrisonCage::OnTimerDone(Entity* self, std::string timerName) -{ - // the anim of the button down is over - if (timerName == "buttonGoingDown") - { - // Play the 'up' animation - GameMessages::SendPlayAnimation(self, u"up"); +void CavePrisonCage::OnTimerDone(Entity* self, std::string timerName) { + // the anim of the button down is over + if (timerName == "buttonGoingDown") { + // Play the 'up' animation + GameMessages::SendPlayAnimation(self, u"up"); - // Setup a timer named 'CageOpen' to be triggered in 1 second - self->AddTimer("CageOpen", 1.0f); - } - else if (timerName == "CageOpen") - { - // play the idle open anim - GameMessages::SendPlayAnimation(self, u"idle-up"); + // Setup a timer named 'CageOpen' to be triggered in 1 second + self->AddTimer("CageOpen", 1.0f); + } else if (timerName == "CageOpen") { + // play the idle open anim + GameMessages::SendPlayAnimation(self, u"idle-up"); - // Get the villeger - auto* villager = EntityManager::Instance()->GetEntity(self->GetVar(u"villager")); + // Get the villeger + auto* villager = EntityManager::Instance()->GetEntity(self->GetVar(u"villager")); - if (villager == nullptr) - { - return; - } + if (villager == nullptr) { + return; + } - GameMessages::SendNotifyClientObject(villager->GetObjectID(), u"TimeToChat", 0, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(villager->GetObjectID(), u"TimeToChat", 0, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - // Get the builder and make sure it still exists - auto* builder = EntityManager::Instance()->GetEntity(self->GetVar(u"Builder")); + // Get the builder and make sure it still exists + auto* builder = EntityManager::Instance()->GetEntity(self->GetVar(u"Builder")); - if (builder == nullptr) - { - return; - } + if (builder == nullptr) { + return; + } - const auto flagNum = 2020 + self->GetVarAs(u"myNumber"); + const auto flagNum = 2020 + self->GetVarAs(u"myNumber"); - // Set the flag on the builder character - builder->GetCharacter()->SetPlayerFlag(flagNum, true); + // Set the flag on the builder character + builder->GetCharacter()->SetPlayerFlag(flagNum, true); - // Setup a timer named 'VillagerEscape' to be triggered in 5 seconds - self->AddTimer("VillagerEscape", 5.0f); - } - else if (timerName == "VillagerEscape") - { - // Get the villeger and make sure it still exists - auto* villager = EntityManager::Instance()->GetEntity(self->GetVar(u"villager")); - - if (villager == nullptr) - { - return; - } + // Setup a timer named 'VillagerEscape' to be triggered in 5 seconds + self->AddTimer("VillagerEscape", 5.0f); + } else if (timerName == "VillagerEscape") { + // Get the villeger and make sure it still exists + auto* villager = EntityManager::Instance()->GetEntity(self->GetVar(u"villager")); - // Kill the villager - villager->Kill(); + if (villager == nullptr) { + return; + } - // Setup a timer named 'SmashCounterweight' to be triggered in 2 seconds - self->AddTimer("SmashCounterweight", 2.0f); - } - else if (timerName == "SmashCounterweight") - { - // Get the counterweight and make sure it still exists - auto* counterweight = EntityManager::Instance()->GetEntity(self->GetVar(u"Counterweight")); + // Kill the villager + villager->Kill(); - if (counterweight == nullptr) - { - return; - } + // Setup a timer named 'SmashCounterweight' to be triggered in 2 seconds + self->AddTimer("SmashCounterweight", 2.0f); + } else if (timerName == "SmashCounterweight") { + // Get the counterweight and make sure it still exists + auto* counterweight = EntityManager::Instance()->GetEntity(self->GetVar(u"Counterweight")); - // Smash the counterweight - counterweight->Smash(); + if (counterweight == nullptr) { + return; + } - // Get the button and make sure it still exists - auto* button = EntityManager::Instance()->GetEntity(self->GetVar(u"Button")); + // Smash the counterweight + counterweight->Smash(); - if (button == nullptr) - { - return; - } + // Get the button and make sure it still exists + auto* button = EntityManager::Instance()->GetEntity(self->GetVar(u"Button")); - // Play the 'up' animation on the button - GameMessages::SendPlayAnimation(button, u"up"); + if (button == nullptr) { + return; + } - // Setup a timer named 'CageClosed' to be triggered in 1 second - self->AddTimer("CageClosed", 1.0f); - } - else if (timerName == "CageClosed") - { - // play the idle closed anim - GameMessages::SendPlayAnimation(self, u"idle"); + // Play the 'up' animation on the button + GameMessages::SendPlayAnimation(button, u"up"); - // Setup a timer named 'ResetPrison' to be triggered in 10 seconds - self->AddTimer("ResetPrison", 10.0f); - } - else if (timerName == "ResetPrison") - { - Setup(self, self->GetVar(u"CWSpawner")); - } + // Setup a timer named 'CageClosed' to be triggered in 1 second + self->AddTimer("CageClosed", 1.0f); + } else if (timerName == "CageClosed") { + // play the idle closed anim + GameMessages::SendPlayAnimation(self, u"idle"); + + // Setup a timer named 'ResetPrison' to be triggered in 10 seconds + self->AddTimer("ResetPrison", 10.0f); + } else if (timerName == "ResetPrison") { + Setup(self, self->GetVar(u"CWSpawner")); + } } diff --git a/dScripts/CavePrisonCage.h b/dScripts/CavePrisonCage.h index 5ae357d5..43d826c7 100644 --- a/dScripts/CavePrisonCage.h +++ b/dScripts/CavePrisonCage.h @@ -3,14 +3,14 @@ class CavePrisonCage : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - void Setup(Entity *self, Spawner* spawner); + void OnStartup(Entity* self) override; + void Setup(Entity* self, Spawner* spawner); void OnRebuildNotifyState(Entity* self, eRebuildState state) override; - void SpawnCounterweight(Entity* self, Spawner* spawner); - void GetButton(Entity* self); + void SpawnCounterweight(Entity* self, Spawner* spawner); + void GetButton(Entity* self); void OnTimerDone(Entity* self, std::string timerName) override; private: - std::vector m_Villagers = { 15851, 15866, 15922, 15924, 15927, 15929 }; - std::vector m_Missions = { 1801, 2039 }; + std::vector m_Villagers = { 15851, 15866, 15922, 15924, 15927, 15929 }; + std::vector m_Missions = { 1801, 2039 }; }; diff --git a/dScripts/ChooseYourDestinationNsToNt.cpp b/dScripts/ChooseYourDestinationNsToNt.cpp index 823d7c85..e50d70c5 100644 --- a/dScripts/ChooseYourDestinationNsToNt.cpp +++ b/dScripts/ChooseYourDestinationNsToNt.cpp @@ -2,77 +2,63 @@ #include "Character.h" #include "GameMessages.h" -bool ChooseYourDestinationNsToNt::CheckChoice(Entity* self, Entity* player) -{ - const auto choiceZoneID = self->GetVar(u"choiceZone"); - const auto newZoneID = self->GetVar(u"currentZone"); +bool ChooseYourDestinationNsToNt::CheckChoice(Entity* self, Entity* player) { + const auto choiceZoneID = self->GetVar(u"choiceZone"); + const auto newZoneID = self->GetVar(u"currentZone"); - if (newZoneID == choiceZoneID) - { - auto* character = player->GetCharacter(); + if (newZoneID == choiceZoneID) { + auto* character = player->GetCharacter(); - if (character == nullptr) - { - return false; - } + if (character == nullptr) { + return false; + } - if (character->HasBeenToWorld(1900)) - { - return true; - } + if (character->HasBeenToWorld(1900)) { + return true; + } - self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(1200)); - self->SetVar(u"teleportString", u"UI_TRAVEL_TO_NS"); + self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(1200)); + self->SetVar(u"teleportString", u"UI_TRAVEL_TO_NS"); - return false; - } + return false; + } - return false; + return false; } -void ChooseYourDestinationNsToNt::SetDestination(Entity* self, Entity* player) -{ - const auto currentMap = self->GetVar(u"currentZone"); - auto newMap = self->GetVar(u"choiceZone"); +void ChooseYourDestinationNsToNt::SetDestination(Entity* self, Entity* player) { + const auto currentMap = self->GetVar(u"currentZone"); + auto newMap = self->GetVar(u"choiceZone"); - if (currentMap == newMap) - { - newMap = 1200; - } + if (currentMap == newMap) { + newMap = 1200; + } - self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap)); + self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap)); } -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); +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; - } + int32_t newMap = 0; + if (!GeneralUtils::TryParse(newMapStr, newMap)) { + return; + } - std::u16string strText = u""; + std::u16string strText = u""; - if (newMap == 1200) - { - strText = u"UI_TRAVEL_TO_NS"; - } - else - { - strText = u"UI_TRAVEL_TO_NEXUS_TOWER"; - } + if (newMap == 1200) { + strText = u"UI_TRAVEL_TO_NS"; + } else { + strText = u"UI_TRAVEL_TO_NEXUS_TOWER"; + } - self->SetVar(u"teleportString", strText); - self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap)); + self->SetVar(u"teleportString", strText); + self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap)); - GameMessages::SendDisplayMessageBox(sender->GetObjectID(), true, self->GetObjectID(), u"TransferBox", 0, strText, u"", sender->GetSystemAddress()); - } - else - { - GameMessages::SendTerminateInteraction(sender->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); - } + GameMessages::SendDisplayMessageBox(sender->GetObjectID(), true, self->GetObjectID(), u"TransferBox", 0, strText, u"", sender->GetSystemAddress()); + } else { + GameMessages::SendTerminateInteraction(sender->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + } } diff --git a/dScripts/ChooseYourDestinationNsToNt.h b/dScripts/ChooseYourDestinationNsToNt.h index cbf3709e..9ce9988a 100644 --- a/dScripts/ChooseYourDestinationNsToNt.h +++ b/dScripts/ChooseYourDestinationNsToNt.h @@ -3,7 +3,7 @@ class ChooseYourDestinationNsToNt { public: - bool CheckChoice(Entity* self, Entity* player); - void SetDestination(Entity* self, Entity* player); - void BaseChoiceBoxRespond(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier); + bool CheckChoice(Entity* self, Entity* player); + void SetDestination(Entity* self, Entity* player); + void BaseChoiceBoxRespond(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier); }; diff --git a/dScripts/ClRing.cpp b/dScripts/ClRing.cpp index 5de3e683..37e76d88 100644 --- a/dScripts/ClRing.cpp +++ b/dScripts/ClRing.cpp @@ -1,6 +1,5 @@ #include "ClRing.h" -void ClRing::OnCollisionPhantom(Entity* self, Entity* target) -{ +void ClRing::OnCollisionPhantom(Entity* self, Entity* target) { self->Smash(target->GetObjectID()); } diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 8569bf9e..fbcb660a 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -377,38 +377,38 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new NpcAgCourseStarter(); else if (scriptName == "scripts\\02_server\\Map\\AG\\L__AG_MONUMENT_RACE_GOAL.lua") script = new AgMonumentRaceGoal(); - else if (scriptName == "scripts\\02_server\\Map\\AG\\L__AG_MONUMENT_RACE_CANCEL.lua") - script = new AgMonumentRaceCancel(); - else if (scriptName == "scripts\\02_server\\Map\\AG_Spider_Queen\\L_ZONE_AG_SPIDER_QUEEN.lua") - script = (ZoneAgProperty*)new ZoneAgSpiderQueen(); - else if (scriptName == "scripts\\02_server\\Map\\AG_Spider_Queen\\L_SPIDER_BOSS_TREASURE_CHEST_SERVER.lua") - script = new SpiderBossTreasureChestServer(); + else if (scriptName == "scripts\\02_server\\Map\\AG\\L__AG_MONUMENT_RACE_CANCEL.lua") + script = new AgMonumentRaceCancel(); + else if (scriptName == "scripts\\02_server\\Map\\AG_Spider_Queen\\L_ZONE_AG_SPIDER_QUEEN.lua") + script = (ZoneAgProperty*)new ZoneAgSpiderQueen(); + else if (scriptName == "scripts\\02_server\\Map\\AG_Spider_Queen\\L_SPIDER_BOSS_TREASURE_CHEST_SERVER.lua") + script = new SpiderBossTreasureChestServer(); else if (scriptName == "scripts\\02_server\\Map\\AG\\L_NPC_COWBOY_SERVER.lua") script = new NpcCowboyServer(); else if (scriptName == "scripts\\02_server\\Map\\Property\\AG_Med\\L_ZONE_AG_MED_PROPERTY.lua") - script = new ZoneAgMedProperty(); + script = new ZoneAgMedProperty(); else if (scriptName == "scripts\\ai\\AG\\L_AG_STROMBIE_PROPERTY.lua") - script = new AgStromlingProperty(); + script = new AgStromlingProperty(); else if (scriptName == "scripts\\ai\\AG\\L_AG_DARKLING_MECH.lua") - script = new BaseEnemyMech(); + script = new BaseEnemyMech(); else if (scriptName == "scripts\\ai\\AG\\L_AG_DARK_SPIDERLING.lua") - script = new AgDarkSpiderling(); + script = new AgDarkSpiderling(); else if (scriptName == "scripts\\ai\\PROPERTY\\L_PROP_GUARDS.lua") - script = new AgPropguards(); + script = new AgPropguards(); else if (scriptName == "scripts\\ai\\PROPERTY\\L_PROPERTY_FX_DAMAGE.lua") - script = new PropertyFXDamage(); + script = new PropertyFXDamage(); else if (scriptName == "scripts\\02_server\\Map\\AG\\L_NPC_PIRATE_SERVER.lua") - script = new NpcPirateServer(); + script = new NpcPirateServer(); else if (scriptName == "scripts\\ai\\AG\\L_AG_PICNIC_BLANKET.lua") - script = new AgPicnicBlanket(); + script = new AgPicnicBlanket(); else if (scriptName == "scripts\\02_server\\Map\\Property\\L_PROPERTY_BANK_INTERACT_SERVER.lua") - script = new PropertyBankInteract(); - else if (scriptName == "scripts\\02_server\\Enemy\\VE\\L_VE_MECH.lua") - script = new VeMech(); - else if (scriptName == "scripts\\02_server\\Map\\VE\\L_MISSION_CONSOLE_SERVER.lua") - script = new VeMissionConsole(); - else if (scriptName == "scripts\\02_server\\Map\\VE\\L_EPSILON_SERVER.lua") - script = new VeEpsilonServer(); + script = new PropertyBankInteract(); + else if (scriptName == "scripts\\02_server\\Enemy\\VE\\L_VE_MECH.lua") + script = new VeMech(); + else if (scriptName == "scripts\\02_server\\Map\\VE\\L_MISSION_CONSOLE_SERVER.lua") + script = new VeMissionConsole(); + else if (scriptName == "scripts\\02_server\\Map\\VE\\L_EPSILON_SERVER.lua") + script = new VeEpsilonServer(); // Win32 thinks this if chain is too long, let's cut it up and serve it as a three course meal //NS: if (scriptName == "scripts\\ai\\NS\\L_NS_MODULAR_BUILD.lua") @@ -418,45 +418,45 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\ai\\NS\\L_NS_QB_IMAGINATION_STATUE.lua") script = new NsQbImaginationStatue(); else if (scriptName == "scripts\\02_server\\Map\\NS\\CONCERT_CHOICEBUILD_MANAGER_SERVER.lua") - script = new NsConcertChoiceBuildManager(); + script = new NsConcertChoiceBuildManager(); else if (scriptName == "scripts\\ai\\NS\\L_NS_CONCERT_CHOICEBUILD.lua") - script = new NsConcertChoiceBuild(); + script = new NsConcertChoiceBuild(); else if (scriptName == "scripts\\ai\\NS\\L_NS_CONCERT_QUICKBUILD.lua") - script = new NsConcertQuickBuild(); + script = new NsConcertQuickBuild(); else if (scriptName == "scripts\\ai\\AG\\L_AG_STAGE_PLATFORMS.lua") - script = new AgStagePlatforms(); + script = new AgStagePlatforms(); else if (scriptName == "scripts\\ai\\NS\\L_NS_CONCERT_INSTRUMENT_QB.lua") - script = new NsConcertInstrument(); + script = new NsConcertInstrument(); else if (scriptName == "scripts\\ai\\NS\\L_NS_JONNY_FLAG_MISSION_SERVER.lua") - script = new NsJohnnyMissionServer(); + script = new NsJohnnyMissionServer(); else if (scriptName == "scripts\\02_server\\Objects\\L_STINKY_FISH_TARGET.lua") - script = new StinkyFishTarget(); + script = new StinkyFishTarget(); else if (scriptName == "scripts\\zone\\PROPERTY\\NS\\L_ZONE_NS_PROPERTY.lua") - script = new ZoneNsProperty(); + script = new ZoneNsProperty(); else if (scriptName == "scripts\\02_server\\Map\\Property\\NS_Med\\L_ZONE_NS_MED_PROPERTY.lua") - script = new ZoneNsMedProperty(); + script = new ZoneNsMedProperty(); else if (scriptName == "scripts\\02_server\\Map\\NS\\L_NS_TOKEN_CONSOLE_SERVER.lua") script = new NsTokenConsoleServer(); else if (scriptName == "scripts\\02_server\\Map\\NS\\L_NS_LUP_TELEPORT.lua") script = new NsLupTeleport(); else if (scriptName == "scripts\\02_server\\Map\\NS\\Waves\\L_ZONE_NS_WAVES.lua") - script = new ZoneNsWaves(); + script = new ZoneNsWaves(); else if (scriptName == "scripts\\02_server\\Enemy\\Waves\\L_WAVES_BOSS_HAMMERLING_ENEMY_SERVER.lua") - script = new WaveBossHammerling(); + script = new WaveBossHammerling(); else if (scriptName == "scripts\\02_server\\Enemy\\Waves\\L_WAVES_BOSS_APE_ENEMY_SERVER.lua") - script = (BaseEnemyApe*) new WaveBossApe(); + script = (BaseEnemyApe*) new WaveBossApe(); else if (scriptName == "scripts\\02_server\\Enemy\\Waves\\L_WAVES_BOSS_DARK_SPIDERLING_ENEMY_SERVER.lua") - script = new WaveBossSpiderling(); + script = new WaveBossSpiderling(); else if (scriptName == "scripts\\02_server\\Enemy\\Waves\\L_WAVES_BOSS_HORESEMEN_ENEMY_SERVER.lua") - script = new WaveBossHorsemen(); + script = new WaveBossHorsemen(); else if (scriptName == "scripts\\02_server\\Minigame\\General\\L_MINIGAME_TREASURE_CHEST_SERVER.lua") - script = new MinigameTreasureChestServer(); + script = new MinigameTreasureChestServer(); else if (scriptName == "scripts\\02_server\\Map\\NS\\L_NS_LEGO_CLUB_DOOR.lua") - script = new NsLegoClubDoor(); + script = new NsLegoClubDoor(); else if (scriptName == "scripts/ai/NS/L_CL_RING.lua") - script = new ClRing(); + script = new ClRing(); else if (scriptName == "scripts\\ai\\WILD\\L_WILD_AMBIENTS.lua") - script = new WildAmbients(); + script = new WildAmbients(); else if (scriptName == "scripts\\ai\\NS\\NS_PP_01\\L_NS_PP_01_TELEPORT.lua") script = new PropertyDeathPlane(); @@ -484,7 +484,7 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Map\\General\\L_QB_ENEMY_STUNNER.lua") script = new QbEnemyStunner(); else if (scriptName == "scripts\\ai\\GF\\L_GF_PET_DIG_BUILD.lua") - script = new PetDigBuild(); // Technically also used once in AG + script = new PetDigBuild(); // Technically also used once in AG else if (scriptName == "scripts\\02_server\\Map\\GF\\L_SPAWN_LION_SERVER.lua") script = new SpawnLionServer(); else if (scriptName == "scripts\\02_server\\Enemy\\General\\L_BASE_ENEMY_APE.lua") @@ -492,13 +492,13 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Enemy\\General\\L_GF_APE_SMASHING_QB.lua") script = new GfApeSmashingQB(); else if (scriptName == "scripts\\zone\\PROPERTY\\GF\\L_ZONE_GF_PROPERTY.lua") - script = new ZoneGfProperty(); + script = new ZoneGfProperty(); // SG else if (scriptName == "scripts\\ai\\MINIGAME\\SG_GF\\SERVER\\SG_CANNON.lua") - script = new SGCannon(); + script = new SGCannon(); else if (scriptName == "scripts\\ai\\MINIGAME\\SG_GF\\L_ZONE_SG_SERVER.lua") - script = new ZoneSGServer(); + script = new ZoneSGServer(); //PR: else if (scriptName == "scripts\\client\\ai\\PR\\L_PR_WHISTLE.lua") @@ -511,16 +511,16 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new HydrantBroken(); else if (scriptName == "scripts\\02_server\\Map\\General\\PET_DIG_SERVER.lua" || scriptName == "scripts\\02_server\\Map\\AM\\L_SKELETON_DRAGON_PET_DIG_SERVER.lua") script = new PetDigServer(); - else if (scriptName == "scripts\\client\\ai\\PR\\L_CRAB_SERVER.lua") - script = new CrabServer(); - else if (scriptName == "scripts\\02_server\\Pets\\L_PET_FROM_DIG_SERVER.lua") - script = new PetFromDigServer(); - else if (scriptName == "scripts\\02_server\\Pets\\L_PET_FROM_OBJECT_SERVER.lua") - script = new PetFromObjectServer(); - else if (scriptName == "scripts\\02_server\\Pets\\L_DAMAGING_PET.lua") - script = new DamagingPets(); - else if (scriptName == "scripts\\02_server\\Map\\PR\\L_SPAWN_GRYPHON_SERVER.lua") - script = new SpawnGryphonServer(); + else if (scriptName == "scripts\\client\\ai\\PR\\L_CRAB_SERVER.lua") + script = new CrabServer(); + else if (scriptName == "scripts\\02_server\\Pets\\L_PET_FROM_DIG_SERVER.lua") + script = new PetFromDigServer(); + else if (scriptName == "scripts\\02_server\\Pets\\L_PET_FROM_OBJECT_SERVER.lua") + script = new PetFromObjectServer(); + else if (scriptName == "scripts\\02_server\\Pets\\L_DAMAGING_PET.lua") + script = new DamagingPets(); + else if (scriptName == "scripts\\02_server\\Map\\PR\\L_SPAWN_GRYPHON_SERVER.lua") + script = new SpawnGryphonServer(); //FV Scripts: else if (scriptName == "scripts\\02_server\\Map\\FV\\L_ACT_CANDLE.lua") @@ -544,13 +544,13 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\ai\\GENERAL\\L_INSTANCE_EXIT_TRANSFER_PLAYER_TO_LAST_NON_INSTANCE.lua") script = new InstanceExitTransferPlayerToLastNonInstance(); else if (scriptName == "scripts\\ai\\FV\\L_NPC_FREE_GF_NINJAS.lua") - script = new FvFreeGfNinjas(); + script = new FvFreeGfNinjas(); else if (scriptName == "scripts\\ai\\FV\\L_FV_PANDA_SPAWNER_SERVER.lua") - script = new FvPandaSpawnerServer(); + script = new FvPandaSpawnerServer(); else if (scriptName == "scripts\\ai\\FV\\L_FV_PANDA_SERVER.lua") - script = new FvPandaServer(); - else if (scriptName == "scripts\\zone\\PROPERTY\\FV\\L_ZONE_FV_PROPERTY.lua") - script = new ZoneFvProperty(); + script = new FvPandaServer(); + else if (scriptName == "scripts\\zone\\PROPERTY\\FV\\L_ZONE_FV_PROPERTY.lua") + script = new ZoneFvProperty(); else if (scriptName == "scripts\\ai\\FV\\L_FV_BRICK_PUZZLE_SERVER.lua") script = new FvBrickPuzzleServer(); else if (scriptName == "scripts\\ai\\FV\\L_FV_CONSOLE_LEFT_QUICKBUILD.lua") @@ -579,16 +579,16 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new WishingWellServer(); else if (scriptName == "scripts\\ai\\ACT\\L_ACT_PLAYER_DEATH_TRIGGER.lua") script = new ActPlayerDeathTrigger(); - else if (scriptName == "scripts\\02_server\\Map\\General\\L_GROWING_FLOWER_SERVER.lua") - script = new GrowingFlower(); + else if (scriptName == "scripts\\02_server\\Map\\General\\L_GROWING_FLOWER_SERVER.lua") + script = new GrowingFlower(); else if (scriptName == "scripts\\02_server\\Map\\General\\L_TOKEN_CONSOLE_SERVER.lua") script = new TokenConsoleServer(); - else if (scriptName == "scripts\\ai\\ACT\\FootRace\\L_ACT_BASE_FOOT_RACE.lua") - script = new BaseFootRaceManager(); - else if (scriptName == "scripts\\02_server\\Map\\General\\L_PROP_PLATFORM.lua") - script = new PropertyPlatform(); - else if (scriptName == "scripts\\02_server\\Map\\VE\\L_VE_BRICKSAMPLE_SERVER.lua") - return new VeBricksampleServer(); + else if (scriptName == "scripts\\ai\\ACT\\FootRace\\L_ACT_BASE_FOOT_RACE.lua") + script = new BaseFootRaceManager(); + else if (scriptName == "scripts\\02_server\\Map\\General\\L_PROP_PLATFORM.lua") + script = new PropertyPlatform(); + else if (scriptName == "scripts\\02_server\\Map\\VE\\L_VE_BRICKSAMPLE_SERVER.lua") + return new VeBricksampleServer(); else if (scriptName == "scripts\\02_server\\Map\\General\\L_MAIL_BOX_SERVER.lua") script = new MailBoxServer(); else if (scriptName == "scripts\\ai\\ACT\\L_ACT_MINE.lua") @@ -604,9 +604,9 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Map\\FV\\Racing\\RACE_MAELSTROM_GEISER.lua") script = new RaceMaelstromGeiser(); else if (scriptName == "scripts\\ai\\RACING\\OBJECTS\\FV_RACE_SMASH_EGG_IMAGINE_SERVER.lua") - script = new FvRaceSmashEggImagineServer(); + script = new FvRaceSmashEggImagineServer(); else if (scriptName == "scripts\\ai\\RACING\\OBJECTS\\RACE_SMASH_SERVER.lua") - script = new RaceSmashServer(); + script = new RaceSmashServer(); //NT: else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_SENTINELWALKWAY_SERVER.lua") @@ -642,19 +642,19 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_CONSOLE_TELEPORT_SERVER.lua") script = new NtConsoleTeleportServer(); else if (scriptName == "scripts\\02_server\\Map\\NT\\L_SPAWN_STEGO_SERVER.lua") - script = new SpawnStegoServer(); + script = new SpawnStegoServer(); else if (scriptName == "scripts\\02_server\\Map\\NT\\L_SPAWN_SABERCAT_SERVER.lua") - script = new SpawnSaberCatServer(); + script = new SpawnSaberCatServer(); else if (scriptName == "scripts\\02_server\\Map\\NT\\L_SPAWN_SHRAKE_SERVER.lua") - script = new SpawnShrakeServer(); - else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_DUKE_SERVER.lua") - script = new NtDukeServer(); - else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_HAEL_SERVER.lua") - script = new NtHaelServer(); - else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_OVERBUILD_SERVER.lua") - script = new NtOverbuildServer(); - else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_VANDA_SERVER.lua") - script = new NtVandaServer(); + script = new SpawnShrakeServer(); + else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_DUKE_SERVER.lua") + script = new NtDukeServer(); + else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_HAEL_SERVER.lua") + script = new NtHaelServer(); + else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_OVERBUILD_SERVER.lua") + script = new NtOverbuildServer(); + else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_VANDA_SERVER.lua") + script = new NtVandaServer(); else if (scriptName == "scripts\\02_server\\Map\\General\\L_FORCE_VOLUME_SERVER.lua") script = new ForceVolumeServer(); else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_XRAY_SERVER.lua") @@ -706,33 +706,33 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Enemy\\AM\\L_AM_DARKLING_APE.lua") script = new BaseEnemyApe(); else if (scriptName == "scripts\\02_server\\Map\\AM\\L_BLUE_X.lua") - script = new AmBlueX(); + script = new AmBlueX(); else if (scriptName == "scripts\\02_server\\Map\\AM\\L_TEAPOT_SERVER.lua") script = new AmTeapotServer(); // Ninjago else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_GARMADON_CELEBRATION_SERVER.lua") - script = new NjGarmadonCelebration(); - else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_WU_NPC.lua") - script = new NjWuNPC(); - else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_SCROLL_CHEST_SERVER.lua") - script = new NjScrollChestServer(); - else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_COLE_NPC.lua") - script = new NjColeNPC(); - else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_JAY_MISSION_ITEMS.lua") - script = (NjNPCMissionSpinjitzuServer*) new NjJayMissionItems(); - else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_NPC_MISSION_SPINJITZU_SERVER.lua") - script = new NjNPCMissionSpinjitzuServer(); + script = new NjGarmadonCelebration(); + else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_WU_NPC.lua") + script = new NjWuNPC(); + else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_SCROLL_CHEST_SERVER.lua") + script = new NjScrollChestServer(); + else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_COLE_NPC.lua") + script = new NjColeNPC(); + else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_JAY_MISSION_ITEMS.lua") + script = (NjNPCMissionSpinjitzuServer*) new NjJayMissionItems(); + else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_NPC_MISSION_SPINJITZU_SERVER.lua") + script = new NjNPCMissionSpinjitzuServer(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_ENEMY_SKELETON_SPAWNER.lua") script = new EnemySkeletonSpawner(); - else if (scriptName == "scripts\\02_server\\Map\\General\\L_NJ_RAIL_SWITCH.lua") - script = new NjRailSwitch(); - else if (scriptName == "scripts\\02_server\\Map\\General\\Ninjago\\L_RAIL_ACTIVATORS_SERVER.lua") - script = new NjRailActivatorsServer(); - else if (scriptName == "scripts\\02_server\\Map\\General\\Ninjago\\L_RAIL_POST_SERVER.lua") - script = new NjRailPostServer(); - else if (scriptName == "scripts\\02_server\\Map\\General\\Ninjago\\L_ICE_RAIL_ACTIVATOR_SERVER.lua") - script = new NjIceRailActivator(); + else if (scriptName == "scripts\\02_server\\Map\\General\\L_NJ_RAIL_SWITCH.lua") + script = new NjRailSwitch(); + else if (scriptName == "scripts\\02_server\\Map\\General\\Ninjago\\L_RAIL_ACTIVATORS_SERVER.lua") + script = new NjRailActivatorsServer(); + else if (scriptName == "scripts\\02_server\\Map\\General\\Ninjago\\L_RAIL_POST_SERVER.lua") + script = new NjRailPostServer(); + else if (scriptName == "scripts\\02_server\\Map\\General\\Ninjago\\L_ICE_RAIL_ACTIVATOR_SERVER.lua") + script = new NjIceRailActivator(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_FALLING_TILE.lua") script = new FallingTile(); else if (scriptName == "scripts\\02_server\\Enemy\\General\\L_ENEMY_NJ_BUFF_STUN_IMMUNITY.lua") @@ -746,7 +746,7 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_CAVE_PRISON_CAGE.lua") script = new CavePrisonCage(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\boss_instance\\L_MONASTERY_BOSS_INSTANCE_SERVER.lua") - script = new NjMonastryBossInstance(); + script = new NjMonastryBossInstance(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_CATAPULT_BOUNCER_SERVER.lua") script = new CatapultBouncerServer(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_CATAPULT_BASE_SERVER.lua") @@ -762,13 +762,13 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_BURNING_TILE.lua") script = new BurningTile(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_SPAWN_EARTH_PET_SERVER.lua") - script = new NjEarthDragonPetServer(); + script = new NjEarthDragonPetServer(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_EARTH_PET_SERVER.lua") - script = new NjEarthPetServer(); + script = new NjEarthPetServer(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_DRAGON_EMBLEM_CHEST_SERVER.lua") - script = new NjDragonEmblemChestServer(); + script = new NjDragonEmblemChestServer(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_NYA_MISSION_ITEMS.lua") - script = new NjNyaMissionitems(); + script = new NjNyaMissionitems(); //DLU: else if (scriptName == "scripts\\02_server\\DLU\\DLUVanityNPC.lua") @@ -776,35 +776,35 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr // Survival minigame else if (scriptName == "scripts\\02_server\\Enemy\\Survival\\L_AG_SURVIVAL_STROMBIE.lua") - script = new AgSurvivalStromling(); + script = new AgSurvivalStromling(); else if (scriptName == "scripts\\02_server\\Enemy\\Survival\\L_AG_SURVIVAL_DARKLING_MECH.lua") - script = new AgSurvivalMech(); + script = new AgSurvivalMech(); else if (scriptName == "scripts\\02_server\\Enemy\\Survival\\L_AG_SURVIVAL_DARK_SPIDERLING.lua") - script = new AgSurvivalSpiderling(); + script = new AgSurvivalSpiderling(); // Scripted equipment else if (scriptName == "scripts\\EquipmentScripts\\Sunflower.lua") - script = new Sunflower(); + script = new Sunflower(); else if (scriptName == "scripts/EquipmentScripts/AnvilOfArmor.lua") - script = new AnvilOfArmor(); + script = new AnvilOfArmor(); else if (scriptName == "scripts/EquipmentScripts/FountainOfImagination.lua") - script = new FountainOfImagination(); + script = new FountainOfImagination(); else if (scriptName == "scripts/EquipmentScripts/CauldronOfLife.lua") - script = new CauldronOfLife(); + script = new CauldronOfLife(); else if (scriptName == "scripts\\02_server\\Equipment\\L_BOOTYDIG_SERVER.lua") - script = new BootyDigServer(); + script = new BootyDigServer(); else if (scriptName == "scripts\\EquipmentScripts\\PersonalFortress.lua") script = new PersonalFortress(); else if (scriptName == "scripts\\02_server\\Map\\General\\L_PROPERTY_DEVICE.lua") - script = new PropertyDevice(); + script = new PropertyDevice(); else if (scriptName == "scripts\\02_server\\Map\\General\\L_IMAG_BACKPACK_HEALS_SERVER.lua") - script = new ImaginationBackpackHealServer(); + script = new ImaginationBackpackHealServer(); else if (scriptName == "scripts\\ai\\GENERAL\\L_LEGO_DIE_ROLL.lua") script = new LegoDieRoll(); - else if (scriptName == "scripts\\EquipmentScripts\\BuccaneerValiantShip.lua") - script = new BuccaneerValiantShip(); + else if (scriptName == "scripts\\EquipmentScripts\\BuccaneerValiantShip.lua") + script = new BuccaneerValiantShip(); else if (scriptName == "scripts\\EquipmentScripts\\FireFirstSkillonStartup.lua") - script = new FireFirstSkillonStartup(); + script = new FireFirstSkillonStartup(); // FB else if (scriptName == "scripts\\ai\\NS\\WH\\L_ROCKHYDRANT_BROKEN.lua") script = new RockHydrantBroken(); @@ -819,7 +819,7 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (script == invalidToReturn) { if (scriptName.length() > 0) Game::logger->LogDebug("CppScripts", "Attempted to load CppScript for '%s', but returned InvalidScript.", scriptName.c_str()); - // information not really needed for sys admins but is for developers + // information not really needed for sys admins but is for developers script = invalidToReturn; } diff --git a/dScripts/CppScripts.h b/dScripts/CppScripts.h index bf30017c..916d2638 100644 --- a/dScripts/CppScripts.h +++ b/dScripts/CppScripts.h @@ -11,15 +11,15 @@ class NiPoint3; namespace CppScripts { /** * Base class for all scripts. Includes virtual methods to be overridden to handle LUA equivelent events. - * + * * All methods pass 'self' as the first parameter, this is the associated parent entity for the event. * There will only ever be one instance of each script. - * + * * Do not use class members as entity specific variables unless you're sure there will only event be one instance of this script. * Do use class members as script wide variables, variables all entities which this script will access. - * + * * Use self->GetVar(u"variable_name") and self->SetVar(u"variable_name", value) to manage variables. - * + * * Designed to yield as close to a 1:1 mapping as possible with LUA. * There will be events which are not implemented or inheritetly LUA features not easily translated to C++. * Most of the time these can be worked around or ignored. @@ -31,79 +31,79 @@ namespace CppScripts { /** * Invoked one frame after the script is loaded. - * + * * Equivalent to 'function onStartup(self)' */ virtual void OnStartup(Entity* self) {}; /** * Invoked upon an entity entering the phantom collider on self. - * + * * Equivalent to 'function onCollisionPhantom(self, msg)' */ virtual void OnCollisionPhantom(Entity* self, Entity* target) {}; /** * Invoked when a player accepted a mission. - * + * * Equivalent to 'function onMissionDialogueOK(self, msg)' */ virtual void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) {}; /** * Invoked when the client or the server invoked an event server-side. - * + * * Equivalent to 'function onFireEventServerSide(self, msg)' */ - virtual void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) {}; + virtual void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) {}; /** * Invoked upon sending a object notification. - * + * * Equivalent to 'function onNotifyObject(self, msg)' */ - virtual void OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) {}; - + virtual void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) {}; + /** * Invoked upon a player exiting the modular build minigame. - * + * * Equivalent to 'function onModularBuildExit(self, msg)' */ virtual void OnModularBuildExit(Entity* self, Entity* player, bool bCompleted, std::vector modules) {}; - + /** * Invoked when a player has loaded into the zone. - * + * * Equivalent to 'function onPlayerLoaded(self, msg)' */ virtual void OnPlayerLoaded(Entity* self, Entity* player) {}; /** * Invoked when a player has died. - * + * * Equivalent to 'function onPlayerDied(self, msg)' */ virtual void OnPlayerDied(Entity* self, Entity* player) {}; /** * Invoked when a player has resurrected. - * + * * Equivalent to 'function onPlayerResurrected(self, msg)' */ virtual void OnPlayerResurrected(Entity* self, Entity* player) {}; /** * Invoked when a player has left the zone. - * + * * Equivalent to 'function onPlayerExit(self, msg)' */ virtual void OnPlayerExit(Entity* self, Entity* player) {}; /** * Invoked when a player has interacted with the proximity collider on self. - * + * * Equivalent to 'function onProximityUpdate(self, msg)' - * + * * @param name The name of the proximity collider recviving an interaction. * @param status "ENTER" if a player has entered the proximity collider; "LEAVE" if a player has left the proximity collider */ @@ -111,182 +111,182 @@ namespace CppScripts { /** * Invoked when a timer on self has expired. - * + * * Equivalent to 'function onTimerDone(self, msg)' */ virtual void OnTimerDone(Entity* self, std::string timerName) {}; /** * Invoked when a player interactions with self. - * + * * Equivalent to 'function onUse(self, msg)' */ virtual void OnUse(Entity* self, Entity* user) {}; /** * Invoked when self has died. - * + * * Equivalent to 'function onDie(self, msg)' */ virtual void OnDie(Entity* self, Entity* killer) {}; /** * Invoked when self has received a hit. - * + * * Equivalent to 'function onHit(self, msg)' */ virtual void OnHit(Entity* self, Entity* attacker) {}; /** * Invoked when self has received an emote from a player. - * + * * Equivalent to 'function onEmoteReceived(self, msg)' */ virtual void OnEmoteReceived(Entity* self, int32_t emote, Entity* target) {}; /** * Invoked when a player has started building this quickbuild. - * + * * Equivalent to 'function onRebuildStart(self, msg)' */ virtual void OnRebuildStart(Entity* self, Entity* target) {}; - + /** * Invoked when this quickbuild has changed state. - * + * * Equivalent to 'function onRebuildNotifyState(self, msg)' */ virtual void OnRebuildNotifyState(Entity* self, eRebuildState state) {}; /** * Invoked when this quickbuild has been completed. - * + * * Equivalent to 'function onRebuildComplete(self, msg)' */ virtual void OnRebuildComplete(Entity* self, Entity* target) {}; /** * Invoked when self has received either a hit or heal. - * + * * Equivalent to 'function onHitOrHealResult(self, msg)' */ virtual void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) {}; - + /** * Invoked when a player has responsed to a mission. - * + * * Equivalent to 'function onRespondToMission(self, msg)' */ virtual void OnRespondToMission(Entity* self, int missionID, Entity* player, int reward) {}; - + /** * Invoked once per frame. - * + * * No LUA eqivalent. */ virtual void OnUpdate(Entity* self) {}; - + /** * Invoked when this property has been rented. - * + * * Equivalent to 'function onZonePropertyRented(self, msg)' */ virtual void OnZonePropertyRented(Entity* self, Entity* renter) {}; - + /** * Invoked when a player has begun to edit this property. - * + * * Equivalent to 'function onZonePropertyEditBegin(self, msg)' */ virtual void OnZonePropertyEditBegin(Entity* self) {}; /** * Invoked when a player has concluded editing this property. - * + * * Equivalent to 'function onZonePropertyEditEnd(self, msg)' */ virtual void OnZonePropertyEditEnd(Entity* self) {}; /** * Invoked when a player has equipped a model while editing this property. - * + * * Equivalent to 'function onZonePropertyModelEquipped(self, msg)' */ virtual void OnZonePropertyModelEquipped(Entity* self) {}; /** * Invoked when a player has placed a model while editing this property. - * + * * Equivalent to 'function onZonePropertyModelPlaced(self, msg)' */ virtual void OnZonePropertyModelPlaced(Entity* self, Entity* player) {}; /** * Invoked when a player has picked up a model while editing this property. - * + * * Equivalent to 'function onZonePropertyModelPickedUp(self, msg)' */ virtual void OnZonePropertyModelPickedUp(Entity* self, Entity* player) {}; /** * Invoked when a player removed a model while editing this property. - * + * * Equivalent to 'function onZonePropertyModelRemoved(self, msg)' */ virtual void OnZonePropertyModelRemoved(Entity* self, Entity* player) {}; /** * Invoked when a player removed a model while holding it when editing this property. - * + * * Equivalent to 'function onZonePropertyModelRemoved(self, msg)' */ virtual void OnZonePropertyModelRemovedWhileEquipped(Entity* self, Entity* player) {}; - + /** * Invoked when a player rotated a model while editing this property. - * + * * Equivalent to 'function onZonePropertyModelRotated(self, msg)' */ virtual void OnZonePropertyModelRotated(Entity* self, Entity* player) {}; /** * Invoked when the pet taming minigame encounted an event. - * + * * Equivalent to 'function onNotifyPetTamingMinigame(self, msg)' */ virtual void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) {}; - + /** * Invoked when a player responded to a message box. - * + * * Equivalent to 'function onMessageBoxResponse(self, msg)' */ virtual void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) {}; - + /** * Invoked when a player responded to a choice box. - * + * * Equivalent to 'function onChoiceBoxResponse(self, msg)' */ virtual void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) {}; - + /** * Invoked when self arrived at a moving platform waypoint. - * + * * Equivalent to 'function onWaypointReached(self, msg)' */ virtual void OnWaypointReached(Entity* self, uint32_t waypointIndex) {}; - + /** * Invoked when a player fired a skill event on self. - * + * * Equivalent to 'function onSkillEventFired(self, msg)' */ virtual void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) {}; - + /** * Invoked when self casted a skill. - * + * * Equivalent to 'function onSkillCast(self, msg)' */ virtual void OnSkillCast(Entity* self, uint32_t skillID) {}; @@ -309,13 +309,15 @@ namespace CppScripts { * @param value2 some other value to represent the change * @param stringValue some string value to represent the change */ - virtual void OnActivityStateChangeRequest(Entity* self, const LWOOBJID senderID, const int32_t value1, - const int32_t value2, const std::u16string& stringValue) {}; + virtual void OnActivityStateChangeRequest(Entity* self, const LWOOBJID senderID, const int32_t value1, + const int32_t value2, const std::u16string& stringValue) { + }; virtual void OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, - float_t pathTime, float_t totalTime, int32_t waypoint) {}; + float_t pathTime, float_t totalTime, int32_t waypoint) { + }; }; Script* GetScript(Entity* parent, const std::string& scriptName); std::vector GetEntityScripts(Entity* entity); -}; \ No newline at end of file +}; diff --git a/dScripts/CrabServer.cpp b/dScripts/CrabServer.cpp index 7cab7fb5..890b8ed9 100644 --- a/dScripts/CrabServer.cpp +++ b/dScripts/CrabServer.cpp @@ -2,42 +2,42 @@ #include "PetComponent.h" void CrabServer::OnStartup(Entity* self) { - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwner() != nullptr) - return; + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwner() != nullptr) + return; - // Triggers the local crab script for taming etc. - auto tamer = self->GetVar(u"tamer"); - // Client compares this with player:GetID() which is a string, so we'll have to give it a string - self->SetNetworkVar(u"crabtamer", std::to_string(tamer)); + // Triggers the local crab script for taming etc. + auto tamer = self->GetVar(u"tamer"); + // Client compares this with player:GetID() which is a string, so we'll have to give it a string + self->SetNetworkVar(u"crabtamer", std::to_string(tamer)); - // Kill if the player decides that the crab is not worthy - self->AddTimer("killself", 45.0f); + // Kill if the player decides that the crab is not worthy + self->AddTimer("killself", 45.0f); } void CrabServer::OnTimerDone(Entity* self, std::string timerName) { - if (timerName == "killself") { + if (timerName == "killself") { - // Don't accidentally kill a pet that is already owned - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwner() != nullptr) - return; + // Don't accidentally kill a pet that is already owned + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwner() != nullptr) + return; - self->Smash(self->GetObjectID(), SILENT); - } + self->Smash(self->GetObjectID(), SILENT); + } } void CrabServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { - if (type == NOTIFY_TYPE_BEGIN) { - self->CancelTimer("killself"); - } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { - self->Smash(self->GetObjectID(), SILENT); - } else if (type == NOTIFY_TYPE_SUCCESS) { - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr) - 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); - } + if (type == NOTIFY_TYPE_BEGIN) { + self->CancelTimer("killself"); + } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { + self->Smash(self->GetObjectID(), SILENT); + } else if (type == NOTIFY_TYPE_SUCCESS) { + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr) + 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); + } } diff --git a/dScripts/CrabServer.h b/dScripts/CrabServer.h index b773ed75..28533cb5 100644 --- a/dScripts/CrabServer.h +++ b/dScripts/CrabServer.h @@ -4,7 +4,7 @@ class CrabServer : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; }; diff --git a/dScripts/DLUVanityNPC.cpp b/dScripts/DLUVanityNPC.cpp index c219a5f9..e3db2353 100644 --- a/dScripts/DLUVanityNPC.cpp +++ b/dScripts/DLUVanityNPC.cpp @@ -3,46 +3,44 @@ #include "dServer.h" #include "VanityUtilities.h" -void DLUVanityNPC::OnStartup(Entity* self) -{ - m_NPC = VanityUtilities::GetNPC("averysumner - Destroyer of Worlds"); +void DLUVanityNPC::OnStartup(Entity* self) { + m_NPC = VanityUtilities::GetNPC("averysumner - Destroyer of Worlds"); - if (m_NPC == nullptr) { - return; - } + if (m_NPC == nullptr) { + return; + } - if (self->GetVar(u"teleport")) { - self->AddTimer("setupTeleport", 15.0f); - } + if (self->GetVar(u"teleport")) { + self->AddTimer("setupTeleport", 15.0f); + } } -void DLUVanityNPC::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "setupTeleport") { - GameMessages::SendPlayAnimation(self, u"interact"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportBeam", "teleportBeam"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportRings", "teleportRings"); +void DLUVanityNPC::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "setupTeleport") { + GameMessages::SendPlayAnimation(self, u"interact"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportBeam", "teleportBeam"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportRings", "teleportRings"); - self->AddTimer("teleport", 2.0f); - self->AddTimer("stopFX", 2.0f); - } else if (timerName == "stopFX") { - GameMessages::SendStopFXEffect(self, true, "teleportBeam"); - GameMessages::SendStopFXEffect(self, true, "teleportRings"); - } else if (timerName == "teleport") { - std::vector& locations = m_NPC->m_Locations[Game::server->GetZoneID()]; + self->AddTimer("teleport", 2.0f); + self->AddTimer("stopFX", 2.0f); + } else if (timerName == "stopFX") { + GameMessages::SendStopFXEffect(self, true, "teleportBeam"); + GameMessages::SendStopFXEffect(self, true, "teleportRings"); + } else if (timerName == "teleport") { + std::vector& locations = m_NPC->m_Locations[Game::server->GetZoneID()]; -selectLocation: - VanityNPCLocation& newLocation = locations[GeneralUtils::GenerateRandomNumber(0, locations.size() - 1)]; + selectLocation: + VanityNPCLocation& newLocation = locations[GeneralUtils::GenerateRandomNumber(0, locations.size() - 1)]; - if (self->GetPosition() == newLocation.m_Position) { - goto selectLocation; // cry about it - } - - self->SetPosition(newLocation.m_Position); - self->SetRotation(newLocation.m_Rotation); - 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); - } + if (self->GetPosition() == newLocation.m_Position) { + goto selectLocation; // cry about it + } + + self->SetPosition(newLocation.m_Position); + self->SetRotation(newLocation.m_Rotation); + 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); + } } diff --git a/dScripts/DLUVanityNPC.h b/dScripts/DLUVanityNPC.h index 4eba3554..aeb8e051 100644 --- a/dScripts/DLUVanityNPC.h +++ b/dScripts/DLUVanityNPC.h @@ -5,9 +5,9 @@ class VanityNPC; class DLUVanityNPC : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - VanityNPC* m_NPC; + VanityNPC* m_NPC; }; diff --git a/dScripts/DamagingPets.cpp b/dScripts/DamagingPets.cpp index f82bc83e..f7eada00 100644 --- a/dScripts/DamagingPets.cpp +++ b/dScripts/DamagingPets.cpp @@ -4,142 +4,142 @@ #include "BaseCombatAIComponent.h" #include "RenderComponent.h" -void DamagingPets::OnStartup(Entity *self) { +void DamagingPets::OnStartup(Entity* self) { - // Make the pet hostile or non-hostile based on whether or not it is tamed - const auto* petComponent = self->GetComponent(); - if (petComponent != nullptr && petComponent->GetOwner() == nullptr) { - self->AddTimer("GoEvil", 0.5f); - } + // Make the pet hostile or non-hostile based on whether or not it is tamed + const auto* petComponent = self->GetComponent(); + if (petComponent != nullptr && petComponent->GetOwner() == nullptr) { + self->AddTimer("GoEvil", 0.5f); + } } -void DamagingPets::OnPlayerLoaded(Entity *self, Entity *player) { +void DamagingPets::OnPlayerLoaded(Entity* self, Entity* player) { - // Makes it so that new players also see the effect - self->AddCallbackTimer(2.5f, [self]() { - if (self != nullptr) { - const auto* petComponent = self->GetComponent(); - if (petComponent != nullptr && petComponent->GetOwner() == nullptr && self->GetVar(u"IsEvil")) { - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) { - auto counter = 1; - for (const auto petEffect : GetPetInfo(self).effect) { - renderComponent->PlayEffect(petEffect, u"create", "FXname" + std::to_string(counter)); - counter++; - } - } - } - } - }); + // Makes it so that new players also see the effect + self->AddCallbackTimer(2.5f, [self]() { + if (self != nullptr) { + const auto* petComponent = self->GetComponent(); + if (petComponent != nullptr && petComponent->GetOwner() == nullptr && self->GetVar(u"IsEvil")) { + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) { + auto counter = 1; + for (const auto petEffect : GetPetInfo(self).effect) { + renderComponent->PlayEffect(petEffect, u"create", "FXname" + std::to_string(counter)); + counter++; + } + } + } + } + }); } -void DamagingPets::OnNotifyPetTamingMinigame(Entity *self, Entity *tamer, eNotifyType type) { - switch (type) { - case NOTIFY_TYPE_SUCCESS: - case NOTIFY_TYPE_BEGIN: - self->CancelAllTimers(); - ClearEffects(self); - break; - case NOTIFY_TYPE_FAILED: - case NOTIFY_TYPE_QUIT: - { - self->SetNetworkVar(u"bIAmTamable", false); - self->AddTimer("GoEvil", 1.0f); - break; - } - default: - break; - } +void DamagingPets::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { + switch (type) { + case NOTIFY_TYPE_SUCCESS: + case NOTIFY_TYPE_BEGIN: + self->CancelAllTimers(); + ClearEffects(self); + break; + case NOTIFY_TYPE_FAILED: + case NOTIFY_TYPE_QUIT: + { + self->SetNetworkVar(u"bIAmTamable", false); + self->AddTimer("GoEvil", 1.0f); + break; + } + default: + break; + } } -void DamagingPets::OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) { - const auto infoForPet = GetPetInfo(self); - if (infoForPet.skill == message) { +void DamagingPets::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + const auto infoForPet = GetPetInfo(self); + if (infoForPet.skill == message) { - // Only make pets tamable that aren't tamed yet - const auto* petComponent = self->GetComponent(); - if (petComponent != nullptr && petComponent->GetOwner() == nullptr && self->GetVar(u"IsEvil")) { - ClearEffects(self); - self->AddTimer("GoEvil", 30.0f); - self->SetNetworkVar(u"bIAmTamable", true); - } - } + // Only make pets tamable that aren't tamed yet + const auto* petComponent = self->GetComponent(); + if (petComponent != nullptr && petComponent->GetOwner() == nullptr && self->GetVar(u"IsEvil")) { + ClearEffects(self); + self->AddTimer("GoEvil", 30.0f); + self->SetNetworkVar(u"bIAmTamable", true); + } + } } -void DamagingPets::OnTimerDone(Entity *self, std::string message) { - if (message == "GoEvil") { - MakeUntamable(self); - } +void DamagingPets::OnTimerDone(Entity* self, std::string message) { + if (message == "GoEvil") { + MakeUntamable(self); + } } -void DamagingPets::MakeUntamable(Entity *self) { - auto* petComponent = self->GetComponent(); +void DamagingPets::MakeUntamable(Entity* self) { + auto* petComponent = self->GetComponent(); - // If the pet is currently not being tamed, make it hostile - if (petComponent != nullptr && petComponent->GetStatus() != 5) { - self->SetNetworkVar(u"bIAmTamable", false); - self->SetVar(u"IsEvil", true); - petComponent->SetStatus(1); + // If the pet is currently not being tamed, make it hostile + if (petComponent != nullptr && petComponent->GetStatus() != 5) { + self->SetNetworkVar(u"bIAmTamable", false); + self->SetVar(u"IsEvil", true); + petComponent->SetStatus(1); - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(false); - } + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(false); + } - // Special faction that can attack the player but the player can't attack - auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetFaction(114); - destroyableComponent->SetHealth(5); - } + // Special faction that can attack the player but the player can't attack + auto* destroyableComponent = self->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetFaction(114); + destroyableComponent->SetHealth(5); + } - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) { - auto counter = 1; - for (const auto petEffect : GetPetInfo(self).effect) { - renderComponent->PlayEffect(petEffect, u"create", "FXname" + std::to_string(counter)); - counter++; - } - } - } + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) { + auto counter = 1; + for (const auto petEffect : GetPetInfo(self).effect) { + renderComponent->PlayEffect(petEffect, u"create", "FXname" + std::to_string(counter)); + counter++; + } + } + } } -void DamagingPets::ClearEffects(Entity *self) { - self->SetVar(u"IsEvil", false); +void DamagingPets::ClearEffects(Entity* self) { + self->SetVar(u"IsEvil", false); - auto* petComponent = self->GetComponent(); - if (petComponent != nullptr) { - petComponent->SetStatus(67108866); - } + auto* petComponent = self->GetComponent(); + if (petComponent != nullptr) { + petComponent->SetStatus(67108866); + } - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(true); - } + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(true); + } - auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetFaction(99); - } + auto* destroyableComponent = self->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetFaction(99); + } - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) { - auto counter = 1; - for (const auto petEffect : GetPetInfo(self).effect) { - renderComponent->StopEffect("FXname" + std::to_string(counter)); - counter++; - } - } + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) { + auto counter = 1; + for (const auto petEffect : GetPetInfo(self).effect) { + renderComponent->StopEffect("FXname" + std::to_string(counter)); + counter++; + } + } } -PetInfo DamagingPets::GetPetInfo(Entity *self) { - const auto infoForPet = petInfo.find(self->GetLOT()); - return infoForPet != petInfo.end() ? infoForPet->second : petInfo.begin()->second; +PetInfo DamagingPets::GetPetInfo(Entity* self) { + const auto infoForPet = petInfo.find(self->GetLOT()); + return infoForPet != petInfo.end() ? infoForPet->second : petInfo.begin()->second; } // Does not compile on Win32 with name specifiers const std::map DamagingPets::petInfo = { - { 5639, { /*.effect =*/ { 3170, 4058 }, /*.skill =*/ "waterspray"}}, // Red dragon - { 5641, { /*.effect =*/ { 3170, 4058 }, /*.skill =*/ "waterspray"}}, // Green dragon - { 3261, { /*.effect =*/ { 1490 }, /*.skill =*/ "waterspray"}}, // Skunk + { 5639, { /*.effect =*/ { 3170, 4058 }, /*.skill =*/ "waterspray"}}, // Red dragon + { 5641, { /*.effect =*/ { 3170, 4058 }, /*.skill =*/ "waterspray"}}, // Green dragon + { 3261, { /*.effect =*/ { 1490 }, /*.skill =*/ "waterspray"}}, // Skunk }; diff --git a/dScripts/DamagingPets.h b/dScripts/DamagingPets.h index 04c4e6bf..2ce0ddc1 100644 --- a/dScripts/DamagingPets.h +++ b/dScripts/DamagingPets.h @@ -5,20 +5,20 @@ * Information about pets regarding which effect to play when a skill is cast */ struct PetInfo { - const std::vector effect; - const std::string skill; + const std::vector effect; + const std::string skill; }; class DamagingPets : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string message) override; - void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; - void OnSkillEventFired(Entity* self, Entity* target, const std::string& message) override; - void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string message) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; + void OnSkillEventFired(Entity* self, Entity* target, const std::string& message) override; + void OnPlayerLoaded(Entity* self, Entity* player) override; private: - static void MakeUntamable(Entity* self); - static PetInfo GetPetInfo(Entity* self); - static void ClearEffects(Entity* self); - static const std::map petInfo; + static void MakeUntamable(Entity* self); + static PetInfo GetPetInfo(Entity* self); + static void ClearEffects(Entity* self); + static const std::map petInfo; }; diff --git a/dScripts/Darkitect.cpp b/dScripts/Darkitect.cpp index c4e1e45d..323d0247 100644 --- a/dScripts/Darkitect.cpp +++ b/dScripts/Darkitect.cpp @@ -5,8 +5,7 @@ #include "GameMessages.h" #include "Character.h" -void Darkitect::Reveal(Entity* self, Entity* player) -{ +void Darkitect::Reveal(Entity* self, Entity* player) { const auto playerID = player->GetObjectID(); GameMessages::SendNotifyClientObject(self->GetObjectID(), u"reveal", 0, 0, playerID, "", player->GetSystemAddress()); @@ -31,5 +30,5 @@ void Darkitect::Reveal(Entity* self, Entity* player) EntityManager::Instance()->SerializeEntity(player); } - }); + }); } diff --git a/dScripts/EnemyNjBuff.cpp b/dScripts/EnemyNjBuff.cpp index 8dd19cce..07b2d899 100644 --- a/dScripts/EnemyNjBuff.cpp +++ b/dScripts/EnemyNjBuff.cpp @@ -1,14 +1,12 @@ #include "EnemyNjBuff.h" #include "SkillComponent.h" -void EnemyNjBuff::OnStartup(Entity* self) -{ - auto* skillComponent = self->GetComponent(); +void EnemyNjBuff::OnStartup(Entity* self) { + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - skillComponent->CalculateBehavior(1127, 24812, self->GetObjectID(), true); + skillComponent->CalculateBehavior(1127, 24812, self->GetObjectID(), true); } diff --git a/dScripts/EnemyRoninSpawner.cpp b/dScripts/EnemyRoninSpawner.cpp index 25288968..b6cae3bb 100644 --- a/dScripts/EnemyRoninSpawner.cpp +++ b/dScripts/EnemyRoninSpawner.cpp @@ -3,78 +3,66 @@ #include "RenderComponent.h" #include "EntityManager.h" -void EnemyRoninSpawner::OnStartup(Entity* self) -{ - self->SetProximityRadius(15, "ronin"); +void EnemyRoninSpawner::OnStartup(Entity* self) { + self->SetProximityRadius(15, "ronin"); } -void EnemyRoninSpawner::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "hatchTime") - { - auto* renderComponent = self->GetComponent(); +void EnemyRoninSpawner::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "hatchTime") { + auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) - { - renderComponent->PlayEffect(644, u"create", "BurstFX1"); - } + if (renderComponent != nullptr) { + renderComponent->PlayEffect(644, u"create", "BurstFX1"); + } - EntityInfo info {}; - info.lot = 7815; - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = 7815; + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.spawnerID = self->GetObjectID(); - auto* spawnedEntity = EntityManager::Instance()->CreateEntity(info); + auto* spawnedEntity = EntityManager::Instance()->CreateEntity(info); - if (spawnedEntity == nullptr) - { - return; - } + if (spawnedEntity == nullptr) { + return; + } - EntityManager::Instance()->ConstructEntity(spawnedEntity); + EntityManager::Instance()->ConstructEntity(spawnedEntity); - spawnedEntity->AddCallbackTimer(60, [spawnedEntity]() { - spawnedEntity->Smash(spawnedEntity->GetObjectID()); - }); + spawnedEntity->AddCallbackTimer(60, [spawnedEntity]() { + spawnedEntity->Smash(spawnedEntity->GetObjectID()); + }); - self->Smash(self->GetObjectID()); - } + self->Smash(self->GetObjectID()); + } } -void EnemyRoninSpawner::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (entering->IsPlayer() && name == "ronin" && status == "ENTER" && !self->GetVar(u"hatching")) - { - StartHatching(self); +void EnemyRoninSpawner::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (entering->IsPlayer() && name == "ronin" && status == "ENTER" && !self->GetVar(u"hatching")) { + StartHatching(self); - auto* skillComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(305, 3568, LWOOBJID_EMPTY); - } - } + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(305, 3568, LWOOBJID_EMPTY); + } + } } -void EnemyRoninSpawner::OnHit(Entity* self, Entity* attacker) -{ - if (!self->GetVar(u"hatching")) - { - StartHatching(self); - } +void EnemyRoninSpawner::OnHit(Entity* self, Entity* attacker) { + if (!self->GetVar(u"hatching")) { + StartHatching(self); + } } -void EnemyRoninSpawner::StartHatching(Entity* self) -{ - self->SetVar(u"hatching", true); +void EnemyRoninSpawner::StartHatching(Entity* self) { + self->SetVar(u"hatching", true); - auto* renderComponent = self->GetComponent(); + auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) - { - renderComponent->PlayEffect(2260, u"rebuild_medium", "WakeUpFX1"); - } + if (renderComponent != nullptr) { + renderComponent->PlayEffect(2260, u"rebuild_medium", "WakeUpFX1"); + } - self->AddTimer("hatchTime", 2); + self->AddTimer("hatchTime", 2); } diff --git a/dScripts/EnemyRoninSpawner.h b/dScripts/EnemyRoninSpawner.h index 0b14d0cf..02990f36 100644 --- a/dScripts/EnemyRoninSpawner.h +++ b/dScripts/EnemyRoninSpawner.h @@ -5,8 +5,8 @@ class EnemyRoninSpawner final : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnTimerDone(Entity* self, std::string timerName) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnHit(Entity* self, Entity* attacker) override; - void StartHatching(Entity* self); + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnHit(Entity* self, Entity* attacker) override; + void StartHatching(Entity* self); }; diff --git a/dScripts/EnemySkeletonSpawner.cpp b/dScripts/EnemySkeletonSpawner.cpp index f8c89ec6..451fa1d5 100644 --- a/dScripts/EnemySkeletonSpawner.cpp +++ b/dScripts/EnemySkeletonSpawner.cpp @@ -3,86 +3,73 @@ #include "RenderComponent.h" #include "EntityManager.h" -void EnemySkeletonSpawner::OnStartup(Entity* self) -{ - self->SetProximityRadius(15, "ronin"); +void EnemySkeletonSpawner::OnStartup(Entity* self) { + self->SetProximityRadius(15, "ronin"); - auto* skillComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(1127, 24812, LWOOBJID_EMPTY, true); - } + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(1127, 24812, LWOOBJID_EMPTY, true); + } } -void EnemySkeletonSpawner::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "hatchTime") - { - auto* renderComponent = self->GetComponent(); +void EnemySkeletonSpawner::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "hatchTime") { + auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) - { - renderComponent->PlayEffect(644, u"create", "BurstFX1"); - } + if (renderComponent != nullptr) { + renderComponent->PlayEffect(644, u"create", "BurstFX1"); + } - EntityInfo info {}; - info.lot = 14024; - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = 14024; + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.spawnerID = self->GetObjectID(); - auto* spawnedEntity = EntityManager::Instance()->CreateEntity(info); + auto* spawnedEntity = EntityManager::Instance()->CreateEntity(info); - if (spawnedEntity == nullptr) - { - return; - } + if (spawnedEntity == nullptr) { + return; + } - EntityManager::Instance()->ConstructEntity(spawnedEntity); + EntityManager::Instance()->ConstructEntity(spawnedEntity); - spawnedEntity->AddCallbackTimer(60, [spawnedEntity]() { - spawnedEntity->Smash(spawnedEntity->GetObjectID()); - }); + spawnedEntity->AddCallbackTimer(60, [spawnedEntity]() { + spawnedEntity->Smash(spawnedEntity->GetObjectID()); + }); - self->Smash(self->GetObjectID()); - } + self->Smash(self->GetObjectID()); + } } -void EnemySkeletonSpawner::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (entering->IsPlayer() && name == "ronin" && status == "ENTER" && !self->GetVar(u"hatching")) - { - StartHatching(self); +void EnemySkeletonSpawner::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (entering->IsPlayer() && name == "ronin" && status == "ENTER" && !self->GetVar(u"hatching")) { + StartHatching(self); - auto* skillComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(305, 3568, LWOOBJID_EMPTY); - } - } + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(305, 3568, LWOOBJID_EMPTY); + } + } } -void EnemySkeletonSpawner::OnHit(Entity* self, Entity* attacker) -{ - if (!self->GetVar(u"hatching")) - { - StartHatching(self); - } +void EnemySkeletonSpawner::OnHit(Entity* self, Entity* attacker) { + if (!self->GetVar(u"hatching")) { + StartHatching(self); + } } -void EnemySkeletonSpawner::StartHatching(Entity* self) -{ - self->SetVar(u"hatching", true); +void EnemySkeletonSpawner::StartHatching(Entity* self) { + self->SetVar(u"hatching", true); - auto* renderComponent = self->GetComponent(); + auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) - { - renderComponent->PlayEffect(9017, u"cast", "WakeUpFX1"); - renderComponent->PlayEffect(9018, u"burst", "WakeUpFX1"); - } + if (renderComponent != nullptr) { + renderComponent->PlayEffect(9017, u"cast", "WakeUpFX1"); + renderComponent->PlayEffect(9018, u"burst", "WakeUpFX1"); + } - self->AddTimer("hatchTime", 2); + self->AddTimer("hatchTime", 2); } diff --git a/dScripts/EnemySkeletonSpawner.h b/dScripts/EnemySkeletonSpawner.h index a4a212d2..16bbfdd9 100644 --- a/dScripts/EnemySkeletonSpawner.h +++ b/dScripts/EnemySkeletonSpawner.h @@ -5,8 +5,8 @@ class EnemySkeletonSpawner final : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnTimerDone(Entity* self, std::string timerName) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnHit(Entity* self, Entity* attacker) override; - void StartHatching(Entity* self); + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnHit(Entity* self, Entity* attacker) override; + void StartHatching(Entity* self); }; diff --git a/dScripts/EnemySpiderSpawner.cpp b/dScripts/EnemySpiderSpawner.cpp index 98524ae1..96302a33 100644 --- a/dScripts/EnemySpiderSpawner.cpp +++ b/dScripts/EnemySpiderSpawner.cpp @@ -6,22 +6,22 @@ //---------------------------------------------- //--Initiate egg hatching on call //---------------------------------------------- -void EnemySpiderSpawner::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { +void EnemySpiderSpawner::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { if (args == "prepEgg") { // Highlight eggs about to hatch with Maelstrom effect GameMessages::SendPlayFXEffect(self->GetObjectID(), 2856, u"maelstrom", "test", LWOOBJID_EMPTY, 1.0f, 1.0f, true); - + // Make indestructible auto dest = static_cast(self->GetComponent(COMPONENT_TYPE_DESTROYABLE)); if (dest) { dest->SetFaction(-1); } EntityManager::Instance()->SerializeEntity(self); - + // Keep track of who prepped me self->SetI64(u"SpawnOwner", sender->GetObjectID()); - + } else if (args == "hatchEgg") { // Final countdown to pop self->AddTimer("StartSpawnTime", hatchTime); @@ -36,10 +36,10 @@ void EnemySpiderSpawner::OnTimerDone(Entity* self, std::string timerName) { SpawnSpiderling(self); } else if (timerName == "SpawnSpiderling") { GameMessages::SendPlayFXEffect(self->GetObjectID(), 644, u"create", "egg_puff_b", LWOOBJID_EMPTY, 1.0f, 1.0f, true); - + //TODO: set the aggro radius larger - EntityInfo info {}; + EntityInfo info{}; info.lot = 16197; info.pos = self->GetPosition(); info.spawner = nullptr; @@ -59,7 +59,7 @@ void EnemySpiderSpawner::OnTimerDone(Entity* self, std::string timerName) { } self->ScheduleKillAfterUpdate(); - } + } } //-------------------------------------------------------------- diff --git a/dScripts/EnemySpiderSpawner.h b/dScripts/EnemySpiderSpawner.h index def08ab1..f850a6eb 100644 --- a/dScripts/EnemySpiderSpawner.h +++ b/dScripts/EnemySpiderSpawner.h @@ -16,8 +16,8 @@ class EnemySpiderSpawner final : public CppScripts::Script { public: - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; void OnTimerDone(Entity* self, std::string timerName) override; private: diff --git a/dScripts/ExplodingAsset.cpp b/dScripts/ExplodingAsset.cpp index b4bd6913..46ff1522 100644 --- a/dScripts/ExplodingAsset.cpp +++ b/dScripts/ExplodingAsset.cpp @@ -26,7 +26,7 @@ void ExplodingAsset::OnHit(Entity* self, Entity* attacker) { if (destroyable == nullptr) { continue; } - + destroyable->Smash(attacker->GetObjectID()); } } @@ -49,26 +49,25 @@ void ExplodingAsset::OnHit(Entity* self, Entity* attacker) { // Progress all scripted missions related to this asset auto* missionComponent = attacker->GetComponent(); if (missionComponent != nullptr) { - if (missionID != 0) { - missionComponent->ForceProgressValue(missionID, - static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), - self->GetLOT(), false); - } + if (missionID != 0) { + missionComponent->ForceProgressValue(missionID, + static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), + self->GetLOT(), false); + } - if (!achievementIDs.empty()) { - for (const auto& achievementID : GeneralUtils::SplitString(achievementIDs, u'_')) { - missionComponent->ForceProgressValue(std::stoi(GeneralUtils::UTF16ToWTF8(achievementID)), - static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), - self->GetLOT()); - } - } + if (!achievementIDs.empty()) { + for (const auto& achievementID : GeneralUtils::SplitString(achievementIDs, u'_')) { + missionComponent->ForceProgressValue(std::stoi(GeneralUtils::UTF16ToWTF8(achievementID)), + static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), + self->GetLOT()); + } + } } self->ScheduleKillAfterUpdate(); } -void ExplodingAsset::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ +void ExplodingAsset::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { /* if msg.objId:BelongsToFaction{factionID = 1}.bIsInFaction then if (msg.status == "ENTER") then @@ -94,21 +93,17 @@ void ExplodingAsset::OnProximityUpdate(Entity* self, Entity* entering, std::stri if (!std::count(factions.begin(), factions.end(), 1)) return; - if (status == "ENTER") - { + if (status == "ENTER") { GameMessages::SendPlayAnimation(self, u"bounce"); GameMessages::SendPlayFXEffect(self, -1, u"anim", "bouncin", LWOOBJID_EMPTY, 1, 1, true); self->SetVar(u"playersNearChest", self->GetVar(u"playersNearChest") + 1); - } - else if (status == "LEAVE") - { + } else if (status == "LEAVE") { self->SetVar(u"playersNearChest", self->GetVar(u"playersNearChest") - 1); - if (self->GetVar(u"playersNearChest") < 1) - { + if (self->GetVar(u"playersNearChest") < 1) { GameMessages::SendPlayAnimation(self, u"idle"); GameMessages::SendStopFXEffect(self, true, "bouncin"); self->SetVar(u"playersNearChest", 0); } } -} \ No newline at end of file +} diff --git a/dScripts/ExplodingAsset.h b/dScripts/ExplodingAsset.h index bd2c2544..9b97ecc7 100644 --- a/dScripts/ExplodingAsset.h +++ b/dScripts/ExplodingAsset.h @@ -7,4 +7,4 @@ public: void OnStartup(Entity* self); void OnHit(Entity* self, Entity* attacker); void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status); -}; \ No newline at end of file +}; diff --git a/dScripts/FallingTile.cpp b/dScripts/FallingTile.cpp index 2dd8c7bc..7804c8bc 100644 --- a/dScripts/FallingTile.cpp +++ b/dScripts/FallingTile.cpp @@ -2,67 +2,54 @@ #include "MovingPlatformComponent.h" #include "GameMessages.h" -void FallingTile::OnStartup(Entity* self) -{ - auto* movingPlatfromComponent = self->GetComponent(); +void FallingTile::OnStartup(Entity* self) { + auto* movingPlatfromComponent = self->GetComponent(); - if (movingPlatfromComponent == nullptr) - { - return; - } + if (movingPlatfromComponent == nullptr) { + return; + } - movingPlatfromComponent->SetSerialized(true); + movingPlatfromComponent->SetSerialized(true); } -void FallingTile::OnCollisionPhantom(Entity* self, Entity* target) -{ - if (self->GetVar(u"AboutToFall")) - { - return; - } +void FallingTile::OnCollisionPhantom(Entity* self, Entity* target) { + if (self->GetVar(u"AboutToFall")) { + return; + } - self->AddTimer("flipTime", 0.75f); + self->AddTimer("flipTime", 0.75f); - self->SetVar(u"AboutToFall", true); + self->SetVar(u"AboutToFall", true); - self->SetNetworkVar(u"startEffect", 2); + self->SetNetworkVar(u"startEffect", 2); } -void FallingTile::OnWaypointReached(Entity* self, uint32_t waypointIndex) -{ - if (waypointIndex == 1) - { - } - else if (waypointIndex == 0) - { - } +void FallingTile::OnWaypointReached(Entity* self, uint32_t waypointIndex) { + if (waypointIndex == 1) { + } else if (waypointIndex == 0) { + } } -void FallingTile::OnTimerDone(Entity* self, std::string timerName) -{ - auto* movingPlatfromComponent = self->GetComponent(); +void FallingTile::OnTimerDone(Entity* self, std::string timerName) { + auto* movingPlatfromComponent = self->GetComponent(); - if (movingPlatfromComponent == nullptr) - { - return; - } + if (movingPlatfromComponent == nullptr) { + return; + } - if (timerName == "flipTime") - { - self->AddTimer("flipBack", 2.0f); + if (timerName == "flipTime") { + self->AddTimer("flipBack", 2.0f); - self->SetNetworkVar(u"stopEffect", 3); + self->SetNetworkVar(u"stopEffect", 3); - movingPlatfromComponent->GotoWaypoint(1); + movingPlatfromComponent->GotoWaypoint(1); - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"down", "down"); - } - else if (timerName == "flipBack") - { - self->SetVar(u"AboutToFall", false); + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"down", "down"); + } else if (timerName == "flipBack") { + self->SetVar(u"AboutToFall", false); - movingPlatfromComponent->GotoWaypoint(0); - - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"up", "up"); - } + movingPlatfromComponent->GotoWaypoint(0); + + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"up", "up"); + } } diff --git a/dScripts/FallingTile.h b/dScripts/FallingTile.h index 073fc403..bac1c73b 100644 --- a/dScripts/FallingTile.h +++ b/dScripts/FallingTile.h @@ -5,7 +5,7 @@ class FallingTile : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnCollisionPhantom(Entity* self, Entity* target) override; - void OnWaypointReached(Entity* self, uint32_t waypointIndex) override; - void OnTimerDone(Entity* self, std::string timerName) override; -}; \ No newline at end of file + void OnCollisionPhantom(Entity* self, Entity* target) override; + void OnWaypointReached(Entity* self, uint32_t waypointIndex) override; + void OnTimerDone(Entity* self, std::string timerName) override; +}; diff --git a/dScripts/FireFirstSkillonStartup.cpp b/dScripts/FireFirstSkillonStartup.cpp index da1b420e..cd0d94f2 100644 --- a/dScripts/FireFirstSkillonStartup.cpp +++ b/dScripts/FireFirstSkillonStartup.cpp @@ -5,20 +5,20 @@ #include "CDObjectSkillsTable.h" void FireFirstSkillonStartup::OnStartup(Entity* self) { - auto skillComponent = self->GetComponent(); - if (!skillComponent) return; + auto skillComponent = self->GetComponent(); + if (!skillComponent) return; - // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance()->GetTable("ObjectSkills"); - std::vector skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); + // Get the skill IDs of this object. + CDObjectSkillsTable* skillsTable = CDClientManager::Instance()->GetTable("ObjectSkills"); + 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("SkillBehavior"); + // For each skill, cast it with the associated behavior ID. + for (auto skill : skills) { + CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance()->GetTable("SkillBehavior"); CDSkillBehavior behaviorData = skillBehaviorTable->GetSkillByID(skill.skillID); - // Should parent entity be null, make the originator self. - const auto target = self->GetParentEntity() ? self->GetParentEntity()->GetObjectID() : self->GetObjectID(); - skillComponent->CalculateBehavior(skill.skillID, behaviorData.behaviorID, LWOOBJID_EMPTY, false, false, target); - } -} \ No newline at end of file + // Should parent entity be null, make the originator self. + const auto target = self->GetParentEntity() ? self->GetParentEntity()->GetObjectID() : self->GetObjectID(); + skillComponent->CalculateBehavior(skill.skillID, behaviorData.behaviorID, LWOOBJID_EMPTY, false, false, target); + } +} diff --git a/dScripts/FireFirstSkillonStartup.h b/dScripts/FireFirstSkillonStartup.h index ad182e70..6b10f362 100644 --- a/dScripts/FireFirstSkillonStartup.h +++ b/dScripts/FireFirstSkillonStartup.h @@ -5,8 +5,8 @@ #include "CppScripts.h" class FireFirstSkillonStartup : public CppScripts::Script { - public: - void OnStartup(Entity* self) override; +public: + void OnStartup(Entity* self) override; }; #endif //!__FIREFIRSTSKILLONSTARTUP__H__ diff --git a/dScripts/FlameJetServer.cpp b/dScripts/FlameJetServer.cpp index 936f2a94..771dd841 100644 --- a/dScripts/FlameJetServer.cpp +++ b/dScripts/FlameJetServer.cpp @@ -2,56 +2,46 @@ #include "SkillComponent.h" #include "GameMessages.h" -void FlameJetServer::OnStartup(Entity* self) -{ - if (self->GetVar(u"NotActive")) - { - return; - } +void FlameJetServer::OnStartup(Entity* self) { + if (self->GetVar(u"NotActive")) { + return; + } - self->SetNetworkVar(u"FlameOn", true); + self->SetNetworkVar(u"FlameOn", true); } -void FlameJetServer::OnCollisionPhantom(Entity* self, Entity* target) -{ - if (!target->IsPlayer()) - { - return; - } +void FlameJetServer::OnCollisionPhantom(Entity* self, Entity* target) { + if (!target->IsPlayer()) { + return; + } - if (!self->GetNetworkVar(u"FlameOn")) - { - return; - } + if (!self->GetNetworkVar(u"FlameOn")) { + return; + } - auto* skillComponent = target->GetComponent(); + auto* skillComponent = target->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - skillComponent->CalculateBehavior(726, 11723, target->GetObjectID(), true); + skillComponent->CalculateBehavior(726, 11723, target->GetObjectID(), true); - auto dir = target->GetRotation().GetForwardVector(); + auto dir = target->GetRotation().GetForwardVector(); - dir.y = 25; - dir.x = -dir.x * 15; - dir.z = -dir.z * 15; + dir.y = 25; + dir.x = -dir.x * 15; + dir.z = -dir.z * 15; - GameMessages::SendKnockback(target->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 1000, dir); + GameMessages::SendKnockback(target->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 1000, dir); } -void FlameJetServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - Game::logger->Log("FlameJetServer::OnFireEventServerSide", "Event: %s", args.c_str()); +void FlameJetServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + Game::logger->Log("FlameJetServer::OnFireEventServerSide", "Event: %s", args.c_str()); - if (args == "OnActivated") - { - self->SetNetworkVar(u"FlameOn", false); - } - else if (args == "OnDectivated") - { - self->SetNetworkVar(u"FlameOn", true); - } + if (args == "OnActivated") { + self->SetNetworkVar(u"FlameOn", false); + } else if (args == "OnDectivated") { + self->SetNetworkVar(u"FlameOn", true); + } } diff --git a/dScripts/FlameJetServer.h b/dScripts/FlameJetServer.h index 4f815d63..e8123c43 100644 --- a/dScripts/FlameJetServer.h +++ b/dScripts/FlameJetServer.h @@ -5,6 +5,6 @@ class FlameJetServer : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnCollisionPhantom(Entity* self, Entity* target) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; -}; \ No newline at end of file + void OnCollisionPhantom(Entity* self, Entity* target) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; +}; diff --git a/dScripts/ForceVolumeServer.cpp b/dScripts/ForceVolumeServer.cpp index e9320527..fbaad6ee 100644 --- a/dScripts/ForceVolumeServer.cpp +++ b/dScripts/ForceVolumeServer.cpp @@ -2,21 +2,20 @@ #include "PhantomPhysicsComponent.h" #include "EntityManager.h" -void ForceVolumeServer::OnStartup(Entity* self) -{ - auto* phantomPhysicsComponent = self->GetComponent(); - - if (phantomPhysicsComponent == nullptr) return; +void ForceVolumeServer::OnStartup(Entity* self) { + auto* phantomPhysicsComponent = self->GetComponent(); - const auto forceAmount = self->GetVar(u"ForceAmt"); - const auto forceX = self->GetVar(u"ForceX"); - const auto forceY = self->GetVar(u"ForceY"); - const auto forceZ = self->GetVar(u"ForceZ"); + if (phantomPhysicsComponent == nullptr) return; - phantomPhysicsComponent->SetEffectType(0); // PUSH - phantomPhysicsComponent->SetDirectionalMultiplier(forceAmount); - phantomPhysicsComponent->SetDirection({ forceX, forceY, forceZ }); - phantomPhysicsComponent->SetPhysicsEffectActive(true); + const auto forceAmount = self->GetVar(u"ForceAmt"); + const auto forceX = self->GetVar(u"ForceX"); + const auto forceY = self->GetVar(u"ForceY"); + const auto forceZ = self->GetVar(u"ForceZ"); - EntityManager::Instance()->SerializeEntity(self); + phantomPhysicsComponent->SetEffectType(0); // PUSH + phantomPhysicsComponent->SetDirectionalMultiplier(forceAmount); + phantomPhysicsComponent->SetDirection({ forceX, forceY, forceZ }); + phantomPhysicsComponent->SetPhysicsEffectActive(true); + + EntityManager::Instance()->SerializeEntity(self); } diff --git a/dScripts/FountainOfImagination.cpp b/dScripts/FountainOfImagination.cpp index 43351e18..6560e1cf 100644 --- a/dScripts/FountainOfImagination.cpp +++ b/dScripts/FountainOfImagination.cpp @@ -2,14 +2,14 @@ #include "dCommonVars.h" #include "Entity.h" -void FountainOfImagination::OnStartup(Entity *self) { - self->SetVar(u"numCycles", 6); - self->SetVar(u"secPerCycle", 30.0f); - self->SetVar(u"delayToFirstCycle", 1.5f); - self->SetVar(u"deathDelay", 30.0f); - self->SetVar(u"numberOfPowerups", 5); - self->SetVar(u"lootLOT", 935); +void FountainOfImagination::OnStartup(Entity* self) { + self->SetVar(u"numCycles", 6); + self->SetVar(u"secPerCycle", 30.0f); + self->SetVar(u"delayToFirstCycle", 1.5f); + self->SetVar(u"deathDelay", 30.0f); + self->SetVar(u"numberOfPowerups", 5); + self->SetVar(u"lootLOT", 935); - // Initiate the actual script - OnTemplateStartup(self); + // Initiate the actual script + OnTemplateStartup(self); } diff --git a/dScripts/FountainOfImagination.h b/dScripts/FountainOfImagination.h index 6ad0becd..e477a026 100644 --- a/dScripts/FountainOfImagination.h +++ b/dScripts/FountainOfImagination.h @@ -2,5 +2,5 @@ #include "ScriptedPowerupSpawner.h" class FountainOfImagination : public ScriptedPowerupSpawner { - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/FvBounceOverWall.cpp b/dScripts/FvBounceOverWall.cpp index 1c85ffbd..294c11f0 100644 --- a/dScripts/FvBounceOverWall.cpp +++ b/dScripts/FvBounceOverWall.cpp @@ -2,9 +2,9 @@ #include "MissionComponent.h" void FvBounceOverWall::OnCollisionPhantom(Entity* self, Entity* target) { - auto missionComponent = target->GetComponent(); - if (missionComponent == nullptr) return; + auto missionComponent = target->GetComponent(); + if (missionComponent == nullptr) return; - // We force progress here to the Gate Crasher mission due to an overlap in LOTs with the 'Shark Bite' missions. - missionComponent->ForceProgress(GateCrasherMissionId, GateCrasherMissionUid, 1); -} \ No newline at end of file + // We force progress here to the Gate Crasher mission due to an overlap in LOTs with the 'Shark Bite' missions. + missionComponent->ForceProgress(GateCrasherMissionId, GateCrasherMissionUid, 1); +} diff --git a/dScripts/FvBounceOverWall.h b/dScripts/FvBounceOverWall.h index 875122c9..ee8c8b3a 100644 --- a/dScripts/FvBounceOverWall.h +++ b/dScripts/FvBounceOverWall.h @@ -3,20 +3,20 @@ class FvBounceOverWall : public CppScripts::Script { - /** - * @brief When a collision has been made with self this method is called. - * - * @param self The Entity that called this function. - * @param target The target Entity of self. - */ - void OnCollisionPhantom(Entity* self, Entity* target) override; + /** + * @brief When a collision has been made with self this method is called. + * + * @param self The Entity that called this function. + * @param target The target Entity of self. + */ + void OnCollisionPhantom(Entity* self, Entity* target) override; private: - /** - * MissionId for the Gate Crasher mission. - */ - int32_t GateCrasherMissionId = 849; - /** - * MissionUid for the Gate Crasher mission. - */ - int32_t GateCrasherMissionUid = 1241; -}; \ No newline at end of file + /** + * MissionId for the Gate Crasher mission. + */ + int32_t GateCrasherMissionId = 849; + /** + * MissionUid for the Gate Crasher mission. + */ + int32_t GateCrasherMissionUid = 1241; +}; diff --git a/dScripts/FvBrickPuzzleServer.cpp b/dScripts/FvBrickPuzzleServer.cpp index df6cc395..cea6146b 100644 --- a/dScripts/FvBrickPuzzleServer.cpp +++ b/dScripts/FvBrickPuzzleServer.cpp @@ -4,79 +4,65 @@ #include "Spawner.h" #include "RebuildComponent.h" -void FvBrickPuzzleServer::OnStartup(Entity* self) -{ - const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); +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; - } + int32_t pipeNum = 0; + if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { + return; + } - if (pipeNum != 1) - { - self->AddTimer("reset", 30); - } + if (pipeNum != 1) { + self->AddTimer("reset", 30); + } } -void FvBrickPuzzleServer::OnDie(Entity* self, Entity* killer) -{ - const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); +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; - } + int32_t pipeNum = 0; + if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { + return; + } - const auto pipeGroup = myGroup.substr(0, 10); + const auto pipeGroup = myGroup.substr(0, 10); - const auto nextPipeNum = pipeNum + 1; + const auto nextPipeNum = pipeNum + 1; - const auto samePipeSpawners = dZoneManager::Instance()->GetSpawnersByName(myGroup); + const auto samePipeSpawners = dZoneManager::Instance()->GetSpawnersByName(myGroup); - if (!samePipeSpawners.empty()) - { - samePipeSpawners[0]->SoftReset(); + if (!samePipeSpawners.empty()) { + samePipeSpawners[0]->SoftReset(); - samePipeSpawners[0]->Deactivate(); - } + samePipeSpawners[0]->Deactivate(); + } - if (killer != nullptr && killer->IsPlayer()) - { - const auto nextPipe = pipeGroup + std::to_string(nextPipeNum); + if (killer != nullptr && killer->IsPlayer()) { + const auto nextPipe = pipeGroup + std::to_string(nextPipeNum); - const auto nextPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); + const auto nextPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); - if (!nextPipeSpawners.empty()) - { - nextPipeSpawners[0]->Activate(); - } - } - else - { - const auto nextPipe = pipeGroup + "1"; + if (!nextPipeSpawners.empty()) { + nextPipeSpawners[0]->Activate(); + } + } else { + const auto nextPipe = pipeGroup + "1"; - const auto firstPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); + const auto firstPipeSpawners = dZoneManager::Instance()->GetSpawnersByName(nextPipe); + + if (!firstPipeSpawners.empty()) { + firstPipeSpawners[0]->Activate(); + } + } - if (!firstPipeSpawners.empty()) - { - firstPipeSpawners[0]->Activate(); - } - } - } -void FvBrickPuzzleServer::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "reset") - { - auto* rebuildComponent = self->GetComponent(); +void FvBrickPuzzleServer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "reset") { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent != nullptr && rebuildComponent->GetState() == REBUILD_OPEN) - { - self->Smash(self->GetObjectID(), SILENT); - } - } + if (rebuildComponent != nullptr && rebuildComponent->GetState() == REBUILD_OPEN) { + self->Smash(self->GetObjectID(), SILENT); + } + } } diff --git a/dScripts/FvBrickPuzzleServer.h b/dScripts/FvBrickPuzzleServer.h index f5eceaee..4297100e 100644 --- a/dScripts/FvBrickPuzzleServer.h +++ b/dScripts/FvBrickPuzzleServer.h @@ -1,10 +1,10 @@ #pragma once #include "CppScripts.h" -class FvBrickPuzzleServer : public CppScripts::Script +class FvBrickPuzzleServer : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnDie(Entity* self, Entity* killer) override; void OnTimerDone(Entity* self, std::string timerName) override; -}; \ No newline at end of file +}; diff --git a/dScripts/FvCandle.cpp b/dScripts/FvCandle.cpp index 63f90f0b..efd717ee 100644 --- a/dScripts/FvCandle.cpp +++ b/dScripts/FvCandle.cpp @@ -2,7 +2,7 @@ #include "MissionComponent.h" #include "RenderComponent.h" -std::vector FvCandle::m_Missions = {850, 1431, 1529, 1566, 1603}; +std::vector FvCandle::m_Missions = { 850, 1431, 1529, 1566, 1603 }; void FvCandle::OnStartup(Entity* self) { auto* render = static_cast(self->GetComponent(COMPONENT_TYPE_RENDER)); @@ -25,13 +25,11 @@ void FvCandle::BlowOutCandle(Entity* self, Entity* blower) { auto* render = static_cast(self->GetComponent(COMPONENT_TYPE_RENDER)); if (render == nullptr) return; - + auto* missionComponent = blower->GetComponent(); - if (missionComponent != nullptr) - { - for (const auto mission : m_Missions) - { + if (missionComponent != nullptr) { + for (const auto mission : m_Missions) { missionComponent->ForceProgressTaskType(mission, 1, 1); } } @@ -54,4 +52,4 @@ void FvCandle::OnTimerDone(Entity* self, std::string timerName) { render->StopEffect("candle_smoke", false); render->PlayEffect(2108, u"create", "candle_light", LWOOBJID_EMPTY, 1.0f, 1.0f, true); -} \ No newline at end of file +} diff --git a/dScripts/FvCandle.h b/dScripts/FvCandle.h index 362d2a05..e0cd4e04 100644 --- a/dScripts/FvCandle.h +++ b/dScripts/FvCandle.h @@ -1,7 +1,7 @@ #pragma once #include "CppScripts.h" -class FvCandle : public CppScripts::Script +class FvCandle : public CppScripts::Script { public: void OnStartup(Entity* self); @@ -11,4 +11,4 @@ private: void BlowOutCandle(Entity* self, Entity* blower); static std::vector m_Missions; -}; \ No newline at end of file +}; diff --git a/dScripts/FvConsoleLeftQuickbuild.cpp b/dScripts/FvConsoleLeftQuickbuild.cpp index ef281f15..b998b9ec 100644 --- a/dScripts/FvConsoleLeftQuickbuild.cpp +++ b/dScripts/FvConsoleLeftQuickbuild.cpp @@ -2,57 +2,46 @@ #include "EntityManager.h" #include "GameMessages.h" -void FvConsoleLeftQuickbuild::OnStartup(Entity* self) -{ - self->SetVar(u"IAmBuilt", false); - self->SetVar(u"AmActive", false); +void FvConsoleLeftQuickbuild::OnStartup(Entity* self) { + self->SetVar(u"IAmBuilt", false); + self->SetVar(u"AmActive", false); } -void FvConsoleLeftQuickbuild::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state == REBUILD_COMPLETED) - { - self->SetVar(u"IAmBuilt", true); - - const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); +void FvConsoleLeftQuickbuild::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == REBUILD_COMPLETED) { + self->SetVar(u"IAmBuilt", true); - if (!objects.empty()) - { - objects[0]->NotifyObject(self, "ConsoleLeftUp"); - } - } - else if (state == REBUILD_RESETTING) - { - self->SetVar(u"IAmBuilt", false); - self->SetVar(u"AmActive", false); - - const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); + const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); - if (!objects.empty()) - { - objects[0]->NotifyObject(self, "ConsoleLeftDown"); - } - } + if (!objects.empty()) { + objects[0]->NotifyObject(self, "ConsoleLeftUp"); + } + } else if (state == REBUILD_RESETTING) { + self->SetVar(u"IAmBuilt", false); + self->SetVar(u"AmActive", false); + + const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); + + if (!objects.empty()) { + objects[0]->NotifyObject(self, "ConsoleLeftDown"); + } + } } -void FvConsoleLeftQuickbuild::OnUse(Entity* self, Entity* user) -{ - if (self->GetVar(u"AmActive")) - { - return; - } +void FvConsoleLeftQuickbuild::OnUse(Entity* self, Entity* user) { + if (self->GetVar(u"AmActive")) { + return; + } - if (self->GetVar(u"IAmBuilt")) - { - self->SetVar(u"AmActive", true); + if (self->GetVar(u"IAmBuilt")) { + self->SetVar(u"AmActive", true); - const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); + const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); - if (!objects.empty()) - { - objects[0]->NotifyObject(self, "ConsoleLeftActive"); - } - } + if (!objects.empty()) { + objects[0]->NotifyObject(self, "ConsoleLeftActive"); + } + } - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/FvConsoleLeftQuickbuild.h b/dScripts/FvConsoleLeftQuickbuild.h index 8c796e0f..bbdea27e 100644 --- a/dScripts/FvConsoleLeftQuickbuild.h +++ b/dScripts/FvConsoleLeftQuickbuild.h @@ -1,10 +1,10 @@ #pragma once #include "CppScripts.h" -class FvConsoleLeftQuickbuild : public CppScripts::Script +class FvConsoleLeftQuickbuild : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnRebuildNotifyState(Entity* self, eRebuildState state) override; void OnUse(Entity* self, Entity* user) override; -}; \ No newline at end of file +}; diff --git a/dScripts/FvConsoleRightQuickbuild.cpp b/dScripts/FvConsoleRightQuickbuild.cpp index 0bf9849a..ea047cd8 100644 --- a/dScripts/FvConsoleRightQuickbuild.cpp +++ b/dScripts/FvConsoleRightQuickbuild.cpp @@ -2,57 +2,46 @@ #include "EntityManager.h" #include "GameMessages.h" -void FvConsoleRightQuickbuild::OnStartup(Entity* self) -{ - self->SetVar(u"IAmBuilt", false); - self->SetVar(u"AmActive", false); +void FvConsoleRightQuickbuild::OnStartup(Entity* self) { + self->SetVar(u"IAmBuilt", false); + self->SetVar(u"AmActive", false); } -void FvConsoleRightQuickbuild::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state == REBUILD_COMPLETED) - { - self->SetVar(u"IAmBuilt", true); - - const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); +void FvConsoleRightQuickbuild::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == REBUILD_COMPLETED) { + self->SetVar(u"IAmBuilt", true); - if (!objects.empty()) - { - objects[0]->NotifyObject(self, "ConsoleRightUp"); - } - } - else if (state == REBUILD_RESETTING) - { - self->SetVar(u"IAmBuilt", false); - self->SetVar(u"AmActive", false); - - const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); + const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); - if (!objects.empty()) - { - objects[0]->NotifyObject(self, "ConsoleRightDown"); - } - } + if (!objects.empty()) { + objects[0]->NotifyObject(self, "ConsoleRightUp"); + } + } else if (state == REBUILD_RESETTING) { + self->SetVar(u"IAmBuilt", false); + self->SetVar(u"AmActive", false); + + const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); + + if (!objects.empty()) { + objects[0]->NotifyObject(self, "ConsoleRightDown"); + } + } } -void FvConsoleRightQuickbuild::OnUse(Entity* self, Entity* user) -{ - if (self->GetVar(u"AmActive")) - { - return; - } +void FvConsoleRightQuickbuild::OnUse(Entity* self, Entity* user) { + if (self->GetVar(u"AmActive")) { + return; + } - if (self->GetVar(u"IAmBuilt")) - { - self->SetVar(u"AmActive", true); + if (self->GetVar(u"IAmBuilt")) { + self->SetVar(u"AmActive", true); - const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); + const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); - if (!objects.empty()) - { - objects[0]->NotifyObject(self, "ConsoleRightActive"); - } - } + if (!objects.empty()) { + objects[0]->NotifyObject(self, "ConsoleRightActive"); + } + } - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/FvConsoleRightQuickbuild.h b/dScripts/FvConsoleRightQuickbuild.h index cd0f4a04..fab8c814 100644 --- a/dScripts/FvConsoleRightQuickbuild.h +++ b/dScripts/FvConsoleRightQuickbuild.h @@ -1,10 +1,10 @@ #pragma once #include "CppScripts.h" -class FvConsoleRightQuickbuild : public CppScripts::Script +class FvConsoleRightQuickbuild : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnRebuildNotifyState(Entity* self, eRebuildState state) override; void OnUse(Entity* self, Entity* user) override; -}; \ No newline at end of file +}; diff --git a/dScripts/FvDragonSmashingGolemQb.cpp b/dScripts/FvDragonSmashingGolemQb.cpp index 6a88d9a0..a9d38aa5 100644 --- a/dScripts/FvDragonSmashingGolemQb.cpp +++ b/dScripts/FvDragonSmashingGolemQb.cpp @@ -2,35 +2,29 @@ #include "GameMessages.h" #include "EntityManager.h" -void FvDragonSmashingGolemQb::OnStartup(Entity* self) -{ - self->AddTimer("GolemBreakTimer", 10.5f); +void FvDragonSmashingGolemQb::OnStartup(Entity* self) { + self->AddTimer("GolemBreakTimer", 10.5f); } -void FvDragonSmashingGolemQb::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "GolemBreakTimer") - { - self->Smash(); - } +void FvDragonSmashingGolemQb::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "GolemBreakTimer") { + self->Smash(); + } } -void FvDragonSmashingGolemQb::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state == eRebuildState::REBUILD_COMPLETED) - { - GameMessages::SendPlayAnimation(self, u"dragonsmash"); +void FvDragonSmashingGolemQb::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == eRebuildState::REBUILD_COMPLETED) { + GameMessages::SendPlayAnimation(self, u"dragonsmash"); - const auto dragonId = self->GetVar(u"Dragon"); + const auto dragonId = self->GetVar(u"Dragon"); - auto* dragon = EntityManager::Instance()->GetEntity(dragonId); + auto* dragon = EntityManager::Instance()->GetEntity(dragonId); - if (dragon != nullptr) - { - dragon->OnFireEventServerSide(self, "rebuildDone"); - } + if (dragon != nullptr) { + dragon->OnFireEventServerSide(self, "rebuildDone"); + } - self->CancelTimer("GolemBreakTimer"); - self->AddTimer("GolemBreakTimer", 10.5f); - } + self->CancelTimer("GolemBreakTimer"); + self->AddTimer("GolemBreakTimer", 10.5f); + } } diff --git a/dScripts/FvDragonSmashingGolemQb.h b/dScripts/FvDragonSmashingGolemQb.h index 3cbe9a40..8aa772a3 100644 --- a/dScripts/FvDragonSmashingGolemQb.h +++ b/dScripts/FvDragonSmashingGolemQb.h @@ -1,10 +1,10 @@ #pragma once #include "CppScripts.h" -class FvDragonSmashingGolemQb : public CppScripts::Script +class FvDragonSmashingGolemQb : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnRebuildNotifyState(Entity* self, eRebuildState state) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnRebuildNotifyState(Entity* self, eRebuildState state) override; }; diff --git a/dScripts/FvFacilityBrick.cpp b/dScripts/FvFacilityBrick.cpp index fce9e630..1ae910e4 100644 --- a/dScripts/FvFacilityBrick.cpp +++ b/dScripts/FvFacilityBrick.cpp @@ -3,117 +3,95 @@ #include "dZoneManager.h" #include "EntityManager.h" -void FvFacilityBrick::OnStartup(Entity* self) -{ - self->SetVar(u"ConsoleLEFTActive", false); - self->SetVar(u"ConsoleRIGHTtActive", false); +void FvFacilityBrick::OnStartup(Entity* self) { + self->SetVar(u"ConsoleLEFTActive", false); + self->SetVar(u"ConsoleRIGHTtActive", false); } -void FvFacilityBrick::OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1, int32_t param2) -{ - auto* brickSpawner = dZoneManager::Instance()->GetSpawnersByName("ImaginationBrick")[0]; - auto* bugSpawner = dZoneManager::Instance()->GetSpawnersByName("MaelstromBug")[0]; - auto* canisterSpawner = dZoneManager::Instance()->GetSpawnersByName("BrickCanister")[0]; +void FvFacilityBrick::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) { + auto* brickSpawner = dZoneManager::Instance()->GetSpawnersByName("ImaginationBrick")[0]; + auto* bugSpawner = dZoneManager::Instance()->GetSpawnersByName("MaelstromBug")[0]; + auto* canisterSpawner = dZoneManager::Instance()->GetSpawnersByName("BrickCanister")[0]; - if (name == "ConsoleLeftUp") - { - GameMessages::SendStopFXEffect(self, true, "LeftPipeOff"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2775, u"create", "LeftPipeEnergy"); - } - else if (name == "ConsoleLeftDown") - { - self->SetVar(u"ConsoleLEFTActive", false); + if (name == "ConsoleLeftUp") { + GameMessages::SendStopFXEffect(self, true, "LeftPipeOff"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2775, u"create", "LeftPipeEnergy"); + } else if (name == "ConsoleLeftDown") { + self->SetVar(u"ConsoleLEFTActive", false); - GameMessages::SendStopFXEffect(self, true, "LeftPipeEnergy"); - GameMessages::SendStopFXEffect(self, true, "LeftPipeOn"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2774, u"create", "LeftPipeOff"); - } - else if (name == "ConsoleLeftActive") - { - self->SetVar(u"ConsoleLEFTActive", true); + GameMessages::SendStopFXEffect(self, true, "LeftPipeEnergy"); + GameMessages::SendStopFXEffect(self, true, "LeftPipeOn"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2774, u"create", "LeftPipeOff"); + } else if (name == "ConsoleLeftActive") { + self->SetVar(u"ConsoleLEFTActive", true); - GameMessages::SendStopFXEffect(self, true, "LeftPipeEnergy"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2776, u"create", "LeftPipeOn"); - } - - else if (name == "ConsoleRightUp") - { - GameMessages::SendStopFXEffect(self, true, "RightPipeOff"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2778, u"create", "RightPipeEnergy"); - } - else if (name == "ConsoleRightDown") - { - self->SetVar(u"ConsoleRIGHTActive", false); + GameMessages::SendStopFXEffect(self, true, "LeftPipeEnergy"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2776, u"create", "LeftPipeOn"); + } - GameMessages::SendStopFXEffect(self, true, "RightPipeEnergy"); - GameMessages::SendStopFXEffect(self, true, "RightPipeOn"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2777, u"create", "RightPipeOff"); - } - else if (name == "ConsoleRightActive") - { - self->SetVar(u"ConsoleRIGHTActive", true); + else if (name == "ConsoleRightUp") { + GameMessages::SendStopFXEffect(self, true, "RightPipeOff"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2778, u"create", "RightPipeEnergy"); + } else if (name == "ConsoleRightDown") { + self->SetVar(u"ConsoleRIGHTActive", false); - GameMessages::SendStopFXEffect(self, true, "RightPipeOff"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2779, u"create", "RightPipeEnergy"); - } + GameMessages::SendStopFXEffect(self, true, "RightPipeEnergy"); + GameMessages::SendStopFXEffect(self, true, "RightPipeOn"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2777, u"create", "RightPipeOff"); + } else if (name == "ConsoleRightActive") { + self->SetVar(u"ConsoleRIGHTActive", true); - if (self->GetVar(u"ConsoleLEFTActive") && self->GetVar(u"ConsoleRIGHTActive")) - { - auto* object = EntityManager::Instance()->GetEntitiesInGroup("Brick")[0]; + GameMessages::SendStopFXEffect(self, true, "RightPipeOff"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2779, u"create", "RightPipeEnergy"); + } - if (object != nullptr) - { - GameMessages::SendPlayFXEffect(object->GetObjectID(), 122, u"create", "bluebrick"); - GameMessages::SendPlayFXEffect(object->GetObjectID(), 1034, u"cast", "imaginationexplosion"); - } + if (self->GetVar(u"ConsoleLEFTActive") && self->GetVar(u"ConsoleRIGHTActive")) { + auto* object = EntityManager::Instance()->GetEntitiesInGroup("Brick")[0]; - object = EntityManager::Instance()->GetEntitiesInGroup("Canister")[0]; + if (object != nullptr) { + GameMessages::SendPlayFXEffect(object->GetObjectID(), 122, u"create", "bluebrick"); + GameMessages::SendPlayFXEffect(object->GetObjectID(), 1034, u"cast", "imaginationexplosion"); + } - if (object != nullptr) - { - object->Smash(self->GetObjectID(), SILENT); - } + object = EntityManager::Instance()->GetEntitiesInGroup("Canister")[0]; - canisterSpawner->Reset(); - canisterSpawner->Deactivate(); - } - else if (self->GetVar(u"ConsoleLEFTActive") || self->GetVar(u"ConsoleRIGHTActive")) - { - brickSpawner->Activate(); + if (object != nullptr) { + object->Smash(self->GetObjectID(), SILENT); + } - auto* object = EntityManager::Instance()->GetEntitiesInGroup("Brick")[0]; + canisterSpawner->Reset(); + canisterSpawner->Deactivate(); + } else if (self->GetVar(u"ConsoleLEFTActive") || self->GetVar(u"ConsoleRIGHTActive")) { + brickSpawner->Activate(); - if (object != nullptr) - { - GameMessages::SendStopFXEffect(object, true, "bluebrick"); - } + auto* object = EntityManager::Instance()->GetEntitiesInGroup("Brick")[0]; - bugSpawner->Reset(); - bugSpawner->Deactivate(); + if (object != nullptr) { + GameMessages::SendStopFXEffect(object, true, "bluebrick"); + } - canisterSpawner->Reset(); - canisterSpawner->Activate(); - } - else - { - brickSpawner->Reset(); - brickSpawner->Deactivate(); + bugSpawner->Reset(); + bugSpawner->Deactivate(); - bugSpawner->Reset(); - bugSpawner->Activate(); - } + canisterSpawner->Reset(); + canisterSpawner->Activate(); + } else { + brickSpawner->Reset(); + brickSpawner->Deactivate(); + + bugSpawner->Reset(); + bugSpawner->Activate(); + } } -void FvFacilityBrick::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) -{ - if (args != "PlayFX") - { - return; - } +void FvFacilityBrick::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args != "PlayFX") { + return; + } - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2774, u"create", "LeftPipeOff"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2777, u"create", "RightPipeOff"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2750, u"create", "imagination_canister"); - GameMessages::SendPlayFXEffect(self->GetObjectID(), 2751, u"create", "canister_light_filler"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2774, u"create", "LeftPipeOff"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2777, u"create", "RightPipeOff"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2750, u"create", "imagination_canister"); + GameMessages::SendPlayFXEffect(self->GetObjectID(), 2751, u"create", "canister_light_filler"); } diff --git a/dScripts/FvFacilityBrick.h b/dScripts/FvFacilityBrick.h index 794dd5b6..c7580c25 100644 --- a/dScripts/FvFacilityBrick.h +++ b/dScripts/FvFacilityBrick.h @@ -1,11 +1,11 @@ #pragma once #include "CppScripts.h" -class FvFacilityBrick : public CppScripts::Script +class FvFacilityBrick : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnNotifyObject(Entity *self, Entity *sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; -}; \ No newline at end of file + void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; +}; diff --git a/dScripts/FvFlyingCreviceDragon.cpp b/dScripts/FvFlyingCreviceDragon.cpp index 4255daf5..16eda512 100644 --- a/dScripts/FvFlyingCreviceDragon.cpp +++ b/dScripts/FvFlyingCreviceDragon.cpp @@ -4,129 +4,104 @@ #include "SkillComponent.h" #include "GeneralUtils.h" -void FvFlyingCreviceDragon::OnStartup(Entity* self) -{ - self->AddTimer("waypoint", 5); +void FvFlyingCreviceDragon::OnStartup(Entity* self) { + self->AddTimer("waypoint", 5); } -void FvFlyingCreviceDragon::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "waypoint") - { - auto point = self->GetVar(u"waypoint"); +void FvFlyingCreviceDragon::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "waypoint") { + auto point = self->GetVar(u"waypoint"); - if (point >= 20) - { - point = 0; - } + if (point >= 20) { + point = 0; + } - self->SetVar(u"waypoint", point + 1); + self->SetVar(u"waypoint", point + 1); - self->AddTimer("waypoint", 5); + self->AddTimer("waypoint", 5); - OnArrived(self); + OnArrived(self); - return; - } + return; + } - std::string groupName = ""; + std::string groupName = ""; - if (timerName == "platform1attack") - { - groupName = "dragonFireballs1"; - } - else if (timerName == "platform3attack") - { - groupName = "dragonFireballs3"; - } + if (timerName == "platform1attack") { + groupName = "dragonFireballs1"; + } else if (timerName == "platform3attack") { + groupName = "dragonFireballs3"; + } - const auto& group = EntityManager::Instance()->GetEntitiesInGroup(groupName); + const auto& group = EntityManager::Instance()->GetEntitiesInGroup(groupName); - if (group.empty()) - { - return; - } + if (group.empty()) { + return; + } - auto* skillComponent = group[0]->GetComponent(); + auto* skillComponent = group[0]->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY, true); - } + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY, true); + } - auto minionCount = 1; - for (size_t i = 1; i < group.size(); i++) - { - if (minionCount == 4) - { - return; - } + auto minionCount = 1; + for (size_t i = 1; i < group.size(); i++) { + if (minionCount == 4) { + return; + } - if (/*GeneralUtils::GenerateRandomNumber(1, 5) > 3*/ true) - { - skillComponent = group[i]->GetComponent(); + if (/*GeneralUtils::GenerateRandomNumber(1, 5) > 3*/ true) { + skillComponent = group[i]->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY); + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY); - ++minionCount; - } - } - } + ++minionCount; + } + } + } } -void FvFlyingCreviceDragon::OnArrived(Entity* self) -{ - auto point = self->GetVar(u"waypoint"); +void FvFlyingCreviceDragon::OnArrived(Entity* self) { + auto point = self->GetVar(u"waypoint"); - if (point == 4) - { - GameMessages::SendPlayAnimation(self, u"attack1", 2); - self->AddTimer("platform1attack", 1.75f); - } - else if (point == 12) - { - GameMessages::SendPlayAnimation(self, u"attack2", 2); + if (point == 4) { + GameMessages::SendPlayAnimation(self, u"attack1", 2); + self->AddTimer("platform1attack", 1.75f); + } else if (point == 12) { + GameMessages::SendPlayAnimation(self, u"attack2", 2); - const auto& group2 = EntityManager::Instance()->GetEntitiesInGroup("dragonFireballs2"); + const auto& group2 = EntityManager::Instance()->GetEntitiesInGroup("dragonFireballs2"); - if (group2.empty()) - { - return; - } + if (group2.empty()) { + return; + } - auto* skillComponent = group2[0]->GetComponent(); + auto* skillComponent = group2[0]->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY); - } + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY); + } - auto minionCount = 1; - for (size_t i = 1; i < group2.size(); i++) - { - if (minionCount == 4) - { - return; - } + auto minionCount = 1; + for (size_t i = 1; i < group2.size(); i++) { + if (minionCount == 4) { + return; + } - if (GeneralUtils::GenerateRandomNumber(1, 5) > 3) - { - skillComponent = group2[i]->GetComponent(); + if (GeneralUtils::GenerateRandomNumber(1, 5) > 3) { + skillComponent = group2[i]->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY, true); + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(762, 12506, LWOOBJID_EMPTY, true); - ++minionCount; - } - } - } - } - else if (point == 16) - { - GameMessages::SendPlayAnimation(self, u"attack3", 2); - self->AddTimer("platform3attack", 0.5f); - } + ++minionCount; + } + } + } + } else if (point == 16) { + GameMessages::SendPlayAnimation(self, u"attack3", 2); + self->AddTimer("platform3attack", 0.5f); + } } diff --git a/dScripts/FvFlyingCreviceDragon.h b/dScripts/FvFlyingCreviceDragon.h index 657f4eed..92e95d26 100644 --- a/dScripts/FvFlyingCreviceDragon.h +++ b/dScripts/FvFlyingCreviceDragon.h @@ -1,10 +1,10 @@ #pragma once #include "CppScripts.h" -class FvFlyingCreviceDragon : public CppScripts::Script +class FvFlyingCreviceDragon : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnArrived(Entity* self); + void OnTimerDone(Entity* self, std::string timerName) override; + void OnArrived(Entity* self); }; diff --git a/dScripts/FvFong.cpp b/dScripts/FvFong.cpp index 9a3de0b2..7f63e5e5 100644 --- a/dScripts/FvFong.cpp +++ b/dScripts/FvFong.cpp @@ -2,10 +2,8 @@ #include "Darkitect.h" #include "MissionState.h" -void FvFong::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) -{ - if (missionID == 734 && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) - { +void FvFong::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + if (missionID == 734 && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { Darkitect Baron; Baron.Reveal(self, target); } diff --git a/dScripts/FvFong.h b/dScripts/FvFong.h index fc47b484..074e6d8c 100644 --- a/dScripts/FvFong.h +++ b/dScripts/FvFong.h @@ -3,6 +3,6 @@ class FvFong : public CppScripts::Script { - public: - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; +public: + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; }; diff --git a/dScripts/FvFreeGfNinjas.cpp b/dScripts/FvFreeGfNinjas.cpp index 8022b32f..1751b6a7 100644 --- a/dScripts/FvFreeGfNinjas.cpp +++ b/dScripts/FvFreeGfNinjas.cpp @@ -2,42 +2,41 @@ #include "Character.h" #include "MissionComponent.h" -void FvFreeGfNinjas::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - if (missionID == 705 && missionState == MissionState::MISSION_STATE_AVAILABLE) { - auto* missionComponent = target->GetComponent(); - if (missionComponent == nullptr) - return; +void FvFreeGfNinjas::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + if (missionID == 705 && missionState == MissionState::MISSION_STATE_AVAILABLE) { + auto* missionComponent = target->GetComponent(); + if (missionComponent == nullptr) + return; - missionComponent->AcceptMission(701); - missionComponent->AcceptMission(702); - missionComponent->AcceptMission(703); - missionComponent->AcceptMission(704); + missionComponent->AcceptMission(701); + missionComponent->AcceptMission(702); + missionComponent->AcceptMission(703); + missionComponent->AcceptMission(704); - auto* character = target->GetCharacter(); - if (character != nullptr) - character->SetPlayerFlag(68, true); - } else if (missionID == 786) { - auto* character = target->GetCharacter(); - if (character != nullptr) - character->SetPlayerFlag(81, true); - } + auto* character = target->GetCharacter(); + if (character != nullptr) + character->SetPlayerFlag(68, true); + } else if (missionID == 786) { + auto* character = target->GetCharacter(); + if (character != nullptr) + character->SetPlayerFlag(81, true); + } } -void FvFreeGfNinjas::OnUse(Entity* self, Entity* user) -{ - // To allow player who already have the mission to progress. - auto* missionComponent = user->GetComponent(); - if (missionComponent == nullptr) - return; +void FvFreeGfNinjas::OnUse(Entity* self, Entity* user) { + // To allow player who already have the mission to progress. + auto* missionComponent = user->GetComponent(); + if (missionComponent == nullptr) + return; - if (missionComponent->GetMissionState(705) == MissionState::MISSION_STATE_ACTIVE) { - auto* character = user->GetCharacter(); - if (character != nullptr) - character->SetPlayerFlag(68, true); + if (missionComponent->GetMissionState(705) == MissionState::MISSION_STATE_ACTIVE) { + auto* character = user->GetCharacter(); + if (character != nullptr) + character->SetPlayerFlag(68, true); - missionComponent->AcceptMission(701, true); - missionComponent->AcceptMission(702, true); - missionComponent->AcceptMission(703, true); - missionComponent->AcceptMission(704, true); - } + missionComponent->AcceptMission(701, true); + missionComponent->AcceptMission(702, true); + missionComponent->AcceptMission(703, true); + missionComponent->AcceptMission(704, true); + } } diff --git a/dScripts/FvFreeGfNinjas.h b/dScripts/FvFreeGfNinjas.h index cdff0d2d..c7e4876e 100644 --- a/dScripts/FvFreeGfNinjas.h +++ b/dScripts/FvFreeGfNinjas.h @@ -3,6 +3,6 @@ class FvFreeGfNinjas : public CppScripts::Script { public: - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; - void OnUse(Entity* self, Entity* user) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/FvHorsemenTrigger.cpp b/dScripts/FvHorsemenTrigger.cpp index 541c11e0..e87d9629 100644 --- a/dScripts/FvHorsemenTrigger.cpp +++ b/dScripts/FvHorsemenTrigger.cpp @@ -2,64 +2,52 @@ #include "EntityManager.h" #include "MissionComponent.h" -void FvHorsemenTrigger::OnStartup(Entity* self) -{ - self->SetProximityRadius(40, "horsemenTrigger"); +void FvHorsemenTrigger::OnStartup(Entity* self) { + self->SetProximityRadius(40, "horsemenTrigger"); - self->SetVar>(u"players", {}); + self->SetVar>(u"players", {}); } -void FvHorsemenTrigger::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (name != "horsemenTrigger" || !entering->IsPlayer()) - { - return; - } +void FvHorsemenTrigger::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (name != "horsemenTrigger" || !entering->IsPlayer()) { + return; + } - auto players = self->GetVar>(u"players"); + auto players = self->GetVar>(u"players"); - const auto& iter = std::find(players.begin(), players.end(), entering->GetObjectID()); + const auto& iter = std::find(players.begin(), players.end(), entering->GetObjectID()); - if (status == "ENTER" && iter == players.end()) - { - players.push_back(entering->GetObjectID()); - } - else if (status == "LEAVE" && iter != players.end()) - { - players.erase(iter); - } + if (status == "ENTER" && iter == players.end()) { + players.push_back(entering->GetObjectID()); + } else if (status == "LEAVE" && iter != players.end()) { + players.erase(iter); + } - self->SetVar>(u"players", players); + self->SetVar>(u"players", players); } void -FvHorsemenTrigger::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) -{ - auto players = self->GetVar>(u"players"); +FvHorsemenTrigger::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + auto players = self->GetVar>(u"players"); - if (args == "HorsemenDeath") - { - for (const auto& playerId : self->GetVar>(u"players")) - { - auto* player = EntityManager::Instance()->GetEntity(playerId); + if (args == "HorsemenDeath") { + for (const auto& playerId : self->GetVar>(u"players")) { + auto* player = EntityManager::Instance()->GetEntity(playerId); - if (player == nullptr) - { - continue; - } + if (player == nullptr) { + continue; + } - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent == nullptr) - { - continue; - } + if (missionComponent == nullptr) { + continue; + } - for (const auto missionId : m_Missions) - { - missionComponent->ForceProgressTaskType(missionId, 1, 1); - } - } - } + for (const auto missionId : m_Missions) { + missionComponent->ForceProgressTaskType(missionId, 1, 1); + } + } + } } diff --git a/dScripts/FvHorsemenTrigger.h b/dScripts/FvHorsemenTrigger.h index 9ec47084..233e2f5b 100644 --- a/dScripts/FvHorsemenTrigger.h +++ b/dScripts/FvHorsemenTrigger.h @@ -2,14 +2,14 @@ #include "CppScripts.h" #include "RenderComponent.h" -class FvHorsemenTrigger : public CppScripts::Script +class FvHorsemenTrigger : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; private: - std::vector m_Missions = {854, 738, 1432, 1530, 1567, 1604}; + std::vector m_Missions = { 854, 738, 1432, 1530, 1567, 1604 }; }; diff --git a/dScripts/FvMaelstromCavalry.cpp b/dScripts/FvMaelstromCavalry.cpp index b4a32991..9214667e 100644 --- a/dScripts/FvMaelstromCavalry.cpp +++ b/dScripts/FvMaelstromCavalry.cpp @@ -1,37 +1,30 @@ #include "FvMaelstromCavalry.h" #include "EntityManager.h" -void FvMaelstromCavalry::OnStartup(Entity* self) -{ - for (const auto& group : self->GetGroups()) - { - const auto& objects = EntityManager::Instance()->GetEntitiesInGroup(group); +void FvMaelstromCavalry::OnStartup(Entity* self) { + for (const auto& group : self->GetGroups()) { + const auto& objects = EntityManager::Instance()->GetEntitiesInGroup(group); - for (auto* obj : objects) - { - if (obj->GetLOT() != 8551) continue; + for (auto* obj : objects) { + if (obj->GetLOT() != 8551) continue; - obj->OnFireEventServerSide(self, "ISpawned"); - } - } + obj->OnFireEventServerSide(self, "ISpawned"); + } + } } -void FvMaelstromCavalry::OnDie(Entity* self, Entity* killer) -{ - if (killer == nullptr) - { - return; - } +void FvMaelstromCavalry::OnDie(Entity* self, Entity* killer) { + if (killer == nullptr) { + return; + } - if (killer->GetLOT() != 8665) - { - return; - } + if (killer->GetLOT() != 8665) { + return; + } - const auto& triggers = EntityManager::Instance()->GetEntitiesInGroup("HorsemenTrigger"); + const auto& triggers = EntityManager::Instance()->GetEntitiesInGroup("HorsemenTrigger"); - for (auto* trigger : triggers) - { - trigger->OnFireEventServerSide(self, "HorsemenDeath"); - } + for (auto* trigger : triggers) { + trigger->OnFireEventServerSide(self, "HorsemenDeath"); + } } diff --git a/dScripts/FvMaelstromCavalry.h b/dScripts/FvMaelstromCavalry.h index 0fc3e840..40784ba9 100644 --- a/dScripts/FvMaelstromCavalry.h +++ b/dScripts/FvMaelstromCavalry.h @@ -1,7 +1,7 @@ #pragma once #include "CppScripts.h" -class FvMaelstromCavalry : public CppScripts::Script +class FvMaelstromCavalry : public CppScripts::Script { public: void OnStartup(Entity* self); diff --git a/dScripts/FvMaelstromDragon.cpp b/dScripts/FvMaelstromDragon.cpp index 66e7de85..47ddb4bf 100644 --- a/dScripts/FvMaelstromDragon.cpp +++ b/dScripts/FvMaelstromDragon.cpp @@ -4,197 +4,172 @@ #include "BaseCombatAIComponent.h" #include "DestroyableComponent.h" -void FvMaelstromDragon::OnStartup(Entity* self) -{ - self->SetVar(u"weakspot", 0); +void FvMaelstromDragon::OnStartup(Entity* self) { + self->SetVar(u"weakspot", 0); - auto* baseCombatAIComponent = self->GetComponent(); + auto* baseCombatAIComponent = self->GetComponent(); - if (baseCombatAIComponent != nullptr) - { - baseCombatAIComponent->SetStunImmune(true); - } + if (baseCombatAIComponent != nullptr) { + baseCombatAIComponent->SetStunImmune(true); + } } -void FvMaelstromDragon::OnDie(Entity* self, Entity* killer) -{ - if (self->GetVar(u"bDied")) - { - return; - } +void FvMaelstromDragon::OnDie(Entity* self, Entity* killer) { + if (self->GetVar(u"bDied")) { + return; + } - self->SetVar(u"bDied", true); + self->SetVar(u"bDied", true); - auto position = self->GetPosition(); - auto rotation = self->GetRotation(); + auto position = self->GetPosition(); + auto rotation = self->GetRotation(); - auto chestObject = 11229; + auto chestObject = 11229; - EntityInfo info {}; - info.lot = chestObject; - info.pos = position; - info.rot = rotation; - info.spawnerID = self->GetObjectID(); + EntityInfo info{}; + info.lot = chestObject; + info.pos = position; + info.rot = rotation; + info.spawnerID = self->GetObjectID(); - auto* chest = EntityManager::Instance()->CreateEntity(info); + auto* chest = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(chest); + EntityManager::Instance()->ConstructEntity(chest); - auto golemId = self->GetVar(u"Golem"); + auto golemId = self->GetVar(u"Golem"); - auto* golem = EntityManager::Instance()->GetEntity(golemId); + auto* golem = EntityManager::Instance()->GetEntity(golemId); - if (golem != nullptr) - { - golem->Smash(self->GetObjectID()); - } + if (golem != nullptr) { + golem->Smash(self->GetObjectID()); + } } -void FvMaelstromDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) -{ - GameMessages::SendPlayFXEffect(self, -1, u"gothit", "", LWOOBJID_EMPTY, 1, 1, true); +void FvMaelstromDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { + GameMessages::SendPlayFXEffect(self, -1, u"gothit", "", LWOOBJID_EMPTY, 1, 1, true); - if (true) - { - auto weakpoint = self->GetVar(u"weakspot"); + if (true) { + auto weakpoint = self->GetVar(u"weakspot"); - if (weakpoint == 1) - { - self->Smash(attacker->GetObjectID()); - } - } + if (weakpoint == 1) { + self->Smash(attacker->GetObjectID()); + } + } - auto* destroyableComponent = self->GetComponent(); + auto* destroyableComponent = self->GetComponent(); - if (destroyableComponent != nullptr) - { - Game::logger->Log("FvMaelstromDragon", "Hit %i", destroyableComponent->GetArmor()); + if (destroyableComponent != nullptr) { + Game::logger->Log("FvMaelstromDragon", "Hit %i", destroyableComponent->GetArmor()); - if (destroyableComponent->GetArmor() > 0) return; + if (destroyableComponent->GetArmor() > 0) return; - auto weakpoint = self->GetVar(u"weakpoint"); + auto weakpoint = self->GetVar(u"weakpoint"); - if (weakpoint == 0) - { - Game::logger->Log("FvMaelstromDragon", "Activating weakpoint"); + if (weakpoint == 0) { + Game::logger->Log("FvMaelstromDragon", "Activating weakpoint"); - self->AddTimer("ReviveTimer", 12); + self->AddTimer("ReviveTimer", 12); - auto* baseCombatAIComponent = self->GetComponent(); - auto* skillComponent = self->GetComponent(); + auto* baseCombatAIComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (baseCombatAIComponent != nullptr) - { - baseCombatAIComponent->SetDisabled(true); - baseCombatAIComponent->SetStunned(true); - } + if (baseCombatAIComponent != nullptr) { + baseCombatAIComponent->SetDisabled(true); + baseCombatAIComponent->SetStunned(true); + } - if (skillComponent != nullptr) - { - skillComponent->Interrupt(); - } + if (skillComponent != nullptr) { + skillComponent->Interrupt(); + } - self->SetVar(u"weakpoint", 2); + self->SetVar(u"weakpoint", 2); - GameMessages::SendPlayAnimation(self, u"stunstart", 1.7f); + GameMessages::SendPlayAnimation(self, u"stunstart", 1.7f); - self->AddTimer("timeToStunLoop", 1); + self->AddTimer("timeToStunLoop", 1); - auto position = self->GetPosition(); - auto forward = self->GetRotation().GetForwardVector(); - auto backwards = forward * -1; + auto position = self->GetPosition(); + auto forward = self->GetRotation().GetForwardVector(); + auto backwards = forward * -1; - forward.x *= 10; - forward.z *= 10; + forward.x *= 10; + forward.z *= 10; - auto rotation = self->GetRotation(); + auto rotation = self->GetRotation(); - auto objectPosition = NiPoint3(); + auto objectPosition = NiPoint3(); - objectPosition.y = position.y; - objectPosition.x = position.x - (backwards.x * 8); - objectPosition.z = position.z - (backwards.z * 8); + objectPosition.y = position.y; + objectPosition.x = position.x - (backwards.x * 8); + objectPosition.z = position.z - (backwards.z * 8); - auto golem = self->GetVar(u"DragonSmashingGolem"); + auto golem = self->GetVar(u"DragonSmashingGolem"); - EntityInfo info {}; - info.lot = golem != 0 ? golem : 8340; - info.pos = objectPosition; - info.rot = rotation; - info.spawnerID = self->GetObjectID(); - info.settings = { - new LDFData(u"rebuild_activators", - std::to_string(objectPosition.x + forward.x) + "\x1f" + - std::to_string(objectPosition.y) + "\x1f" + - std::to_string(objectPosition.z + forward.z) - ), - new LDFData(u"respawn", 100000), - new LDFData(u"rebuild_reset_time", 15), - new LDFData(u"no_timed_spawn", true), - new LDFData(u"Dragon", self->GetObjectID()) - }; + EntityInfo info{}; + info.lot = golem != 0 ? golem : 8340; + info.pos = objectPosition; + info.rot = rotation; + info.spawnerID = self->GetObjectID(); + info.settings = { + new LDFData(u"rebuild_activators", + std::to_string(objectPosition.x + forward.x) + "\x1f" + + std::to_string(objectPosition.y) + "\x1f" + + std::to_string(objectPosition.z + forward.z) + ), + new LDFData(u"respawn", 100000), + new LDFData(u"rebuild_reset_time", 15), + new LDFData(u"no_timed_spawn", true), + new LDFData(u"Dragon", self->GetObjectID()) + }; - auto* golemObject = EntityManager::Instance()->CreateEntity(info); + auto* golemObject = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(golemObject); - } - } + EntityManager::Instance()->ConstructEntity(golemObject); + } + } } -void FvMaelstromDragon::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "ReviveHeldTimer") - { - self->AddTimer("backToAttack", 2.5); - } - else if (timerName == "ExposeWeakSpotTimer") - { - self->SetVar(u"weakspot", 1); - } - else if (timerName == "timeToStunLoop") - { - GameMessages::SendPlayAnimation(self, u"stunloop", 1.8f); - } - else if (timerName == "ReviveTimer") - { - GameMessages::SendPlayAnimation(self, u"stunend", 2.0f); - self->AddTimer("backToAttack", 1); - } - else if (timerName == "backToAttack") - { - auto* baseCombatAIComponent = self->GetComponent(); - auto* skillComponent = self->GetComponent(); +void FvMaelstromDragon::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "ReviveHeldTimer") { + self->AddTimer("backToAttack", 2.5); + } else if (timerName == "ExposeWeakSpotTimer") { + self->SetVar(u"weakspot", 1); + } else if (timerName == "timeToStunLoop") { + GameMessages::SendPlayAnimation(self, u"stunloop", 1.8f); + } else if (timerName == "ReviveTimer") { + GameMessages::SendPlayAnimation(self, u"stunend", 2.0f); + self->AddTimer("backToAttack", 1); + } else if (timerName == "backToAttack") { + auto* baseCombatAIComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (baseCombatAIComponent != nullptr) - { - baseCombatAIComponent->SetDisabled(false); - baseCombatAIComponent->SetStunned(false); - } + if (baseCombatAIComponent != nullptr) { + baseCombatAIComponent->SetDisabled(false); + baseCombatAIComponent->SetStunned(false); + } - if (skillComponent != nullptr) - { - skillComponent->Interrupt(); - } + if (skillComponent != nullptr) { + skillComponent->Interrupt(); + } - self->SetVar(u"weakspot", -1); + self->SetVar(u"weakspot", -1); - GameMessages::SendNotifyObject(self->GetObjectID(), self->GetObjectID(), u"DragonRevive", UNASSIGNED_SYSTEM_ADDRESS); - } + GameMessages::SendNotifyObject(self->GetObjectID(), self->GetObjectID(), u"DragonRevive", UNASSIGNED_SYSTEM_ADDRESS); + } } void -FvMaelstromDragon::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) -{ - if (args != "rebuildDone") return; +FvMaelstromDragon::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args != "rebuildDone") return; - self->AddTimer("ExposeWeakSpotTimer", 3.8f); + self->AddTimer("ExposeWeakSpotTimer", 3.8f); - self->CancelTimer("ReviveTimer"); + self->CancelTimer("ReviveTimer"); - self->AddTimer("ReviveHeldTimer", 10.5f); + self->AddTimer("ReviveHeldTimer", 10.5f); - self->SetVar(u"Golem", sender->GetObjectID()); + self->SetVar(u"Golem", sender->GetObjectID()); - GameMessages::SendPlayAnimation(self, u"quickbuildhold", 1.9f); + GameMessages::SendPlayAnimation(self, u"quickbuildhold", 1.9f); } diff --git a/dScripts/FvMaelstromDragon.h b/dScripts/FvMaelstromDragon.h index 52af80c4..d12e1bb4 100644 --- a/dScripts/FvMaelstromDragon.h +++ b/dScripts/FvMaelstromDragon.h @@ -1,13 +1,13 @@ #pragma once #include "CppScripts.h" -class FvMaelstromDragon : public CppScripts::Script +class FvMaelstromDragon : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnDie(Entity* self, Entity* killer) override; - void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/FvNinjaGuard.cpp b/dScripts/FvNinjaGuard.cpp index dc2bb54b..0a3cb19c 100644 --- a/dScripts/FvNinjaGuard.cpp +++ b/dScripts/FvNinjaGuard.cpp @@ -2,22 +2,16 @@ #include "GameMessages.h" #include "MissionComponent.h" -void FvNinjaGuard::OnStartup(Entity* self) -{ - if (self->GetLOT() == 7412) - { +void FvNinjaGuard::OnStartup(Entity* self) { + if (self->GetLOT() == 7412) { m_LeftGuard = self->GetObjectID(); - } - else if (self->GetLOT() == 11128) - { + } else if (self->GetLOT() == 11128) { m_RightGuard = self->GetObjectID(); } } -void FvNinjaGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* target) -{ - if (emote != 392) - { +void FvNinjaGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* target) { + if (emote != 392) { GameMessages::SendPlayAnimation(self, u"no"); return; @@ -27,26 +21,20 @@ void FvNinjaGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* ta auto* missionComponent = target->GetComponent(); - if (missionComponent != nullptr && missionComponent->HasMission(737)) - { + if (missionComponent != nullptr && missionComponent->HasMission(737)) { missionComponent->ForceProgressTaskType(737, 5, 1, false); } - if (self->GetLOT() == 7412) - { + if (self->GetLOT() == 7412) { auto* rightGuard = EntityManager::Instance()->GetEntity(m_RightGuard); - if (rightGuard != nullptr) - { + if (rightGuard != nullptr) { GameMessages::SendPlayAnimation(rightGuard, u"laugh_rt"); } - } - else if (self->GetLOT() == 11128) - { + } else if (self->GetLOT() == 11128) { auto* leftGuard = EntityManager::Instance()->GetEntity(m_LeftGuard); - if (leftGuard != nullptr) - { + if (leftGuard != nullptr) { GameMessages::SendPlayAnimation(leftGuard, u"laugh_lt"); } } diff --git a/dScripts/FvPandaServer.cpp b/dScripts/FvPandaServer.cpp index ea814936..bea93a6c 100644 --- a/dScripts/FvPandaServer.cpp +++ b/dScripts/FvPandaServer.cpp @@ -2,34 +2,34 @@ #include "PetComponent.h" #include "Character.h" -void FvPandaServer::OnStartup(Entity *self) { - const auto* petComponent = self->GetComponent(); - if (petComponent != nullptr && petComponent->GetOwner() == nullptr) { - self->SetNetworkVar(u"pandatamer", std::to_string(self->GetVar(u"tamer"))); - self->AddTimer("killSelf", 45); - } +void FvPandaServer::OnStartup(Entity* self) { + const auto* petComponent = self->GetComponent(); + if (petComponent != nullptr && petComponent->GetOwner() == nullptr) { + self->SetNetworkVar(u"pandatamer", std::to_string(self->GetVar(u"tamer"))); + self->AddTimer("killSelf", 45); + } } -void FvPandaServer::OnNotifyPetTamingMinigame(Entity *self, Entity *tamer, eNotifyType type) { - if (type == NOTIFY_TYPE_BEGIN) { - self->CancelAllTimers(); - } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { - self->Smash(); - } else if (type == NOTIFY_TYPE_SUCCESS) { - // TODO: Remove from groups +void FvPandaServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { + if (type == NOTIFY_TYPE_BEGIN) { + self->CancelAllTimers(); + } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { + self->Smash(); + } else if (type == NOTIFY_TYPE_SUCCESS) { + // TODO: Remove from groups - auto* character = tamer->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(82, true); - } - } + auto* character = tamer->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(82, true); + } + } } -void FvPandaServer::OnTimerDone(Entity *self, std::string timerName) { - if (timerName == "killSelf") { - const auto* petComponent = self->GetComponent(); - if (petComponent != nullptr && petComponent->GetOwner() == nullptr) { - self->Smash(self->GetObjectID(), SILENT); - } - } +void FvPandaServer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "killSelf") { + const auto* petComponent = self->GetComponent(); + if (petComponent != nullptr && petComponent->GetOwner() == nullptr) { + self->Smash(self->GetObjectID(), SILENT); + } + } } diff --git a/dScripts/FvPandaServer.h b/dScripts/FvPandaServer.h index 377371c1..4948fdf4 100644 --- a/dScripts/FvPandaServer.h +++ b/dScripts/FvPandaServer.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class FvPandaServer : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnNotifyPetTamingMinigame(Entity *self, Entity *tamer, eNotifyType type) override; - void OnTimerDone(Entity *self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/FvPandaSpawnerServer.cpp b/dScripts/FvPandaSpawnerServer.cpp index 97738271..e1f3fb96 100644 --- a/dScripts/FvPandaSpawnerServer.cpp +++ b/dScripts/FvPandaSpawnerServer.cpp @@ -4,45 +4,45 @@ #include "GameMessages.h" #include "ScriptedActivityComponent.h" -void FvPandaSpawnerServer::OnCollisionPhantom(Entity *self, Entity *target) { - auto* character = target->GetCharacter(); - if (character != nullptr && character->GetPlayerFlag(81)) { +void FvPandaSpawnerServer::OnCollisionPhantom(Entity* self, Entity* target) { + auto* character = target->GetCharacter(); + if (character != nullptr && character->GetPlayerFlag(81)) { - auto raceObjects = EntityManager::Instance()->GetEntitiesInGroup("PandaRaceObject"); - if (raceObjects.empty()) - return; + auto raceObjects = EntityManager::Instance()->GetEntitiesInGroup("PandaRaceObject"); + if (raceObjects.empty()) + return; - // Check if the player is currently in a footrace - auto* scriptedActivityComponent = raceObjects.at(0)->GetComponent(); - if (scriptedActivityComponent == nullptr || !scriptedActivityComponent->IsPlayedBy(target)) - return; + // Check if the player is currently in a footrace + auto* scriptedActivityComponent = raceObjects.at(0)->GetComponent(); + if (scriptedActivityComponent == nullptr || !scriptedActivityComponent->IsPlayedBy(target)) + return; - // If the player already spawned a panda - auto playerPandas = EntityManager::Instance()->GetEntitiesInGroup("panda" + std::to_string(target->GetObjectID())); - if (!playerPandas.empty()) { - GameMessages::SendFireEventClientSide(self->GetObjectID(), target->GetSystemAddress(), u"playerPanda", - target->GetObjectID(), 0, 0, target->GetObjectID()); - return; - } + // If the player already spawned a panda + auto playerPandas = EntityManager::Instance()->GetEntitiesInGroup("panda" + std::to_string(target->GetObjectID())); + if (!playerPandas.empty()) { + GameMessages::SendFireEventClientSide(self->GetObjectID(), target->GetSystemAddress(), u"playerPanda", + target->GetObjectID(), 0, 0, target->GetObjectID()); + return; + } - // If there's already too many spawned pandas - auto pandas = EntityManager::Instance()->GetEntitiesInGroup("pandas"); - if (pandas.size() > 4) { - GameMessages::SendFireEventClientSide(self->GetObjectID(), target->GetSystemAddress(), u"tooManyPandas", - target->GetObjectID(), 0, 0, target->GetObjectID()); - return; - } + // If there's already too many spawned pandas + auto pandas = EntityManager::Instance()->GetEntitiesInGroup("pandas"); + if (pandas.size() > 4) { + GameMessages::SendFireEventClientSide(self->GetObjectID(), target->GetSystemAddress(), u"tooManyPandas", + target->GetObjectID(), 0, 0, target->GetObjectID()); + return; + } - EntityInfo info {}; - info.spawnerID = target->GetObjectID(); - info.pos = self->GetPosition(); - info.lot = 5643; - info.settings = { - new LDFData(u"tamer", target->GetObjectID()), - new LDFData(u"groupID", u"panda" + (GeneralUtils::to_u16string(target->GetObjectID())) + u";pandas") - }; + EntityInfo info{}; + info.spawnerID = target->GetObjectID(); + info.pos = self->GetPosition(); + info.lot = 5643; + info.settings = { + new LDFData(u"tamer", target->GetObjectID()), + new LDFData(u"groupID", u"panda" + (GeneralUtils::to_u16string(target->GetObjectID())) + u";pandas") + }; - auto* panda = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(panda); - } + auto* panda = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(panda); + } } diff --git a/dScripts/FvPandaSpawnerServer.h b/dScripts/FvPandaSpawnerServer.h index 0aa459e5..5c138240 100644 --- a/dScripts/FvPandaSpawnerServer.h +++ b/dScripts/FvPandaSpawnerServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class FvPandaSpawnerServer : public CppScripts::Script { - void OnCollisionPhantom(Entity *self, Entity *target) override; + void OnCollisionPhantom(Entity* self, Entity* target) override; }; diff --git a/dScripts/FvPassThroughWall.cpp b/dScripts/FvPassThroughWall.cpp index e894f923..08de5a77 100644 --- a/dScripts/FvPassThroughWall.cpp +++ b/dScripts/FvPassThroughWall.cpp @@ -3,16 +3,16 @@ #include "MissionComponent.h" void FvPassThroughWall::OnCollisionPhantom(Entity* self, Entity* target) { - auto missionComponent = target->GetComponent(); - if (missionComponent == nullptr) return; + auto missionComponent = target->GetComponent(); + if (missionComponent == nullptr) return; - //Because at the moment we do not have an ItemComponent component, we check to make sure a Maelstrom-Infused hood is equipped. There are only three in the game right now. - auto inventoryComponent = target->GetComponent(); - // If no inventory component is found then abort. - if (inventoryComponent == nullptr) return; - // If no Maelstrom hoods are equipped then abort. - if (!inventoryComponent->IsEquipped(WhiteMaelstromHood) && !inventoryComponent->IsEquipped(BlackMaelstromHood) && !inventoryComponent->IsEquipped(RedMaelstromHood)) return; + //Because at the moment we do not have an ItemComponent component, we check to make sure a Maelstrom-Infused hood is equipped. There are only three in the game right now. + auto inventoryComponent = target->GetComponent(); + // If no inventory component is found then abort. + if (inventoryComponent == nullptr) return; + // If no Maelstrom hoods are equipped then abort. + if (!inventoryComponent->IsEquipped(WhiteMaelstromHood) && !inventoryComponent->IsEquipped(BlackMaelstromHood) && !inventoryComponent->IsEquipped(RedMaelstromHood)) return; - // Progress mission Friend of the Ninja since all prerequisites are met. - missionComponent->ForceProgress(friendOfTheNinjaMissionId, friendOfTheNinjaMissionUid, 1); -} \ No newline at end of file + // Progress mission Friend of the Ninja since all prerequisites are met. + missionComponent->ForceProgress(friendOfTheNinjaMissionId, friendOfTheNinjaMissionUid, 1); +} diff --git a/dScripts/FvPassThroughWall.h b/dScripts/FvPassThroughWall.h index 4dacc74e..2f996118 100644 --- a/dScripts/FvPassThroughWall.h +++ b/dScripts/FvPassThroughWall.h @@ -3,32 +3,32 @@ class FvPassThroughWall : public CppScripts::Script { - /** - * @brief This method is called when there is a collision with self from target. - * - * @param self The Entity that called this method. - * @param target The Entity that self is targetting. - */ - void OnCollisionPhantom(Entity* self, Entity* target) override; + /** + * @brief This method is called when there is a collision with self from target. + * + * @param self The Entity that called this method. + * @param target The Entity that self is targetting. + */ + void OnCollisionPhantom(Entity* self, Entity* target) override; private: - /** - * Mission ID for Friend of the Ninjas. - */ - int32_t friendOfTheNinjaMissionId = 848; - /** - * Mission UID for Friend of the Ninjas. - */ - int32_t friendOfTheNinjaMissionUid = 1221; - /** - * Item LOT for Maelstrom-Infused White Ninja Hood - */ - int32_t WhiteMaelstromHood = 2641; - /** - * Item LOT for Maelstrom-Infused Black Ninja Hood - */ - int32_t BlackMaelstromHood = 2642; - /** - * Item LOT for Red Ninja Hood - Maelstrom Infused - */ - int32_t RedMaelstromHood = 1889; -}; \ No newline at end of file + /** + * Mission ID for Friend of the Ninjas. + */ + int32_t friendOfTheNinjaMissionId = 848; + /** + * Mission UID for Friend of the Ninjas. + */ + int32_t friendOfTheNinjaMissionUid = 1221; + /** + * Item LOT for Maelstrom-Infused White Ninja Hood + */ + int32_t WhiteMaelstromHood = 2641; + /** + * Item LOT for Maelstrom-Infused Black Ninja Hood + */ + int32_t BlackMaelstromHood = 2642; + /** + * Item LOT for Red Ninja Hood - Maelstrom Infused + */ + int32_t RedMaelstromHood = 1889; +}; diff --git a/dScripts/FvRaceSmashEggImagineServer.cpp b/dScripts/FvRaceSmashEggImagineServer.cpp index 696504e2..32dbf619 100644 --- a/dScripts/FvRaceSmashEggImagineServer.cpp +++ b/dScripts/FvRaceSmashEggImagineServer.cpp @@ -6,33 +6,33 @@ #include "RacingTaskParam.h" #include "MissionComponent.h" -void FvRaceSmashEggImagineServer::OnDie(Entity *self, Entity *killer) { - if (killer != nullptr) { - auto* destroyableComponent = killer->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetImagination(destroyableComponent->GetImagination() + 10); - EntityManager::Instance()->SerializeEntity(killer); - } +void FvRaceSmashEggImagineServer::OnDie(Entity* self, Entity* killer) { + if (killer != nullptr) { + auto* destroyableComponent = killer->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetImagination(destroyableComponent->GetImagination() + 10); + EntityManager::Instance()->SerializeEntity(killer); + } - // get possessor to progress statistics and tasks. - auto* possessableComponent = killer->GetComponent(); - if (possessableComponent != nullptr) { + // get possessor to progress statistics and tasks. + auto* possessableComponent = killer->GetComponent(); + if (possessableComponent != nullptr) { - auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (possessor != nullptr) { + auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); + if (possessor != nullptr) { - auto* missionComponent = possessor->GetComponent(); - auto* characterComponent = possessor->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(ImaginationPowerUpsCollected); - characterComponent->UpdatePlayerStatistic(RacingSmashablesSmashed); - } - if (missionComponent == nullptr) return; - // Dragon eggs have their own smash server so we handle mission progression for them here. - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASH_SPECIFIC_SMASHABLE); - } - } + auto* missionComponent = possessor->GetComponent(); + auto* characterComponent = possessor->GetComponent(); + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(ImaginationPowerUpsCollected); + characterComponent->UpdatePlayerStatistic(RacingSmashablesSmashed); + } + if (missionComponent == nullptr) return; + // Dragon eggs have their own smash server so we handle mission progression for them here. + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASH_SPECIFIC_SMASHABLE); + } + } - } + } } diff --git a/dScripts/FvRaceSmashEggImagineServer.h b/dScripts/FvRaceSmashEggImagineServer.h index 7c682c36..dd697440 100644 --- a/dScripts/FvRaceSmashEggImagineServer.h +++ b/dScripts/FvRaceSmashEggImagineServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class FvRaceSmashEggImagineServer : public CppScripts::Script { - void OnDie(Entity *self, Entity *killer) override; + void OnDie(Entity* self, Entity* killer) override; }; diff --git a/dScripts/GfApeSmashingQB.cpp b/dScripts/GfApeSmashingQB.cpp index 973cb728..5bba6450 100644 --- a/dScripts/GfApeSmashingQB.cpp +++ b/dScripts/GfApeSmashingQB.cpp @@ -2,21 +2,21 @@ #include "EntityManager.h" #include "GameMessages.h" -void GfApeSmashingQB::OnStartup(Entity *self) { - self->SetNetworkVar(u"lootTagOwner", self->GetVar(u"lootTagOwner")); +void GfApeSmashingQB::OnStartup(Entity* self) { + self->SetNetworkVar(u"lootTagOwner", self->GetVar(u"lootTagOwner")); } -void GfApeSmashingQB::OnTimerDone(Entity *self, std::string timerName) { - if (timerName == "anchorBreakTime") { - self->Smash(); - } +void GfApeSmashingQB::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "anchorBreakTime") { + self->Smash(); + } } -void GfApeSmashingQB::OnRebuildComplete(Entity *self, Entity *target) { - auto* ape = EntityManager::Instance()->GetEntity(self->GetVar(u"ape")); - if (ape != nullptr) { - ape->OnFireEventServerSide(target, "rebuildDone"); - GameMessages::SendPlayAnimation(self, u"smash", 1.7f); - self->AddTimer("anchorBreakTime", 1.0f); - } +void GfApeSmashingQB::OnRebuildComplete(Entity* self, Entity* target) { + auto* ape = EntityManager::Instance()->GetEntity(self->GetVar(u"ape")); + if (ape != nullptr) { + ape->OnFireEventServerSide(target, "rebuildDone"); + GameMessages::SendPlayAnimation(self, u"smash", 1.7f); + self->AddTimer("anchorBreakTime", 1.0f); + } } diff --git a/dScripts/GfApeSmashingQB.h b/dScripts/GfApeSmashingQB.h index 825fe916..0306c260 100644 --- a/dScripts/GfApeSmashingQB.h +++ b/dScripts/GfApeSmashingQB.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class GfApeSmashingQB : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnTimerDone(Entity *self, std::string timerName) override; - void OnRebuildComplete(Entity *self, Entity *target) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnRebuildComplete(Entity* self, Entity* target) override; }; diff --git a/dScripts/GfBanana.cpp b/dScripts/GfBanana.cpp index 346c9ad7..d64f1620 100644 --- a/dScripts/GfBanana.cpp +++ b/dScripts/GfBanana.cpp @@ -4,16 +4,15 @@ #include "DestroyableComponent.h" #include "EntityManager.h" -void GfBanana::SpawnBanana(Entity* self) -{ +void GfBanana::SpawnBanana(Entity* self) { auto position = self->GetPosition(); const auto rotation = self->GetRotation(); - + position.y += 12; position.x -= rotation.GetRightVector().x * 5; position.z -= rotation.GetRightVector().z * 5; - EntityInfo info {}; + EntityInfo info{}; info.pos = position; info.rot = rotation; @@ -26,21 +25,18 @@ void GfBanana::SpawnBanana(Entity* self) self->SetVar(u"banana", entity->GetObjectID()); - entity->AddDieCallback([self]() - { + entity->AddDieCallback([self]() { self->SetVar(u"banana", LWOOBJID_EMPTY); self->AddTimer("bananaTimer", 30); - }); + }); } -void GfBanana::OnStartup(Entity* self) -{ +void GfBanana::OnStartup(Entity* self) { SpawnBanana(self); } -void GfBanana::OnHit(Entity* self, Entity* attacker) -{ +void GfBanana::OnHit(Entity* self, Entity* attacker) { auto* destroyable = self->GetComponent(); destroyable->SetHealth(9999); @@ -51,15 +47,14 @@ void GfBanana::OnHit(Entity* self, Entity* attacker) auto* bananaEntity = EntityManager::Instance()->GetEntity(bananaId); - if (bananaEntity == nullptr) - { + if (bananaEntity == nullptr) { self->SetVar(u"banana", LWOOBJID_EMPTY); self->AddTimer("bananaTimer", 30); return; } - + bananaEntity->SetPosition(bananaEntity->GetPosition() - NiPoint3::UNIT_Y * 8); auto* bananaDestroyable = bananaEntity->GetComponent(); @@ -71,7 +66,7 @@ void GfBanana::OnHit(Entity* self, Entity* attacker) /* auto position = self->GetPosition(); const auto rotation = self->GetRotation(); - + position.y += 12; position.x -= rotation.GetRightVector().x * 5; position.z -= rotation.GetRightVector().z * 5; @@ -91,10 +86,8 @@ void GfBanana::OnHit(Entity* self, Entity* attacker) EntityManager::Instance()->SerializeEntity(self); } -void GfBanana::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "bananaTimer") - { +void GfBanana::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "bananaTimer") { SpawnBanana(self); } -} \ No newline at end of file +} diff --git a/dScripts/GfBanana.h b/dScripts/GfBanana.h index d572c8d9..8deb2396 100644 --- a/dScripts/GfBanana.h +++ b/dScripts/GfBanana.h @@ -5,9 +5,9 @@ class GfBanana final : public CppScripts::Script { public: void SpawnBanana(Entity* self); - + void OnStartup(Entity* self) override; - + void OnHit(Entity* self, Entity* attacker) override; void OnTimerDone(Entity* self, std::string timerName) override; diff --git a/dScripts/GfBananaCluster.cpp b/dScripts/GfBananaCluster.cpp index aacba224..19d1b489 100644 --- a/dScripts/GfBananaCluster.cpp +++ b/dScripts/GfBananaCluster.cpp @@ -1,15 +1,12 @@ #include "GfBananaCluster.h" #include "Entity.h" -void GfBananaCluster::OnStartup(Entity* self) -{ +void GfBananaCluster::OnStartup(Entity* self) { self->AddTimer("startup", 100); } -void GfBananaCluster::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "startup") - { +void GfBananaCluster::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "startup") { self->ScheduleKillAfterUpdate(nullptr); } } diff --git a/dScripts/GfCampfire.cpp b/dScripts/GfCampfire.cpp index 48170c66..95e29a9a 100644 --- a/dScripts/GfCampfire.cpp +++ b/dScripts/GfCampfire.cpp @@ -17,10 +17,9 @@ void GfCampfire::OnStartup(Entity* self) { render->PlayEffect(295, u"running", "Burn"); } -void GfCampfire::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "physicsReady") - { +void GfCampfire::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "physicsReady") { auto* render = static_cast(self->GetComponent(COMPONENT_TYPE_RENDER)); render->PlayEffect(295, u"running", "Burn"); @@ -45,14 +44,12 @@ void GfCampfire::OnProximityUpdate(Entity* self, Entity* entering, std::string n auto* missionComponet = entering->GetComponent(); - if (missionComponet != nullptr) - { + if (missionComponet != nullptr) { missionComponet->ForceProgress(440, 658, 1); } } } - } - else { + } else { int32_t counter = self->GetI32(u"counter"); if (counter > 0) { counter = counter - 1; @@ -65,22 +62,21 @@ void GfCampfire::OnProximityUpdate(Entity* self, Entity* entering, std::string n } } -void GfCampfire::OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) { - if (message == "waterspray" && self->GetVar(u"isBurning")) { - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("Burn"); - renderComponent->PlayEffect(295, u"idle", "Off"); +void GfCampfire::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message == "waterspray" && self->GetVar(u"isBurning")) { + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("Burn"); + renderComponent->PlayEffect(295, u"idle", "Off"); - self->SetVar(u"isBurning", false); - self->AddTimer("FireRestart", 37); - } - } + self->SetVar(u"isBurning", false); + self->AddTimer("FireRestart", 37); + } + } } void GfCampfire::OnTimerDone(Entity* self, std::string timerName) { - if (timerName == "TimeBetweenCast") - { + if (timerName == "TimeBetweenCast") { /* self->AddTimer("TimeBetweenCast", FIRE_COOLDOWN); @@ -90,15 +86,15 @@ void GfCampfire::OnTimerDone(Entity* self, std::string timerName) { if (entering == nullptr) { - + } */ } else if (timerName == "FireRestart" && !self->GetVar(u"isBurning")) { - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("Off"); - renderComponent->PlayEffect(295, u"running", "Burn"); - self->SetVar(u"isBurning", true); - } + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("Off"); + renderComponent->PlayEffect(295, u"running", "Burn"); + self->SetVar(u"isBurning", true); + } } } diff --git a/dScripts/GfCampfire.h b/dScripts/GfCampfire.h index 9e678419..b1d61721 100644 --- a/dScripts/GfCampfire.h +++ b/dScripts/GfCampfire.h @@ -1,16 +1,16 @@ #pragma once #include "CppScripts.h" -class GfCampfire : public CppScripts::Script +class GfCampfire : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; void OnTimerDone(Entity* self, std::string timerName) override; - void OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; private: int32_t m_skillCastId = 43; int32_t FIRE_COOLDOWN = 2; -}; \ No newline at end of file +}; diff --git a/dScripts/GfCaptainsCannon.cpp b/dScripts/GfCaptainsCannon.cpp index ee973a13..7d67c781 100644 --- a/dScripts/GfCaptainsCannon.cpp +++ b/dScripts/GfCaptainsCannon.cpp @@ -3,90 +3,81 @@ #include "EntityManager.h" #include "MissionComponent.h" -void GfCaptainsCannon::OnUse(Entity* self, Entity* user) -{ - if (self->GetVar(u"bIsInUse")) - { - return; - } - - self->SetVar(u"userID", user->GetObjectID()); +void GfCaptainsCannon::OnUse(Entity* self, Entity* user) { + if (self->GetVar(u"bIsInUse")) { + return; + } - self->SetVar(u"bIsInUse", true); - self->SetNetworkVar(u"bIsInUse", true); + self->SetVar(u"userID", user->GetObjectID()); - GameMessages::SendSetStunned(user->GetObjectID(), PUSH, user->GetSystemAddress(), - LWOOBJID_EMPTY, true, true, true, true, true, true, true, true - ); + self->SetVar(u"bIsInUse", true); + self->SetNetworkVar(u"bIsInUse", true); - auto position = self->GetPosition(); - auto forward = self->GetRotation().GetForwardVector(); + GameMessages::SendSetStunned(user->GetObjectID(), PUSH, user->GetSystemAddress(), + LWOOBJID_EMPTY, true, true, true, true, true, true, true, true + ); - position.x += forward.x * -3; - position.z += forward.z * -3; + auto position = self->GetPosition(); + auto forward = self->GetRotation().GetForwardVector(); - auto rotation = self->GetRotation(); + position.x += forward.x * -3; + position.z += forward.z * -3; - GameMessages::SendTeleport(user->GetObjectID(), position, rotation, user->GetSystemAddress()); + auto rotation = self->GetRotation(); - GameMessages::SendPlayAnimation(user, u"cannon-strike-no-equip"); + GameMessages::SendTeleport(user->GetObjectID(), position, rotation, user->GetSystemAddress()); - GameMessages::SendPlayFXEffect(user->GetObjectID(), 6039, u"hook", "hook", LWOOBJID_EMPTY, 1, 1, true); + GameMessages::SendPlayAnimation(user, u"cannon-strike-no-equip"); - self->AddTimer("FireCannon", 1.667f); + GameMessages::SendPlayFXEffect(user->GetObjectID(), 6039, u"hook", "hook", LWOOBJID_EMPTY, 1, 1, true); + + self->AddTimer("FireCannon", 1.667f); } -void GfCaptainsCannon::OnTimerDone(Entity* self, std::string timerName) -{ - const auto playerId = self->GetVar(u"userID"); +void GfCaptainsCannon::OnTimerDone(Entity* self, std::string timerName) { + const auto playerId = self->GetVar(u"userID"); - auto* player = EntityManager::Instance()->GetEntity(playerId); + auto* player = EntityManager::Instance()->GetEntity(playerId); - if (player == nullptr) - { - self->SetVar(u"bIsInUse", false); - self->SetNetworkVar(u"bIsInUse", false); + if (player == nullptr) { + self->SetVar(u"bIsInUse", false); + self->SetNetworkVar(u"bIsInUse", false); - return; - } + return; + } - if (timerName == "FireCannon") - { - float cinematicTime = 6.3f; + if (timerName == "FireCannon") { + float cinematicTime = 6.3f; - GameMessages::SendPlayCinematic(playerId, u"Cannon_Cam", player->GetSystemAddress()); + GameMessages::SendPlayCinematic(playerId, u"Cannon_Cam", player->GetSystemAddress()); - self->AddTimer("cinematicTimer", cinematicTime); + self->AddTimer("cinematicTimer", cinematicTime); - const auto sharkObjects = EntityManager::Instance()->GetEntitiesInGroup("SharkCannon"); + const auto sharkObjects = EntityManager::Instance()->GetEntitiesInGroup("SharkCannon"); - for (auto* shark : sharkObjects) - { - if (shark->GetLOT() != m_SharkItemID) continue; + for (auto* shark : sharkObjects) { + if (shark->GetLOT() != m_SharkItemID) continue; - GameMessages::SendPlayAnimation(shark, u"cannon"); - } + GameMessages::SendPlayAnimation(shark, u"cannon"); + } - GameMessages::SendPlay2DAmbientSound(player, "{7457d85c-4537-4317-ac9d-2f549219ea87}"); - } - else if (timerName == "cinematicTimer") - { - GameMessages::SendSetStunned(playerId, POP, player->GetSystemAddress(), - LWOOBJID_EMPTY, true, true, true, true, true, true, true, true - ); + GameMessages::SendPlay2DAmbientSound(player, "{7457d85c-4537-4317-ac9d-2f549219ea87}"); + } else if (timerName == "cinematicTimer") { + GameMessages::SendSetStunned(playerId, POP, player->GetSystemAddress(), + LWOOBJID_EMPTY, true, true, true, true, true, true, true, true + ); - self->SetVar(u"bIsInUse", false); - self->SetNetworkVar(u"bIsInUse", false); + self->SetVar(u"bIsInUse", false); + self->SetNetworkVar(u"bIsInUse", false); - GameMessages::SendStopFXEffect(player, true, "hook"); + GameMessages::SendStopFXEffect(player, true, "hook"); - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->ForceProgress(601, 910, 1); - } + if (missionComponent != nullptr) { + missionComponent->ForceProgress(601, 910, 1); + } - GameMessages::SendTerminateInteraction(playerId, FROM_INTERACTION, self->GetObjectID()); - } + GameMessages::SendTerminateInteraction(playerId, FROM_INTERACTION, self->GetObjectID()); + } } diff --git a/dScripts/GfCaptainsCannon.h b/dScripts/GfCaptainsCannon.h index 44dd791c..23429b5d 100644 --- a/dScripts/GfCaptainsCannon.h +++ b/dScripts/GfCaptainsCannon.h @@ -1,11 +1,11 @@ #pragma once #include "CppScripts.h" -class GfCaptainsCannon : public CppScripts::Script +class GfCaptainsCannon : public CppScripts::Script { public: - void OnUse(Entity* self, Entity* user) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnUse(Entity* self, Entity* user) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: int32_t m_SharkItemID = 7343; }; diff --git a/dScripts/GfJailWalls.cpp b/dScripts/GfJailWalls.cpp index da547d0b..56710832 100644 --- a/dScripts/GfJailWalls.cpp +++ b/dScripts/GfJailWalls.cpp @@ -2,34 +2,28 @@ #include "dZoneManager.h" #include "GeneralUtils.h" -void GfJailWalls::OnRebuildComplete(Entity* self, Entity* target) -{ - const auto wall = GeneralUtils::UTF16ToWTF8(self->GetVar(u"Wall")); +void GfJailWalls::OnRebuildComplete(Entity* self, Entity* target) { + const auto wall = GeneralUtils::UTF16ToWTF8(self->GetVar(u"Wall")); - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("Jail0" + wall)) - { - spawner->Deactivate(); - } - - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("JailCaptain0" + wall)) - { - spawner->Deactivate(); - } + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("Jail0" + wall)) { + spawner->Deactivate(); + } + + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("JailCaptain0" + wall)) { + spawner->Deactivate(); + } } -void GfJailWalls::OnRebuildNotifyState(Entity* self, eRebuildState state) -{ - if (state != eRebuildState::REBUILD_RESETTING) return; +void GfJailWalls::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state != eRebuildState::REBUILD_RESETTING) return; - const auto wall = GeneralUtils::UTF16ToWTF8(self->GetVar(u"Wall")); + const auto wall = GeneralUtils::UTF16ToWTF8(self->GetVar(u"Wall")); - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("Jail0" + wall)) - { - spawner->Activate(); - } - - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("JailCaptain0" + wall)) - { - spawner->Activate(); - } + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("Jail0" + wall)) { + spawner->Activate(); + } + + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName("JailCaptain0" + wall)) { + spawner->Activate(); + } } diff --git a/dScripts/GfJailWalls.h b/dScripts/GfJailWalls.h index 8f3ad54b..f755f4d7 100644 --- a/dScripts/GfJailWalls.h +++ b/dScripts/GfJailWalls.h @@ -1,9 +1,9 @@ #pragma once #include "CppScripts.h" -class GfJailWalls final : public CppScripts::Script +class GfJailWalls final : public CppScripts::Script { public: - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnRebuildNotifyState(Entity* self, eRebuildState state) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnRebuildNotifyState(Entity* self, eRebuildState state) override; }; diff --git a/dScripts/GfJailkeepMission.cpp b/dScripts/GfJailkeepMission.cpp index bf3b25f8..59f8db0e 100644 --- a/dScripts/GfJailkeepMission.cpp +++ b/dScripts/GfJailkeepMission.cpp @@ -2,39 +2,37 @@ #include "MissionComponent.h" #include "Character.h" -void GfJailkeepMission::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) -{ - auto* missionComponent = target->GetComponent(); - if (missionComponent == nullptr) - return; +void GfJailkeepMission::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + auto* missionComponent = target->GetComponent(); + if (missionComponent == nullptr) + return; - if (missionID == 385 && missionState == MissionState::MISSION_STATE_AVAILABLE) { - missionComponent->AcceptMission(386, true); - missionComponent->AcceptMission(387, true); - missionComponent->AcceptMission(388, true); - missionComponent->AcceptMission(390, true); - } else if (missionID == 385 && missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { - auto* character = target->GetCharacter(); - if (character != nullptr && character->GetPlayerFlag(68)) { - missionComponent->AcceptMission(701); - missionComponent->AcceptMission(702); - missionComponent->AcceptMission(703); - missionComponent->AcceptMission(704); - } - } + if (missionID == 385 && missionState == MissionState::MISSION_STATE_AVAILABLE) { + missionComponent->AcceptMission(386, true); + missionComponent->AcceptMission(387, true); + missionComponent->AcceptMission(388, true); + missionComponent->AcceptMission(390, true); + } else if (missionID == 385 && missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + auto* character = target->GetCharacter(); + if (character != nullptr && character->GetPlayerFlag(68)) { + missionComponent->AcceptMission(701); + missionComponent->AcceptMission(702); + missionComponent->AcceptMission(703); + missionComponent->AcceptMission(704); + } + } } -void GfJailkeepMission::OnUse(Entity* self, Entity* user) -{ - auto* missionComponent = user->GetComponent(); - if (missionComponent == nullptr) - return; +void GfJailkeepMission::OnUse(Entity* self, Entity* user) { + auto* missionComponent = user->GetComponent(); + if (missionComponent == nullptr) + return; - if (missionComponent->GetMissionState(385) == MissionState::MISSION_STATE_ACTIVE) { - missionComponent->AcceptMission(386, true); - missionComponent->AcceptMission(387, true); - missionComponent->AcceptMission(388, true); - missionComponent->AcceptMission(390, true); - } + if (missionComponent->GetMissionState(385) == MissionState::MISSION_STATE_ACTIVE) { + missionComponent->AcceptMission(386, true); + missionComponent->AcceptMission(387, true); + missionComponent->AcceptMission(388, true); + missionComponent->AcceptMission(390, true); + } } diff --git a/dScripts/GfJailkeepMission.h b/dScripts/GfJailkeepMission.h index 6c1b2a3e..f9410032 100644 --- a/dScripts/GfJailkeepMission.h +++ b/dScripts/GfJailkeepMission.h @@ -1,9 +1,9 @@ #pragma once #include "CppScripts.h" -class GfJailkeepMission final : public CppScripts::Script +class GfJailkeepMission final : public CppScripts::Script { public: - void OnUse(Entity* self, Entity* user) override; + void OnUse(Entity* self, Entity* user) override; void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; }; diff --git a/dScripts/GfOrgan.h b/dScripts/GfOrgan.h index 1ebd66a6..6af2d554 100644 --- a/dScripts/GfOrgan.h +++ b/dScripts/GfOrgan.h @@ -8,4 +8,4 @@ public: void OnTimerDone(Entity* self, std::string timerName); private: bool m_canUse; -}; \ No newline at end of file +}; diff --git a/dScripts/GfTikiTorch.cpp b/dScripts/GfTikiTorch.cpp index dd1c14a7..3a06b054 100644 --- a/dScripts/GfTikiTorch.cpp +++ b/dScripts/GfTikiTorch.cpp @@ -27,10 +27,9 @@ void GfTikiTorch::OnUse(Entity* self, Entity* killer) { void GfTikiTorch::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "Relight") { LightTorch(self); - } - else if (timerName == "InteractionCooldown") { + } else if (timerName == "InteractionCooldown") { Entity* player = EntityManager::Instance()->GetEntity(self->GetI64(u"userID")); - + if (player != nullptr && player->GetCharacter()) { GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } @@ -45,32 +44,32 @@ void GfTikiTorch::LightTorch(Entity* self) { auto* renderComponent = static_cast(self->GetComponent(COMPONENT_TYPE_RENDER)); if (renderComponent == nullptr) return; - + self->SetBoolean(u"isInUse", false); renderComponent->PlayEffect(611, u"fire", "tikitorch"); self->SetBoolean(u"isBurning", true); } -void GfTikiTorch::OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) { - if (self->GetBoolean(u"isBurning") && message == "waterspray") { - GameMessages::SendPlayAnimation(self, u"water"); +void GfTikiTorch::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (self->GetBoolean(u"isBurning") && message == "waterspray") { + GameMessages::SendPlayAnimation(self, u"water"); - auto* renderComponent = self->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("tikitorch"); - renderComponent->PlayEffect(611, u"water", "water"); - renderComponent->PlayEffect(611, u"steam", "steam"); - } + auto* renderComponent = self->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("tikitorch"); + renderComponent->PlayEffect(611, u"water", "water"); + renderComponent->PlayEffect(611, u"steam", "steam"); + } - auto* casterMissionComponent = caster->GetComponent(); - if (casterMissionComponent != nullptr) { - for (const auto missionID : m_missions) { - casterMissionComponent->ForceProgressTaskType(missionID, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); - } - } + auto* casterMissionComponent = caster->GetComponent(); + if (casterMissionComponent != nullptr) { + for (const auto missionID : m_missions) { + casterMissionComponent->ForceProgressTaskType(missionID, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); + } + } - self->AddTimer("Relight", 7.0f); - self->SetBoolean(u"isBurning", false); - } + self->AddTimer("Relight", 7.0f); + self->SetBoolean(u"isBurning", false); + } } diff --git a/dScripts/GfTikiTorch.h b/dScripts/GfTikiTorch.h index e9046ddc..5d3de0a8 100644 --- a/dScripts/GfTikiTorch.h +++ b/dScripts/GfTikiTorch.h @@ -1,17 +1,17 @@ #pragma once #include "CppScripts.h" -class GfTikiTorch : public CppScripts::Script +class GfTikiTorch : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnUse(Entity* self, Entity* killer) override; void OnTimerDone(Entity* self, std::string timerName) override; - void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; private: void LightTorch(Entity* self); LOT m_imaginationlot = 935; int32_t m_numspawn = 3; - std::vector m_missions = {472, 1429, 1527, 1564, 1601}; -}; \ No newline at end of file + std::vector m_missions = { 472, 1429, 1527, 1564, 1601 }; +}; diff --git a/dScripts/GrowingFlower.cpp b/dScripts/GrowingFlower.cpp index 1acb2455..7b495841 100644 --- a/dScripts/GrowingFlower.cpp +++ b/dScripts/GrowingFlower.cpp @@ -1,35 +1,35 @@ #include "GrowingFlower.h" #include "MissionComponent.h" -void GrowingFlower::OnSkillEventFired(Entity *self, Entity *target, const std::string &message) { - if (!self->GetVar(u"blooming") && (message == "waterspray" || message == "shovelgrow")) { - self->SetVar(u"blooming", true); - self->SetNetworkVar(u"blooming", true); - self->AddTimer("FlowerDie", GrowingFlower::aliveTime); +void GrowingFlower::OnSkillEventFired(Entity* self, Entity* target, const std::string& message) { + if (!self->GetVar(u"blooming") && (message == "waterspray" || message == "shovelgrow")) { + self->SetVar(u"blooming", true); + self->SetNetworkVar(u"blooming", true); + self->AddTimer("FlowerDie", GrowingFlower::aliveTime); - const auto mission1 = self->GetVar(u"missionID"); - const auto mission2 = self->GetVar(u"missionID2"); + const auto mission1 = self->GetVar(u"missionID"); + const auto mission2 = self->GetVar(u"missionID2"); - LootGenerator::Instance().DropActivityLoot(target, self, self->GetLOT(), 0); + LootGenerator::Instance().DropActivityLoot(target, self, self->GetLOT(), 0); - auto* missionComponent = target->GetComponent(); - if (missionComponent != nullptr) { - for (const auto mission : achievementIDs) - missionComponent->ForceProgressTaskType(mission, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); + auto* missionComponent = target->GetComponent(); + if (missionComponent != nullptr) { + for (const auto mission : achievementIDs) + missionComponent->ForceProgressTaskType(mission, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); - if (mission1 && missionComponent->GetMissionState(mission1) == MissionState::MISSION_STATE_ACTIVE) - missionComponent->ForceProgressTaskType(mission1, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); + if (mission1 && missionComponent->GetMissionState(mission1) == MissionState::MISSION_STATE_ACTIVE) + missionComponent->ForceProgressTaskType(mission1, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); - if (mission2 && missionComponent->GetMissionState(mission2) == MissionState::MISSION_STATE_ACTIVE) - missionComponent->ForceProgressTaskType(mission2, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); - } - } + if (mission2 && missionComponent->GetMissionState(mission2) == MissionState::MISSION_STATE_ACTIVE) + missionComponent->ForceProgressTaskType(mission2, static_cast(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); + } + } } -void GrowingFlower::OnTimerDone(Entity *self, std::string message) { - if (message == "FlowerDie") { - self->Smash(); - } +void GrowingFlower::OnTimerDone(Entity* self, std::string message) { + if (message == "FlowerDie") { + self->Smash(); + } } const std::vector GrowingFlower::achievementIDs = { 143, 152, 153, 1409, 1507, 1544, 1581, 1845 }; diff --git a/dScripts/GrowingFlower.h b/dScripts/GrowingFlower.h index 92fc0035..b7090855 100644 --- a/dScripts/GrowingFlower.h +++ b/dScripts/GrowingFlower.h @@ -3,9 +3,9 @@ class GrowingFlower : public CppScripts::Script { public: - void OnSkillEventFired(Entity* self, Entity* target, const std::string& message) override; - void OnTimerDone(Entity* self, std::string message) override; + void OnSkillEventFired(Entity* self, Entity* target, const std::string& message) override; + void OnTimerDone(Entity* self, std::string message) override; private: - static const std::vector achievementIDs; - constexpr static const float aliveTime = 16.0f; -}; \ No newline at end of file + static const std::vector achievementIDs; + constexpr static const float aliveTime = 16.0f; +}; diff --git a/dScripts/HydrantBroken.cpp b/dScripts/HydrantBroken.cpp index 2b620a21..1409c9fb 100644 --- a/dScripts/HydrantBroken.cpp +++ b/dScripts/HydrantBroken.cpp @@ -2,43 +2,36 @@ #include "EntityManager.h" #include "GameMessages.h" -void HydrantBroken::OnStartup(Entity* self) -{ - self->AddTimer("playEffect", 1); +void HydrantBroken::OnStartup(Entity* self) { + self->AddTimer("playEffect", 1); - const auto hydrant = "hydrant" + self->GetVar(u"hydrant"); + const auto hydrant = "hydrant" + self->GetVar(u"hydrant"); - const auto bouncers = EntityManager::Instance()->GetEntitiesInGroup(hydrant); + const auto bouncers = EntityManager::Instance()->GetEntitiesInGroup(hydrant); - for (auto* bouncer : bouncers) - { - self->SetVar(u"bouncer", bouncer->GetObjectID()); + for (auto* bouncer : bouncers) { + self->SetVar(u"bouncer", bouncer->GetObjectID()); - GameMessages::SendBouncerActiveStatus(bouncer->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendBouncerActiveStatus(bouncer->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendNotifyObject(bouncer->GetObjectID(), self->GetObjectID(), u"enableCollision", UNASSIGNED_SYSTEM_ADDRESS); - } + GameMessages::SendNotifyObject(bouncer->GetObjectID(), self->GetObjectID(), u"enableCollision", UNASSIGNED_SYSTEM_ADDRESS); + } - self->AddTimer("KillBroken", 25); + self->AddTimer("KillBroken", 25); } -void HydrantBroken::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "KillBroken") - { - auto* bouncer = EntityManager::Instance()->GetEntity(self->GetVar(u"bouncer")); +void HydrantBroken::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "KillBroken") { + auto* bouncer = EntityManager::Instance()->GetEntity(self->GetVar(u"bouncer")); - if (bouncer != nullptr) - { - GameMessages::SendBouncerActiveStatus(bouncer->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); + if (bouncer != nullptr) { + GameMessages::SendBouncerActiveStatus(bouncer->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendNotifyObject(bouncer->GetObjectID(), self->GetObjectID(), u"disableCollision", UNASSIGNED_SYSTEM_ADDRESS); - } + GameMessages::SendNotifyObject(bouncer->GetObjectID(), self->GetObjectID(), u"disableCollision", UNASSIGNED_SYSTEM_ADDRESS); + } - self->Kill(); - } - else if (timerName == "playEffect") - { - GameMessages::SendPlayFXEffect(self->GetObjectID(), 384, u"water", "water", LWOOBJID_EMPTY, 1, 1, true); - } + self->Kill(); + } else if (timerName == "playEffect") { + GameMessages::SendPlayFXEffect(self->GetObjectID(), 384, u"water", "water", LWOOBJID_EMPTY, 1, 1, true); + } } diff --git a/dScripts/HydrantBroken.h b/dScripts/HydrantBroken.h index 65f38604..9ed1f4ab 100644 --- a/dScripts/HydrantBroken.h +++ b/dScripts/HydrantBroken.h @@ -1,9 +1,9 @@ #pragma once #include "CppScripts.h" -class HydrantBroken : public CppScripts::Script +class HydrantBroken : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnTimerDone(Entity* self, std::string timerName) override; -}; \ No newline at end of file +}; diff --git a/dScripts/HydrantSmashable.cpp b/dScripts/HydrantSmashable.cpp index 5cdf84c9..20baa58b 100644 --- a/dScripts/HydrantSmashable.cpp +++ b/dScripts/HydrantSmashable.cpp @@ -2,20 +2,19 @@ #include "EntityManager.h" #include "GeneralUtils.h" -void HydrantSmashable::OnDie(Entity* self, Entity* killer) -{ - const auto hydrantName = self->GetVar(u"hydrant"); +void HydrantSmashable::OnDie(Entity* self, Entity* killer) { + const auto hydrantName = self->GetVar(u"hydrant"); - LDFBaseData* data = new LDFData(u"hydrant", GeneralUtils::UTF16ToWTF8(hydrantName)); + LDFBaseData* data = new LDFData(u"hydrant", GeneralUtils::UTF16ToWTF8(hydrantName)); - EntityInfo info {}; - info.lot = HYDRANT_BROKEN; - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.settings = {data}; - info.spawnerID = self->GetSpawnerID(); + EntityInfo info{}; + info.lot = HYDRANT_BROKEN; + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.settings = { data }; + info.spawnerID = self->GetSpawnerID(); - auto* hydrant = EntityManager::Instance()->CreateEntity(info); + auto* hydrant = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(hydrant); + EntityManager::Instance()->ConstructEntity(hydrant); } diff --git a/dScripts/HydrantSmashable.h b/dScripts/HydrantSmashable.h index 90b0f3a6..156f2e8f 100644 --- a/dScripts/HydrantSmashable.h +++ b/dScripts/HydrantSmashable.h @@ -7,4 +7,4 @@ public: void OnDie(Entity* self, Entity* killer) override; private: LOT HYDRANT_BROKEN = 7328; -}; \ No newline at end of file +}; diff --git a/dScripts/ImaginationBackpackHealServer.cpp b/dScripts/ImaginationBackpackHealServer.cpp index 1d7da2c5..1e0d35cf 100644 --- a/dScripts/ImaginationBackpackHealServer.cpp +++ b/dScripts/ImaginationBackpackHealServer.cpp @@ -2,19 +2,19 @@ #include "GameMessages.h" #include "MissionComponent.h" -void ImaginationBackpackHealServer::OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) { - if (message == "CastImaginationBackpack") { - auto healMission = self->GetVar(u"FXOffMis"); - if (healMission == 0) - healMission = self->GetVar(u"FXOnMis"); - if (healMission == 0) - return; +void ImaginationBackpackHealServer::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message == "CastImaginationBackpack") { + auto healMission = self->GetVar(u"FXOffMis"); + if (healMission == 0) + healMission = self->GetVar(u"FXOnMis"); + if (healMission == 0) + return; - auto* missionComponent = caster->GetComponent(); - if (missionComponent != nullptr && missionComponent->GetMissionState(healMission) == MissionState::MISSION_STATE_ACTIVE) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"ClearMaelstrom", 0, 0, - caster->GetObjectID(), "", caster->GetSystemAddress()); - } - } + auto* missionComponent = caster->GetComponent(); + if (missionComponent != nullptr && missionComponent->GetMissionState(healMission) == MissionState::MISSION_STATE_ACTIVE) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"ClearMaelstrom", 0, 0, + caster->GetObjectID(), "", caster->GetSystemAddress()); + } + } } diff --git a/dScripts/ImaginationBackpackHealServer.h b/dScripts/ImaginationBackpackHealServer.h index 387f38d7..dbe5ab01 100644 --- a/dScripts/ImaginationBackpackHealServer.h +++ b/dScripts/ImaginationBackpackHealServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class ImaginationBackpackHealServer : public CppScripts::Script { - void OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; }; diff --git a/dScripts/ImaginationShrineServer.cpp b/dScripts/ImaginationShrineServer.cpp index 54c02614..267d0480 100644 --- a/dScripts/ImaginationShrineServer.cpp +++ b/dScripts/ImaginationShrineServer.cpp @@ -1,19 +1,16 @@ #include "ImaginationShrineServer.h" #include "RebuildComponent.h" -void ImaginationShrineServer::OnUse(Entity* self, Entity* user) -{ - // If the rebuild component is complete, use the shrine - auto* rebuildComponent = self->GetComponent(); +void ImaginationShrineServer::OnUse(Entity* self, Entity* user) { + // If the rebuild component is complete, use the shrine + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent == nullptr) - { - return; - } + if (rebuildComponent == nullptr) { + return; + } - if (rebuildComponent->GetState() == REBUILD_COMPLETED) - { - // Use the shrine - BaseUse(self, user); - } + if (rebuildComponent->GetState() == REBUILD_COMPLETED) { + // Use the shrine + BaseUse(self, user); + } } diff --git a/dScripts/ImaginationShrineServer.h b/dScripts/ImaginationShrineServer.h index 6bbf84b5..bef137e9 100644 --- a/dScripts/ImaginationShrineServer.h +++ b/dScripts/ImaginationShrineServer.h @@ -5,6 +5,6 @@ class ImaginationShrineServer : public BaseInteractDropLootServer { public: - void OnUse(Entity* self, Entity* user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/ImgBrickConsoleQB.cpp b/dScripts/ImgBrickConsoleQB.cpp index 0dfb6288..4a12324f 100644 --- a/dScripts/ImgBrickConsoleQB.cpp +++ b/dScripts/ImgBrickConsoleQB.cpp @@ -10,280 +10,231 @@ int32_t ImgBrickConsoleQB::ResetBricks = 30; int32_t ImgBrickConsoleQB::ResetConsole = 60; int32_t ImgBrickConsoleQB::ResetInteract = 45; -void ImgBrickConsoleQB::OnStartup(Entity* self) -{ - self->SetNetworkVar(u"used", false); +void ImgBrickConsoleQB::OnStartup(Entity* self) { + self->SetNetworkVar(u"used", false); - self->AddTimer("reset", ResetBricks); + self->AddTimer("reset", ResetBricks); } -void ImgBrickConsoleQB::OnUse(Entity* self, Entity* user) -{ - auto* rebuildComponent = self->GetComponent(); +void ImgBrickConsoleQB::OnUse(Entity* self, Entity* user) { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent->GetState() == REBUILD_COMPLETED) - { - if (!self->GetNetworkVar(u"used")) - { - const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); + if (rebuildComponent->GetState() == REBUILD_COMPLETED) { + if (!self->GetNetworkVar(u"used")) { + const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); - auto bothBuilt = false; + auto bothBuilt = false; - for (auto* console : consoles) - { - auto* consoleRebuildComponent = console->GetComponent(); + for (auto* console : consoles) { + auto* consoleRebuildComponent = console->GetComponent(); - if (consoleRebuildComponent->GetState() != REBUILD_COMPLETED) - { - continue; - } + if (consoleRebuildComponent->GetState() != REBUILD_COMPLETED) { + continue; + } - console->CancelAllTimers(); + console->CancelAllTimers(); - if (console->GetNetworkVar(u"used")) - { - bothBuilt = true; - } - } + if (console->GetNetworkVar(u"used")) { + bothBuilt = true; + } + } - if (bothBuilt) - { - SmashCanister(self); - } - else - { - SpawnBrick(self); - } + if (bothBuilt) { + SmashCanister(self); + } else { + SpawnBrick(self); + } - self->AddTimer("Die", ResetInteract); + self->AddTimer("Die", ResetInteract); - auto onFX = 0; + auto onFX = 0; - const auto location = GeneralUtils::UTF16ToWTF8(self->GetVar(u"console")); + const auto location = GeneralUtils::UTF16ToWTF8(self->GetVar(u"console")); - if (location == "Left") - { - onFX = 2776; - } - else - { - onFX = 2779; - } + if (location == "Left") { + onFX = 2776; + } else { + onFX = 2779; + } - const auto& facility = EntityManager::Instance()->GetEntitiesInGroup("FacilityPipes"); + const auto& facility = EntityManager::Instance()->GetEntitiesInGroup("FacilityPipes"); - if (!facility.empty()) - { - GameMessages::SendStopFXEffect(facility[0], true, location + "PipeEnergy"); - GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), onFX, u"create", location + "PipeOn"); - } - } + if (!facility.empty()) { + GameMessages::SendStopFXEffect(facility[0], true, location + "PipeEnergy"); + GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), onFX, u"create", location + "PipeOn"); + } + } - auto* player = user; + auto* player = user; - auto* missionComponent = player->GetComponent(); - auto* inventoryComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); + auto* inventoryComponent = player->GetComponent(); - if (missionComponent != nullptr && inventoryComponent != nullptr) - { - if (missionComponent->GetMissionState(1302) == MissionState::MISSION_STATE_ACTIVE) - { - inventoryComponent->RemoveItem(13074, 1); - - missionComponent->ForceProgressTaskType(1302, 1, 1); - } - - if (missionComponent->GetMissionState(1926) == MissionState::MISSION_STATE_ACTIVE) - { - inventoryComponent->RemoveItem(14472, 1); + if (missionComponent != nullptr && inventoryComponent != nullptr) { + if (missionComponent->GetMissionState(1302) == MissionState::MISSION_STATE_ACTIVE) { + inventoryComponent->RemoveItem(13074, 1); - missionComponent->ForceProgressTaskType(1926, 1, 1); - } - } + missionComponent->ForceProgressTaskType(1302, 1, 1); + } - self->SetNetworkVar(u"used", true); + if (missionComponent->GetMissionState(1926) == MissionState::MISSION_STATE_ACTIVE) { + inventoryComponent->RemoveItem(14472, 1); - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); - } + missionComponent->ForceProgressTaskType(1926, 1, 1); + } + } + + self->SetNetworkVar(u"used", true); + + GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + } } -void ImgBrickConsoleQB::SpawnBrick(Entity* self) -{ - const auto netDevil = dZoneManager::Instance()->GetSpawnersByName("MaelstromBug"); - if (!netDevil.empty()) - { - netDevil[0]->Reset(); - netDevil[0]->Deactivate(); - } +void ImgBrickConsoleQB::SpawnBrick(Entity* self) { + const auto netDevil = dZoneManager::Instance()->GetSpawnersByName("MaelstromBug"); + if (!netDevil.empty()) { + netDevil[0]->Reset(); + netDevil[0]->Deactivate(); + } - const auto brick = dZoneManager::Instance()->GetSpawnersByName("Imagination"); - if (!brick.empty()) - { - brick[0]->Activate(); - } + const auto brick = dZoneManager::Instance()->GetSpawnersByName("Imagination"); + if (!brick.empty()) { + brick[0]->Activate(); + } } -void ImgBrickConsoleQB::SmashCanister(Entity* self) -{ - const auto brick = EntityManager::Instance()->GetEntitiesInGroup("Imagination"); - if (!brick.empty()) - { - GameMessages::SendPlayFXEffect(brick[0]->GetObjectID(), 122, u"create", "bluebrick"); - GameMessages::SendPlayFXEffect(brick[0]->GetObjectID(), 1034, u"cast", "imaginationexplosion"); - } +void ImgBrickConsoleQB::SmashCanister(Entity* self) { + const auto brick = EntityManager::Instance()->GetEntitiesInGroup("Imagination"); + if (!brick.empty()) { + GameMessages::SendPlayFXEffect(brick[0]->GetObjectID(), 122, u"create", "bluebrick"); + GameMessages::SendPlayFXEffect(brick[0]->GetObjectID(), 1034, u"cast", "imaginationexplosion"); + } - const auto canisters = EntityManager::Instance()->GetEntitiesInGroup("Canister"); - for (auto* canister : canisters) - { - canister->Smash(canister->GetObjectID(), VIOLENT); - } - - const auto canister = dZoneManager::Instance()->GetSpawnersByName("BrickCanister"); - if (!canister.empty()) - { - canister[0]->Reset(); - canister[0]->Deactivate(); - } + const auto canisters = EntityManager::Instance()->GetEntitiesInGroup("Canister"); + for (auto* canister : canisters) { + canister->Smash(canister->GetObjectID(), VIOLENT); + } + + const auto canister = dZoneManager::Instance()->GetSpawnersByName("BrickCanister"); + if (!canister.empty()) { + canister[0]->Reset(); + canister[0]->Deactivate(); + } } -void ImgBrickConsoleQB::OnRebuildComplete(Entity* self, Entity* target) -{ - auto energyFX = 0; +void ImgBrickConsoleQB::OnRebuildComplete(Entity* self, Entity* target) { + auto energyFX = 0; - const auto location = GeneralUtils::UTF16ToWTF8(self->GetVar(u"console")); + const auto location = GeneralUtils::UTF16ToWTF8(self->GetVar(u"console")); - if (location == "Left") - { - energyFX = 2775; - } - else - { - energyFX = 2778; - } + if (location == "Left") { + energyFX = 2775; + } else { + energyFX = 2778; + } - const auto& facility = EntityManager::Instance()->GetEntitiesInGroup("FacilityPipes"); + const auto& facility = EntityManager::Instance()->GetEntitiesInGroup("FacilityPipes"); - if (!facility.empty()) - { - GameMessages::SendStopFXEffect(facility[0], true, location + "PipeOff"); - GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), energyFX, u"create", location + "PipeEnergy"); - } + if (!facility.empty()) { + GameMessages::SendStopFXEffect(facility[0], true, location + "PipeOff"); + GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), energyFX, u"create", location + "PipeEnergy"); + } - const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); + const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); - for (auto* console : consoles) - { - auto* consoleRebuildComponent = console->GetComponent(); + for (auto* console : consoles) { + auto* consoleRebuildComponent = console->GetComponent(); - if (consoleRebuildComponent->GetState() != REBUILD_COMPLETED) - { - continue; - } + if (consoleRebuildComponent->GetState() != REBUILD_COMPLETED) { + continue; + } - console->CancelAllTimers(); - } + console->CancelAllTimers(); + } - self->AddTimer("Die", ResetConsole); + self->AddTimer("Die", ResetConsole); } -void ImgBrickConsoleQB::OnDie(Entity* self, Entity* killer) -{ - if (self->GetVar(u"Died")) - { - return; - } +void ImgBrickConsoleQB::OnDie(Entity* self, Entity* killer) { + if (self->GetVar(u"Died")) { + return; + } - self->CancelAllTimers(); + self->CancelAllTimers(); - self->SetVar(u"Died", true); + self->SetVar(u"Died", true); - auto* rebuildComponent = self->GetComponent(); + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent->GetState() == REBUILD_COMPLETED) - { - auto offFX = 0; + if (rebuildComponent->GetState() == REBUILD_COMPLETED) { + auto offFX = 0; - const auto location = GeneralUtils::UTF16ToWTF8(self->GetVar(u"console")); + const auto location = GeneralUtils::UTF16ToWTF8(self->GetVar(u"console")); - if (location == "Left") - { - offFX = 2774; - } - else - { - offFX = 2777; - } + if (location == "Left") { + offFX = 2774; + } else { + offFX = 2777; + } - const auto& facility = EntityManager::Instance()->GetEntitiesInGroup("FacilityPipes"); + const auto& facility = EntityManager::Instance()->GetEntitiesInGroup("FacilityPipes"); - if (!facility.empty()) - { - GameMessages::SendStopFXEffect(facility[0], true, location + "PipeEnergy"); - GameMessages::SendStopFXEffect(facility[0], true, location + "PipeOn"); - GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), offFX, u"create", location + "PipeOff"); - GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), 2750, u"create", location + "imagination_canister"); - } - } - - const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - - const auto pipeGroup = myGroup.substr(0, 10); + if (!facility.empty()) { + GameMessages::SendStopFXEffect(facility[0], true, location + "PipeEnergy"); + GameMessages::SendStopFXEffect(facility[0], true, location + "PipeOn"); + GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), offFX, u"create", location + "PipeOff"); + GameMessages::SendPlayFXEffect(facility[0]->GetObjectID(), 2750, u"create", location + "imagination_canister"); + } + } - const auto firstPipe = pipeGroup + "1"; + const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - const auto samePipeSpawner = dZoneManager::Instance()->GetSpawnersByName(myGroup); - if (!samePipeSpawner.empty()) - { - samePipeSpawner[0]->Reset(); - samePipeSpawner[0]->Deactivate(); - } - - const auto firstPipeSpawner = dZoneManager::Instance()->GetSpawnersByName(firstPipe); - if (!firstPipeSpawner.empty()) - { - firstPipeSpawner[0]->Activate(); - } + const auto pipeGroup = myGroup.substr(0, 10); - const auto netdevil = dZoneManager::Instance()->GetSpawnersByName("Imagination"); - if (!netdevil.empty()) - { - netdevil[0]->Reset(); - netdevil[0]->Deactivate(); - } + const auto firstPipe = pipeGroup + "1"; - const auto brick = dZoneManager::Instance()->GetSpawnersByName("MaelstromBug"); - if (!brick.empty()) - { - brick[0]->Activate(); - } + const auto samePipeSpawner = dZoneManager::Instance()->GetSpawnersByName(myGroup); + if (!samePipeSpawner.empty()) { + samePipeSpawner[0]->Reset(); + samePipeSpawner[0]->Deactivate(); + } - const auto canister = dZoneManager::Instance()->GetSpawnersByName("BrickCanister"); - if (!canister.empty()) - { - canister[0]->Activate(); - } + const auto firstPipeSpawner = dZoneManager::Instance()->GetSpawnersByName(firstPipe); + if (!firstPipeSpawner.empty()) { + firstPipeSpawner[0]->Activate(); + } - self->SetNetworkVar(u"used", false); + const auto netdevil = dZoneManager::Instance()->GetSpawnersByName("Imagination"); + if (!netdevil.empty()) { + netdevil[0]->Reset(); + netdevil[0]->Deactivate(); + } + + const auto brick = dZoneManager::Instance()->GetSpawnersByName("MaelstromBug"); + if (!brick.empty()) { + brick[0]->Activate(); + } + + const auto canister = dZoneManager::Instance()->GetSpawnersByName("BrickCanister"); + if (!canister.empty()) { + canister[0]->Activate(); + } + + self->SetNetworkVar(u"used", false); } -void ImgBrickConsoleQB::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "reset") - { - auto* rebuildComponent = self->GetComponent(); +void ImgBrickConsoleQB::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "reset") { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent->GetState() == REBUILD_OPEN) - { - self->Smash(self->GetObjectID(), SILENT); - } - } - else if (timerName == "Die") - { - const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); + if (rebuildComponent->GetState() == REBUILD_OPEN) { + self->Smash(self->GetObjectID(), SILENT); + } + } else if (timerName == "Die") { + const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); - for (auto* console : consoles) - { - console->Smash(console->GetObjectID(), VIOLENT); - } - } + for (auto* console : consoles) { + console->Smash(console->GetObjectID(), VIOLENT); + } + } } diff --git a/dScripts/ImgBrickConsoleQB.h b/dScripts/ImgBrickConsoleQB.h index f51f8e6c..062a5888 100644 --- a/dScripts/ImgBrickConsoleQB.h +++ b/dScripts/ImgBrickConsoleQB.h @@ -1,19 +1,19 @@ #pragma once #include "CppScripts.h" -class ImgBrickConsoleQB : public CppScripts::Script +class ImgBrickConsoleQB : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void SpawnBrick(Entity* self); - void SmashCanister(Entity* self); - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnDie(Entity* self, Entity* killer) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void SpawnBrick(Entity* self); + void SmashCanister(Entity* self); + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnDie(Entity* self, Entity* killer) override; + void OnTimerDone(Entity* self, std::string timerName) override; public: - static int32_t ResetBricks; - static int32_t ResetConsole; - static int32_t ResetInteract; -}; \ No newline at end of file + static int32_t ResetBricks; + static int32_t ResetConsole; + static int32_t ResetInteract; +}; diff --git a/dScripts/InstanceExitTransferPlayerToLastNonInstance.cpp b/dScripts/InstanceExitTransferPlayerToLastNonInstance.cpp index 307c6c73..4e42e7fb 100644 --- a/dScripts/InstanceExitTransferPlayerToLastNonInstance.cpp +++ b/dScripts/InstanceExitTransferPlayerToLastNonInstance.cpp @@ -4,56 +4,53 @@ #include "Character.h" #include "dServer.h" -void InstanceExitTransferPlayerToLastNonInstance::OnUse(Entity* self, Entity* user) -{ - auto transferText = self->GetVar(u"transferText"); - if (transferText.empty()) - transferText = u"DRAGON_EXIT_QUESTION"; +void InstanceExitTransferPlayerToLastNonInstance::OnUse(Entity* self, Entity* user) { + auto transferText = self->GetVar(u"transferText"); + if (transferText.empty()) + transferText = u"DRAGON_EXIT_QUESTION"; - GameMessages::SendDisplayMessageBox( - user->GetObjectID(), - true, - self->GetObjectID(), - u"Instance_Exit", - 1, - transferText, - u"", - user->GetSystemAddress() - ); + GameMessages::SendDisplayMessageBox( + user->GetObjectID(), + true, + self->GetObjectID(), + u"Instance_Exit", + 1, + transferText, + u"", + user->GetSystemAddress() + ); } -void InstanceExitTransferPlayerToLastNonInstance::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - auto* player = dynamic_cast(sender); - if (player == nullptr) - return; +void InstanceExitTransferPlayerToLastNonInstance::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + auto* player = dynamic_cast(sender); + if (player == nullptr) + return; - auto* character = sender->GetCharacter(); - if (character != nullptr) { - if (identifier == u"Instance_Exit" && button == 1) { - auto lastInstance = character->GetLastNonInstanceZoneID(); + auto* character = sender->GetCharacter(); + if (character != nullptr) { + if (identifier == u"Instance_Exit" && button == 1) { + auto lastInstance = character->GetLastNonInstanceZoneID(); - // Sanity check - if (lastInstance == 0) { - switch (Game::server->GetZoneID()) - { - case 2001: - lastInstance = 2000; - break; - case 1402: - lastInstance = 1400; - break; - default: - lastInstance = 1100; - break; - } - } + // Sanity check + if (lastInstance == 0) { + switch (Game::server->GetZoneID()) { + case 2001: + lastInstance = 2000; + break; + case 1402: + lastInstance = 1400; + break; + default: + lastInstance = 1100; + break; + } + } - player->SendToZone(lastInstance); - } - } + player->SendToZone(lastInstance); + } + } - GameMessages::SendTerminateInteraction(sender->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(sender->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/InstanceExitTransferPlayerToLastNonInstance.h b/dScripts/InstanceExitTransferPlayerToLastNonInstance.h index 3321191d..01e9fe3f 100644 --- a/dScripts/InstanceExitTransferPlayerToLastNonInstance.h +++ b/dScripts/InstanceExitTransferPlayerToLastNonInstance.h @@ -1,7 +1,7 @@ #pragma once #include "CppScripts.h" -class InstanceExitTransferPlayerToLastNonInstance : public CppScripts::Script +class InstanceExitTransferPlayerToLastNonInstance : public CppScripts::Script { public: void OnUse(Entity* self, Entity* user) override; diff --git a/dScripts/LegoDieRoll.cpp b/dScripts/LegoDieRoll.cpp index 386313be..e86550f9 100644 --- a/dScripts/LegoDieRoll.cpp +++ b/dScripts/LegoDieRoll.cpp @@ -4,51 +4,49 @@ #include "MissionComponent.h" void LegoDieRoll::OnStartup(Entity* self) { - self->AddTimer("DoneRolling", 10.0f); - self->AddTimer("ThrowDice", LegoDieRoll::animTime); + self->AddTimer("DoneRolling", 10.0f); + self->AddTimer("ThrowDice", LegoDieRoll::animTime); } void LegoDieRoll::OnTimerDone(Entity* self, std::string timerName) { - if (timerName == "DoneRolling") { - self->Smash(self->GetObjectID(), SILENT); - } - else if (timerName == "ThrowDice") { - int dieRoll = GeneralUtils::GenerateRandomNumber(1, 6); + if (timerName == "DoneRolling") { + self->Smash(self->GetObjectID(), SILENT); + } else if (timerName == "ThrowDice") { + int dieRoll = GeneralUtils::GenerateRandomNumber(1, 6); - switch (dieRoll) - { - case 1: - GameMessages::SendPlayAnimation(self, u"roll-die-1"); - break; - case 2: - GameMessages::SendPlayAnimation(self, u"roll-die-2"); - break; - case 3: - GameMessages::SendPlayAnimation(self, u"roll-die-3"); - break; - case 4: - GameMessages::SendPlayAnimation(self, u"roll-die-4"); - break; - case 5: - GameMessages::SendPlayAnimation(self, u"roll-die-5"); - break; - case 6: - { - GameMessages::SendPlayAnimation(self, u"roll-die-6"); - // tracking the It's Truly Random Achievement - auto* owner = self->GetOwner(); - auto* missionComponent = owner->GetComponent(); + switch (dieRoll) { + case 1: + GameMessages::SendPlayAnimation(self, u"roll-die-1"); + break; + case 2: + GameMessages::SendPlayAnimation(self, u"roll-die-2"); + break; + case 3: + GameMessages::SendPlayAnimation(self, u"roll-die-3"); + break; + case 4: + GameMessages::SendPlayAnimation(self, u"roll-die-4"); + break; + case 5: + GameMessages::SendPlayAnimation(self, u"roll-die-5"); + break; + case 6: + { + GameMessages::SendPlayAnimation(self, u"roll-die-6"); + // tracking the It's Truly Random Achievement + auto* owner = self->GetOwner(); + auto* missionComponent = owner->GetComponent(); - if (missionComponent != nullptr) { - const auto rollMissionState = missionComponent->GetMissionState(756); - if (rollMissionState == MissionState::MISSION_STATE_ACTIVE) { - missionComponent->ForceProgress(756, 1103, 1); - } - } - break; - } - default: - break; - } - } -} \ No newline at end of file + if (missionComponent != nullptr) { + const auto rollMissionState = missionComponent->GetMissionState(756); + if (rollMissionState == MissionState::MISSION_STATE_ACTIVE) { + missionComponent->ForceProgress(756, 1103, 1); + } + } + break; + } + default: + break; + } + } +} diff --git a/dScripts/LegoDieRoll.h b/dScripts/LegoDieRoll.h index 3b28d529..ea047e04 100644 --- a/dScripts/LegoDieRoll.h +++ b/dScripts/LegoDieRoll.h @@ -6,6 +6,6 @@ public: void OnStartup(Entity* self); void OnTimerDone(Entity* self, std::string timerName); private: - constexpr static const float animTime = 2.0f; + constexpr static const float animTime = 2.0f; }; diff --git a/dScripts/Lieutenant.cpp b/dScripts/Lieutenant.cpp index 91ffce63..d3b0fc1f 100644 --- a/dScripts/Lieutenant.cpp +++ b/dScripts/Lieutenant.cpp @@ -2,49 +2,43 @@ #include "SkillComponent.h" #include "dZoneManager.h" -void Lieutenant::OnStartup(Entity* self) -{ - auto* skillComponent = self->GetComponent(); +void Lieutenant::OnStartup(Entity* self) { + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - skillComponent->CalculateBehavior(1127, 24812, self->GetObjectID(), true); + skillComponent->CalculateBehavior(1127, 24812, self->GetObjectID(), true); } -void Lieutenant::OnDie(Entity* self, Entity* killer) -{ - const auto myLOT = self->GetLOT(); +void Lieutenant::OnDie(Entity* self, Entity* killer) { + const auto myLOT = self->GetLOT(); - std::string spawnerName; + std::string spawnerName; - switch (myLOT) - { - case 16047: - spawnerName = "EarthShrine_ERail"; - break; - case 16050: - spawnerName = "IceShrine_QBBouncer"; - break; - case 16049: - spawnerName = "LightningShrine_LRail"; - break; - default: - return; - } + switch (myLOT) { + case 16047: + spawnerName = "EarthShrine_ERail"; + break; + case 16050: + spawnerName = "IceShrine_QBBouncer"; + break; + case 16049: + spawnerName = "LightningShrine_LRail"; + break; + default: + return; + } - const auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); + const auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); - if (spawners.empty()) - { - return; - } + if (spawners.empty()) { + return; + } - for (auto* spawner : spawners) - { - spawner->Reset(); - spawner->Activate(); - } + for (auto* spawner : spawners) { + spawner->Reset(); + spawner->Activate(); + } } diff --git a/dScripts/Lieutenant.h b/dScripts/Lieutenant.h index 8635671a..ff6212ef 100644 --- a/dScripts/Lieutenant.h +++ b/dScripts/Lieutenant.h @@ -6,6 +6,6 @@ class Lieutenant : public CppScripts::Script public: void OnStartup(Entity* self) override; - void OnDie(Entity* self, Entity* killer) override; + void OnDie(Entity* self, Entity* killer) override; }; diff --git a/dScripts/MaestromExtracticatorServer.cpp b/dScripts/MaestromExtracticatorServer.cpp index a542389f..caaba28f 100644 --- a/dScripts/MaestromExtracticatorServer.cpp +++ b/dScripts/MaestromExtracticatorServer.cpp @@ -12,8 +12,8 @@ void MaestromExtracticatorServer::OnStartup(Entity* self) { self->AddTimer("RemoveSample", destroyAfterNoSampleTime); } -void MaestromExtracticatorServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { +void MaestromExtracticatorServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { if (sender == nullptr) return; @@ -25,8 +25,8 @@ void MaestromExtracticatorServer::OnFireEventServerSide(Entity *self, Entity *se if (missionComponent == nullptr) return; missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, 14718); - CollectSample(self, sender->GetObjectID()); - sender->ScheduleKillAfterUpdate(); + CollectSample(self, sender->GetObjectID()); + sender->ScheduleKillAfterUpdate(); } } diff --git a/dScripts/MaestromExtracticatorServer.h b/dScripts/MaestromExtracticatorServer.h index e59628c9..c4adb51e 100644 --- a/dScripts/MaestromExtracticatorServer.h +++ b/dScripts/MaestromExtracticatorServer.h @@ -4,8 +4,8 @@ class MaestromExtracticatorServer : public CppScripts::Script { public: void OnStartup(Entity* self); - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3); + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3); void CollectSample(Entity* self, LWOOBJID sampleObj); void PlayAnimAndReturnTime(Entity* self, std::string animID); void OnTimerDone(Entity* self, std::string timerName); @@ -15,4 +15,4 @@ private: const std::string collectAnim = "collect_maelstrom"; const float defaultTime = 4.0f; const float destroyAfterNoSampleTime = 8.0f; -}; \ No newline at end of file +}; diff --git a/dScripts/MailBoxServer.cpp b/dScripts/MailBoxServer.cpp index 56e7793e..81156835 100644 --- a/dScripts/MailBoxServer.cpp +++ b/dScripts/MailBoxServer.cpp @@ -3,9 +3,9 @@ #include "GameMessages.h" void MailBoxServer::OnUse(Entity* self, Entity* user) { - AMFStringValue* value = new AMFStringValue(); + AMFStringValue* value = new AMFStringValue(); value->SetStringValue("Mail"); AMFArrayValue args; args.InsertValue("state", value); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); -} \ No newline at end of file +} diff --git a/dScripts/MailBoxServer.h b/dScripts/MailBoxServer.h index 9cd93e24..f459e8b3 100644 --- a/dScripts/MailBoxServer.h +++ b/dScripts/MailBoxServer.h @@ -4,12 +4,12 @@ class MailBoxServer : public CppScripts::Script { public: - /** - * When a mailbox is interacted with, this method updates the player game state - * to be in a mailbox. - * - * @param self The object that owns this script. - * @param user The user that interacted with this Entity. - */ - void OnUse(Entity* self, Entity* user) override; -}; \ No newline at end of file + /** + * When a mailbox is interacted with, this method updates the player game state + * to be in a mailbox. + * + * @param self The object that owns this script. + * @param user The user that interacted with this Entity. + */ + void OnUse(Entity* self, Entity* user) override; +}; diff --git a/dScripts/MastTeleport.cpp b/dScripts/MastTeleport.cpp index 94d5f552..ebde7b20 100644 --- a/dScripts/MastTeleport.cpp +++ b/dScripts/MastTeleport.cpp @@ -8,92 +8,81 @@ #include #endif -void MastTeleport::OnStartup(Entity* self) -{ - self->SetNetworkVar(u"hookPreconditions", "154;44", UNASSIGNED_SYSTEM_ADDRESS); +void MastTeleport::OnStartup(Entity* self) { + self->SetNetworkVar(u"hookPreconditions", "154;44", UNASSIGNED_SYSTEM_ADDRESS); } -void MastTeleport::OnRebuildComplete(Entity* self, Entity* target) -{ - if (Preconditions::Check(target, 154) && Preconditions::Check(target, 44)) - { - self->SetVar(u"userID", target->GetObjectID()); +void MastTeleport::OnRebuildComplete(Entity* self, Entity* target) { + if (Preconditions::Check(target, 154) && Preconditions::Check(target, 44)) { + self->SetVar(u"userID", target->GetObjectID()); - GameMessages::SendSetStunned(target->GetObjectID(), PUSH, target->GetSystemAddress(), - LWOOBJID_EMPTY, true, true, true, true, true, true, true - ); + GameMessages::SendSetStunned(target->GetObjectID(), PUSH, target->GetSystemAddress(), + LWOOBJID_EMPTY, true, true, true, true, true, true, true + ); - self->AddTimer("Start", 3); - } + self->AddTimer("Start", 3); + } } -void MastTeleport::OnTimerDone(Entity* self, std::string timerName) -{ - const auto playerId = self->GetVar(u"userID"); +void MastTeleport::OnTimerDone(Entity* self, std::string timerName) { + const auto playerId = self->GetVar(u"userID"); - auto* player = EntityManager::Instance()->GetEntity(playerId); - - if (player == nullptr) return; + auto* player = EntityManager::Instance()->GetEntity(playerId); - if (timerName == "Start") - { - auto position = self->GetPosition(); - auto rotation = self->GetRotation(); + if (player == nullptr) return; - GameMessages::SendTeleport(playerId, position, rotation, player->GetSystemAddress(), true); + if (timerName == "Start") { + auto position = self->GetPosition(); + auto rotation = self->GetRotation(); - // Hacky fix for odd rotations - if (self->GetVar(u"MastName") != u"Jail") - { - GameMessages::SendOrientToAngle(playerId, true, (M_PI / 180) * 140.0f, player->GetSystemAddress()); - } - else - { - GameMessages::SendOrientToAngle(playerId, true, (M_PI / 180) * 100.0f, player->GetSystemAddress()); - } - - const auto cinematic = GeneralUtils::UTF16ToWTF8(self->GetVar(u"Cinematic")); - const auto leanIn = self->GetVar(u"LeanIn"); + GameMessages::SendTeleport(playerId, position, rotation, player->GetSystemAddress(), true); - if (!cinematic.empty()) - { - GameMessages::SendPlayCinematic(playerId, GeneralUtils::ASCIIToUTF16(cinematic), player->GetSystemAddress(), - true, true, false, false, 0, false, leanIn - ); - } - - GameMessages::SendPlayFXEffect(playerId, 6039, u"hook", "hook", LWOOBJID_EMPTY, 1, 1, true); + // Hacky fix for odd rotations + if (self->GetVar(u"MastName") != u"Jail") { + GameMessages::SendOrientToAngle(playerId, true, (M_PI / 180) * 140.0f, player->GetSystemAddress()); + } else { + GameMessages::SendOrientToAngle(playerId, true, (M_PI / 180) * 100.0f, player->GetSystemAddress()); + } - GameMessages::SendPlayAnimation(player, u"crow-swing-no-equip"); + const auto cinematic = GeneralUtils::UTF16ToWTF8(self->GetVar(u"Cinematic")); + const auto leanIn = self->GetVar(u"LeanIn"); - GameMessages::SendPlayAnimation(self, u"swing"); + if (!cinematic.empty()) { + GameMessages::SendPlayCinematic(playerId, GeneralUtils::ASCIIToUTF16(cinematic), player->GetSystemAddress(), + true, true, false, false, 0, false, leanIn + ); + } - self->AddTimer("PlayerAnimDone", 6.25f); - } - else if (timerName == "PlayerAnimDone") - { - GameMessages::SendStopFXEffect(player, true, "hook"); + GameMessages::SendPlayFXEffect(playerId, 6039, u"hook", "hook", LWOOBJID_EMPTY, 1, 1, true); - auto forward = self->GetRotation().GetForwardVector(); + GameMessages::SendPlayAnimation(player, u"crow-swing-no-equip"); - const auto degrees = -25.0f; + GameMessages::SendPlayAnimation(self, u"swing"); - const auto rads = degrees * (static_cast(M_PI) / 180.0f); + self->AddTimer("PlayerAnimDone", 6.25f); + } else if (timerName == "PlayerAnimDone") { + GameMessages::SendStopFXEffect(player, true, "hook"); - const Vector3 newPlayerRot = {0, rads, 0}; + auto forward = self->GetRotation().GetForwardVector(); - auto position = self->GetPosition(); + const auto degrees = -25.0f; - position.x += (forward.x * 20.5f); - position.y += 12; - position.z += (forward.z * 20.5f); + const auto rads = degrees * (static_cast(M_PI) / 180.0f); - GameMessages::SendOrientToAngle(playerId, true, rads, player->GetSystemAddress()); + const Vector3 newPlayerRot = { 0, rads, 0 }; - GameMessages::SendTeleport(playerId, position, NiQuaternion::IDENTITY, player->GetSystemAddress()); + auto position = self->GetPosition(); - GameMessages::SendSetStunned(playerId, POP, player->GetSystemAddress(), - LWOOBJID_EMPTY, true, true, true, true, true, true, true - ); - } + position.x += (forward.x * 20.5f); + position.y += 12; + position.z += (forward.z * 20.5f); + + GameMessages::SendOrientToAngle(playerId, true, rads, player->GetSystemAddress()); + + GameMessages::SendTeleport(playerId, position, NiQuaternion::IDENTITY, player->GetSystemAddress()); + + GameMessages::SendSetStunned(playerId, POP, player->GetSystemAddress(), + LWOOBJID_EMPTY, true, true, true, true, true, true, true + ); + } } diff --git a/dScripts/MastTeleport.h b/dScripts/MastTeleport.h index 1b5dc481..ea35d754 100644 --- a/dScripts/MastTeleport.h +++ b/dScripts/MastTeleport.h @@ -4,6 +4,6 @@ class MastTeleport : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnRebuildComplete(Entity* self, Entity* target) override; + void OnRebuildComplete(Entity* self, Entity* target) override; void OnTimerDone(Entity* self, std::string timerName) override; -}; \ No newline at end of file +}; diff --git a/dScripts/MinigameTreasureChestServer.cpp b/dScripts/MinigameTreasureChestServer.cpp index fc3f14c0..66222d59 100644 --- a/dScripts/MinigameTreasureChestServer.cpp +++ b/dScripts/MinigameTreasureChestServer.cpp @@ -4,61 +4,61 @@ #include "EntityManager.h" #include "dZoneManager.h" -void MinigameTreasureChestServer::OnUse(Entity *self, Entity *user) { - auto* sac = self->GetComponent(); - if (sac == nullptr) - return; +void MinigameTreasureChestServer::OnUse(Entity* self, Entity* user) { + auto* sac = self->GetComponent(); + if (sac == nullptr) + return; - if (self->GetVar(u"used")) - return; - self->SetVar(u"used", true); + if (self->GetVar(u"used")) + return; + self->SetVar(u"used", true); - if (!IsPlayerInActivity(self, user->GetObjectID())) - UpdatePlayer(self, user->GetObjectID()); + if (!IsPlayerInActivity(self, user->GetObjectID())) + UpdatePlayer(self, user->GetObjectID()); - auto* team = TeamManager::Instance()->GetTeam(user->GetObjectID()); - uint32_t activityRating = 0; - if (team != nullptr) { - for (const auto& teamMemberID : team->members) { - auto* teamMember = EntityManager::Instance()->GetEntity(teamMemberID); - if (teamMember != nullptr) { - activityRating = CalculateActivityRating(self, teamMemberID); + auto* team = TeamManager::Instance()->GetTeam(user->GetObjectID()); + uint32_t activityRating = 0; + if (team != nullptr) { + for (const auto& teamMemberID : team->members) { + auto* teamMember = EntityManager::Instance()->GetEntity(teamMemberID); + if (teamMember != nullptr) { + activityRating = CalculateActivityRating(self, teamMemberID); - if (self->GetLOT() == frakjawChestId) activityRating = team->members.size(); + if (self->GetLOT() == frakjawChestId) activityRating = team->members.size(); - LootGenerator::Instance().DropActivityLoot(teamMember, self, sac->GetActivityID(), activityRating); - } - } - } else { - activityRating = CalculateActivityRating(self, user->GetObjectID()); + LootGenerator::Instance().DropActivityLoot(teamMember, self, sac->GetActivityID(), activityRating); + } + } + } else { + activityRating = CalculateActivityRating(self, user->GetObjectID()); - if (self->GetLOT() == frakjawChestId) activityRating = 1; - - LootGenerator::Instance().DropActivityLoot(user, self, sac->GetActivityID(), activityRating); - } + if (self->GetLOT() == frakjawChestId) activityRating = 1; - sac->PlayerRemove(user->GetObjectID()); + LootGenerator::Instance().DropActivityLoot(user, self, sac->GetActivityID(), activityRating); + } - auto* zoneControl = dZoneManager::Instance()->GetZoneControlObject(); - if (zoneControl != nullptr) { - zoneControl->OnFireEventServerSide(self, "Survival_Update", 0); - } + sac->PlayerRemove(user->GetObjectID()); - self->Smash(self->GetObjectID()); + auto* zoneControl = dZoneManager::Instance()->GetZoneControlObject(); + if (zoneControl != nullptr) { + zoneControl->OnFireEventServerSide(self, "Survival_Update", 0); + } + + self->Smash(self->GetObjectID()); } -uint32_t MinigameTreasureChestServer::CalculateActivityRating(Entity *self, LWOOBJID playerID) { - auto* team = TeamManager::Instance()->GetTeam(playerID); - return team != nullptr ? team->members.size() * 100 : ActivityManager::CalculateActivityRating(self, playerID) * 100; +uint32_t MinigameTreasureChestServer::CalculateActivityRating(Entity* self, LWOOBJID playerID) { + auto* team = TeamManager::Instance()->GetTeam(playerID); + return team != nullptr ? team->members.size() * 100 : ActivityManager::CalculateActivityRating(self, playerID) * 100; } -void MinigameTreasureChestServer::OnStartup(Entity *self) { +void MinigameTreasureChestServer::OnStartup(Entity* self) { - // BONS treasure chest thinks it's on FV, causing it to start a lobby - if (dZoneManager::Instance()->GetZoneID().GetMapID() == 1204) { - auto* sac = self->GetComponent(); - if (sac != nullptr) { - sac->SetInstanceMapID(1204); - } - } + // BONS treasure chest thinks it's on FV, causing it to start a lobby + if (dZoneManager::Instance()->GetZoneID().GetMapID() == 1204) { + auto* sac = self->GetComponent(); + if (sac != nullptr) { + sac->SetInstanceMapID(1204); + } + } } diff --git a/dScripts/MinigameTreasureChestServer.h b/dScripts/MinigameTreasureChestServer.h index c718f016..3159e70e 100644 --- a/dScripts/MinigameTreasureChestServer.h +++ b/dScripts/MinigameTreasureChestServer.h @@ -3,9 +3,9 @@ class MinigameTreasureChestServer : public ActivityManager { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - uint32_t CalculateActivityRating(Entity *self, LWOOBJID playerID) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + uint32_t CalculateActivityRating(Entity* self, LWOOBJID playerID) override; private: - const uint32_t frakjawChestId = 16486; + const uint32_t frakjawChestId = 16486; }; diff --git a/dScripts/MonCoreNookDoors.cpp b/dScripts/MonCoreNookDoors.cpp index c3fcf9be..dc759c50 100644 --- a/dScripts/MonCoreNookDoors.cpp +++ b/dScripts/MonCoreNookDoors.cpp @@ -1,45 +1,37 @@ #include "MonCoreNookDoors.h" #include "dZoneManager.h" -void MonCoreNookDoors::OnStartup(Entity* self) -{ - SpawnDoor(self); +void MonCoreNookDoors::OnStartup(Entity* self) { + SpawnDoor(self); } -void MonCoreNookDoors::SpawnDoor(Entity* self) -{ - const auto doorNum = self->GetVarAsString(u"number"); +void MonCoreNookDoors::SpawnDoor(Entity* self) { + const auto doorNum = self->GetVarAsString(u"number"); - if (doorNum.empty()) - { - return; - } + if (doorNum.empty()) { + return; + } - const auto spawners = dZoneManager::Instance()->GetSpawnersByName("MonCoreNookDoor0" + doorNum); + const auto spawners = dZoneManager::Instance()->GetSpawnersByName("MonCoreNookDoor0" + doorNum); - if (spawners.empty()) - { - return; - } + if (spawners.empty()) { + return; + } - auto* spawner = spawners[0]; + auto* spawner = spawners[0]; - spawner->Reset(); - spawner->Activate(); + spawner->Reset(); + spawner->Activate(); } -void MonCoreNookDoors::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - if (args == "DoorSmashed") - { - self->AddTimer("RespawnDoor", 30); - } +void MonCoreNookDoors::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args == "DoorSmashed") { + self->AddTimer("RespawnDoor", 30); + } } -void MonCoreNookDoors::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "RespawnDoor") - { - SpawnDoor(self); - } +void MonCoreNookDoors::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "RespawnDoor") { + SpawnDoor(self); + } } diff --git a/dScripts/MonCoreNookDoors.h b/dScripts/MonCoreNookDoors.h index a7ad7906..58661575 100644 --- a/dScripts/MonCoreNookDoors.h +++ b/dScripts/MonCoreNookDoors.h @@ -3,12 +3,12 @@ class MonCoreNookDoors : public CppScripts::Script { public: - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; - void SpawnDoor(Entity* self); + void SpawnDoor(Entity* self); - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/MonCoreSmashableDoors.cpp b/dScripts/MonCoreSmashableDoors.cpp index 0e7950f5..4ec11e56 100644 --- a/dScripts/MonCoreSmashableDoors.cpp +++ b/dScripts/MonCoreSmashableDoors.cpp @@ -1,24 +1,21 @@ #include "MonCoreSmashableDoors.h" #include "EntityManager.h" -void MonCoreSmashableDoors::OnDie(Entity* self, Entity* killer) -{ - auto myNum = self->GetVarAsString(u"spawner_name"); +void MonCoreSmashableDoors::OnDie(Entity* self, Entity* killer) { + auto myNum = self->GetVarAsString(u"spawner_name"); myNum = myNum.substr(myNum.length() - 1, 1); - - auto triggerGroup = "CoreNookTrig0" + myNum; + + auto triggerGroup = "CoreNookTrig0" + myNum; // Get the trigger auto triggers = EntityManager::Instance()->GetEntitiesInGroup(triggerGroup); - if (triggers.empty()) - { + if (triggers.empty()) { return; } - for (auto trigger : triggers) - { + for (auto trigger : triggers) { trigger->OnFireEventServerSide(self, "DoorSmashed"); } } diff --git a/dScripts/MonCoreSmashableDoors.h b/dScripts/MonCoreSmashableDoors.h index 2c2f28ae..1f205e96 100644 --- a/dScripts/MonCoreSmashableDoors.h +++ b/dScripts/MonCoreSmashableDoors.h @@ -3,6 +3,6 @@ class MonCoreSmashableDoors : public CppScripts::Script { public: - void OnDie(Entity* self, Entity* killer) override; + void OnDie(Entity* self, Entity* killer) override; }; diff --git a/dScripts/NPCAddRemoveItem.cpp b/dScripts/NPCAddRemoveItem.cpp index 58c46ac0..ce47b12a 100644 --- a/dScripts/NPCAddRemoveItem.cpp +++ b/dScripts/NPCAddRemoveItem.cpp @@ -1,30 +1,30 @@ #include "NPCAddRemoveItem.h" #include "InventoryComponent.h" -void NPCAddRemoveItem::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - auto* inventory = target->GetComponent(); - if (inventory == nullptr) - return; +void NPCAddRemoveItem::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + auto* inventory = target->GetComponent(); + if (inventory == nullptr) + return; - for (const auto& missionSetting : m_MissionItemSettings) { - if (missionSetting.first == missionID) { - for (const auto& itemSetting : missionSetting.second) { - for (const auto& lot : itemSetting.items) { - if (itemSetting.add && (missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE)) { - inventory->AddItem(lot, 1, eLootSourceType::LOOT_SOURCE_NONE); - } else if (itemSetting.remove && (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE)) { - inventory->RemoveItem(lot, 1); - } - } - } - } - } + for (const auto& missionSetting : m_MissionItemSettings) { + if (missionSetting.first == missionID) { + for (const auto& itemSetting : missionSetting.second) { + for (const auto& lot : itemSetting.items) { + if (itemSetting.add && (missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE)) { + inventory->AddItem(lot, 1, eLootSourceType::LOOT_SOURCE_NONE); + } else if (itemSetting.remove && (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE)) { + inventory->RemoveItem(lot, 1); + } + } + } + } + } } std::map> NPCAddRemoveItem::GetSettings() { - return std::map>(); + return std::map>(); } -void NPCAddRemoveItem::OnStartup(Entity *self) { - m_MissionItemSettings = GetSettings(); +void NPCAddRemoveItem::OnStartup(Entity* self) { + m_MissionItemSettings = GetSettings(); } diff --git a/dScripts/NPCAddRemoveItem.h b/dScripts/NPCAddRemoveItem.h index 1b4aba13..a266f817 100644 --- a/dScripts/NPCAddRemoveItem.h +++ b/dScripts/NPCAddRemoveItem.h @@ -2,9 +2,9 @@ #include "CppScripts.h" struct ItemSetting { - std::vector items; // The items to add/remove - bool add; // Add items on mission accept - bool remove; // Remove items on mission complete + std::vector items; // The items to add/remove + bool add; // Add items on mission accept + bool remove; // Remove items on mission complete }; /** @@ -12,9 +12,9 @@ struct ItemSetting { */ class NPCAddRemoveItem : public CppScripts::Script { protected: - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; - virtual std::map> GetSettings(); + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + virtual std::map> GetSettings(); private: - void OnStartup(Entity *self) override; - std::map> m_MissionItemSettings; + void OnStartup(Entity* self) override; + std::map> m_MissionItemSettings; }; diff --git a/dScripts/NjColeNPC.cpp b/dScripts/NjColeNPC.cpp index 1b889445..f151db40 100644 --- a/dScripts/NjColeNPC.cpp +++ b/dScripts/NjColeNPC.cpp @@ -2,58 +2,47 @@ #include "MissionComponent.h" #include "InventoryComponent.h" -void NjColeNPC::OnEmoteReceived(Entity* self, int32_t emote, Entity* target) -{ - if (emote != 393) - { - return; - } +void NjColeNPC::OnEmoteReceived(Entity* self, int32_t emote, Entity* target) { + if (emote != 393) { + return; + } - auto* inventoryComponent = target->GetComponent(); + auto* inventoryComponent = target->GetComponent(); - if (inventoryComponent == nullptr) - { - return; - } + if (inventoryComponent == nullptr) { + return; + } - if (!inventoryComponent->IsEquipped(14499) && !inventoryComponent->IsEquipped(16644)) - { - return; - } + if (!inventoryComponent->IsEquipped(14499) && !inventoryComponent->IsEquipped(16644)) { + return; + } - auto* missionComponent = target->GetComponent(); + auto* missionComponent = target->GetComponent(); - if (missionComponent == nullptr) - { - return; - } + if (missionComponent == nullptr) { + return; + } - missionComponent->ForceProgressTaskType(1818, 1, 1); + missionComponent->ForceProgressTaskType(1818, 1, 1); } -void NjColeNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) -{ - NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(self, target, missionID, missionState); +void NjColeNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(self, target, missionID, missionState); - if (missionID == 1818 && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) - { - auto* missionComponent = target->GetComponent(); - auto* inventoryComponent = target->GetComponent(); + if (missionID == 1818 && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { + auto* missionComponent = target->GetComponent(); + auto* inventoryComponent = target->GetComponent(); - if (missionComponent == nullptr || inventoryComponent == nullptr) - { - return; - } + if (missionComponent == nullptr || inventoryComponent == nullptr) { + return; + } - if (inventoryComponent->GetLotCount(14499) > 0) - { - inventoryComponent->RemoveItem(14499, 1); - } - else - { - return; - } + if (inventoryComponent->GetLotCount(14499) > 0) { + inventoryComponent->RemoveItem(14499, 1); + } else { + return; + } - inventoryComponent->AddItem(16644, 1, eLootSourceType::LOOT_SOURCE_NONE); - } + inventoryComponent->AddItem(16644, 1, eLootSourceType::LOOT_SOURCE_NONE); + } } diff --git a/dScripts/NjColeNPC.h b/dScripts/NjColeNPC.h index c6421a66..cf8e67e1 100644 --- a/dScripts/NjColeNPC.h +++ b/dScripts/NjColeNPC.h @@ -1,7 +1,7 @@ #include "NjNPCMissionSpinjitzuServer.h" class NjColeNPC : public NjNPCMissionSpinjitzuServer { - void OnEmoteReceived(Entity* self, int32_t emote, Entity* target) override; + void OnEmoteReceived(Entity* self, int32_t emote, Entity* target) override; - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; }; diff --git a/dScripts/NjDragonEmblemChestServer.cpp b/dScripts/NjDragonEmblemChestServer.cpp index ea699c55..fa4d8556 100644 --- a/dScripts/NjDragonEmblemChestServer.cpp +++ b/dScripts/NjDragonEmblemChestServer.cpp @@ -2,14 +2,14 @@ #include "Character.h" #include "DestroyableComponent.h" -void NjDragonEmblemChestServer::OnUse(Entity *self, Entity *user) { - auto* character = user->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(NJ_WU_SHOW_DAILY_CHEST, false); - } +void NjDragonEmblemChestServer::OnUse(Entity* self, Entity* user) { + auto* character = user->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(NJ_WU_SHOW_DAILY_CHEST, false); + } - auto* destroyable = self->GetComponent(); - if (destroyable != nullptr) { - LootGenerator::Instance().DropLoot(user, self, destroyable->GetLootMatrixID(), 0, 0); - } + auto* destroyable = self->GetComponent(); + if (destroyable != nullptr) { + LootGenerator::Instance().DropLoot(user, self, destroyable->GetLootMatrixID(), 0, 0); + } } diff --git a/dScripts/NjDragonEmblemChestServer.h b/dScripts/NjDragonEmblemChestServer.h index ab0abc05..b1c59a22 100644 --- a/dScripts/NjDragonEmblemChestServer.h +++ b/dScripts/NjDragonEmblemChestServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NjDragonEmblemChestServer : public CppScripts::Script { - void OnUse(Entity *self, Entity *user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/NjEarthDragonPetServer.cpp b/dScripts/NjEarthDragonPetServer.cpp index 2b91f33c..87f3dd4b 100644 --- a/dScripts/NjEarthDragonPetServer.cpp +++ b/dScripts/NjEarthDragonPetServer.cpp @@ -1,10 +1,10 @@ #include "NjEarthDragonPetServer.h" #include "Entity.h" -void NjEarthDragonPetServer::SetVariables(Entity *self) { - self->SetVar(u"petLOT", 16210); - self->SetVar(u"petType", "earthpet"); - self->SetVar(u"maxPets", 3); - self->SetVar(u"spawnAnim", u"spawn"); - self->SetVar(u"spawnCinematic", u"EarthPetSpawn"); +void NjEarthDragonPetServer::SetVariables(Entity* self) { + self->SetVar(u"petLOT", 16210); + self->SetVar(u"petType", "earthpet"); + self->SetVar(u"maxPets", 3); + self->SetVar(u"spawnAnim", u"spawn"); + self->SetVar(u"spawnCinematic", u"EarthPetSpawn"); } diff --git a/dScripts/NjEarthDragonPetServer.h b/dScripts/NjEarthDragonPetServer.h index 2227bbb6..51e84c34 100644 --- a/dScripts/NjEarthDragonPetServer.h +++ b/dScripts/NjEarthDragonPetServer.h @@ -2,5 +2,5 @@ #include "SpawnPetBaseServer.h" class NjEarthDragonPetServer : public SpawnPetBaseServer { - void SetVariables(Entity* self) override; + void SetVariables(Entity* self) override; }; diff --git a/dScripts/NjEarthPetServer.cpp b/dScripts/NjEarthPetServer.cpp index 12036355..36655c63 100644 --- a/dScripts/NjEarthPetServer.cpp +++ b/dScripts/NjEarthPetServer.cpp @@ -1,12 +1,12 @@ #include "NjEarthPetServer.h" #include "PetComponent.h" -void NjEarthPetServer::OnStartup(Entity *self) { - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwnerId() != LWOOBJID_EMPTY) - return; +void NjEarthPetServer::OnStartup(Entity* self) { + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwnerId() != LWOOBJID_EMPTY) + return; - // Removes the chocolate bars - petComponent->SetPreconditions(const_cast(m_Precondition)); - PetFromObjectServer::OnStartup(self); + // Removes the chocolate bars + petComponent->SetPreconditions(const_cast(m_Precondition)); + PetFromObjectServer::OnStartup(self); } diff --git a/dScripts/NjEarthPetServer.h b/dScripts/NjEarthPetServer.h index 0e327168..3423c019 100644 --- a/dScripts/NjEarthPetServer.h +++ b/dScripts/NjEarthPetServer.h @@ -2,6 +2,6 @@ #include "PetFromObjectServer.h" class NjEarthPetServer : public PetFromObjectServer { - void OnStartup(Entity *self) override; - const std::string m_Precondition = "279"; + void OnStartup(Entity* self) override; + const std::string m_Precondition = "279"; }; diff --git a/dScripts/NjGarmadonCelebration.cpp b/dScripts/NjGarmadonCelebration.cpp index ab71e092..c223c55c 100644 --- a/dScripts/NjGarmadonCelebration.cpp +++ b/dScripts/NjGarmadonCelebration.cpp @@ -2,16 +2,16 @@ #include "Character.h" #include "GameMessages.h" -void NjGarmadonCelebration::OnCollisionPhantom(Entity *self, Entity *target) { - auto* character = target->GetCharacter(); +void NjGarmadonCelebration::OnCollisionPhantom(Entity* self, Entity* target) { + auto* character = target->GetCharacter(); - if (character == nullptr) { - return; - } + if (character == nullptr) { + return; + } - if (!character->GetPlayerFlag(ePlayerFlags::NJ_GARMADON_CINEMATIC_SEEN)) { - character->SetPlayerFlag(ePlayerFlags::NJ_GARMADON_CINEMATIC_SEEN, true); + if (!character->GetPlayerFlag(ePlayerFlags::NJ_GARMADON_CINEMATIC_SEEN)) { + character->SetPlayerFlag(ePlayerFlags::NJ_GARMADON_CINEMATIC_SEEN, true); - GameMessages::SendStartCelebrationEffect(target, target->GetSystemAddress(), GarmadonCelebrationID); - } + GameMessages::SendStartCelebrationEffect(target, target->GetSystemAddress(), GarmadonCelebrationID); + } } diff --git a/dScripts/NjGarmadonCelebration.h b/dScripts/NjGarmadonCelebration.h index 858ecfce..fe08a169 100644 --- a/dScripts/NjGarmadonCelebration.h +++ b/dScripts/NjGarmadonCelebration.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class NjGarmadonCelebration : public CppScripts::Script { - void OnCollisionPhantom(Entity *self, Entity *target) override; + void OnCollisionPhantom(Entity* self, Entity* target) override; private: - const int32_t GarmadonCelebrationID = 23; + const int32_t GarmadonCelebrationID = 23; }; diff --git a/dScripts/NjIceRailActivator.cpp b/dScripts/NjIceRailActivator.cpp index dbf0acd6..2549cd0f 100644 --- a/dScripts/NjIceRailActivator.cpp +++ b/dScripts/NjIceRailActivator.cpp @@ -2,24 +2,24 @@ #include "EntityManager.h" #include "GameMessages.h" -void NjIceRailActivator::OnPlayerRailArrived(Entity *self, Entity *sender, const std::u16string &pathName, - int32_t waypoint) { - const auto breakPoint = self->GetVar(BreakpointVariable); - if (breakPoint == waypoint) { - const auto& blockGroup = self->GetVar(BlockGroupVariable); +void NjIceRailActivator::OnPlayerRailArrived(Entity* self, Entity* sender, const std::u16string& pathName, + int32_t waypoint) { + const auto breakPoint = self->GetVar(BreakpointVariable); + if (breakPoint == waypoint) { + const auto& blockGroup = self->GetVar(BlockGroupVariable); - for (auto* block : EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(blockGroup))) { - GameMessages::SendPlayAnimation(block, u"explode"); + for (auto* block : EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(blockGroup))) { + GameMessages::SendPlayAnimation(block, u"explode"); - const auto blockID = block->GetObjectID(); + const auto blockID = block->GetObjectID(); - self->AddCallbackTimer(1.0f, [self, blockID]() { - auto* block = EntityManager::Instance()->GetEntity(blockID); + self->AddCallbackTimer(1.0f, [self, blockID]() { + auto* block = EntityManager::Instance()->GetEntity(blockID); - if (block != nullptr) { - block->Kill(self); - } - }); - } - } + if (block != nullptr) { + block->Kill(self); + } + }); + } + } } diff --git a/dScripts/NjIceRailActivator.h b/dScripts/NjIceRailActivator.h index dd56be62..05927898 100644 --- a/dScripts/NjIceRailActivator.h +++ b/dScripts/NjIceRailActivator.h @@ -1,10 +1,10 @@ #pragma once #include "NjRailActivatorsServer.h" -class NjIceRailActivator : public NjRailActivatorsServer{ - void OnPlayerRailArrived(Entity* self, Entity* sender, const std::u16string& pathName, int32_t waypoint) override; +class NjIceRailActivator : public NjRailActivatorsServer { + void OnPlayerRailArrived(Entity* self, Entity* sender, const std::u16string& pathName, int32_t waypoint) override; private: - std::u16string BreakpointVariable = u"BreakPoint"; - std::u16string BlockGroupVariable = u"BlockGroup"; - std::u16string IceBlockVariable = u"IceBlock"; + std::u16string BreakpointVariable = u"BreakPoint"; + std::u16string BlockGroupVariable = u"BlockGroup"; + std::u16string IceBlockVariable = u"IceBlock"; }; diff --git a/dScripts/NjJayMissionItems.cpp b/dScripts/NjJayMissionItems.cpp index c4b037bb..cc871b86 100644 --- a/dScripts/NjJayMissionItems.cpp +++ b/dScripts/NjJayMissionItems.cpp @@ -1,13 +1,13 @@ #include "NjJayMissionItems.h" -void NjJayMissionItems::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(self, target, missionID, missionState); - NPCAddRemoveItem::OnMissionDialogueOK(self, target, missionID, missionState); +void NjJayMissionItems::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(self, target, missionID, missionState); + NPCAddRemoveItem::OnMissionDialogueOK(self, target, missionID, missionState); } std::map> NjJayMissionItems::GetSettings() { - return { - {1789, {{{14474},false, true}}}, - {1927, {{{14493},false, true}}} - }; + return { + {1789, {{{14474},false, true}}}, + {1927, {{{14493},false, true}}} + }; } diff --git a/dScripts/NjJayMissionItems.h b/dScripts/NjJayMissionItems.h index 19cb4f40..c49f49ea 100644 --- a/dScripts/NjJayMissionItems.h +++ b/dScripts/NjJayMissionItems.h @@ -5,6 +5,6 @@ #include class NjJayMissionItems : public NjNPCMissionSpinjitzuServer, NPCAddRemoveItem { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; - std::map> GetSettings() override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + std::map> GetSettings() override; }; diff --git a/dScripts/NjMonastryBossInstance.cpp b/dScripts/NjMonastryBossInstance.cpp index 2aa7222e..dbab7365 100644 --- a/dScripts/NjMonastryBossInstance.cpp +++ b/dScripts/NjMonastryBossInstance.cpp @@ -14,510 +14,510 @@ // Event handling // // // // // // // // -void NjMonastryBossInstance::OnStartup(Entity *self) { - auto spawnerNames = std::vector { LedgeFrakjawSpawner, LowerFrakjawSpawner, BaseEnemiesSpawner + std::to_string(1), - BaseEnemiesSpawner + std::to_string(2), BaseEnemiesSpawner + std::to_string(3), - BaseEnemiesSpawner + std::to_string(4), CounterweightSpawner }; +void NjMonastryBossInstance::OnStartup(Entity* self) { + auto spawnerNames = std::vector{ LedgeFrakjawSpawner, LowerFrakjawSpawner, BaseEnemiesSpawner + std::to_string(1), + BaseEnemiesSpawner + std::to_string(2), BaseEnemiesSpawner + std::to_string(3), + BaseEnemiesSpawner + std::to_string(4), CounterweightSpawner }; - // Add a notification request for all the spawned entities, corresponds to notifySpawnedObjectLoaded - for (const auto& spawnerName : spawnerNames) { - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { - spawner->AddEntitySpawnedCallback([self, this](Entity* entity) { - const auto lot = entity->GetLOT(); - switch (lot) { - case LedgedFrakjawLOT: - NjMonastryBossInstance::HandleLedgedFrakjawSpawned(self, entity); - return; - case CounterWeightLOT: - NjMonastryBossInstance::HandleCounterWeightSpawned(self, entity); - return; - case LowerFrakjawLOT: - NjMonastryBossInstance::HandleLowerFrakjawSpawned(self, entity); - return; - default: - NjMonastryBossInstance::HandleWaveEnemySpawned(self, entity); - return; - } - }); - } - } + // Add a notification request for all the spawned entities, corresponds to notifySpawnedObjectLoaded + for (const auto& spawnerName : spawnerNames) { + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { + spawner->AddEntitySpawnedCallback([self, this](Entity* entity) { + const auto lot = entity->GetLOT(); + switch (lot) { + case LedgedFrakjawLOT: + NjMonastryBossInstance::HandleLedgedFrakjawSpawned(self, entity); + return; + case CounterWeightLOT: + NjMonastryBossInstance::HandleCounterWeightSpawned(self, entity); + return; + case LowerFrakjawLOT: + NjMonastryBossInstance::HandleLowerFrakjawSpawned(self, entity); + return; + default: + NjMonastryBossInstance::HandleWaveEnemySpawned(self, entity); + return; + } + }); + } + } } -void NjMonastryBossInstance::OnPlayerLoaded(Entity *self, Entity *player) { - ActivityTimerStop(self, WaitingForPlayersTimer); +void NjMonastryBossInstance::OnPlayerLoaded(Entity* self, Entity* player) { + ActivityTimerStop(self, WaitingForPlayersTimer); - // Join the player in the activity - UpdatePlayer(self, player->GetObjectID()); + // Join the player in the activity + UpdatePlayer(self, player->GetObjectID()); - // Buff the player - auto* destroyableComponent = player->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->SetHealth((int32_t) destroyableComponent->GetMaxHealth()); - destroyableComponent->SetArmor((int32_t) destroyableComponent->GetMaxArmor()); - destroyableComponent->SetImagination((int32_t) destroyableComponent->GetMaxImagination()); - } + // Buff the player + auto* destroyableComponent = player->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->SetHealth((int32_t)destroyableComponent->GetMaxHealth()); + destroyableComponent->SetArmor((int32_t)destroyableComponent->GetMaxArmor()); + destroyableComponent->SetImagination((int32_t)destroyableComponent->GetMaxImagination()); + } - // Add player ID to instance - auto totalPlayersLoaded = self->GetVar>(TotalPlayersLoadedVariable); - totalPlayersLoaded.push_back(player->GetObjectID()); + // Add player ID to instance + auto totalPlayersLoaded = self->GetVar>(TotalPlayersLoadedVariable); + totalPlayersLoaded.push_back(player->GetObjectID()); - // Properly position the player - self->SetVar>(TotalPlayersLoadedVariable, totalPlayersLoaded); - // This was always spawning all players at position one before and other values cause players to be invisible. - TeleportPlayer(player, 1); + // Properly position the player + self->SetVar>(TotalPlayersLoadedVariable, totalPlayersLoaded); + // This was always spawning all players at position one before and other values cause players to be invisible. + TeleportPlayer(player, 1); - // Large teams face a tougher challenge - if (totalPlayersLoaded.size() >= 3) - self->SetVar(LargeTeamVariable, true); + // Large teams face a tougher challenge + if (totalPlayersLoaded.size() >= 3) + self->SetVar(LargeTeamVariable, true); - // Start the game if all players in the team have loaded - auto* team = TeamManager::Instance()->GetTeam(player->GetObjectID()); - if (team == nullptr || totalPlayersLoaded.size() == team->members.size()) { - StartFight(self); - return; - } + // Start the game if all players in the team have loaded + auto* team = TeamManager::Instance()->GetTeam(player->GetObjectID()); + if (team == nullptr || totalPlayersLoaded.size() == team->members.size()) { + StartFight(self); + return; + } - self->AddCallbackTimer(0.0f, [self, player]() { - if (player != nullptr) { - // If we don't have enough players yet, wait for the others to load and notify the client to play a cool cinematic - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayerLoaded", 0, 0, - player->GetObjectID(), "", player->GetSystemAddress()); - } - }); + self->AddCallbackTimer(0.0f, [self, player]() { + if (player != nullptr) { + // If we don't have enough players yet, wait for the others to load and notify the client to play a cool cinematic + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayerLoaded", 0, 0, + player->GetObjectID(), "", player->GetSystemAddress()); + } + }); - ActivityTimerStart(self, WaitingForPlayersTimer, 45.0f, 45.0f); + ActivityTimerStart(self, WaitingForPlayersTimer, 45.0f, 45.0f); } -void NjMonastryBossInstance::OnPlayerExit(Entity *self, Entity *player) { - UpdatePlayer(self, player->GetObjectID(), true); - // Fetch the total players loaded from the vars - auto totalPlayersLoaded = self->GetVar >(TotalPlayersLoadedVariable); +void NjMonastryBossInstance::OnPlayerExit(Entity* self, Entity* player) { + UpdatePlayer(self, player->GetObjectID(), true); + // Fetch the total players loaded from the vars + auto totalPlayersLoaded = self->GetVar >(TotalPlayersLoadedVariable); - // Find the player to remove - auto playerToRemove = std::find(totalPlayersLoaded.begin(), totalPlayersLoaded.end(), player->GetObjectID()); + // Find the player to remove + auto playerToRemove = std::find(totalPlayersLoaded.begin(), totalPlayersLoaded.end(), player->GetObjectID()); - // If we found the player remove them from out list of players - if (playerToRemove != totalPlayersLoaded.end()) { - totalPlayersLoaded.erase(playerToRemove); - } else { - Game::logger->Log("NjMonastryBossInstance", "Failed to remove player at exit."); - } + // If we found the player remove them from out list of players + if (playerToRemove != totalPlayersLoaded.end()) { + totalPlayersLoaded.erase(playerToRemove); + } else { + Game::logger->Log("NjMonastryBossInstance", "Failed to remove player at exit."); + } - // Set the players loaded var back - self->SetVar>(TotalPlayersLoadedVariable, totalPlayersLoaded); + // Set the players loaded var back + self->SetVar>(TotalPlayersLoadedVariable, totalPlayersLoaded); - // Since this is an exit method, check if enough players have left. If enough have left - // resize the instance to account for such. - if (totalPlayersLoaded.size() <= 2) self->SetVar(LargeTeamVariable, false); + // Since this is an exit method, check if enough players have left. If enough have left + // resize the instance to account for such. + if (totalPlayersLoaded.size() <= 2) self->SetVar(LargeTeamVariable, false); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayerLeft", 0, 0, player->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayerLeft", 0, 0, player->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); } -void NjMonastryBossInstance::OnActivityTimerDone(Entity *self, const std::string &name) { - auto split = GeneralUtils::SplitString(name, TimerSplitChar); - auto timerName = split[0]; - auto objectID = split.size() > 1 ? (LWOOBJID) std::stoull(split[1]) : LWOOBJID_EMPTY; +void NjMonastryBossInstance::OnActivityTimerDone(Entity* self, const std::string& name) { + auto split = GeneralUtils::SplitString(name, TimerSplitChar); + auto timerName = split[0]; + auto objectID = split.size() > 1 ? (LWOOBJID)std::stoull(split[1]) : LWOOBJID_EMPTY; - if (timerName == WaitingForPlayersTimer) { - StartFight(self); - } else if (timerName == SpawnNextWaveTimer) { - auto* frakjaw = EntityManager::Instance()->GetEntity(self->GetVar(LedgeFrakjawVariable)); - if (frakjaw != nullptr) { - SummonWave(self, frakjaw); - } - } else if (timerName == SpawnWaveTimer) { - auto wave = self->GetVar(WaveNumberVariable); - self->SetVar(WaveNumberVariable, wave + 1); - self->SetVar(TotalAliveInWaveVariable, 0); + if (timerName == WaitingForPlayersTimer) { + StartFight(self); + } else if (timerName == SpawnNextWaveTimer) { + auto* frakjaw = EntityManager::Instance()->GetEntity(self->GetVar(LedgeFrakjawVariable)); + if (frakjaw != nullptr) { + SummonWave(self, frakjaw); + } + } else if (timerName == SpawnWaveTimer) { + auto wave = self->GetVar(WaveNumberVariable); + self->SetVar(WaveNumberVariable, wave + 1); + self->SetVar(TotalAliveInWaveVariable, 0); - if (wave < m_Waves.size()) { - auto waves = m_Waves.at(wave); - auto counter = 0; + if (wave < m_Waves.size()) { + auto waves = m_Waves.at(wave); + auto counter = 0; - for (const auto& waveEnemy : waves) { - const auto numberToSpawn = self->GetVar(LargeTeamVariable) - ? waveEnemy.largeNumber : waveEnemy.smallNumber; + for (const auto& waveEnemy : waves) { + const auto numberToSpawn = self->GetVar(LargeTeamVariable) + ? waveEnemy.largeNumber : waveEnemy.smallNumber; - auto spawnIndex = counter % 4 + 1; - SpawnOnNetwork(self, waveEnemy.lot, numberToSpawn, BaseEnemiesSpawner + std::to_string(spawnIndex)); - counter++; - } - } - } else if (timerName + TimerSplitChar == UnstunTimer) { - auto* entity = EntityManager::Instance()->GetEntity(objectID); - if (entity != nullptr) { - auto* combatAI = entity->GetComponent(); - if (combatAI != nullptr) { - combatAI->SetDisabled(false); - } - } - } else if (timerName == SpawnCounterWeightTimer) { - auto spawners = dZoneManager::Instance()->GetSpawnersByName(CounterweightSpawner); - if (!spawners.empty()) { - // Spawn the counter weight at a specific waypoint, there's one for each round - auto* spawner = spawners.front(); + auto spawnIndex = counter % 4 + 1; + SpawnOnNetwork(self, waveEnemy.lot, numberToSpawn, BaseEnemiesSpawner + std::to_string(spawnIndex)); + counter++; + } + } + } else if (timerName + TimerSplitChar == UnstunTimer) { + auto* entity = EntityManager::Instance()->GetEntity(objectID); + if (entity != nullptr) { + auto* combatAI = entity->GetComponent(); + if (combatAI != nullptr) { + combatAI->SetDisabled(false); + } + } + } else if (timerName == SpawnCounterWeightTimer) { + auto spawners = dZoneManager::Instance()->GetSpawnersByName(CounterweightSpawner); + if (!spawners.empty()) { + // Spawn the counter weight at a specific waypoint, there's one for each round + auto* spawner = spawners.front(); - spawner->Spawn({ - spawner->m_Info.nodes.at((self->GetVar(WaveNumberVariable) - 1) % 3) - }, true); - } - } else if (timerName == LowerFrakjawCamTimer) { - // Destroy the frakjaw on the ledge - auto* ledgeFrakjaw = EntityManager::Instance()->GetEntity(self->GetVar(LedgeFrakjawVariable)); - if (ledgeFrakjaw != nullptr) { - ledgeFrakjaw->Kill(); - } + spawner->Spawn({ + spawner->m_Info.nodes.at((self->GetVar(WaveNumberVariable) - 1) % 3) + }, true); + } + } else if (timerName == LowerFrakjawCamTimer) { + // Destroy the frakjaw on the ledge + auto* ledgeFrakjaw = EntityManager::Instance()->GetEntity(self->GetVar(LedgeFrakjawVariable)); + if (ledgeFrakjaw != nullptr) { + ledgeFrakjaw->Kill(); + } - ActivityTimerStart(self, SpawnLowerFrakjawTimer, 1.0f, 1.0f); - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, - LWOOBJID_EMPTY, BottomFrakSpawn, UNASSIGNED_SYSTEM_ADDRESS); - } else if (timerName == SpawnLowerFrakjawTimer) { - auto spawners = dZoneManager::Instance()->GetSpawnersByName(LowerFrakjawSpawner); - if (!spawners.empty()) { - auto* spawner = spawners.front(); - spawner->Activate(); - } - } else if (timerName == SpawnRailTimer) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, - LWOOBJID_EMPTY, FireRailSpawn, UNASSIGNED_SYSTEM_ADDRESS); + ActivityTimerStart(self, SpawnLowerFrakjawTimer, 1.0f, 1.0f); + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, + LWOOBJID_EMPTY, BottomFrakSpawn, UNASSIGNED_SYSTEM_ADDRESS); + } else if (timerName == SpawnLowerFrakjawTimer) { + auto spawners = dZoneManager::Instance()->GetSpawnersByName(LowerFrakjawSpawner); + if (!spawners.empty()) { + auto* spawner = spawners.front(); + spawner->Activate(); + } + } else if (timerName == SpawnRailTimer) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, + LWOOBJID_EMPTY, FireRailSpawn, UNASSIGNED_SYSTEM_ADDRESS); - auto spawners = dZoneManager::Instance()->GetSpawnersByName(FireRailSpawner); - if (!spawners.empty()) { - auto* spawner = spawners.front(); - spawner->Activate(); - } - } else if (timerName + TimerSplitChar == FrakjawSpawnInTimer) { - auto* lowerFrakjaw = EntityManager::Instance()->GetEntity(objectID); - if (lowerFrakjaw != nullptr) { - LowerFrakjawSummon(self, lowerFrakjaw); - } - } else if (timerName == WaveOverTimer) { - WaveOver(self); - } else if (timerName == FightOverTimer) { - FightOver(self); - } + auto spawners = dZoneManager::Instance()->GetSpawnersByName(FireRailSpawner); + if (!spawners.empty()) { + auto* spawner = spawners.front(); + spawner->Activate(); + } + } else if (timerName + TimerSplitChar == FrakjawSpawnInTimer) { + auto* lowerFrakjaw = EntityManager::Instance()->GetEntity(objectID); + if (lowerFrakjaw != nullptr) { + LowerFrakjawSummon(self, lowerFrakjaw); + } + } else if (timerName == WaveOverTimer) { + WaveOver(self); + } else if (timerName == FightOverTimer) { + FightOver(self); + } } // // // // // // // // // Custom functions // // // // // // // // // -void NjMonastryBossInstance::StartFight(Entity *self) { - if (self->GetVar(FightStartedVariable)) - return; +void NjMonastryBossInstance::StartFight(Entity* self) { + if (self->GetVar(FightStartedVariable)) + return; - self->SetVar(FightStartedVariable, true); + self->SetVar(FightStartedVariable, true); - // Activate the frakjaw spawner - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(LedgeFrakjawSpawner)) { - spawner->Activate(); - } + // Activate the frakjaw spawner + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(LedgeFrakjawSpawner)) { + spawner->Activate(); + } } -void NjMonastryBossInstance::HandleLedgedFrakjawSpawned(Entity *self, Entity *ledgedFrakjaw) { - self->SetVar(LedgeFrakjawVariable, ledgedFrakjaw->GetObjectID()); - SummonWave(self, ledgedFrakjaw); +void NjMonastryBossInstance::HandleLedgedFrakjawSpawned(Entity* self, Entity* ledgedFrakjaw) { + self->SetVar(LedgeFrakjawVariable, ledgedFrakjaw->GetObjectID()); + SummonWave(self, ledgedFrakjaw); } -void NjMonastryBossInstance::HandleCounterWeightSpawned(Entity *self, Entity *counterWeight) { - auto* rebuildComponent = counterWeight->GetComponent(); - if (rebuildComponent != nullptr) { - rebuildComponent->AddRebuildStateCallback([this, self, counterWeight](eRebuildState state) { +void NjMonastryBossInstance::HandleCounterWeightSpawned(Entity* self, Entity* counterWeight) { + auto* rebuildComponent = counterWeight->GetComponent(); + if (rebuildComponent != nullptr) { + rebuildComponent->AddRebuildStateCallback([this, self, counterWeight](eRebuildState state) { - switch (state) { - case REBUILD_BUILDING: - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, - 0, 0, counterWeight->GetObjectID(), - BaseCounterweightQB + std::to_string(self->GetVar(WaveNumberVariable)), - UNASSIGNED_SYSTEM_ADDRESS); - return; - case REBUILD_INCOMPLETE: - GameMessages::SendNotifyClientObject(self->GetObjectID(), EndCinematicNotification, - 0, 0, LWOOBJID_EMPTY,"", - UNASSIGNED_SYSTEM_ADDRESS); - return; - case REBUILD_RESETTING: - ActivityTimerStart(self, SpawnCounterWeightTimer, 0.0f, 0.0f); - return; - case REBUILD_COMPLETED: { - // TODO: Move the platform? + switch (state) { + case REBUILD_BUILDING: + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, + 0, 0, counterWeight->GetObjectID(), + BaseCounterweightQB + std::to_string(self->GetVar(WaveNumberVariable)), + UNASSIGNED_SYSTEM_ADDRESS); + return; + case REBUILD_INCOMPLETE: + GameMessages::SendNotifyClientObject(self->GetObjectID(), EndCinematicNotification, + 0, 0, LWOOBJID_EMPTY, "", + UNASSIGNED_SYSTEM_ADDRESS); + return; + case REBUILD_RESETTING: + ActivityTimerStart(self, SpawnCounterWeightTimer, 0.0f, 0.0f); + return; + case REBUILD_COMPLETED: { + // TODO: Move the platform? - // The counterweight is actually a moving platform and we should listen to the last waypoint event here - // 0.5f is a rough estimate of that path, though, and results in less needed logic - self->AddCallbackTimer(0.5f, [this, self, counterWeight]() { - if (counterWeight != nullptr) { - counterWeight->Kill(); - } + // The counterweight is actually a moving platform and we should listen to the last waypoint event here + // 0.5f is a rough estimate of that path, though, and results in less needed logic + self->AddCallbackTimer(0.5f, [this, self, counterWeight]() { + if (counterWeight != nullptr) { + counterWeight->Kill(); + } - auto* frakjaw = EntityManager::Instance()->GetEntity(self->GetVar(LedgeFrakjawVariable)); - if (frakjaw == nullptr) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"LedgeFrakjawDead", 0, - 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - return; - } + auto* frakjaw = EntityManager::Instance()->GetEntity(self->GetVar(LedgeFrakjawVariable)); + if (frakjaw == nullptr) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"LedgeFrakjawDead", 0, + 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + return; + } - auto* skillComponent = frakjaw->GetComponent(); - if (skillComponent != nullptr) { - skillComponent->CalculateBehavior(1635, 39097, frakjaw->GetObjectID(), true, false); - } + auto* skillComponent = frakjaw->GetComponent(); + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(1635, 39097, frakjaw->GetObjectID(), true, false); + } - GameMessages::SendPlayAnimation(frakjaw, StunnedAnimation); - GameMessages::SendPlayNDAudioEmitter(frakjaw, UNASSIGNED_SYSTEM_ADDRESS, CounterSmashAudio); + GameMessages::SendPlayAnimation(frakjaw, StunnedAnimation); + GameMessages::SendPlayNDAudioEmitter(frakjaw, UNASSIGNED_SYSTEM_ADDRESS, CounterSmashAudio); - // Before wave 4 we should lower frakjaw from the ledge - if (self->GetVar(WaveNumberVariable) == 3) { - LowerFrakjaw(self, frakjaw); - return; - } + // Before wave 4 we should lower frakjaw from the ledge + if (self->GetVar(WaveNumberVariable) == 3) { + LowerFrakjaw(self, frakjaw); + return; + } - ActivityTimerStart(self, SpawnNextWaveTimer, 2.0f, 2.0f); - }); - } - default: - return; - } - }); - } + ActivityTimerStart(self, SpawnNextWaveTimer, 2.0f, 2.0f); + }); + } + default: + return; + } + }); + } } -void NjMonastryBossInstance::HandleLowerFrakjawSpawned(Entity *self, Entity *lowerFrakjaw) { - GameMessages::SendPlayAnimation(lowerFrakjaw, TeleportInAnimation); - self->SetVar(LowerFrakjawVariable, lowerFrakjaw->GetObjectID()); +void NjMonastryBossInstance::HandleLowerFrakjawSpawned(Entity* self, Entity* lowerFrakjaw) { + GameMessages::SendPlayAnimation(lowerFrakjaw, TeleportInAnimation); + self->SetVar(LowerFrakjawVariable, lowerFrakjaw->GetObjectID()); - auto* combatAI = lowerFrakjaw->GetComponent(); - if (combatAI != nullptr) { - combatAI->SetDisabled(true); - } + auto* combatAI = lowerFrakjaw->GetComponent(); + if (combatAI != nullptr) { + combatAI->SetDisabled(true); + } - auto* destroyableComponent = lowerFrakjaw->GetComponent(); - if (destroyableComponent != nullptr) { - destroyableComponent->AddOnHitCallback([this, self, lowerFrakjaw](Entity* attacker) { - NjMonastryBossInstance::HandleLowerFrakjawHit(self, lowerFrakjaw, attacker); - }); - } + auto* destroyableComponent = lowerFrakjaw->GetComponent(); + if (destroyableComponent != nullptr) { + destroyableComponent->AddOnHitCallback([this, self, lowerFrakjaw](Entity* attacker) { + NjMonastryBossInstance::HandleLowerFrakjawHit(self, lowerFrakjaw, attacker); + }); + } - lowerFrakjaw->AddDieCallback([this, self, lowerFrakjaw]() { - NjMonastryBossInstance::HandleLowerFrakjawDied(self, lowerFrakjaw); - }); + lowerFrakjaw->AddDieCallback([this, self, lowerFrakjaw]() { + NjMonastryBossInstance::HandleLowerFrakjawDied(self, lowerFrakjaw); + }); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"LedgeFrakjawDead", 0, 0, - LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"LedgeFrakjawDead", 0, 0, + LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - if (self->GetVar(LargeTeamVariable)) { - // Double frakjaws health for large teams - if (destroyableComponent != nullptr) { - const auto doubleHealth = destroyableComponent->GetHealth() * 2; - destroyableComponent->SetHealth(doubleHealth); - destroyableComponent->SetMaxHealth((float_t) doubleHealth); - } + if (self->GetVar(LargeTeamVariable)) { + // Double frakjaws health for large teams + if (destroyableComponent != nullptr) { + const auto doubleHealth = destroyableComponent->GetHealth() * 2; + destroyableComponent->SetHealth(doubleHealth); + destroyableComponent->SetMaxHealth((float_t)doubleHealth); + } - ActivityTimerStart(self, FrakjawSpawnInTimer + std::to_string(lowerFrakjaw->GetObjectID()), - 2.0f, 2.0f); - ActivityTimerStart(self, UnstunTimer + std::to_string(lowerFrakjaw->GetObjectID()), - 7.0f, 7.0f); - } else { - ActivityTimerStart(self, UnstunTimer + std::to_string(lowerFrakjaw->GetObjectID()), - 5.0f, 5.0f); - } + ActivityTimerStart(self, FrakjawSpawnInTimer + std::to_string(lowerFrakjaw->GetObjectID()), + 2.0f, 2.0f); + ActivityTimerStart(self, UnstunTimer + std::to_string(lowerFrakjaw->GetObjectID()), + 7.0f, 7.0f); + } else { + ActivityTimerStart(self, UnstunTimer + std::to_string(lowerFrakjaw->GetObjectID()), + 5.0f, 5.0f); + } } -void NjMonastryBossInstance::HandleLowerFrakjawHit(Entity *self, Entity *lowerFrakjaw, Entity *attacker) { - auto* destroyableComponent = lowerFrakjaw->GetComponent(); - if (destroyableComponent == nullptr) - return; +void NjMonastryBossInstance::HandleLowerFrakjawHit(Entity* self, Entity* lowerFrakjaw, Entity* attacker) { + auto* destroyableComponent = lowerFrakjaw->GetComponent(); + if (destroyableComponent == nullptr) + return; - // Progress the fight to the last wave if frakjaw has less than 50% of his health left - if (destroyableComponent->GetHealth() <= (uint32_t) destroyableComponent->GetMaxHealth() / 2 && !self->GetVar(OnLastWaveVarbiale)) { - self->SetVar(OnLastWaveVarbiale, true); + // Progress the fight to the last wave if frakjaw has less than 50% of his health left + if (destroyableComponent->GetHealth() <= (uint32_t)destroyableComponent->GetMaxHealth() / 2 && !self->GetVar(OnLastWaveVarbiale)) { + self->SetVar(OnLastWaveVarbiale, true); - // Stun frakjaw during the cinematic - auto* combatAI = lowerFrakjaw->GetComponent(); - if (combatAI != nullptr) { - combatAI->SetDisabled(true); - } - ActivityTimerStart(self, UnstunTimer + std::to_string(lowerFrakjaw->GetObjectID()), 5.0f, 5.0f); + // Stun frakjaw during the cinematic + auto* combatAI = lowerFrakjaw->GetComponent(); + if (combatAI != nullptr) { + combatAI->SetDisabled(true); + } + ActivityTimerStart(self, UnstunTimer + std::to_string(lowerFrakjaw->GetObjectID()), 5.0f, 5.0f); - const auto trashMobsAlive = self->GetVar>(TrashMobsAliveVariable); - std::vector newTrashMobs = {}; + const auto trashMobsAlive = self->GetVar>(TrashMobsAliveVariable); + std::vector newTrashMobs = {}; - for (const auto& trashMobID : trashMobsAlive) { - auto* trashMob = EntityManager::Instance()->GetEntity(trashMobID); - if (trashMob != nullptr) { - newTrashMobs.push_back(trashMobID); + for (const auto& trashMobID : trashMobsAlive) { + auto* trashMob = EntityManager::Instance()->GetEntity(trashMobID); + if (trashMob != nullptr) { + newTrashMobs.push_back(trashMobID); - // Stun all the enemies until the cinematic is over - auto* trashMobCombatAI = trashMob->GetComponent(); - if (trashMobCombatAI != nullptr) { - trashMobCombatAI->SetDisabled(true); - } - ActivityTimerStart(self, UnstunTimer + std::to_string(trashMobID), 5.0f, 5.0f); - } - } + // Stun all the enemies until the cinematic is over + auto* trashMobCombatAI = trashMob->GetComponent(); + if (trashMobCombatAI != nullptr) { + trashMobCombatAI->SetDisabled(true); + } + ActivityTimerStart(self, UnstunTimer + std::to_string(trashMobID), 5.0f, 5.0f); + } + } - self->SetVar>(TrashMobsAliveVariable, newTrashMobs); + self->SetVar>(TrashMobsAliveVariable, newTrashMobs); - LowerFrakjawSummon(self, lowerFrakjaw); - RemovePoison(self); - } + LowerFrakjawSummon(self, lowerFrakjaw); + RemovePoison(self); + } } -void NjMonastryBossInstance::HandleLowerFrakjawDied(Entity *self, Entity *lowerFrakjaw) { - ActivityTimerStart(self, FightOverTimer, 2.0f, 2.0f); +void NjMonastryBossInstance::HandleLowerFrakjawDied(Entity* self, Entity* lowerFrakjaw) { + ActivityTimerStart(self, FightOverTimer, 2.0f, 2.0f); } -void NjMonastryBossInstance::HandleWaveEnemySpawned(Entity *self, Entity *waveEnemy) { - waveEnemy->AddDieCallback([this, self, waveEnemy]() { - NjMonastryBossInstance::HandleWaveEnemyDied(self, waveEnemy); - }); +void NjMonastryBossInstance::HandleWaveEnemySpawned(Entity* self, Entity* waveEnemy) { + waveEnemy->AddDieCallback([this, self, waveEnemy]() { + NjMonastryBossInstance::HandleWaveEnemyDied(self, waveEnemy); + }); - auto waveEnemies = self->GetVar>(TrashMobsAliveVariable); - waveEnemies.push_back(waveEnemy->GetObjectID()); - self->SetVar>(TrashMobsAliveVariable, waveEnemies); + auto waveEnemies = self->GetVar>(TrashMobsAliveVariable); + waveEnemies.push_back(waveEnemy->GetObjectID()); + self->SetVar>(TrashMobsAliveVariable, waveEnemies); - auto* combatAI = waveEnemy->GetComponent(); - if (combatAI != nullptr) { - combatAI->SetDisabled(true); - ActivityTimerStart(self, UnstunTimer + std::to_string(waveEnemy->GetObjectID()), 3.0f, 3.0f); - } + auto* combatAI = waveEnemy->GetComponent(); + if (combatAI != nullptr) { + combatAI->SetDisabled(true); + ActivityTimerStart(self, UnstunTimer + std::to_string(waveEnemy->GetObjectID()), 3.0f, 3.0f); + } } -void NjMonastryBossInstance::HandleWaveEnemyDied(Entity *self, Entity* waveEnemy) { - auto waveEnemies = self->GetVar>(TrashMobsAliveVariable); - waveEnemies.erase(std::remove(waveEnemies.begin(), waveEnemies.end(), waveEnemy->GetObjectID()), waveEnemies.end()); - self->SetVar>(TrashMobsAliveVariable, waveEnemies); +void NjMonastryBossInstance::HandleWaveEnemyDied(Entity* self, Entity* waveEnemy) { + auto waveEnemies = self->GetVar>(TrashMobsAliveVariable); + waveEnemies.erase(std::remove(waveEnemies.begin(), waveEnemies.end(), waveEnemy->GetObjectID()), waveEnemies.end()); + self->SetVar>(TrashMobsAliveVariable, waveEnemies); - if (waveEnemies.empty()) { - ActivityTimerStart(self, WaveOverTimer, 2.0f, 2.0f); - } + if (waveEnemies.empty()) { + ActivityTimerStart(self, WaveOverTimer, 2.0f, 2.0f); + } } -void NjMonastryBossInstance::TeleportPlayer(Entity *player, uint32_t position) { - for (const auto* spawnPoint : EntityManager::Instance()->GetEntitiesInGroup("SpawnPoint" + std::to_string(position))) { - GameMessages::SendTeleport(player->GetObjectID(), spawnPoint->GetPosition(), spawnPoint->GetRotation(), - player->GetSystemAddress(), true); - } +void NjMonastryBossInstance::TeleportPlayer(Entity* player, uint32_t position) { + for (const auto* spawnPoint : EntityManager::Instance()->GetEntitiesInGroup("SpawnPoint" + std::to_string(position))) { + GameMessages::SendTeleport(player->GetObjectID(), spawnPoint->GetPosition(), spawnPoint->GetRotation(), + player->GetSystemAddress(), true); + } } void NjMonastryBossInstance::SummonWave(Entity* self, Entity* frakjaw) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, LWOOBJID_EMPTY, - LedgeFrakSummon, UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendPlayAnimation(frakjaw, SummonAnimation); + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, LWOOBJID_EMPTY, + LedgeFrakSummon, UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendPlayAnimation(frakjaw, SummonAnimation); - // Stop the music for the first, fourth and fifth wave - const auto wave = self->GetVar(WaveNumberVariable); - if (wave >= 1 || wave < (m_Waves.size() - 1)) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), StopMusicNotification, 0, 0, - LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(wave - 1), - UNASSIGNED_SYSTEM_ADDRESS); - } + // Stop the music for the first, fourth and fifth wave + const auto wave = self->GetVar(WaveNumberVariable); + if (wave >= 1 || wave < (m_Waves.size() - 1)) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), StopMusicNotification, 0, 0, + LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(wave - 1), + UNASSIGNED_SYSTEM_ADDRESS); + } - // After frakjaw moves down the music stays the same - if (wave < (m_Waves.size() - 1)) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), StartMusicNotification, 0, 0, - LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(wave), - UNASSIGNED_SYSTEM_ADDRESS); - } + // After frakjaw moves down the music stays the same + if (wave < (m_Waves.size() - 1)) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), StartMusicNotification, 0, 0, + LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(wave), + UNASSIGNED_SYSTEM_ADDRESS); + } - ActivityTimerStart(self, SpawnWaveTimer, 4.0f, 4.0f); + ActivityTimerStart(self, SpawnWaveTimer, 4.0f, 4.0f); } -void NjMonastryBossInstance::LowerFrakjawSummon(Entity *self, Entity *frakjaw) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, - LWOOBJID_EMPTY, BottomFrakSummon, UNASSIGNED_SYSTEM_ADDRESS); - ActivityTimerStart(self, SpawnWaveTimer, 2.0f, 2.0f); - GameMessages::SendPlayAnimation(frakjaw, SummonAnimation); +void NjMonastryBossInstance::LowerFrakjawSummon(Entity* self, Entity* frakjaw) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, + LWOOBJID_EMPTY, BottomFrakSummon, UNASSIGNED_SYSTEM_ADDRESS); + ActivityTimerStart(self, SpawnWaveTimer, 2.0f, 2.0f); + GameMessages::SendPlayAnimation(frakjaw, SummonAnimation); } -void NjMonastryBossInstance::RemovePoison(Entity *self) { - const auto& totalPlayer = self->GetVar>(TotalPlayersLoadedVariable); - for (const auto& playerID : totalPlayer) { +void NjMonastryBossInstance::RemovePoison(Entity* self) { + const auto& totalPlayer = self->GetVar>(TotalPlayersLoadedVariable); + for (const auto& playerID : totalPlayer) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player != nullptr) { - auto* buffComponent = player->GetComponent(); - if (buffComponent != nullptr) { - buffComponent->RemoveBuff(PoisonBuff); - } - } - } + auto* buffComponent = player->GetComponent(); + if (buffComponent != nullptr) { + buffComponent->RemoveBuff(PoisonBuff); + } + } + } } -void NjMonastryBossInstance::LowerFrakjaw(Entity *self, Entity* frakjaw) { - GameMessages::SendPlayAnimation(frakjaw, TeleportOutAnimation); - ActivityTimerStart(self, LowerFrakjawCamTimer, 2.0f, 2.0f); +void NjMonastryBossInstance::LowerFrakjaw(Entity* self, Entity* frakjaw) { + GameMessages::SendPlayAnimation(frakjaw, TeleportOutAnimation); + ActivityTimerStart(self, LowerFrakjawCamTimer, 2.0f, 2.0f); - GameMessages::SendNotifyClientObject(frakjaw->GetObjectID(), StopMusicNotification, 0, 0, - LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(m_Waves.size() - 3), UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendNotifyClientObject(frakjaw->GetObjectID(), StartMusicNotification, 0, 0, - LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(m_Waves.size() - 2), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(frakjaw->GetObjectID(), StopMusicNotification, 0, 0, + LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(m_Waves.size() - 3), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(frakjaw->GetObjectID(), StartMusicNotification, 0, 0, + LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(m_Waves.size() - 2), UNASSIGNED_SYSTEM_ADDRESS); } void NjMonastryBossInstance::SpawnOnNetwork(Entity* self, const LOT& toSpawn, const uint32_t& numberToSpawn, const std::string& spawnerName) { - auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); - if (spawners.empty() || numberToSpawn <= 0) - return; + auto spawners = dZoneManager::Instance()->GetSpawnersByName(spawnerName); + if (spawners.empty() || numberToSpawn <= 0) + return; - auto* spawner = spawners.front(); + auto* spawner = spawners.front(); - // Spawn the lot N times - spawner->SetSpawnLot(toSpawn); - for (auto i = 0; i < numberToSpawn; i++) - spawner->Spawn({ spawner->m_Info.nodes.at(i % spawner->m_Info.nodes.size()) }, true); + // Spawn the lot N times + spawner->SetSpawnLot(toSpawn); + for (auto i = 0; i < numberToSpawn; i++) + spawner->Spawn({ spawner->m_Info.nodes.at(i % spawner->m_Info.nodes.size()) }, true); } -void NjMonastryBossInstance::WaveOver(Entity *self) { - auto wave = self->GetVar(WaveNumberVariable); - if (wave >= m_Waves.size() - 1) - return; +void NjMonastryBossInstance::WaveOver(Entity* self) { + auto wave = self->GetVar(WaveNumberVariable); + if (wave >= m_Waves.size() - 1) + return; - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, - LWOOBJID_EMPTY, BaseCounterweightSpawn + std::to_string(wave), - UNASSIGNED_SYSTEM_ADDRESS); - ActivityTimerStart(self, SpawnCounterWeightTimer, 1.5f, 1.5f); - RemovePoison(self); + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, + LWOOBJID_EMPTY, BaseCounterweightSpawn + std::to_string(wave), + UNASSIGNED_SYSTEM_ADDRESS); + ActivityTimerStart(self, SpawnCounterWeightTimer, 1.5f, 1.5f); + RemovePoison(self); } -void NjMonastryBossInstance::FightOver(Entity *self) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"GroundFrakjawDead", 0, 0, - LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); +void NjMonastryBossInstance::FightOver(Entity* self) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"GroundFrakjawDead", 0, 0, + LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - // Remove all the enemies from the battlefield - for (auto i = 1; i < 5; i++) { - auto spawners = dZoneManager::Instance()->GetSpawnersByName(BaseEnemiesSpawner + std::to_string(i)); - if (!spawners.empty()) { - auto* spawner = spawners.front(); - spawner->Deactivate(); - spawner->Reset(); - } - } + // Remove all the enemies from the battlefield + for (auto i = 1; i < 5; i++) { + auto spawners = dZoneManager::Instance()->GetSpawnersByName(BaseEnemiesSpawner + std::to_string(i)); + if (!spawners.empty()) { + auto* spawner = spawners.front(); + spawner->Deactivate(); + spawner->Reset(); + } + } - RemovePoison(self); - ActivityTimerStart(self, SpawnRailTimer, 1.5f, 1.5f); + RemovePoison(self); + ActivityTimerStart(self, SpawnRailTimer, 1.5f, 1.5f); - // Set the music to play the victory music - GameMessages::SendNotifyClientObject(self->GetObjectID(), StopMusicNotification, 0, 0, - LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(m_Waves.size() - 2), - UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendNotifyClientObject(self->GetObjectID(), FlashMusicNotification, 0, 0, - LWOOBJID_EMPTY, "Monastery_Frakjaw_Battle_Win", UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, - LWOOBJID_EMPTY, TreasureChestSpawning, UNASSIGNED_SYSTEM_ADDRESS); + // Set the music to play the victory music + GameMessages::SendNotifyClientObject(self->GetObjectID(), StopMusicNotification, 0, 0, + LWOOBJID_EMPTY, AudioWaveAudio + std::to_string(m_Waves.size() - 2), + UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(self->GetObjectID(), FlashMusicNotification, 0, 0, + LWOOBJID_EMPTY, "Monastery_Frakjaw_Battle_Win", UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, + LWOOBJID_EMPTY, TreasureChestSpawning, UNASSIGNED_SYSTEM_ADDRESS); - auto treasureChests = EntityManager::Instance()->GetEntitiesInGroup(ChestSpawnpointGroup); - for (auto* treasureChest : treasureChests) { - auto info = EntityInfo {}; + auto treasureChests = EntityManager::Instance()->GetEntitiesInGroup(ChestSpawnpointGroup); + for (auto* treasureChest : treasureChests) { + auto info = EntityInfo{}; - info.lot = ChestLOT; - info.pos = treasureChest->GetPosition(); - info.rot = treasureChest->GetRotation(); - info.spawnerID = self->GetObjectID(); - info.settings = { - new LDFData(u"parent_tag", self->GetObjectID()) - }; + info.lot = ChestLOT; + info.pos = treasureChest->GetPosition(); + info.rot = treasureChest->GetRotation(); + info.spawnerID = self->GetObjectID(); + info.settings = { + new LDFData(u"parent_tag", self->GetObjectID()) + }; - // Finally spawn a treasure chest at the correct spawn point - auto* chestObject = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(chestObject); - } + // Finally spawn a treasure chest at the correct spawn point + auto* chestObject = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(chestObject); + } } diff --git a/dScripts/NjMonastryBossInstance.h b/dScripts/NjMonastryBossInstance.h index 6153d84f..86553c18 100644 --- a/dScripts/NjMonastryBossInstance.h +++ b/dScripts/NjMonastryBossInstance.h @@ -2,156 +2,156 @@ #include "ActivityManager.h" enum FrakjawEnemies { - BoneWolf = 16191, - BlackSmith = 14007, - Marksman = 14008, - Commando = 14009, - MadScientist = 16511 + BoneWolf = 16191, + BlackSmith = 14007, + Marksman = 14008, + Commando = 14009, + MadScientist = 16511 }; enum FrakjawLots : LOT { - ChestLOT = 16486, - LedgedFrakjawLOT = 16289, - LowerFrakjawLOT = 16048, - CounterWeightLOT = 16141 + ChestLOT = 16486, + LedgedFrakjawLOT = 16289, + LowerFrakjawLOT = 16048, + CounterWeightLOT = 16141 }; struct FrakjawWaveEnemy { - LOT lot; - uint32_t largeNumber; - uint32_t smallNumber; + LOT lot; + uint32_t largeNumber; + uint32_t smallNumber; }; class NjMonastryBossInstance : public ActivityManager { public: - void OnStartup(Entity* self) override; - void OnPlayerLoaded(Entity* self, Entity* player) override; - void OnPlayerExit(Entity* self, Entity* player) override; - void OnActivityTimerDone(Entity *self, const std::string &name) override; + void OnStartup(Entity* self) override; + void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnPlayerExit(Entity* self, Entity* player) override; + void OnActivityTimerDone(Entity* self, const std::string& name) override; private: - void StartFight(Entity* self); - void WaveOver(Entity* self); - void FightOver(Entity* self); - void SummonWave(Entity* self, Entity* frakjaw); - void LowerFrakjaw(Entity* self, Entity* frakjaw); - void LowerFrakjawSummon(Entity* self, Entity* frakjaw); - void RemovePoison(Entity* self); - static void SpawnOnNetwork(Entity* self, const LOT& toSpawn, const uint32_t& numberToSpawn, const std::string& spawnerName); - static void TeleportPlayer(Entity* player, uint32_t position); + void StartFight(Entity* self); + void WaveOver(Entity* self); + void FightOver(Entity* self); + void SummonWave(Entity* self, Entity* frakjaw); + void LowerFrakjaw(Entity* self, Entity* frakjaw); + void LowerFrakjawSummon(Entity* self, Entity* frakjaw); + void RemovePoison(Entity* self); + static void SpawnOnNetwork(Entity* self, const LOT& toSpawn, const uint32_t& numberToSpawn, const std::string& spawnerName); + static void TeleportPlayer(Entity* player, uint32_t position); - // Event handlers for anything spawned by the main spawner - void HandleLedgedFrakjawSpawned(Entity* self, Entity* ledgedFrakjaw); - void HandleCounterWeightSpawned(Entity* self, Entity* counterWeight); - void HandleLowerFrakjawSpawned(Entity* self, Entity* lowerFrakjaw); - void HandleWaveEnemySpawned(Entity* self, Entity* waveEnemy); - void HandleWaveEnemyDied(Entity* self, Entity* waveEnemy); - void HandleLowerFrakjawHit(Entity* self, Entity* lowerFrakjaw, Entity* attacker); - void HandleLowerFrakjawDied(Entity* self, Entity* lowerFrakjaw); + // Event handlers for anything spawned by the main spawner + void HandleLedgedFrakjawSpawned(Entity* self, Entity* ledgedFrakjaw); + void HandleCounterWeightSpawned(Entity* self, Entity* counterWeight); + void HandleLowerFrakjawSpawned(Entity* self, Entity* lowerFrakjaw); + void HandleWaveEnemySpawned(Entity* self, Entity* waveEnemy); + void HandleWaveEnemyDied(Entity* self, Entity* waveEnemy); + void HandleLowerFrakjawHit(Entity* self, Entity* lowerFrakjaw, Entity* attacker); + void HandleLowerFrakjawDied(Entity* self, Entity* lowerFrakjaw); - const std::vector> m_Waves = { - // Wave 1 - { - { FrakjawEnemies::Marksman, 2, 1}, - { FrakjawEnemies::BlackSmith, 4, 3}, - { FrakjawEnemies::Commando, 2, 1}, - { FrakjawEnemies::MadScientist, 1, 0}, - }, + const std::vector> m_Waves = { + // Wave 1 + { + { FrakjawEnemies::Marksman, 2, 1}, + { FrakjawEnemies::BlackSmith, 4, 3}, + { FrakjawEnemies::Commando, 2, 1}, + { FrakjawEnemies::MadScientist, 1, 0}, + }, - // Wave 2 - { - { FrakjawEnemies::BoneWolf, 1, 0}, - { FrakjawEnemies::BlackSmith, 2, 2}, - { FrakjawEnemies::Marksman, 2, 1}, - { FrakjawEnemies::MadScientist, 1, 1}, - }, + // Wave 2 + { + { FrakjawEnemies::BoneWolf, 1, 0}, + { FrakjawEnemies::BlackSmith, 2, 2}, + { FrakjawEnemies::Marksman, 2, 1}, + { FrakjawEnemies::MadScientist, 1, 1}, + }, - // Wave 3 - { - { FrakjawEnemies::BoneWolf, 2, 1}, - { FrakjawEnemies::Marksman, 2, 1}, - { FrakjawEnemies::Commando, 2, 2}, - { FrakjawEnemies::MadScientist, 1, 0}, - }, + // Wave 3 + { + { FrakjawEnemies::BoneWolf, 2, 1}, + { FrakjawEnemies::Marksman, 2, 1}, + { FrakjawEnemies::Commando, 2, 2}, + { FrakjawEnemies::MadScientist, 1, 0}, + }, - // Wave 4 - { - { FrakjawEnemies::BlackSmith, 2, 2}, - { FrakjawEnemies::BoneWolf, 1, 1}, - { FrakjawEnemies::Commando, 3, 1}, - { FrakjawEnemies::Marksman, 2, 0}, - }, + // Wave 4 + { + { FrakjawEnemies::BlackSmith, 2, 2}, + { FrakjawEnemies::BoneWolf, 1, 1}, + { FrakjawEnemies::Commando, 3, 1}, + { FrakjawEnemies::Marksman, 2, 0}, + }, - // Wave 5 - { - { FrakjawEnemies::MadScientist, 1, 0}, - { FrakjawEnemies::BoneWolf, 2, 0}, - { FrakjawEnemies::Commando, 3, 0}, - { FrakjawEnemies::Marksman, 2, 0}, - } - }; + // Wave 5 + { + { FrakjawEnemies::MadScientist, 1, 0}, + { FrakjawEnemies::BoneWolf, 2, 0}, + { FrakjawEnemies::Commando, 3, 0}, + { FrakjawEnemies::Marksman, 2, 0}, + } + }; - const int32_t PoisonBuff = 60; + const int32_t PoisonBuff = 60; - // Variables - const std::u16string TotalPlayersLoadedVariable = u"TotalPlayersLoaded"; - const std::u16string LargeTeamVariable = u"LargeTeam"; - const std::u16string FightStartedVariable = u"FightStarted"; - const std::u16string LedgeFrakjawVariable = u"LedgeFrakjaw"; - const std::u16string LowerFrakjawVariable = u"LowerFrakjaw"; - const std::u16string WaveNumberVariable = u"WaveNumber"; - const std::u16string OnLastWaveVarbiale = u"OnLastWave"; - const std::u16string TrashMobsAliveVariable = u"TrashMobsAlive"; - const std::u16string TotalAliveInWaveVariable = u"TotalAliveInWave"; + // Variables + const std::u16string TotalPlayersLoadedVariable = u"TotalPlayersLoaded"; + const std::u16string LargeTeamVariable = u"LargeTeam"; + const std::u16string FightStartedVariable = u"FightStarted"; + const std::u16string LedgeFrakjawVariable = u"LedgeFrakjaw"; + const std::u16string LowerFrakjawVariable = u"LowerFrakjaw"; + const std::u16string WaveNumberVariable = u"WaveNumber"; + const std::u16string OnLastWaveVarbiale = u"OnLastWave"; + const std::u16string TrashMobsAliveVariable = u"TrashMobsAlive"; + const std::u16string TotalAliveInWaveVariable = u"TotalAliveInWave"; - // Timers - const char TimerSplitChar = '+'; - const std::string WaitingForPlayersTimer = "WaitingForPlayers"; - const std::string SpawnWaveTimer = "SpawnWave"; - const std::string SpawnNextWaveTimer = "SpawnNextWave"; - const std::string UnstunTimer = "Unstun+"; - const std::string FrakjawSpawnInTimer = "LowerFrakjawSpawnIn+"; - const std::string WaveOverTimer = "WaveOverTimer"; - const std::string FightOverTimer = "FightOver"; - const std::string LowerFrakjawCamTimer = "StartLowerFrakjawCam"; - const std::string SpawnCounterWeightTimer = "SpawnQB"; - const std::string SpawnRailTimer = "SpawnRailQB"; - const std::string SpawnLowerFrakjawTimer = "SpawnLowerFrakjaw"; + // Timers + const char TimerSplitChar = '+'; + const std::string WaitingForPlayersTimer = "WaitingForPlayers"; + const std::string SpawnWaveTimer = "SpawnWave"; + const std::string SpawnNextWaveTimer = "SpawnNextWave"; + const std::string UnstunTimer = "Unstun+"; + const std::string FrakjawSpawnInTimer = "LowerFrakjawSpawnIn+"; + const std::string WaveOverTimer = "WaveOverTimer"; + const std::string FightOverTimer = "FightOver"; + const std::string LowerFrakjawCamTimer = "StartLowerFrakjawCam"; + const std::string SpawnCounterWeightTimer = "SpawnQB"; + const std::string SpawnRailTimer = "SpawnRailQB"; + const std::string SpawnLowerFrakjawTimer = "SpawnLowerFrakjaw"; - // Groups - const std::string ChestSpawnpointGroup = "ChestSpawnPoint"; + // Groups + const std::string ChestSpawnpointGroup = "ChestSpawnPoint"; - // Spawner network names - const std::string LedgeFrakjawSpawner = "LedgeFrakjaw"; - const std::string LowerFrakjawSpawner = "LowerFrakjaw"; - const std::string BaseEnemiesSpawner = "EnemySpawnPoints_"; - const std::string CounterweightSpawner = "Counterweights"; - const std::string FireRailSpawner = "FireRailActivatorQB"; - const std::string ExtraRocks = "ExtraRocks"; + // Spawner network names + const std::string LedgeFrakjawSpawner = "LedgeFrakjaw"; + const std::string LowerFrakjawSpawner = "LowerFrakjaw"; + const std::string BaseEnemiesSpawner = "EnemySpawnPoints_"; + const std::string CounterweightSpawner = "Counterweights"; + const std::string FireRailSpawner = "FireRailActivatorQB"; + const std::string ExtraRocks = "ExtraRocks"; - // Cinematics - const std::string LedgeFrakSummon = "FrakjawSummoning"; - const std::string BaseCounterweightQB = "CounterweightQB"; - const std::string BaseCounterweightSpawn = "CWQBSpawn"; - const std::string BottomFrakSummon = "BottomFrakjawSummoning"; - const std::string BottomFrakSpawn = "BottomFrakjawSpawning"; - const std::string TreasureChestSpawning = "TreasureChestSpawning"; - const std::string FireRailSpawn = "RailQBSpawn"; + // Cinematics + const std::string LedgeFrakSummon = "FrakjawSummoning"; + const std::string BaseCounterweightQB = "CounterweightQB"; + const std::string BaseCounterweightSpawn = "CWQBSpawn"; + const std::string BottomFrakSummon = "BottomFrakjawSummoning"; + const std::string BottomFrakSpawn = "BottomFrakjawSpawning"; + const std::string TreasureChestSpawning = "TreasureChestSpawning"; + const std::string FireRailSpawn = "RailQBSpawn"; - // Notifications - const std::u16string StopMusicNotification = u"StopMusic"; - const std::u16string StartMusicNotification = u"StartMusic"; - const std::u16string FlashMusicNotification = u"FlashMusic"; - const std::u16string PlayCinematicNotification = u"PlayCinematic"; - const std::u16string EndCinematicNotification = u"EndCinematic"; + // Notifications + const std::u16string StopMusicNotification = u"StopMusic"; + const std::u16string StartMusicNotification = u"StartMusic"; + const std::u16string FlashMusicNotification = u"FlashMusic"; + const std::u16string PlayCinematicNotification = u"PlayCinematic"; + const std::u16string EndCinematicNotification = u"EndCinematic"; - // Animations - const std::u16string SummonAnimation = u"summon"; - const std::u16string TeleportOutAnimation = u"teleport-out"; - const std::u16string TeleportInAnimation = u"teleport-in"; - const std::u16string StunnedAnimation = u"stunned"; + // Animations + const std::u16string SummonAnimation = u"summon"; + const std::u16string TeleportOutAnimation = u"teleport-out"; + const std::u16string TeleportInAnimation = u"teleport-in"; + const std::u16string StunnedAnimation = u"stunned"; - // Audio cues - const std::string AudioWaveAudio = "Monastery_Frakjaw_Battle_"; - const std::string BattleOverAudio = "Monastery_Frakjaw_Battle_Win"; - const std::string CounterSmashAudio = "{d76d7b9d-9dc2-4e52-a315-69b25ef521ca}"; + // Audio cues + const std::string AudioWaveAudio = "Monastery_Frakjaw_Battle_"; + const std::string BattleOverAudio = "Monastery_Frakjaw_Battle_Win"; + const std::string CounterSmashAudio = "{d76d7b9d-9dc2-4e52-a315-69b25ef521ca}"; }; diff --git a/dScripts/NjNPCMissionSpinjitzuServer.cpp b/dScripts/NjNPCMissionSpinjitzuServer.cpp index 74b01617..19f5f42a 100644 --- a/dScripts/NjNPCMissionSpinjitzuServer.cpp +++ b/dScripts/NjNPCMissionSpinjitzuServer.cpp @@ -2,23 +2,23 @@ #include "Character.h" #include "EntityManager.h" -void NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, - MissionState missionState) { +void NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, + MissionState missionState) { - const auto& element = self->GetVar(ElementVariable); - if (missionID == ElementMissions.at(element) && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { + const auto& element = self->GetVar(ElementVariable); + if (missionID == ElementMissions.at(element) && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { - const auto targetID = target->GetObjectID(); + const auto targetID = target->GetObjectID(); - // Wait for an animation to complete and flag that the player has learned spinjitzu - self->AddCallbackTimer(5.0f, [targetID, element]() { - auto* target = EntityManager::Instance()->GetEntity(targetID); - if (target != nullptr) { - auto* character = target->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(ElementFlags.at(element), true); - } - } - }); - } + // Wait for an animation to complete and flag that the player has learned spinjitzu + self->AddCallbackTimer(5.0f, [targetID, element]() { + auto* target = EntityManager::Instance()->GetEntity(targetID); + if (target != nullptr) { + auto* character = target->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(ElementFlags.at(element), true); + } + } + }); + } } diff --git a/dScripts/NjNPCMissionSpinjitzuServer.h b/dScripts/NjNPCMissionSpinjitzuServer.h index 5b346ee7..8f25a86a 100644 --- a/dScripts/NjNPCMissionSpinjitzuServer.h +++ b/dScripts/NjNPCMissionSpinjitzuServer.h @@ -3,22 +3,22 @@ #include static std::map ElementFlags = { - {u"earth", ePlayerFlags::NJ_EARTH_SPINJITZU}, - {u"lightning", ePlayerFlags::NJ_LIGHTNING_SPINJITZU}, - {u"ice", ePlayerFlags::NJ_ICE_SPINJITZU}, - {u"fire", ePlayerFlags::NJ_FIRE_SPINJITZU} + {u"earth", ePlayerFlags::NJ_EARTH_SPINJITZU}, + {u"lightning", ePlayerFlags::NJ_LIGHTNING_SPINJITZU}, + {u"ice", ePlayerFlags::NJ_ICE_SPINJITZU}, + {u"fire", ePlayerFlags::NJ_FIRE_SPINJITZU} }; static std::map ElementMissions = { - {u"earth", 1796}, - {u"lightning", 1952}, - {u"ice", 1959}, - {u"fire", 1962}, + {u"earth", 1796}, + {u"lightning", 1952}, + {u"ice", 1959}, + {u"fire", 1962}, }; class NjNPCMissionSpinjitzuServer : public CppScripts::Script { public: - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; private: - const std::u16string ElementVariable = u"element"; + const std::u16string ElementVariable = u"element"; }; diff --git a/dScripts/NjNyaMissionitems.cpp b/dScripts/NjNyaMissionitems.cpp index 11ec74bd..4e5304d8 100644 --- a/dScripts/NjNyaMissionitems.cpp +++ b/dScripts/NjNyaMissionitems.cpp @@ -1,8 +1,8 @@ #include "NjNyaMissionitems.h" std::map> NjNyaMissionitems::GetSettings() { - return { - {1809, {{{14472}, true, false}}}, - {1821, {{{14500}, false, true}}} - }; + return { + {1809, {{{14472}, true, false}}}, + {1821, {{{14500}, false, true}}} + }; } diff --git a/dScripts/NjNyaMissionitems.h b/dScripts/NjNyaMissionitems.h index 5e2bbc7b..11b78ebd 100644 --- a/dScripts/NjNyaMissionitems.h +++ b/dScripts/NjNyaMissionitems.h @@ -4,5 +4,5 @@ #include class NjNyaMissionitems : public NPCAddRemoveItem { - std::map> GetSettings() override; + std::map> GetSettings() override; }; diff --git a/dScripts/NjRailActivatorsServer.cpp b/dScripts/NjRailActivatorsServer.cpp index 6c7e6ada..a07de24a 100644 --- a/dScripts/NjRailActivatorsServer.cpp +++ b/dScripts/NjRailActivatorsServer.cpp @@ -2,15 +2,15 @@ #include "RebuildComponent.h" #include "Character.h" -void NjRailActivatorsServer::OnUse(Entity *self, Entity *user) { - const auto flag = self->GetVar(u"RailFlagNum"); - auto* rebuildComponent = self->GetComponent(); +void NjRailActivatorsServer::OnUse(Entity* self, Entity* user) { + const auto flag = self->GetVar(u"RailFlagNum"); + auto* rebuildComponent = self->GetComponent(); - // Only allow use if this is not a quick build or the quick build is built - if (rebuildComponent == nullptr || rebuildComponent->GetState() == REBUILD_COMPLETED) { - auto* character = user->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(flag, true); - } - } + // Only allow use if this is not a quick build or the quick build is built + if (rebuildComponent == nullptr || rebuildComponent->GetState() == REBUILD_COMPLETED) { + auto* character = user->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(flag, true); + } + } } diff --git a/dScripts/NjRailActivatorsServer.h b/dScripts/NjRailActivatorsServer.h index 3e94f119..6f267705 100644 --- a/dScripts/NjRailActivatorsServer.h +++ b/dScripts/NjRailActivatorsServer.h @@ -2,5 +2,5 @@ #include "NjRailPostServer.h" class NjRailActivatorsServer : public NjRailPostServer { - void OnUse(Entity *self, Entity *user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/NjRailPostServer.cpp b/dScripts/NjRailPostServer.cpp index 097006c7..23389a98 100644 --- a/dScripts/NjRailPostServer.cpp +++ b/dScripts/NjRailPostServer.cpp @@ -2,50 +2,50 @@ #include "RebuildComponent.h" #include "EntityManager.h" -void NjRailPostServer::OnStartup(Entity *self) { - auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent != nullptr) { - self->SetNetworkVar(NetworkNotActiveVariable, true); - } +void NjRailPostServer::OnStartup(Entity* self) { + auto* rebuildComponent = self->GetComponent(); + if (rebuildComponent != nullptr) { + self->SetNetworkVar(NetworkNotActiveVariable, true); + } } -void NjRailPostServer::OnNotifyObject(Entity *self, Entity *sender, const std::string &name, int32_t param1, - int32_t param2) { - if (name == "PostRebuilt") { - self->SetNetworkVar(NetworkNotActiveVariable, false); - } else if (name == "PostDied") { - self->SetNetworkVar(NetworkNotActiveVariable, true); - } +void NjRailPostServer::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, + int32_t param2) { + if (name == "PostRebuilt") { + self->SetNetworkVar(NetworkNotActiveVariable, false); + } else if (name == "PostDied") { + self->SetNetworkVar(NetworkNotActiveVariable, true); + } } -void NjRailPostServer::OnRebuildNotifyState(Entity *self, eRebuildState state) { - if (state == REBUILD_COMPLETED) { - auto* relatedRail = GetRelatedRail(self); - if (relatedRail == nullptr) - return; +void NjRailPostServer::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == REBUILD_COMPLETED) { + auto* relatedRail = GetRelatedRail(self); + if (relatedRail == nullptr) + return; - relatedRail->NotifyObject(self, "PostRebuilt"); + relatedRail->NotifyObject(self, "PostRebuilt"); - if (self->GetVar(NotActiveVariable)) - return; + if (self->GetVar(NotActiveVariable)) + return; - self->SetNetworkVar(NetworkNotActiveVariable, false); - } else if (state == REBUILD_RESETTING) { - auto* relatedRail = GetRelatedRail(self); - if (relatedRail == nullptr) - return; + self->SetNetworkVar(NetworkNotActiveVariable, false); + } else if (state == REBUILD_RESETTING) { + auto* relatedRail = GetRelatedRail(self); + if (relatedRail == nullptr) + return; - relatedRail->NotifyObject(self, "PostDied"); - } + relatedRail->NotifyObject(self, "PostDied"); + } } -Entity *NjRailPostServer::GetRelatedRail(Entity* self) { - const auto& railGroup = self->GetVar(RailGroupVariable); - if (!railGroup.empty()) { - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(railGroup))) { - return entity; - } - } +Entity* NjRailPostServer::GetRelatedRail(Entity* self) { + const auto& railGroup = self->GetVar(RailGroupVariable); + if (!railGroup.empty()) { + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(railGroup))) { + return entity; + } + } - return nullptr; + return nullptr; } diff --git a/dScripts/NjRailPostServer.h b/dScripts/NjRailPostServer.h index 65a95733..3486db87 100644 --- a/dScripts/NjRailPostServer.h +++ b/dScripts/NjRailPostServer.h @@ -2,12 +2,12 @@ #include "CppScripts.h" class NjRailPostServer : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnNotifyObject(Entity *self, Entity *sender, const std::string &name, int32_t param1, int32_t param2) override; - void OnRebuildNotifyState(Entity *self, eRebuildState state) override; + void OnStartup(Entity* self) override; + void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) override; + void OnRebuildNotifyState(Entity* self, eRebuildState state) override; private: - Entity* GetRelatedRail(Entity* self); - const std::u16string NetworkNotActiveVariable = u"NetworkNotActive"; - const std::u16string NotActiveVariable = u"NotActive"; - const std::u16string RailGroupVariable = u"RailGroup"; + Entity* GetRelatedRail(Entity* self); + const std::u16string NetworkNotActiveVariable = u"NetworkNotActive"; + const std::u16string NotActiveVariable = u"NotActive"; + const std::u16string RailGroupVariable = u"RailGroup"; }; diff --git a/dScripts/NjRailSwitch.cpp b/dScripts/NjRailSwitch.cpp index 70a52a0e..e53445d9 100644 --- a/dScripts/NjRailSwitch.cpp +++ b/dScripts/NjRailSwitch.cpp @@ -1,12 +1,12 @@ #include "NjRailSwitch.h" #include "GameMessages.h" -void NjRailSwitch::OnUse(Entity *self, Entity *user) { -// const auto path = self->GetVar(u"rail_path"); -// const auto pathStart = self->GetVar(u"rail_path_start"); -// const auto pathGoForward = self->GetVar(u"rail_path_direction"); -// const auto cinematicName = self->GetVar(u"cinematic"); -// -// GameMessages::SendSetRailMovement(self->GetObjectID(), pathGoForward, path, pathStart, user->GetSystemAddress()); -// GameMessages::SendPlayCinematic(self->GetObjectID(), cinematicName, user->GetSystemAddress()); +void NjRailSwitch::OnUse(Entity* self, Entity* user) { + // const auto path = self->GetVar(u"rail_path"); + // const auto pathStart = self->GetVar(u"rail_path_start"); + // const auto pathGoForward = self->GetVar(u"rail_path_direction"); + // const auto cinematicName = self->GetVar(u"cinematic"); + // + // GameMessages::SendSetRailMovement(self->GetObjectID(), pathGoForward, path, pathStart, user->GetSystemAddress()); + // GameMessages::SendPlayCinematic(self->GetObjectID(), cinematicName, user->GetSystemAddress()); } diff --git a/dScripts/NjRailSwitch.h b/dScripts/NjRailSwitch.h index 453b9650..38ce2095 100644 --- a/dScripts/NjRailSwitch.h +++ b/dScripts/NjRailSwitch.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NjRailSwitch : public CppScripts::Script { - void OnUse(Entity *self, Entity *user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/NjScrollChestServer.cpp b/dScripts/NjScrollChestServer.cpp index b72f93cf..4e1350b4 100644 --- a/dScripts/NjScrollChestServer.cpp +++ b/dScripts/NjScrollChestServer.cpp @@ -1,17 +1,17 @@ #include "NjScrollChestServer.h" #include "InventoryComponent.h" -void NjScrollChestServer::OnUse(Entity *self, Entity *user) { - const auto keyLOT = self->GetVar(u"KeyNum"); - const auto rewardItemLOT = self->GetVar(u"openItemID"); +void NjScrollChestServer::OnUse(Entity* self, Entity* user) { + const auto keyLOT = self->GetVar(u"KeyNum"); + const auto rewardItemLOT = self->GetVar(u"openItemID"); - auto* playerInventory = user->GetComponent(); - if (playerInventory != nullptr && playerInventory->GetLotCount(keyLOT) == 1) { + auto* playerInventory = user->GetComponent(); + if (playerInventory != nullptr && playerInventory->GetLotCount(keyLOT) == 1) { - // Check for the key and remove - playerInventory->RemoveItem(keyLOT, 1); + // Check for the key and remove + playerInventory->RemoveItem(keyLOT, 1); - // Reward the player with the item set - playerInventory->AddItem(rewardItemLOT, 1, eLootSourceType::LOOT_SOURCE_NONE); - } + // Reward the player with the item set + playerInventory->AddItem(rewardItemLOT, 1, eLootSourceType::LOOT_SOURCE_NONE); + } } diff --git a/dScripts/NjScrollChestServer.h b/dScripts/NjScrollChestServer.h index c2891ab5..39a64473 100644 --- a/dScripts/NjScrollChestServer.h +++ b/dScripts/NjScrollChestServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NjScrollChestServer : public CppScripts::Script { - void OnUse(Entity *self, Entity *user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/NjWuNPC.cpp b/dScripts/NjWuNPC.cpp index 9c950e5c..855e4433 100644 --- a/dScripts/NjWuNPC.cpp +++ b/dScripts/NjWuNPC.cpp @@ -4,60 +4,60 @@ #include "EntityManager.h" #include "GameMessages.h" -void NjWuNPC::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { +void NjWuNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { - // The Dragon statue daily mission - if (missionID == m_MainDragonMissionID) { - auto* character = target->GetCharacter(); - auto* missionComponent = target->GetComponent(); - if (character == nullptr || missionComponent == nullptr) - return; + // The Dragon statue daily mission + if (missionID == m_MainDragonMissionID) { + auto* character = target->GetCharacter(); + auto* missionComponent = target->GetComponent(); + if (character == nullptr || missionComponent == nullptr) + return; - switch(missionState) { - case MissionState::MISSION_STATE_AVAILABLE: - case MissionState::MISSION_STATE_COMPLETE_AVAILABLE: - { - // Reset the sub missions - for (const auto& subMissionID : m_SubDragonMissionIDs) { - missionComponent->RemoveMission(subMissionID); - missionComponent->AcceptMission(subMissionID); - } + switch (missionState) { + case MissionState::MISSION_STATE_AVAILABLE: + case MissionState::MISSION_STATE_COMPLETE_AVAILABLE: + { + // Reset the sub missions + for (const auto& subMissionID : m_SubDragonMissionIDs) { + missionComponent->RemoveMission(subMissionID); + missionComponent->AcceptMission(subMissionID); + } - character->SetPlayerFlag(ePlayerFlags::NJ_WU_SHOW_DAILY_CHEST, false); + character->SetPlayerFlag(ePlayerFlags::NJ_WU_SHOW_DAILY_CHEST, false); - // Hide the chest - for (auto* chest : EntityManager::Instance()->GetEntitiesInGroup(m_DragonChestGroup)) { - GameMessages::SendNotifyClientObject(chest->GetObjectID(), m_ShowChestNotification, 0, -1, - target->GetObjectID(), "", target->GetSystemAddress()); - } + // Hide the chest + for (auto* chest : EntityManager::Instance()->GetEntitiesInGroup(m_DragonChestGroup)) { + GameMessages::SendNotifyClientObject(chest->GetObjectID(), m_ShowChestNotification, 0, -1, + target->GetObjectID(), "", target->GetSystemAddress()); + } - return; - } - case MissionState::MISSION_STATE_READY_TO_COMPLETE: - case MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE: - { - character->SetPlayerFlag(NJ_WU_SHOW_DAILY_CHEST, true); + return; + } + case MissionState::MISSION_STATE_READY_TO_COMPLETE: + case MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE: + { + character->SetPlayerFlag(NJ_WU_SHOW_DAILY_CHEST, true); - // Show the chest - for (auto* chest : EntityManager::Instance()->GetEntitiesInGroup(m_DragonChestGroup)) { - GameMessages::SendNotifyClientObject(chest->GetObjectID(), m_ShowChestNotification, 1, -1, - target->GetObjectID(), "", target->GetSystemAddress()); - } + // Show the chest + for (auto* chest : EntityManager::Instance()->GetEntitiesInGroup(m_DragonChestGroup)) { + GameMessages::SendNotifyClientObject(chest->GetObjectID(), m_ShowChestNotification, 1, -1, + target->GetObjectID(), "", target->GetSystemAddress()); + } - auto playerID = target->GetObjectID(); - self->AddCallbackTimer(5.0f, [this, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - return; + auto playerID = target->GetObjectID(); + self->AddCallbackTimer(5.0f, [this, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + return; - // Stop the dragon effects - for (auto* dragon : EntityManager::Instance()->GetEntitiesInGroup(m_DragonStatueGroup)) { - GameMessages::SendStopFXEffect(dragon, true, "on"); - } - }); - } - default: - return; - } - } + // Stop the dragon effects + for (auto* dragon : EntityManager::Instance()->GetEntitiesInGroup(m_DragonStatueGroup)) { + GameMessages::SendStopFXEffect(dragon, true, "on"); + } + }); + } + default: + return; + } + } } diff --git a/dScripts/NjWuNPC.h b/dScripts/NjWuNPC.h index 8ad6dbf3..d0cd750b 100644 --- a/dScripts/NjWuNPC.h +++ b/dScripts/NjWuNPC.h @@ -2,12 +2,12 @@ #include "AmTemplateSkillVolume.h" class NjWuNPC : public AmTemplateSkillVolume { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; - const uint32_t m_MainDragonMissionID = 2040; - const std::vector m_SubDragonMissionIDs = {2064, 2065, 2066, 2067}; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + const uint32_t m_MainDragonMissionID = 2040; + const std::vector m_SubDragonMissionIDs = { 2064, 2065, 2066, 2067 }; - // Groups and variables - const std::string m_DragonChestGroup = "DragonEmblemChest"; - const std::string m_DragonStatueGroup = "Minidragons"; - const std::u16string m_ShowChestNotification = u"showChest"; + // Groups and variables + const std::string m_DragonChestGroup = "DragonEmblemChest"; + const std::string m_DragonStatueGroup = "Minidragons"; + const std::u16string m_ShowChestNotification = u"showChest"; }; diff --git a/dScripts/NjhubLavaPlayerDeathTrigger.cpp b/dScripts/NjhubLavaPlayerDeathTrigger.cpp index af47f99b..c065f84a 100644 --- a/dScripts/NjhubLavaPlayerDeathTrigger.cpp +++ b/dScripts/NjhubLavaPlayerDeathTrigger.cpp @@ -1,10 +1,9 @@ #include "NjhubLavaPlayerDeathTrigger.h" #include "Entity.h" -void NjhubLavaPlayerDeathTrigger::OnCollisionPhantom(Entity *self, Entity *target) -{ - if (!target->IsPlayer()) - return; +void NjhubLavaPlayerDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) { + if (!target->IsPlayer()) + return; - target->Smash(self->GetObjectID(), VIOLENT, u"drown"); + target->Smash(self->GetObjectID(), VIOLENT, u"drown"); } diff --git a/dScripts/NjhubLavaPlayerDeathTrigger.h b/dScripts/NjhubLavaPlayerDeathTrigger.h index 48ff85d0..2cf0883f 100644 --- a/dScripts/NjhubLavaPlayerDeathTrigger.h +++ b/dScripts/NjhubLavaPlayerDeathTrigger.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NjhubLavaPlayerDeathTrigger : public CppScripts::Script { - void OnCollisionPhantom(Entity *self, Entity *target) override; + void OnCollisionPhantom(Entity* self, Entity* target) override; }; diff --git a/dScripts/NpcAgCourseStarter.cpp b/dScripts/NpcAgCourseStarter.cpp index 188186fb..503d966a 100644 --- a/dScripts/NpcAgCourseStarter.cpp +++ b/dScripts/NpcAgCourseStarter.cpp @@ -19,8 +19,7 @@ void NpcAgCourseStarter::OnUse(Entity* self, Entity* user) { if (scriptedActivityComponent->GetActivityPlayerData(user->GetObjectID()) != nullptr) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"exit", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); - } - else { + } else { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"start", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); } } @@ -40,8 +39,7 @@ void NpcAgCourseStarter::OnMessageBoxResponse(Entity* self, Entity* sender, int3 scriptedActivityComponent->RemoveActivityPlayerData(sender->GetObjectID()); EntityManager::Instance()->SerializeEntity(self); - } - else if (identifier == u"player_dialog_start_course" && button == 1) { + } else if (identifier == u"player_dialog_start_course" && button == 1) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"start_timer", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); GameMessages::SendActivityStart(self->GetObjectID(), sender->GetSystemAddress()); @@ -55,14 +53,12 @@ void NpcAgCourseStarter::OnMessageBoxResponse(Entity* self, Entity* sender, int3 data->values[1] = *(float*)&startTime; EntityManager::Instance()->SerializeEntity(self); - } - else if (identifier == u"FootRaceCancel") { + } else if (identifier == u"FootRaceCancel") { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stop_timer", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); if (scriptedActivityComponent->GetActivityPlayerData(sender->GetObjectID()) != nullptr) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"exit", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); - } - else { + } else { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"start", 0, 0, LWOOBJID_EMPTY, "", sender->GetSystemAddress()); } @@ -70,43 +66,43 @@ void NpcAgCourseStarter::OnMessageBoxResponse(Entity* self, Entity* sender, int3 } } -void NpcAgCourseStarter::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { +void NpcAgCourseStarter::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { auto* scriptedActivityComponent = self->GetComponent(); if (scriptedActivityComponent == nullptr) return; auto* data = scriptedActivityComponent->GetActivityPlayerData(sender->GetObjectID()); - if (data == nullptr) - return; + if (data == nullptr) + return; if (args == "course_cancel") { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"cancel_timer", 0, 0, - LWOOBJID_EMPTY, "", sender->GetSystemAddress()); - scriptedActivityComponent->RemoveActivityPlayerData(sender->GetObjectID()); + LWOOBJID_EMPTY, "", sender->GetSystemAddress()); + scriptedActivityComponent->RemoveActivityPlayerData(sender->GetObjectID()); } else if (args == "course_finish") { - time_t endTime = std::time(0); - time_t finish = (endTime - *(time_t *) &data->values[1]); + time_t endTime = std::time(0); + time_t finish = (endTime - *(time_t*)&data->values[1]); - data->values[2] = *(float *) &finish; + data->values[2] = *(float*)&finish; - auto *missionComponent = sender->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->ForceProgressTaskType(1884, 1, 1, false); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, -finish, self->GetObjectID(), - "performact_time"); - } + auto* missionComponent = sender->GetComponent(); + if (missionComponent != nullptr) { + missionComponent->ForceProgressTaskType(1884, 1, 1, false); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, -finish, self->GetObjectID(), + "performact_time"); + } - EntityManager::Instance()->SerializeEntity(self); - LeaderboardManager::SaveScore(sender->GetObjectID(), scriptedActivityComponent->GetActivityID(), - 0, (uint32_t) finish); + EntityManager::Instance()->SerializeEntity(self); + LeaderboardManager::SaveScore(sender->GetObjectID(), scriptedActivityComponent->GetActivityID(), + 0, (uint32_t)finish); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"ToggleLeaderBoard", - scriptedActivityComponent->GetActivityID(), 0, sender->GetObjectID(), - "", sender->GetSystemAddress()); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stop_timer", 1, finish, LWOOBJID_EMPTY, "", - sender->GetSystemAddress()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"ToggleLeaderBoard", + scriptedActivityComponent->GetActivityID(), 0, sender->GetObjectID(), + "", sender->GetSystemAddress()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stop_timer", 1, finish, LWOOBJID_EMPTY, "", + sender->GetSystemAddress()); - scriptedActivityComponent->RemoveActivityPlayerData(sender->GetObjectID()); + scriptedActivityComponent->RemoveActivityPlayerData(sender->GetObjectID()); } } diff --git a/dScripts/NpcAgCourseStarter.h b/dScripts/NpcAgCourseStarter.h index bc885a40..eda1fa93 100644 --- a/dScripts/NpcAgCourseStarter.h +++ b/dScripts/NpcAgCourseStarter.h @@ -8,6 +8,6 @@ class NpcAgCourseStarter : public CppScripts::Script { void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; -}; \ No newline at end of file + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; +}; diff --git a/dScripts/NpcCowboyServer.cpp b/dScripts/NpcCowboyServer.cpp index f4986045..c4940e4d 100644 --- a/dScripts/NpcCowboyServer.cpp +++ b/dScripts/NpcCowboyServer.cpp @@ -2,32 +2,25 @@ #include "MissionState.h" #include "InventoryComponent.h" -void NpcCowboyServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) -{ - if (missionID != 1880) - { - return; - } +void NpcCowboyServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + if (missionID != 1880) { + return; + } - auto* inventoryComponent = target->GetComponent(); + auto* inventoryComponent = target->GetComponent(); - if (inventoryComponent == nullptr) - { - return; - } + if (inventoryComponent == nullptr) { + return; + } - if (missionState == MissionState::MISSION_STATE_COMPLETE_ACTIVE|| - missionState == MissionState::MISSION_STATE_ACTIVE || - missionState == MissionState::MISSION_STATE_AVAILABLE || - missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) - { - if (inventoryComponent->GetLotCount(14378) == 0) - { - inventoryComponent->AddItem(14378, 1, eLootSourceType::LOOT_SOURCE_NONE); - } - } - else if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) - { - inventoryComponent->RemoveItem(14378, 1); - } + if (missionState == MissionState::MISSION_STATE_COMPLETE_ACTIVE || + missionState == MissionState::MISSION_STATE_ACTIVE || + missionState == MissionState::MISSION_STATE_AVAILABLE || + missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) { + if (inventoryComponent->GetLotCount(14378) == 0) { + inventoryComponent->AddItem(14378, 1, eLootSourceType::LOOT_SOURCE_NONE); + } + } else if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + inventoryComponent->RemoveItem(14378, 1); + } } diff --git a/dScripts/NpcNjAssistantServer.cpp b/dScripts/NpcNjAssistantServer.cpp index b9743756..a53d8ba3 100644 --- a/dScripts/NpcNjAssistantServer.cpp +++ b/dScripts/NpcNjAssistantServer.cpp @@ -9,9 +9,9 @@ void NpcNjAssistantServer::OnMissionDialogueOK(Entity* self, Entity* target, int if (missionState == MissionState::MISSION_STATE_COMPLETE || missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"switch", 0, 0, LWOOBJID_EMPTY, "", target->GetSystemAddress()); - + auto* inv = static_cast(target->GetComponent(COMPONENT_TYPE_INVENTORY)); - + // If we are ready to complete our missions, we take the kit from you: if (inv && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { auto* id = inv->FindItemByLot(14397); //the kit's lot @@ -20,8 +20,7 @@ void NpcNjAssistantServer::OnMissionDialogueOK(Entity* self, Entity* target, int inv->RemoveItem(id->GetLot(), id->GetCount()); } } - } - else if (missionState == MissionState::MISSION_STATE_AVAILABLE) { + } else if (missionState == MissionState::MISSION_STATE_AVAILABLE) { auto* missionComponent = static_cast(target->GetComponent(COMPONENT_TYPE_MISSION)); missionComponent->CompleteMission(mailAchievement, true); } diff --git a/dScripts/NpcNjAssistantServer.h b/dScripts/NpcNjAssistantServer.h index c8fac54c..7ba847d0 100644 --- a/dScripts/NpcNjAssistantServer.h +++ b/dScripts/NpcNjAssistantServer.h @@ -7,4 +7,4 @@ class NpcNjAssistantServer : public CppScripts::Script { private: int mailMission = 1728; //mission to get the item out of your mailbox int mailAchievement = 1729; // fun fact: spelled "Achivement" in the actual script -}; \ No newline at end of file +}; diff --git a/dScripts/NpcNpSpacemanBob.cpp b/dScripts/NpcNpSpacemanBob.cpp index 91fe0f95..5157e488 100644 --- a/dScripts/NpcNpSpacemanBob.cpp +++ b/dScripts/NpcNpSpacemanBob.cpp @@ -2,14 +2,12 @@ #include "DestroyableComponent.h" #include "MissionComponent.h" -void NpcNpSpacemanBob::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) -{ - if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE && missionID == 173) - { +void NpcNpSpacemanBob::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE && missionID == 173) { DestroyableComponent* destroyable = static_cast(target->GetComponent(COMPONENT_TYPE_DESTROYABLE)); destroyable->SetImagination(6); MissionComponent* mission = static_cast(target->GetComponent(COMPONENT_TYPE_MISSION)); - + mission->CompleteMission(664); } } diff --git a/dScripts/NpcPirateServer.cpp b/dScripts/NpcPirateServer.cpp index 04c62b47..47571fa6 100644 --- a/dScripts/NpcPirateServer.cpp +++ b/dScripts/NpcPirateServer.cpp @@ -1,17 +1,17 @@ #include "NpcPirateServer.h" #include "InventoryComponent.h" -void NpcPirateServer::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - auto* inventory = target->GetComponent(); - if (inventory != nullptr && missionID == 1881) { - auto* luckyShovel = inventory->FindItemByLot(14591); +void NpcPirateServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + auto* inventory = target->GetComponent(); + if (inventory != nullptr && missionID == 1881) { + auto* luckyShovel = inventory->FindItemByLot(14591); - // Add or remove the lucky shovel based on whether the mission was completed or started - if ((missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) - && luckyShovel == nullptr) { - inventory->AddItem(14591, 1, eLootSourceType::LOOT_SOURCE_NONE); - } else if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { - inventory->RemoveItem(14591, 1); - } - } + // Add or remove the lucky shovel based on whether the mission was completed or started + if ((missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) + && luckyShovel == nullptr) { + inventory->AddItem(14591, 1, eLootSourceType::LOOT_SOURCE_NONE); + } else if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + inventory->RemoveItem(14591, 1); + } + } } diff --git a/dScripts/NpcPirateServer.h b/dScripts/NpcPirateServer.h index 795356d6..dcb399c5 100644 --- a/dScripts/NpcPirateServer.h +++ b/dScripts/NpcPirateServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NpcPirateServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; }; diff --git a/dScripts/NpcWispServer.cpp b/dScripts/NpcWispServer.cpp index 0f573d65..cd4a4d9c 100644 --- a/dScripts/NpcWispServer.cpp +++ b/dScripts/NpcWispServer.cpp @@ -6,38 +6,38 @@ void NpcWispServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { if (missionID != 1849 && missionID != 1883) - return; + return; auto* inventory = target->GetComponent(); if (inventory == nullptr) - return; + return; LOT maelstromVacuumLot = 14592; auto* maelstromVacuum = inventory->FindItemByLot(maelstromVacuumLot); // For the daily we add the maelstrom vacuum if the player doesn't have it yet if (missionID == 1883 && (missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) - && maelstromVacuum == nullptr) { - inventory->AddItem(maelstromVacuumLot, 1, eLootSourceType::LOOT_SOURCE_NONE); + && maelstromVacuum == nullptr) { + inventory->AddItem(maelstromVacuumLot, 1, eLootSourceType::LOOT_SOURCE_NONE); } else if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { - inventory->RemoveItem(maelstromVacuumLot, 1); + inventory->RemoveItem(maelstromVacuumLot, 1); } // Next up hide or show the samples based on the mission state - auto visible = 1; - if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { - visible = 0; - } + auto visible = 1; + if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + visible = 0; + } - auto groups = missionID == 1849 - ? std::vector { "MaelstromSamples" } - : std::vector { "MaelstromSamples", "MaelstromSamples2ndary1", "MaelstromSamples2ndary2"}; + auto groups = missionID == 1849 + ? std::vector { "MaelstromSamples" } + : std::vector{ "MaelstromSamples", "MaelstromSamples2ndary1", "MaelstromSamples2ndary2" }; - for (const auto& group : groups) { - auto samples = EntityManager::Instance()->GetEntitiesInGroup(group); - for (auto* sample : samples) { - GameMessages::SendNotifyClientObject(sample->GetObjectID(), u"SetVisibility", visible, 0, - target->GetObjectID(), "", target->GetSystemAddress()); - } - } + for (const auto& group : groups) { + auto samples = EntityManager::Instance()->GetEntitiesInGroup(group); + for (auto* sample : samples) { + GameMessages::SendNotifyClientObject(sample->GetObjectID(), u"SetVisibility", visible, 0, + target->GetObjectID(), "", target->GetSystemAddress()); + } + } } diff --git a/dScripts/NpcWispServer.h b/dScripts/NpcWispServer.h index 133a9d8f..86c9c33d 100644 --- a/dScripts/NpcWispServer.h +++ b/dScripts/NpcWispServer.h @@ -3,4 +3,4 @@ class NpcWispServer : public CppScripts::Script { void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState); -}; \ No newline at end of file +}; diff --git a/dScripts/NsConcertChoiceBuild.cpp b/dScripts/NsConcertChoiceBuild.cpp index 8a93544c..af6389cd 100644 --- a/dScripts/NsConcertChoiceBuild.cpp +++ b/dScripts/NsConcertChoiceBuild.cpp @@ -1,4 +1,4 @@ #include "NsConcertChoiceBuild.h" -void NsConcertChoiceBuild::OnStartup(Entity *self) { +void NsConcertChoiceBuild::OnStartup(Entity* self) { } diff --git a/dScripts/NsConcertChoiceBuild.h b/dScripts/NsConcertChoiceBuild.h index 310a0677..74fdc9dc 100644 --- a/dScripts/NsConcertChoiceBuild.h +++ b/dScripts/NsConcertChoiceBuild.h @@ -3,5 +3,5 @@ class NsConcertChoiceBuild : public CppScripts::Script { public: - void OnStartup(Entity* self) override; -}; \ No newline at end of file + void OnStartup(Entity* self) override; +}; diff --git a/dScripts/NsConcertChoiceBuildManager.cpp b/dScripts/NsConcertChoiceBuildManager.cpp index 8875beed..33436525 100644 --- a/dScripts/NsConcertChoiceBuildManager.cpp +++ b/dScripts/NsConcertChoiceBuildManager.cpp @@ -1,64 +1,64 @@ #include "NsConcertChoiceBuildManager.h" #include "EntityManager.h" -const std::vector NsConcertChoiceBuildManager::crates { - { "laser", 11203, 5.0, "Concert_Laser_QB_" }, - { "rocket", 11204, 3.0, "Concert_Rocket_QB_" }, - { "speaker", 11205, 5.0, "Concert_Speaker_QB_" }, - { "spotlight", 11206, 5.0, "Concert_Spotlight_QB_" } +const std::vector NsConcertChoiceBuildManager::crates{ + { "laser", 11203, 5.0, "Concert_Laser_QB_" }, + { "rocket", 11204, 3.0, "Concert_Rocket_QB_" }, + { "speaker", 11205, 5.0, "Concert_Speaker_QB_" }, + { "spotlight", 11206, 5.0, "Concert_Spotlight_QB_" } }; -void NsConcertChoiceBuildManager::OnStartup(Entity *self) { - NsConcertChoiceBuildManager::SpawnCrate(self); +void NsConcertChoiceBuildManager::OnStartup(Entity* self) { + NsConcertChoiceBuildManager::SpawnCrate(self); } -void NsConcertChoiceBuildManager::SpawnCrate(Entity *self) { - const auto spawnNumber = self->GetVar(u"spawnNumber") % crates.size(); - const auto crate = crates[spawnNumber]; +void NsConcertChoiceBuildManager::SpawnCrate(Entity* self) { + const auto spawnNumber = self->GetVar(u"spawnNumber") % crates.size(); + const auto crate = crates[spawnNumber]; - const auto groups = self->GetGroups(); - if (groups.empty()) - return; + const auto groups = self->GetGroups(); + if (groups.empty()) + return; - // Groups are of the form CB_1, CB_2, etc. - auto group = groups.at(0); - const auto splitGroup = GeneralUtils::SplitString(group, '_'); - if (splitGroup.size() < 2) - return; - const auto groupNumber = std::stoi(splitGroup.at(1)); + // Groups are of the form CB_1, CB_2, etc. + auto group = groups.at(0); + const auto splitGroup = GeneralUtils::SplitString(group, '_'); + if (splitGroup.size() < 2) + return; + const auto groupNumber = std::stoi(splitGroup.at(1)); - EntityInfo info {}; - info.lot = crate.lot; - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.spawnerID = self->GetObjectID(); - info.settings = { - new LDFData(u"startsQBActivator", true), - new LDFData(u"grpNameQBShowBricks", crate.group + std::to_string(groupNumber)), - new LDFData(u"groupID", GeneralUtils::ASCIIToUTF16("Crate_" + group)), - new LDFData(u"crateTime", crate.time), - }; + EntityInfo info{}; + info.lot = crate.lot; + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.spawnerID = self->GetObjectID(); + info.settings = { + new LDFData(u"startsQBActivator", true), + new LDFData(u"grpNameQBShowBricks", crate.group + std::to_string(groupNumber)), + new LDFData(u"groupID", GeneralUtils::ASCIIToUTF16("Crate_" + group)), + new LDFData(u"crateTime", crate.time), + }; - auto* spawnedCrate = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(spawnedCrate); + auto* spawnedCrate = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(spawnedCrate); - spawnedCrate->AddDieCallback([self]() { - self->CancelAllTimers(); // Don't switch if the crate was smashed - self->SetVar(u"currentCrate", LWOOBJID_EMPTY); - }); + spawnedCrate->AddDieCallback([self]() { + self->CancelAllTimers(); // Don't switch if the crate was smashed + self->SetVar(u"currentCrate", LWOOBJID_EMPTY); + }); - self->SetVar(u"spawnNumber", spawnNumber + 1); - self->SetVar(u"currentTimer", crate.time); - self->SetVar(u"currentCrate", spawnedCrate->GetObjectID()); + self->SetVar(u"spawnNumber", spawnNumber + 1); + self->SetVar(u"currentTimer", crate.time); + self->SetVar(u"currentCrate", spawnedCrate->GetObjectID()); - // Timer that rotates the crates - self->AddCallbackTimer(crate.time, [self]() { - auto crateID = self->GetVar(u"currentCrate"); - if (crateID != LWOOBJID_EMPTY) { - EntityManager::Instance()->DestroyEntity(crateID); - self->SetVar(u"currentCrate", LWOOBJID_EMPTY); - } + // Timer that rotates the crates + self->AddCallbackTimer(crate.time, [self]() { + auto crateID = self->GetVar(u"currentCrate"); + if (crateID != LWOOBJID_EMPTY) { + EntityManager::Instance()->DestroyEntity(crateID); + self->SetVar(u"currentCrate", LWOOBJID_EMPTY); + } - SpawnCrate(self); - }); + SpawnCrate(self); + }); } diff --git a/dScripts/NsConcertChoiceBuildManager.h b/dScripts/NsConcertChoiceBuildManager.h index 25c7690b..4e9ac4ba 100644 --- a/dScripts/NsConcertChoiceBuildManager.h +++ b/dScripts/NsConcertChoiceBuildManager.h @@ -2,16 +2,16 @@ #include "CppScripts.h" struct Crate { - std::string name; - LOT lot; - float time; - std::string group; + std::string name; + LOT lot; + float time; + std::string group; }; class NsConcertChoiceBuildManager : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - static void SpawnCrate(Entity* self); + void OnStartup(Entity* self) override; + static void SpawnCrate(Entity* self); private: - static const std::vector crates; + static const std::vector crates; }; diff --git a/dScripts/NsConcertInstrument.cpp b/dScripts/NsConcertInstrument.cpp index a449a6a4..508b7b5b 100644 --- a/dScripts/NsConcertInstrument.cpp +++ b/dScripts/NsConcertInstrument.cpp @@ -9,350 +9,350 @@ // Constants are at the bottom -void NsConcertInstrument::OnStartup(Entity *self) { - self->SetVar(u"beingPlayed", false); - self->SetVar(u"activePlayer", LWOOBJID_EMPTY); - self->SetVar(u"oldItemLeft", LWOOBJID_EMPTY); - self->SetVar(u"oldItemRight", LWOOBJID_EMPTY); +void NsConcertInstrument::OnStartup(Entity* self) { + self->SetVar(u"beingPlayed", false); + self->SetVar(u"activePlayer", LWOOBJID_EMPTY); + self->SetVar(u"oldItemLeft", LWOOBJID_EMPTY); + self->SetVar(u"oldItemRight", LWOOBJID_EMPTY); } -void NsConcertInstrument::OnRebuildNotifyState(Entity *self, eRebuildState state) { - if (state == REBUILD_RESETTING || state == REBUILD_OPEN) { - self->SetVar(u"activePlayer", LWOOBJID_EMPTY); - } +void NsConcertInstrument::OnRebuildNotifyState(Entity* self, eRebuildState state) { + if (state == REBUILD_RESETTING || state == REBUILD_OPEN) { + self->SetVar(u"activePlayer", LWOOBJID_EMPTY); + } } -void NsConcertInstrument::OnRebuildComplete(Entity *self, Entity *target) { - if (!target->GetIsDead()) { - self->SetVar(u"activePlayer", target->GetObjectID()); +void NsConcertInstrument::OnRebuildComplete(Entity* self, Entity* target) { + if (!target->GetIsDead()) { + self->SetVar(u"activePlayer", target->GetObjectID()); - self->AddCallbackTimer(0.2f, [self, target]() { - RepositionPlayer(self, target); - if (hideInstrumentOnPlay.at(GetInstrumentLot(self))) - self->SetNetworkVar(u"Hide", true); - }); + self->AddCallbackTimer(0.2f, [self, target]() { + RepositionPlayer(self, target); + if (hideInstrumentOnPlay.at(GetInstrumentLot(self))) + self->SetNetworkVar(u"Hide", true); + }); - self->AddCallbackTimer(0.1f, [self, target]() { - StartPlayingInstrument(self, target); - }); - } + self->AddCallbackTimer(0.1f, [self, target]() { + StartPlayingInstrument(self, target); + }); + } } -void NsConcertInstrument::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { - if (args == "stopPlaying") { - const auto activePlayerID = self->GetVar(u"activePlayer"); - if (activePlayerID == LWOOBJID_EMPTY) - return; +void NsConcertInstrument::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (args == "stopPlaying") { + const auto activePlayerID = self->GetVar(u"activePlayer"); + if (activePlayerID == LWOOBJID_EMPTY) + return; - const auto activePlayer = EntityManager::Instance()->GetEntity(activePlayerID); - if (activePlayer == nullptr) - return; + const auto activePlayer = EntityManager::Instance()->GetEntity(activePlayerID); + if (activePlayer == nullptr) + return; - StopPlayingInstrument(self, activePlayer); - } + StopPlayingInstrument(self, activePlayer); + } } -void NsConcertInstrument::OnTimerDone(Entity *self, std::string name) { - const auto activePlayerID = self->GetVar(u"activePlayer"); - if (activePlayerID == LWOOBJID_EMPTY) - return; +void NsConcertInstrument::OnTimerDone(Entity* self, std::string name) { + const auto activePlayerID = self->GetVar(u"activePlayer"); + if (activePlayerID == LWOOBJID_EMPTY) + return; - // If for some reason the player becomes null (for example an unexpected leave), we need to clean up - const auto activePlayer = EntityManager::Instance()->GetEntity(activePlayerID); - if (activePlayer == nullptr && name != "cleanupAfterStop") { - StopPlayingInstrument(self, nullptr); - return; - } + // If for some reason the player becomes null (for example an unexpected leave), we need to clean up + const auto activePlayer = EntityManager::Instance()->GetEntity(activePlayerID); + if (activePlayer == nullptr && name != "cleanupAfterStop") { + StopPlayingInstrument(self, nullptr); + return; + } - if (activePlayer != nullptr && name == "checkPlayer" && self->GetVar(u"beingPlayed")) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"checkMovement", 0, 0, - activePlayer->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); - auto* stats = activePlayer->GetComponent(); - if (stats) { - if (stats->GetImagination() > 0) { - self->AddTimer("checkPlayer", updateFrequency); - } else { - StopPlayingInstrument(self, activePlayer); - } - } - } else if (activePlayer != nullptr && name == "deductImagination" && self->GetVar(u"beingPlayed")) { - auto* stats = activePlayer->GetComponent(); - if (stats) - stats->SetImagination(stats->GetImagination() - instrumentImaginationCost); + if (activePlayer != nullptr && name == "checkPlayer" && self->GetVar(u"beingPlayed")) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"checkMovement", 0, 0, + activePlayer->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + auto* stats = activePlayer->GetComponent(); + if (stats) { + if (stats->GetImagination() > 0) { + self->AddTimer("checkPlayer", updateFrequency); + } else { + StopPlayingInstrument(self, activePlayer); + } + } + } else if (activePlayer != nullptr && name == "deductImagination" && self->GetVar(u"beingPlayed")) { + auto* stats = activePlayer->GetComponent(); + if (stats) + stats->SetImagination(stats->GetImagination() - instrumentImaginationCost); - self->AddTimer("deductImagination", instrumentCostFrequency); - } else if (name == "cleanupAfterStop") { - if (activePlayer != nullptr) { - UnEquipInstruments(self, activePlayer); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stopPlaying", 0, 0, - activePlayer->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); - } + self->AddTimer("deductImagination", instrumentCostFrequency); + } else if (name == "cleanupAfterStop") { + if (activePlayer != nullptr) { + UnEquipInstruments(self, activePlayer); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stopPlaying", 0, 0, + activePlayer->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + } - auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent != nullptr) - rebuildComponent->ResetRebuild(false); + auto* rebuildComponent = self->GetComponent(); + if (rebuildComponent != nullptr) + rebuildComponent->ResetRebuild(false); - self->Smash(self->GetObjectID(), VIOLENT); - self->SetVar(u"activePlayer", LWOOBJID_EMPTY); - } else if (activePlayer != nullptr && name == "achievement") { - auto* missionComponent = activePlayer->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->ForceProgress(302, 462, self->GetLOT()); - } - self->AddTimer("achievement2", 10.0f); - } else if (activePlayer != nullptr && name == "achievement2") { - auto* missionComponent = activePlayer->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->ForceProgress(602, achievementTaskID.at(GetInstrumentLot(self)), self->GetLOT()); - } - } + self->Smash(self->GetObjectID(), VIOLENT); + self->SetVar(u"activePlayer", LWOOBJID_EMPTY); + } else if (activePlayer != nullptr && name == "achievement") { + auto* missionComponent = activePlayer->GetComponent(); + if (missionComponent != nullptr) { + missionComponent->ForceProgress(302, 462, self->GetLOT()); + } + self->AddTimer("achievement2", 10.0f); + } else if (activePlayer != nullptr && name == "achievement2") { + auto* missionComponent = activePlayer->GetComponent(); + if (missionComponent != nullptr) { + missionComponent->ForceProgress(602, achievementTaskID.at(GetInstrumentLot(self)), self->GetLOT()); + } + } } -void NsConcertInstrument::StartPlayingInstrument(Entity *self, Entity* player) { - const auto instrumentLot = GetInstrumentLot(self); - self->SetVar(u"beingPlayed", true); +void NsConcertInstrument::StartPlayingInstrument(Entity* self, Entity* player) { + const auto instrumentLot = GetInstrumentLot(self); + self->SetVar(u"beingPlayed", true); - // Stuff to notify the player - EquipInstruments(self, player); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"startPlaying", 0, 0, - player->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendPlayCinematic(player->GetObjectID(), cinematics.at(instrumentLot), UNASSIGNED_SYSTEM_ADDRESS); - self->AddCallbackTimer(1.0f, [player, instrumentLot]() { - GameMessages::SendPlayAnimation(player, animations.at(instrumentLot), 2.0f); - }); + // Stuff to notify the player + EquipInstruments(self, player); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"startPlaying", 0, 0, + player->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendPlayCinematic(player->GetObjectID(), cinematics.at(instrumentLot), UNASSIGNED_SYSTEM_ADDRESS); + self->AddCallbackTimer(1.0f, [player, instrumentLot]() { + GameMessages::SendPlayAnimation(player, animations.at(instrumentLot), 2.0f); + }); - for (auto* soundBox : EntityManager::Instance()->GetEntitiesInGroup("Audio-Concert")) { - auto* soundTrigger = soundBox->GetComponent(); - if (soundTrigger != nullptr) { - soundTrigger->ActivateMusicCue(music.at(instrumentLot)); - } - } + for (auto* soundBox : EntityManager::Instance()->GetEntitiesInGroup("Audio-Concert")) { + auto* soundTrigger = soundBox->GetComponent(); + if (soundTrigger != nullptr) { + soundTrigger->ActivateMusicCue(music.at(instrumentLot)); + } + } - // Add timers for deducting imagination and checking if the instruments can still be played - self->AddTimer("checkPlayer", updateFrequency); - self->AddTimer("deductImagination", instrumentCostFrequency); - self->AddTimer("achievement", 20.0f); + // Add timers for deducting imagination and checking if the instruments can still be played + self->AddTimer("checkPlayer", updateFrequency); + self->AddTimer("deductImagination", instrumentCostFrequency); + self->AddTimer("achievement", 20.0f); } -void NsConcertInstrument::StopPlayingInstrument(Entity *self, Entity* player) { - // No use in stopping twice - if (!self->GetVar(u"beingPlayed")) - return; +void NsConcertInstrument::StopPlayingInstrument(Entity* self, Entity* player) { + // No use in stopping twice + if (!self->GetVar(u"beingPlayed")) + return; - const auto instrumentLot = GetInstrumentLot(self); + const auto instrumentLot = GetInstrumentLot(self); - // Player might be null if they left - if (player != nullptr) { - auto* missions = player->GetComponent(); - if (missions != nullptr && missions->GetMissionState(176) == MissionState::MISSION_STATE_ACTIVE) { - missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } + // Player might be null if they left + if (player != nullptr) { + auto* missions = player->GetComponent(); + if (missions != nullptr && missions->GetMissionState(176) == MissionState::MISSION_STATE_ACTIVE) { + missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } - GameMessages::SendEndCinematic(player->GetObjectID(), cinematics.at(instrumentLot), UNASSIGNED_SYSTEM_ADDRESS, 1.0f); - GameMessages::SendPlayAnimation(player, smashAnimations.at(instrumentLot), 2.0f); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stopCheckingMovement", 0, 0, - player->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); - } + GameMessages::SendEndCinematic(player->GetObjectID(), cinematics.at(instrumentLot), UNASSIGNED_SYSTEM_ADDRESS, 1.0f); + GameMessages::SendPlayAnimation(player, smashAnimations.at(instrumentLot), 2.0f); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"stopCheckingMovement", 0, 0, + player->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + } - self->SetVar(u"beingPlayed", false); + self->SetVar(u"beingPlayed", false); - for (auto* soundBox : EntityManager::Instance()->GetEntitiesInGroup("Audio-Concert")) { - auto* soundTrigger = soundBox->GetComponent(); - if (soundTrigger != nullptr) { - soundTrigger->DeactivateMusicCue(music.at(instrumentLot)); - } - } + for (auto* soundBox : EntityManager::Instance()->GetEntitiesInGroup("Audio-Concert")) { + auto* soundTrigger = soundBox->GetComponent(); + if (soundTrigger != nullptr) { + soundTrigger->DeactivateMusicCue(music.at(instrumentLot)); + } + } - self->CancelAllTimers(); - self->AddTimer("cleanupAfterStop", instrumentSmashAnimationTime.at(instrumentLot)); + self->CancelAllTimers(); + self->AddTimer("cleanupAfterStop", instrumentSmashAnimationTime.at(instrumentLot)); } -void NsConcertInstrument::EquipInstruments(Entity *self, Entity *player) { - auto* inventory = player->GetComponent(); - if (inventory != nullptr) { - auto equippedItems = inventory->GetEquippedItems(); +void NsConcertInstrument::EquipInstruments(Entity* self, Entity* player) { + auto* inventory = player->GetComponent(); + if (inventory != nullptr) { + auto equippedItems = inventory->GetEquippedItems(); - // Un equip the current left item - const auto equippedLeftItem = equippedItems.find("special_l"); - if (equippedLeftItem != equippedItems.end()) { - auto* leftItem = inventory->FindItemById(equippedLeftItem->second.id); - if (leftItem != nullptr) { - leftItem->UnEquip(); - self->SetVar(u"oldItemLeft", leftItem->GetId()); - } - } + // Un equip the current left item + const auto equippedLeftItem = equippedItems.find("special_l"); + if (equippedLeftItem != equippedItems.end()) { + auto* leftItem = inventory->FindItemById(equippedLeftItem->second.id); + if (leftItem != nullptr) { + leftItem->UnEquip(); + self->SetVar(u"oldItemLeft", leftItem->GetId()); + } + } - // Un equip the current right item - const auto equippedRightItem = equippedItems.find("special_r"); - if (equippedRightItem != equippedItems.end()) { - auto* rightItem = inventory->FindItemById(equippedRightItem->second.id); - if (rightItem != nullptr) { - rightItem->UnEquip(); - self->SetVar(u"oldItemRight", rightItem->GetId()); - } - } + // Un equip the current right item + const auto equippedRightItem = equippedItems.find("special_r"); + if (equippedRightItem != equippedItems.end()) { + auto* rightItem = inventory->FindItemById(equippedRightItem->second.id); + if (rightItem != nullptr) { + rightItem->UnEquip(); + self->SetVar(u"oldItemRight", rightItem->GetId()); + } + } - // Equip the left hand instrument - const auto leftInstrumentLot = instrumentLotLeft.find(GetInstrumentLot(self))->second; - if (leftInstrumentLot != LOT_NULL) { - inventory->AddItem(leftInstrumentLot, 1, eLootSourceType::LOOT_SOURCE_NONE, TEMP_ITEMS, {}, LWOOBJID_EMPTY, false); - auto* leftInstrument = inventory->FindItemByLot(leftInstrumentLot, TEMP_ITEMS); - leftInstrument->Equip(); - } + // Equip the left hand instrument + const auto leftInstrumentLot = instrumentLotLeft.find(GetInstrumentLot(self))->second; + if (leftInstrumentLot != LOT_NULL) { + inventory->AddItem(leftInstrumentLot, 1, eLootSourceType::LOOT_SOURCE_NONE, TEMP_ITEMS, {}, LWOOBJID_EMPTY, false); + auto* leftInstrument = inventory->FindItemByLot(leftInstrumentLot, TEMP_ITEMS); + leftInstrument->Equip(); + } - // Equip the right hand instrument - const auto rightInstrumentLot = instrumentLotRight.find(GetInstrumentLot(self))->second; - if (rightInstrumentLot != LOT_NULL) { - inventory->AddItem(rightInstrumentLot, 1, eLootSourceType::LOOT_SOURCE_NONE, TEMP_ITEMS, {}, LWOOBJID_EMPTY, false); - auto* rightInstrument = inventory->FindItemByLot(rightInstrumentLot, TEMP_ITEMS); - rightInstrument->Equip(); - } - } + // Equip the right hand instrument + const auto rightInstrumentLot = instrumentLotRight.find(GetInstrumentLot(self))->second; + if (rightInstrumentLot != LOT_NULL) { + inventory->AddItem(rightInstrumentLot, 1, eLootSourceType::LOOT_SOURCE_NONE, TEMP_ITEMS, {}, LWOOBJID_EMPTY, false); + auto* rightInstrument = inventory->FindItemByLot(rightInstrumentLot, TEMP_ITEMS); + rightInstrument->Equip(); + } + } } -void NsConcertInstrument::UnEquipInstruments(Entity *self, Entity *player) { - auto* inventory = player->GetComponent(); - if (inventory != nullptr) { - auto equippedItems = inventory->GetEquippedItems(); +void NsConcertInstrument::UnEquipInstruments(Entity* self, Entity* player) { + auto* inventory = player->GetComponent(); + if (inventory != nullptr) { + auto equippedItems = inventory->GetEquippedItems(); - // Un equip the current left instrument - const auto equippedInstrumentLeft = equippedItems.find("special_l"); - if (equippedInstrumentLeft != equippedItems.end()) { - auto* leftItem = inventory->FindItemById(equippedInstrumentLeft->second.id); - if (leftItem != nullptr) { - leftItem->UnEquip(); - inventory->RemoveItem(leftItem->GetLot(), 1, TEMP_ITEMS); - } - } + // Un equip the current left instrument + const auto equippedInstrumentLeft = equippedItems.find("special_l"); + if (equippedInstrumentLeft != equippedItems.end()) { + auto* leftItem = inventory->FindItemById(equippedInstrumentLeft->second.id); + if (leftItem != nullptr) { + leftItem->UnEquip(); + inventory->RemoveItem(leftItem->GetLot(), 1, TEMP_ITEMS); + } + } - // Un equip the current right instrument - const auto equippedInstrumentRight = equippedItems.find("special_r"); - if (equippedInstrumentRight != equippedItems.end()) { - auto* rightItem = inventory->FindItemById(equippedInstrumentRight->second.id); - if (rightItem != nullptr) { - rightItem->UnEquip(); - inventory->RemoveItem(rightItem->GetLot(), 1, TEMP_ITEMS); - } - } + // Un equip the current right instrument + const auto equippedInstrumentRight = equippedItems.find("special_r"); + if (equippedInstrumentRight != equippedItems.end()) { + auto* rightItem = inventory->FindItemById(equippedInstrumentRight->second.id); + if (rightItem != nullptr) { + rightItem->UnEquip(); + inventory->RemoveItem(rightItem->GetLot(), 1, TEMP_ITEMS); + } + } - // Equip the old left hand item - const auto leftItemID = self->GetVar(u"oldItemLeft"); - if (leftItemID != LWOOBJID_EMPTY) { - auto* item = inventory->FindItemById(leftItemID); - if (item != nullptr) - item->Equip(); - self->SetVar(u"oldItemLeft", LWOOBJID_EMPTY); - } + // Equip the old left hand item + const auto leftItemID = self->GetVar(u"oldItemLeft"); + if (leftItemID != LWOOBJID_EMPTY) { + auto* item = inventory->FindItemById(leftItemID); + if (item != nullptr) + item->Equip(); + self->SetVar(u"oldItemLeft", LWOOBJID_EMPTY); + } - // Equip the old right hand item - const auto rightItemID = self->GetVar(u"oldItemRight"); - if (rightItemID != LWOOBJID_EMPTY) { - auto* item = inventory->FindItemById(rightItemID); - if (item != nullptr) - item->Equip(); - self->SetVar(u"oldItemRight", LWOOBJID_EMPTY); - } - } + // Equip the old right hand item + const auto rightItemID = self->GetVar(u"oldItemRight"); + if (rightItemID != LWOOBJID_EMPTY) { + auto* item = inventory->FindItemById(rightItemID); + if (item != nullptr) + item->Equip(); + self->SetVar(u"oldItemRight", LWOOBJID_EMPTY); + } + } } -void NsConcertInstrument::RepositionPlayer(Entity *self, Entity *player) { - auto position = self->GetPosition(); - auto rotation = self->GetRotation(); - position.SetY(0.0f); +void NsConcertInstrument::RepositionPlayer(Entity* self, Entity* player) { + auto position = self->GetPosition(); + auto rotation = self->GetRotation(); + position.SetY(0.0f); - switch (GetInstrumentLot(self)) { - case Bass: - case Guitar: - position.SetX(position.GetX() + 5.0f); - break; - case Keyboard: - position.SetX(position.GetX() - 0.45f); - position.SetZ(position.GetZ() + 0.75f); - rotation = NiQuaternion::CreateFromAxisAngle(position, -0.8f); // Slight rotation to make the animation sensible - break; - case Drum: - position.SetZ(position.GetZ() - 0.5f); - break; - } + switch (GetInstrumentLot(self)) { + case Bass: + case Guitar: + position.SetX(position.GetX() + 5.0f); + break; + case Keyboard: + position.SetX(position.GetX() - 0.45f); + position.SetZ(position.GetZ() + 0.75f); + rotation = NiQuaternion::CreateFromAxisAngle(position, -0.8f); // Slight rotation to make the animation sensible + break; + case Drum: + position.SetZ(position.GetZ() - 0.5f); + break; + } - GameMessages::SendTeleport(player->GetObjectID(), position, rotation, player->GetSystemAddress()); + GameMessages::SendTeleport(player->GetObjectID(), position, rotation, player->GetSystemAddress()); } -InstrumentLot NsConcertInstrument::GetInstrumentLot(Entity *self) { - return static_cast(self->GetLOT()); +InstrumentLot NsConcertInstrument::GetInstrumentLot(Entity* self) { + return static_cast(self->GetLOT()); } // Static stuff needed for script execution -const std::map NsConcertInstrument::animations { - { Guitar, u"guitar"}, - { Bass, u"bass"}, - { Keyboard, u"keyboard"}, - { Drum, u"drums"} +const std::map NsConcertInstrument::animations{ + { Guitar, u"guitar"}, + { Bass, u"bass"}, + { Keyboard, u"keyboard"}, + { Drum, u"drums"} }; -const std::map NsConcertInstrument::smashAnimations { - {Guitar, u"guitar-smash"}, - {Bass, u"bass-smash"}, - {Keyboard, u"keyboard-smash"}, - {Drum, u"keyboard-smash"} +const std::map NsConcertInstrument::smashAnimations{ + {Guitar, u"guitar-smash"}, + {Bass, u"bass-smash"}, + {Keyboard, u"keyboard-smash"}, + {Drum, u"keyboard-smash"} }; -const std::map NsConcertInstrument::instrumentSmashAnimationTime { - {Guitar, 2.167f}, - {Bass, 1.167f}, - {Keyboard, 1.0f}, - {Drum, 1.0f} +const std::map NsConcertInstrument::instrumentSmashAnimationTime{ + {Guitar, 2.167f}, + {Bass, 1.167f}, + {Keyboard, 1.0f}, + {Drum, 1.0f} }; -const std::map NsConcertInstrument::music { - {Guitar, "Concert_Guitar"}, - {Bass, "Concert_Bass"}, - {Keyboard, "Concert_Keys"}, - {Drum, "Concert_Drums"}, +const std::map NsConcertInstrument::music{ + {Guitar, "Concert_Guitar"}, + {Bass, "Concert_Bass"}, + {Keyboard, "Concert_Keys"}, + {Drum, "Concert_Drums"}, }; -const std::map NsConcertInstrument::cinematics { - {Guitar, u"Concert_Cam_G"}, - {Bass, u"Concert_Cam_B"}, - {Keyboard, u"Concert_Cam_K"}, - {Drum, u"Concert_Cam_D"}, +const std::map NsConcertInstrument::cinematics{ + {Guitar, u"Concert_Cam_G"}, + {Bass, u"Concert_Cam_B"}, + {Keyboard, u"Concert_Cam_K"}, + {Drum, u"Concert_Cam_D"}, }; -const std::map NsConcertInstrument::instrumentLotLeft { - {Guitar, 4991}, - {Bass, 4992}, - {Keyboard, LOT_NULL}, - {Drum, 4995}, +const std::map NsConcertInstrument::instrumentLotLeft{ + {Guitar, 4991}, + {Bass, 4992}, + {Keyboard, LOT_NULL}, + {Drum, 4995}, }; -const std::map NsConcertInstrument::instrumentLotRight { - {Guitar, LOT_NULL}, - {Bass, LOT_NULL}, - {Keyboard, LOT_NULL}, - {Drum, 4996}, +const std::map NsConcertInstrument::instrumentLotRight{ + {Guitar, LOT_NULL}, + {Bass, LOT_NULL}, + {Keyboard, LOT_NULL}, + {Drum, 4996}, }; -const std::map NsConcertInstrument::hideInstrumentOnPlay { - {Guitar, true}, - {Bass, true}, - {Keyboard, false}, - {Drum, false}, +const std::map NsConcertInstrument::hideInstrumentOnPlay{ + {Guitar, true}, + {Bass, true}, + {Keyboard, false}, + {Drum, false}, }; -const std::map NsConcertInstrument::instrumentEquipTime { - {Guitar, 1.033}, - {Bass, 0.75}, - {Keyboard, -1}, - {Drum, 0}, +const std::map NsConcertInstrument::instrumentEquipTime{ + {Guitar, 1.033}, + {Bass, 0.75}, + {Keyboard, -1}, + {Drum, 0}, }; -const std::map NsConcertInstrument::achievementTaskID { - {Guitar, 911}, - {Bass, 912}, - {Keyboard, 913}, - {Drum, 914}, +const std::map NsConcertInstrument::achievementTaskID{ + {Guitar, 911}, + {Bass, 912}, + {Keyboard, 913}, + {Drum, 914}, }; const uint32_t NsConcertInstrument::instrumentImaginationCost = 2; diff --git a/dScripts/NsConcertInstrument.h b/dScripts/NsConcertInstrument.h index bf59d886..87ccc419 100644 --- a/dScripts/NsConcertInstrument.h +++ b/dScripts/NsConcertInstrument.h @@ -2,90 +2,90 @@ #include "CppScripts.h" enum InstrumentLot { - Guitar = 4039, - Bass = 4040, - Keyboard = 4041, - Drum = 4042 + Guitar = 4039, + Bass = 4040, + Keyboard = 4041, + Drum = 4042 }; class NsConcertInstrument : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnRebuildNotifyState(Entity* self, eRebuildState state) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string name) override; + void OnStartup(Entity* self) override; + void OnRebuildNotifyState(Entity* self, eRebuildState state) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnTimerDone(Entity* self, std::string name) override; private: - static void StartPlayingInstrument(Entity* self, Entity* player); - static void StopPlayingInstrument(Entity* self, Entity* player); - static void EquipInstruments(Entity* self, Entity* player); - static void UnEquipInstruments(Entity* self, Entity* player); - static void RepositionPlayer(Entity* self, Entity* player); - static InstrumentLot GetInstrumentLot(Entity* self); + static void StartPlayingInstrument(Entity* self, Entity* player); + static void StopPlayingInstrument(Entity* self, Entity* player); + static void EquipInstruments(Entity* self, Entity* player); + static void UnEquipInstruments(Entity* self, Entity* player); + static void RepositionPlayer(Entity* self, Entity* player); + static InstrumentLot GetInstrumentLot(Entity* self); - /** - * Animations played when using an instrument - */ - static const std::map animations; + /** + * Animations played when using an instrument + */ + static const std::map animations; - /** - * Animation played when an instrument is smashed - */ - static const std::map smashAnimations; + /** + * Animation played when an instrument is smashed + */ + static const std::map smashAnimations; - /** - * Music to play while playing an instrument - */ - static const std::map music; + /** + * Music to play while playing an instrument + */ + static const std::map music; - /** - * Cinematics to play while playing an instrument - */ - static const std::map cinematics; + /** + * Cinematics to play while playing an instrument + */ + static const std::map cinematics; - /** - * Lot to equip in your left hand when playing an instrument - */ - static const std::map instrumentLotLeft; + /** + * Lot to equip in your left hand when playing an instrument + */ + static const std::map instrumentLotLeft; - /** - * Lot to play in your right hand when playing an instrument - */ - static const std::map instrumentLotRight; + /** + * Lot to play in your right hand when playing an instrument + */ + static const std::map instrumentLotRight; - /** - * Whether to hide the instrument or not when someone is playing it - */ - static const std::map hideInstrumentOnPlay; + /** + * Whether to hide the instrument or not when someone is playing it + */ + static const std::map hideInstrumentOnPlay; - /** - * How long to wait before unequipping the instrument if the instrument was smashed - */ - static const std::map instrumentEquipTime; + /** + * How long to wait before unequipping the instrument if the instrument was smashed + */ + static const std::map instrumentEquipTime; - /** - * How long the smash animation takes for each of the instruments - */ - static const std::map instrumentSmashAnimationTime; + /** + * How long the smash animation takes for each of the instruments + */ + static const std::map instrumentSmashAnimationTime; - /** - * Task ID of tasks of the Solo Artist 2 achievement - */ - static const std::map achievementTaskID; + /** + * Task ID of tasks of the Solo Artist 2 achievement + */ + static const std::map achievementTaskID; - /** - * How much imagination playing an instrument costs per interval - */ - static const uint32_t instrumentImaginationCost; + /** + * How much imagination playing an instrument costs per interval + */ + static const uint32_t instrumentImaginationCost; - /** - * The interval to deduct imagination at when playing an instrument - */ - static const float instrumentCostFrequency; + /** + * The interval to deduct imagination at when playing an instrument + */ + static const float instrumentCostFrequency; - /** - * The interval to check if the player still has enough imagination - */ - static const float updateFrequency; -}; \ No newline at end of file + /** + * The interval to check if the player still has enough imagination + */ + static const float updateFrequency; +}; diff --git a/dScripts/NsConcertQuickBuild.cpp b/dScripts/NsConcertQuickBuild.cpp index ba7b4010..fcec4dc7 100644 --- a/dScripts/NsConcertQuickBuild.cpp +++ b/dScripts/NsConcertQuickBuild.cpp @@ -10,215 +10,215 @@ const float NsConcertQuickBuild::resetTime = 40.0f; const float NsConcertQuickBuild::resetBlinkTime = 6.0f; const float NsConcertQuickBuild::resetStageTime = 66.5f; const float NsConcertQuickBuild::resetActivatorTime = 30.0f; -const std::map NsConcertQuickBuild::quickBuildSets { - {5846, QuickBuildSet {"laser", {"discoball", "discofloor", "stagelights", "spotlight"}}}, - {5847, QuickBuildSet {"spotlight", {"spotlight", "stagelights"}}}, - {5848, QuickBuildSet {"rocket", {"flamethrower"}}}, - {5845, QuickBuildSet {"speaker", {"speaker", "speakerHill", "stagelights", "spotlight"}}} +const std::map NsConcertQuickBuild::quickBuildSets{ + {5846, QuickBuildSet {"laser", {"discoball", "discofloor", "stagelights", "spotlight"}}}, + {5847, QuickBuildSet {"spotlight", {"spotlight", "stagelights"}}}, + {5848, QuickBuildSet {"rocket", {"flamethrower"}}}, + {5845, QuickBuildSet {"speaker", {"speaker", "speakerHill", "stagelights", "spotlight"}}} }; -const std::map NsConcertQuickBuild::quickBuildFX { - {"discoball", "effectsDiscoball"}, - {"speaker", "effectsShell"}, - {"speakerHill", "effectsHill"}, - {"spotlight", "effectsHill"}, - {"discofloor", "effectsShell"}, - {"flamethrower", "effectsShell"}, - {"stagelights", "effectsShell"} +const std::map NsConcertQuickBuild::quickBuildFX{ + {"discoball", "effectsDiscoball"}, + {"speaker", "effectsShell"}, + {"speakerHill", "effectsHill"}, + {"spotlight", "effectsHill"}, + {"discofloor", "effectsShell"}, + {"flamethrower", "effectsShell"}, + {"stagelights", "effectsShell"} }; std::vector NsConcertQuickBuild::finishedQuickBuilds = {}; -void NsConcertQuickBuild::OnStartup(Entity *self) { - const auto groups = self->GetGroups(); - if (groups.empty()) - return; +void NsConcertQuickBuild::OnStartup(Entity* self) { + const auto groups = self->GetGroups(); + if (groups.empty()) + return; - // Groups are of the form Concert_Laser_QB_1, Concert_Laser_QB_2, etc. - auto group = groups.at(0); - const auto splitGroup = GeneralUtils::SplitString(group, '_'); - if (splitGroup.size() < 4) - return; + // Groups are of the form Concert_Laser_QB_1, Concert_Laser_QB_2, etc. + auto group = groups.at(0); + const auto splitGroup = GeneralUtils::SplitString(group, '_'); + if (splitGroup.size() < 4) + return; - // Get the manager of the crate of this quick build - const auto groupNumber = std::stoi(splitGroup.at(3)); - const auto managerObjects = EntityManager::Instance()->GetEntitiesInGroup("CB_" + std::to_string(groupNumber)); - if (managerObjects.empty()) - return; + // Get the manager of the crate of this quick build + const auto groupNumber = std::stoi(splitGroup.at(3)); + const auto managerObjects = EntityManager::Instance()->GetEntitiesInGroup("CB_" + std::to_string(groupNumber)); + if (managerObjects.empty()) + return; - auto* managerObject = managerObjects.at(0); - self->SetVar(u"managerObject", managerObject->GetObjectID()); - self->SetVar(u"groupNumber", groupNumber); + auto* managerObject = managerObjects.at(0); + self->SetVar(u"managerObject", managerObject->GetObjectID()); + self->SetVar(u"groupNumber", groupNumber); - // Makes the quick build blink after a certain amount of time - self->AddCallbackTimer(GetBlinkTime(resetActivatorTime), [self]() { - self->SetNetworkVar(u"startEffect", NsConcertQuickBuild::GetBlinkTime(resetActivatorTime)); - }); + // Makes the quick build blink after a certain amount of time + self->AddCallbackTimer(GetBlinkTime(resetActivatorTime), [self]() { + self->SetNetworkVar(u"startEffect", NsConcertQuickBuild::GetBlinkTime(resetActivatorTime)); + }); - // Destroys the quick build after a while if it wasn't built - self->AddCallbackTimer(resetActivatorTime, [self]() { - self->SetNetworkVar(u"startEffect", -1.0f); - self->Smash(self->GetObjectID(), SILENT); - }); + // Destroys the quick build after a while if it wasn't built + self->AddCallbackTimer(resetActivatorTime, [self]() { + self->SetNetworkVar(u"startEffect", -1.0f); + self->Smash(self->GetObjectID(), SILENT); + }); } float NsConcertQuickBuild::GetBlinkTime(float time) { - return time <= NsConcertQuickBuild::resetBlinkTime ? 1.0f : time - NsConcertQuickBuild::resetBlinkTime; + return time <= NsConcertQuickBuild::resetBlinkTime ? 1.0f : time - NsConcertQuickBuild::resetBlinkTime; } -void NsConcertQuickBuild::OnDie(Entity *self, Entity *killer) { - auto* managerObject = EntityManager::Instance()->GetEntity(self->GetVar(u"managerObject")); - if (managerObject) { - managerObject->CancelAllTimers(); - managerObject->AddCallbackTimer(1.0f, [managerObject]() { - NsConcertChoiceBuildManager::SpawnCrate(managerObject); - }); - } +void NsConcertQuickBuild::OnDie(Entity* self, Entity* killer) { + auto* managerObject = EntityManager::Instance()->GetEntity(self->GetVar(u"managerObject")); + if (managerObject) { + managerObject->CancelAllTimers(); + managerObject->AddCallbackTimer(1.0f, [managerObject]() { + NsConcertChoiceBuildManager::SpawnCrate(managerObject); + }); + } - auto position = std::find(finishedQuickBuilds.begin(), finishedQuickBuilds.end(), self->GetObjectID()); - if (position != finishedQuickBuilds.end()) - finishedQuickBuilds.erase(position); + auto position = std::find(finishedQuickBuilds.begin(), finishedQuickBuilds.end(), self->GetObjectID()); + if (position != finishedQuickBuilds.end()) + finishedQuickBuilds.erase(position); } -void NsConcertQuickBuild::OnRebuildComplete(Entity *self, Entity *target) { - const auto groupNumber = self->GetVar(u"groupNumber"); - finishedQuickBuilds.push_back(self->GetObjectID()); - self->SetNetworkVar(u"startEffect", -1.0f); +void NsConcertQuickBuild::OnRebuildComplete(Entity* self, Entity* target) { + const auto groupNumber = self->GetVar(u"groupNumber"); + finishedQuickBuilds.push_back(self->GetObjectID()); + self->SetNetworkVar(u"startEffect", -1.0f); - ProgressStageCraft(self, target); + ProgressStageCraft(self, target); - // Find all the quick build objects of the same lot - auto finishedQuickBuildObjects = std::vector(); - for (auto quickBuildID : finishedQuickBuilds) { - const auto quickBuildObject = EntityManager::Instance()->GetEntity(quickBuildID); - if (quickBuildObject && quickBuildObject->GetLOT() == self->GetLOT()) { - quickBuildObject->SetVar(u"Player_" + (GeneralUtils::to_u16string(groupNumber)), target->GetObjectID()); - finishedQuickBuildObjects.push_back(quickBuildObject); - } - } + // Find all the quick build objects of the same lot + auto finishedQuickBuildObjects = std::vector(); + for (auto quickBuildID : finishedQuickBuilds) { + const auto quickBuildObject = EntityManager::Instance()->GetEntity(quickBuildID); + if (quickBuildObject && quickBuildObject->GetLOT() == self->GetLOT()) { + quickBuildObject->SetVar(u"Player_" + (GeneralUtils::to_u16string(groupNumber)), target->GetObjectID()); + finishedQuickBuildObjects.push_back(quickBuildObject); + } + } - // If all 4 sets were built, do cool stuff - if (finishedQuickBuildObjects.size() >= 4) { + // If all 4 sets were built, do cool stuff + if (finishedQuickBuildObjects.size() >= 4) { - // Move all the platforms so the user can collect the imagination brick - const auto movingPlatforms = EntityManager::Instance()->GetEntitiesInGroup("ConcertPlatforms"); - for (auto* movingPlatform : movingPlatforms) { - auto* component = movingPlatform->GetComponent(); - if (component) { - component->WarpToWaypoint(component->GetLastWaypointIndex()); + // Move all the platforms so the user can collect the imagination brick + const auto movingPlatforms = EntityManager::Instance()->GetEntitiesInGroup("ConcertPlatforms"); + for (auto* movingPlatform : movingPlatforms) { + auto* component = movingPlatform->GetComponent(); + if (component) { + component->WarpToWaypoint(component->GetLastWaypointIndex()); - movingPlatform->AddCallbackTimer(resetStageTime, [movingPlatform, component]() { - component->WarpToWaypoint(0); - }); - } - } + movingPlatform->AddCallbackTimer(resetStageTime, [movingPlatform, component]() { + component->WarpToWaypoint(0); + }); + } + } - ProgressLicensedTechnician(self); + ProgressLicensedTechnician(self); - // Reset all timers for the quickbuilds and make them indestructible - for (auto quickBuild : finishedQuickBuildObjects) { - quickBuild->SetNetworkVar(u"startEffect", -1.0f); - quickBuild->CancelAllTimers(); + // Reset all timers for the quickbuilds and make them indestructible + for (auto quickBuild : finishedQuickBuildObjects) { + quickBuild->SetNetworkVar(u"startEffect", -1.0f); + quickBuild->CancelAllTimers(); - // Indicate that the stage will reset - quickBuild->AddCallbackTimer(GetBlinkTime(resetStageTime), [quickBuild]() { - quickBuild->SetNetworkVar(u"startEffect", GetBlinkTime(resetTime)); - }); + // Indicate that the stage will reset + quickBuild->AddCallbackTimer(GetBlinkTime(resetStageTime), [quickBuild]() { + quickBuild->SetNetworkVar(u"startEffect", GetBlinkTime(resetTime)); + }); - // Reset the stage - quickBuild->AddCallbackTimer(resetStageTime, [quickBuild]() { - CancelEffects(quickBuild); - quickBuild->SetNetworkVar(u"startEffect", -1); - quickBuild->Smash(); - }); + // Reset the stage + quickBuild->AddCallbackTimer(resetStageTime, [quickBuild]() { + CancelEffects(quickBuild); + quickBuild->SetNetworkVar(u"startEffect", -1); + quickBuild->Smash(); + }); - auto* destroyableComponent = quickBuild->GetComponent(); - if (destroyableComponent) - destroyableComponent->SetFaction(-1); - } + auto* destroyableComponent = quickBuild->GetComponent(); + if (destroyableComponent) + destroyableComponent->SetFaction(-1); + } - UpdateEffects(self); - return; - } + UpdateEffects(self); + return; + } - // If not all 4 sets were built, reset the timers that were set on spawn - self->CancelAllTimers(); + // If not all 4 sets were built, reset the timers that were set on spawn + self->CancelAllTimers(); - // Makes the quick build blink after a certain amount of time - self->AddCallbackTimer(GetBlinkTime(resetTime), [self]() { - self->SetNetworkVar(u"startEffect", NsConcertQuickBuild::GetBlinkTime(resetActivatorTime)); - }); + // Makes the quick build blink after a certain amount of time + self->AddCallbackTimer(GetBlinkTime(resetTime), [self]() { + self->SetNetworkVar(u"startEffect", NsConcertQuickBuild::GetBlinkTime(resetActivatorTime)); + }); - // Destroys the quick build after a while if it wasn't built - self->AddCallbackTimer(resetTime, [self]() { - self->SetNetworkVar(u"startEffect", -1.0f); - self->Smash(self->GetObjectID()); - }); + // Destroys the quick build after a while if it wasn't built + self->AddCallbackTimer(resetTime, [self]() { + self->SetNetworkVar(u"startEffect", -1.0f); + self->Smash(self->GetObjectID()); + }); } -void NsConcertQuickBuild::ProgressStageCraft(Entity *self, Entity* player) { - auto* missionComponent = player->GetComponent(); - if (missionComponent) { +void NsConcertQuickBuild::ProgressStageCraft(Entity* self, Entity* player) { + auto* missionComponent = player->GetComponent(); + if (missionComponent) { - // Has to be forced as to not accidentally trigger the licensed technician achievement - switch(self->GetLOT()) { - case 5845: - missionComponent->ForceProgress(283, 432, 5845); - break; - case 5846: - missionComponent->ForceProgress(283, 433, 5846); - break; - case 5847: - missionComponent->ForceProgress(283, 434, 5847); - break; - case 5848: - missionComponent->ForceProgress(283, 435, 5848); - break; - default: - break; - } - } + // Has to be forced as to not accidentally trigger the licensed technician achievement + switch (self->GetLOT()) { + case 5845: + missionComponent->ForceProgress(283, 432, 5845); + break; + case 5846: + missionComponent->ForceProgress(283, 433, 5846); + break; + case 5847: + missionComponent->ForceProgress(283, 434, 5847); + break; + case 5848: + missionComponent->ForceProgress(283, 435, 5848); + break; + default: + break; + } + } } -void NsConcertQuickBuild::ProgressLicensedTechnician(Entity *self) { - for (auto i = 1; i < 5; i++) { - const auto playerID = self->GetVar(u"Player_" + (GeneralUtils::to_u16string(i))); - if (playerID != LWOOBJID_EMPTY) { - const auto player = EntityManager::Instance()->GetEntity(playerID); - if (player) { - auto playerMissionComponent = player->GetComponent(); - if (playerMissionComponent) - playerMissionComponent->ForceProgress(598, 903, self->GetLOT()); - } - } - } +void NsConcertQuickBuild::ProgressLicensedTechnician(Entity* self) { + for (auto i = 1; i < 5; i++) { + const auto playerID = self->GetVar(u"Player_" + (GeneralUtils::to_u16string(i))); + if (playerID != LWOOBJID_EMPTY) { + const auto player = EntityManager::Instance()->GetEntity(playerID); + if (player) { + auto playerMissionComponent = player->GetComponent(); + if (playerMissionComponent) + playerMissionComponent->ForceProgress(598, 903, self->GetLOT()); + } + } + } } -void NsConcertQuickBuild::UpdateEffects(Entity *self) { - CancelEffects(self); +void NsConcertQuickBuild::UpdateEffects(Entity* self) { + CancelEffects(self); - auto setIterator = quickBuildSets.find(self->GetLOT()); - if (setIterator == quickBuildSets.end()) - return; + auto setIterator = quickBuildSets.find(self->GetLOT()); + if (setIterator == quickBuildSets.end()) + return; - for (const auto& effectName : setIterator->second.effects) { - const auto effectObjects = EntityManager::Instance()->GetEntitiesInGroup(quickBuildFX.at(effectName)); - for (auto* effectObject : effectObjects) { - GameMessages::SendPlayFXEffect(effectObject, 0, GeneralUtils::ASCIIToUTF16(effectName), - effectName + "Effect", LWOOBJID_EMPTY, 1, 1, true); - } - } + for (const auto& effectName : setIterator->second.effects) { + const auto effectObjects = EntityManager::Instance()->GetEntitiesInGroup(quickBuildFX.at(effectName)); + for (auto* effectObject : effectObjects) { + GameMessages::SendPlayFXEffect(effectObject, 0, GeneralUtils::ASCIIToUTF16(effectName), + effectName + "Effect", LWOOBJID_EMPTY, 1, 1, true); + } + } } -void NsConcertQuickBuild::CancelEffects(Entity *self) { - auto setIterator = quickBuildSets.find(self->GetLOT()); - if (setIterator == quickBuildSets.end()) - return; +void NsConcertQuickBuild::CancelEffects(Entity* self) { + auto setIterator = quickBuildSets.find(self->GetLOT()); + if (setIterator == quickBuildSets.end()) + return; - for (const auto& effectName : setIterator->second.effects) { - const auto effectObjects = EntityManager::Instance()->GetEntitiesInGroup(quickBuildFX.at(effectName)); - for (auto* effectObject : effectObjects) { - GameMessages::SendStopFXEffect(effectObject, true, effectName + "Effect"); - } - } + for (const auto& effectName : setIterator->second.effects) { + const auto effectObjects = EntityManager::Instance()->GetEntitiesInGroup(quickBuildFX.at(effectName)); + for (auto* effectObject : effectObjects) { + GameMessages::SendStopFXEffect(effectObject, true, effectName + "Effect"); + } + } } diff --git a/dScripts/NsConcertQuickBuild.h b/dScripts/NsConcertQuickBuild.h index b3f6d702..667580f6 100644 --- a/dScripts/NsConcertQuickBuild.h +++ b/dScripts/NsConcertQuickBuild.h @@ -2,26 +2,26 @@ #include "CppScripts.h" struct QuickBuildSet { - std::string name; - std::vector effects; + std::string name; + std::vector effects; }; class NsConcertQuickBuild : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnDie(Entity* self, Entity* killer) override; + void OnStartup(Entity* self) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnDie(Entity* self, Entity* killer) override; private: - static std::vector finishedQuickBuilds; - static const float resetBlinkTime; - static const float resetStageTime; - static const float resetActivatorTime; - static const float resetTime; - static const std::map quickBuildFX; - static const std::map quickBuildSets; - static float GetBlinkTime(float time); - static void ProgressStageCraft(Entity* self, Entity* player); - static void ProgressLicensedTechnician(Entity* self); - static void UpdateEffects(Entity* self); - static void CancelEffects(Entity* self); + static std::vector finishedQuickBuilds; + static const float resetBlinkTime; + static const float resetStageTime; + static const float resetActivatorTime; + static const float resetTime; + static const std::map quickBuildFX; + static const std::map quickBuildSets; + static float GetBlinkTime(float time); + static void ProgressStageCraft(Entity* self, Entity* player); + static void ProgressLicensedTechnician(Entity* self); + static void UpdateEffects(Entity* self); + static void CancelEffects(Entity* self); }; diff --git a/dScripts/NsGetFactionMissionServer.cpp b/dScripts/NsGetFactionMissionServer.cpp index d4d03243..d759e3ad 100644 --- a/dScripts/NsGetFactionMissionServer.cpp +++ b/dScripts/NsGetFactionMissionServer.cpp @@ -3,8 +3,7 @@ #include "MissionComponent.h" #include "Character.h" -void NsGetFactionMissionServer::OnRespondToMission(Entity* self, int missionID, Entity* player, int reward) -{ +void NsGetFactionMissionServer::OnRespondToMission(Entity* self, int missionID, Entity* player, int reward) { if (missionID != 474) return; if (reward != LOT_NULL) { @@ -17,20 +16,17 @@ void NsGetFactionMissionServer::OnRespondToMission(Entity* self, int missionID, factionMissions = { 555, 556 }; celebrationID = 14; flagID = 46; - } - else if (reward == 6979) { + } else if (reward == 6979) { // Assembly factionMissions = { 544, 545 }; celebrationID = 15; flagID = 47; - } - else if (reward == 6981) { + } else if (reward == 6981) { // Paradox factionMissions = { 577, 578 }; celebrationID = 16; flagID = 48; - } - else if (reward == 6978) { + } else if (reward == 6978) { // Sentinel factionMissions = { 566, 567 }; celebrationID = 17; diff --git a/dScripts/NsJohnnyMissionServer.cpp b/dScripts/NsJohnnyMissionServer.cpp index 6fc73a82..2d9ae93c 100644 --- a/dScripts/NsJohnnyMissionServer.cpp +++ b/dScripts/NsJohnnyMissionServer.cpp @@ -1,14 +1,14 @@ #include "NsJohnnyMissionServer.h" #include "MissionComponent.h" -void NsJohnnyMissionServer::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - if (missionID == 773 && missionState <= MissionState::MISSION_STATE_ACTIVE) { - auto* missionComponent = target->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->AcceptMission(774); - missionComponent->AcceptMission(775); - missionComponent->AcceptMission(776); - missionComponent->AcceptMission(777); - } - } +void NsJohnnyMissionServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + if (missionID == 773 && missionState <= MissionState::MISSION_STATE_ACTIVE) { + auto* missionComponent = target->GetComponent(); + if (missionComponent != nullptr) { + missionComponent->AcceptMission(774); + missionComponent->AcceptMission(775); + missionComponent->AcceptMission(776); + missionComponent->AcceptMission(777); + } + } } diff --git a/dScripts/NsJohnnyMissionServer.h b/dScripts/NsJohnnyMissionServer.h index 920231da..8de39afa 100644 --- a/dScripts/NsJohnnyMissionServer.h +++ b/dScripts/NsJohnnyMissionServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NsJohnnyMissionServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; }; diff --git a/dScripts/NsLegoClubDoor.cpp b/dScripts/NsLegoClubDoor.cpp index 0a73c6d0..56a213b8 100644 --- a/dScripts/NsLegoClubDoor.cpp +++ b/dScripts/NsLegoClubDoor.cpp @@ -3,162 +3,150 @@ #include "GameMessages.h" #include "AMFFormat.h" -void NsLegoClubDoor::OnStartup(Entity* self) -{ - self->SetVar(u"currentZone", (int32_t) dZoneManager::Instance()->GetZoneID().GetMapID()); - self->SetVar(u"choiceZone", m_ChoiceZoneID); - self->SetVar(u"teleportAnim", m_TeleportAnim); - self->SetVar(u"teleportString", m_TeleportString); - self->SetVar(u"spawnPoint", m_SpawnPoint); +void NsLegoClubDoor::OnStartup(Entity* self) { + self->SetVar(u"currentZone", (int32_t)dZoneManager::Instance()->GetZoneID().GetMapID()); + self->SetVar(u"choiceZone", m_ChoiceZoneID); + self->SetVar(u"teleportAnim", m_TeleportAnim); + self->SetVar(u"teleportString", m_TeleportString); + self->SetVar(u"spawnPoint", m_SpawnPoint); - args = {}; + args = {}; - AMFStringValue* callbackClient = new AMFStringValue(); - callbackClient->SetStringValue(std::to_string(self->GetObjectID())); - args.InsertValue("callbackClient", callbackClient); + AMFStringValue* callbackClient = new AMFStringValue(); + callbackClient->SetStringValue(std::to_string(self->GetObjectID())); + args.InsertValue("callbackClient", callbackClient); - AMFStringValue* strIdentifier = new AMFStringValue(); - strIdentifier->SetStringValue("choiceDoor"); - args.InsertValue("strIdentifier", strIdentifier); + AMFStringValue* strIdentifier = new AMFStringValue(); + strIdentifier->SetStringValue("choiceDoor"); + args.InsertValue("strIdentifier", strIdentifier); - AMFStringValue* title = new AMFStringValue(); - title->SetStringValue("%[UI_CHOICE_DESTINATION]"); - args.InsertValue("title", title); + AMFStringValue* title = new AMFStringValue(); + title->SetStringValue("%[UI_CHOICE_DESTINATION]"); + args.InsertValue("title", title); - AMFArrayValue* choiceOptions = new AMFArrayValue(); + AMFArrayValue* choiceOptions = new AMFArrayValue(); - { - AMFArrayValue* nsArgs = new AMFArrayValue(); + { + AMFArrayValue* nsArgs = new AMFArrayValue(); - AMFStringValue* image = new AMFStringValue(); - image->SetStringValue("textures/ui/zone_thumnails/Nimbus_Station.dds"); - nsArgs->InsertValue("image", image); + AMFStringValue* image = new AMFStringValue(); + image->SetStringValue("textures/ui/zone_thumnails/Nimbus_Station.dds"); + nsArgs->InsertValue("image", image); - AMFStringValue* caption = new AMFStringValue(); - caption->SetStringValue("%[UI_CHOICE_NS]"); - nsArgs->InsertValue("caption", caption); + AMFStringValue* caption = new AMFStringValue(); + caption->SetStringValue("%[UI_CHOICE_NS]"); + nsArgs->InsertValue("caption", caption); - AMFStringValue* identifier = new AMFStringValue(); - identifier->SetStringValue("zoneID_1200"); - nsArgs->InsertValue("identifier", identifier); + AMFStringValue* identifier = new AMFStringValue(); + identifier->SetStringValue("zoneID_1200"); + nsArgs->InsertValue("identifier", identifier); - AMFStringValue* tooltipText = new AMFStringValue(); - tooltipText->SetStringValue("%[UI_CHOICE_NS_HOVER]"); - nsArgs->InsertValue("tooltipText", tooltipText); + AMFStringValue* tooltipText = new AMFStringValue(); + tooltipText->SetStringValue("%[UI_CHOICE_NS_HOVER]"); + nsArgs->InsertValue("tooltipText", tooltipText); - choiceOptions->PushBackValue(nsArgs); - } + choiceOptions->PushBackValue(nsArgs); + } - { - AMFArrayValue* ntArgs = new AMFArrayValue(); + { + AMFArrayValue* ntArgs = new AMFArrayValue(); - AMFStringValue* image = new AMFStringValue(); - image->SetStringValue("textures/ui/zone_thumnails/Nexus_Tower.dds"); - ntArgs->InsertValue("image", image); + AMFStringValue* image = new AMFStringValue(); + image->SetStringValue("textures/ui/zone_thumnails/Nexus_Tower.dds"); + ntArgs->InsertValue("image", image); - AMFStringValue* caption = new AMFStringValue(); - caption->SetStringValue("%[UI_CHOICE_NT]"); - ntArgs->InsertValue("caption", caption); + AMFStringValue* caption = new AMFStringValue(); + caption->SetStringValue("%[UI_CHOICE_NT]"); + ntArgs->InsertValue("caption", caption); - AMFStringValue* identifier = new AMFStringValue(); - identifier->SetStringValue("zoneID_1900"); - ntArgs->InsertValue("identifier", identifier); + AMFStringValue* identifier = new AMFStringValue(); + identifier->SetStringValue("zoneID_1900"); + ntArgs->InsertValue("identifier", identifier); - AMFStringValue* tooltipText = new AMFStringValue(); - tooltipText->SetStringValue("%[UI_CHOICE_NT_HOVER]"); - ntArgs->InsertValue("tooltipText", tooltipText); + AMFStringValue* tooltipText = new AMFStringValue(); + tooltipText->SetStringValue("%[UI_CHOICE_NT_HOVER]"); + ntArgs->InsertValue("tooltipText", tooltipText); - choiceOptions->PushBackValue(ntArgs); - } + choiceOptions->PushBackValue(ntArgs); + } - options = choiceOptions; + options = choiceOptions; - args.InsertValue("options", choiceOptions); + args.InsertValue("options", choiceOptions); } -void NsLegoClubDoor::OnUse(Entity* self, Entity* user) -{ - auto* player = user; +void NsLegoClubDoor::OnUse(Entity* self, Entity* user) { + auto* player = user; - if (CheckChoice(self, player)) - { - AMFArrayValue* multiArgs = new AMFArrayValue(); - - AMFStringValue* callbackClient = new AMFStringValue(); - callbackClient->SetStringValue(std::to_string(self->GetObjectID())); - multiArgs->InsertValue("callbackClient", callbackClient); + if (CheckChoice(self, player)) { + AMFArrayValue* multiArgs = new AMFArrayValue(); - AMFStringValue* strIdentifier = new AMFStringValue(); - strIdentifier->SetStringValue("choiceDoor"); - multiArgs->InsertValue("strIdentifier", strIdentifier); + AMFStringValue* callbackClient = new AMFStringValue(); + callbackClient->SetStringValue(std::to_string(self->GetObjectID())); + multiArgs->InsertValue("callbackClient", callbackClient); - AMFStringValue* title = new AMFStringValue(); - title->SetStringValue("%[UI_CHOICE_DESTINATION]"); - multiArgs->InsertValue("title", title); + AMFStringValue* strIdentifier = new AMFStringValue(); + strIdentifier->SetStringValue("choiceDoor"); + multiArgs->InsertValue("strIdentifier", strIdentifier); - multiArgs->InsertValue("options", options); + AMFStringValue* title = new AMFStringValue(); + title->SetStringValue("%[UI_CHOICE_DESTINATION]"); + multiArgs->InsertValue("title", title); - GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "QueueChoiceBox", multiArgs); - } - else if (self->GetVar(u"currentZone") != m_ChoiceZoneID) - { - AMFArrayValue* multiArgs = new AMFArrayValue(); + multiArgs->InsertValue("options", options); - AMFStringValue* state = new AMFStringValue(); - state->SetStringValue("Lobby"); - multiArgs->InsertValue("state", state); + GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "QueueChoiceBox", multiArgs); + } else if (self->GetVar(u"currentZone") != m_ChoiceZoneID) { + AMFArrayValue* multiArgs = new AMFArrayValue(); - AMFArrayValue* context = new AMFArrayValue(); + AMFStringValue* state = new AMFStringValue(); + state->SetStringValue("Lobby"); + multiArgs->InsertValue("state", state); - AMFStringValue* user = new AMFStringValue(); - user->SetStringValue(std::to_string(player->GetObjectID())); - context->InsertValue("user", user); + AMFArrayValue* context = new AMFArrayValue(); - AMFStringValue* callbackObj = new AMFStringValue(); - callbackObj->SetStringValue(std::to_string(self->GetObjectID())); - context->InsertValue("callbackObj", callbackObj); + AMFStringValue* user = new AMFStringValue(); + user->SetStringValue(std::to_string(player->GetObjectID())); + context->InsertValue("user", user); - AMFStringValue* helpVisible = new AMFStringValue(); - helpVisible->SetStringValue("show"); - context->InsertValue("HelpVisible", helpVisible); + AMFStringValue* callbackObj = new AMFStringValue(); + callbackObj->SetStringValue(std::to_string(self->GetObjectID())); + context->InsertValue("callbackObj", callbackObj); - AMFStringValue* type = new AMFStringValue(); - type->SetStringValue("Lego_Club_Valid"); - context->InsertValue("type", type); + AMFStringValue* helpVisible = new AMFStringValue(); + helpVisible->SetStringValue("show"); + context->InsertValue("HelpVisible", helpVisible); - multiArgs->InsertValue("context", context); + AMFStringValue* type = new AMFStringValue(); + type->SetStringValue("Lego_Club_Valid"); + context->InsertValue("type", type); - GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "pushGameState", multiArgs); - } - else - { - BaseOnUse(self, player); - } + multiArgs->InsertValue("context", context); + + GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "pushGameState", multiArgs); + } else { + BaseOnUse(self, player); + } } -void NsLegoClubDoor::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - std::u16string strIdentifier = identifier; +void NsLegoClubDoor::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + std::u16string strIdentifier = identifier; - if (strIdentifier == u"PlayButton" || strIdentifier == u"CloseButton") - { - strIdentifier = u"TransferBox"; - } + if (strIdentifier == u"PlayButton" || strIdentifier == u"CloseButton") { + strIdentifier = u"TransferBox"; + } - BaseOnMessageBoxResponse(self, sender, button, strIdentifier, userData); + BaseOnMessageBoxResponse(self, sender, button, strIdentifier, userData); } -void NsLegoClubDoor::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) -{ - BaseChoiceBoxRespond(self, sender, button, buttonIdentifier, identifier); +void NsLegoClubDoor::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { + BaseChoiceBoxRespond(self, sender, button, buttonIdentifier, identifier); } -void NsLegoClubDoor::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void NsLegoClubDoor::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } -void NsLegoClubDoor::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); +void NsLegoClubDoor::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); } diff --git a/dScripts/NsLegoClubDoor.h b/dScripts/NsLegoClubDoor.h index 7f17692d..0a7a6ee0 100644 --- a/dScripts/NsLegoClubDoor.h +++ b/dScripts/NsLegoClubDoor.h @@ -6,18 +6,18 @@ class NsLegoClubDoor : public CppScripts::Script, ChooseYourDestinationNsToNt, BaseConsoleTeleportServer { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; - void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; + void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; private: - int32_t m_ChoiceZoneID = 1700; - std::string m_SpawnPoint = "NS_LEGO_Club"; - std::u16string m_TeleportAnim = u"lup-teleport"; - std::u16string m_TeleportString = u"ROCKET_TOOLTIP_USE_THE_GATEWAY_TO_TRAVEL_TO_LUP_WORLD"; - AMFArrayValue args = {}; - AMFArrayValue* options = {}; + int32_t m_ChoiceZoneID = 1700; + std::string m_SpawnPoint = "NS_LEGO_Club"; + std::u16string m_TeleportAnim = u"lup-teleport"; + std::u16string m_TeleportString = u"ROCKET_TOOLTIP_USE_THE_GATEWAY_TO_TRAVEL_TO_LUP_WORLD"; + AMFArrayValue args = {}; + AMFArrayValue* options = {}; }; diff --git a/dScripts/NsLupTeleport.cpp b/dScripts/NsLupTeleport.cpp index 4c196d01..9cd4359b 100644 --- a/dScripts/NsLupTeleport.cpp +++ b/dScripts/NsLupTeleport.cpp @@ -3,107 +3,98 @@ #include "GameMessages.h" #include "AMFFormat.h" -void NsLupTeleport::OnStartup(Entity* self) -{ - self->SetVar(u"currentZone", (int32_t) dZoneManager::Instance()->GetZoneID().GetMapID()); - self->SetVar(u"choiceZone", m_ChoiceZoneID); - self->SetVar(u"teleportAnim", m_TeleportAnim); - self->SetVar(u"teleportString", m_TeleportString); - self->SetVar(u"spawnPoint", m_SpawnPoint); +void NsLupTeleport::OnStartup(Entity* self) { + self->SetVar(u"currentZone", (int32_t)dZoneManager::Instance()->GetZoneID().GetMapID()); + self->SetVar(u"choiceZone", m_ChoiceZoneID); + self->SetVar(u"teleportAnim", m_TeleportAnim); + self->SetVar(u"teleportString", m_TeleportString); + self->SetVar(u"spawnPoint", m_SpawnPoint); - args = {}; + args = {}; - AMFStringValue* callbackClient = new AMFStringValue(); - callbackClient->SetStringValue(std::to_string(self->GetObjectID())); - args.InsertValue("callbackClient", callbackClient); + AMFStringValue* callbackClient = new AMFStringValue(); + callbackClient->SetStringValue(std::to_string(self->GetObjectID())); + args.InsertValue("callbackClient", callbackClient); - AMFStringValue* strIdentifier = new AMFStringValue(); - strIdentifier->SetStringValue("choiceDoor"); - args.InsertValue("strIdentifier", strIdentifier); + AMFStringValue* strIdentifier = new AMFStringValue(); + strIdentifier->SetStringValue("choiceDoor"); + args.InsertValue("strIdentifier", strIdentifier); - AMFStringValue* title = new AMFStringValue(); - title->SetStringValue("%[UI_CHOICE_DESTINATION]"); - args.InsertValue("title", title); + AMFStringValue* title = new AMFStringValue(); + title->SetStringValue("%[UI_CHOICE_DESTINATION]"); + args.InsertValue("title", title); - AMFArrayValue* choiceOptions = new AMFArrayValue(); + AMFArrayValue* choiceOptions = new AMFArrayValue(); - { - AMFArrayValue* nsArgs = new AMFArrayValue(); + { + AMFArrayValue* nsArgs = new AMFArrayValue(); - AMFStringValue* image = new AMFStringValue(); - image->SetStringValue("textures/ui/zone_thumnails/Nimbus_Station.dds"); - nsArgs->InsertValue("image", image); + AMFStringValue* image = new AMFStringValue(); + image->SetStringValue("textures/ui/zone_thumnails/Nimbus_Station.dds"); + nsArgs->InsertValue("image", image); - AMFStringValue* caption = new AMFStringValue(); - caption->SetStringValue("%[UI_CHOICE_NS]"); - nsArgs->InsertValue("caption", caption); + AMFStringValue* caption = new AMFStringValue(); + caption->SetStringValue("%[UI_CHOICE_NS]"); + nsArgs->InsertValue("caption", caption); - AMFStringValue* identifier = new AMFStringValue(); - identifier->SetStringValue("zoneID_1200"); - nsArgs->InsertValue("identifier", identifier); + AMFStringValue* identifier = new AMFStringValue(); + identifier->SetStringValue("zoneID_1200"); + nsArgs->InsertValue("identifier", identifier); - AMFStringValue* tooltipText = new AMFStringValue(); - tooltipText->SetStringValue("%[UI_CHOICE_NS_HOVER]"); - nsArgs->InsertValue("tooltipText", tooltipText); + AMFStringValue* tooltipText = new AMFStringValue(); + tooltipText->SetStringValue("%[UI_CHOICE_NS_HOVER]"); + nsArgs->InsertValue("tooltipText", tooltipText); - choiceOptions->PushBackValue(nsArgs); - } + choiceOptions->PushBackValue(nsArgs); + } - { - AMFArrayValue* ntArgs = new AMFArrayValue(); + { + AMFArrayValue* ntArgs = new AMFArrayValue(); - AMFStringValue* image = new AMFStringValue(); - image->SetStringValue("textures/ui/zone_thumnails/Nexus_Tower.dds"); - ntArgs->InsertValue("image", image); + AMFStringValue* image = new AMFStringValue(); + image->SetStringValue("textures/ui/zone_thumnails/Nexus_Tower.dds"); + ntArgs->InsertValue("image", image); - AMFStringValue* caption = new AMFStringValue(); - caption->SetStringValue("%[UI_CHOICE_NT]"); - ntArgs->InsertValue("caption", caption); + AMFStringValue* caption = new AMFStringValue(); + caption->SetStringValue("%[UI_CHOICE_NT]"); + ntArgs->InsertValue("caption", caption); - AMFStringValue* identifier = new AMFStringValue(); - identifier->SetStringValue("zoneID_1900"); - ntArgs->InsertValue("identifier", identifier); + AMFStringValue* identifier = new AMFStringValue(); + identifier->SetStringValue("zoneID_1900"); + ntArgs->InsertValue("identifier", identifier); - AMFStringValue* tooltipText = new AMFStringValue(); - tooltipText->SetStringValue("%[UI_CHOICE_NT_HOVER]"); - ntArgs->InsertValue("tooltipText", tooltipText); + AMFStringValue* tooltipText = new AMFStringValue(); + tooltipText->SetStringValue("%[UI_CHOICE_NT_HOVER]"); + ntArgs->InsertValue("tooltipText", tooltipText); - choiceOptions->PushBackValue(ntArgs); - } + choiceOptions->PushBackValue(ntArgs); + } - args.InsertValue("options", choiceOptions); + args.InsertValue("options", choiceOptions); } -void NsLupTeleport::OnUse(Entity* self, Entity* user) -{ - auto* player = user; +void NsLupTeleport::OnUse(Entity* self, Entity* user) { + auto* player = user; - if (CheckChoice(self, player)) - { - GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "QueueChoiceBox", &args); - } - else - { - BaseOnUse(self, player); - } + if (CheckChoice(self, player)) { + GameMessages::SendUIMessageServerToSingleClient(player, player->GetSystemAddress(), "QueueChoiceBox", &args); + } else { + BaseOnUse(self, player); + } } -void NsLupTeleport::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - BaseOnMessageBoxResponse(self, sender, button, identifier, userData); +void NsLupTeleport::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + BaseOnMessageBoxResponse(self, sender, button, identifier, userData); } -void NsLupTeleport::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) -{ - BaseChoiceBoxRespond(self, sender, button, buttonIdentifier, identifier); +void NsLupTeleport::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { + BaseChoiceBoxRespond(self, sender, button, buttonIdentifier, identifier); } -void NsLupTeleport::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void NsLupTeleport::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } -void NsLupTeleport::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); +void NsLupTeleport::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); } diff --git a/dScripts/NsLupTeleport.h b/dScripts/NsLupTeleport.h index 833f5f0a..35edf0bc 100644 --- a/dScripts/NsLupTeleport.h +++ b/dScripts/NsLupTeleport.h @@ -6,17 +6,17 @@ class NsLupTeleport : public CppScripts::Script, ChooseYourDestinationNsToNt, BaseConsoleTeleportServer { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; - void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; + void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; private: - int32_t m_ChoiceZoneID = 1600; - std::string m_SpawnPoint = "NS_LW"; - std::u16string m_TeleportAnim = u"lup-teleport"; - std::u16string m_TeleportString = u"UI_TRAVEL_TO_LUP_STATION"; - AMFArrayValue args = {}; + int32_t m_ChoiceZoneID = 1600; + std::string m_SpawnPoint = "NS_LW"; + std::u16string m_TeleportAnim = u"lup-teleport"; + std::u16string m_TeleportString = u"UI_TRAVEL_TO_LUP_STATION"; + AMFArrayValue args = {}; }; diff --git a/dScripts/NsQbImaginationStatue.cpp b/dScripts/NsQbImaginationStatue.cpp index 4404ba5f..a2e335b7 100644 --- a/dScripts/NsQbImaginationStatue.cpp +++ b/dScripts/NsQbImaginationStatue.cpp @@ -2,46 +2,39 @@ #include "EntityManager.h" #include "GameMessages.h" -void NsQbImaginationStatue::OnStartup(Entity* self) -{ - +void NsQbImaginationStatue::OnStartup(Entity* self) { + } -void NsQbImaginationStatue::OnRebuildComplete(Entity* self, Entity* target) -{ - if (target == nullptr) return; +void NsQbImaginationStatue::OnRebuildComplete(Entity* self, Entity* target) { + if (target == nullptr) return; - self->SetVar(u"Player", target->GetObjectID()); + self->SetVar(u"Player", target->GetObjectID()); - SpawnLoot(self); - - self->AddTimer("SpawnDelay", 1.5f); + SpawnLoot(self); - self->AddTimer("StopSpawner", 10.0f); + self->AddTimer("SpawnDelay", 1.5f); + + self->AddTimer("StopSpawner", 10.0f); } -void NsQbImaginationStatue::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "SpawnDelay") - { - SpawnLoot(self); +void NsQbImaginationStatue::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "SpawnDelay") { + SpawnLoot(self); - self->AddTimer("SpawnDelay", 1.5f); - } - else if (timerName == "StopSpawner") - { - self->CancelAllTimers(); - } + self->AddTimer("SpawnDelay", 1.5f); + } else if (timerName == "StopSpawner") { + self->CancelAllTimers(); + } } -void NsQbImaginationStatue::SpawnLoot(Entity* self) -{ - const auto playerId = self->GetVar(u"Player"); +void NsQbImaginationStatue::SpawnLoot(Entity* self) { + const auto playerId = self->GetVar(u"Player"); - auto* player = EntityManager::Instance()->GetEntity(playerId); + auto* player = EntityManager::Instance()->GetEntity(playerId); - if (player == nullptr) return; - - GameMessages::SendDropClientLoot(player, self->GetObjectID(), 935, 0); - GameMessages::SendDropClientLoot(player, self->GetObjectID(), 935, 0); + if (player == nullptr) return; + + GameMessages::SendDropClientLoot(player, self->GetObjectID(), 935, 0); + GameMessages::SendDropClientLoot(player, self->GetObjectID(), 935, 0); } diff --git a/dScripts/NsQbImaginationStatue.h b/dScripts/NsQbImaginationStatue.h index 3d699ac9..b7a78c32 100644 --- a/dScripts/NsQbImaginationStatue.h +++ b/dScripts/NsQbImaginationStatue.h @@ -5,7 +5,7 @@ class NsQbImaginationStatue : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void SpawnLoot(Entity* self); + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void SpawnLoot(Entity* self); }; diff --git a/dScripts/NsTokenConsoleServer.cpp b/dScripts/NsTokenConsoleServer.cpp index 976b9bc8..a62c165c 100644 --- a/dScripts/NsTokenConsoleServer.cpp +++ b/dScripts/NsTokenConsoleServer.cpp @@ -5,71 +5,57 @@ #include "MissionComponent.h" #include "RebuildComponent.h" -void NsTokenConsoleServer::OnStartup(Entity* self) -{ - +void NsTokenConsoleServer::OnStartup(Entity* self) { + } -void NsTokenConsoleServer::OnUse(Entity* self, Entity* user) -{ - auto* rebuildComponent = self->GetComponent(); +void NsTokenConsoleServer::OnUse(Entity* self, Entity* user) { + auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent == nullptr) - { - return; - } + if (rebuildComponent == nullptr) { + return; + } - if (rebuildComponent->GetState() != REBUILD_COMPLETED) - { - return; - } + if (rebuildComponent->GetState() != REBUILD_COMPLETED) { + return; + } - auto* inventoryComponent = user->GetComponent(); - auto* missionComponent = user->GetComponent(); - auto* character = user->GetCharacter(); + auto* inventoryComponent = user->GetComponent(); + auto* missionComponent = user->GetComponent(); + auto* character = user->GetCharacter(); - if (inventoryComponent == nullptr || missionComponent == nullptr || character == nullptr) - { - return; - } + if (inventoryComponent == nullptr || missionComponent == nullptr || character == nullptr) { + return; + } - if (inventoryComponent->GetLotCount(6194) < 25) - { - return; - } + if (inventoryComponent->GetLotCount(6194) < 25) { + return; + } - inventoryComponent->RemoveItem(6194, 25); + inventoryComponent->RemoveItem(6194, 25); - const auto useSound = self->GetVar(u"sound1"); + const auto useSound = self->GetVar(u"sound1"); - if (!useSound.empty()) - { - GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, useSound); - } - - // Player must be in faction to interact with this entity. - LOT tokenLOT = 0; + if (!useSound.empty()) { + GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, useSound); + } - if (character->GetPlayerFlag(46)) - { - tokenLOT = 8321; - } - else if (character->GetPlayerFlag(47)) - { - tokenLOT = 8318; - } - else if (character->GetPlayerFlag(48)) - { - tokenLOT = 8320; - } - else if (character->GetPlayerFlag(49)) - { - tokenLOT = 8319; - } + // Player must be in faction to interact with this entity. + LOT tokenLOT = 0; - inventoryComponent->AddItem(tokenLOT, 5, eLootSourceType::LOOT_SOURCE_NONE); + if (character->GetPlayerFlag(46)) { + tokenLOT = 8321; + } else if (character->GetPlayerFlag(47)) { + tokenLOT = 8318; + } else if (character->GetPlayerFlag(48)) { + tokenLOT = 8320; + } else if (character->GetPlayerFlag(49)) { + tokenLOT = 8319; + } - missionComponent->ForceProgressTaskType(863, 1, 1, false); - - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + inventoryComponent->AddItem(tokenLOT, 5, eLootSourceType::LOOT_SOURCE_NONE); + + missionComponent->ForceProgressTaskType(863, 1, 1, false); + + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/NsTokenConsoleServer.h b/dScripts/NsTokenConsoleServer.h index d0cdb011..364cb714 100644 --- a/dScripts/NsTokenConsoleServer.h +++ b/dScripts/NsTokenConsoleServer.h @@ -5,5 +5,5 @@ class NsTokenConsoleServer : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/NtAssemblyTubeServer.cpp b/dScripts/NtAssemblyTubeServer.cpp index 935993f4..f30f4fc7 100644 --- a/dScripts/NtAssemblyTubeServer.cpp +++ b/dScripts/NtAssemblyTubeServer.cpp @@ -3,126 +3,112 @@ #include "EntityManager.h" #include "MissionComponent.h" -void NtAssemblyTubeServer::OnStartup(Entity* self) -{ - self->SetProximityRadius(5, "teleport"); +void NtAssemblyTubeServer::OnStartup(Entity* self) { + self->SetProximityRadius(5, "teleport"); } -void NtAssemblyTubeServer::OnPlayerLoaded(Entity* self, Entity* player) -{ - +void NtAssemblyTubeServer::OnPlayerLoaded(Entity* self, Entity* player) { + } -void NtAssemblyTubeServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (status != "ENTER" || !entering->IsPlayer() || name != "teleport") return; +void NtAssemblyTubeServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (status != "ENTER" || !entering->IsPlayer() || name != "teleport") return; - auto* player = entering; - const auto playerID = player->GetObjectID(); + auto* player = entering; + const auto playerID = player->GetObjectID(); - RunAssemblyTube(self, player); + RunAssemblyTube(self, player); - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } } -void NtAssemblyTubeServer::RunAssemblyTube(Entity* self, Entity* player) -{ - const auto playerID = player->GetObjectID(); - - const auto iter = m_TeleportingPlayerTable.find(playerID); - if (iter == m_TeleportingPlayerTable.end()) m_TeleportingPlayerTable[playerID] = false; - const auto bPlayerBeingTeleported = m_TeleportingPlayerTable[playerID]; +void NtAssemblyTubeServer::RunAssemblyTube(Entity* self, Entity* player) { + const auto playerID = player->GetObjectID(); - if (player->IsPlayer() && !bPlayerBeingTeleported) - { - auto teleCinematic = self->GetVar(u"Cinematic"); + const auto iter = m_TeleportingPlayerTable.find(playerID); + if (iter == m_TeleportingPlayerTable.end()) m_TeleportingPlayerTable[playerID] = false; + const auto bPlayerBeingTeleported = m_TeleportingPlayerTable[playerID]; - GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); + if (player->IsPlayer() && !bPlayerBeingTeleported) { + auto teleCinematic = self->GetVar(u"Cinematic"); - if (!teleCinematic.empty()) - { - const auto teleCinematicUname = teleCinematic; - GameMessages::SendPlayCinematic(player->GetObjectID(), teleCinematicUname, player->GetSystemAddress(), - true, true, true, false, 0, false, -1, false, true - ); - } + GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - GameMessages::SendPlayAnimation(player, u"tube-sucker", 4.0f); + if (!teleCinematic.empty()) { + const auto teleCinematicUname = teleCinematic; + GameMessages::SendPlayCinematic(player->GetObjectID(), teleCinematicUname, player->GetSystemAddress(), + true, true, true, false, 0, false, -1, false, true + ); + } - const auto animTime = 3; + GameMessages::SendPlayAnimation(player, u"tube-sucker", 4.0f); - self->AddCallbackTimer(animTime, [this, self, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); + const auto animTime = 3; - if (player == nullptr) - { - return; - } + self->AddCallbackTimer(animTime, [this, self, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - TeleportPlayer(self, player); - }); - } + if (player == nullptr) { + return; + } + + TeleportPlayer(self, player); + }); + } } -void NtAssemblyTubeServer::TeleportPlayer(Entity* self, Entity* player) -{ - auto destinationGroup = self->GetVar(u"teleGroup"); - auto* destination = self; +void NtAssemblyTubeServer::TeleportPlayer(Entity* self, Entity* player) { + auto destinationGroup = self->GetVar(u"teleGroup"); + auto* destination = self; - if (!destinationGroup.empty()) - { - const auto& groupObjs = EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(destinationGroup)); + if (!destinationGroup.empty()) { + const auto& groupObjs = EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(destinationGroup)); - if (!groupObjs.empty()) - { - destination = groupObjs[0]; - } - } + if (!groupObjs.empty()) { + destination = groupObjs[0]; + } + } - const auto destPosition = destination->GetPosition(); - const auto destRotation = destination->GetRotation(); + const auto destPosition = destination->GetPosition(); + const auto destRotation = destination->GetRotation(); - GameMessages::SendTeleport(player->GetObjectID(), destPosition, destRotation, player->GetSystemAddress(), true); + GameMessages::SendTeleport(player->GetObjectID(), destPosition, destRotation, player->GetSystemAddress(), true); - GameMessages::SendPlayAnimation(player, u"tube-resurrect", 4.0f); + GameMessages::SendPlayAnimation(player, u"tube-resurrect", 4.0f); - const auto animTime = 2; + const auto animTime = 2; - const auto playerID = player->GetObjectID(); - - self->AddCallbackTimer(animTime, [this, self, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); + const auto playerID = player->GetObjectID(); - if (player == nullptr) - { - return; - } + self->AddCallbackTimer(animTime, [this, self, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - UnlockPlayer(self, player); - }); + if (player == nullptr) { + return; + } - const auto useSound = self->GetVar(u"sound1"); + UnlockPlayer(self, player); + }); - if (!useSound.empty()) - { - GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), useSound); - } + const auto useSound = self->GetVar(u"sound1"); + + if (!useSound.empty()) { + GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), useSound); + } } -void NtAssemblyTubeServer::UnlockPlayer(Entity* self, Entity* player) -{ - const auto playerID = player->GetObjectID(); +void NtAssemblyTubeServer::UnlockPlayer(Entity* self, Entity* player) { + const auto playerID = player->GetObjectID(); - m_TeleportingPlayerTable[playerID] = false; + m_TeleportingPlayerTable[playerID] = false; - GameMessages::SendSetStunned(playerID, POP, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); + GameMessages::SendSetStunned(playerID, POP, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); } diff --git a/dScripts/NtAssemblyTubeServer.h b/dScripts/NtAssemblyTubeServer.h index 116be068..35dcc6f6 100644 --- a/dScripts/NtAssemblyTubeServer.h +++ b/dScripts/NtAssemblyTubeServer.h @@ -5,12 +5,12 @@ class NtAssemblyTubeServer : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnPlayerLoaded(Entity* self, Entity* player) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void RunAssemblyTube(Entity* self, Entity* player); - void TeleportPlayer(Entity* self, Entity* player); - void UnlockPlayer(Entity* self, Entity* player); + void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void RunAssemblyTube(Entity* self, Entity* player); + void TeleportPlayer(Entity* self, Entity* player); + void UnlockPlayer(Entity* self, Entity* player); private: - std::map m_TeleportingPlayerTable; + std::map m_TeleportingPlayerTable; }; diff --git a/dScripts/NtBeamImaginationCollectors.cpp b/dScripts/NtBeamImaginationCollectors.cpp index ed756c02..b8036c89 100644 --- a/dScripts/NtBeamImaginationCollectors.cpp +++ b/dScripts/NtBeamImaginationCollectors.cpp @@ -2,33 +2,28 @@ #include "GeneralUtils.h" #include "GameMessages.h" -void NtBeamImaginationCollectors::OnStartup(Entity* self) -{ - self->AddTimer("PlayFX", GetRandomNum()); +void NtBeamImaginationCollectors::OnStartup(Entity* self) { + self->AddTimer("PlayFX", GetRandomNum()); } -int32_t NtBeamImaginationCollectors::GetRandomNum() -{ - int32_t randNum = m_LastRandom; +int32_t NtBeamImaginationCollectors::GetRandomNum() { + int32_t randNum = m_LastRandom; - while (randNum == m_LastRandom) - { - randNum = GeneralUtils::GenerateRandomNumber(m_RandMin, m_RandMax); - } + while (randNum == m_LastRandom) { + randNum = GeneralUtils::GenerateRandomNumber(m_RandMin, m_RandMax); + } - m_LastRandom = randNum; + m_LastRandom = randNum; - return randNum; + return randNum; } -void NtBeamImaginationCollectors::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName != "PlayFX") - { - return; - } +void NtBeamImaginationCollectors::OnTimerDone(Entity* self, std::string timerName) { + if (timerName != "PlayFX") { + return; + } - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, m_FxName, "Beam"); - - self->AddTimer("PlayFX", GetRandomNum()); + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, m_FxName, "Beam"); + + self->AddTimer("PlayFX", GetRandomNum()); } diff --git a/dScripts/NtBeamImaginationCollectors.h b/dScripts/NtBeamImaginationCollectors.h index d494d66c..28424766 100644 --- a/dScripts/NtBeamImaginationCollectors.h +++ b/dScripts/NtBeamImaginationCollectors.h @@ -4,13 +4,13 @@ class NtBeamImaginationCollectors : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - int32_t GetRandomNum(); - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + int32_t GetRandomNum(); + void OnTimerDone(Entity* self, std::string timerName) override; private: - int32_t m_LastRandom = 0; - int32_t m_RandMin = 5; - int32_t m_RandMax = 15; - std::u16string m_FxName = u"beam_collect"; + int32_t m_LastRandom = 0; + int32_t m_RandMin = 5; + int32_t m_RandMax = 15; + std::u16string m_FxName = u"beam_collect"; }; diff --git a/dScripts/NtCombatChallengeDummy.cpp b/dScripts/NtCombatChallengeDummy.cpp index a391e00f..c9cd8f0a 100644 --- a/dScripts/NtCombatChallengeDummy.cpp +++ b/dScripts/NtCombatChallengeDummy.cpp @@ -1,32 +1,26 @@ #include "NtCombatChallengeDummy.h" #include "EntityManager.h" -void NtCombatChallengeDummy::OnDie(Entity* self, Entity* killer) -{ - const auto challengeObjectID = self->GetVar(u"challengeObjectID"); +void NtCombatChallengeDummy::OnDie(Entity* self, Entity* killer) { + const auto challengeObjectID = self->GetVar(u"challengeObjectID"); - auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); + auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); - if (challengeObject != nullptr) - { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) - { - script->OnDie(challengeObject, killer); - } - } + if (challengeObject != nullptr) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) { + script->OnDie(challengeObject, killer); + } + } } -void NtCombatChallengeDummy::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) -{ - const auto challengeObjectID = self->GetVar(u"challengeObjectID"); +void NtCombatChallengeDummy::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { + const auto challengeObjectID = self->GetVar(u"challengeObjectID"); - auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); + auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); - if (challengeObject != nullptr) - { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) - { - script->OnHitOrHealResult(challengeObject, attacker, damage); - } - } + if (challengeObject != nullptr) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) { + script->OnHitOrHealResult(challengeObject, attacker, damage); + } + } } diff --git a/dScripts/NtCombatChallengeDummy.h b/dScripts/NtCombatChallengeDummy.h index d9ef8cbd..bf7d4f04 100644 --- a/dScripts/NtCombatChallengeDummy.h +++ b/dScripts/NtCombatChallengeDummy.h @@ -4,6 +4,6 @@ class NtCombatChallengeDummy : public CppScripts::Script { public: - void OnDie(Entity* self, Entity* killer) override; - void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; + void OnDie(Entity* self, Entity* killer) override; + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; }; diff --git a/dScripts/NtCombatChallengeExplodingDummy.cpp b/dScripts/NtCombatChallengeExplodingDummy.cpp index 24494939..c117c63a 100644 --- a/dScripts/NtCombatChallengeExplodingDummy.cpp +++ b/dScripts/NtCombatChallengeExplodingDummy.cpp @@ -2,36 +2,31 @@ #include "EntityManager.h" #include "SkillComponent.h" -void NtCombatChallengeExplodingDummy::OnDie(Entity* self, Entity* killer) -{ - const auto challengeObjectID = self->GetVar(u"challengeObjectID"); +void NtCombatChallengeExplodingDummy::OnDie(Entity* self, Entity* killer) { + const auto challengeObjectID = self->GetVar(u"challengeObjectID"); - auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); + auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); - if (challengeObject != nullptr) - { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) - { - script->OnDie(challengeObject, killer); - } - } + if (challengeObject != nullptr) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) { + script->OnDie(challengeObject, killer); + } + } } void NtCombatChallengeExplodingDummy::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { - const auto challengeObjectID = self->GetVar(u"challengeObjectID"); + const auto challengeObjectID = self->GetVar(u"challengeObjectID"); - auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); + auto* challengeObject = EntityManager::Instance()->GetEntity(challengeObjectID); - if (challengeObject != nullptr) - { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) - { - script->OnHitOrHealResult(challengeObject, attacker, damage); - } - } - auto skillComponent = self->GetComponent(); - if (skillComponent != nullptr) { - skillComponent->CalculateBehavior(1338, 30875, attacker->GetObjectID()); - } - self->Kill(attacker); -} \ No newline at end of file + if (challengeObject != nullptr) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) { + script->OnHitOrHealResult(challengeObject, attacker, damage); + } + } + auto skillComponent = self->GetComponent(); + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(1338, 30875, attacker->GetObjectID()); + } + self->Kill(attacker); +} diff --git a/dScripts/NtCombatChallengeExplodingDummy.h b/dScripts/NtCombatChallengeExplodingDummy.h index c1c5ef1c..ff48c726 100644 --- a/dScripts/NtCombatChallengeExplodingDummy.h +++ b/dScripts/NtCombatChallengeExplodingDummy.h @@ -3,6 +3,6 @@ class NtCombatChallengeExplodingDummy : public CppScripts::Script { - void OnDie(Entity* self, Entity* killer) override; - void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; -}; \ No newline at end of file + void OnDie(Entity* self, Entity* killer) override; + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; +}; diff --git a/dScripts/NtCombatChallengeServer.cpp b/dScripts/NtCombatChallengeServer.cpp index 4bf5dffc..2b88ccf8 100644 --- a/dScripts/NtCombatChallengeServer.cpp +++ b/dScripts/NtCombatChallengeServer.cpp @@ -4,241 +4,205 @@ #include "InventoryComponent.h" #include "MissionComponent.h" -void NtCombatChallengeServer::OnUse(Entity* self, Entity* user) -{ - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UI_Open", 0, 0, user->GetObjectID(), "", user->GetSystemAddress()); +void NtCombatChallengeServer::OnUse(Entity* self, Entity* user) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UI_Open", 0, 0, user->GetObjectID(), "", user->GetSystemAddress()); } -void NtCombatChallengeServer::OnDie(Entity* self, Entity* killer) -{ - if (killer != self && killer != nullptr) - { - SpawnTargetDummy(self); - } +void NtCombatChallengeServer::OnDie(Entity* self, Entity* killer) { + if (killer != self && killer != nullptr) { + SpawnTargetDummy(self); + } } -void NtCombatChallengeServer::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) -{ - const auto playerID = self->GetVar(u"playerID"); +void NtCombatChallengeServer::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { + const auto playerID = self->GetVar(u"playerID"); - auto* player = EntityManager::Instance()->GetEntity(playerID); + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - auto totalDmg = self->GetVar(u"totalDmg"); + auto totalDmg = self->GetVar(u"totalDmg"); - totalDmg += damage; + totalDmg += damage; - self->SetVar(u"totalDmg", totalDmg); - self->SetNetworkVar(u"totalDmg", totalDmg); + self->SetVar(u"totalDmg", totalDmg); + self->SetNetworkVar(u"totalDmg", totalDmg); - GameMessages::SendPlayNDAudioEmitter(self, attacker->GetSystemAddress(), scoreSound); + GameMessages::SendPlayNDAudioEmitter(self, attacker->GetSystemAddress(), scoreSound); } -void NtCombatChallengeServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) -{ - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UI_Close", 0, 0, sender->GetObjectID(), "", sender->GetSystemAddress()); +void NtCombatChallengeServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UI_Close", 0, 0, sender->GetObjectID(), "", sender->GetSystemAddress()); } -void NtCombatChallengeServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - if (identifier == u"PlayButton" && button == 1) - { - self->SetNetworkVar(u"bInUse", true); +void NtCombatChallengeServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + if (identifier == u"PlayButton" && button == 1) { + self->SetNetworkVar(u"bInUse", true); - self->SetVar(u"playerID", sender->GetObjectID()); + self->SetVar(u"playerID", sender->GetObjectID()); - auto* inventoryComponent = sender->GetComponent(); + auto* inventoryComponent = sender->GetComponent(); - if (inventoryComponent != nullptr) - { - inventoryComponent->RemoveItem(3039, 1); - } + if (inventoryComponent != nullptr) { + inventoryComponent->RemoveItem(3039, 1); + } - GameMessages::SendPlayNDAudioEmitter(self, sender->GetSystemAddress(), startSound); + GameMessages::SendPlayNDAudioEmitter(self, sender->GetSystemAddress(), startSound); - self->AddTimer("start_delay", 2.0f); + self->AddTimer("start_delay", 2.0f); - GameMessages::SendShowActivityCountdown(self->GetObjectID(), false, false, u"", 0, sender->GetSystemAddress()); + GameMessages::SendShowActivityCountdown(self->GetObjectID(), false, false, u"", 0, sender->GetSystemAddress()); - self->SetNetworkVar(u"toggle", true); - } - else if (identifier == u"CloseButton") - { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UI_Close", 1, 0, sender->GetObjectID(), "", sender->GetSystemAddress()); - } + self->SetNetworkVar(u"toggle", true); + } else if (identifier == u"CloseButton") { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UI_Close", 1, 0, sender->GetObjectID(), "", sender->GetSystemAddress()); + } } -void NtCombatChallengeServer::SpawnTargetDummy(Entity* self) -{ - const auto playerID = self->GetVar(u"playerID"); +void NtCombatChallengeServer::SpawnTargetDummy(Entity* self) { + const auto playerID = self->GetVar(u"playerID"); - auto* player = EntityManager::Instance()->GetEntity(playerID); + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - auto targetNumber = self->GetVar(u"TargetNumber"); - if (targetNumber == 0) targetNumber = 1; + auto targetNumber = self->GetVar(u"TargetNumber"); + if (targetNumber == 0) targetNumber = 1; - if (targetNumber > tTargets.size()) targetNumber = tTargets.size(); + if (targetNumber > tTargets.size()) targetNumber = tTargets.size(); - self->SetVar(u"TargetNumber", targetNumber + 1); + self->SetVar(u"TargetNumber", targetNumber + 1); - const auto dummyLOT = tTargets[targetNumber - 1]; + const auto dummyLOT = tTargets[targetNumber - 1]; - EntityInfo info {}; - info.lot = dummyLOT; - info.spawnerID = self->GetObjectID(); - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.settings = { new LDFData(u"custom_script_server", "scripts\\02_server\\Map\\NT\\L_NT_COMBAT_CHALLENGE_DUMMY.lua") }; + EntityInfo info{}; + info.lot = dummyLOT; + info.spawnerID = self->GetObjectID(); + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.settings = { new LDFData(u"custom_script_server", "scripts\\02_server\\Map\\NT\\L_NT_COMBAT_CHALLENGE_DUMMY.lua") }; - auto* dummy = EntityManager::Instance()->CreateEntity(info); + auto* dummy = EntityManager::Instance()->CreateEntity(info); - dummy->SetVar(u"challengeObjectID", self->GetObjectID()); + dummy->SetVar(u"challengeObjectID", self->GetObjectID()); - EntityManager::Instance()->ConstructEntity(dummy); + EntityManager::Instance()->ConstructEntity(dummy); - self->SetVar(u"currentDummy", dummy->GetObjectID()); + self->SetVar(u"currentDummy", dummy->GetObjectID()); } -void NtCombatChallengeServer::SetAttackImmunity(LWOOBJID objID, bool bTurnOn) -{ - +void NtCombatChallengeServer::SetAttackImmunity(LWOOBJID objID, bool bTurnOn) { + } -void NtCombatChallengeServer::OnChildLoaded(Entity* self, Entity* child) -{ - auto targetNumber = self->GetVar(u"TargetNumber"); - if (targetNumber == 0) targetNumber = 1; - self->SetVar(u"TargetNumber", targetNumber + 1); +void NtCombatChallengeServer::OnChildLoaded(Entity* self, Entity* child) { + auto targetNumber = self->GetVar(u"TargetNumber"); + if (targetNumber == 0) targetNumber = 1; + self->SetVar(u"TargetNumber", targetNumber + 1); - const auto playerID = self->GetVar(u"playerID"); + const auto playerID = self->GetVar(u"playerID"); - auto* player = EntityManager::Instance()->GetEntity(playerID); + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - child->SetRotation(NiQuaternion::LookAt(child->GetPosition(), player->GetPosition())); + child->SetRotation(NiQuaternion::LookAt(child->GetPosition(), player->GetPosition())); - self->SetVar(u"currentTargetID", child->GetObjectID()); + self->SetVar(u"currentTargetID", child->GetObjectID()); - EntityManager::Instance()->SerializeEntity(child); + EntityManager::Instance()->SerializeEntity(child); - child->GetGroups().push_back("targets_" + std::to_string(self->GetObjectID())); + child->GetGroups().push_back("targets_" + std::to_string(self->GetObjectID())); } -void NtCombatChallengeServer::ResetGame(Entity* self) -{ - const auto totalDmg = self->GetVar(u"totalDmg"); - const auto playerID = self->GetVar(u"playerID"); +void NtCombatChallengeServer::ResetGame(Entity* self) { + const auto totalDmg = self->GetVar(u"totalDmg"); + const auto playerID = self->GetVar(u"playerID"); - auto* player = EntityManager::Instance()->GetEntity(playerID); + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) - { - auto* missionComponent = player->GetComponent(); + if (player != nullptr) { + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - for (const auto& mission : tMissions) - { - if (totalDmg >= mission.damage) - { - missionComponent->ForceProgressTaskType(mission.mission, 1, 1); - } - } - } - } + if (missionComponent != nullptr) { + for (const auto& mission : tMissions) { + if (totalDmg >= mission.damage) { + missionComponent->ForceProgressTaskType(mission.mission, 1, 1); + } + } + } + } - self->SetVar(u"TargetNumber", 1); - self->SetVar(u"playerID", LWOOBJID_EMPTY); - self->SetVar(u"totalDmg", 0); - self->SetNetworkVar(u"totalDmg", false); - self->SetNetworkVar(u"update_time", 0); + self->SetVar(u"TargetNumber", 1); + self->SetVar(u"playerID", LWOOBJID_EMPTY); + self->SetVar(u"totalDmg", 0); + self->SetNetworkVar(u"totalDmg", false); + self->SetNetworkVar(u"update_time", 0); - const auto& targetObjs = EntityManager::Instance()->GetEntitiesInGroup("targets_" + std::to_string(self->GetObjectID())); + const auto& targetObjs = EntityManager::Instance()->GetEntitiesInGroup("targets_" + std::to_string(self->GetObjectID())); - for (auto* target : targetObjs) - { - target->Smash(self->GetObjectID()); - } + for (auto* target : targetObjs) { + target->Smash(self->GetObjectID()); + } - const auto currentID = self->GetVar(u"currentDummy"); + const auto currentID = self->GetVar(u"currentDummy"); - auto* current = EntityManager::Instance()->GetEntity(currentID); + auto* current = EntityManager::Instance()->GetEntity(currentID); - if (current != nullptr) - { - current->Smash(self->GetObjectID()); - } + if (current != nullptr) { + current->Smash(self->GetObjectID()); + } } -void NtCombatChallengeServer::OnActivityTimerUpdate(Entity* self, float timeRemaining) -{ - self->SetNetworkVar(u"update_time", std::ceil(timeRemaining)); +void NtCombatChallengeServer::OnActivityTimerUpdate(Entity* self, float timeRemaining) { + self->SetNetworkVar(u"update_time", std::ceil(timeRemaining)); - if (timeRemaining <= 3) - { - GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, timerLowSound); - } - else - { - GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, timerSound); - } + if (timeRemaining <= 3) { + GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, timerLowSound); + } else { + GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, timerSound); + } } -void NtCombatChallengeServer::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "start_delay") - { - self->SetVar(u"game_tick", gameTime); +void NtCombatChallengeServer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "start_delay") { + self->SetVar(u"game_tick", gameTime); - SpawnTargetDummy(self); + SpawnTargetDummy(self); - self->AddTimer("game_tick", 1); + self->AddTimer("game_tick", 1); - self->SetNetworkVar(u"totalTime", gameTime); - } - else if (timerName == "game_tick") - { - auto gameTick = self->GetVar(u"game_tick"); + self->SetNetworkVar(u"totalTime", gameTime); + } else if (timerName == "game_tick") { + auto gameTick = self->GetVar(u"game_tick"); - gameTick -= 1; + gameTick -= 1; - self->SetVar(u"game_tick", gameTick); + self->SetVar(u"game_tick", gameTick); - if (gameTick <= 0) - { - ResetGame(self); + if (gameTick <= 0) { + ResetGame(self); - GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, stopSound); + GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, stopSound); - self->AddTimer("reset_tick", 5); - } - else - { - self->AddTimer("game_tick", 1); + self->AddTimer("reset_tick", 5); + } else { + self->AddTimer("game_tick", 1); - OnActivityTimerUpdate(self, gameTick); - } - } - else if (timerName == "reset_tick") - { - self->SetNetworkVar(u"toggle", false); - self->SetNetworkVar(u"bInUse", false); - } + OnActivityTimerUpdate(self, gameTick); + } + } else if (timerName == "reset_tick") { + self->SetNetworkVar(u"toggle", false); + self->SetNetworkVar(u"bInUse", false); + } } diff --git a/dScripts/NtCombatChallengeServer.h b/dScripts/NtCombatChallengeServer.h index 6a193a11..72bb981f 100644 --- a/dScripts/NtCombatChallengeServer.h +++ b/dScripts/NtCombatChallengeServer.h @@ -4,44 +4,44 @@ class NtCombatChallengeServer : public CppScripts::Script { public: - void OnUse(Entity* self, Entity* user) override; - void OnDie(Entity* self, Entity* killer) override; - void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; - void SpawnTargetDummy(Entity* self); - void SetAttackImmunity(LWOOBJID objID, bool bTurnOn); - void OnChildLoaded(Entity* self, Entity* child); - void ResetGame(Entity* self); - void OnActivityTimerUpdate(Entity* self, float timeRemaining); - void OnTimerDone(Entity* self, std::string timerName) override; + void OnUse(Entity* self, Entity* user) override; + void OnDie(Entity* self, Entity* killer) override; + void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; + void SpawnTargetDummy(Entity* self); + void SetAttackImmunity(LWOOBJID objID, bool bTurnOn); + void OnChildLoaded(Entity* self, Entity* child); + void ResetGame(Entity* self); + void OnActivityTimerUpdate(Entity* self, float timeRemaining); + void OnTimerDone(Entity* self, std::string timerName) override; private: - float gameTime = 30.0f; - std::string startSound = "{a477f897-30da-4b15-8fce-895c6547adae}"; - std::string stopSound = "{a832b9c5-b000-4c97-820a-2a7d1e68dd9d}"; - std::string timerSound = "{79b38431-4fc7-403b-8ede-eaff700a7ab0}"; - std::string timerLowSound = "{0e1f1284-e1c4-42ed-8ef9-93e8756948f8}"; - std::string scoreSound = "{cfdade40-3d97-4cf5-b53c-862e0b84c1a1}"; + float gameTime = 30.0f; + std::string startSound = "{a477f897-30da-4b15-8fce-895c6547adae}"; + std::string stopSound = "{a832b9c5-b000-4c97-820a-2a7d1e68dd9d}"; + std::string timerSound = "{79b38431-4fc7-403b-8ede-eaff700a7ab0}"; + std::string timerLowSound = "{0e1f1284-e1c4-42ed-8ef9-93e8756948f8}"; + std::string scoreSound = "{cfdade40-3d97-4cf5-b53c-862e0b84c1a1}"; - std::vector tTargets = { - 13556, 13556, 13764, 13764, 13765, 13765, - 13766, 13766, 13767, 13767, 13768, 13768, - 13830, 13769, 13769, 13770, 13830, 13770, + std::vector tTargets = { + 13556, 13556, 13764, 13764, 13765, 13765, + 13766, 13766, 13767, 13767, 13768, 13768, + 13830, 13769, 13769, 13770, 13830, 13770, 13771, 13771, 13830, 13772 - }; + }; - struct MissionRequirements - { - int32_t mission; - int32_t damage; - }; + struct MissionRequirements + { + int32_t mission; + int32_t damage; + }; - std::vector tMissions = { - {1010, 25}, - {1340, 100}, - {1341, 240}, - {1342, 290} - }; + std::vector tMissions = { + {1010, 25}, + {1340, 100}, + {1341, 240}, + {1342, 290} + }; }; diff --git a/dScripts/NtConsoleTeleportServer.cpp b/dScripts/NtConsoleTeleportServer.cpp index b03ae34e..324a2fc0 100644 --- a/dScripts/NtConsoleTeleportServer.cpp +++ b/dScripts/NtConsoleTeleportServer.cpp @@ -2,33 +2,27 @@ #include "Entity.h" #include "AMFFormat.h" -void NtConsoleTeleportServer::OnStartup(Entity* self) -{ - self->SetVar(u"teleportAnim", m_TeleportAnim); - self->SetVar(u"teleportString", m_TeleportString); +void NtConsoleTeleportServer::OnStartup(Entity* self) { + self->SetVar(u"teleportAnim", m_TeleportAnim); + self->SetVar(u"teleportString", m_TeleportString); } -void NtConsoleTeleportServer::OnUse(Entity* self, Entity* user) -{ - BaseOnUse(self, user); +void NtConsoleTeleportServer::OnUse(Entity* self, Entity* user) { + BaseOnUse(self, user); } -void NtConsoleTeleportServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) -{ - BaseOnMessageBoxResponse(self, sender, button, identifier, userData); +void NtConsoleTeleportServer::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { + BaseOnMessageBoxResponse(self, sender, button, identifier, userData); } -void NtConsoleTeleportServer::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) -{ - +void NtConsoleTeleportServer::OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { + } -void NtConsoleTeleportServer::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void NtConsoleTeleportServer::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } -void NtConsoleTeleportServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) -{ - BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); +void NtConsoleTeleportServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + BaseOnFireEventServerSide(self, sender, args, param1, param2, param3); } diff --git a/dScripts/NtConsoleTeleportServer.h b/dScripts/NtConsoleTeleportServer.h index 7bba7ee1..59ac7bf4 100644 --- a/dScripts/NtConsoleTeleportServer.h +++ b/dScripts/NtConsoleTeleportServer.h @@ -6,16 +6,16 @@ class NtConsoleTeleportServer : public CppScripts::Script, BaseConsoleTeleportServer { public: - void OnStartup(Entity* self) override; - void OnUse(Entity* self, Entity* user) override; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; - void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) override; + void OnChoiceBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; private: - int32_t m_ChoiceZoneID = 1800; - std::string m_SpawnPoint = "NS_LW"; - std::u16string m_TeleportAnim = u"lup-teleport"; - std::u16string m_TeleportString = u"UI_TRAVEL_TO_CRUX_PRIME"; + int32_t m_ChoiceZoneID = 1800; + std::string m_SpawnPoint = "NS_LW"; + std::u16string m_TeleportAnim = u"lup-teleport"; + std::u16string m_TeleportString = u"UI_TRAVEL_TO_CRUX_PRIME"; }; diff --git a/dScripts/NtDarkitectRevealServer.cpp b/dScripts/NtDarkitectRevealServer.cpp index b8afa510..80ceb91e 100644 --- a/dScripts/NtDarkitectRevealServer.cpp +++ b/dScripts/NtDarkitectRevealServer.cpp @@ -2,15 +2,13 @@ #include "Darkitect.h" #include "MissionComponent.h" -void NtDarkitectRevealServer::OnUse(Entity* self, Entity* user) -{ +void NtDarkitectRevealServer::OnUse(Entity* self, Entity* user) { Darkitect Baron; Baron.Reveal(self, user); auto* missionComponent = user->GetComponent(); - if (missionComponent != nullptr) - { + if (missionComponent != nullptr) { missionComponent->ForceProgressTaskType(1344, 1, 14293); } } diff --git a/dScripts/NtDirtCloudServer.cpp b/dScripts/NtDirtCloudServer.cpp index 82572703..a9a70c5c 100644 --- a/dScripts/NtDirtCloudServer.cpp +++ b/dScripts/NtDirtCloudServer.cpp @@ -1,53 +1,46 @@ #include "NtDirtCloudServer.h" #include "MissionComponent.h" -std::map> NtDirtCloudServer::m_Missions = +std::map> NtDirtCloudServer::m_Missions = { - {"Dirt_Clouds_Sent", {1333,1253}}, - {"Dirt_Clouds_Assem", {1333,1276}}, - {"Dirt_Clouds_Para", {1333,1277}}, - {"Dirt_Clouds_Halls", {1333,1283}} + {"Dirt_Clouds_Sent", {1333,1253}}, + {"Dirt_Clouds_Assem", {1333,1276}}, + {"Dirt_Clouds_Para", {1333,1277}}, + {"Dirt_Clouds_Halls", {1333,1283}} }; -void NtDirtCloudServer::OnStartup(Entity* self) -{ - self->SetVar(u"CloudOn", true); +void NtDirtCloudServer::OnStartup(Entity* self) { + self->SetVar(u"CloudOn", true); } -void NtDirtCloudServer::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) -{ - if (message != "soapspray") - { - return; - } +void NtDirtCloudServer::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message != "soapspray") { + return; + } - if (!self->GetVar(u"CloudOn")) - { - return; - } + if (!self->GetVar(u"CloudOn")) { + return; + } - const auto mySpawner = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); + const auto mySpawner = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - if (m_Missions.count(mySpawner) == 0) - { - return; - } + if (m_Missions.count(mySpawner) == 0) { + return; + } - const auto& myMis = m_Missions[mySpawner]; + const auto& myMis = m_Missions[mySpawner]; - auto* missionComponent = caster->GetComponent(); + auto* missionComponent = caster->GetComponent(); - if (missionComponent == nullptr) - { - return; - } + if (missionComponent == nullptr) { + return; + } - for (const auto missionID : myMis) - { - missionComponent->ForceProgressTaskType(missionID, 1, 1); - } - - self->SetVar(u"CloudOn", false); + for (const auto missionID : myMis) { + missionComponent->ForceProgressTaskType(missionID, 1, 1); + } - self->Smash(self->GetObjectID(), VIOLENT); + self->SetVar(u"CloudOn", false); + + self->Smash(self->GetObjectID(), VIOLENT); } diff --git a/dScripts/NtDirtCloudServer.h b/dScripts/NtDirtCloudServer.h index 0c9e50d1..150a33df 100644 --- a/dScripts/NtDirtCloudServer.h +++ b/dScripts/NtDirtCloudServer.h @@ -4,9 +4,9 @@ class NtDirtCloudServer : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; + void OnStartup(Entity* self) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; private: - static std::map> m_Missions; + static std::map> m_Missions; }; diff --git a/dScripts/NtDukeServer.cpp b/dScripts/NtDukeServer.cpp index df3f39d6..327d3290 100644 --- a/dScripts/NtDukeServer.cpp +++ b/dScripts/NtDukeServer.cpp @@ -2,37 +2,37 @@ #include "InventoryComponent.h" #include "MissionComponent.h" -void NtDukeServer::SetVariables(Entity *self) { - self->SetVar(m_SpyProximityVariable, 35.0f); +void NtDukeServer::SetVariables(Entity* self) { + self->SetVar(m_SpyProximityVariable, 35.0f); - self->SetVar(m_SpyDataVariable, { - NT_FACTION_SPY_DUKE, 13548, 1319 - }); + self->SetVar(m_SpyDataVariable, { + NT_FACTION_SPY_DUKE, 13548, 1319 + }); - self->SetVar>(m_SpyDialogueTableVariable, { - { "DUKE_NT_CONVO_1", 0 }, - { "DUKE_NT_CONVO_2", 0 }, - { "DUKE_NT_CONVO_3", 0 }, - }); + self->SetVar>(m_SpyDialogueTableVariable, { + { "DUKE_NT_CONVO_1", 0 }, + { "DUKE_NT_CONVO_2", 0 }, + { "DUKE_NT_CONVO_3", 0 }, + }); - // If there's an alternating conversation, indices should be provided using the conversationID variables - self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID() }); + // If there's an alternating conversation, indices should be provided using the conversationID variables + self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID() }); } -void NtDukeServer::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { +void NtDukeServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { - // Handles adding and removing the sword for the Crux Prime Sword mission - auto* missionComponent = target->GetComponent(); - auto* inventoryComponent = target->GetComponent(); + // Handles adding and removing the sword for the Crux Prime Sword mission + auto* missionComponent = target->GetComponent(); + auto* inventoryComponent = target->GetComponent(); - if (missionComponent != nullptr && inventoryComponent != nullptr) { - auto state = missionComponent->GetMissionState(m_SwordMissionID); - auto lotCount = inventoryComponent->GetLotCount(m_SwordLot); + if (missionComponent != nullptr && inventoryComponent != nullptr) { + auto state = missionComponent->GetMissionState(m_SwordMissionID); + auto lotCount = inventoryComponent->GetLotCount(m_SwordLot); - if ((state == MissionState::MISSION_STATE_AVAILABLE || state == MissionState::MISSION_STATE_ACTIVE) && lotCount < 1) { - inventoryComponent->AddItem(m_SwordLot, 1, eLootSourceType::LOOT_SOURCE_NONE); - } else if (state == MissionState::MISSION_STATE_READY_TO_COMPLETE) { - inventoryComponent->RemoveItem(m_SwordLot, lotCount); - } - } + if ((state == MissionState::MISSION_STATE_AVAILABLE || state == MissionState::MISSION_STATE_ACTIVE) && lotCount < 1) { + inventoryComponent->AddItem(m_SwordLot, 1, eLootSourceType::LOOT_SOURCE_NONE); + } else if (state == MissionState::MISSION_STATE_READY_TO_COMPLETE) { + inventoryComponent->RemoveItem(m_SwordLot, lotCount); + } + } } diff --git a/dScripts/NtDukeServer.h b/dScripts/NtDukeServer.h index f56e9912..0878e86c 100644 --- a/dScripts/NtDukeServer.h +++ b/dScripts/NtDukeServer.h @@ -2,8 +2,8 @@ #include "NtFactionSpyServer.h" class NtDukeServer : public NtFactionSpyServer { - void SetVariables(Entity *self) override; - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; - const uint32_t m_SwordMissionID = 1448; - const LOT m_SwordLot = 13777; + void SetVariables(Entity* self) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + const uint32_t m_SwordMissionID = 1448; + const LOT m_SwordLot = 13777; }; diff --git a/dScripts/NtFactionSpyServer.cpp b/dScripts/NtFactionSpyServer.cpp index f1104e34..ac068a32 100644 --- a/dScripts/NtFactionSpyServer.cpp +++ b/dScripts/NtFactionSpyServer.cpp @@ -5,96 +5,96 @@ #include "GameMessages.h" #include "MissionComponent.h" -void NtFactionSpyServer::OnStartup(Entity *self) { - SetVariables(self); +void NtFactionSpyServer::OnStartup(Entity* self) { + SetVariables(self); - // Set the proximity to sense later - auto* proximityMonitor = self->GetComponent(); - if (proximityMonitor == nullptr) { - proximityMonitor = new ProximityMonitorComponent(self, -1, -1); - self->AddComponent(COMPONENT_TYPE_PROXIMITY_MONITOR, proximityMonitor); - } + // Set the proximity to sense later + auto* proximityMonitor = self->GetComponent(); + if (proximityMonitor == nullptr) { + proximityMonitor = new ProximityMonitorComponent(self, -1, -1); + self->AddComponent(COMPONENT_TYPE_PROXIMITY_MONITOR, proximityMonitor); + } - proximityMonitor->SetProximityRadius(self->GetVar(m_SpyProximityVariable), m_ProximityName); + proximityMonitor->SetProximityRadius(self->GetVar(m_SpyProximityVariable), m_ProximityName); } void NtFactionSpyServer::SetVariables(Entity* self) { - self->SetVar(m_SpyProximityVariable, 0.0f); - self->SetVar(m_SpyDataVariable, {}); - self->SetVar>(m_SpyDialogueTableVariable, {}); + self->SetVar(m_SpyProximityVariable, 0.0f); + self->SetVar(m_SpyDataVariable, {}); + self->SetVar>(m_SpyDialogueTableVariable, {}); - // If there's an alternating conversation, indices should be provided using the conversationID variables - self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID() }); + // If there's an alternating conversation, indices should be provided using the conversationID variables + self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID() }); } -void NtFactionSpyServer::OnProximityUpdate(Entity *self, Entity *entering, std::string name, std::string status) { - if (name == m_ProximityName && status == "ENTER" && IsSpy(self, entering)) { - auto cinematic = self->GetVar(m_SpyCinematicVariable); - if (!cinematic.empty()) { +void NtFactionSpyServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (name == m_ProximityName && status == "ENTER" && IsSpy(self, entering)) { + auto cinematic = self->GetVar(m_SpyCinematicVariable); + if (!cinematic.empty()) { - // Save the root of this cinematic so we can identify updates later - auto cinematicSplit = GeneralUtils::SplitString(cinematic, u'_'); - if (!cinematicSplit.empty()) { - self->SetVar(m_CinematicRootVariable, cinematicSplit.at(0)); - } + // Save the root of this cinematic so we can identify updates later + auto cinematicSplit = GeneralUtils::SplitString(cinematic, u'_'); + if (!cinematicSplit.empty()) { + self->SetVar(m_CinematicRootVariable, cinematicSplit.at(0)); + } - GameMessages::SendPlayCinematic(entering->GetObjectID(), cinematic, entering->GetSystemAddress(), - true, true, true); - } - } + GameMessages::SendPlayCinematic(entering->GetObjectID(), cinematic, entering->GetSystemAddress(), + true, true, true); + } + } } -bool NtFactionSpyServer::IsSpy(Entity* self, Entity *possibleSpy) { - auto spyData = self->GetVar(m_SpyDataVariable); - if (!spyData.missionID || !spyData.flagID || !spyData.itemID) - return false; +bool NtFactionSpyServer::IsSpy(Entity* self, Entity* possibleSpy) { + auto spyData = self->GetVar(m_SpyDataVariable); + if (!spyData.missionID || !spyData.flagID || !spyData.itemID) + return false; - auto* missionComponent = possibleSpy->GetComponent(); - auto* inventoryComponent = possibleSpy->GetComponent(); - auto* character = possibleSpy->GetCharacter(); + auto* missionComponent = possibleSpy->GetComponent(); + auto* inventoryComponent = possibleSpy->GetComponent(); + auto* character = possibleSpy->GetCharacter(); - // A player is a spy if they have the spy mission, have the spy equipment equipped and don't have the spy flag set yet - return missionComponent != nullptr && missionComponent->GetMissionState(spyData.missionID) == MissionState::MISSION_STATE_ACTIVE - && inventoryComponent != nullptr && inventoryComponent->IsEquipped(spyData.itemID) - && character != nullptr && !character->GetPlayerFlag(spyData.flagID); + // A player is a spy if they have the spy mission, have the spy equipment equipped and don't have the spy flag set yet + return missionComponent != nullptr && missionComponent->GetMissionState(spyData.missionID) == MissionState::MISSION_STATE_ACTIVE + && inventoryComponent != nullptr && inventoryComponent->IsEquipped(spyData.itemID) + && character != nullptr && !character->GetPlayerFlag(spyData.flagID); } -void NtFactionSpyServer::OnCinematicUpdate(Entity *self, Entity *sender, eCinematicEvent event, - const std::u16string &pathName, float_t pathTime, float_t totalTime, - int32_t waypoint) { +void NtFactionSpyServer::OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, + const std::u16string& pathName, float_t pathTime, float_t totalTime, + int32_t waypoint) { - const auto& cinematicRoot = self->GetVar(m_CinematicRootVariable); - auto pathNameCopy = std::u16string(pathName); // Mutable copy - auto pathSplit = GeneralUtils::SplitString(pathNameCopy, u'_'); + const auto& cinematicRoot = self->GetVar(m_CinematicRootVariable); + auto pathNameCopy = std::u16string(pathName); // Mutable copy + auto pathSplit = GeneralUtils::SplitString(pathNameCopy, u'_'); - // Make sure we have a path of type _ - if (pathSplit.size() >= 2) { - auto pathRoot = pathSplit.at(0); - auto pathIndex = std::stoi(GeneralUtils::UTF16ToWTF8(pathSplit.at(1))) - 1; - const auto& dialogueTable = self->GetVar>(m_SpyDialogueTableVariable); + // Make sure we have a path of type _ + if (pathSplit.size() >= 2) { + auto pathRoot = pathSplit.at(0); + auto pathIndex = std::stoi(GeneralUtils::UTF16ToWTF8(pathSplit.at(1))) - 1; + const auto& dialogueTable = self->GetVar>(m_SpyDialogueTableVariable); - // Make sure we're listening to the root we're interested in - if (pathRoot == cinematicRoot) { - if (event == STARTED && pathIndex >= 0 && pathIndex < dialogueTable.size()) { + // Make sure we're listening to the root we're interested in + if (pathRoot == cinematicRoot) { + if (event == STARTED && pathIndex >= 0 && pathIndex < dialogueTable.size()) { - // If the cinematic started, show part of the conversation - GameMessages::SendNotifyClientObject(self->GetObjectID(), m_SpyDialogueNotification, 0, - 0, ParamObjectForConversationID(self, dialogueTable.at(pathIndex).conversationID), - dialogueTable.at(pathIndex).token, sender->GetSystemAddress()); + // If the cinematic started, show part of the conversation + GameMessages::SendNotifyClientObject(self->GetObjectID(), m_SpyDialogueNotification, 0, + 0, ParamObjectForConversationID(self, dialogueTable.at(pathIndex).conversationID), + dialogueTable.at(pathIndex).token, sender->GetSystemAddress()); - } else if (event == ENDED && pathIndex >= dialogueTable.size() - 1) { - auto spyData = self->GetVar(m_SpyDataVariable); - auto* character = sender->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(spyData.flagID, true); - } - } - } - } + } else if (event == ENDED && pathIndex >= dialogueTable.size() - 1) { + auto spyData = self->GetVar(m_SpyDataVariable); + auto* character = sender->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(spyData.flagID, true); + } + } + } + } } LWOOBJID NtFactionSpyServer::ParamObjectForConversationID(Entity* self, uint32_t conversationID) { - auto paramObjects = self->GetVar>(m_SpyCinematicObjectsVariable); - auto index = conversationID >= paramObjects.size() ? paramObjects.size() - 1 : conversationID; - return paramObjects.at(index); + auto paramObjects = self->GetVar>(m_SpyCinematicObjectsVariable); + auto index = conversationID >= paramObjects.size() ? paramObjects.size() - 1 : conversationID; + return paramObjects.at(index); } diff --git a/dScripts/NtFactionSpyServer.h b/dScripts/NtFactionSpyServer.h index ec8df1f4..67955dd4 100644 --- a/dScripts/NtFactionSpyServer.h +++ b/dScripts/NtFactionSpyServer.h @@ -2,31 +2,31 @@ #include "CppScripts.h" struct SpyDialogue { - std::string token; - uint32_t conversationID; + std::string token; + uint32_t conversationID; }; struct SpyData { - uint32_t flagID; - LOT itemID; - uint32_t missionID; + uint32_t flagID; + LOT itemID; + uint32_t missionID; }; class NtFactionSpyServer : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnProximityUpdate(Entity *self, Entity *entering, std::string name, std::string status) override; - void OnCinematicUpdate(Entity *self, Entity *sender, eCinematicEvent event, const std::u16string &pathName, float_t pathTime, float_t totalTime, int32_t waypoint) override; + void OnStartup(Entity* self) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, float_t pathTime, float_t totalTime, int32_t waypoint) override; protected: - virtual void SetVariables(Entity* self); - bool IsSpy(Entity* self, Entity* possibleSpy); - LWOOBJID ParamObjectForConversationID(Entity* self, uint32_t conversationID); + virtual void SetVariables(Entity* self); + bool IsSpy(Entity* self, Entity* possibleSpy); + LWOOBJID ParamObjectForConversationID(Entity* self, uint32_t conversationID); - const std::string m_ProximityName = "SpyDistance"; - const std::u16string m_SpyDialogueNotification = u"displayDialogueLine"; - const std::u16string m_SpyCinematicVariable = u"SpyCinematic"; - const std::u16string m_SpyCinematicObjectsVariable = u"SpyCinematicObjects"; - const std::u16string m_CinematicRootVariable = u"CinematicRoot"; - const std::u16string m_SpyProximityVariable = u"Proximity"; - const std::u16string m_SpyDialogueTableVariable = u"SpyDialogueTable"; - const std::u16string m_SpyDataVariable = u"SpyData"; + const std::string m_ProximityName = "SpyDistance"; + const std::u16string m_SpyDialogueNotification = u"displayDialogueLine"; + const std::u16string m_SpyCinematicVariable = u"SpyCinematic"; + const std::u16string m_SpyCinematicObjectsVariable = u"SpyCinematicObjects"; + const std::u16string m_CinematicRootVariable = u"CinematicRoot"; + const std::u16string m_SpyProximityVariable = u"Proximity"; + const std::u16string m_SpyDialogueTableVariable = u"SpyDialogueTable"; + const std::u16string m_SpyDataVariable = u"SpyData"; }; diff --git a/dScripts/NtHaelServer.cpp b/dScripts/NtHaelServer.cpp index a4c16e1f..fbad421f 100644 --- a/dScripts/NtHaelServer.cpp +++ b/dScripts/NtHaelServer.cpp @@ -1,20 +1,20 @@ #include "NtHaelServer.h" #include "Entity.h" -void NtHaelServer::SetVariables(Entity *self) { - self->SetVar(m_SpyProximityVariable, 25.0f); +void NtHaelServer::SetVariables(Entity* self) { + self->SetVar(m_SpyProximityVariable, 25.0f); - self->SetVar(m_SpyDataVariable, { - NT_FACTION_SPY_HAEL, 13892, 1321 - }); + self->SetVar(m_SpyDataVariable, { + NT_FACTION_SPY_HAEL, 13892, 1321 + }); - self->SetVar>(m_SpyDialogueTableVariable, { - { "HAEL_NT_CONVO_1", 0 }, - { "HAEL_NT_CONVO_2", 0 }, - { "HAEL_NT_CONVO_3", 0 }, - { "HAEL_NT_CONVO_4", 0 }, - }); + self->SetVar>(m_SpyDialogueTableVariable, { + { "HAEL_NT_CONVO_1", 0 }, + { "HAEL_NT_CONVO_2", 0 }, + { "HAEL_NT_CONVO_3", 0 }, + { "HAEL_NT_CONVO_4", 0 }, + }); - // If there's an alternating conversation, indices should be provided using the conversationID variables - self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID() }); + // If there's an alternating conversation, indices should be provided using the conversationID variables + self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID() }); } diff --git a/dScripts/NtHaelServer.h b/dScripts/NtHaelServer.h index 8e3dbe47..4597198f 100644 --- a/dScripts/NtHaelServer.h +++ b/dScripts/NtHaelServer.h @@ -2,5 +2,5 @@ #include "NtFactionSpyServer.h" class NtHaelServer : public NtFactionSpyServer { - void SetVariables(Entity *self) override; + void SetVariables(Entity* self) override; }; diff --git a/dScripts/NtImagBeamBuffer.cpp b/dScripts/NtImagBeamBuffer.cpp index 067a8d61..d98a7403 100644 --- a/dScripts/NtImagBeamBuffer.cpp +++ b/dScripts/NtImagBeamBuffer.cpp @@ -2,65 +2,52 @@ #include "EntityManager.h" #include "SkillComponent.h" -void NtImagBeamBuffer::OnStartup(Entity* self) -{ - self->SetProximityRadius(100, "ImagZone"); +void NtImagBeamBuffer::OnStartup(Entity* self) { + self->SetProximityRadius(100, "ImagZone"); - self->AddTimer("BuffImag", 2.0f); + self->AddTimer("BuffImag", 2.0f); } -void NtImagBeamBuffer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (name != "ImagZone" || !entering->IsPlayer()) - { - return; - } +void NtImagBeamBuffer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (name != "ImagZone" || !entering->IsPlayer()) { + return; + } - if (status == "ENTER") - { - const auto& iter = std::find(m_EntitiesInProximity.begin(), m_EntitiesInProximity.end(), entering->GetObjectID()); + if (status == "ENTER") { + const auto& iter = std::find(m_EntitiesInProximity.begin(), m_EntitiesInProximity.end(), entering->GetObjectID()); - if (iter == m_EntitiesInProximity.end()) - { - m_EntitiesInProximity.push_back(entering->GetObjectID()); - } - } - else if (status == "LEAVE") - { - const auto& iter = std::find(m_EntitiesInProximity.begin(), m_EntitiesInProximity.end(), entering->GetObjectID()); + if (iter == m_EntitiesInProximity.end()) { + m_EntitiesInProximity.push_back(entering->GetObjectID()); + } + } else if (status == "LEAVE") { + const auto& iter = std::find(m_EntitiesInProximity.begin(), m_EntitiesInProximity.end(), entering->GetObjectID()); - if (iter != m_EntitiesInProximity.end()) - { - m_EntitiesInProximity.erase(iter); - } - } + if (iter != m_EntitiesInProximity.end()) { + m_EntitiesInProximity.erase(iter); + } + } } -void NtImagBeamBuffer::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName != "BuffImag") - { - return; - } +void NtImagBeamBuffer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName != "BuffImag") { + return; + } - auto* skillComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - for (const auto entityID : m_EntitiesInProximity) - { - auto* entity = EntityManager::Instance()->GetEntity(entityID); + for (const auto entityID : m_EntitiesInProximity) { + auto* entity = EntityManager::Instance()->GetEntity(entityID); - if (entity == nullptr) - { - continue; - } + if (entity == nullptr) { + continue; + } - skillComponent->CalculateBehavior(1311, 30235, entityID, true); - } + skillComponent->CalculateBehavior(1311, 30235, entityID, true); + } - self->AddTimer("BuffImag", 2.0f); + self->AddTimer("BuffImag", 2.0f); } diff --git a/dScripts/NtImagBeamBuffer.h b/dScripts/NtImagBeamBuffer.h index 4c6c7fc3..38e3819c 100644 --- a/dScripts/NtImagBeamBuffer.h +++ b/dScripts/NtImagBeamBuffer.h @@ -4,10 +4,10 @@ class NtImagBeamBuffer : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - std::vector m_EntitiesInProximity = {}; + std::vector m_EntitiesInProximity = {}; }; diff --git a/dScripts/NtOverbuildServer.cpp b/dScripts/NtOverbuildServer.cpp index 7bc62f50..8411e55b 100644 --- a/dScripts/NtOverbuildServer.cpp +++ b/dScripts/NtOverbuildServer.cpp @@ -1,30 +1,30 @@ #include "NtOverbuildServer.h" #include "EntityManager.h" -void NtOverbuildServer::SetVariables(Entity *self) { - self->SetVar(m_SpyProximityVariable, 30.0f); +void NtOverbuildServer::SetVariables(Entity* self) { + self->SetVar(m_SpyProximityVariable, 30.0f); - self->SetVar(m_SpyDataVariable, { - NT_FACTION_SPY_OVERBUILD, 13891, 1320 - }); + self->SetVar(m_SpyDataVariable, { + NT_FACTION_SPY_OVERBUILD, 13891, 1320 + }); - self->SetVar>(m_SpyDialogueTableVariable, { - { "OVERBUILD_NT_CONVO_1", 0 }, - { "OVERBUILD_NT_CONVO_2", 1 }, - { "OVERBUILD_NT_CONVO_3", 0 }, - { "OVERBUILD_NT_CONVO_4", 1 }, - { "OVERBUILD_NT_CONVO_5", 0 }, - { "OVERBUILD_NT_CONVO_6", 1 }, - { "OVERBUILD_NT_CONVO_7", 0 }, - }); + self->SetVar>(m_SpyDialogueTableVariable, { + { "OVERBUILD_NT_CONVO_1", 0 }, + { "OVERBUILD_NT_CONVO_2", 1 }, + { "OVERBUILD_NT_CONVO_3", 0 }, + { "OVERBUILD_NT_CONVO_4", 1 }, + { "OVERBUILD_NT_CONVO_5", 0 }, + { "OVERBUILD_NT_CONVO_6", 1 }, + { "OVERBUILD_NT_CONVO_7", 0 }, + }); - // Find the second object Dr. Overbuild interacts with - LWOOBJID otherConvoObjectID = LWOOBJID_EMPTY; - for (auto* otherConvoObject : EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(self->GetVar(m_OtherEntitiesGroupVariable)))) { - otherConvoObjectID = otherConvoObject->GetObjectID(); - break; - } + // Find the second object Dr. Overbuild interacts with + LWOOBJID otherConvoObjectID = LWOOBJID_EMPTY; + for (auto* otherConvoObject : EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(self->GetVar(m_OtherEntitiesGroupVariable)))) { + otherConvoObjectID = otherConvoObject->GetObjectID(); + break; + } - // If there's an alternating conversation, indices should be provided using the conversationID variables - self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID(), otherConvoObjectID }); + // If there's an alternating conversation, indices should be provided using the conversationID variables + self->SetVar>(m_SpyCinematicObjectsVariable, { self->GetObjectID(), otherConvoObjectID }); } diff --git a/dScripts/NtOverbuildServer.h b/dScripts/NtOverbuildServer.h index 301dd4e3..a34d117e 100644 --- a/dScripts/NtOverbuildServer.h +++ b/dScripts/NtOverbuildServer.h @@ -2,6 +2,6 @@ #include "NtFactionSpyServer.h" class NtOverbuildServer : public NtFactionSpyServer { - void SetVariables(Entity *self) override; - const std::u16string m_OtherEntitiesGroupVariable = u"SpyConvo2Group"; + void SetVariables(Entity* self) override; + const std::u16string m_OtherEntitiesGroupVariable = u"SpyConvo2Group"; }; diff --git a/dScripts/NtParadoxPanelServer.cpp b/dScripts/NtParadoxPanelServer.cpp index 556002fe..06482c82 100644 --- a/dScripts/NtParadoxPanelServer.cpp +++ b/dScripts/NtParadoxPanelServer.cpp @@ -4,8 +4,7 @@ #include "EntityManager.h" #include "Character.h" -void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) -{ +void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"bActive", 1, 0, user->GetObjectID(), "", user->GetSystemAddress()); GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); @@ -16,18 +15,15 @@ void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) const auto playerID = user->GetObjectID(); - for (const auto mission : tPlayerOnMissions) - { - if (missionComponent->GetMissionState(mission) != MissionState::MISSION_STATE_ACTIVE) - { + for (const auto mission : tPlayerOnMissions) { + if (missionComponent->GetMissionState(mission) != MissionState::MISSION_STATE_ACTIVE) { continue; } - self->AddCallbackTimer(2, [this, self, playerID] () { + self->AddCallbackTimer(2, [this, self, playerID]() { auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { + if (player == nullptr) { return; } @@ -36,11 +32,11 @@ void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) player->GetCharacter()->SetPlayerFlag(flag, true); GameMessages::SendPlayAnimation(player, u"rebuild-celebrate"); - + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SparkStop", 0, 0, player->GetObjectID(), "", player->GetSystemAddress()); GameMessages::SendSetStunned(player->GetObjectID(), eStunState::POP, player->GetSystemAddress(), LWOOBJID_EMPTY, false, false, true, false, true, true, false, false, true); self->SetVar(u"bActive", false); - }); + }); GameMessages::SendPlayAnimation(user, u"nexus-powerpanel", 6.0f); GameMessages::SendSetStunned(user->GetObjectID(), eStunState::PUSH, user->GetSystemAddress(), LWOOBJID_EMPTY, false, false, true, false, true, true, false, false, true); return; @@ -48,17 +44,16 @@ void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) GameMessages::SendPlayAnimation(user, shockAnim); - const auto dir = self->GetRotation().GetRightVector(); + const auto dir = self->GetRotation().GetRightVector(); - GameMessages::SendKnockback(user->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 0, {dir.x * 15, 5, dir.z * 15}); + GameMessages::SendKnockback(user->GetObjectID(), self->GetObjectID(), self->GetObjectID(), 0, { dir.x * 15, 5, dir.z * 15 }); GameMessages::SendPlayFXEffect(self, 6432, u"create", "console_sparks", LWOOBJID_EMPTY, 1.0, 1.0, true); - - self->AddCallbackTimer(2, [this, self, playerID] () { + + self->AddCallbackTimer(2, [this, self, playerID]() { auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { + if (player == nullptr) { return; } @@ -67,5 +62,5 @@ void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) GameMessages::SendStopFXEffect(self, true, "console_sparks"); self->SetVar(u"bActive", false); - }); + }); } diff --git a/dScripts/NtParadoxPanelServer.h b/dScripts/NtParadoxPanelServer.h index e966e376..796a599b 100644 --- a/dScripts/NtParadoxPanelServer.h +++ b/dScripts/NtParadoxPanelServer.h @@ -8,6 +8,6 @@ public: private: std::u16string shockAnim = u"knockback-recovery"; float fxTime = 2.0; - std::vector tPlayerOnMissions = {1278, 1279, 1280, 1281}; + std::vector tPlayerOnMissions = { 1278, 1279, 1280, 1281 }; }; diff --git a/dScripts/NtParadoxTeleServer.cpp b/dScripts/NtParadoxTeleServer.cpp index 84222374..8003e93f 100644 --- a/dScripts/NtParadoxTeleServer.cpp +++ b/dScripts/NtParadoxTeleServer.cpp @@ -3,125 +3,111 @@ #include "EntityManager.h" #include "MissionComponent.h" -void NtParadoxTeleServer::OnStartup(Entity* self) -{ - self->SetProximityRadius(5, "teleport"); +void NtParadoxTeleServer::OnStartup(Entity* self) { + self->SetProximityRadius(5, "teleport"); } -void NtParadoxTeleServer::OnPlayerLoaded(Entity* self, Entity* player) -{ - +void NtParadoxTeleServer::OnPlayerLoaded(Entity* self, Entity* player) { + } -void NtParadoxTeleServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (status != "ENTER" || !entering->IsPlayer() || name != "teleport") return; +void NtParadoxTeleServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (status != "ENTER" || !entering->IsPlayer() || name != "teleport") return; - auto* player = entering; - const auto playerID = player->GetObjectID(); + auto* player = entering; + const auto playerID = player->GetObjectID(); - const auto iter = m_TeleportingPlayerTable.find(playerID); - if (iter == m_TeleportingPlayerTable.end()) m_TeleportingPlayerTable[playerID] = false; - const auto bPlayerBeingTeleported = m_TeleportingPlayerTable[playerID]; + const auto iter = m_TeleportingPlayerTable.find(playerID); + if (iter == m_TeleportingPlayerTable.end()) m_TeleportingPlayerTable[playerID] = false; + const auto bPlayerBeingTeleported = m_TeleportingPlayerTable[playerID]; - if (player->IsPlayer() && !bPlayerBeingTeleported) - { - GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); + if (player->IsPlayer() && !bPlayerBeingTeleported) { + GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - GameMessages::SendPlayAnimation(player, u"teledeath", 4.0f); + GameMessages::SendPlayAnimation(player, u"teledeath", 4.0f); - const auto animTime = 2; + const auto animTime = 2; - self->AddCallbackTimer(animTime, [this, self, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); + self->AddCallbackTimer(animTime, [this, self, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - TeleportPlayer(self, player); - }); - } + TeleportPlayer(self, player); + }); + } - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } } -void NtParadoxTeleServer::TeleportPlayer(Entity* self, Entity* player) -{ - auto destinationGroup = self->GetVar(u"teleGroup"); - auto* destination = self; +void NtParadoxTeleServer::TeleportPlayer(Entity* self, Entity* player) { + auto destinationGroup = self->GetVar(u"teleGroup"); + auto* destination = self; - if (!destinationGroup.empty()) - { - const auto& groupObjs = EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(destinationGroup)); + if (!destinationGroup.empty()) { + const auto& groupObjs = EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(destinationGroup)); - if (!groupObjs.empty()) - { - destination = groupObjs[0]; - } - } + if (!groupObjs.empty()) { + destination = groupObjs[0]; + } + } - const auto destPosition = destination->GetPosition(); - const auto destRotation = destination->GetRotation(); + const auto destPosition = destination->GetPosition(); + const auto destRotation = destination->GetRotation(); - auto teleCinematic = self->GetVar(u"Cinematic"); + auto teleCinematic = self->GetVar(u"Cinematic"); - if (!teleCinematic.empty()) - { - const auto teleCinematicUname = teleCinematic; - GameMessages::SendPlayCinematic(player->GetObjectID(), teleCinematicUname, player->GetSystemAddress()); - } + if (!teleCinematic.empty()) { + const auto teleCinematicUname = teleCinematic; + GameMessages::SendPlayCinematic(player->GetObjectID(), teleCinematicUname, player->GetSystemAddress()); + } - GameMessages::SendTeleport(player->GetObjectID(), destPosition, destRotation, player->GetSystemAddress(), true); + GameMessages::SendTeleport(player->GetObjectID(), destPosition, destRotation, player->GetSystemAddress(), true); - GameMessages::SendPlayAnimation(player, u"paradox-teleport-in", 4.0f); + GameMessages::SendPlayAnimation(player, u"paradox-teleport-in", 4.0f); - const auto animTime = 2; + const auto animTime = 2; - const auto playerID = player->GetObjectID(); - - self->AddCallbackTimer(animTime, [this, self, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); + const auto playerID = player->GetObjectID(); - if (player == nullptr) - { - return; - } + self->AddCallbackTimer(animTime, [this, self, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - UnlockPlayer(self, player); - }); + if (player == nullptr) { + return; + } - const auto useSound = self->GetVar(u"sound1"); + UnlockPlayer(self, player); + }); - if (!useSound.empty()) - { - GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), useSound); - } + const auto useSound = self->GetVar(u"sound1"); + + if (!useSound.empty()) { + GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), useSound); + } } -void NtParadoxTeleServer::UnlockPlayer(Entity* self, Entity* player) -{ - const auto playerID = player->GetObjectID(); +void NtParadoxTeleServer::UnlockPlayer(Entity* self, Entity* player) { + const auto playerID = player->GetObjectID(); - m_TeleportingPlayerTable[playerID] = false; + m_TeleportingPlayerTable[playerID] = false; - GameMessages::SendSetStunned(playerID, POP, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); + GameMessages::SendSetStunned(playerID, POP, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - auto teleCinematic = self->GetVar(u"Cinematic"); + auto teleCinematic = self->GetVar(u"Cinematic"); - if (!teleCinematic.empty()) - { - const auto teleCinematicUname = teleCinematic; - GameMessages::SendEndCinematic(player->GetObjectID(), teleCinematicUname, player->GetSystemAddress()); - } + if (!teleCinematic.empty()) { + const auto teleCinematicUname = teleCinematic; + GameMessages::SendEndCinematic(player->GetObjectID(), teleCinematicUname, player->GetSystemAddress()); + } } diff --git a/dScripts/NtParadoxTeleServer.h b/dScripts/NtParadoxTeleServer.h index 9f73bd85..b094411a 100644 --- a/dScripts/NtParadoxTeleServer.h +++ b/dScripts/NtParadoxTeleServer.h @@ -5,11 +5,11 @@ class NtParadoxTeleServer : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnPlayerLoaded(Entity* self, Entity* player) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - void TeleportPlayer(Entity* self, Entity* player); - void UnlockPlayer(Entity* self, Entity* player); + void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void TeleportPlayer(Entity* self, Entity* player); + void UnlockPlayer(Entity* self, Entity* player); private: - std::map m_TeleportingPlayerTable; + std::map m_TeleportingPlayerTable; }; diff --git a/dScripts/NtSentinelWalkwayServer.cpp b/dScripts/NtSentinelWalkwayServer.cpp index 3d7c75a3..7b943172 100644 --- a/dScripts/NtSentinelWalkwayServer.cpp +++ b/dScripts/NtSentinelWalkwayServer.cpp @@ -3,47 +3,41 @@ #include "EntityManager.h" #include "MissionComponent.h" -void NtSentinelWalkwayServer::OnStartup(Entity* self) -{ - auto* phantomPhysicsComponent = self->GetComponent(); - - if (phantomPhysicsComponent == nullptr) - { - return; - } +void NtSentinelWalkwayServer::OnStartup(Entity* self) { + auto* phantomPhysicsComponent = self->GetComponent(); - auto force = self->GetVar(u"force"); + if (phantomPhysicsComponent == nullptr) { + return; + } - if (force == 0) - { - force = 115; - } + auto force = self->GetVar(u"force"); - const auto forward = self->GetRotation().GetRightVector() * -1; + if (force == 0) { + force = 115; + } - phantomPhysicsComponent->SetEffectType(0); // PUSH - phantomPhysicsComponent->SetDirectionalMultiplier(force); - phantomPhysicsComponent->SetDirection(forward); - phantomPhysicsComponent->SetPhysicsEffectActive(true); + const auto forward = self->GetRotation().GetRightVector() * -1; - EntityManager::Instance()->SerializeEntity(self); + phantomPhysicsComponent->SetEffectType(0); // PUSH + phantomPhysicsComponent->SetDirectionalMultiplier(force); + phantomPhysicsComponent->SetDirection(forward); + phantomPhysicsComponent->SetPhysicsEffectActive(true); - self->SetProximityRadius(3, "speedboost"); + EntityManager::Instance()->SerializeEntity(self); + + self->SetProximityRadius(3, "speedboost"); } -void NtSentinelWalkwayServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (name != "speedboost" || !entering->IsPlayer() || status != "ENTER") - { - return; - } +void NtSentinelWalkwayServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (name != "speedboost" || !entering->IsPlayer() || status != "ENTER") { + return; + } - auto* player = entering; + auto* player = entering; - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } } diff --git a/dScripts/NtSleepingGuard.cpp b/dScripts/NtSleepingGuard.cpp index 74bc50f0..597b5997 100644 --- a/dScripts/NtSleepingGuard.cpp +++ b/dScripts/NtSleepingGuard.cpp @@ -2,13 +2,11 @@ #include "GameMessages.h" #include "MissionComponent.h" -void NtSleepingGuard::OnStartup(Entity* self) -{ +void NtSleepingGuard::OnStartup(Entity* self) { self->SetNetworkVar(u"asleep", true); } -void NtSleepingGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* target) -{ +void NtSleepingGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* target) { if (!self->GetNetworkVar(u"asleep")) return; @@ -23,18 +21,15 @@ void NtSleepingGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* auto* missionComponent = target->GetComponent(); - if (missionComponent != nullptr) - { + if (missionComponent != nullptr) { missionComponent->CompleteMission(1346); } self->AddTimer("AsleepAgain", 5.0f); } -void NtSleepingGuard::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "AsleepAgain") - { +void NtSleepingGuard::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "AsleepAgain") { self->SetNetworkVar(u"asleep", true); } } diff --git a/dScripts/NtVandaServer.cpp b/dScripts/NtVandaServer.cpp index 29750101..bfc35203 100644 --- a/dScripts/NtVandaServer.cpp +++ b/dScripts/NtVandaServer.cpp @@ -1,13 +1,13 @@ #include "NtVandaServer.h" #include "InventoryComponent.h" -void NtVandaServer::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { +void NtVandaServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { - // Removes the alien parts after completing the mission - if (missionID == m_AlienPartMissionID && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { - auto* inventoryComponent = target->GetComponent(); - for (const auto& alienPartLot : m_AlienPartLots) { - inventoryComponent->RemoveItem(alienPartLot, 1); - } - } + // Removes the alien parts after completing the mission + if (missionID == m_AlienPartMissionID && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { + auto* inventoryComponent = target->GetComponent(); + for (const auto& alienPartLot : m_AlienPartLots) { + inventoryComponent->RemoveItem(alienPartLot, 1); + } + } } diff --git a/dScripts/NtVandaServer.h b/dScripts/NtVandaServer.h index 84d494fc..69e868f5 100644 --- a/dScripts/NtVandaServer.h +++ b/dScripts/NtVandaServer.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class NtVandaServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; - const uint32_t m_AlienPartMissionID = 1183; - const std::vector m_AlienPartLots = { 12479, 12480, 12481 }; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + const uint32_t m_AlienPartMissionID = 1183; + const std::vector m_AlienPartLots = { 12479, 12480, 12481 }; }; diff --git a/dScripts/NtVentureCannonServer.cpp b/dScripts/NtVentureCannonServer.cpp index 66172733..d7f4cb99 100644 --- a/dScripts/NtVentureCannonServer.cpp +++ b/dScripts/NtVentureCannonServer.cpp @@ -2,133 +2,121 @@ #include "GameMessages.h" #include "EntityManager.h" -void NtVentureCannonServer::OnUse(Entity* self, Entity* user) -{ - auto* player = user; - const auto playerID = player->GetObjectID(); +void NtVentureCannonServer::OnUse(Entity* self, Entity* user) { + auto* player = user; + const auto playerID = player->GetObjectID(); - auto enterCinematic = self->GetVar(u"EnterCinematic"); + auto enterCinematic = self->GetVar(u"EnterCinematic"); - if (enterCinematic.empty()) - { - return; - } + if (enterCinematic.empty()) { + return; + } - self->SetNetworkVar(u"bIsInUse", true); + self->SetNetworkVar(u"bIsInUse", true); - GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); + GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - auto destPosition = self->GetPosition(); + auto destPosition = self->GetPosition(); - destPosition.y += 5 - 1.57f; + destPosition.y += 5 - 1.57f; - auto destRotation = self->GetRotation(); - - GameMessages::SendTeleport(playerID, destPosition, destRotation, player->GetSystemAddress(), true); + auto destRotation = self->GetRotation(); - GameMessages::SendPlayAnimation(player, u"scale-down", 4.0f); + GameMessages::SendTeleport(playerID, destPosition, destRotation, player->GetSystemAddress(), true); - const auto enterCinematicUname = enterCinematic; - GameMessages::SendPlayCinematic(player->GetObjectID(), enterCinematicUname, player->GetSystemAddress()); + GameMessages::SendPlayAnimation(player, u"scale-down", 4.0f); - GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), "{e8bf79ce-7453-4a7d-b872-fee65e97ff15}"); - - self->AddCallbackTimer(3, [this, self]() { - self->SetNetworkVar(u"bIsInUse", false); - }); + const auto enterCinematicUname = enterCinematic; + GameMessages::SendPlayCinematic(player->GetObjectID(), enterCinematicUname, player->GetSystemAddress()); - self->AddCallbackTimer(1.5f, [this, self, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); + GameMessages::SendPlayNDAudioEmitter(player, player->GetSystemAddress(), "{e8bf79ce-7453-4a7d-b872-fee65e97ff15}"); - if (player == nullptr) - { - return; - } + self->AddCallbackTimer(3, [this, self]() { + self->SetNetworkVar(u"bIsInUse", false); + }); - EnterCannonEnded(self, player); - }); + self->AddCallbackTimer(1.5f, [this, self, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); + + if (player == nullptr) { + return; + } + + EnterCannonEnded(self, player); + }); } -void NtVentureCannonServer::EnterCannonEnded(Entity* self, Entity* player) -{ - const auto playerID = player->GetObjectID(); +void NtVentureCannonServer::EnterCannonEnded(Entity* self, Entity* player) { + const auto playerID = player->GetObjectID(); - const auto& cannonEffectGroup = EntityManager::Instance()->GetEntitiesInGroup("cannonEffect"); + const auto& cannonEffectGroup = EntityManager::Instance()->GetEntitiesInGroup("cannonEffect"); - if (!cannonEffectGroup.empty()) - { - auto* cannonEffect = cannonEffectGroup[0]; + if (!cannonEffectGroup.empty()) { + auto* cannonEffect = cannonEffectGroup[0]; - GameMessages::SendPlayFXEffect(cannonEffect, 6036, u"create", "cannon_blast", LWOOBJID_EMPTY, 1, 1, true); - - GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(cannonEffect, u"camshake-bridge", cannonEffect->GetObjectID(), 100); - } + GameMessages::SendPlayFXEffect(cannonEffect, 6036, u"create", "cannon_blast", LWOOBJID_EMPTY, 1, 1, true); - FirePlayer(self, player); + GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(cannonEffect, u"camshake-bridge", cannonEffect->GetObjectID(), 100); + } - auto exitCinematic = self->GetVar(u"ExitCinematic"); + FirePlayer(self, player); - if (exitCinematic.empty()) - { - UnlockCannonPlayer(self, player); + auto exitCinematic = self->GetVar(u"ExitCinematic"); - return; - } + if (exitCinematic.empty()) { + UnlockCannonPlayer(self, player); - const auto exitCinematicUname = exitCinematic; - GameMessages::SendPlayCinematic(player->GetObjectID(), exitCinematicUname, player->GetSystemAddress(), - true, true, true, false, 0, false, 0, false, false - ); + return; + } - self->AddCallbackTimer(1.5f, [this, self, playerID]() { - auto* player = EntityManager::Instance()->GetEntity(playerID); + const auto exitCinematicUname = exitCinematic; + GameMessages::SendPlayCinematic(player->GetObjectID(), exitCinematicUname, player->GetSystemAddress(), + true, true, true, false, 0, false, 0, false, false + ); - if (player == nullptr) - { - return; - } + self->AddCallbackTimer(1.5f, [this, self, playerID]() { + auto* player = EntityManager::Instance()->GetEntity(playerID); - ExitCannonEnded(self, player); - }); + if (player == nullptr) { + return; + } + + ExitCannonEnded(self, player); + }); } -void NtVentureCannonServer::ExitCannonEnded(Entity* self, Entity* player) -{ - UnlockCannonPlayer(self, player); +void NtVentureCannonServer::ExitCannonEnded(Entity* self, Entity* player) { + UnlockCannonPlayer(self, player); } -void NtVentureCannonServer::UnlockCannonPlayer(Entity* self, Entity* player) -{ - GameMessages::SendSetStunned(player->GetObjectID(), POP, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true - ); +void NtVentureCannonServer::UnlockCannonPlayer(Entity* self, Entity* player) { + GameMessages::SendSetStunned(player->GetObjectID(), POP, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true + ); - self->SetNetworkVar(u"bIsInUse", false); + self->SetNetworkVar(u"bIsInUse", false); - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } -void NtVentureCannonServer::FirePlayer(Entity* self, Entity* player) -{ - auto destinationGroup = self->GetVar(u"teleGroup"); - auto* destination = self; +void NtVentureCannonServer::FirePlayer(Entity* self, Entity* player) { + auto destinationGroup = self->GetVar(u"teleGroup"); + auto* destination = self; - if (!destinationGroup.empty()) - { - const auto& groupObjs = EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(destinationGroup)); + if (!destinationGroup.empty()) { + const auto& groupObjs = EntityManager::Instance()->GetEntitiesInGroup(GeneralUtils::UTF16ToWTF8(destinationGroup)); - if (!groupObjs.empty()) - { - destination = groupObjs[0]; - } - } + if (!groupObjs.empty()) { + destination = groupObjs[0]; + } + } - const auto destPosition = destination->GetPosition(); - const auto destRotation = destination->GetRotation(); + const auto destPosition = destination->GetPosition(); + const auto destRotation = destination->GetRotation(); - GameMessages::SendTeleport(player->GetObjectID(), destPosition, destRotation, player->GetSystemAddress(), true); + GameMessages::SendTeleport(player->GetObjectID(), destPosition, destRotation, player->GetSystemAddress(), true); - GameMessages::SendPlayAnimation(player, u"venture-cannon-out", 4.0f); + GameMessages::SendPlayAnimation(player, u"venture-cannon-out", 4.0f); } diff --git a/dScripts/NtVentureCannonServer.h b/dScripts/NtVentureCannonServer.h index 5ad6a54e..a5998f14 100644 --- a/dScripts/NtVentureCannonServer.h +++ b/dScripts/NtVentureCannonServer.h @@ -4,9 +4,9 @@ class NtVentureCannonServer : public CppScripts::Script { public: - void OnUse(Entity* self, Entity* user) override; - void EnterCannonEnded(Entity* self, Entity* player); - void ExitCannonEnded(Entity* self, Entity* player); - void UnlockCannonPlayer(Entity* self, Entity* player); - void FirePlayer(Entity* self, Entity* player); + void OnUse(Entity* self, Entity* user) override; + void EnterCannonEnded(Entity* self, Entity* player); + void ExitCannonEnded(Entity* self, Entity* player); + void UnlockCannonPlayer(Entity* self, Entity* player); + void FirePlayer(Entity* self, Entity* player); }; diff --git a/dScripts/NtVentureSpeedPadServer.cpp b/dScripts/NtVentureSpeedPadServer.cpp index 19a752d2..0995d1df 100644 --- a/dScripts/NtVentureSpeedPadServer.cpp +++ b/dScripts/NtVentureSpeedPadServer.cpp @@ -2,32 +2,27 @@ #include "SkillComponent.h" #include "MissionComponent.h" -void NtVentureSpeedPadServer::OnStartup(Entity* self) -{ - self->SetProximityRadius(3, "speedboost"); +void NtVentureSpeedPadServer::OnStartup(Entity* self) { + self->SetProximityRadius(3, "speedboost"); } -void NtVentureSpeedPadServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (name != "speedboost" || !entering->IsPlayer() || status != "ENTER") - { - return; - } +void NtVentureSpeedPadServer::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (name != "speedboost" || !entering->IsPlayer() || status != "ENTER") { + return; + } - auto* player = entering; + auto* player = entering; - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) - { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); - } + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + } - auto* skillComponent = player->GetComponent(); + auto* skillComponent = player->GetComponent(); - if (skillComponent != nullptr) - { - skillComponent->CalculateBehavior(927, 18913, player->GetObjectID(), true); - } + if (skillComponent != nullptr) { + skillComponent->CalculateBehavior(927, 18913, player->GetObjectID(), true); + } } diff --git a/dScripts/NtXRayServer.cpp b/dScripts/NtXRayServer.cpp index b65cf65b..3b281b79 100644 --- a/dScripts/NtXRayServer.cpp +++ b/dScripts/NtXRayServer.cpp @@ -1,14 +1,12 @@ #include "NtXRayServer.h" #include "SkillComponent.h" -void NtXRayServer::OnCollisionPhantom(Entity* self, Entity* target) -{ - auto* skillComponent = target->GetComponent(); - - if (skillComponent == nullptr) - { - return; - } +void NtXRayServer::OnCollisionPhantom(Entity* self, Entity* target) { + auto* skillComponent = target->GetComponent(); - skillComponent->CalculateBehavior(1220, 27641, target->GetObjectID()); + if (skillComponent == nullptr) { + return; + } + + skillComponent->CalculateBehavior(1220, 27641, target->GetObjectID()); } diff --git a/dScripts/PersonalFortress.cpp b/dScripts/PersonalFortress.cpp index 88ac9163..e7e89e80 100644 --- a/dScripts/PersonalFortress.cpp +++ b/dScripts/PersonalFortress.cpp @@ -4,54 +4,47 @@ #include "DestroyableComponent.h" #include "EntityManager.h" -void PersonalFortress::OnStartup(Entity* self) -{ - auto* owner = self->GetOwner(); - self->AddTimer("FireSkill", 1.5); - GameMessages::SendSetStunned(owner->GetObjectID(), PUSH, owner->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true, true, true - ); - - auto* destroyableComponent = owner->GetComponent(); +void PersonalFortress::OnStartup(Entity* self) { + auto* owner = self->GetOwner(); + self->AddTimer("FireSkill", 1.5); + GameMessages::SendSetStunned(owner->GetObjectID(), PUSH, owner->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true, true, true + ); - if (destroyableComponent != nullptr) - { - destroyableComponent->PushImmunity(); - } + auto* destroyableComponent = owner->GetComponent(); - EntityManager::Instance()->SerializeEntity(owner); + if (destroyableComponent != nullptr) { + destroyableComponent->PushImmunity(); + } + + EntityManager::Instance()->SerializeEntity(owner); } -void PersonalFortress::OnDie(Entity* self, Entity* killer) -{ - auto* owner = self->GetOwner(); - GameMessages::SendSetStunned(owner->GetObjectID(), POP, owner->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true, true, true - ); +void PersonalFortress::OnDie(Entity* self, Entity* killer) { + auto* owner = self->GetOwner(); + GameMessages::SendSetStunned(owner->GetObjectID(), POP, owner->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true, true, true + ); - auto* destroyableComponent = owner->GetComponent(); + auto* destroyableComponent = owner->GetComponent(); - if (destroyableComponent != nullptr) - { - destroyableComponent->PopImmunity(); - } + if (destroyableComponent != nullptr) { + destroyableComponent->PopImmunity(); + } - EntityManager::Instance()->SerializeEntity(owner); + EntityManager::Instance()->SerializeEntity(owner); } -void PersonalFortress::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "FireSkill") - { - auto* owner = self->GetOwner(); +void PersonalFortress::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "FireSkill") { + auto* owner = self->GetOwner(); - auto* skillComponent = self->GetComponent(); + auto* skillComponent = self->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - skillComponent->CalculateBehavior(650, 13364, LWOOBJID_EMPTY, true, false); - } + skillComponent->CalculateBehavior(650, 13364, LWOOBJID_EMPTY, true, false); + } } diff --git a/dScripts/PersonalFortress.h b/dScripts/PersonalFortress.h index 5cae24ba..4d69ba1d 100644 --- a/dScripts/PersonalFortress.h +++ b/dScripts/PersonalFortress.h @@ -6,7 +6,7 @@ class PersonalFortress : public CppScripts::Script public: void OnStartup(Entity* self) override; - void OnDie(Entity* self, Entity* killer) override; + void OnDie(Entity* self, Entity* killer) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/PetDigBuild.cpp b/dScripts/PetDigBuild.cpp index 7ff88fff..ae159575 100644 --- a/dScripts/PetDigBuild.cpp +++ b/dScripts/PetDigBuild.cpp @@ -3,47 +3,47 @@ #include "MissionComponent.h" void PetDigBuild::OnRebuildComplete(Entity* self, Entity* target) { - auto flagNumber = self->GetVar(u"flagNum"); + auto flagNumber = self->GetVar(u"flagNum"); - EntityInfo info {}; - auto pos = self->GetPosition(); - pos.SetY(pos.GetY() + 0.5f); - info.pos = pos; - info.rot = self->GetRotation(); - info.spawnerID = self->GetSpawnerID(); - info.settings = { - new LDFData(u"builder", target->GetObjectID()), - new LDFData(u"X", self->GetObjectID()) - }; + EntityInfo info{}; + auto pos = self->GetPosition(); + pos.SetY(pos.GetY() + 0.5f); + info.pos = pos; + info.rot = self->GetRotation(); + info.spawnerID = self->GetSpawnerID(); + info.settings = { + new LDFData(u"builder", target->GetObjectID()), + new LDFData(u"X", self->GetObjectID()) + }; - if (!flagNumber.empty()) { - info.lot = 7410; // Normal GF treasure - info.settings.push_back(new LDFData(u"groupID", u"Flag" + flagNumber)); - } else { - auto* missionComponent = target->GetComponent(); - if (missionComponent != nullptr && missionComponent->GetMissionState(746) == MissionState::MISSION_STATE_ACTIVE) { - info.lot = 9307; // Special Captain Jack treasure that drops a mission item - } else { - info.lot = 3495; // Normal AG treasure - } - } + if (!flagNumber.empty()) { + info.lot = 7410; // Normal GF treasure + info.settings.push_back(new LDFData(u"groupID", u"Flag" + flagNumber)); + } else { + auto* missionComponent = target->GetComponent(); + if (missionComponent != nullptr && missionComponent->GetMissionState(746) == MissionState::MISSION_STATE_ACTIVE) { + info.lot = 9307; // Special Captain Jack treasure that drops a mission item + } else { + info.lot = 3495; // Normal AG treasure + } + } - auto* treasure = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(treasure); - self->SetVar(u"chestObj", treasure->GetObjectID()); + auto* treasure = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(treasure); + self->SetVar(u"chestObj", treasure->GetObjectID()); } void PetDigBuild::OnDie(Entity* self, Entity* killer) { - auto treasureID = self->GetVar(u"chestObj"); - if (treasureID == LWOOBJID_EMPTY) - return; + auto treasureID = self->GetVar(u"chestObj"); + if (treasureID == LWOOBJID_EMPTY) + return; - auto treasure = EntityManager::Instance()->GetEntity(treasureID); - if (treasure == nullptr) - return; + auto treasure = EntityManager::Instance()->GetEntity(treasureID); + if (treasure == nullptr) + return; - // If the quick build expired and the treasure was not collected, hide the treasure - if (!treasure->GetIsDead()) { - treasure->Smash(self->GetObjectID(), SILENT); - } + // If the quick build expired and the treasure was not collected, hide the treasure + if (!treasure->GetIsDead()) { + treasure->Smash(self->GetObjectID(), SILENT); + } } diff --git a/dScripts/PetDigBuild.h b/dScripts/PetDigBuild.h index c70d9e84..f342d7bb 100644 --- a/dScripts/PetDigBuild.h +++ b/dScripts/PetDigBuild.h @@ -4,6 +4,6 @@ class PetDigBuild : public CppScripts::Script { public: - void OnRebuildComplete(Entity* self, Entity* target); - void OnDie(Entity* self, Entity* killer); + void OnRebuildComplete(Entity* self, Entity* target); + void OnDie(Entity* self, Entity* killer); }; diff --git a/dScripts/PetDigServer.cpp b/dScripts/PetDigServer.cpp index dc7e85dd..e26b079a 100644 --- a/dScripts/PetDigServer.cpp +++ b/dScripts/PetDigServer.cpp @@ -5,154 +5,151 @@ #include "Character.h" #include "PetComponent.h" -std::vector PetDigServer::treasures {}; +std::vector PetDigServer::treasures{}; -const DigInfo PetDigServer::defaultDigInfo = DigInfo { 3495, -1, -1, false, false, false, false }; +const DigInfo PetDigServer::defaultDigInfo = DigInfo{ 3495, -1, -1, false, false, false, false }; /** * Summary of all the special treasure behaviors, indexed by their lot */ -const std::map PetDigServer::digInfoMap { - // Regular treasures - {3495, defaultDigInfo}, +const std::map PetDigServer::digInfoMap{ + // Regular treasures + {3495, defaultDigInfo}, - // Pet cove treasure - {7612, DigInfo { 7612, -1, -1, false, false, false, false }}, + // Pet cove treasure + {7612, DigInfo { 7612, -1, -1, false, false, false, false }}, - // Gnarled Forest flag treasure - {7410, DigInfo { 7410, -1, -1, false, true, false, false }}, + // Gnarled Forest flag treasure + {7410, DigInfo { 7410, -1, -1, false, true, false, false }}, - // Gnarled Forest crab treasure - {9308, DigInfo { 9308, 7694, -1, false, false, false, false }}, + // Gnarled Forest crab treasure + {9308, DigInfo { 9308, 7694, -1, false, false, false, false }}, - // Avant Gardens mission treasure - {9307, DigInfo { 9307, -1, -1, false, true, false, true }}, + // Avant Gardens mission treasure + {9307, DigInfo { 9307, -1, -1, false, true, false, true }}, - // Avant Gardens bouncer treasure - {7559, DigInfo { 7559, -1, -1, false, false, true, false }}, + // Avant Gardens bouncer treasure + {7559, DigInfo { 7559, -1, -1, false, false, true, false }}, - // Crux Prime dragon treasure - {13098, DigInfo { 13098, 13067, 1298, false, false, false, false }}, + // Crux Prime dragon treasure + {13098, DigInfo { 13098, 13067, 1298, false, false, false, false }}, - // Bone treasure (can only be digged using the dragon) - {12192, DigInfo { 12192, -1, -1, true, false, false, false }}, + // Bone treasure (can only be digged using the dragon) + {12192, DigInfo { 12192, -1, -1, true, false, false, false }}, }; -void PetDigServer::OnStartup(Entity* self) -{ - treasures.push_back(self->GetObjectID()); - const auto digInfoIterator = digInfoMap.find(self->GetLOT()); - const auto digInfo = digInfoIterator != digInfoMap.end() ? digInfoIterator->second : defaultDigInfo; +void PetDigServer::OnStartup(Entity* self) { + treasures.push_back(self->GetObjectID()); + const auto digInfoIterator = digInfoMap.find(self->GetLOT()); + const auto digInfo = digInfoIterator != digInfoMap.end() ? digInfoIterator->second : defaultDigInfo; - // Reset any bouncers that might've been created by the previous dig - if (digInfo.bouncer) { - auto bounceNumber = GeneralUtils::UTF16ToWTF8(self->GetVar(u"BouncerNumber")); - auto bouncerSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncer" + bounceNumber); - auto switchSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncerSwitch" + bounceNumber); + // Reset any bouncers that might've been created by the previous dig + if (digInfo.bouncer) { + auto bounceNumber = GeneralUtils::UTF16ToWTF8(self->GetVar(u"BouncerNumber")); + auto bouncerSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncer" + bounceNumber); + auto switchSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncerSwitch" + bounceNumber); - for (auto* bouncerSpawner : bouncerSpawners) { - for (auto* bouncer : bouncerSpawner->m_Info.nodes) - bouncerSpawner->Deactivate(); - bouncerSpawner->Reset(); - } + for (auto* bouncerSpawner : bouncerSpawners) { + for (auto* bouncer : bouncerSpawner->m_Info.nodes) + bouncerSpawner->Deactivate(); + bouncerSpawner->Reset(); + } - for (auto* switchSpawner : switchSpawners) { - switchSpawner->Deactivate(); - switchSpawner->Reset(); - } - } + for (auto* switchSpawner : switchSpawners) { + switchSpawner->Deactivate(); + switchSpawner->Reset(); + } + } } -void PetDigServer::OnDie(Entity* self, Entity* killer) -{ - const auto iterator = std::find(treasures.begin(), treasures.end(), self->GetObjectID()); - if (iterator != treasures.end()) - { - treasures.erase(iterator); - } +void PetDigServer::OnDie(Entity* self, Entity* killer) { + const auto iterator = std::find(treasures.begin(), treasures.end(), self->GetObjectID()); + if (iterator != treasures.end()) { + treasures.erase(iterator); + } - auto* owner = killer->GetOwner(); - const auto digInfoIterator = digInfoMap.find(self->GetLOT()); - const auto digInfo = digInfoIterator != digInfoMap.end() ? digInfoIterator->second : defaultDigInfo; + auto* owner = killer->GetOwner(); + const auto digInfoIterator = digInfoMap.find(self->GetLOT()); + const auto digInfo = digInfoIterator != digInfoMap.end() ? digInfoIterator->second : defaultDigInfo; - if (digInfo.spawnLot >= 0) { - PetDigServer::SpawnPet(self, owner, digInfo); - } else if (digInfo.builderOnly) { + if (digInfo.spawnLot >= 0) { + PetDigServer::SpawnPet(self, owner, digInfo); + } else if (digInfo.builderOnly) { - // Some treasures may only be retrieved by the player that built the diggable - auto builder = self->GetVar(u"builder"); // Set by the pet dig build script - if (builder != owner->GetObjectID()) - return; - } else if (digInfo.xBuild) { - PetDigServer::HandleXBuildDig(self, owner, killer); - return; - } else if (digInfo.bouncer) { - PetDigServer::HandleBouncerDig(self, owner); - } + // Some treasures may only be retrieved by the player that built the diggable + auto builder = self->GetVar(u"builder"); // Set by the pet dig build script + if (builder != owner->GetObjectID()) + return; + } else if (digInfo.xBuild) { + PetDigServer::HandleXBuildDig(self, owner, killer); + return; + } else if (digInfo.bouncer) { + PetDigServer::HandleBouncerDig(self, owner); + } - PetDigServer::ProgressPetDigMissions(owner, self); + PetDigServer::ProgressPetDigMissions(owner, self); - self->SetNetworkVar(u"treasure_dug", true); - // TODO: Reset other pets + self->SetNetworkVar(u"treasure_dug", true); + // TODO: Reset other pets - // Handles smashing leftovers (edge case for the AG X) - auto* xObject = EntityManager::Instance()->GetEntity(self->GetVar(u"X")); - if (xObject != nullptr) { - xObject->Smash(xObject->GetObjectID(), VIOLENT); - } + // Handles smashing leftovers (edge case for the AG X) + auto* xObject = EntityManager::Instance()->GetEntity(self->GetVar(u"X")); + if (xObject != nullptr) { + xObject->Smash(xObject->GetObjectID(), VIOLENT); + } } -void PetDigServer::HandleXBuildDig(const Entity *self, Entity *owner, Entity* pet) { - auto playerID = self->GetVar(u"builder"); - if (playerID == LWOOBJID_EMPTY || playerID != owner->GetObjectID()) - return; +void PetDigServer::HandleXBuildDig(const Entity* self, Entity* owner, Entity* pet) { + auto playerID = self->GetVar(u"builder"); + if (playerID == LWOOBJID_EMPTY || playerID != owner->GetObjectID()) + return; - auto* playerEntity = EntityManager::Instance()->GetEntity(playerID); - if (!playerEntity || !playerEntity->GetParentUser() || !playerEntity->GetParentUser()->GetLastUsedChar()) - return; + auto* playerEntity = EntityManager::Instance()->GetEntity(playerID); + if (!playerEntity || !playerEntity->GetParentUser() || !playerEntity->GetParentUser()->GetLastUsedChar()) + return; - auto* player = playerEntity->GetCharacter(); - const auto groupID = self->GetVar(u"groupID"); - auto playerFlag = 0; + auto* player = playerEntity->GetCharacter(); + const auto groupID = self->GetVar(u"groupID"); + auto playerFlag = 0; - // The flag that the player dug up - if (groupID == u"Flag1") { - playerFlag = 61; - } else if (groupID == u"Flag2") { - playerFlag = 62; - } else if (groupID == u"Flag3") { - playerFlag = 63; - } + // The flag that the player dug up + if (groupID == u"Flag1") { + playerFlag = 61; + } else if (groupID == u"Flag2") { + playerFlag = 62; + } else if (groupID == u"Flag3") { + playerFlag = 63; + } - // If the player doesn't have the flag yet - if (playerFlag != 0 && !player->GetPlayerFlag(playerFlag)) { - auto* petComponent = pet->GetComponent(); - if (petComponent != nullptr) { - // TODO: Pet state = 9 ?? - } + // If the player doesn't have the flag yet + if (playerFlag != 0 && !player->GetPlayerFlag(playerFlag)) { + auto* petComponent = pet->GetComponent(); + if (petComponent != nullptr) { + // TODO: Pet state = 9 ?? + } - // Shows the flag object to the player - player->SetPlayerFlag(playerFlag, true); - } + // Shows the flag object to the player + player->SetPlayerFlag(playerFlag, true); + } - auto* xObject = EntityManager::Instance()->GetEntity(self->GetVar(u"X")); - if (xObject != nullptr) { - xObject->Smash(xObject->GetObjectID(), VIOLENT); - } + auto* xObject = EntityManager::Instance()->GetEntity(self->GetVar(u"X")); + if (xObject != nullptr) { + xObject->Smash(xObject->GetObjectID(), VIOLENT); + } } -void PetDigServer::HandleBouncerDig(const Entity *self, const Entity *owner) { - auto bounceNumber = GeneralUtils::UTF16ToWTF8(self->GetVar(u"BouncerNumber")); - auto bouncerSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncer" + bounceNumber); - auto switchSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncerSwitch" + bounceNumber); +void PetDigServer::HandleBouncerDig(const Entity* self, const Entity* owner) { + auto bounceNumber = GeneralUtils::UTF16ToWTF8(self->GetVar(u"BouncerNumber")); + auto bouncerSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncer" + bounceNumber); + auto switchSpawners = dZoneManager::Instance()->GetSpawnersByName("PetBouncerSwitch" + bounceNumber); - for (auto* bouncerSpawner : bouncerSpawners) { - bouncerSpawner->Activate(); - } + for (auto* bouncerSpawner : bouncerSpawners) { + bouncerSpawner->Activate(); + } - for (auto* switchSpawner : switchSpawners) { - switchSpawner->Activate(); - } + for (auto* switchSpawner : switchSpawners) { + switchSpawner->Activate(); + } } /** @@ -160,33 +157,30 @@ void PetDigServer::HandleBouncerDig(const Entity *self, const Entity *owner) { * \param owner the owner that just made a pet dig something up */ void PetDigServer::ProgressPetDigMissions(const Entity* owner, const Entity* chest) { - auto* missionComponent = owner->GetComponent(); + auto* missionComponent = owner->GetComponent(); - if (missionComponent != nullptr) - { - // Can You Dig It progress - const auto digMissionState = missionComponent->GetMissionState(843); - if (digMissionState == MissionState::MISSION_STATE_ACTIVE) - { - missionComponent->ForceProgress(843, 1216, 1); - } + if (missionComponent != nullptr) { + // Can You Dig It progress + const auto digMissionState = missionComponent->GetMissionState(843); + if (digMissionState == MissionState::MISSION_STATE_ACTIVE) { + missionComponent->ForceProgress(843, 1216, 1); + } - // Pet Excavator progress - const auto excavatorMissionState = missionComponent->GetMissionState(505); - if (excavatorMissionState == MissionState::MISSION_STATE_ACTIVE) - { - if (chest->HasVar(u"PetDig")) { - int32_t playerFlag = 1260 + chest->GetVarAs(u"PetDig"); - Character* player = owner->GetCharacter(); + // Pet Excavator progress + const auto excavatorMissionState = missionComponent->GetMissionState(505); + if (excavatorMissionState == MissionState::MISSION_STATE_ACTIVE) { + if (chest->HasVar(u"PetDig")) { + int32_t playerFlag = 1260 + chest->GetVarAs(u"PetDig"); + Character* player = owner->GetCharacter(); - // check if player flag is set - if (!player->GetPlayerFlag(playerFlag)) { - missionComponent->ForceProgress(505, 767, 1); - player->SetPlayerFlag(playerFlag, 1); - } - } - } - } + // check if player flag is set + if (!player->GetPlayerFlag(playerFlag)) { + missionComponent->ForceProgress(505, 767, 1); + player->SetPlayerFlag(playerFlag, 1); + } + } + } + } } /** @@ -195,45 +189,42 @@ void PetDigServer::ProgressPetDigMissions(const Entity* owner, const Entity* che * \param digInfo information regarding the treasure, will also contain info about the pet to spawn */ void PetDigServer::SpawnPet(Entity* self, const Entity* owner, const DigInfo digInfo) { - // Some treasures require a mission to be active - if (digInfo.requiredMission >= 0) { - auto* missionComponent = owner->GetComponent(); - if (missionComponent != nullptr && missionComponent->GetMissionState(digInfo.requiredMission) < MissionState::MISSION_STATE_ACTIVE) { - return; - } - } + // Some treasures require a mission to be active + if (digInfo.requiredMission >= 0) { + auto* missionComponent = owner->GetComponent(); + if (missionComponent != nullptr && missionComponent->GetMissionState(digInfo.requiredMission) < MissionState::MISSION_STATE_ACTIVE) { + return; + } + } - EntityInfo info {}; - info.lot = digInfo.spawnLot; - info.pos = self->GetPosition(); - info.rot = self->GetRotation(); - info.spawnerID = self->GetSpawnerID(); - info.settings = { - new LDFData(u"tamer", owner->GetObjectID()), - new LDFData(u"group", "pet" + std::to_string(owner->GetObjectID())), - new LDFData(u"spawnAnim", "spawn-pet"), - new LDFData(u"spawnTimer", 1.0) - }; + EntityInfo info{}; + info.lot = digInfo.spawnLot; + info.pos = self->GetPosition(); + info.rot = self->GetRotation(); + info.spawnerID = self->GetSpawnerID(); + info.settings = { + new LDFData(u"tamer", owner->GetObjectID()), + new LDFData(u"group", "pet" + std::to_string(owner->GetObjectID())), + new LDFData(u"spawnAnim", "spawn-pet"), + new LDFData(u"spawnTimer", 1.0) + }; - auto* spawnedPet = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(spawnedPet); + auto* spawnedPet = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(spawnedPet); } -Entity* PetDigServer::GetClosestTresure(NiPoint3 position) -{ - float closestDistance = 0; +Entity* PetDigServer::GetClosestTresure(NiPoint3 position) { + float closestDistance = 0; Entity* closest = nullptr; - for (const auto tresureId : treasures) - { - auto* tresure = EntityManager::Instance()->GetEntity(tresureId); + for (const auto tresureId : treasures) { + auto* tresure = EntityManager::Instance()->GetEntity(tresureId); - if (tresure == nullptr) continue; + if (tresure == nullptr) continue; float distance = Vector3::DistanceSquared(tresure->GetPosition(), position); - if (closest == nullptr || distance < closestDistance) - { + if (closest == nullptr || distance < closestDistance) { closestDistance = distance; closest = tresure; } diff --git a/dScripts/PetDigServer.h b/dScripts/PetDigServer.h index 968ca50d..1122517b 100644 --- a/dScripts/PetDigServer.h +++ b/dScripts/PetDigServer.h @@ -2,29 +2,29 @@ #include "CppScripts.h" struct DigInfo { - LOT digLot; // The lot of the chest - LOT spawnLot; // Option lot of pet to spawn - int32_t requiredMission; // Optional mission required before pet can be spawned, if < 0 == don't use - bool specificPet; // This treasure requires a specific pet to be dug up - bool xBuild; // This treasure is retrieved from a buildable cross - bool bouncer; // This treasure spawns a bouncer - bool builderOnly; // Only the builder of this diggable may access the rewards, for example with crosses + LOT digLot; // The lot of the chest + LOT spawnLot; // Option lot of pet to spawn + int32_t requiredMission; // Optional mission required before pet can be spawned, if < 0 == don't use + bool specificPet; // This treasure requires a specific pet to be dug up + bool xBuild; // This treasure is retrieved from a buildable cross + bool bouncer; // This treasure spawns a bouncer + bool builderOnly; // Only the builder of this diggable may access the rewards, for example with crosses }; class PetDigServer : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnDie(Entity* self, Entity* killer) override; + void OnStartup(Entity* self) override; + void OnDie(Entity* self, Entity* killer) override; static Entity* GetClosestTresure(NiPoint3 position); private: - static void ProgressPetDigMissions(const Entity* owner, const Entity* chest); - static void SpawnPet(Entity* self, const Entity* owner, DigInfo digInfo); - static void HandleXBuildDig(const Entity* self, Entity* owner, Entity* pet); - static void HandleBouncerDig(const Entity* self, const Entity* owner); - static std::vector treasures; - static const DigInfo defaultDigInfo; - static const std::map digInfoMap; + static void ProgressPetDigMissions(const Entity* owner, const Entity* chest); + static void SpawnPet(Entity* self, const Entity* owner, DigInfo digInfo); + static void HandleXBuildDig(const Entity* self, Entity* owner, Entity* pet); + static void HandleBouncerDig(const Entity* self, const Entity* owner); + static std::vector treasures; + static const DigInfo defaultDigInfo; + static const std::map digInfoMap; }; diff --git a/dScripts/PetFromDigServer.cpp b/dScripts/PetFromDigServer.cpp index 235f6f8b..5aca7486 100644 --- a/dScripts/PetFromDigServer.cpp +++ b/dScripts/PetFromDigServer.cpp @@ -2,43 +2,43 @@ #include "PetComponent.h" void PetFromDigServer::OnStartup(Entity* self) { - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwner() != nullptr) - return; + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwner() != nullptr) + return; - // Triggers the local dig pet script for taming etc. - auto tamer = self->GetVar(u"tamer"); + // Triggers the local dig pet script for taming etc. + auto tamer = self->GetVar(u"tamer"); - // Client compares this with player:GetID() which is a string, so we'll have to give it a string - self->SetNetworkVar(u"pettamer", std::to_string(tamer)); + // Client compares this with player:GetID() which is a string, so we'll have to give it a string + self->SetNetworkVar(u"pettamer", std::to_string(tamer)); - // Kill if the player decides that the dig pet is not worthy - self->AddTimer("killself", 45.0f); + // Kill if the player decides that the dig pet is not worthy + self->AddTimer("killself", 45.0f); } void PetFromDigServer::OnTimerDone(Entity* self, std::string timerName) { - if (timerName == "killself") { + if (timerName == "killself") { - // Don't accidentally kill a pet that is already owned - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwner() != nullptr) - return; + // Don't accidentally kill a pet that is already owned + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwner() != nullptr) + return; - self->Smash(self->GetObjectID(), SILENT); - } + self->Smash(self->GetObjectID(), SILENT); + } } void PetFromDigServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { - if (type == NOTIFY_TYPE_BEGIN) { - self->CancelTimer("killself"); - } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { - self->Smash(self->GetObjectID(), SILENT); - } else if (type == NOTIFY_TYPE_SUCCESS) { - auto* petComponent = self->GetComponent(); - if (petComponent == nullptr) - 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); - } + if (type == NOTIFY_TYPE_BEGIN) { + self->CancelTimer("killself"); + } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { + self->Smash(self->GetObjectID(), SILENT); + } else if (type == NOTIFY_TYPE_SUCCESS) { + auto* petComponent = self->GetComponent(); + if (petComponent == nullptr) + 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); + } } diff --git a/dScripts/PetFromDigServer.h b/dScripts/PetFromDigServer.h index e4a69a71..3faf248d 100644 --- a/dScripts/PetFromDigServer.h +++ b/dScripts/PetFromDigServer.h @@ -4,7 +4,7 @@ class PetFromDigServer : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; - void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; }; diff --git a/dScripts/PetFromObjectServer.cpp b/dScripts/PetFromObjectServer.cpp index 4658fcce..899b394a 100644 --- a/dScripts/PetFromObjectServer.cpp +++ b/dScripts/PetFromObjectServer.cpp @@ -1,34 +1,34 @@ #include "PetFromObjectServer.h" #include "PetComponent.h" -void PetFromObjectServer::OnStartup(Entity *self) { - self->SetNetworkVar(u"pettamer", std::to_string(self->GetVar(u"tamer"))); - self->AddTimer("killSelf", 45.0f); +void PetFromObjectServer::OnStartup(Entity* self) { + self->SetNetworkVar(u"pettamer", std::to_string(self->GetVar(u"tamer"))); + self->AddTimer("killSelf", 45.0f); } -void PetFromObjectServer::OnTimerDone(Entity *self, std::string timerName) { - if (timerName == "killSelf") { - const auto* petComponent = self->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwner() != nullptr) - return; - self->Smash(self->GetObjectID(), SILENT); - } +void PetFromObjectServer::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "killSelf") { + const auto* petComponent = self->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwner() != nullptr) + return; + self->Smash(self->GetObjectID(), SILENT); + } } -void PetFromObjectServer::OnNotifyPetTamingMinigame(Entity *self, Entity *tamer, eNotifyType type) { - switch (type) { - case NOTIFY_TYPE_BEGIN: - self->CancelAllTimers(); - break; - case NOTIFY_TYPE_QUIT: - case NOTIFY_TYPE_FAILED: - self->Smash(self->GetObjectID(), SILENT); - break; - case NOTIFY_TYPE_SUCCESS: - // TODO: Remove from groups? - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UpdateSuccessPicking", 0, - 0, tamer->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); - default: - break; - } +void PetFromObjectServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { + switch (type) { + case NOTIFY_TYPE_BEGIN: + self->CancelAllTimers(); + break; + case NOTIFY_TYPE_QUIT: + case NOTIFY_TYPE_FAILED: + self->Smash(self->GetObjectID(), SILENT); + break; + case NOTIFY_TYPE_SUCCESS: + // TODO: Remove from groups? + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UpdateSuccessPicking", 0, + 0, tamer->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + default: + break; + } } diff --git a/dScripts/PetFromObjectServer.h b/dScripts/PetFromObjectServer.h index 989df880..1a7c244b 100644 --- a/dScripts/PetFromObjectServer.h +++ b/dScripts/PetFromObjectServer.h @@ -3,7 +3,7 @@ class PetFromObjectServer : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - void OnTimerDone(Entity *self, std::string timerName) override; - void OnNotifyPetTamingMinigame(Entity *self, Entity *tamer, eNotifyType type) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; }; diff --git a/dScripts/PrSeagullFly.cpp b/dScripts/PrSeagullFly.cpp index a4dd5fcd..5c71f32a 100644 --- a/dScripts/PrSeagullFly.cpp +++ b/dScripts/PrSeagullFly.cpp @@ -1,24 +1,19 @@ #include "PrSeagullFly.h" #include "Entity.h" -void PrSeagullFly::OnStartup(Entity* self) -{ +void PrSeagullFly::OnStartup(Entity* self) { self->SetVar(u"playersNear", 0); - self->SetProximityRadius(15, "birdMonitor"); + self->SetProximityRadius(15, "birdMonitor"); } -void PrSeagullFly::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (!entering->IsPlayer()) return; +void PrSeagullFly::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (!entering->IsPlayer()) return; - if (status == "ENTER") - { + if (status == "ENTER") { self->SetVar(u"playersNear", self->GetVar(u"playersNear") + 1); - } - else if (status == "LEAVE") - { + } else if (status == "LEAVE") { self->SetVar(u"playersNear", self->GetVar(u"playersNear") - 1); - } + } - self->SetNetworkVar(u"BirdLanded", self->GetVar(u"playersNear") == 0); + self->SetNetworkVar(u"BirdLanded", self->GetVar(u"playersNear") == 0); } diff --git a/dScripts/PrWhistle.cpp b/dScripts/PrWhistle.cpp index 4d4d0708..888e1c65 100644 --- a/dScripts/PrWhistle.cpp +++ b/dScripts/PrWhistle.cpp @@ -2,16 +2,13 @@ #include "Character.h" #include "Entity.h" -void PrWhistle::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) -{ - if (args == "unlockEmote") - { - auto* character = sender->GetCharacter(); +void PrWhistle::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "unlockEmote") { + auto* character = sender->GetCharacter(); - if (character != nullptr) - { - character->UnlockEmote(115); - } - } + if (character != nullptr) { + character->UnlockEmote(115); + } + } } diff --git a/dScripts/PrWhistle.h b/dScripts/PrWhistle.h index 58bc0a23..1209ba0d 100644 --- a/dScripts/PrWhistle.h +++ b/dScripts/PrWhistle.h @@ -4,7 +4,7 @@ class PrWhistle : public CppScripts::Script { public: - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/PropertyBankInteract.cpp b/dScripts/PropertyBankInteract.cpp index d564c503..788768ca 100644 --- a/dScripts/PropertyBankInteract.cpp +++ b/dScripts/PropertyBankInteract.cpp @@ -2,42 +2,42 @@ #include "EntityManager.h" #include "GameMessages.h" -void PropertyBankInteract::OnStartup(Entity *self) { - auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - if (zoneControl != nullptr) { - zoneControl->OnFireEventServerSide(self, "CheckForPropertyOwner"); - } +void PropertyBankInteract::OnStartup(Entity* self) { + auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + if (zoneControl != nullptr) { + zoneControl->OnFireEventServerSide(self, "CheckForPropertyOwner"); + } } -void PropertyBankInteract::OnPlayerLoaded(Entity *self, Entity *player) { - auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - if (zoneControl != nullptr) { - zoneControl->OnFireEventServerSide(self, "CheckForPropertyOwner"); - } +void PropertyBankInteract::OnPlayerLoaded(Entity* self, Entity* player) { + auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + if (zoneControl != nullptr) { + zoneControl->OnFireEventServerSide(self, "CheckForPropertyOwner"); + } } -void PropertyBankInteract::OnUse(Entity *self, Entity *user) { +void PropertyBankInteract::OnUse(Entity* self, Entity* user) { - AMFArrayValue args; - auto* value = new AMFStringValue(); - value->SetStringValue("bank"); - args.InsertValue("state", value); + AMFArrayValue args; + auto* value = new AMFStringValue(); + value->SetStringValue("bank"); + args.InsertValue("state", value); - GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); + GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"OpenBank", 0, 0, LWOOBJID_EMPTY, - "", user->GetSystemAddress()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"OpenBank", 0, 0, LWOOBJID_EMPTY, + "", user->GetSystemAddress()); } -void PropertyBankInteract::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { - if (args == "ToggleBank") { - AMFArrayValue amfArgs; +void PropertyBankInteract::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (args == "ToggleBank") { + AMFArrayValue amfArgs; amfArgs.InsertValue("visible", new AMFFalseValue()); - GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleBank", &amfArgs); + GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleBank", &amfArgs); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"CloseBank", 0, 0, LWOOBJID_EMPTY, - "", sender->GetSystemAddress()); - } + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"CloseBank", 0, 0, LWOOBJID_EMPTY, + "", sender->GetSystemAddress()); + } } diff --git a/dScripts/PropertyBankInteract.h b/dScripts/PropertyBankInteract.h index 54bc0484..d780e486 100644 --- a/dScripts/PropertyBankInteract.h +++ b/dScripts/PropertyBankInteract.h @@ -2,9 +2,9 @@ #include "CppScripts.h" class PropertyBankInteract : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnPlayerLoaded(Entity *self, Entity *player) override; - void OnUse(Entity *self, Entity *user) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnStartup(Entity* self) override; + void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnUse(Entity* self, Entity* user) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/PropertyDeathPlane.cpp b/dScripts/PropertyDeathPlane.cpp index 93981dac..ab659d8a 100644 --- a/dScripts/PropertyDeathPlane.cpp +++ b/dScripts/PropertyDeathPlane.cpp @@ -3,16 +3,14 @@ #include "GameMessages.h" #include "EntityManager.h" -void PropertyDeathPlane::OnCollisionPhantom(Entity* self, Entity* target) -{ - const auto teleportGroup = EntityManager::Instance()->GetEntitiesInGroup("Teleport"); +void PropertyDeathPlane::OnCollisionPhantom(Entity* self, Entity* target) { + const auto teleportGroup = EntityManager::Instance()->GetEntitiesInGroup("Teleport"); - if (teleportGroup.size() == 0) - { - return; - } + if (teleportGroup.size() == 0) { + return; + } - auto* teleport = teleportGroup[0]; + auto* teleport = teleportGroup[0]; - GameMessages::SendTeleport(target->GetObjectID(), teleport->GetPosition(), teleport->GetRotation(), target->GetSystemAddress()); + GameMessages::SendTeleport(target->GetObjectID(), teleport->GetPosition(), teleport->GetRotation(), target->GetSystemAddress()); } diff --git a/dScripts/PropertyDevice.cpp b/dScripts/PropertyDevice.cpp index ed0d7b81..64771de1 100644 --- a/dScripts/PropertyDevice.cpp +++ b/dScripts/PropertyDevice.cpp @@ -3,23 +3,23 @@ #include "EntityManager.h" #include "MissionComponent.h" -void PropertyDevice::OnStartup(Entity *self) { - auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); - if (zoneControl != nullptr) { - zoneControl->OnFireEventServerSide(self, "CheckForPropertyOwner"); - } +void PropertyDevice::OnStartup(Entity* self) { + auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); + if (zoneControl != nullptr) { + zoneControl->OnFireEventServerSide(self, "CheckForPropertyOwner"); + } } -void PropertyDevice::OnRebuildComplete(Entity *self, Entity *target) { - auto propertyOwnerID = self->GetNetworkVar(m_PropertyOwnerVariable); - if (propertyOwnerID == std::to_string(LWOOBJID_EMPTY)) - return; +void PropertyDevice::OnRebuildComplete(Entity* self, Entity* target) { + auto propertyOwnerID = self->GetNetworkVar(m_PropertyOwnerVariable); + if (propertyOwnerID == std::to_string(LWOOBJID_EMPTY)) + return; - auto* missionComponent = target->GetComponent(); - if (missionComponent != nullptr) { - if (missionComponent->GetMissionState(m_PropertyMissionID) == MissionState::MISSION_STATE_ACTIVE) { - GameMessages::SendPlayFXEffect(self->GetObjectID(), 641, u"create", "callhome"); - missionComponent->ForceProgress(m_PropertyMissionID, 1793, self->GetLOT()); - } - } + auto* missionComponent = target->GetComponent(); + if (missionComponent != nullptr) { + if (missionComponent->GetMissionState(m_PropertyMissionID) == MissionState::MISSION_STATE_ACTIVE) { + GameMessages::SendPlayFXEffect(self->GetObjectID(), 641, u"create", "callhome"); + missionComponent->ForceProgress(m_PropertyMissionID, 1793, self->GetLOT()); + } + } } diff --git a/dScripts/PropertyDevice.h b/dScripts/PropertyDevice.h index 9c97df4d..87ca10ad 100644 --- a/dScripts/PropertyDevice.h +++ b/dScripts/PropertyDevice.h @@ -2,8 +2,8 @@ #include "CppScripts.h" class PropertyDevice : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnRebuildComplete(Entity *self, Entity *target) override; - const std::u16string m_PropertyOwnerVariable = u"PropertyOwnerID"; - const uint32_t m_PropertyMissionID = 1291; + void OnStartup(Entity* self) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + const std::u16string m_PropertyOwnerVariable = u"PropertyOwnerID"; + const uint32_t m_PropertyMissionID = 1291; }; diff --git a/dScripts/PropertyFXDamage.cpp b/dScripts/PropertyFXDamage.cpp index 2c01ceb1..d12cc9e1 100644 --- a/dScripts/PropertyFXDamage.cpp +++ b/dScripts/PropertyFXDamage.cpp @@ -2,17 +2,17 @@ #include "DestroyableComponent.h" #include "SkillComponent.h" -void PropertyFXDamage::OnCollisionPhantom(Entity *self, Entity *target) { - if (target == nullptr) - return; +void PropertyFXDamage::OnCollisionPhantom(Entity* self, Entity* target) { + if (target == nullptr) + return; - auto* skills = self->GetComponent(); - auto* targetStats = target->GetComponent(); + auto* skills = self->GetComponent(); + auto* targetStats = target->GetComponent(); - if (skills != nullptr && targetStats != nullptr) { - auto targetFactions = targetStats->GetFactionIDs(); - if (std::find(targetFactions.begin(), targetFactions.end(), 1) != targetFactions.end()) { - skills->CalculateBehavior(11386, 692, target->GetObjectID()); - } - } + if (skills != nullptr && targetStats != nullptr) { + auto targetFactions = targetStats->GetFactionIDs(); + if (std::find(targetFactions.begin(), targetFactions.end(), 1) != targetFactions.end()) { + skills->CalculateBehavior(11386, 692, target->GetObjectID()); + } + } } diff --git a/dScripts/PropertyFXDamage.h b/dScripts/PropertyFXDamage.h index b1e67c0a..6973de0c 100644 --- a/dScripts/PropertyFXDamage.h +++ b/dScripts/PropertyFXDamage.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class PropertyFXDamage : public CppScripts::Script { - void OnCollisionPhantom(Entity *self, Entity *target) override; + void OnCollisionPhantom(Entity* self, Entity* target) override; }; diff --git a/dScripts/PropertyPlatform.cpp b/dScripts/PropertyPlatform.cpp index 3b744663..89687ac3 100644 --- a/dScripts/PropertyPlatform.cpp +++ b/dScripts/PropertyPlatform.cpp @@ -2,31 +2,31 @@ #include "RebuildComponent.h" #include "GameMessages.h" -void PropertyPlatform::OnRebuildComplete(Entity *self, Entity *target) { -// auto* movingPlatform = self->GetComponent(); -// if (movingPlatform != nullptr) { -// movingPlatform->StopPathing(); -// movingPlatform->SetNoAutoStart(true); -// } - GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 0, 0, MovementPlatformState::Stationary); +void PropertyPlatform::OnRebuildComplete(Entity* self, Entity* target) { + // auto* movingPlatform = self->GetComponent(); + // if (movingPlatform != nullptr) { + // movingPlatform->StopPathing(); + // movingPlatform->SetNoAutoStart(true); + // } + GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, + 0, 0, MovementPlatformState::Stationary); } -void PropertyPlatform::OnUse(Entity *self, Entity *user) { - auto* rebuildComponent = self->GetComponent(); - if (rebuildComponent != nullptr && rebuildComponent->GetState() == REBUILD_COMPLETED) { -// auto* movingPlatform = self->GetComponent(); -// if (movingPlatform != nullptr) { -// movingPlatform->GotoWaypoint(1); -// } - GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 1, 1, MovementPlatformState::Moving); +void PropertyPlatform::OnUse(Entity* self, Entity* user) { + auto* rebuildComponent = self->GetComponent(); + if (rebuildComponent != nullptr && rebuildComponent->GetState() == REBUILD_COMPLETED) { + // auto* movingPlatform = self->GetComponent(); + // if (movingPlatform != nullptr) { + // movingPlatform->GotoWaypoint(1); + // } + GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, + 1, 1, MovementPlatformState::Moving); - self->AddCallbackTimer(movementDelay + effectDelay, [self, this]() { - self->SetNetworkVar(u"startEffect", dieDelay); - self->AddCallbackTimer(dieDelay, [self]() { - self->Smash(); - }); - }); - } + self->AddCallbackTimer(movementDelay + effectDelay, [self, this]() { + self->SetNetworkVar(u"startEffect", dieDelay); + self->AddCallbackTimer(dieDelay, [self]() { + self->Smash(); + }); + }); + } } diff --git a/dScripts/PropertyPlatform.h b/dScripts/PropertyPlatform.h index 9a2b3229..ec863ab0 100644 --- a/dScripts/PropertyPlatform.h +++ b/dScripts/PropertyPlatform.h @@ -3,11 +3,11 @@ class PropertyPlatform : public CppScripts::Script { public: - void OnUse(Entity *self, Entity *user) override; - void OnRebuildComplete(Entity *self, Entity *target) override; + void OnUse(Entity* self, Entity* user) override; + void OnRebuildComplete(Entity* self, Entity* target) override; private: - float_t movementDelay = 10.0f; - float_t effectDelay = 5.0f; - float_t dieDelay = 5.0f; - uint32_t desiredWaypoint = 1; + float_t movementDelay = 10.0f; + float_t effectDelay = 5.0f; + float_t dieDelay = 5.0f; + uint32_t desiredWaypoint = 1; }; diff --git a/dScripts/QbEnemyStunner.cpp b/dScripts/QbEnemyStunner.cpp index a3dfa94b..5d31a788 100644 --- a/dScripts/QbEnemyStunner.cpp +++ b/dScripts/QbEnemyStunner.cpp @@ -2,73 +2,64 @@ #include "SkillComponent.h" #include "DestroyableComponent.h" -void QbEnemyStunner::OnRebuildComplete(Entity* self, Entity* target) -{ - auto* destroyable = self->GetComponent(); +void QbEnemyStunner::OnRebuildComplete(Entity* self, Entity* target) { + auto* destroyable = self->GetComponent(); - if (destroyable != nullptr) - { - destroyable->SetFaction(115); - } + if (destroyable != nullptr) { + destroyable->SetFaction(115); + } - auto skillComponent = self->GetComponent(); - if (!skillComponent) return; + auto skillComponent = self->GetComponent(); + if (!skillComponent) return; - // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance()->GetTable("ObjectSkills"); - 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("SkillBehavior"); + // Get the skill IDs of this object. + CDObjectSkillsTable* skillsTable = CDClientManager::Instance()->GetTable("ObjectSkills"); + 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("SkillBehavior"); CDSkillBehavior behaviorData = skillBehaviorTable->GetSkillByID(skill.skillID); - skillBehaviorMap.insert(std::make_pair(skill.skillID, behaviorData.behaviorID)); - } + skillBehaviorMap.insert(std::make_pair(skill.skillID, behaviorData.behaviorID)); + } - // If there are no skills found, insert a default skill to use. - if (skillBehaviorMap.size() == 0) { - skillBehaviorMap.insert(std::make_pair(499U, 6095U)); - } + // If there are no skills found, insert a default skill to use. + if (skillBehaviorMap.size() == 0) { + skillBehaviorMap.insert(std::make_pair(499U, 6095U)); + } - // Start all skills associated with the object next tick - self->AddTimer("TickTime", 0); + // Start all skills associated with the object next tick + self->AddTimer("TickTime", 0); - self->AddTimer("PlayEffect", 20); + self->AddTimer("PlayEffect", 20); - self->SetVar>(u"skillBehaviorMap", skillBehaviorMap); + self->SetVar>(u"skillBehaviorMap", skillBehaviorMap); } -void QbEnemyStunner::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "DieTime") - { - self->Smash(); +void QbEnemyStunner::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "DieTime") { + self->Smash(); - self->CancelAllTimers(); - } - else if (timerName == "PlayEffect") - { - self->SetNetworkVar(u"startEffect", 5.0f, UNASSIGNED_SYSTEM_ADDRESS); + self->CancelAllTimers(); + } else if (timerName == "PlayEffect") { + self->SetNetworkVar(u"startEffect", 5.0f, UNASSIGNED_SYSTEM_ADDRESS); - self->AddTimer("DieTime", 5.0f); - } - else if (timerName == "TickTime") - { - auto* skillComponent = self->GetComponent(); + self->AddTimer("DieTime", 5.0f); + } else if (timerName == "TickTime") { + auto* skillComponent = self->GetComponent(); - if (skillComponent != nullptr) - { - auto skillBehaviorMap = self->GetVar>(u"skillBehaviorMap"); - if (skillBehaviorMap.size() == 0) { - // Should no skills have been found, default to the mermaid stunner - skillComponent->CalculateBehavior(499U, 6095U, LWOOBJID_EMPTY); - } else { - for (auto pair : skillBehaviorMap) { - skillComponent->CalculateBehavior(pair.first, pair.second, LWOOBJID_EMPTY); - } - } - } - self->AddTimer("TickTime", 1); - } + if (skillComponent != nullptr) { + auto skillBehaviorMap = self->GetVar>(u"skillBehaviorMap"); + if (skillBehaviorMap.size() == 0) { + // Should no skills have been found, default to the mermaid stunner + skillComponent->CalculateBehavior(499U, 6095U, LWOOBJID_EMPTY); + } else { + for (auto pair : skillBehaviorMap) { + skillComponent->CalculateBehavior(pair.first, pair.second, LWOOBJID_EMPTY); + } + } + } + self->AddTimer("TickTime", 1); + } } diff --git a/dScripts/QbEnemyStunner.h b/dScripts/QbEnemyStunner.h index 18c52d4d..fd9033d6 100644 --- a/dScripts/QbEnemyStunner.h +++ b/dScripts/QbEnemyStunner.h @@ -4,6 +4,6 @@ class QbEnemyStunner : public CppScripts::Script { public: - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/RaceImagineCrateServer.cpp b/dScripts/RaceImagineCrateServer.cpp index 3729004a..a35007b4 100644 --- a/dScripts/RaceImagineCrateServer.cpp +++ b/dScripts/RaceImagineCrateServer.cpp @@ -7,54 +7,49 @@ #include "MissionComponent.h" #include "SkillComponent.h" -void RaceImagineCrateServer::OnDie(Entity* self, Entity* killer) -{ - if (self->GetVar(u"bIsDead")) - { - return; - } +void RaceImagineCrateServer::OnDie(Entity* self, Entity* killer) { + if (self->GetVar(u"bIsDead")) { + return; + } - self->SetVar(u"bIsDead", true); + self->SetVar(u"bIsDead", true); - if (killer == nullptr) - { - return; - } + if (killer == nullptr) { + return; + } - auto* skillComponent = killer->GetComponent(); + auto* skillComponent = killer->GetComponent(); - if (skillComponent == nullptr) - { - return; - } + if (skillComponent == nullptr) { + return; + } - auto* destroyableComponent = killer->GetComponent(); + auto* destroyableComponent = killer->GetComponent(); - if (destroyableComponent != nullptr) - { - destroyableComponent->SetImagination(60); + if (destroyableComponent != nullptr) { + destroyableComponent->SetImagination(60); - EntityManager::Instance()->SerializeEntity(killer); - } + EntityManager::Instance()->SerializeEntity(killer); + } - // Find possessor of race car to progress missions and update stats. - auto* possessableComponent = killer->GetComponent(); - if (possessableComponent != nullptr) { + // Find possessor of race car to progress missions and update stats. + auto* possessableComponent = killer->GetComponent(); + if (possessableComponent != nullptr) { - auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (possessor != nullptr) { + auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); + if (possessor != nullptr) { - auto* missionComponent = possessor->GetComponent(); - auto* characterComponent = possessor->GetComponent(); + auto* missionComponent = possessor->GetComponent(); + auto* characterComponent = possessor->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(RacingImaginationCratesSmashed); - characterComponent->UpdatePlayerStatistic(RacingSmashablesSmashed); - } + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(RacingImaginationCratesSmashed); + characterComponent->UpdatePlayerStatistic(RacingSmashablesSmashed); + } - // Progress racing smashable missions - if(missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); - } - } + // Progress racing smashable missions + if (missionComponent == nullptr) return; + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); + } + } } diff --git a/dScripts/RaceImagineCrateServer.h b/dScripts/RaceImagineCrateServer.h index 42f36b30..92020925 100644 --- a/dScripts/RaceImagineCrateServer.h +++ b/dScripts/RaceImagineCrateServer.h @@ -4,11 +4,11 @@ class RaceImagineCrateServer : public CppScripts::Script { public: -/** - * @brief When a boost smashable has been smashed, this function is called - * - * @param self The Entity that called this function. - * @param killer The Entity that killed this Entity. - */ - void OnDie(Entity* self, Entity* killer) override; + /** + * @brief When a boost smashable has been smashed, this function is called + * + * @param self The Entity that called this function. + * @param killer The Entity that killed this Entity. + */ + void OnDie(Entity* self, Entity* killer) override; }; diff --git a/dScripts/RaceImaginePowerup.cpp b/dScripts/RaceImaginePowerup.cpp index a940b88d..9bdd0813 100644 --- a/dScripts/RaceImaginePowerup.cpp +++ b/dScripts/RaceImaginePowerup.cpp @@ -5,37 +5,32 @@ #include "RacingTaskParam.h" #include "MissionComponent.h" -void RaceImaginePowerup::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) -{ - if (sender->IsPlayer() && args == "powerup") - { - auto* possessorComponent = sender->GetComponent(); +void RaceImaginePowerup::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (sender->IsPlayer() && args == "powerup") { + auto* possessorComponent = sender->GetComponent(); - if (possessorComponent == nullptr) - { - return; - } + if (possessorComponent == nullptr) { + return; + } - auto* vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + auto* vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); - if (vehicle == nullptr) - { - return; - } + if (vehicle == nullptr) { + return; + } - auto* destroyableComponent = vehicle->GetComponent(); + auto* destroyableComponent = vehicle->GetComponent(); - if (destroyableComponent == nullptr) - { - return; - } + if (destroyableComponent == nullptr) { + return; + } - destroyableComponent->Imagine(10); + destroyableComponent->Imagine(10); - auto* missionComponent = sender->GetComponent(); + auto* missionComponent = sender->GetComponent(); - if (missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COLLECT_IMAGINATION); - } + if (missionComponent == nullptr) return; + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COLLECT_IMAGINATION); + } } diff --git a/dScripts/RaceImaginePowerup.h b/dScripts/RaceImaginePowerup.h index c9d7be2d..2df2e060 100644 --- a/dScripts/RaceImaginePowerup.h +++ b/dScripts/RaceImaginePowerup.h @@ -4,6 +4,6 @@ class RaceImaginePowerup : public CppScripts::Script { public: - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/RaceMaelstromGeiser.cpp b/dScripts/RaceMaelstromGeiser.cpp index 88a45bbd..b737d449 100644 --- a/dScripts/RaceMaelstromGeiser.cpp +++ b/dScripts/RaceMaelstromGeiser.cpp @@ -6,99 +6,80 @@ #include "RacingControlComponent.h" #include "dZoneManager.h" -void RaceMaelstromGeiser::OnStartup(Entity* self) -{ - self->SetVar(u"AmFiring", false); - - self->AddTimer("downTime", self->GetVar(u"startTime")); +void RaceMaelstromGeiser::OnStartup(Entity* self) { + self->SetVar(u"AmFiring", false); - self->SetProximityRadius(15, "deathZone"); + self->AddTimer("downTime", self->GetVar(u"startTime")); + + self->SetProximityRadius(15, "deathZone"); } -void RaceMaelstromGeiser::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ - if (!entering->IsPlayer() || name != "deathZone" || status != "ENTER") - { - return; - } +void RaceMaelstromGeiser::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (!entering->IsPlayer() || name != "deathZone" || status != "ENTER") { + return; + } - if (!self->GetVar(u"AmFiring")) - { - return; - } + if (!self->GetVar(u"AmFiring")) { + return; + } - auto* possessableComponent = entering->GetComponent(); + auto* possessableComponent = entering->GetComponent(); - Entity* vehicle; - Entity* player; + Entity* vehicle; + Entity* player; - if (possessableComponent != nullptr) - { - player = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); + if (possessableComponent != nullptr) { + player = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (player == nullptr) - { - return; - } + if (player == nullptr) { + return; + } - vehicle = entering; - } - else if (entering->IsPlayer()) - { - auto* possessorComponent = entering->GetComponent(); + vehicle = entering; + } else if (entering->IsPlayer()) { + auto* possessorComponent = entering->GetComponent(); - if (possessorComponent == nullptr) - { - return; - } + if (possessorComponent == nullptr) { + return; + } - vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); - if (vehicle == nullptr) - { - return; - } + if (vehicle == nullptr) { + return; + } - player = entering; - } - else - { - return; - } - + player = entering; + } else { + return; + } - GameMessages::SendDie(vehicle, self->GetObjectID(), LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, true, false, 0); - auto* zoneController = dZoneManager::Instance()->GetZoneControlObject(); + GameMessages::SendDie(vehicle, self->GetObjectID(), LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, true, false, 0); - auto* racingControlComponent = zoneController->GetComponent(); + auto* zoneController = dZoneManager::Instance()->GetZoneControlObject(); - if (racingControlComponent != nullptr) - { - racingControlComponent->OnRequestDie(player); - } + auto* racingControlComponent = zoneController->GetComponent(); + + if (racingControlComponent != nullptr) { + racingControlComponent->OnRequestDie(player); + } } -void RaceMaelstromGeiser::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "downTime") - { - GameMessages::SendPlayFXEffect(self->GetObjectID(), 4048, u"rebuild_medium", "geiser", LWOOBJID_EMPTY, 1, 1, true); +void RaceMaelstromGeiser::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "downTime") { + GameMessages::SendPlayFXEffect(self->GetObjectID(), 4048, u"rebuild_medium", "geiser", LWOOBJID_EMPTY, 1, 1, true); - self->AddTimer("buildUpTime", 1); - } - else if (timerName == "buildUpTime") - { - self->SetVar(u"AmFiring", true); + self->AddTimer("buildUpTime", 1); + } else if (timerName == "buildUpTime") { + self->SetVar(u"AmFiring", true); - self->AddTimer("killTime", 1.5f); - } - else if (timerName == "killTime") - { - GameMessages::SendStopFXEffect(self, true, "geiser"); + self->AddTimer("killTime", 1.5f); + } else if (timerName == "killTime") { + GameMessages::SendStopFXEffect(self, true, "geiser"); - self->SetVar(u"AmFiring", false); + self->SetVar(u"AmFiring", false); - self->AddTimer("downTime", 3.0); - } + self->AddTimer("downTime", 3.0); + } } diff --git a/dScripts/RaceMaelstromGeiser.h b/dScripts/RaceMaelstromGeiser.h index 79cc384c..3ca0953b 100644 --- a/dScripts/RaceMaelstromGeiser.h +++ b/dScripts/RaceMaelstromGeiser.h @@ -4,7 +4,7 @@ class RaceMaelstromGeiser : public CppScripts::Script { public: - void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; }; diff --git a/dScripts/RaceSmashServer.cpp b/dScripts/RaceSmashServer.cpp index 8c8b3f79..d0dc3d78 100644 --- a/dScripts/RaceSmashServer.cpp +++ b/dScripts/RaceSmashServer.cpp @@ -5,26 +5,26 @@ #include "RacingTaskParam.h" #include "MissionComponent.h" -void RaceSmashServer::OnDie(Entity *self, Entity *killer) { - // Crate is smashed by the car - auto* possessableComponent = killer->GetComponent(); - if (possessableComponent != nullptr) { +void RaceSmashServer::OnDie(Entity* self, Entity* killer) { + // Crate is smashed by the car + auto* possessableComponent = killer->GetComponent(); + if (possessableComponent != nullptr) { - auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); - if (possessor != nullptr) { + auto* possessor = EntityManager::Instance()->GetEntity(possessableComponent->GetPossessor()); + if (possessor != nullptr) { - auto* missionComponent = possessor->GetComponent(); - auto* characterComponent = possessor->GetComponent(); + auto* missionComponent = possessor->GetComponent(); + auto* characterComponent = possessor->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(RacingSmashablesSmashed); - } + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(RacingSmashablesSmashed); + } - // Progress racing smashable missions - if(missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); - // Progress missions that ask us to smash a specific smashable. - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASH_SPECIFIC_SMASHABLE); - } - } + // Progress racing smashable missions + if (missionComponent == nullptr) return; + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); + // Progress missions that ask us to smash a specific smashable. + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASH_SPECIFIC_SMASHABLE); + } + } } diff --git a/dScripts/RaceSmashServer.h b/dScripts/RaceSmashServer.h index 7fa1441d..096092bd 100644 --- a/dScripts/RaceSmashServer.h +++ b/dScripts/RaceSmashServer.h @@ -2,11 +2,11 @@ #include "CppScripts.h" class RaceSmashServer : public CppScripts::Script { - /** - * @brief When a smashable has been destroyed, this function is called. - * - * @param self The Entity that called this function. - * @param killer The Entity that killed this Entity. - */ - void OnDie(Entity *self, Entity *killer) override; + /** + * @brief When a smashable has been destroyed, this function is called. + * + * @param self The Entity that called this function. + * @param killer The Entity that killed this Entity. + */ + void OnDie(Entity* self, Entity* killer) override; }; diff --git a/dScripts/RainOfArrows.cpp b/dScripts/RainOfArrows.cpp index d9a7ba42..141cd3ab 100644 --- a/dScripts/RainOfArrows.cpp +++ b/dScripts/RainOfArrows.cpp @@ -3,79 +3,68 @@ #include "SkillComponent.h" #include "GameMessages.h" -void RainOfArrows::OnStartup(Entity* self) -{ - +void RainOfArrows::OnStartup(Entity* self) { + } -void RainOfArrows::OnRebuildComplete(Entity* self, Entity* target) -{ - auto myPos = self->GetPosition(); - auto myRot = self->GetRotation(); +void RainOfArrows::OnRebuildComplete(Entity* self, Entity* target) { + auto myPos = self->GetPosition(); + auto myRot = self->GetRotation(); - EntityInfo info; - info.lot = m_ArrowFXObject; - info.pos = myPos; - info.rot = myRot; - info.spawnerID = self->GetObjectID(); + EntityInfo info; + info.lot = m_ArrowFXObject; + info.pos = myPos; + info.rot = myRot; + info.spawnerID = self->GetObjectID(); - auto* entity = EntityManager::Instance()->CreateEntity(info); + auto* entity = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(entity); - - self->SetVar(u"ChildFX", entity->GetObjectID()); - self->SetVar(u"playerID", target->GetObjectID()); + EntityManager::Instance()->ConstructEntity(entity); - self->AddTimer("ArrowsIncoming", m_ArrowDelay); - self->AddTimer("PlayArrowSound", m_ArrowDelay - 4); + self->SetVar(u"ChildFX", entity->GetObjectID()); + self->SetVar(u"playerID", target->GetObjectID()); + + self->AddTimer("ArrowsIncoming", m_ArrowDelay); + self->AddTimer("PlayArrowSound", m_ArrowDelay - 4); } -void RainOfArrows::OnTimerDone(Entity* self, std::string timerName) -{ - auto* child = EntityManager::Instance()->GetEntity( - self->GetVar(u"ChildFX") - ); - - auto* player = EntityManager::Instance()->GetEntity( - self->GetVar(u"playerID") - ); +void RainOfArrows::OnTimerDone(Entity* self, std::string timerName) { + auto* child = EntityManager::Instance()->GetEntity( + self->GetVar(u"ChildFX") + ); - if (timerName == "ArrowsIncoming") - { - if (child == nullptr) - { - return; - } + auto* player = EntityManager::Instance()->GetEntity( + self->GetVar(u"playerID") + ); - auto* skillComponent = child->GetComponent(); + if (timerName == "ArrowsIncoming") { + if (child == nullptr) { + return; + } - if (skillComponent == nullptr) - { - return; - } + auto* skillComponent = child->GetComponent(); - skillComponent->CalculateBehavior( - m_ArrowSkill, - m_ArrowBehavior, - LWOOBJID_EMPTY, - true, - false, - player != nullptr ? player->GetObjectID() : LWOOBJID_EMPTY - ); - - self->AddTimer("FireSkill", 0.7f); - } - else if (timerName == "PlayArrowSound") - { - GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, m_ArrowsGUID); - } - else if (timerName == "FireSkill") - { - if (child != nullptr) - { - child->Smash(); - } + if (skillComponent == nullptr) { + return; + } - self->Smash(player != nullptr ? player->GetObjectID() : LWOOBJID_EMPTY); - } + skillComponent->CalculateBehavior( + m_ArrowSkill, + m_ArrowBehavior, + LWOOBJID_EMPTY, + true, + false, + player != nullptr ? player->GetObjectID() : LWOOBJID_EMPTY + ); + + self->AddTimer("FireSkill", 0.7f); + } else if (timerName == "PlayArrowSound") { + GameMessages::SendPlayNDAudioEmitter(self, UNASSIGNED_SYSTEM_ADDRESS, m_ArrowsGUID); + } else if (timerName == "FireSkill") { + if (child != nullptr) { + child->Smash(); + } + + self->Smash(player != nullptr ? player->GetObjectID() : LWOOBJID_EMPTY); + } } diff --git a/dScripts/RainOfArrows.h b/dScripts/RainOfArrows.h index 5b997251..778ddfea 100644 --- a/dScripts/RainOfArrows.h +++ b/dScripts/RainOfArrows.h @@ -5,13 +5,13 @@ class RainOfArrows : public CppScripts::Script { public: void OnStartup(Entity* self) override; - void OnRebuildComplete(Entity* self, Entity* target) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnRebuildComplete(Entity* self, Entity* target) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - LOT m_ArrowFXObject = 15850; - int32_t m_ArrowSkill = 1482; - int32_t m_ArrowBehavior = 36680; - int32_t m_ArrowDelay = 6; - std::string m_ArrowsGUID = "{532cba3c-54da-446c-986b-128af9647bdb}"; -}; \ No newline at end of file + LOT m_ArrowFXObject = 15850; + int32_t m_ArrowSkill = 1482; + int32_t m_ArrowBehavior = 36680; + int32_t m_ArrowDelay = 6; + std::string m_ArrowsGUID = "{532cba3c-54da-446c-986b-128af9647bdb}"; +}; diff --git a/dScripts/RandomSpawnerFin.cpp b/dScripts/RandomSpawnerFin.cpp index da0b655e..57793511 100644 --- a/dScripts/RandomSpawnerFin.cpp +++ b/dScripts/RandomSpawnerFin.cpp @@ -1,9 +1,8 @@ #include "RandomSpawnerFin.h" -void RandomSpawnerFin::OnStartup(Entity* self) -{ - zones = { - { //-- ** Load 1 -------------------------- ** +void RandomSpawnerFin::OnStartup(Entity* self) { + zones = { + { //-- ** Load 1 -------------------------- ** {{mobs.pirate, 3, "type1",}, {mobs.ronin, 3, "type2",}, {mobs.spider, 2, "type3",}}, @@ -63,25 +62,24 @@ void RandomSpawnerFin::OnStartup(Entity* self) {mobs.horse, 1, "type3",}}, 10 }, - }; - - sectionMultipliers = { - {"secA", 1}, - {"secB", 1}, - {"secC", 1.2f}, - {"secD", 1.3f}, - {"secE", 1.6f}, - {"secF", 1}, - {"secG", 1}, - {"secH", 1.2f}, - }; + }; - zoneName = "fin"; + sectionMultipliers = { + {"secA", 1}, + {"secB", 1}, + {"secC", 1.2f}, + {"secD", 1.3f}, + {"secE", 1.6f}, + {"secF", 1}, + {"secG", 1}, + {"secH", 1.2f}, + }; - BaseStartup(self); + zoneName = "fin"; + + BaseStartup(self); } -void RandomSpawnerFin::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void RandomSpawnerFin::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } diff --git a/dScripts/RandomSpawnerFin.h b/dScripts/RandomSpawnerFin.h index 174b90f0..30416858 100644 --- a/dScripts/RandomSpawnerFin.h +++ b/dScripts/RandomSpawnerFin.h @@ -5,22 +5,22 @@ class RandomSpawnerFin : public CppScripts::Script, BaseRandomServer { void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - struct Mobs - { - static const LOT stromb = 11212; - static const LOT mech = 11213; - static const LOT spider = 11214; - static const LOT pirate = 11215; - static const LOT admiral = 11216; - static const LOT gorilla = 11217; - static const LOT ronin = 11218; - static const LOT horse = 11219; - static const LOT dragon = 112201; - }; + struct Mobs + { + static const LOT stromb = 11212; + static const LOT mech = 11213; + static const LOT spider = 11214; + static const LOT pirate = 11215; + static const LOT admiral = 11216; + static const LOT gorilla = 11217; + static const LOT ronin = 11218; + static const LOT horse = 11219; + static const LOT dragon = 112201; + }; - Mobs mobs; + Mobs mobs; }; diff --git a/dScripts/RandomSpawnerPit.cpp b/dScripts/RandomSpawnerPit.cpp index 8dfa61b0..ceea9412 100644 --- a/dScripts/RandomSpawnerPit.cpp +++ b/dScripts/RandomSpawnerPit.cpp @@ -1,9 +1,8 @@ #include "RandomSpawnerPit.h" -void RandomSpawnerPit::OnStartup(Entity* self) -{ - zones = { - { //-- ** Load 1 -------------------------- ** +void RandomSpawnerPit::OnStartup(Entity* self) { + zones = { + { //-- ** Load 1 -------------------------- ** {{mobs.admiral, 4, "type1",}, {mobs.spider, 3, "type2",}}, 5 @@ -63,23 +62,22 @@ void RandomSpawnerPit::OnStartup(Entity* self) {mobs.pirate, 5, "type2",}}, 15 }, - }; + }; - sectionMultipliers = { - {"secA", 1}, - {"secB", 1.2f}, - {"secC", 1.2f}, - {"secD", 1}, - }; + sectionMultipliers = { + {"secA", 1}, + {"secB", 1.2f}, + {"secC", 1.2f}, + {"secD", 1}, + }; - zoneName = "pit"; + zoneName = "pit"; mobDeathResetNumber = 20; changeNum = 18; - BaseStartup(self); + BaseStartup(self); } -void RandomSpawnerPit::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void RandomSpawnerPit::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } diff --git a/dScripts/RandomSpawnerPit.h b/dScripts/RandomSpawnerPit.h index 8346ec37..5ffceec5 100644 --- a/dScripts/RandomSpawnerPit.h +++ b/dScripts/RandomSpawnerPit.h @@ -5,22 +5,22 @@ class RandomSpawnerPit : public CppScripts::Script, BaseRandomServer { void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - struct Mobs - { - static const LOT stromb = 11212; - static const LOT mech = 11213; - static const LOT spider = 11214; - static const LOT pirate = 11215; - static const LOT admiral = 11216; - static const LOT gorilla = 11217; - static const LOT ronin = 11218; - static const LOT horse = 11219; - static const LOT dragon = 112200; - }; + struct Mobs + { + static const LOT stromb = 11212; + static const LOT mech = 11213; + static const LOT spider = 11214; + static const LOT pirate = 11215; + static const LOT admiral = 11216; + static const LOT gorilla = 11217; + static const LOT ronin = 11218; + static const LOT horse = 11219; + static const LOT dragon = 112200; + }; - Mobs mobs; + Mobs mobs; }; diff --git a/dScripts/RandomSpawnerStr.cpp b/dScripts/RandomSpawnerStr.cpp index fa6ac117..0f7f5114 100644 --- a/dScripts/RandomSpawnerStr.cpp +++ b/dScripts/RandomSpawnerStr.cpp @@ -1,9 +1,8 @@ #include "RandomSpawnerStr.h" -void RandomSpawnerStr::OnStartup(Entity* self) -{ - zones = { - { //-- ** Load 1 -------------------------- ** +void RandomSpawnerStr::OnStartup(Entity* self) { + zones = { + { //-- ** Load 1 -------------------------- ** {{mobs.stromb, 4, "type1",}, {mobs.pirate, 3, "type2",}, {mobs.ronin, 3, "type3",}}, @@ -63,22 +62,21 @@ void RandomSpawnerStr::OnStartup(Entity* self) {mobs.pirate, 4, "type3",}}, 1 }, - }; + }; - sectionMultipliers = { - {"secA", 1}, - {"secB", 1}, - {"secC", 1.2f}, - }; + sectionMultipliers = { + {"secA", 1}, + {"secB", 1}, + {"secC", 1.2f}, + }; - zoneName = "str"; + zoneName = "str"; mobDeathResetNumber = 20; changeNum = 15; - BaseStartup(self); + BaseStartup(self); } -void RandomSpawnerStr::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void RandomSpawnerStr::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } diff --git a/dScripts/RandomSpawnerStr.h b/dScripts/RandomSpawnerStr.h index a3ee920e..b6f0bbea 100644 --- a/dScripts/RandomSpawnerStr.h +++ b/dScripts/RandomSpawnerStr.h @@ -5,22 +5,22 @@ class RandomSpawnerStr : public CppScripts::Script, BaseRandomServer { void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - struct Mobs - { - static const LOT stromb = 11212; - static const LOT mech = 11213; - static const LOT spider = 11214; - static const LOT pirate = 11215; - static const LOT admiral = 11216; - static const LOT gorilla = 11217; - static const LOT ronin = 11218; - static const LOT horse = 11219; - static const LOT dragon = 112200; - }; + struct Mobs + { + static const LOT stromb = 11212; + static const LOT mech = 11213; + static const LOT spider = 11214; + static const LOT pirate = 11215; + static const LOT admiral = 11216; + static const LOT gorilla = 11217; + static const LOT ronin = 11218; + static const LOT horse = 11219; + static const LOT dragon = 112200; + }; - Mobs mobs; + Mobs mobs; }; diff --git a/dScripts/RandomSpawnerZip.cpp b/dScripts/RandomSpawnerZip.cpp index 083d4ae7..3f45a784 100644 --- a/dScripts/RandomSpawnerZip.cpp +++ b/dScripts/RandomSpawnerZip.cpp @@ -1,9 +1,8 @@ #include "RandomSpawnerZip.h" -void RandomSpawnerZip::OnStartup(Entity* self) -{ - zones = { - { //-- ** Load 1 -------------------------- ** +void RandomSpawnerZip::OnStartup(Entity* self) { + zones = { + { //-- ** Load 1 -------------------------- ** {{mobs.stromb, 3, "type1",}, {mobs.pirate, 2, "type2",}, {mobs.admiral, 2, "type3",}, @@ -73,21 +72,20 @@ void RandomSpawnerZip::OnStartup(Entity* self) {mobs.pirate, 0, "type4",}}, 1 }, - }; + }; - sectionMultipliers = { - {"secA", 1.2f}, - {"secB", 1.2f}, - }; + sectionMultipliers = { + {"secA", 1.2f}, + {"secB", 1.2f}, + }; - zoneName = "zip"; + zoneName = "zip"; mobDeathResetNumber = 20; changeNum = 9; - BaseStartup(self); + BaseStartup(self); } -void RandomSpawnerZip::OnTimerDone(Entity* self, std::string timerName) -{ - BaseOnTimerDone(self, timerName); +void RandomSpawnerZip::OnTimerDone(Entity* self, std::string timerName) { + BaseOnTimerDone(self, timerName); } diff --git a/dScripts/RandomSpawnerZip.h b/dScripts/RandomSpawnerZip.h index 6c0cf511..f2aa6635 100644 --- a/dScripts/RandomSpawnerZip.h +++ b/dScripts/RandomSpawnerZip.h @@ -5,22 +5,22 @@ class RandomSpawnerZip : public CppScripts::Script, BaseRandomServer { void OnStartup(Entity* self) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; private: - struct Mobs - { - static const LOT stromb = 11212; - static const LOT mech = 11213; - static const LOT spider = 11214; - static const LOT pirate = 11215; - static const LOT admiral = 11216; - static const LOT gorilla = 11217; - static const LOT ronin = 11218; - static const LOT horse = 11219; - static const LOT dragon = 112200; - }; + struct Mobs + { + static const LOT stromb = 11212; + static const LOT mech = 11213; + static const LOT spider = 11214; + static const LOT pirate = 11215; + static const LOT admiral = 11216; + static const LOT gorilla = 11217; + static const LOT ronin = 11218; + static const LOT horse = 11219; + static const LOT dragon = 112200; + }; - Mobs mobs; + Mobs mobs; }; diff --git a/dScripts/RockHydrantBroken.cpp b/dScripts/RockHydrantBroken.cpp index 50e3c88d..835d52f6 100644 --- a/dScripts/RockHydrantBroken.cpp +++ b/dScripts/RockHydrantBroken.cpp @@ -2,16 +2,14 @@ #include "EntityManager.h" #include "GameMessages.h" -void RockHydrantBroken::OnStartup(Entity* self) -{ +void RockHydrantBroken::OnStartup(Entity* self) { self->AddTimer("playEffect", 1); const auto hydrant = "hydrant" + self->GetVar(u"hydrant"); const auto bouncers = EntityManager::Instance()->GetEntitiesInGroup(hydrant); - for (auto* bouncer : bouncers) - { + for (auto* bouncer : bouncers) { self->SetVar(u"bouncer", bouncer->GetObjectID()); @@ -23,23 +21,18 @@ void RockHydrantBroken::OnStartup(Entity* self) self->AddTimer("KillBroken", 10); } -void RockHydrantBroken::OnTimerDone(Entity* self, std::string timerName) -{ - if (timerName == "KillBroken") - { +void RockHydrantBroken::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "KillBroken") { auto* bouncer = EntityManager::Instance()->GetEntity(self->GetVar(u"bouncer")); - if (bouncer != nullptr) - { + if (bouncer != nullptr) { GameMessages::SendBouncerActiveStatus(bouncer->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendNotifyObject(bouncer->GetObjectID(), self->GetObjectID(), u"disableCollision", UNASSIGNED_SYSTEM_ADDRESS); } self->Kill(); - } - else if (timerName == "playEffect") - { + } else if (timerName == "playEffect") { GameMessages::SendPlayFXEffect(self->GetObjectID(), 4737, u"water", "water", LWOOBJID_EMPTY, 1, 1, true); } } diff --git a/dScripts/RockHydrantSmashable.cpp b/dScripts/RockHydrantSmashable.cpp index 8d5b5861..d76eca8d 100644 --- a/dScripts/RockHydrantSmashable.cpp +++ b/dScripts/RockHydrantSmashable.cpp @@ -2,17 +2,16 @@ #include "EntityManager.h" #include "GeneralUtils.h" -void RockHydrantSmashable::OnDie(Entity* self, Entity* killer) -{ +void RockHydrantSmashable::OnDie(Entity* self, Entity* killer) { const auto hydrantName = self->GetVar(u"hydrant"); LDFBaseData* data = new LDFData(u"hydrant", GeneralUtils::UTF16ToWTF8(hydrantName)); - EntityInfo info {}; + EntityInfo info{}; info.lot = ROCK_HYDRANT_BROKEN; info.pos = self->GetPosition(); info.rot = self->GetRotation(); - info.settings = {data}; + info.settings = { data }; info.spawnerID = self->GetSpawnerID(); auto* hydrant = EntityManager::Instance()->CreateEntity(info); diff --git a/dScripts/SGCannon.cpp b/dScripts/SGCannon.cpp index 9f270562..049837a4 100644 --- a/dScripts/SGCannon.cpp +++ b/dScripts/SGCannon.cpp @@ -12,1071 +12,1058 @@ #include "../dWorldServer/ObjectIDManager.h" #include "MissionComponent.h" -void SGCannon::OnStartup(Entity *self) { - Game::logger->Log("SGCannon", "OnStartup"); +void SGCannon::OnStartup(Entity* self) { + Game::logger->Log("SGCannon", "OnStartup"); - m_Waves = GetWaves(); - constants = GetConstants(); + m_Waves = GetWaves(); + constants = GetConstants(); - ResetVars(self); + ResetVars(self); - self->SetVar(GameStartedVariable, false); - self->SetVar(InitialVelocityVariable, {}); - self->SetVar(ImpactSkillVariale, constants.impactSkillID); + self->SetVar(GameStartedVariable, false); + self->SetVar(InitialVelocityVariable, {}); + self->SetVar(ImpactSkillVariale, constants.impactSkillID); - auto* shootingGalleryComponent = self->GetComponent(); - if (shootingGalleryComponent != nullptr) { - shootingGalleryComponent->SetStaticParams({ - Vector3 { -327.8609924316406, 256.8999938964844, 1.6482199430465698 }, - Vector3 { -181.4320068359375, 212.39999389648438, 2.5182199478149414 } - }); + auto* shootingGalleryComponent = self->GetComponent(); + if (shootingGalleryComponent != nullptr) { + shootingGalleryComponent->SetStaticParams({ + Vector3 { -327.8609924316406, 256.8999938964844, 1.6482199430465698 }, + Vector3 { -181.4320068359375, 212.39999389648438, 2.5182199478149414 } + }); - shootingGalleryComponent->SetDynamicParams({ - Vector3 { 0.0, 4.3, 9.0 }, - Vector3 { }, - 129.0, - 800.0, - 30.0, - 0.0, - -1.0, - 58.6 - }); - } + shootingGalleryComponent->SetDynamicParams({ + Vector3 { 0.0, 4.3, 9.0 }, + Vector3 { }, + 129.0, + 800.0, + 30.0, + 0.0, + -1.0, + 58.6 + }); + } - self->SetVar(TimeLimitVariable, 30); - self->SetVar>(ValidActorsVariable, {3109, 3110, 3111, 3112, 3125, 3126}); - self->SetVar>(ValidEffectsVariable, {3122}); - self->SetVar>(StreakBonusVariable, {1, 2, 5, 10}); - self->SetVar(SuperChargeActiveVariable, false); - self->SetVar(MatrixVariable, 1); - self->SetVar(InitVariable, true); + self->SetVar(TimeLimitVariable, 30); + self->SetVar>(ValidActorsVariable, { 3109, 3110, 3111, 3112, 3125, 3126 }); + self->SetVar>(ValidEffectsVariable, { 3122 }); + self->SetVar>(StreakBonusVariable, { 1, 2, 5, 10 }); + self->SetVar(SuperChargeActiveVariable, false); + self->SetVar(MatrixVariable, 1); + self->SetVar(InitVariable, true); - auto* simplePhysicsComponent = self->GetComponent(); + auto* simplePhysicsComponent = self->GetComponent(); - if (simplePhysicsComponent != nullptr) { - simplePhysicsComponent->SetPhysicsMotionState(5); - } + if (simplePhysicsComponent != nullptr) { + simplePhysicsComponent->SetPhysicsMotionState(5); + } } -void SGCannon::OnPlayerLoaded(Entity *self, Entity *player) { - Game::logger->Log("SGCannon", "Player loaded"); - self->SetVar(PlayerIDVariable, player->GetObjectID()); +void SGCannon::OnPlayerLoaded(Entity* self, Entity* player) { + Game::logger->Log("SGCannon", "Player loaded"); + self->SetVar(PlayerIDVariable, player->GetObjectID()); } -void SGCannon::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - Script::OnFireEventServerSide(self, sender, args, param1, param2, param3); +void SGCannon::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + Script::OnFireEventServerSide(self, sender, args, param1, param2, param3); } -void SGCannon::OnActivityStateChangeRequest(Entity *self, LWOOBJID senderID, int32_t value1, int32_t value2, - const std::u16string &stringValue) { - Game::logger->Log("SGCannon", "Got activity state change request: %s", GeneralUtils::UTF16ToWTF8(stringValue).c_str()); - if (stringValue == u"clientready") { - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - Game::logger->Log("SGCannon", "Player is ready"); - /*GameMessages::SendSetStunned(player->GetObjectID(), PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true);*/ +void SGCannon::OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, int32_t value2, + const std::u16string& stringValue) { + Game::logger->Log("SGCannon", "Got activity state change request: %s", GeneralUtils::UTF16ToWTF8(stringValue).c_str()); + if (stringValue == u"clientready") { + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + Game::logger->Log("SGCannon", "Player is ready"); + /*GameMessages::SendSetStunned(player->GetObjectID(), PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true);*/ - Game::logger->Log("SGCannon", "Sending ActivityEnter"); + Game::logger->Log("SGCannon", "Sending ActivityEnter"); - GameMessages::SendActivityEnter(self->GetObjectID(), player->GetSystemAddress()); + GameMessages::SendActivityEnter(self->GetObjectID(), player->GetSystemAddress()); - auto* shootingGalleryComponent = self->GetComponent(); + auto* shootingGalleryComponent = self->GetComponent(); - if (shootingGalleryComponent != nullptr) { - shootingGalleryComponent->SetCurrentPlayerID(player->GetObjectID()); + if (shootingGalleryComponent != nullptr) { + shootingGalleryComponent->SetCurrentPlayerID(player->GetObjectID()); - Game::logger->Log("SGCannon", "Setting player ID"); + Game::logger->Log("SGCannon", "Setting player ID"); - EntityManager::Instance()->SerializeEntity(self); - } - else { - Game::logger->Log("SGCannon", "Shooting gallery component is null"); - } + EntityManager::Instance()->SerializeEntity(self); + } else { + Game::logger->Log("SGCannon", "Shooting gallery component is null"); + } - auto* characterComponent = player->GetComponent(); + auto* characterComponent = player->GetComponent(); - if (characterComponent != nullptr) { - characterComponent->SetIsRacing(true); - characterComponent->SetCurrentActivity(2); - auto possessor = player->GetComponent(); - if(possessor) { - possessor->SetPossessable(self->GetObjectID()); - possessor->SetPossessableType(ePossessionType::NO_POSSESSION); - } + if (characterComponent != nullptr) { + characterComponent->SetIsRacing(true); + characterComponent->SetCurrentActivity(2); + auto possessor = player->GetComponent(); + if (possessor) { + possessor->SetPossessable(self->GetObjectID()); + possessor->SetPossessableType(ePossessionType::NO_POSSESSION); + } - EntityManager::Instance()->SerializeEntity(player); - } + EntityManager::Instance()->SerializeEntity(player); + } - self->SetNetworkVar(HideScoreBoardVariable, true); - self->SetNetworkVar(ReSetSuperChargeVariable, true); - self->SetNetworkVar(ShowLoadingUI, true); + self->SetNetworkVar(HideScoreBoardVariable, true); + self->SetNetworkVar(ReSetSuperChargeVariable, true); + self->SetNetworkVar(ShowLoadingUI, true); - /* - GameMessages::SendTeleport( - player->GetObjectID(), - {-292.6415710449219, 230.20237731933594, -3.9090466499328613}, - {0.7067984342575073, -6.527870573336259e-05, 0.707414984703064, 0.00021762956748716533}, - player->GetSystemAddress(), true - ); - */ + /* + GameMessages::SendTeleport( + player->GetObjectID(), + {-292.6415710449219, 230.20237731933594, -3.9090466499328613}, + {0.7067984342575073, -6.527870573336259e-05, 0.707414984703064, 0.00021762956748716533}, + player->GetSystemAddress(), true + ); + */ - //GameMessages::SendRequestActivityEnter(self->GetObjectID(), player->GetSystemAddress(), false, player->GetObjectID()); - } - else { - Game::logger->Log("SGCannon", "Player not found"); - } - } - else if (value1 == 1200) { - StartGame(self); - } + //GameMessages::SendRequestActivityEnter(self->GetObjectID(), player->GetSystemAddress(), false, player->GetObjectID()); + } else { + Game::logger->Log("SGCannon", "Player not found"); + } + } else if (value1 == 1200) { + StartGame(self); + } } -void SGCannon::OnMessageBoxResponse(Entity *self, Entity *sender, int32_t button, const std::u16string &identifier, - const std::u16string &userData) { - auto * player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - if (button == 1 && identifier == u"Shooting_Gallery_Stop") - { - UpdatePlayer(self, player->GetObjectID(), true); - RemovePlayer(player->GetObjectID()); - StopGame(self, true); - return; - } +void SGCannon::OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, + const std::u16string& userData) { + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + if (button == 1 && identifier == u"Shooting_Gallery_Stop") { + UpdatePlayer(self, player->GetObjectID(), true); + RemovePlayer(player->GetObjectID()); + StopGame(self, true); + return; + } - if (identifier == u"Scoreboardinfo") { - GameMessages::SendDisplayMessageBox(player->GetObjectID(), true, - dZoneManager::Instance()->GetZoneControlObject()->GetObjectID(), - u"Shooting_Gallery_Retry?", 2, u"Retry?", - u"", player->GetSystemAddress()); - } else { - if ((button == 1 && (identifier == u"Shooting_Gallery_Retry" || identifier == u"RePlay")) - || identifier == u"SG1" || button == 0) { + if (identifier == u"Scoreboardinfo") { + GameMessages::SendDisplayMessageBox(player->GetObjectID(), true, + dZoneManager::Instance()->GetZoneControlObject()->GetObjectID(), + u"Shooting_Gallery_Retry?", 2, u"Retry?", + u"", player->GetSystemAddress()); + } else { + if ((button == 1 && (identifier == u"Shooting_Gallery_Retry" || identifier == u"RePlay")) + || identifier == u"SG1" || button == 0) { - if (identifier == u"RePlay") { - static_cast(player)->SendToZone(1300); + if (identifier == u"RePlay") { + static_cast(player)->SendToZone(1300); - return; - } + return; + } - self->SetNetworkVar(ClearVariable, true); - StartGame(self); - } else if (button == 1 && identifier == u"Shooting_Gallery_Exit") { - UpdatePlayer(self, player->GetObjectID(), true); - RemovePlayer(player->GetObjectID()); - } - } - } + self->SetNetworkVar(ClearVariable, true); + StartGame(self); + } else if (button == 1 && identifier == u"Shooting_Gallery_Exit") { + UpdatePlayer(self, player->GetObjectID(), true); + RemovePlayer(player->GetObjectID()); + } + } + } } -void SGCannon::OnActivityTimerDone(Entity *self, const std::string &name) { - if (name == SuperChargeTimer && !self->GetVar(SuperChargePausedVariable)) { - if (self->GetVar(WaveStatusVariable) || self->GetVar(CurrentSuperChargedTimeVariable) < 1) { - self->SetNetworkVar(ChargeCountingVariable, 99); - self->SetNetworkVar(SuperChargeBarVariable, 0); - ToggleSuperCharge(self, false); - } - } else if (name == SpawnWaveTimer) { - if (self->GetVar(GameStartedVariable)) { - self->SetVar(WaveStatusVariable, true); - const auto wave = (int32_t) self->GetVar(ThisWaveVariable); +void SGCannon::OnActivityTimerDone(Entity* self, const std::string& name) { + if (name == SuperChargeTimer && !self->GetVar(SuperChargePausedVariable)) { + if (self->GetVar(WaveStatusVariable) || self->GetVar(CurrentSuperChargedTimeVariable) < 1) { + self->SetNetworkVar(ChargeCountingVariable, 99); + self->SetNetworkVar(SuperChargeBarVariable, 0); + ToggleSuperCharge(self, false); + } + } else if (name == SpawnWaveTimer) { + if (self->GetVar(GameStartedVariable)) { + self->SetVar(WaveStatusVariable, true); + const auto wave = (int32_t)self->GetVar(ThisWaveVariable); - if (wave != 0 && self->GetVar(SuperChargePausedVariable)) { - StartChargedCannon(self, self->GetVar(CurrentSuperChargedTimeVariable)); - self->SetVar(CurrentSuperChargedTimeVariable, 0); - } + if (wave != 0 && self->GetVar(SuperChargePausedVariable)) { + StartChargedCannon(self, self->GetVar(CurrentSuperChargedTimeVariable)); + self->SetVar(CurrentSuperChargedTimeVariable, 0); + } - TimerToggle(self, true); + TimerToggle(self, true); - for (const auto& enemyToSpawn : m_Waves.at(self->GetVar(ThisWaveVariable))) { - SpawnObject(self, enemyToSpawn, true); - } + for (const auto& enemyToSpawn : m_Waves.at(self->GetVar(ThisWaveVariable))) { + SpawnObject(self, enemyToSpawn, true); + } - Game::logger->Log("SGCannon", "Current wave spawn: %i/%i", wave, m_Waves.size()); + Game::logger->Log("SGCannon", "Current wave spawn: %i/%i", wave, m_Waves.size()); - // All waves completed - const auto timeLimit = (float_t) self->GetVar(TimeLimitVariable); - if (wave >= m_Waves.size()) { - ActivityTimerStart(self, GameOverTimer, timeLimit, timeLimit); - } else { - ActivityTimerStart(self, EndWaveTimer, timeLimit, timeLimit); - } + // All waves completed + const auto timeLimit = (float_t)self->GetVar(TimeLimitVariable); + if (wave >= m_Waves.size()) { + ActivityTimerStart(self, GameOverTimer, timeLimit, timeLimit); + } else { + ActivityTimerStart(self, EndWaveTimer, timeLimit, timeLimit); + } - const auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - GameMessages::SendPlayFXEffect(player->GetObjectID(), -1, u"SG-start", ""); + const auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + GameMessages::SendPlayFXEffect(player->GetObjectID(), -1, u"SG-start", ""); - GameMessages::SendStartActivityTime(self->GetObjectID(), timeLimit, player->GetSystemAddress()); - Game::logger->Log("SGCannon", "Sending ActivityPause false"); + GameMessages::SendStartActivityTime(self->GetObjectID(), timeLimit, player->GetSystemAddress()); + Game::logger->Log("SGCannon", "Sending ActivityPause false"); - GameMessages::SendActivityPause(self->GetObjectID(), false, player->GetSystemAddress()); - } - } - } else if (name == EndWaveTimer) { - self->SetVar(WaveStatusVariable, false); - TimerToggle(self); - RecordPlayerScore(self); + GameMessages::SendActivityPause(self->GetObjectID(), false, player->GetSystemAddress()); + } + } + } else if (name == EndWaveTimer) { + self->SetVar(WaveStatusVariable, false); + TimerToggle(self); + RecordPlayerScore(self); - if (self->GetVar(ThisWaveVariable) >= 2) { - GameMessages::SendActivityPause(self->GetObjectID(), true); - ActivityTimerStart(self, GameOverTimer, 0.1, 0.1); - return; - } + if (self->GetVar(ThisWaveVariable) >= 2) { + GameMessages::SendActivityPause(self->GetObjectID(), true); + ActivityTimerStart(self, GameOverTimer, 0.1, 0.1); + return; + } - self->SetVar(ThisWaveVariable, self->GetVar(ThisWaveVariable) + 1); - PlaySceneAnimation(self, u"wave" + GeneralUtils::to_u16string(self->GetVar(ThisWaveVariable)), true, true, 1.7f); - self->SetNetworkVar(WaveNumVariable, self->GetVar(ThisWaveVariable) + 1); - self->SetNetworkVar(WaveStrVariable, self->GetVar(TimeLimitVariable)); + self->SetVar(ThisWaveVariable, self->GetVar(ThisWaveVariable) + 1); + PlaySceneAnimation(self, u"wave" + GeneralUtils::to_u16string(self->GetVar(ThisWaveVariable)), true, true, 1.7f); + self->SetNetworkVar(WaveNumVariable, self->GetVar(ThisWaveVariable) + 1); + self->SetNetworkVar(WaveStrVariable, self->GetVar(TimeLimitVariable)); - Game::logger->Log("SGCannon", "Current wave: %i/%i", self->GetVar(ThisWaveVariable), m_Waves.size()); + Game::logger->Log("SGCannon", "Current wave: %i/%i", self->GetVar(ThisWaveVariable), m_Waves.size()); - if (self->GetVar(ThisWaveVariable) >= m_Waves.size()) { - ActivityTimerStart(self, GameOverTimer, 0.1, 0.1); - } else { - ActivityTimerStart(self, SpawnWaveTimer, constants.inBetweenWavePause, constants.inBetweenWavePause); - } + if (self->GetVar(ThisWaveVariable) >= m_Waves.size()) { + ActivityTimerStart(self, GameOverTimer, 0.1, 0.1); + } else { + ActivityTimerStart(self, SpawnWaveTimer, constants.inBetweenWavePause, constants.inBetweenWavePause); + } - Game::logger->Log("SGCannon", "Sending ActivityPause true"); + Game::logger->Log("SGCannon", "Sending ActivityPause true"); - GameMessages::SendActivityPause(self->GetObjectID(), true); - if (self->GetVar(SuperChargeActiveVariable) && !self->GetVar(SuperChargePausedVariable)) { - PauseChargeCannon(self); - } - } else if (name == GameOverTimer) { - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - Game::logger->Log("SGCannon", "Sending ActivityPause true"); + GameMessages::SendActivityPause(self->GetObjectID(), true); + if (self->GetVar(SuperChargeActiveVariable) && !self->GetVar(SuperChargePausedVariable)) { + PauseChargeCannon(self); + } + } else if (name == GameOverTimer) { + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + Game::logger->Log("SGCannon", "Sending ActivityPause true"); - GameMessages::SendActivityPause(self->GetObjectID(), true, player->GetSystemAddress()); + GameMessages::SendActivityPause(self->GetObjectID(), true, player->GetSystemAddress()); - /*const auto leftoverCannonballs = EntityManager::Instance()->GetEntitiesInGroup("cannonball"); - if (leftoverCannonballs.empty()) { - RecordPlayerScore(self); + /*const auto leftoverCannonballs = EntityManager::Instance()->GetEntitiesInGroup("cannonball"); + if (leftoverCannonballs.empty()) { + RecordPlayerScore(self); - } else { - ActivityTimerStart(self, EndGameBufferTimer, 1, leftoverCannonballs.size()); - }*/ + } else { + ActivityTimerStart(self, EndGameBufferTimer, 1, leftoverCannonballs.size()); + }*/ - ActivityTimerStart(self, EndGameBufferTimer, 1, 1); + ActivityTimerStart(self, EndGameBufferTimer, 1, 1); - TimerToggle(self); - } - } else if (name.rfind(DoSpawnTimer, 0) == 0) { - if (self->GetVar(GameStartedVariable)) { - const auto spawnNumber = (uint32_t) std::stoi(name.substr(7)); - const auto& activeSpawns = self->GetVar>(ActiveSpawnsVariable); - const auto& toSpawn = activeSpawns.at(spawnNumber); + TimerToggle(self); + } + } else if (name.rfind(DoSpawnTimer, 0) == 0) { + if (self->GetVar(GameStartedVariable)) { + const auto spawnNumber = (uint32_t)std::stoi(name.substr(7)); + const auto& activeSpawns = self->GetVar>(ActiveSpawnsVariable); + const auto& toSpawn = activeSpawns.at(spawnNumber); - const auto pathIndex = GeneralUtils::GenerateRandomNumber(0, toSpawn.spawnPaths.size() - 1); + const auto pathIndex = GeneralUtils::GenerateRandomNumber(0, toSpawn.spawnPaths.size() - 1); - const auto* path = dZoneManager::Instance()->GetZone()->GetPath( - toSpawn.spawnPaths.at(pathIndex) - ); + const auto* path = dZoneManager::Instance()->GetZone()->GetPath( + toSpawn.spawnPaths.at(pathIndex) + ); - auto info = EntityInfo {}; - info.lot = toSpawn.lot; - info.spawnerID = self->GetObjectID(); - info.pos = path->pathWaypoints.at(0).position; + auto info = EntityInfo{}; + info.lot = toSpawn.lot; + info.spawnerID = self->GetObjectID(); + info.pos = path->pathWaypoints.at(0).position; - info.settings = { - new LDFData(u"SpawnData", toSpawn), - new LDFData(u"custom_script_server", "scripts/ai/ACT/SG_TARGET.lua"), - new LDFData(u"custom_script_client", "scripts/client/ai/SG_TARGET_CLIENT.lua"), - new LDFData(u"attached_path", path->pathName), - new LDFData(u"attached_path_start", 0), - new LDFData(u"groupID", u"SGEnemy") - }; + info.settings = { + new LDFData(u"SpawnData", toSpawn), + new LDFData(u"custom_script_server", "scripts/ai/ACT/SG_TARGET.lua"), + new LDFData(u"custom_script_client", "scripts/client/ai/SG_TARGET_CLIENT.lua"), + new LDFData(u"attached_path", path->pathName), + new LDFData(u"attached_path_start", 0), + new LDFData(u"groupID", u"SGEnemy") + }; - Game::logger->Log("SGCannon", "Spawning enemy %i on path %s", toSpawn.lot, path->pathName.c_str()); + Game::logger->Log("SGCannon", "Spawning enemy %i on path %s", toSpawn.lot, path->pathName.c_str()); - auto* enemy = EntityManager::Instance()->CreateEntity(info, nullptr, self); - EntityManager::Instance()->ConstructEntity(enemy); + auto* enemy = EntityManager::Instance()->CreateEntity(info, nullptr, self); + EntityManager::Instance()->ConstructEntity(enemy); - if (true) { - auto* movementAI = new MovementAIComponent(enemy, {}); + if (true) { + auto* movementAI = new MovementAIComponent(enemy, {}); - enemy->AddComponent(COMPONENT_TYPE_MOVEMENT_AI, movementAI); + enemy->AddComponent(COMPONENT_TYPE_MOVEMENT_AI, movementAI); - movementAI->SetSpeed(toSpawn.initialSpeed); - movementAI->SetCurrentSpeed(toSpawn.initialSpeed); - movementAI->SetHaltDistance(0.0f); + movementAI->SetSpeed(toSpawn.initialSpeed); + movementAI->SetCurrentSpeed(toSpawn.initialSpeed); + movementAI->SetHaltDistance(0.0f); - std::vector pathWaypoints; + std::vector pathWaypoints; - for (const auto& waypoint : path->pathWaypoints) { - pathWaypoints.push_back(waypoint.position); - } + for (const auto& waypoint : path->pathWaypoints) { + pathWaypoints.push_back(waypoint.position); + } - if (GeneralUtils::GenerateRandomNumber(0, 1) < 0.5f) { - std::reverse(pathWaypoints.begin(), pathWaypoints.end()); - } + if (GeneralUtils::GenerateRandomNumber(0, 1) < 0.5f) { + std::reverse(pathWaypoints.begin(), pathWaypoints.end()); + } - movementAI->SetPath(pathWaypoints); + movementAI->SetPath(pathWaypoints); - enemy->AddDieCallback([this, self, enemy, name] () { - RegisterHit(self, enemy, name); - }); - } + enemy->AddDieCallback([this, self, enemy, name]() { + RegisterHit(self, enemy, name); + }); + } - // Save the enemy and tell it to start pathing - if (enemy != nullptr) { - const_cast&>(self->GetVar>(SpawnedObjects)).push_back(enemy->GetObjectID()); - GameMessages::SendPlatformResync(enemy, UNASSIGNED_SYSTEM_ADDRESS); - } - } - } else if (name == EndGameBufferTimer) { - RecordPlayerScore(self); - StopGame(self, false); - } + // Save the enemy and tell it to start pathing + if (enemy != nullptr) { + const_cast&>(self->GetVar>(SpawnedObjects)).push_back(enemy->GetObjectID()); + GameMessages::SendPlatformResync(enemy, UNASSIGNED_SYSTEM_ADDRESS); + } + } + } else if (name == EndGameBufferTimer) { + RecordPlayerScore(self); + StopGame(self, false); + } } void -SGCannon::OnActivityTimerUpdate(Entity *self, const std::string &name, float_t timeRemaining, float_t elapsedTime) { - ActivityManager::OnActivityTimerUpdate(self, name, timeRemaining, elapsedTime); +SGCannon::OnActivityTimerUpdate(Entity* self, const std::string& name, float_t timeRemaining, float_t elapsedTime) { + ActivityManager::OnActivityTimerUpdate(self, name, timeRemaining, elapsedTime); } -void SGCannon::StartGame(Entity *self) { - self->SetNetworkVar(TimeLimitVariable, self->GetVar(TimeLimitVariable)); - self->SetNetworkVar(AudioStartIntroVariable, true); - self->SetVar(CurrentRewardVariable, LOT_NULL); +void SGCannon::StartGame(Entity* self) { + self->SetNetworkVar(TimeLimitVariable, self->GetVar(TimeLimitVariable)); + self->SetNetworkVar(AudioStartIntroVariable, true); + self->SetVar(CurrentRewardVariable, LOT_NULL); - auto rewardObjects = EntityManager::Instance()->GetEntitiesInGroup(constants.rewardModelGroup); - for (auto* reward : rewardObjects) { - reward->OnFireEventServerSide(self, ModelToBuildEvent); - } + auto rewardObjects = EntityManager::Instance()->GetEntitiesInGroup(constants.rewardModelGroup); + for (auto* reward : rewardObjects) { + reward->OnFireEventServerSide(self, ModelToBuildEvent); + } - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self)); - Game::logger->Log("SGCannon", "Sending ActivityStart"); - GameMessages::SendActivityStart(self->GetObjectID(), player->GetSystemAddress()); + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + GetLeaderboardData(self, player->GetObjectID(), GetActivityID(self)); + Game::logger->Log("SGCannon", "Sending ActivityStart"); + GameMessages::SendActivityStart(self->GetObjectID(), player->GetSystemAddress()); - GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"start", ""); + GameMessages::SendPlayFXEffect(self->GetObjectID(), -1, u"start", ""); - self->SetNetworkVar(ClearVariable, true); - DoGameStartup(self); + self->SetNetworkVar(ClearVariable, true); + DoGameStartup(self); - if (!self->GetVar(FirstTimeDoneVariable)) { - TakeActivityCost(self, player->GetObjectID()); - } + if (!self->GetVar(FirstTimeDoneVariable)) { + TakeActivityCost(self, player->GetObjectID()); + } - self->SetVar(FirstTimeDoneVariable, true); - } + self->SetVar(FirstTimeDoneVariable, true); + } - SpawnNewModel(self); + SpawnNewModel(self); } -void SGCannon::DoGameStartup(Entity *self) { - ResetVars(self); - self->SetVar(GameStartedVariable, true); - self->SetNetworkVar(ClearVariable, true); - self->SetVar(ThisWaveVariable, 0); +void SGCannon::DoGameStartup(Entity* self) { + ResetVars(self); + self->SetVar(GameStartedVariable, true); + self->SetNetworkVar(ClearVariable, true); + self->SetVar(ThisWaveVariable, 0); - if (constants.firstWaveStartTime < 1) { - constants.firstWaveStartTime = 1; - } + if (constants.firstWaveStartTime < 1) { + constants.firstWaveStartTime = 1; + } - ActivityTimerStart(self, SpawnWaveTimer, constants.firstWaveStartTime, - constants.firstWaveStartTime); + ActivityTimerStart(self, SpawnWaveTimer, constants.firstWaveStartTime, + constants.firstWaveStartTime); } -void SGCannon::SpawnNewModel(Entity *self) { +void SGCannon::SpawnNewModel(Entity* self) { - // Add a new reward to the existing rewards - const auto currentReward = self->GetVar(CurrentRewardVariable); - if (currentReward != -1) { - auto rewards = self->GetVar>(RewardsVariable); - rewards.push_back(currentReward); - self->SetNetworkVar(RewardAddedVariable, currentReward); - } + // Add a new reward to the existing rewards + const auto currentReward = self->GetVar(CurrentRewardVariable); + if (currentReward != -1) { + auto rewards = self->GetVar>(RewardsVariable); + rewards.push_back(currentReward); + self->SetNetworkVar(RewardAddedVariable, currentReward); + } - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - for (auto* rewardModel : EntityManager::Instance()->GetEntitiesInGroup(constants.rewardModelGroup)) { - uint32_t lootMatrix; - switch (self->GetVar(MatrixVariable)) { - case 1: - lootMatrix = constants.scoreLootMatrix1; - break; - case 2: - lootMatrix = constants.scoreLootMatrix2; - break; - case 3: - lootMatrix = constants.scoreLootMatrix3; - break; - case 4: - lootMatrix = constants.scoreLootMatrix4; - break; - case 5: - lootMatrix = constants.scoreLootMatrix5; - break; - default: - lootMatrix = 0; - } + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + for (auto* rewardModel : EntityManager::Instance()->GetEntitiesInGroup(constants.rewardModelGroup)) { + uint32_t lootMatrix; + switch (self->GetVar(MatrixVariable)) { + case 1: + lootMatrix = constants.scoreLootMatrix1; + break; + case 2: + lootMatrix = constants.scoreLootMatrix2; + break; + case 3: + lootMatrix = constants.scoreLootMatrix3; + break; + case 4: + lootMatrix = constants.scoreLootMatrix4; + break; + case 5: + lootMatrix = constants.scoreLootMatrix5; + break; + default: + lootMatrix = 0; + } - if (lootMatrix != 0) { - std::unordered_map toDrop = {}; - toDrop = LootGenerator::Instance().RollLootMatrix(player, lootMatrix); + if (lootMatrix != 0) { + std::unordered_map toDrop = {}; + toDrop = LootGenerator::Instance().RollLootMatrix(player, lootMatrix); - for (auto drop : toDrop) { - rewardModel->OnFireEventServerSide(self, ModelToBuildEvent, drop.first); - self->SetVar(CurrentRewardVariable, drop.first); - } - } - } - } + for (auto drop : toDrop) { + rewardModel->OnFireEventServerSide(self, ModelToBuildEvent, drop.first); + self->SetVar(CurrentRewardVariable, drop.first); + } + } + } + } } void SGCannon::RemovePlayer(LWOOBJID playerID) { - auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player == nullptr) - return; + auto* player = EntityManager::Instance()->GetEntity(playerID); + if (player == nullptr) + return; - auto* playerObject = dynamic_cast(player); - if (playerObject == nullptr) - return; + auto* playerObject = dynamic_cast(player); + if (playerObject == nullptr) + return; - auto* character = playerObject->GetCharacter(); - if (character != nullptr) { - playerObject->SendToZone(character->GetLastNonInstanceZoneID()); - } + auto* character = playerObject->GetCharacter(); + if (character != nullptr) { + playerObject->SendToZone(character->GetLastNonInstanceZoneID()); + } } -void SGCannon::StartChargedCannon(Entity *self, uint32_t optionalTime) { - optionalTime = optionalTime == 0 ? constants.chargedTime : optionalTime; - self->SetVar(SuperChargePausedVariable, false); - ToggleSuperCharge(self, true); - ActivityTimerStart(self, SuperChargeTimer, 1, optionalTime); +void SGCannon::StartChargedCannon(Entity* self, uint32_t optionalTime) { + optionalTime = optionalTime == 0 ? constants.chargedTime : optionalTime; + self->SetVar(SuperChargePausedVariable, false); + ToggleSuperCharge(self, true); + ActivityTimerStart(self, SuperChargeTimer, 1, optionalTime); - if (!self->GetVar(WaveStatusVariable)) { - PauseChargeCannon(self); - } + if (!self->GetVar(WaveStatusVariable)) { + PauseChargeCannon(self); + } } -void SGCannon::TimerToggle(Entity *self, bool start) { - if (start) { - self->SetNetworkVar(CountVariable, self->GetVar(TimeLimitVariable)); - self->SetVar(GameStartedVariable, true); - } else { - self->SetNetworkVar(StopVariable, true); - } +void SGCannon::TimerToggle(Entity* self, bool start) { + if (start) { + self->SetNetworkVar(CountVariable, self->GetVar(TimeLimitVariable)); + self->SetVar(GameStartedVariable, true); + } else { + self->SetNetworkVar(StopVariable, true); + } } void SGCannon::SpawnObject(Entity* self, const SGEnemy& toSpawn, bool spawnNow) { - auto activeSpawns = self->GetVar>(ActiveSpawnsVariable); - activeSpawns.push_back(toSpawn); - self->SetVar>(ActiveSpawnsVariable, activeSpawns); + auto activeSpawns = self->GetVar>(ActiveSpawnsVariable); + activeSpawns.push_back(toSpawn); + self->SetVar>(ActiveSpawnsVariable, activeSpawns); - self->SetVar(SpawnNumberVariable, activeSpawns.size() - 1); - const auto timerName = DoSpawnTimer + std::to_string(activeSpawns.size() - 1); + self->SetVar(SpawnNumberVariable, activeSpawns.size() - 1); + const auto timerName = DoSpawnTimer + std::to_string(activeSpawns.size() - 1); - if (spawnNow) { - if (toSpawn.minSpawnTime > 0 && toSpawn.maxSpawnTime > 0) { - const auto spawnTime = GeneralUtils::GenerateRandomNumber(toSpawn.minSpawnTime, toSpawn.maxSpawnTime); + if (spawnNow) { + if (toSpawn.minSpawnTime > 0 && toSpawn.maxSpawnTime > 0) { + const auto spawnTime = GeneralUtils::GenerateRandomNumber(toSpawn.minSpawnTime, toSpawn.maxSpawnTime); - ActivityTimerStart(self, timerName, spawnTime, spawnTime); - } else { - ActivityTimerStart(self, timerName, 1, 1); - } - } else if (toSpawn.respawns) { - const auto spawnTime = GeneralUtils::GenerateRandomNumber(toSpawn.minRespawnTime, toSpawn.maxRespawnTime); + ActivityTimerStart(self, timerName, spawnTime, spawnTime); + } else { + ActivityTimerStart(self, timerName, 1, 1); + } + } else if (toSpawn.respawns) { + const auto spawnTime = GeneralUtils::GenerateRandomNumber(toSpawn.minRespawnTime, toSpawn.maxRespawnTime); - ActivityTimerStart(self, timerName, spawnTime, spawnTime); - } + ActivityTimerStart(self, timerName, spawnTime, spawnTime); + } } -void SGCannon::RecordPlayerScore(Entity *self) { - const auto totalScore = self->GetVar(TotalScoreVariable); - const auto currentWave = self->GetVar(ThisWaveVariable); +void SGCannon::RecordPlayerScore(Entity* self) { + const auto totalScore = self->GetVar(TotalScoreVariable); + const auto currentWave = self->GetVar(ThisWaveVariable); - if (currentWave > 0) { - auto totalWaveScore = 0; - auto playerScores = self->GetVar>(PlayerScoresVariable); + if (currentWave > 0) { + auto totalWaveScore = 0; + auto playerScores = self->GetVar>(PlayerScoresVariable); - for (const auto& waveScore : playerScores) { - totalWaveScore += waveScore; - } + for (const auto& waveScore : playerScores) { + totalWaveScore += waveScore; + } - if (currentWave >= playerScores.size()) { - playerScores.push_back(totalWaveScore); - } else { - playerScores[currentWave] = totalWaveScore; - } - } + if (currentWave >= playerScores.size()) { + playerScores.push_back(totalWaveScore); + } else { + playerScores[currentWave] = totalWaveScore; + } + } } void SGCannon::PlaySceneAnimation(Entity* self, const std::u16string& animationName, bool onCannon, bool onPlayer, float_t priority) { - for (auto* cannon : EntityManager::Instance()->GetEntitiesInGroup("cannongroup")) { - GameMessages::SendPlayAnimation(cannon, animationName, priority); - } + for (auto* cannon : EntityManager::Instance()->GetEntitiesInGroup("cannongroup")) { + GameMessages::SendPlayAnimation(cannon, animationName, priority); + } - if (onCannon) { - GameMessages::SendPlayAnimation(self, animationName, priority); - } + if (onCannon) { + GameMessages::SendPlayAnimation(self, animationName, priority); + } - if (onPlayer) { - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player != nullptr) { - GameMessages::SendPlayAnimation(player, animationName, priority); - } - } + if (onPlayer) { + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player != nullptr) { + GameMessages::SendPlayAnimation(player, animationName, priority); + } + } } -void SGCannon::PauseChargeCannon(Entity *self) { - const auto time = std::max((uint32_t) std::ceil(ActivityTimerGetCurrentTime(self, SuperChargeTimer)), (uint32_t) 1); +void SGCannon::PauseChargeCannon(Entity* self) { + const auto time = std::max((uint32_t)std::ceil(ActivityTimerGetCurrentTime(self, SuperChargeTimer)), (uint32_t)1); - self->SetVar(SuperChargePausedVariable, true); - self->SetVar(CurrentSuperChargedTimeVariable, time); - self->SetNetworkVar(ChargeCountingVariable, time); + self->SetVar(SuperChargePausedVariable, true); + self->SetVar(CurrentSuperChargedTimeVariable, time); + self->SetNetworkVar(ChargeCountingVariable, time); - ActivityTimerStop(self, SuperChargeTimer); + ActivityTimerStop(self, SuperChargeTimer); } -void SGCannon::StopGame(Entity *self, bool cancel) { - self->SetNetworkVar(ReSetSuperChargeVariable, true); - self->SetNetworkVar(HideSuperChargeVariable, true); +void SGCannon::StopGame(Entity* self, bool cancel) { + self->SetNetworkVar(ReSetSuperChargeVariable, true); + self->SetNetworkVar(HideSuperChargeVariable, true); - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player == nullptr) - return; + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player == nullptr) + return; - ToggleSuperCharge(self, false); + ToggleSuperCharge(self, false); - // The player won, store all the score and send rewards - if (!cancel) { - auto percentage = 0; - auto misses = self->GetVar(MissesVariable); - auto fired = self->GetVar(ShotsFiredVariable); + // The player won, store all the score and send rewards + if (!cancel) { + auto percentage = 0; + auto misses = self->GetVar(MissesVariable); + auto fired = self->GetVar(ShotsFiredVariable); - if (fired > 0) { - percentage = misses / fired; - } + if (fired > 0) { + percentage = misses / fired; + } - auto* missionComponent = player->GetComponent(); + auto* missionComponent = player->GetComponent(); - if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar(TotalScoreVariable), self->GetObjectID(), "performact_score"); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar(MaxStreakVariable), self->GetObjectID(), "performact_streak"); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ACTIVITY, m_CannonLot, 0, "", self->GetVar(TotalScoreVariable)); - } + if (missionComponent != nullptr) { + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar(TotalScoreVariable), self->GetObjectID(), "performact_score"); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar(MaxStreakVariable), self->GetObjectID(), "performact_streak"); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ACTIVITY, m_CannonLot, 0, "", self->GetVar(TotalScoreVariable)); + } - LootGenerator::Instance().GiveActivityLoot(player, self, GetGameID(self), self->GetVar(TotalScoreVariable)); + LootGenerator::Instance().GiveActivityLoot(player, self, GetGameID(self), self->GetVar(TotalScoreVariable)); - StopActivity(self, player->GetObjectID(), self->GetVar(TotalScoreVariable), self->GetVar(MaxStreakVariable), percentage); - self->SetNetworkVar(AudioFinalWaveDoneVariable, true); + StopActivity(self, player->GetObjectID(), self->GetVar(TotalScoreVariable), self->GetVar(MaxStreakVariable), percentage); + self->SetNetworkVar(AudioFinalWaveDoneVariable, true); - // Give the player the model rewards they earned - auto* inventory = player->GetComponent(); - if (inventory != nullptr) { - for (const auto rewardLot : self->GetVar>(RewardsVariable)) { - inventory->AddItem(rewardLot, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY, eInventoryType::MODELS); - } - } + // Give the player the model rewards they earned + auto* inventory = player->GetComponent(); + if (inventory != nullptr) { + for (const auto rewardLot : self->GetVar>(RewardsVariable)) { + inventory->AddItem(rewardLot, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY, eInventoryType::MODELS); + } + } - self->SetNetworkVar(u"UI_Rewards", - GeneralUtils::to_u16string(self->GetVar(TotalScoreVariable)) + u"_0_0_0_0_0_0" - ); + self->SetNetworkVar(u"UI_Rewards", + GeneralUtils::to_u16string(self->GetVar(TotalScoreVariable)) + u"_0_0_0_0_0_0" + ); - GameMessages::SendRequestActivitySummaryLeaderboardData( - player->GetObjectID(), - self->GetObjectID(), - player->GetSystemAddress(), - GetGameID(self), - 1, - 10, - 0, - false - ); - } + GameMessages::SendRequestActivitySummaryLeaderboardData( + player->GetObjectID(), + self->GetObjectID(), + player->GetSystemAddress(), + GetGameID(self), + 1, + 10, + 0, + false + ); + } - GameMessages::SendActivityStop(self->GetObjectID(), false, cancel, player->GetSystemAddress()); - self->SetVar(GameStartedVariable, false); - ActivityTimerStopAllTimers(self); + GameMessages::SendActivityStop(self->GetObjectID(), false, cancel, player->GetSystemAddress()); + self->SetVar(GameStartedVariable, false); + ActivityTimerStopAllTimers(self); - // Destroy all spawners - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup("SGEnemy")) { - entity->Kill(); - } + // Destroy all spawners + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup("SGEnemy")) { + entity->Kill(); + } - ResetVars(self); + ResetVars(self); } -void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& timerName) -{ - const auto& spawnInfo = target->GetVar(u"SpawnData"); +void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& timerName) { + const auto& spawnInfo = target->GetVar(u"SpawnData"); - if (spawnInfo.respawns) - { - const auto respawnTime = GeneralUtils::GenerateRandomNumber(spawnInfo.minRespawnTime, spawnInfo.maxRespawnTime); + if (spawnInfo.respawns) { + const auto respawnTime = GeneralUtils::GenerateRandomNumber(spawnInfo.minRespawnTime, spawnInfo.maxRespawnTime); - ActivityTimerStart(self, timerName, respawnTime, respawnTime); - } + ActivityTimerStart(self, timerName, respawnTime, respawnTime); + } - int score = spawnInfo.score; + int score = spawnInfo.score; - if (score > 0) { - score += score * GetCurrentBonus(self); + if (score > 0) { + score += score * GetCurrentBonus(self); - if (!self->GetVar(SuperChargeActiveVariable)) { - self->SetVar(u"m_curStreak", self->GetVar(u"m_curStreak") + 1); - } - } - else { - if (!self->GetVar(SuperChargeActiveVariable)) { - self->SetVar(u"m_curStreak", 0); - } + if (!self->GetVar(SuperChargeActiveVariable)) { + self->SetVar(u"m_curStreak", self->GetVar(u"m_curStreak") + 1); + } + } else { + if (!self->GetVar(SuperChargeActiveVariable)) { + self->SetVar(u"m_curStreak", 0); + } - self->SetNetworkVar(u"hitFriend", true); - } + self->SetNetworkVar(u"hitFriend", true); + } - auto lastSuperTotal = self->GetVar(u"LastSuperTotal"); + auto lastSuperTotal = self->GetVar(u"LastSuperTotal"); - auto scScore = self->GetVar(TotalScoreVariable) - lastSuperTotal; + auto scScore = self->GetVar(TotalScoreVariable) - lastSuperTotal; - Game::logger->Log("SGCannon", "LastSuperTotal: %i, scScore: %i, constants.chargedPoints: %i", - lastSuperTotal, scScore, constants.chargedPoints - ); + Game::logger->Log("SGCannon", "LastSuperTotal: %i, scScore: %i, constants.chargedPoints: %i", + lastSuperTotal, scScore, constants.chargedPoints + ); - if (!self->GetVar(SuperChargeActiveVariable) && scScore >= constants.chargedPoints && score >= 0) { - StartChargedCannon(self); - self->SetNetworkVar(u"SuperChargeBar", 100.0f); - self->SetVar(u"LastSuperTotal", self->GetVar(TotalScoreVariable)); - } + if (!self->GetVar(SuperChargeActiveVariable) && scScore >= constants.chargedPoints && score >= 0) { + StartChargedCannon(self); + self->SetNetworkVar(u"SuperChargeBar", 100.0f); + self->SetVar(u"LastSuperTotal", self->GetVar(TotalScoreVariable)); + } - UpdateStreak(self); + UpdateStreak(self); - GameMessages::SendNotifyClientShootingGalleryScore(self->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS, - 0.0f, - score, - target->GetObjectID(), - target->GetPosition() - ); + GameMessages::SendNotifyClientShootingGalleryScore(self->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS, + 0.0f, + score, + target->GetObjectID(), + target->GetPosition() + ); - auto newScore = (int) self->GetVar(TotalScoreVariable) + score; + auto newScore = (int)self->GetVar(TotalScoreVariable) + score; - if (newScore < 0) { - newScore = 0; - } + if (newScore < 0) { + newScore = 0; + } - self->SetVar(TotalScoreVariable, newScore); + self->SetVar(TotalScoreVariable, newScore); - self->SetNetworkVar(u"updateScore", newScore); + self->SetNetworkVar(u"updateScore", newScore); - self->SetNetworkVar(u"beatHighScore", GeneralUtils::to_u16string(newScore)); + self->SetNetworkVar(u"beatHighScore", GeneralUtils::to_u16string(newScore)); - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player == nullptr) return; + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + if (player == nullptr) return; - auto missionComponent = player->GetComponent(); - if (missionComponent == nullptr) return; + auto missionComponent = player->GetComponent(); + if (missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, spawnInfo.lot, self->GetObjectID()); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, spawnInfo.lot, self->GetObjectID()); } -void SGCannon::UpdateStreak(Entity* self) -{ - const auto streakBonus = GetCurrentBonus(self); +void SGCannon::UpdateStreak(Entity* self) { + const auto streakBonus = GetCurrentBonus(self); - const auto curStreak = self->GetVar(u"m_curStreak"); + const auto curStreak = self->GetVar(u"m_curStreak"); - const auto marks = curStreak % 3; + const auto marks = curStreak % 3; - self->SetNetworkVar(u"cStreak", curStreak); + self->SetNetworkVar(u"cStreak", curStreak); - if (curStreak >= 0 && curStreak < 13) { - if (marks == 1) { - self->SetNetworkVar(u"Mark1", true); - } - else if (marks == 2) { - self->SetNetworkVar(u"Mark2", true); - } - else if (marks == 0 && curStreak > 0) { - self->SetVar(u"StreakBonus", streakBonus); - self->SetNetworkVar(u"ShowStreak", streakBonus + 1); - self->SetNetworkVar(u"Mark3", true); - } - else { - self->SetVar(u"StreakBonus", streakBonus); - self->SetNetworkVar(u"UnMarkAll", true); - } - } - auto maxStreak = self->GetVar(MaxStreakVariable); - if (maxStreak < curStreak) self->SetVar(MaxStreakVariable, curStreak); + if (curStreak >= 0 && curStreak < 13) { + if (marks == 1) { + self->SetNetworkVar(u"Mark1", true); + } else if (marks == 2) { + self->SetNetworkVar(u"Mark2", true); + } else if (marks == 0 && curStreak > 0) { + self->SetVar(u"StreakBonus", streakBonus); + self->SetNetworkVar(u"ShowStreak", streakBonus + 1); + self->SetNetworkVar(u"Mark3", true); + } else { + self->SetVar(u"StreakBonus", streakBonus); + self->SetNetworkVar(u"UnMarkAll", true); + } + } + auto maxStreak = self->GetVar(MaxStreakVariable); + if (maxStreak < curStreak) self->SetVar(MaxStreakVariable, curStreak); } -float_t SGCannon::GetCurrentBonus(Entity* self) -{ - auto streak = self->GetVar(u"m_curStreak"); +float_t SGCannon::GetCurrentBonus(Entity* self) { + auto streak = self->GetVar(u"m_curStreak"); - if (streak > 12) { - streak = 12; - } + if (streak > 12) { + streak = 12; + } - return streak / 3; + return streak / 3; } -void SGCannon::ToggleSuperCharge(Entity *self, bool enable) { - if (enable && self->GetVar(SuperChargeActiveVariable)) - return; +void SGCannon::ToggleSuperCharge(Entity* self, bool enable) { + if (enable && self->GetVar(SuperChargeActiveVariable)) + return; - auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); + auto* player = EntityManager::Instance()->GetEntity(self->GetVar(PlayerIDVariable)); - if (player == nullptr) { - Game::logger->Log("SGCannon", "Player not found in toggle super charge"); - return; - } + if (player == nullptr) { + Game::logger->Log("SGCannon", "Player not found in toggle super charge"); + return; + } - auto* inventoryComponent = player->GetComponent(); + auto* inventoryComponent = player->GetComponent(); - auto equippedItems = inventoryComponent->GetEquippedItems(); + auto equippedItems = inventoryComponent->GetEquippedItems(); - Game::logger->Log("SGCannon", "Player has %d equipped items", equippedItems.size()); + Game::logger->Log("SGCannon", "Player has %d equipped items", equippedItems.size()); - auto skillID = constants.cannonSkill; - auto coolDown = constants.cannonRefireRate; + auto skillID = constants.cannonSkill; + auto coolDown = constants.cannonRefireRate; - auto* selfInventoryComponent = self->GetComponent(); + auto* selfInventoryComponent = self->GetComponent(); - if (inventoryComponent == nullptr) { - Game::logger->Log("SGCannon", "Inventory component not found"); - return; - } + if (inventoryComponent == nullptr) { + Game::logger->Log("SGCannon", "Inventory component not found"); + return; + } - if (enable) { - Game::logger->Log("SGCannon", "Player is activating super charge"); - selfInventoryComponent->UpdateSlot("greeble_r", { ObjectIDManager::GenerateRandomObjectID(), 6505, 1, 0 }); - selfInventoryComponent->UpdateSlot("greeble_l", { ObjectIDManager::GenerateRandomObjectID(), 6506, 1, 0 }); + if (enable) { + Game::logger->Log("SGCannon", "Player is activating super charge"); + selfInventoryComponent->UpdateSlot("greeble_r", { ObjectIDManager::GenerateRandomObjectID(), 6505, 1, 0 }); + selfInventoryComponent->UpdateSlot("greeble_l", { ObjectIDManager::GenerateRandomObjectID(), 6506, 1, 0 }); - // TODO: Equip items - skillID = constants.cannonSuperChargeSkill; - coolDown = 400; - } else { - selfInventoryComponent->UpdateSlot("greeble_r", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); - selfInventoryComponent->UpdateSlot("greeble_l", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); + // TODO: Equip items + skillID = constants.cannonSuperChargeSkill; + coolDown = 400; + } else { + selfInventoryComponent->UpdateSlot("greeble_r", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); + selfInventoryComponent->UpdateSlot("greeble_l", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); - self->SetNetworkVar(u"SuperChargeBar", 0); + self->SetNetworkVar(u"SuperChargeBar", 0); - Game::logger->Log("SGCannon", "Player disables super charge"); + Game::logger->Log("SGCannon", "Player disables super charge"); - // TODO: Unequip items - for (const auto& equipped : equippedItems) { - if (equipped.first == "special_r" || equipped.first == "special_l") { - Game::logger->Log("SGCannon", "Trying to unequip a weapon, %i", equipped.second.lot); + // TODO: Unequip items + for (const auto& equipped : equippedItems) { + if (equipped.first == "special_r" || equipped.first == "special_l") { + Game::logger->Log("SGCannon", "Trying to unequip a weapon, %i", equipped.second.lot); - auto* item = inventoryComponent->FindItemById(equipped.second.id); + auto* item = inventoryComponent->FindItemById(equipped.second.id); - if (item != nullptr) { - inventoryComponent->UnEquipItem(item); - } - else { - Game::logger->Log("SGCannon", "Item not found, %i", equipped.second.lot); - } - } - } + if (item != nullptr) { + inventoryComponent->UnEquipItem(item); + } else { + Game::logger->Log("SGCannon", "Item not found, %i", equipped.second.lot); + } + } + } - self->SetVar(NumberOfChargesVariable, 0); - } + self->SetVar(NumberOfChargesVariable, 0); + } - const auto& constants = GetConstants(); + const auto& constants = GetConstants(); - auto* shootingGalleryComponent = self->GetComponent(); + auto* shootingGalleryComponent = self->GetComponent(); - if (shootingGalleryComponent == nullptr) { - return; - } + if (shootingGalleryComponent == nullptr) { + return; + } - DynamicShootingGalleryParams properties = shootingGalleryComponent->GetDynamicParams(); + DynamicShootingGalleryParams properties = shootingGalleryComponent->GetDynamicParams(); - properties.cannonFOV = 58.6f; - properties.cannonVelocity = 129.0; - properties.cannonRefireRate = 800; - properties.cannonMinDistance = 30; - properties.cannonTimeout = -1; + properties.cannonFOV = 58.6f; + properties.cannonVelocity = 129.0; + properties.cannonRefireRate = 800; + properties.cannonMinDistance = 30; + properties.cannonTimeout = -1; - shootingGalleryComponent->SetDynamicParams(properties); + shootingGalleryComponent->SetDynamicParams(properties); - EntityManager::Instance()->SerializeEntity(self); - EntityManager::Instance()->SerializeEntity(player); + EntityManager::Instance()->SerializeEntity(self); + EntityManager::Instance()->SerializeEntity(player); - self->SetNetworkVar(CannonBallSkillIDVariable, skillID); - self->SetVar(SuperChargeActiveVariable, enable); + self->SetNetworkVar(CannonBallSkillIDVariable, skillID); + self->SetVar(SuperChargeActiveVariable, enable); } std::vector> SGCannon::GetWaves() { - return { - // Wave 1 - { - // Ship 1 - { - std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1500, false, 0.0, 1.0, - 1.0, false, true - }, + return { + // Wave 1 + { + // Ship 1 + { + std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, + 6015, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 2 - { - std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 2 + { + std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, + 6300, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 500, false, 0.0, 1.0, + 1.0, false, true + }, - // Sub 1 - { - std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 10.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 1 + { + std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 10.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Sub 2 - { - std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 2 + { + std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Friendly - { - std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, - 2168,0.0,5.0,true, 2.0, 5.0, - 1.0, -1000, false, 0.0, 1.0, - 1.0, false,true - } - }, + // Friendly + { + std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, + 2168,0.0,5.0,true, 2.0, 5.0, + 1.0, -1000, false, 0.0, 1.0, + 1.0, false,true + } + }, - // Wave 2 - { - // Ship 1 - { - std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1500, false, 0.0, 1.0, - 1.0, false, true - }, + // Wave 2 + { + // Ship 1 + { + std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, + 6015, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 2 - { - std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 2 + { + std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, + 6300, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 3 - { - std::vector { "Wave_2_Ship_1" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 3 + { + std::vector { "Wave_2_Ship_1" }, + 6300, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 4 - { - std::vector { "Wave_2_Ship_2" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 4 + { + std::vector { "Wave_2_Ship_2" }, + 6015, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 500, false, 0.0, 1.0, + 1.0, false, true + }, - // Sub 1 - { - std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 1 + { + std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Sub 2 - { - std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 2 + { + std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Duck - { - std::vector { "Wave_1_Duck_1", "Wave_1_Duck_2" }, - 5946, 5.0, 10.0, true, 5.0, 10.0, - 4.0, 5000, false, 0.0, 1.0, - 1.0, false, true - }, + // Duck + { + std::vector { "Wave_1_Duck_1", "Wave_1_Duck_2" }, + 5946, 5.0, 10.0, true, 5.0, 10.0, + 4.0, 5000, false, 0.0, 1.0, + 1.0, false, true + }, - // Friendly - { - std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, - 2168,0.0,5.0,true, 2.0, 5.0, - 1.0, -1000, false, 0.0, 1.0, - 1.0, false,true - } - }, + // Friendly + { + std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, + 2168,0.0,5.0,true, 2.0, 5.0, + 1.0, -1000, false, 0.0, 1.0, + 1.0, false,true + } + }, - // Wave 3 - { - // Ship 1 - { - std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1500, false, 0.0, 1.0, - 1.0, false, true - }, + // Wave 3 + { + // Ship 1 + { + std::vector { "Wave_1_Ship_1", "Wave_1_Ship_3" }, + 6015, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 2 - { - std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 2 + { + std::vector { "Wave_1_Ship_2", "Wave_1_Ship_4" }, + 6300, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 3 - { - std::vector { "Wave_2_Ship_1", "Wave_2_Ship_2" }, - 6015, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 3 + { + std::vector { "Wave_2_Ship_1", "Wave_2_Ship_2" }, + 6015, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 500, false, 0.0, 1.0, + 1.0, false, true + }, - // Ship 4 - { - std::vector { "Wave_3_Ship_1", "Wave_3_Ship_2" }, - 6300, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1500, false, 0.0, 1.0, - 1.0, false, true - }, + // Ship 4 + { + std::vector { "Wave_3_Ship_1", "Wave_3_Ship_2" }, + 6300, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1500, false, 0.0, 1.0, + 1.0, false, true + }, - // Sub 1 - { - std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 1 + { + std::vector { "Wave_1_Sub_1", "Wave_1_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Sub 2 - { - std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 2 + { + std::vector { "Wave_2_Sub_1", "Wave_2_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Sub 3 - { - std::vector { "Wave_3_Sub_1", "Wave_3_Sub_2" }, - 6016, 0.0, 2.0, true, 0.0, 2.0, - 2.0, 1000, false, 0.0, 1.0, - 1.0, true, true - }, + // Sub 3 + { + std::vector { "Wave_3_Sub_1", "Wave_3_Sub_2" }, + 6016, 0.0, 2.0, true, 0.0, 2.0, + 2.0, 1000, false, 0.0, 1.0, + 1.0, true, true + }, - // Duck - { - std::vector { "Wave_1_Duck_1", "Wave_1_Duck_2" }, - 5946, 5.0, 10.0, true, 5.0, 10.0, - 4.0, 5000, false, 0.0, 1.0, - 1.0, false, true - }, + // Duck + { + std::vector { "Wave_1_Duck_1", "Wave_1_Duck_2" }, + 5946, 5.0, 10.0, true, 5.0, 10.0, + 4.0, 5000, false, 0.0, 1.0, + 1.0, false, true + }, - // Ness - { - std::vector { "Wave_1_Ness_1", "Wave_1_Ness_2", "Wave_2_Ness_1" }, - 2565, 10.0, 15.0, true, 10.0, 15.0, - 2.0, 10000, false, 0.0, 1.0, - 1.0, true, true - }, + // Ness + { + std::vector { "Wave_1_Ness_1", "Wave_1_Ness_2", "Wave_2_Ness_1" }, + 2565, 10.0, 15.0, true, 10.0, 15.0, + 2.0, 10000, false, 0.0, 1.0, + 1.0, true, true + }, - // Friendly 1 - { - std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, - 2168,0.0,5.0,true, 2.0, 5.0, - 1.0, -1000, false, 0.0, 1.0, - 1.0, false,true - }, + // Friendly 1 + { + std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, + 2168,0.0,5.0,true, 2.0, 5.0, + 1.0, -1000, false, 0.0, 1.0, + 1.0, false,true + }, - // Friendly 2 - { - std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, - 2168,0.0,5.0,true, 2.0, 5.0, - 1.0, -1000, false, 0.0, 1.0, - 1.0, false,true - } - } - }; + // Friendly 2 + { + std::vector { "Wave_3_FShip_1", "Wave_3_FShip_2" }, + 2168,0.0,5.0,true, 2.0, 5.0, + 1.0, -1000, false, 0.0, 1.0, + 1.0, false,true + } + } + }; } -void SGCannon::ResetVars(Entity *self) { - self->SetVar(SpawnNumberVariable, 0); - self->SetVar(CurrentSpawnNumberVariable, 0); - self->SetVar(ThisWaveVariable, 0); - self->SetVar(GameScoreVariable, 0); - self->SetVar(GameTimeVariable, 0); - self->SetVar(GameStartedVariable, false); - self->SetVar(ShotsFiredVariable, 0); - self->SetVar(MaxStreakVariable, 0); - self->SetVar(MissesVariable, 0); - self->SetVar(CurrentStreakVariable, 0); - self->SetVar(CurrentSuperChargedTimeVariable, 0); - self->SetVar>(StreakBonusVariable, {}); - self->SetVar(LastSuperTotalVariable, 0); - self->SetVar(CurrentRewardVariable, LOT_NULL); - self->SetVar>(RewardsVariable, {}); - self->SetVar(TotalScoreVariable, 0); +void SGCannon::ResetVars(Entity* self) { + self->SetVar(SpawnNumberVariable, 0); + self->SetVar(CurrentSpawnNumberVariable, 0); + self->SetVar(ThisWaveVariable, 0); + self->SetVar(GameScoreVariable, 0); + self->SetVar(GameTimeVariable, 0); + self->SetVar(GameStartedVariable, false); + self->SetVar(ShotsFiredVariable, 0); + self->SetVar(MaxStreakVariable, 0); + self->SetVar(MissesVariable, 0); + self->SetVar(CurrentStreakVariable, 0); + self->SetVar(CurrentSuperChargedTimeVariable, 0); + self->SetVar>(StreakBonusVariable, {}); + self->SetVar(LastSuperTotalVariable, 0); + self->SetVar(CurrentRewardVariable, LOT_NULL); + self->SetVar>(RewardsVariable, {}); + self->SetVar(TotalScoreVariable, 0); - const_cast&>(self->GetVar>(ActiveSpawnsVariable)).clear(); - self->SetVar>(ActiveSpawnsVariable, {}); + const_cast&>(self->GetVar>(ActiveSpawnsVariable)).clear(); + self->SetVar>(ActiveSpawnsVariable, {}); - const_cast&>(self->GetVar>(SpawnedObjects)).clear(); - self->SetVar>(SpawnedObjects, {}); + const_cast&>(self->GetVar>(SpawnedObjects)).clear(); + self->SetVar>(SpawnedObjects, {}); - if (self->GetVar(InitVariable)) { - ToggleSuperCharge(self, false); - } + if (self->GetVar(InitVariable)) { + ToggleSuperCharge(self, false); + } - self->SetVar(ImpactSkillVariale, constants.impactSkillID); - self->SetVar>(PlayerScoresVariable, {}); - ActivityTimerStopAllTimers(self); + self->SetVar(ImpactSkillVariale, constants.impactSkillID); + self->SetVar>(PlayerScoresVariable, {}); + ActivityTimerStopAllTimers(self); } SGConstants SGCannon::GetConstants() { - return { - Vector3 { -908.542480, 229.773178, -908.542480 }, - Quaternion { 0.91913521289825, 0, 0.39394217729568, 0 }, - 1864, - 34, - 1822, - Vector3 { 6.652, -2, 1.5 }, - 157, - 129.0, - 30.0, - 800.0, - Vector3 { 0, 4.3, 9 }, - 6297, - 1822, - 249, - 228, - -1, - 58.6, - true, - 2, - 10, - 25000, - "QBRewardGroup", - 1864, - 50000, - 157, - 100000, - 187, - 200000, - 188, - 400000, - 189, - 800000, - 190, - 4.0, - 7.0 - }; + return { + Vector3 { -908.542480, 229.773178, -908.542480 }, + Quaternion { 0.91913521289825, 0, 0.39394217729568, 0 }, + 1864, + 34, + 1822, + Vector3 { 6.652, -2, 1.5 }, + 157, + 129.0, + 30.0, + 800.0, + Vector3 { 0, 4.3, 9 }, + 6297, + 1822, + 249, + 228, + -1, + 58.6, + true, + 2, + 10, + 25000, + "QBRewardGroup", + 1864, + 50000, + 157, + 100000, + 187, + 200000, + 188, + 400000, + 189, + 800000, + 190, + 4.0, + 7.0 + }; } diff --git a/dScripts/SGCannon.h b/dScripts/SGCannon.h index 56db4c81..df9831ad 100644 --- a/dScripts/SGCannon.h +++ b/dScripts/SGCannon.h @@ -3,151 +3,151 @@ #include "ActivityManager.h" struct SGEnemy { - std::vector spawnPaths {}; - LOT lot; - float_t minSpawnTime; - float_t maxSpawnTime; - bool respawns; - float_t minRespawnTime; - float_t maxRespawnTime; - float_t initialSpeed; - int32_t score; - bool changeSpeedAtWaypoint; - float_t speedChangeChance; - float_t minSpeed; - float_t maxSpeed; - bool isMovingPlatform; - bool despawnOnLastWaypoint; + std::vector spawnPaths{}; + LOT lot; + float_t minSpawnTime; + float_t maxSpawnTime; + bool respawns; + float_t minRespawnTime; + float_t maxRespawnTime; + float_t initialSpeed; + int32_t score; + bool changeSpeedAtWaypoint; + float_t speedChangeChance; + float_t minSpeed; + float_t maxSpeed; + bool isMovingPlatform; + bool despawnOnLastWaypoint; }; struct SGConstants { - Vector3 playerStartPosition; - Quaternion playerStartRotation; - LOT cannonLot; - uint32_t impactSkillID; - LOT projectileLot; - Vector3 playerOffset; - uint32_t rewardModelMatrix; - float_t cannonVelocity; - float_t cannonMinDistance; - float_t cannonRefireRate; - Vector3 cannonBarrelOffset; - LOT cannonSuperchargedProjectileLot; - LOT cannonProjectileLot; - uint32_t cannonSuperChargeSkill; - uint32_t cannonSkill; - int32_t cannonTimeout; - float_t cannonFOV; - bool useLeaderboards; - uint32_t streakModifier; - uint32_t chargedTime; - uint32_t chargedPoints; - std::string rewardModelGroup; - uint32_t activityID; - uint32_t scoreReward1; - uint32_t scoreLootMatrix1; - uint32_t scoreReward2; - uint32_t scoreLootMatrix2; - uint32_t scoreReward3; - uint32_t scoreLootMatrix3; - uint32_t scoreReward4; - uint32_t scoreLootMatrix4; - uint32_t scoreReward5; - uint32_t scoreLootMatrix5; - float_t firstWaveStartTime; - float_t inBetweenWavePause; + Vector3 playerStartPosition; + Quaternion playerStartRotation; + LOT cannonLot; + uint32_t impactSkillID; + LOT projectileLot; + Vector3 playerOffset; + uint32_t rewardModelMatrix; + float_t cannonVelocity; + float_t cannonMinDistance; + float_t cannonRefireRate; + Vector3 cannonBarrelOffset; + LOT cannonSuperchargedProjectileLot; + LOT cannonProjectileLot; + uint32_t cannonSuperChargeSkill; + uint32_t cannonSkill; + int32_t cannonTimeout; + float_t cannonFOV; + bool useLeaderboards; + uint32_t streakModifier; + uint32_t chargedTime; + uint32_t chargedPoints; + std::string rewardModelGroup; + uint32_t activityID; + uint32_t scoreReward1; + uint32_t scoreLootMatrix1; + uint32_t scoreReward2; + uint32_t scoreLootMatrix2; + uint32_t scoreReward3; + uint32_t scoreLootMatrix3; + uint32_t scoreReward4; + uint32_t scoreLootMatrix4; + uint32_t scoreReward5; + uint32_t scoreLootMatrix5; + float_t firstWaveStartTime; + float_t inBetweenWavePause; }; class SGCannon : public ActivityManager { public: - void OnStartup(Entity *self) override; - void OnPlayerLoaded(Entity *self, Entity *player) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; - void OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, - int32_t value2, const std::u16string& stringValue) override; - void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, - const std::u16string& userData) override; - void OnActivityTimerDone(Entity *self, const std::string &name) override; - void OnActivityTimerUpdate(Entity *self, const std::string &name, float_t timeRemaining, float_t elapsedTime) override; + void OnStartup(Entity* self) override; + void OnPlayerLoaded(Entity* self, Entity* player) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, + int32_t value2, const std::u16string& stringValue) override; + void OnMessageBoxResponse(Entity* self, Entity* sender, int32_t button, const std::u16string& identifier, + const std::u16string& userData) override; + void OnActivityTimerDone(Entity* self, const std::string& name) override; + void OnActivityTimerUpdate(Entity* self, const std::string& name, float_t timeRemaining, float_t elapsedTime) override; private: - static std::vector> GetWaves(); - static SGConstants GetConstants(); - void ResetVars(Entity* self); - void StartGame(Entity* self); - void DoGameStartup(Entity* self); - void SpawnNewModel(Entity* self); - void TimerToggle(Entity* self, bool start = false); - void SpawnObject(Entity* self, const SGEnemy& toSpawn, bool spawnNow = false); - void StartChargedCannon(Entity* self, uint32_t optionalTime = 0); - void ToggleSuperCharge(Entity* self, bool enable); - void RecordPlayerScore(Entity* self); - void PlaySceneAnimation(Entity* self, const std::u16string& animationName, bool onCannon, bool onPlayer, float_t priority); - static void RemovePlayer(LWOOBJID playerID); - void PauseChargeCannon(Entity* self); - void StopGame(Entity* self, bool cancel = false); - void RegisterHit(Entity* self, Entity* target, const std::string& timerName); - void UpdateStreak(Entity* self); - float_t GetCurrentBonus(Entity* self); + static std::vector> GetWaves(); + static SGConstants GetConstants(); + void ResetVars(Entity* self); + void StartGame(Entity* self); + void DoGameStartup(Entity* self); + void SpawnNewModel(Entity* self); + void TimerToggle(Entity* self, bool start = false); + void SpawnObject(Entity* self, const SGEnemy& toSpawn, bool spawnNow = false); + void StartChargedCannon(Entity* self, uint32_t optionalTime = 0); + void ToggleSuperCharge(Entity* self, bool enable); + void RecordPlayerScore(Entity* self); + void PlaySceneAnimation(Entity* self, const std::u16string& animationName, bool onCannon, bool onPlayer, float_t priority); + static void RemovePlayer(LWOOBJID playerID); + void PauseChargeCannon(Entity* self); + void StopGame(Entity* self, bool cancel = false); + void RegisterHit(Entity* self, Entity* target, const std::string& timerName); + void UpdateStreak(Entity* self); + float_t GetCurrentBonus(Entity* self); - LOT m_CannonLot = 1864; - std::u16string PlayerIDVariable = u"PlayerID"; - std::u16string HideScoreBoardVariable = u"HideScoreBoard"; - std::u16string ReSetSuperChargeVariable = u"ReSetSuperCharge"; - std::u16string ShowLoadingUI = u"showLoadingUI"; - std::u16string SpawnNumberVariable = u"SpawnNum"; - std::u16string CurrentSpawnNumberVariable = u"CurSpawnNum"; - std::u16string ThisWaveVariable = u"ThisWave"; - std::u16string GameScoreVariable = u"GameScore"; - std::u16string GameTimeVariable = u"GameTime"; - std::u16string GameStartedVariable = u"GameStarted"; - std::u16string ShotsFiredVariable = u"ShotsFired"; - std::u16string MaxStreakVariable = u"MaxStreak"; - std::u16string MissesVariable = u"Misses"; - std::u16string CurrentStreakVariable = u"CurrentStreak"; - std::u16string CurrentSuperChargedTimeVariable = u"CurrentSuperChargedTime"; - std::u16string StreakBonusVariable = u"StreakBonus"; - std::u16string LastSuperTotalVariable = u"LastSuperTotal"; - std::u16string CurrentRewardVariable = u"CurrentReward"; - std::u16string RewardsVariable = u"Rewards"; - std::u16string TotalScoreVariable = u"TotalScore"; - std::u16string InitVariable = u"Init"; - std::u16string ImpactSkillVariale = u"ImpactSkill"; - std::u16string PlayerScoresVariable = u"PlayerScores"; - std::u16string InitialVelocityVariable = u"InitialVelocity"; - std::u16string ValidActorsVariable = u"ValidActors"; - std::u16string ValidEffectsVariable = u"ValidEffects"; - std::u16string SuperChargeActiveVariable = u"SuperChargeActive"; - std::u16string MatrixVariable = u"Matrix"; - std::u16string TimeLimitVariable = u"game_timelimit"; - std::u16string AudioStartIntroVariable = u"Audio_Start_Intro"; - std::u16string ClearVariable = u"Clear"; - std::u16string FirstTimeDoneVariable = u"FirstTimeDone"; - std::u16string RewardAddedVariable = u"rewardAdded"; - std::u16string SuperChargePausedVariable = u"Super_Charge_Paused"; - std::u16string WaveStatusVariable = u"WaveStatus"; - std::u16string CountVariable = u"count"; - std::u16string StopVariable = u"Stop"; - std::u16string ActiveSpawnsVariable = u"ActiveSpawns"; - std::u16string SpawnedObjects = u"SpawnedObjects"; - std::u16string WaveNumVariable = u"wave.waveNum"; - std::u16string WaveStrVariable = u"wave.waveStr"; - std::u16string ChargeCountingVariable = u"charge_counting"; - std::u16string SuperChargeBarVariable = u"SuperChargeBar"; - std::u16string NumberOfChargesVariable = u"NumberOfCharges"; - std::u16string CannonBallSkillIDVariable = u"cbskill"; - std::u16string HideSuperChargeVariable = u"HideSuper"; - std::u16string AudioFinalWaveDoneVariable = u"Audio_Final_Wave_Done"; + LOT m_CannonLot = 1864; + std::u16string PlayerIDVariable = u"PlayerID"; + std::u16string HideScoreBoardVariable = u"HideScoreBoard"; + std::u16string ReSetSuperChargeVariable = u"ReSetSuperCharge"; + std::u16string ShowLoadingUI = u"showLoadingUI"; + std::u16string SpawnNumberVariable = u"SpawnNum"; + std::u16string CurrentSpawnNumberVariable = u"CurSpawnNum"; + std::u16string ThisWaveVariable = u"ThisWave"; + std::u16string GameScoreVariable = u"GameScore"; + std::u16string GameTimeVariable = u"GameTime"; + std::u16string GameStartedVariable = u"GameStarted"; + std::u16string ShotsFiredVariable = u"ShotsFired"; + std::u16string MaxStreakVariable = u"MaxStreak"; + std::u16string MissesVariable = u"Misses"; + std::u16string CurrentStreakVariable = u"CurrentStreak"; + std::u16string CurrentSuperChargedTimeVariable = u"CurrentSuperChargedTime"; + std::u16string StreakBonusVariable = u"StreakBonus"; + std::u16string LastSuperTotalVariable = u"LastSuperTotal"; + std::u16string CurrentRewardVariable = u"CurrentReward"; + std::u16string RewardsVariable = u"Rewards"; + std::u16string TotalScoreVariable = u"TotalScore"; + std::u16string InitVariable = u"Init"; + std::u16string ImpactSkillVariale = u"ImpactSkill"; + std::u16string PlayerScoresVariable = u"PlayerScores"; + std::u16string InitialVelocityVariable = u"InitialVelocity"; + std::u16string ValidActorsVariable = u"ValidActors"; + std::u16string ValidEffectsVariable = u"ValidEffects"; + std::u16string SuperChargeActiveVariable = u"SuperChargeActive"; + std::u16string MatrixVariable = u"Matrix"; + std::u16string TimeLimitVariable = u"game_timelimit"; + std::u16string AudioStartIntroVariable = u"Audio_Start_Intro"; + std::u16string ClearVariable = u"Clear"; + std::u16string FirstTimeDoneVariable = u"FirstTimeDone"; + std::u16string RewardAddedVariable = u"rewardAdded"; + std::u16string SuperChargePausedVariable = u"Super_Charge_Paused"; + std::u16string WaveStatusVariable = u"WaveStatus"; + std::u16string CountVariable = u"count"; + std::u16string StopVariable = u"Stop"; + std::u16string ActiveSpawnsVariable = u"ActiveSpawns"; + std::u16string SpawnedObjects = u"SpawnedObjects"; + std::u16string WaveNumVariable = u"wave.waveNum"; + std::u16string WaveStrVariable = u"wave.waveStr"; + std::u16string ChargeCountingVariable = u"charge_counting"; + std::u16string SuperChargeBarVariable = u"SuperChargeBar"; + std::u16string NumberOfChargesVariable = u"NumberOfCharges"; + std::u16string CannonBallSkillIDVariable = u"cbskill"; + std::u16string HideSuperChargeVariable = u"HideSuper"; + std::u16string AudioFinalWaveDoneVariable = u"Audio_Final_Wave_Done"; - std::string SpawnWaveTimer = "SpawnWave"; - std::string EndWaveTimer = "EndWave"; - std::string GameOverTimer = "GameOver"; - std::string DoSpawnTimer = "DoSpawn"; - std::string EndGameBufferTimer = "endGameBuffer"; - std::string SuperChargeTimer = "SuperChargeTimer"; + std::string SpawnWaveTimer = "SpawnWave"; + std::string EndWaveTimer = "EndWave"; + std::string GameOverTimer = "GameOver"; + std::string DoSpawnTimer = "DoSpawn"; + std::string EndGameBufferTimer = "endGameBuffer"; + std::string SuperChargeTimer = "SuperChargeTimer"; - std::string ModelToBuildEvent = "modelToBuild"; + std::string ModelToBuildEvent = "modelToBuild"; - std::regex DoSpawnRegex = std::regex("\\d*"); - SGConstants constants {}; - std::vector> m_Waves {}; + std::regex DoSpawnRegex = std::regex("\\d*"); + SGConstants constants{}; + std::vector> m_Waves{}; }; diff --git a/dScripts/ScriptComponent.cpp b/dScripts/ScriptComponent.cpp index 3c5c2584..272de5ab 100644 --- a/dScripts/ScriptComponent.cpp +++ b/dScripts/ScriptComponent.cpp @@ -18,27 +18,27 @@ ScriptComponent::~ScriptComponent() { } void ScriptComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - if (bIsInitialUpdate) { - const auto& networkSettings = m_Parent->GetNetworkSettings(); - auto hasNetworkSettings = !networkSettings.empty(); - outBitStream->Write(hasNetworkSettings); + if (bIsInitialUpdate) { + const auto& networkSettings = m_Parent->GetNetworkSettings(); + auto hasNetworkSettings = !networkSettings.empty(); + outBitStream->Write(hasNetworkSettings); - if (hasNetworkSettings) { + if (hasNetworkSettings) { - // First write the most inner LDF data - RakNet::BitStream ldfData; - ldfData.Write(0); - ldfData.Write(networkSettings.size()); + // First write the most inner LDF data + RakNet::BitStream ldfData; + ldfData.Write(0); + ldfData.Write(networkSettings.size()); - for (auto* networkSetting : networkSettings) { - networkSetting->WriteToPacket(&ldfData); - } + for (auto* networkSetting : networkSettings) { + networkSetting->WriteToPacket(&ldfData); + } - // Finally write everything to the stream - outBitStream->Write(ldfData.GetNumberOfBytesUsed()); - outBitStream->Write(ldfData); - } - } + // Finally write everything to the stream + outBitStream->Write(ldfData.GetNumberOfBytesUsed()); + outBitStream->Write(ldfData); + } + } } CppScripts::Script* ScriptComponent::GetScript() { @@ -46,7 +46,7 @@ CppScripts::Script* ScriptComponent::GetScript() { } void ScriptComponent::SetScript(const std::string& scriptName) { - //we don't need to delete the script because others may be using it :) + //we don't need to delete the script because others may be using it :) /*if (m_Client) { m_Script = new InvalidScript(); return; diff --git a/dScripts/ScriptComponent.h b/dScripts/ScriptComponent.h index 82d1f648..94226627 100644 --- a/dScripts/ScriptComponent.h +++ b/dScripts/ScriptComponent.h @@ -19,45 +19,45 @@ class Entity; class ScriptComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_SCRIPT; - - ScriptComponent(Entity* parent, std::string scriptName, bool serialized, bool client = false); - ~ScriptComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + ScriptComponent(Entity* parent, std::string scriptName, bool serialized, bool client = false); + ~ScriptComponent() override; - /** - * Returns the script that's attached to this entity - * @return the script that's attached to this entity - */ + void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + + /** + * Returns the script that's attached to this entity + * @return the script that's attached to this entity + */ CppScripts::Script* GetScript(); - /** - * Sets whether the entity should be serialized, unused - * @param var whether the entity should be serialized - */ + /** + * Sets whether the entity should be serialized, unused + * @param var whether the entity should be serialized + */ void SetSerialized(const bool var) { m_Serialized = var; } - /** - * Sets the script using a path by looking through dScripts for a script that matches - * @param scriptName the name of the script to find - */ + /** + * Sets the script using a path by looking through dScripts for a script that matches + * @param scriptName the name of the script to find + */ void SetScript(const std::string& scriptName); private: - /** - * The script attached to this entity - */ + /** + * The script attached to this entity + */ CppScripts::Script* m_Script; - /** - * Whether or not the comp should be serialized, unused - */ + /** + * Whether or not the comp should be serialized, unused + */ bool m_Serialized; - /** - * Whether or not this script is a client script - */ + /** + * Whether or not this script is a client script + */ bool m_Client; }; diff --git a/dScripts/ScriptedPowerupSpawner.cpp b/dScripts/ScriptedPowerupSpawner.cpp index 91c25856..730e65ba 100644 --- a/dScripts/ScriptedPowerupSpawner.cpp +++ b/dScripts/ScriptedPowerupSpawner.cpp @@ -2,45 +2,45 @@ #include "RenderComponent.h" #include "EntityManager.h" -void ScriptedPowerupSpawner::OnTemplateStartup(Entity *self) { - self->SetVar(u"currentCycle", 1); - self->AddTimer("timeToSpawn", self->GetVar(u"delayToFirstCycle")); +void ScriptedPowerupSpawner::OnTemplateStartup(Entity* self) { + self->SetVar(u"currentCycle", 1); + self->AddTimer("timeToSpawn", self->GetVar(u"delayToFirstCycle")); } -void ScriptedPowerupSpawner::OnTimerDone(Entity *self, std::string message) { - if (message == "die") { - self->Smash(); - } else if (message == "timeToSpawn") { +void ScriptedPowerupSpawner::OnTimerDone(Entity* self, std::string message) { + if (message == "die") { + self->Smash(); + } else if (message == "timeToSpawn") { - const auto itemLOT = self->GetVar(u"lootLOT"); + const auto itemLOT = self->GetVar(u"lootLOT"); - // Build drop table - std::unordered_map drops; + // Build drop table + std::unordered_map drops; - drops.emplace(itemLOT, 1); + drops.emplace(itemLOT, 1); - // Spawn the required number of powerups - auto* owner = EntityManager::Instance()->GetEntity(self->GetSpawnerID()); - if (owner != nullptr) { - auto* renderComponent = self->GetComponent(); - for (auto i = 0; i < self->GetVar(u"numberOfPowerups"); i++) { - if (renderComponent != nullptr) { - renderComponent->PlayEffect(0, u"cast", "N_cast"); - } + // Spawn the required number of powerups + auto* owner = EntityManager::Instance()->GetEntity(self->GetSpawnerID()); + if (owner != nullptr) { + auto* renderComponent = self->GetComponent(); + for (auto i = 0; i < self->GetVar(u"numberOfPowerups"); i++) { + if (renderComponent != nullptr) { + renderComponent->PlayEffect(0, u"cast", "N_cast"); + } - LootGenerator::Instance().DropLoot(owner, self, drops, 0, 0); - } + LootGenerator::Instance().DropLoot(owner, self, drops, 0, 0); + } - // Increment the current cycle - if (self->GetVar(u"currentCycle") < self->GetVar(u"numCycles")) { - self->AddTimer("timeToSpawn", self->GetVar(u"secPerCycle")); - self->SetVar(u"currentCycle", self->GetVar(u"currentCycle") + 1); - } + // Increment the current cycle + if (self->GetVar(u"currentCycle") < self->GetVar(u"numCycles")) { + self->AddTimer("timeToSpawn", self->GetVar(u"secPerCycle")); + self->SetVar(u"currentCycle", self->GetVar(u"currentCycle") + 1); + } - // Kill if this was the last cycle - if (self->GetVar(u"currentCycle") >= self->GetVar(u"numCycles")) { - self->AddTimer("die", self->GetVar(u"deathDelay")); - } - } - } + // Kill if this was the last cycle + if (self->GetVar(u"currentCycle") >= self->GetVar(u"numCycles")) { + self->AddTimer("die", self->GetVar(u"deathDelay")); + } + } + } } diff --git a/dScripts/ScriptedPowerupSpawner.h b/dScripts/ScriptedPowerupSpawner.h index 597e8673..1fa57d90 100644 --- a/dScripts/ScriptedPowerupSpawner.h +++ b/dScripts/ScriptedPowerupSpawner.h @@ -13,11 +13,11 @@ */ class ScriptedPowerupSpawner : public CppScripts::Script { public: - /** - * Called by the child script after on startup - * \param self the object this script belongs to - */ - static void OnTemplateStartup(Entity* self); - void OnTimerDone(Entity* self, std::string message) override; + /** + * Called by the child script after on startup + * \param self the object this script belongs to + */ + static void OnTemplateStartup(Entity* self); + void OnTimerDone(Entity* self, std::string message) override; }; diff --git a/dScripts/SpawnGryphonServer.cpp b/dScripts/SpawnGryphonServer.cpp index d411569c..22e5ff59 100644 --- a/dScripts/SpawnGryphonServer.cpp +++ b/dScripts/SpawnGryphonServer.cpp @@ -3,25 +3,25 @@ #include "GameMessages.h" #include "MissionComponent.h" -void SpawnGryphonServer::SetVariables(Entity *self) { - self->SetVar(u"petLOT", 12433); - self->SetVar(u"petType", "gryphon"); - self->SetVar(u"maxPets", 2); - self->SetVar(u"spawnAnim", u"spawn"); - self->SetVar(u"spawnCinematic", u"SentinelPet"); +void SpawnGryphonServer::SetVariables(Entity* self) { + self->SetVar(u"petLOT", 12433); + self->SetVar(u"petType", "gryphon"); + self->SetVar(u"maxPets", 2); + self->SetVar(u"spawnAnim", u"spawn"); + self->SetVar(u"spawnCinematic", u"SentinelPet"); } -void SpawnGryphonServer::OnUse(Entity *self, Entity *user) { - auto* missionComponent = user->GetComponent(); - auto* inventoryComponent = user->GetComponent(); +void SpawnGryphonServer::OnUse(Entity* self, Entity* user) { + auto* missionComponent = user->GetComponent(); + auto* inventoryComponent = user->GetComponent(); - // Little extra for handling the case of the egg being placed the first time - if (missionComponent != nullptr && inventoryComponent != nullptr - && missionComponent->GetMissionState(1391) == MissionState::MISSION_STATE_ACTIVE) { - inventoryComponent->RemoveItem(12483, inventoryComponent->GetLotCount(12483)); - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); - return; - } + // Little extra for handling the case of the egg being placed the first time + if (missionComponent != nullptr && inventoryComponent != nullptr + && missionComponent->GetMissionState(1391) == MissionState::MISSION_STATE_ACTIVE) { + inventoryComponent->RemoveItem(12483, inventoryComponent->GetLotCount(12483)); + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + return; + } - SpawnPetBaseServer::OnUse(self, user); + SpawnPetBaseServer::OnUse(self, user); } diff --git a/dScripts/SpawnGryphonServer.h b/dScripts/SpawnGryphonServer.h index 8f76e1dc..eacf93e4 100644 --- a/dScripts/SpawnGryphonServer.h +++ b/dScripts/SpawnGryphonServer.h @@ -2,6 +2,6 @@ #include "SpawnPetBaseServer.h" class SpawnGryphonServer : public SpawnPetBaseServer { - void SetVariables(Entity *self) override; - void OnUse(Entity *self, Entity *user) override; + void SetVariables(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/SpawnLionServer.cpp b/dScripts/SpawnLionServer.cpp index b19531a4..622985b1 100644 --- a/dScripts/SpawnLionServer.cpp +++ b/dScripts/SpawnLionServer.cpp @@ -1,10 +1,10 @@ #include "SpawnLionServer.h" #include "Entity.h" -void SpawnLionServer::SetVariables(Entity *self) { - self->SetVar(u"petLOT", 3520); - self->SetVar(u"petType", "lion"); - self->SetVar(u"maxPets", 5); - self->SetVar(u"spawnAnim", u"spawn-lion"); - self->SetVar(u"spawnCinematic", u"Lion_spawn"); +void SpawnLionServer::SetVariables(Entity* self) { + self->SetVar(u"petLOT", 3520); + self->SetVar(u"petType", "lion"); + self->SetVar(u"maxPets", 5); + self->SetVar(u"spawnAnim", u"spawn-lion"); + self->SetVar(u"spawnCinematic", u"Lion_spawn"); } diff --git a/dScripts/SpawnLionServer.h b/dScripts/SpawnLionServer.h index b4cd208c..2c8e7f0f 100644 --- a/dScripts/SpawnLionServer.h +++ b/dScripts/SpawnLionServer.h @@ -2,5 +2,5 @@ #include "SpawnPetBaseServer.h" class SpawnLionServer : public SpawnPetBaseServer { - void SetVariables(Entity *self) override; + void SetVariables(Entity* self) override; }; diff --git a/dScripts/SpawnPetBaseServer.cpp b/dScripts/SpawnPetBaseServer.cpp index d23e371a..1d73a5b8 100644 --- a/dScripts/SpawnPetBaseServer.cpp +++ b/dScripts/SpawnPetBaseServer.cpp @@ -3,80 +3,80 @@ #include "EntityManager.h" #include "PetComponent.h" -void SpawnPetBaseServer::OnStartup(Entity *self) { - SetVariables(self); - self->SetVar(u"spawnedPets", ""); +void SpawnPetBaseServer::OnStartup(Entity* self) { + SetVariables(self); + self->SetVar(u"spawnedPets", ""); } -void SpawnPetBaseServer::OnUse(Entity *self, Entity *user) { - auto possibleSpawners = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(u"petType") + "Spawner"); - if (possibleSpawners.empty()) - return; +void SpawnPetBaseServer::OnUse(Entity* self, Entity* user) { + auto possibleSpawners = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(u"petType") + "Spawner"); + if (possibleSpawners.empty()) + return; - if (!CheckNumberOfPets(self, user)) - return; + if (!CheckNumberOfPets(self, user)) + return; - auto* spawner = possibleSpawners.at(0); - auto petType = GeneralUtils::ASCIIToUTF16(self->GetVar(u"petType")); + auto* spawner = possibleSpawners.at(0); + auto petType = GeneralUtils::ASCIIToUTF16(self->GetVar(u"petType")); - EntityInfo info {}; - info.pos = spawner->GetPosition(); - info.rot = spawner->GetRotation(); - info.lot = self->GetVar(u"petLOT"); - info.spawnerID = self->GetObjectID(); - info.settings = { - new LDFData(u"tamer", user->GetObjectID()), - new LDFData(u"groupID", petType + (GeneralUtils::to_u16string(user->GetObjectID())) + u";" + petType + u"s"), - new LDFData(u"spawnAnim", self->GetVar(u"spawnAnim")), - new LDFData(u"spawnTimer", 1.0f) - }; + EntityInfo info{}; + info.pos = spawner->GetPosition(); + info.rot = spawner->GetRotation(); + info.lot = self->GetVar(u"petLOT"); + info.spawnerID = self->GetObjectID(); + info.settings = { + new LDFData(u"tamer", user->GetObjectID()), + new LDFData(u"groupID", petType + (GeneralUtils::to_u16string(user->GetObjectID())) + u";" + petType + u"s"), + new LDFData(u"spawnAnim", self->GetVar(u"spawnAnim")), + new LDFData(u"spawnTimer", 1.0f) + }; - auto* pet = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(pet); + auto* pet = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(pet); - self->SetVar(u"spawnedPets", self->GetVar(u"spawnedPets") + "," - + std::to_string(pet->GetObjectID())); + self->SetVar(u"spawnedPets", self->GetVar(u"spawnedPets") + "," + + std::to_string(pet->GetObjectID())); - auto spawnCinematic = self->GetVar(u"spawnCinematic"); - if (!spawnCinematic.empty()) { - GameMessages::SendPlayCinematic(user->GetObjectID(), spawnCinematic, UNASSIGNED_SYSTEM_ADDRESS); - } + auto spawnCinematic = self->GetVar(u"spawnCinematic"); + if (!spawnCinematic.empty()) { + GameMessages::SendPlayCinematic(user->GetObjectID(), spawnCinematic, UNASSIGNED_SYSTEM_ADDRESS); + } - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } -bool SpawnPetBaseServer::CheckNumberOfPets(Entity *self, Entity* user) { - auto petIDString = self->GetVar(u"spawnedPets"); - auto petIDs = GeneralUtils::SplitString(petIDString, ','); +bool SpawnPetBaseServer::CheckNumberOfPets(Entity* self, Entity* user) { + auto petIDString = self->GetVar(u"spawnedPets"); + auto petIDs = GeneralUtils::SplitString(petIDString, ','); - // Check all the pets that were tamed in the process or were smashed - std::vector petsToKeep {}; - for (const auto& petID : petIDs) { - if (petID.empty()) - continue; + // Check all the pets that were tamed in the process or were smashed + std::vector petsToKeep{}; + for (const auto& petID : petIDs) { + if (petID.empty()) + continue; - const auto* spawnedPet = EntityManager::Instance()->GetEntity(std::stoull(petID)); - if (spawnedPet == nullptr) - continue; + const auto* spawnedPet = EntityManager::Instance()->GetEntity(std::stoull(petID)); + if (spawnedPet == nullptr) + continue; - const auto* petComponent = spawnedPet->GetComponent(); - if (petComponent == nullptr || petComponent->GetOwner() != nullptr) - continue; + const auto* petComponent = spawnedPet->GetComponent(); + if (petComponent == nullptr || petComponent->GetOwner() != nullptr) + continue; - // Each user can only spawn one pet - if (spawnedPet->GetVar(u"tamer") == user->GetObjectID()) - return false; + // Each user can only spawn one pet + if (spawnedPet->GetVar(u"tamer") == user->GetObjectID()) + return false; - petsToKeep.push_back(spawnedPet->GetObjectID()); - } + petsToKeep.push_back(spawnedPet->GetObjectID()); + } - self->SetNetworkVar(u"TooManyPets", petsToKeep.size() >= self->GetVar(u"maxPets")); + self->SetNetworkVar(u"TooManyPets", petsToKeep.size() >= self->GetVar(u"maxPets")); - std::string newPetIDs; - for (const auto petID : petsToKeep) { - newPetIDs += (std::to_string(petID) + ","); - } - self->SetVar(u"spawnedPets", newPetIDs); + std::string newPetIDs; + for (const auto petID : petsToKeep) { + newPetIDs += (std::to_string(petID) + ","); + } + self->SetVar(u"spawnedPets", newPetIDs); - return petsToKeep.size() < self->GetVar(u"maxPets"); + return petsToKeep.size() < self->GetVar(u"maxPets"); } diff --git a/dScripts/SpawnPetBaseServer.h b/dScripts/SpawnPetBaseServer.h index 80412b13..9ae51084 100644 --- a/dScripts/SpawnPetBaseServer.h +++ b/dScripts/SpawnPetBaseServer.h @@ -11,9 +11,9 @@ */ class SpawnPetBaseServer : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - void OnUse(Entity *self, Entity *user) override; - virtual void SetVariables(Entity* self) {}; + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + virtual void SetVariables(Entity* self) {}; private: - static bool CheckNumberOfPets(Entity* self, Entity* user); + static bool CheckNumberOfPets(Entity* self, Entity* user); }; diff --git a/dScripts/SpawnSaberCatServer.cpp b/dScripts/SpawnSaberCatServer.cpp index e89d9df7..3307c522 100644 --- a/dScripts/SpawnSaberCatServer.cpp +++ b/dScripts/SpawnSaberCatServer.cpp @@ -1,10 +1,10 @@ #include "SpawnSaberCatServer.h" #include "Entity.h" -void SpawnSaberCatServer::SetVariables(Entity *self) { - self->SetVar(u"petLOT", 12432); - self->SetVar(u"petType", "sabercat"); - self->SetVar(u"maxPets", 3); - self->SetVar(u"spawnAnim", u"pq_m_drop-down"); - self->SetVar(u"spawnCinematic", u"AssemblyPet"); +void SpawnSaberCatServer::SetVariables(Entity* self) { + self->SetVar(u"petLOT", 12432); + self->SetVar(u"petType", "sabercat"); + self->SetVar(u"maxPets", 3); + self->SetVar(u"spawnAnim", u"pq_m_drop-down"); + self->SetVar(u"spawnCinematic", u"AssemblyPet"); } diff --git a/dScripts/SpawnSaberCatServer.h b/dScripts/SpawnSaberCatServer.h index 6be6ff5b..a4d1874c 100644 --- a/dScripts/SpawnSaberCatServer.h +++ b/dScripts/SpawnSaberCatServer.h @@ -2,5 +2,5 @@ #include "SpawnPetBaseServer.h" class SpawnSaberCatServer : public SpawnPetBaseServer { - void SetVariables(Entity *self) override; + void SetVariables(Entity* self) override; }; diff --git a/dScripts/SpawnShrakeServer.cpp b/dScripts/SpawnShrakeServer.cpp index 5be55ebc..cf388ad0 100644 --- a/dScripts/SpawnShrakeServer.cpp +++ b/dScripts/SpawnShrakeServer.cpp @@ -1,10 +1,10 @@ #include "SpawnShrakeServer.h" #include "Entity.h" -void SpawnShrakeServer::SetVariables(Entity *self) { - self->SetVar(u"petLOT", 12434); - self->SetVar(u"petType", "shrake"); - self->SetVar(u"maxPets", 3); - self->SetVar(u"spawnAnim", u"mf_u_g_TT_spawn-1"); - self->SetVar(u"spawnCinematic", u"ParadoxPet"); +void SpawnShrakeServer::SetVariables(Entity* self) { + self->SetVar(u"petLOT", 12434); + self->SetVar(u"petType", "shrake"); + self->SetVar(u"maxPets", 3); + self->SetVar(u"spawnAnim", u"mf_u_g_TT_spawn-1"); + self->SetVar(u"spawnCinematic", u"ParadoxPet"); } diff --git a/dScripts/SpawnShrakeServer.h b/dScripts/SpawnShrakeServer.h index 9d7e86bc..de8c7405 100644 --- a/dScripts/SpawnShrakeServer.h +++ b/dScripts/SpawnShrakeServer.h @@ -2,5 +2,5 @@ #include "SpawnPetBaseServer.h" class SpawnShrakeServer : public SpawnPetBaseServer { - void SetVariables(Entity *self) override; + void SetVariables(Entity* self) override; }; diff --git a/dScripts/SpawnStegoServer.cpp b/dScripts/SpawnStegoServer.cpp index d845ff45..9fddeae5 100644 --- a/dScripts/SpawnStegoServer.cpp +++ b/dScripts/SpawnStegoServer.cpp @@ -1,10 +1,10 @@ #include "SpawnStegoServer.h" #include "Entity.h" -void SpawnStegoServer::SetVariables(Entity *self) { - self->SetVar(u"petLOT", 12431); - self->SetVar(u"petType", "stego"); - self->SetVar(u"maxPets", 3); - self->SetVar(u"spawnAnim", u"spawn"); - self->SetVar(u"spawnCinematic", u"VenturePet"); +void SpawnStegoServer::SetVariables(Entity* self) { + self->SetVar(u"petLOT", 12431); + self->SetVar(u"petType", "stego"); + self->SetVar(u"maxPets", 3); + self->SetVar(u"spawnAnim", u"spawn"); + self->SetVar(u"spawnCinematic", u"VenturePet"); } diff --git a/dScripts/SpawnStegoServer.h b/dScripts/SpawnStegoServer.h index d5bbd20b..955fd119 100644 --- a/dScripts/SpawnStegoServer.h +++ b/dScripts/SpawnStegoServer.h @@ -2,5 +2,5 @@ #include "SpawnPetBaseServer.h" class SpawnStegoServer : public SpawnPetBaseServer { - void SetVariables(Entity *self) override; + void SetVariables(Entity* self) override; }; diff --git a/dScripts/SpecialImaginePowerupSpawner.cpp b/dScripts/SpecialImaginePowerupSpawner.cpp index 8417efa2..0a13fc2b 100644 --- a/dScripts/SpecialImaginePowerupSpawner.cpp +++ b/dScripts/SpecialImaginePowerupSpawner.cpp @@ -5,34 +5,28 @@ #include "DestroyableComponent.h" #include "EntityManager.h" -void SpecialImaginePowerupSpawner::OnStartup(Entity* self) -{ +void SpecialImaginePowerupSpawner::OnStartup(Entity* self) { self->SetProximityRadius(1.5f, "powerupEnter"); self->SetVar(u"bIsDead", false); } -void SpecialImaginePowerupSpawner::OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) -{ - if (name != "powerupEnter" && status != "ENTER") - { +void SpecialImaginePowerupSpawner::OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) { + if (name != "powerupEnter" && status != "ENTER") { return; } - if (entering->GetLOT() != 1) - { + if (entering->GetLOT() != 1) { return; } - if (self->GetVar(u"bIsDead")) - { + if (self->GetVar(u"bIsDead")) { return; } GameMessages::SendPlayFXEffect(self, -1, u"pickup", "", LWOOBJID_EMPTY, 1, 1, true); SkillComponent* skillComponent; - if (!self->TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) - { + if (!self->TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) { return; } @@ -41,14 +35,13 @@ void SpecialImaginePowerupSpawner::OnProximityUpdate(Entity* self, Entity* enter skillComponent->CalculateBehavior(13, 20, source); DestroyableComponent* destroyableComponent; - if (!self->TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) - { + if (!self->TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) { return; } - + self->SetVar(u"bIsDead", true); self->AddCallbackTimer(1.0f, [self]() { EntityManager::Instance()->ScheduleForKill(self); - }); + }); } diff --git a/dScripts/SsModularBuildServer.cpp b/dScripts/SsModularBuildServer.cpp index 33f8db47..d5b6da50 100644 --- a/dScripts/SsModularBuildServer.cpp +++ b/dScripts/SsModularBuildServer.cpp @@ -7,7 +7,7 @@ void SsModularBuildServer::OnModularBuildExit(Entity* self, Entity* player, bool if (bCompleted) { MissionComponent* mission = static_cast(player->GetComponent(COMPONENT_TYPE_MISSION)); Mission* rocketMission = mission->GetMission(missionNum); - + if (rocketMission->GetMissionState() == MissionState::MISSION_STATE_ACTIVE) { mission->ForceProgress(missionNum, 2478, 1); } diff --git a/dScripts/StinkyFishTarget.cpp b/dScripts/StinkyFishTarget.cpp index 57256b6b..19dbce88 100644 --- a/dScripts/StinkyFishTarget.cpp +++ b/dScripts/StinkyFishTarget.cpp @@ -1,42 +1,42 @@ #include "StinkyFishTarget.h" #include "EntityManager.h" -void StinkyFishTarget::OnStartup(Entity *self) { - auto position = self->GetPosition(); - position.SetY(position.GetY() - 0.5f); - self->SetPosition(position); +void StinkyFishTarget::OnStartup(Entity* self) { + auto position = self->GetPosition(); + position.SetY(position.GetY() - 0.5f); + self->SetPosition(position); } -void StinkyFishTarget::OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) { - if (message != "stinkfish" || self->GetVar(u"used")) - return; +void StinkyFishTarget::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { + if (message != "stinkfish" || self->GetVar(u"used")) + return; - self->SetVar(u"used", true); - self->SetVar(u"player", caster->GetObjectID()); + self->SetVar(u"used", true); + self->SetVar(u"player", caster->GetObjectID()); - EntityInfo entityInfo {}; - entityInfo.pos = self->GetPosition(); - entityInfo.rot = self->GetRotation(); - entityInfo.spawnerID = self->GetObjectID(); - entityInfo.settings = { - new LDFData(u"no_timed_spawn", true) - }; + EntityInfo entityInfo{}; + entityInfo.pos = self->GetPosition(); + entityInfo.rot = self->GetRotation(); + entityInfo.spawnerID = self->GetObjectID(); + entityInfo.settings = { + new LDFData(u"no_timed_spawn", true) + }; - auto* fish = EntityManager::Instance()->CreateEntity(entityInfo); - EntityManager::Instance()->ConstructEntity(fish); + auto* fish = EntityManager::Instance()->CreateEntity(entityInfo); + EntityManager::Instance()->ConstructEntity(fish); - self->SetVar(u"fish", fish->GetObjectID()); - self->AddTimer("smash", 5.0f); + self->SetVar(u"fish", fish->GetObjectID()); + self->AddTimer("smash", 5.0f); } -void StinkyFishTarget::OnTimerDone(Entity *self, std::string timerName) { - if (timerName == "smash") { - const auto playerID = self->GetVar(u"player"); - auto* fish = EntityManager::Instance()->GetEntity(self->GetVar(u"fish")); +void StinkyFishTarget::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "smash") { + const auto playerID = self->GetVar(u"player"); + auto* fish = EntityManager::Instance()->GetEntity(self->GetVar(u"fish")); - if (fish != nullptr) { - fish->Smash(playerID); - self->Smash(playerID); - } - } + if (fish != nullptr) { + fish->Smash(playerID); + self->Smash(playerID); + } + } } diff --git a/dScripts/StinkyFishTarget.h b/dScripts/StinkyFishTarget.h index d88ce35e..6c52171d 100644 --- a/dScripts/StinkyFishTarget.h +++ b/dScripts/StinkyFishTarget.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class StinkyFishTarget : public CppScripts::Script { - void OnStartup(Entity *self) override; - void OnSkillEventFired(Entity *self, Entity *caster, const std::string &message) override; - void OnTimerDone(Entity *self, std::string timerName) override; + void OnStartup(Entity* self) override; + void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/StoryBoxInteractServer.cpp b/dScripts/StoryBoxInteractServer.cpp index 187d05a2..2683ddd4 100644 --- a/dScripts/StoryBoxInteractServer.cpp +++ b/dScripts/StoryBoxInteractServer.cpp @@ -5,8 +5,7 @@ #include "AMFFormat.h" void StoryBoxInteractServer::OnUse(Entity* self, Entity* user) { - if (self->GetVar(u"hasCustomText")) - { + if (self->GetVar(u"hasCustomText")) { const auto& customText = self->GetVar(u"customText"); { @@ -20,7 +19,7 @@ void StoryBoxInteractServer::OnUse(Entity* self, Entity* user) { GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); } - user->AddCallbackTimer(0.1f, [user, customText] () { + user->AddCallbackTimer(0.1f, [user, customText]() { AMFArrayValue args; auto* text = new AMFStringValue(); @@ -30,21 +29,20 @@ void StoryBoxInteractServer::OnUse(Entity* self, Entity* user) { args.InsertValue("text", text); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "ToggleStoryBox", &args); - }); + }); return; } - + const auto storyText = self->GetVarAsString(u"storyText"); - + int32_t boxFlag = self->GetVar(u"altFlagID"); - if (boxFlag <= 0) - { - boxFlag = (10000 + Game::server->GetZoneID() +std::stoi(storyText.substr(storyText.length() - 2))); + if (boxFlag <= 0) { + boxFlag = (10000 + Game::server->GetZoneID() + std::stoi(storyText.substr(storyText.length() - 2))); } if (user->GetCharacter()->GetPlayerFlag(boxFlag) == false) { user->GetCharacter()->SetPlayerFlag(boxFlag, true); GameMessages::SendFireEventClientSide(self->GetObjectID(), user->GetSystemAddress(), u"achieve", LWOOBJID_EMPTY, 0, -1, LWOOBJID_EMPTY); } -} \ No newline at end of file +} diff --git a/dScripts/StoryBoxInteractServer.h b/dScripts/StoryBoxInteractServer.h index caa6fd92..913e5185 100644 --- a/dScripts/StoryBoxInteractServer.h +++ b/dScripts/StoryBoxInteractServer.h @@ -4,4 +4,4 @@ class StoryBoxInteractServer : public CppScripts::Script { public: void OnUse(Entity* self, Entity* user); -}; \ No newline at end of file +}; diff --git a/dScripts/Sunflower.cpp b/dScripts/Sunflower.cpp index 436ca5f4..11923e23 100644 --- a/dScripts/Sunflower.cpp +++ b/dScripts/Sunflower.cpp @@ -1,14 +1,14 @@ #include "Sunflower.h" #include "Entity.h" -void Sunflower::OnStartup(Entity *self) { - self->SetVar(u"numCycles", 6); - self->SetVar(u"secPerCycle", 5.0f); - self->SetVar(u"delayToFirstCycle", 1.5f); - self->SetVar(u"deathDelay", 30.0f); - self->SetVar(u"numberOfPowerups", 4); - self->SetVar(u"lootLOT", 11910); +void Sunflower::OnStartup(Entity* self) { + self->SetVar(u"numCycles", 6); + self->SetVar(u"secPerCycle", 5.0f); + self->SetVar(u"delayToFirstCycle", 1.5f); + self->SetVar(u"deathDelay", 30.0f); + self->SetVar(u"numberOfPowerups", 4); + self->SetVar(u"lootLOT", 11910); - // Initiate the actual script - OnTemplateStartup(self); + // Initiate the actual script + OnTemplateStartup(self); } diff --git a/dScripts/Sunflower.h b/dScripts/Sunflower.h index f779d31c..560332c2 100644 --- a/dScripts/Sunflower.h +++ b/dScripts/Sunflower.h @@ -2,5 +2,5 @@ #include "ScriptedPowerupSpawner.h" class Sunflower : public ScriptedPowerupSpawner { - void OnStartup(Entity* self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/TokenConsoleServer.cpp b/dScripts/TokenConsoleServer.cpp index 378cc17f..f21938d1 100644 --- a/dScripts/TokenConsoleServer.cpp +++ b/dScripts/TokenConsoleServer.cpp @@ -19,7 +19,7 @@ void TokenConsoleServer::OnUse(Entity* self, Entity* user) { //figure out which faction the player belongs to: auto character = user->GetCharacter(); if (!character) return; - // At this point the player has to be in a faction. + // At this point the player has to be in a faction. LOT tokenLOT = 0; if (character->GetPlayerFlag(ePlayerFlags::VENTURE_FACTION)) //venture tokenLOT = 8321; @@ -33,4 +33,4 @@ void TokenConsoleServer::OnUse(Entity* self, Entity* user) { } GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); -} \ No newline at end of file +} diff --git a/dScripts/TokenConsoleServer.h b/dScripts/TokenConsoleServer.h index b6bf8010..ef57287c 100644 --- a/dScripts/TokenConsoleServer.h +++ b/dScripts/TokenConsoleServer.h @@ -7,4 +7,4 @@ class TokenConsoleServer : public CppScripts::Script { private: int bricksToTake = 25; int tokensToGive = 5; -}; \ No newline at end of file +}; diff --git a/dScripts/TouchMissionUpdateServer.cpp b/dScripts/TouchMissionUpdateServer.cpp index baa448af..f732305e 100644 --- a/dScripts/TouchMissionUpdateServer.cpp +++ b/dScripts/TouchMissionUpdateServer.cpp @@ -4,45 +4,37 @@ #include "GameMessages.h" #include "MissionComponent.h" -void TouchMissionUpdateServer::OnStartup(Entity* self) -{ +void TouchMissionUpdateServer::OnStartup(Entity* self) { self->SetProximityRadius(20, "touchCheck"); // Those does not have a collider for some reason? } -void TouchMissionUpdateServer::OnCollisionPhantom(Entity* self, Entity* target) -{ +void TouchMissionUpdateServer::OnCollisionPhantom(Entity* self, Entity* target) { int32_t missionId = self->GetVar(u"TouchCompleteID"); - if (missionId == 0) - { + if (missionId == 0) { return; } - + auto* missionComponent = static_cast(target->GetComponent(COMPONENT_TYPE_MISSION)); - if (missionComponent == nullptr) - { + if (missionComponent == nullptr) { return; } auto* mission = missionComponent->GetMission(missionId); - if (mission == nullptr) - { + if (mission == nullptr) { return; } const auto state = mission->GetMissionState(); - if (state >= MissionState::MISSION_STATE_COMPLETE || mission->GetCompletions() > 1) - { + if (state >= MissionState::MISSION_STATE_COMPLETE || mission->GetCompletions() > 1) { return; } - for (auto* task : mission->GetTasks()) - { - if (!task->IsComplete()) - { + for (auto* task : mission->GetTasks()) { + if (!task->IsComplete()) { task->Complete(); } } @@ -50,10 +42,8 @@ void TouchMissionUpdateServer::OnCollisionPhantom(Entity* self, Entity* target) mission->CheckCompletion(); } -void TouchMissionUpdateServer::OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) -{ - if (name != "touchCheck" || status != "ENTER") - { +void TouchMissionUpdateServer::OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) { + if (name != "touchCheck" || status != "ENTER") { return; } diff --git a/dScripts/TreasureChestDragonServer.cpp b/dScripts/TreasureChestDragonServer.cpp index 80f8aa48..15f0709c 100644 --- a/dScripts/TreasureChestDragonServer.cpp +++ b/dScripts/TreasureChestDragonServer.cpp @@ -3,48 +3,40 @@ #include "TeamManager.h" #include "EntityManager.h" -void TreasureChestDragonServer::OnStartup(Entity* self) -{ - +void TreasureChestDragonServer::OnStartup(Entity* self) { + } -void TreasureChestDragonServer::OnUse(Entity* self, Entity* user) -{ - if (self->GetVar(u"bUsed")) - { - return; - } +void TreasureChestDragonServer::OnUse(Entity* self, Entity* user) { + if (self->GetVar(u"bUsed")) { + return; + } - self->SetVar(u"bUsed", true); + self->SetVar(u"bUsed", true); - auto* scriptedActivityComponent = self->GetComponent(); + auto* scriptedActivityComponent = self->GetComponent(); - if (scriptedActivityComponent == nullptr) - { - return; - } + if (scriptedActivityComponent == nullptr) { + return; + } - auto rating = 1; + auto rating = 1; - auto* team = TeamManager::Instance()->GetTeam(user->GetObjectID()); + auto* team = TeamManager::Instance()->GetTeam(user->GetObjectID()); - if (team != nullptr) - { - rating = team->members.size(); + if (team != nullptr) { + rating = team->members.size(); - for (const auto member : team->members) - { - auto* memberObject = EntityManager::Instance()->GetEntity(member); + for (const auto member : team->members) { + auto* memberObject = EntityManager::Instance()->GetEntity(member); - if (memberObject == nullptr) continue; + if (memberObject == nullptr) continue; - LootGenerator::Instance().DropActivityLoot(memberObject, self, scriptedActivityComponent->GetActivityID(), rating); - } - } - else - { - LootGenerator::Instance().DropActivityLoot(user, self, scriptedActivityComponent->GetActivityID(), rating); - } + LootGenerator::Instance().DropActivityLoot(memberObject, self, scriptedActivityComponent->GetActivityID(), rating); + } + } else { + LootGenerator::Instance().DropActivityLoot(user, self, scriptedActivityComponent->GetActivityID(), rating); + } - self->Smash(self->GetObjectID()); + self->Smash(self->GetObjectID()); } diff --git a/dScripts/TriggerAmbush.cpp b/dScripts/TriggerAmbush.cpp index f9fb8cf7..8c408b32 100644 --- a/dScripts/TriggerAmbush.cpp +++ b/dScripts/TriggerAmbush.cpp @@ -2,13 +2,11 @@ #include "dZoneManager.h" -void TriggerAmbush::OnStartup(Entity* self) -{ +void TriggerAmbush::OnStartup(Entity* self) { self->SetProximityRadius(20, "ambush"); } -void TriggerAmbush::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) -{ +void TriggerAmbush::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { if (name != "ambush" || status != "ENTER" || !entering->IsPlayer()) return; if (self->GetVar(u"triggered")) return; @@ -17,26 +15,23 @@ void TriggerAmbush::OnProximityUpdate(Entity* self, Entity* entering, std::strin const auto spawners = dZoneManager::Instance()->GetSpawnersByName("Ambush"); - for (auto* spawner : spawners) - { + for (auto* spawner : spawners) { spawner->Activate(); } self->AddTimer("TriggeredTimer", 45); } -void TriggerAmbush::OnTimerDone(Entity* self, std::string timerName) -{ +void TriggerAmbush::OnTimerDone(Entity* self, std::string timerName) { if (timerName != "TriggeredTimer") return; self->SetVar(u"triggered", false); const auto spawners = dZoneManager::Instance()->GetSpawnersByName("Ambush"); - for (auto* spawner : spawners) - { + for (auto* spawner : spawners) { spawner->Reset(); - + spawner->Deactivate(); } } diff --git a/dScripts/TriggerAmbush.h b/dScripts/TriggerAmbush.h index 2ca7cd36..0544f3cb 100644 --- a/dScripts/TriggerAmbush.h +++ b/dScripts/TriggerAmbush.h @@ -5,8 +5,8 @@ class TriggerAmbush : public CppScripts::Script { public: void OnStartup(Entity* self) override; - + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; - + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/VeBricksampleServer.cpp b/dScripts/VeBricksampleServer.cpp index 76486d78..5166d0c3 100644 --- a/dScripts/VeBricksampleServer.cpp +++ b/dScripts/VeBricksampleServer.cpp @@ -4,18 +4,18 @@ #include "MissionComponent.h" #include "GameMessages.h" -void VeBricksampleServer::OnUse(Entity *self, Entity *user) { - auto* missionComponent = user->GetComponent(); - if (missionComponent != nullptr && missionComponent->GetMissionState(1183) == MissionState::MISSION_STATE_ACTIVE) { - const auto loot = self->GetVar(m_LootVariable); - auto* inventoryComponent = user->GetComponent(); +void VeBricksampleServer::OnUse(Entity* self, Entity* user) { + auto* missionComponent = user->GetComponent(); + if (missionComponent != nullptr && missionComponent->GetMissionState(1183) == MissionState::MISSION_STATE_ACTIVE) { + const auto loot = self->GetVar(m_LootVariable); + auto* inventoryComponent = user->GetComponent(); - if (loot && inventoryComponent != nullptr && inventoryComponent->GetLotCount(loot) == 0) { - inventoryComponent->AddItem(loot, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY); + if (loot && inventoryComponent != nullptr && inventoryComponent->GetLotCount(loot) == 0) { + inventoryComponent->AddItem(loot, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY); - for (auto* brickEntity : EntityManager::Instance()->GetEntitiesInGroup("Bricks")) { - GameMessages::SendNotifyClientObject(brickEntity->GetObjectID(), u"Pickedup"); - } - } - } + for (auto* brickEntity : EntityManager::Instance()->GetEntitiesInGroup("Bricks")) { + GameMessages::SendNotifyClientObject(brickEntity->GetObjectID(), u"Pickedup"); + } + } + } } diff --git a/dScripts/VeBricksampleServer.h b/dScripts/VeBricksampleServer.h index c983a962..d9d37133 100644 --- a/dScripts/VeBricksampleServer.h +++ b/dScripts/VeBricksampleServer.h @@ -2,6 +2,6 @@ #include "CppScripts.h" class VeBricksampleServer : public CppScripts::Script { - void OnUse(Entity *self, Entity *user) override; - const std::u16string m_LootVariable = u"Loot"; + void OnUse(Entity* self, Entity* user) override; + const std::u16string m_LootVariable = u"Loot"; }; diff --git a/dScripts/VeEpsilonServer.cpp b/dScripts/VeEpsilonServer.cpp index b3e24cf4..cc6ecafe 100644 --- a/dScripts/VeEpsilonServer.cpp +++ b/dScripts/VeEpsilonServer.cpp @@ -3,24 +3,24 @@ #include "EntityManager.h" #include "GameMessages.h" -void VeEpsilonServer::OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) { - auto* character = target->GetCharacter(); - if (character == nullptr) - return; +void VeEpsilonServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + auto* character = target->GetCharacter(); + if (character == nullptr) + return; - // Resets the player flags that track which consoles they've used - if ((missionID == m_ConsoleMissionID || missionID == m_ConsoleRepeatMissionID) - && (missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE)) { + // Resets the player flags that track which consoles they've used + if ((missionID == m_ConsoleMissionID || missionID == m_ConsoleRepeatMissionID) + && (missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE)) { - for (auto i = 0; i < 10; i++) { - character->SetPlayerFlag(m_ConsoleBaseFlag + i, false); - } - } + for (auto i = 0; i < 10; i++) { + character->SetPlayerFlag(m_ConsoleBaseFlag + i, false); + } + } - // Notify the client that all objects have updated - self->AddCallbackTimer(3.0f, [this]() { - for (const auto* console : EntityManager::Instance()->GetEntitiesInGroup(m_ConsoleGroup)) { - GameMessages::SendNotifyClientObject(console->GetObjectID(), u""); - } - }); + // Notify the client that all objects have updated + self->AddCallbackTimer(3.0f, [this]() { + for (const auto* console : EntityManager::Instance()->GetEntitiesInGroup(m_ConsoleGroup)) { + GameMessages::SendNotifyClientObject(console->GetObjectID(), u""); + } + }); } diff --git a/dScripts/VeEpsilonServer.h b/dScripts/VeEpsilonServer.h index d89f378f..d1236e96 100644 --- a/dScripts/VeEpsilonServer.h +++ b/dScripts/VeEpsilonServer.h @@ -2,9 +2,9 @@ #include "CppScripts.h" class VeEpsilonServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity *self, Entity *target, int missionID, MissionState missionState) override; - const uint32_t m_ConsoleMissionID = 1220; - const uint32_t m_ConsoleRepeatMissionID = 1225; - const uint32_t m_ConsoleBaseFlag = 1010; - const std::string m_ConsoleGroup = "Consoles"; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + const uint32_t m_ConsoleMissionID = 1220; + const uint32_t m_ConsoleRepeatMissionID = 1225; + const uint32_t m_ConsoleBaseFlag = 1010; + const std::string m_ConsoleGroup = "Consoles"; }; diff --git a/dScripts/VeMech.cpp b/dScripts/VeMech.cpp index 87f2e88f..e1ec5674 100644 --- a/dScripts/VeMech.cpp +++ b/dScripts/VeMech.cpp @@ -1,6 +1,6 @@ #include "VeMech.h" -void VeMech::OnStartup(Entity *self) { - BaseEnemyMech::OnStartup(self); - qbTurretLOT = 8432; +void VeMech::OnStartup(Entity* self) { + BaseEnemyMech::OnStartup(self); + qbTurretLOT = 8432; } diff --git a/dScripts/VeMech.h b/dScripts/VeMech.h index 5fde6610..0f7c8836 100644 --- a/dScripts/VeMech.h +++ b/dScripts/VeMech.h @@ -3,5 +3,5 @@ class VeMech : public BaseEnemyMech { public: - void OnStartup(Entity *self) override; + void OnStartup(Entity* self) override; }; diff --git a/dScripts/VeMissionConsole.cpp b/dScripts/VeMissionConsole.cpp index f815ebdc..2a424c4d 100644 --- a/dScripts/VeMissionConsole.cpp +++ b/dScripts/VeMissionConsole.cpp @@ -3,23 +3,23 @@ #include "Character.h" #include "GameMessages.h" -void VeMissionConsole::OnUse(Entity *self, Entity *user) { - LootGenerator::Instance().DropActivityLoot(user, self, 12551); +void VeMissionConsole::OnUse(Entity* self, Entity* user) { + LootGenerator::Instance().DropActivityLoot(user, self, 12551); - auto* inventoryComponent = user->GetComponent(); - if (inventoryComponent != nullptr) { - inventoryComponent->AddItem(12547, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY); // Add the panel required for pickup - } + auto* inventoryComponent = user->GetComponent(); + if (inventoryComponent != nullptr) { + inventoryComponent->AddItem(12547, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY); // Add the panel required for pickup + } - // The flag to set is 101 - const auto flagNumber = self->GetVar(m_NumberVariable); - const auto flag = std::stoi("101" + GeneralUtils::UTF16ToWTF8(flagNumber)); + // The flag to set is 101 + const auto flagNumber = self->GetVar(m_NumberVariable); + const auto flag = std::stoi("101" + GeneralUtils::UTF16ToWTF8(flagNumber)); - auto* character = user->GetCharacter(); - if (character != nullptr) { - character->SetPlayerFlag(flag, true); - } + auto* character = user->GetCharacter(); + if (character != nullptr) { + character->SetPlayerFlag(flag, true); + } - GameMessages::SendNotifyClientObject(self->GetObjectID(), u""); - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u""); + GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/VeMissionConsole.h b/dScripts/VeMissionConsole.h index aecabdaa..8a12964f 100644 --- a/dScripts/VeMissionConsole.h +++ b/dScripts/VeMissionConsole.h @@ -3,7 +3,7 @@ class VeMissionConsole : public CppScripts::Script { public: - void OnUse(Entity *self, Entity *user) override; + void OnUse(Entity* self, Entity* user) override; private: - const std::u16string m_NumberVariable = u"num"; + const std::u16string m_NumberVariable = u"num"; }; diff --git a/dScripts/WaveBossApe.cpp b/dScripts/WaveBossApe.cpp index f4d8a132..7c26cec1 100644 --- a/dScripts/WaveBossApe.cpp +++ b/dScripts/WaveBossApe.cpp @@ -2,40 +2,40 @@ #include "BaseCombatAIComponent.h" #include "Entity.h" -void WaveBossApe::OnStartup(Entity *self) { - BaseWavesGenericEnemy::OnStartup(self); +void WaveBossApe::OnStartup(Entity* self) { + BaseWavesGenericEnemy::OnStartup(self); - self->SetVar(u"QuickbuildAnchorLOT", 12900); - self->SetVar(u"GroundPoundSkill", 725); - self->SetVar(u"reviveTime", 12); - self->SetVar(u"AnchorDamageDelayTime", 0.5f); - self->SetVar(u"spawnQBTime", 5.0f); + self->SetVar(u"QuickbuildAnchorLOT", 12900); + self->SetVar(u"GroundPoundSkill", 725); + self->SetVar(u"reviveTime", 12); + self->SetVar(u"AnchorDamageDelayTime", 0.5f); + self->SetVar(u"spawnQBTime", 5.0f); - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(true); - combatAIComponent->SetStunImmune(true); - } + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(true); + combatAIComponent->SetStunImmune(true); + } - self->AddToGroup("boss"); + self->AddToGroup("boss"); - BaseEnemyApe::OnStartup(self); + BaseEnemyApe::OnStartup(self); } -void WaveBossApe::OnDie(Entity *self, Entity *killer) { - BaseWavesGenericEnemy::OnDie(self, killer); - BaseEnemyApe::OnDie(self, killer); +void WaveBossApe::OnDie(Entity* self, Entity* killer) { + BaseWavesGenericEnemy::OnDie(self, killer); + BaseEnemyApe::OnDie(self, killer); } -void WaveBossApe::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "startAI") { - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(false); - combatAIComponent->SetStunImmune(false); - } - } else { - BaseEnemyApe::OnFireEventServerSide(self, sender, args, param1, param2, param3); - } +void WaveBossApe::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "startAI") { + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(false); + combatAIComponent->SetStunImmune(false); + } + } else { + BaseEnemyApe::OnFireEventServerSide(self, sender, args, param1, param2, param3); + } } diff --git a/dScripts/WaveBossApe.h b/dScripts/WaveBossApe.h index 321a24b2..57f07402 100644 --- a/dScripts/WaveBossApe.h +++ b/dScripts/WaveBossApe.h @@ -1,10 +1,10 @@ #include "BaseWavesGenericEnemy.h" #include "BaseEnemyApe.h" -class WaveBossApe : public BaseEnemyApe, public BaseWavesGenericEnemy { - uint32_t GetPoints() override { return 5000; } - void OnStartup(Entity* self) override; - void OnDie(Entity* self, Entity *killer) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; +class WaveBossApe : public BaseEnemyApe, public BaseWavesGenericEnemy { + uint32_t GetPoints() override { return 5000; } + void OnStartup(Entity* self) override; + void OnDie(Entity* self, Entity* killer) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/WaveBossHammerling.cpp b/dScripts/WaveBossHammerling.cpp index 4775bf42..4fa78087 100644 --- a/dScripts/WaveBossHammerling.cpp +++ b/dScripts/WaveBossHammerling.cpp @@ -2,24 +2,24 @@ #include "BaseCombatAIComponent.h" #include "Entity.h" -void WaveBossHammerling::OnStartup(Entity *self) { - BaseWavesGenericEnemy::OnStartup(self); +void WaveBossHammerling::OnStartup(Entity* self) { + BaseWavesGenericEnemy::OnStartup(self); - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(true); - combatAIComponent->SetStunImmune(true); - } + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(true); + combatAIComponent->SetStunImmune(true); + } - self->AddToGroup("boss"); + self->AddToGroup("boss"); } -void WaveBossHammerling::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { - if (args == "startAI") { - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(false); - } - } +void WaveBossHammerling::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (args == "startAI") { + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(false); + } + } } diff --git a/dScripts/WaveBossHammerling.h b/dScripts/WaveBossHammerling.h index 3ce22252..64da3647 100644 --- a/dScripts/WaveBossHammerling.h +++ b/dScripts/WaveBossHammerling.h @@ -2,8 +2,8 @@ #include "BaseWavesGenericEnemy.h" class WaveBossHammerling : public BaseWavesGenericEnemy { - void OnStartup(Entity* self) override; - uint32_t GetPoints() override { return 1000; } - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnStartup(Entity* self) override; + uint32_t GetPoints() override { return 1000; } + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/WaveBossHorsemen.cpp b/dScripts/WaveBossHorsemen.cpp index c129d654..238544ab 100644 --- a/dScripts/WaveBossHorsemen.cpp +++ b/dScripts/WaveBossHorsemen.cpp @@ -2,25 +2,25 @@ #include "BaseCombatAIComponent.h" #include "Entity.h" -void WaveBossHorsemen::OnStartup(Entity *self) { - BaseWavesGenericEnemy::OnStartup(self); +void WaveBossHorsemen::OnStartup(Entity* self) { + BaseWavesGenericEnemy::OnStartup(self); - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(true); - combatAIComponent->SetStunImmune(true); - } + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(true); + combatAIComponent->SetStunImmune(true); + } - self->AddToGroup("boss"); + self->AddToGroup("boss"); } void -WaveBossHorsemen::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "startAI") { - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(false); - } - } +WaveBossHorsemen::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "startAI") { + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(false); + } + } } diff --git a/dScripts/WaveBossHorsemen.h b/dScripts/WaveBossHorsemen.h index f6160034..e490ffe4 100644 --- a/dScripts/WaveBossHorsemen.h +++ b/dScripts/WaveBossHorsemen.h @@ -2,8 +2,8 @@ #include "BaseWavesGenericEnemy.h" class WaveBossHorsemen : public BaseWavesGenericEnemy { - uint32_t GetPoints() override { return 5000; } - void OnStartup(Entity* self) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + uint32_t GetPoints() override { return 5000; } + void OnStartup(Entity* self) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/WaveBossSpiderling.cpp b/dScripts/WaveBossSpiderling.cpp index 5c8f8766..ec282ff4 100644 --- a/dScripts/WaveBossSpiderling.cpp +++ b/dScripts/WaveBossSpiderling.cpp @@ -2,25 +2,25 @@ #include "BaseCombatAIComponent.h" #include "Entity.h" -void WaveBossSpiderling::OnStartup(Entity *self) { - BaseWavesGenericEnemy::OnStartup(self); +void WaveBossSpiderling::OnStartup(Entity* self) { + BaseWavesGenericEnemy::OnStartup(self); - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(true); - combatAIComponent->SetStunImmune(true); - } + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(true); + combatAIComponent->SetStunImmune(true); + } - self->AddToGroup("boss"); + self->AddToGroup("boss"); } -void WaveBossSpiderling::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, - int32_t param2, int32_t param3) { - if (args == "startAI") { - auto* combatAIComponent = self->GetComponent(); - if (combatAIComponent != nullptr) { - combatAIComponent->SetDisabled(false); - combatAIComponent->SetStunImmune(false); - } - } +void WaveBossSpiderling::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, + int32_t param2, int32_t param3) { + if (args == "startAI") { + auto* combatAIComponent = self->GetComponent(); + if (combatAIComponent != nullptr) { + combatAIComponent->SetDisabled(false); + combatAIComponent->SetStunImmune(false); + } + } } diff --git a/dScripts/WaveBossSpiderling.h b/dScripts/WaveBossSpiderling.h index 23229efc..906b9d37 100644 --- a/dScripts/WaveBossSpiderling.h +++ b/dScripts/WaveBossSpiderling.h @@ -2,8 +2,8 @@ #include "BaseWavesGenericEnemy.h" class WaveBossSpiderling : public BaseWavesGenericEnemy { - uint32_t GetPoints() override { return 5000; } - void OnStartup(Entity* self) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + uint32_t GetPoints() override { return 5000; } + void OnStartup(Entity* self) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; }; diff --git a/dScripts/WhFans.cpp b/dScripts/WhFans.cpp index f71383cf..44354127 100644 --- a/dScripts/WhFans.cpp +++ b/dScripts/WhFans.cpp @@ -41,8 +41,7 @@ void WhFans::ToggleFX(Entity* self, bool hit) { volumePhys->SetPhysicsEffectActive(false); EntityManager::Instance()->SerializeEntity(volume); } - } - else if (!self->GetVar(u"on") && self->GetVar(u"alive")) { + } else if (!self->GetVar(u"on") && self->GetVar(u"alive")) { GameMessages::SendPlayAnimation(self, u"fan-on"); self->SetVar(u"on", true); @@ -56,8 +55,8 @@ void WhFans::ToggleFX(Entity* self, bool hit) { } } -void WhFans::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { +void WhFans::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { if (args.length() == 0 || !self->GetVar(u"alive")) return; if ((args == "turnOn" && self->GetVar(u"on")) || (args == "turnOff" && !self->GetVar(u"on"))) return; diff --git a/dScripts/WhFans.h b/dScripts/WhFans.h index d41eed5b..0762395b 100644 --- a/dScripts/WhFans.h +++ b/dScripts/WhFans.h @@ -6,8 +6,8 @@ public: void OnStartup(Entity* self) override; void OnDie(Entity* self, Entity* killer) override; void OnFireEventServerSide( - Entity *self, - Entity *sender, + Entity* self, + Entity* sender, std::string args, int32_t param1, int32_t param2, diff --git a/dScripts/WildAmbients.cpp b/dScripts/WildAmbients.cpp index f6414ee8..16dfa043 100644 --- a/dScripts/WildAmbients.cpp +++ b/dScripts/WildAmbients.cpp @@ -1,7 +1,6 @@ #include "WildAmbients.h" #include "GameMessages.h" -void WildAmbients::OnUse(Entity* self, Entity* user) -{ +void WildAmbients::OnUse(Entity* self, Entity* user) { GameMessages::SendPlayAnimation(self, u"interact"); } diff --git a/dScripts/WishingWellServer.cpp b/dScripts/WishingWellServer.cpp index 09e953ac..8ac9e0b2 100644 --- a/dScripts/WishingWellServer.cpp +++ b/dScripts/WishingWellServer.cpp @@ -2,48 +2,43 @@ #include "ScriptedActivityComponent.h" #include "GameMessages.h" -void WishingWellServer::OnStartup(Entity* self) -{ +void WishingWellServer::OnStartup(Entity* self) { } -void WishingWellServer::OnUse(Entity* self, Entity* user) -{ - auto* scriptedActivity = self->GetComponent(); +void WishingWellServer::OnUse(Entity* self, Entity* user) { + auto* scriptedActivity = self->GetComponent(); - if (!scriptedActivity->TakeCost(user)) - { - return; - } + if (!scriptedActivity->TakeCost(user)) { + return; + } - const auto audio = self->GetVar(u"sound1"); + const auto audio = self->GetVar(u"sound1"); - if (!audio.empty()) - { - GameMessages::SendPlayNDAudioEmitter(self, user->GetSystemAddress(), audio); - } + if (!audio.empty()) { + GameMessages::SendPlayNDAudioEmitter(self, user->GetSystemAddress(), audio); + } - LootGenerator::Instance().DropActivityLoot( - user, - self, - static_cast(scriptedActivity->GetActivityID()), - GeneralUtils::GenerateRandomNumber(1, 1000) - ); + LootGenerator::Instance().DropActivityLoot( + user, + self, + static_cast(scriptedActivity->GetActivityID()), + GeneralUtils::GenerateRandomNumber(1, 1000) + ); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"StartCooldown", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"StartCooldown", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); - const auto userID = user->GetObjectID(); + const auto userID = user->GetObjectID(); - self->AddCallbackTimer(10, [self, userID] () { - auto* user = EntityManager::Instance()->GetEntity(userID); + self->AddCallbackTimer(10, [self, userID]() { + auto* user = EntityManager::Instance()->GetEntity(userID); - if (user == nullptr) return; - - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"StopCooldown", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); - }); + if (user == nullptr) return; - GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"StopCooldown", 0, 0, LWOOBJID_EMPTY, "", user->GetSystemAddress()); + }); + + GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } -void WishingWellServer::OnTimerDone(Entity* self, std::string timerName) -{ +void WishingWellServer::OnTimerDone(Entity* self, std::string timerName) { } diff --git a/dScripts/WishingWellServer.h b/dScripts/WishingWellServer.h index 3660c31e..856fa8a8 100644 --- a/dScripts/WishingWellServer.h +++ b/dScripts/WishingWellServer.h @@ -6,6 +6,6 @@ class WishingWellServer : public CppScripts::Script public: void OnStartup(Entity* self) override; void OnUse(Entity* self, Entity* user) override; - void OnTimerDone(Entity* self, std::string timerName) override; + void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/ZoneAgMedProperty.cpp b/dScripts/ZoneAgMedProperty.cpp index da8214b1..db1c4c4b 100644 --- a/dScripts/ZoneAgMedProperty.cpp +++ b/dScripts/ZoneAgMedProperty.cpp @@ -1,42 +1,42 @@ #include "ZoneAgMedProperty.h" #include "Entity.h" -void ZoneAgMedProperty::SetGameVariables(Entity *self) { +void ZoneAgMedProperty::SetGameVariables(Entity* self) { - self->SetVar(ClaimMarkerGroup, "ClaimMarker"); - self->SetVar(GeneratorGroup, "Generator"); - self->SetVar(GuardGroup, "Guard"); - self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); - self->SetVar(PropertyVendorGroup, "PropertyVendor"); - self->SetVar(SpotsGroup, "Spots"); - self->SetVar(MSCloudsGroup, "maelstrom"); - self->SetVar(EnemiesGroup, "Enemies"); - self->SetVar(FXManagerGroup, "FXObject"); - self->SetVar(ImagOrbGroup, "Orb"); - self->SetVar(GeneratorFXGroup, "GeneratorFX"); + self->SetVar(ClaimMarkerGroup, "ClaimMarker"); + self->SetVar(GeneratorGroup, "Generator"); + self->SetVar(GuardGroup, "Guard"); + self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); + self->SetVar(PropertyVendorGroup, "PropertyVendor"); + self->SetVar(SpotsGroup, "Spots"); + self->SetVar(MSCloudsGroup, "maelstrom"); + self->SetVar(EnemiesGroup, "Enemies"); + self->SetVar(FXManagerGroup, "FXObject"); + self->SetVar(ImagOrbGroup, "Orb"); + self->SetVar(GeneratorFXGroup, "GeneratorFX"); - self->SetVar>(EnemiesSpawner, { - "StrombieWander", "Strombies", "Mechs", "OtherEnemy" - }); - self->SetVar(ClaimMarkerSpawner, "ClaimMarker"); - self->SetVar(GeneratorSpawner, "Generator"); - self->SetVar(DamageFXSpawner, "MaelstromFX"); - self->SetVar(FXSpotsSpawner, "MaelstromSpots"); - self->SetVar(PropertyMGSpawner, "PropertyGuard"); - self->SetVar(ImageOrbSpawner, "Orb"); - self->SetVar(GeneratorFXSpawner, "GeneratorFX"); - self->SetVar(SmashablesSpawner, "Smashables"); - self->SetVar(FXManagerSpawner, "FXObject"); - self->SetVar(PropObjsSpawner, "BankObj"); - self->SetVar>(AmbientFXSpawner, { "BirdFX", "SunBeam" }); - self->SetVar>(BehaviorObjsSpawner, {}); + self->SetVar>(EnemiesSpawner, { + "StrombieWander", "Strombies", "Mechs", "OtherEnemy" + }); + self->SetVar(ClaimMarkerSpawner, "ClaimMarker"); + self->SetVar(GeneratorSpawner, "Generator"); + self->SetVar(DamageFXSpawner, "MaelstromFX"); + self->SetVar(FXSpotsSpawner, "MaelstromSpots"); + self->SetVar(PropertyMGSpawner, "PropertyGuard"); + self->SetVar(ImageOrbSpawner, "Orb"); + self->SetVar(GeneratorFXSpawner, "GeneratorFX"); + self->SetVar(SmashablesSpawner, "Smashables"); + self->SetVar(FXManagerSpawner, "FXObject"); + self->SetVar(PropObjsSpawner, "BankObj"); + self->SetVar>(AmbientFXSpawner, { "BirdFX", "SunBeam" }); + self->SetVar>(BehaviorObjsSpawner, {}); - self->SetVar(defeatedProperyFlag, 118); - self->SetVar(placedModelFlag, 119); - self->SetVar(guardMissionFlag, 1293); - self->SetVar(brickLinkMissionIDFlag, 1294); - self->SetVar(passwordFlag, "s3kratK1ttN"); - self->SetVar(generatorIdFlag, 10118); - self->SetVar(orbIDFlag, 10226); - self->SetVar(behaviorQBID, 10445); + self->SetVar(defeatedProperyFlag, 118); + self->SetVar(placedModelFlag, 119); + self->SetVar(guardMissionFlag, 1293); + self->SetVar(brickLinkMissionIDFlag, 1294); + self->SetVar(passwordFlag, "s3kratK1ttN"); + self->SetVar(generatorIdFlag, 10118); + self->SetVar(orbIDFlag, 10226); + self->SetVar(behaviorQBID, 10445); } diff --git a/dScripts/ZoneAgMedProperty.h b/dScripts/ZoneAgMedProperty.h index 83b365fd..95597699 100644 --- a/dScripts/ZoneAgMedProperty.h +++ b/dScripts/ZoneAgMedProperty.h @@ -2,5 +2,5 @@ #include "BasePropertyServer.h" class ZoneAgMedProperty : public BasePropertyServer { - void SetGameVariables(Entity *self) override; + void SetGameVariables(Entity* self) override; }; diff --git a/dScripts/ZoneAgProperty.cpp b/dScripts/ZoneAgProperty.cpp index 44650a35..db2bb78a 100644 --- a/dScripts/ZoneAgProperty.cpp +++ b/dScripts/ZoneAgProperty.cpp @@ -7,45 +7,45 @@ #include "RenderComponent.h" #include "MissionComponent.h" -void ZoneAgProperty::SetGameVariables(Entity *self) { - self->SetVar(GuardGroup, "Guard"); - self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); - self->SetVar(PropertyVendorGroup, "PropertyVendor"); - self->SetVar(PropertyBorderGroup, "PropertyBorder"); - self->SetVar(LandTargetGroup, "Land_Target"); - self->SetVar(SpiderScreamGroup, "Spider_Scream"); - self->SetVar>(ROFTargetsGroup, { "ROF_Targets_00", "ROF_Targets_01", "ROF_Targets_02", "ROF_Targets_03", "ROF_Targets_04" }); - self->SetVar(SpiderEggsGroup, "SpiderEggs"); - self->SetVar(RocksGroup, "Rocks"); - self->SetVar(EnemiesGroup, "SpiderBoss"); - self->SetVar>(ZoneVolumesGroup, { "Zone1Vol", "Zone2Vol", "Zone3Vol", "Zone4Vol", "Zone5Vol", "Zone6Vol", "Zone7Vol", "Zone8Vol", "AggroVol", "TeleVol" }); - self->SetVar(FXManagerGroup, "FXObject"); +void ZoneAgProperty::SetGameVariables(Entity* self) { + self->SetVar(GuardGroup, "Guard"); + self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); + self->SetVar(PropertyVendorGroup, "PropertyVendor"); + self->SetVar(PropertyBorderGroup, "PropertyBorder"); + self->SetVar(LandTargetGroup, "Land_Target"); + self->SetVar(SpiderScreamGroup, "Spider_Scream"); + self->SetVar>(ROFTargetsGroup, { "ROF_Targets_00", "ROF_Targets_01", "ROF_Targets_02", "ROF_Targets_03", "ROF_Targets_04" }); + self->SetVar(SpiderEggsGroup, "SpiderEggs"); + self->SetVar(RocksGroup, "Rocks"); + self->SetVar(EnemiesGroup, "SpiderBoss"); + self->SetVar>(ZoneVolumesGroup, { "Zone1Vol", "Zone2Vol", "Zone3Vol", "Zone4Vol", "Zone5Vol", "Zone6Vol", "Zone7Vol", "Zone8Vol", "AggroVol", "TeleVol" }); + self->SetVar(FXManagerGroup, "FXObject"); - self->SetVar(EnemiesSpawner, "SpiderBoss"); - self->SetVar>(BossSensorSpawner, { "Zone1Vol", "Zone2Vol", "Zone3Vol", "Zone4Vol", "Zone5Vol", "Zone6Vol", "Zone7Vol", "Zone8Vol", "RFS_Targets", "AggroVol", "TeleVol" }); - self->SetVar(LandTargetSpawner, "Land_Target"); - self->SetVar(SpiderScreamSpawner, "Spider_Scream"); - self->SetVar>(ROFTargetsSpawner,{ "ROF_Targets_00", "ROF_Targets_01", "ROF_Targets_02", "ROF_Targets_03", "ROF_Targets_04" }); - self->SetVar(PropertyMGSpawner, "PropertyGuard"); - self->SetVar(FXManagerSpawner, "FXObject"); - self->SetVar(PropObjsSpawner, "BankObj"); - self->SetVar(SpiderEggsSpawner, "SpiderEggs"); - self->SetVar(RocksSpawner, "Rocks"); - self->SetVar>(AmbientFXSpawner, { "BirdFX", "SunBeam" }); - self->SetVar>(SpiderRocketSpawner, { "SpiderRocket_Bot", "SpiderRocket_Mid", "SpiderRocket_Top" }); - self->SetVar(MailboxSpawner, "Mailbox"); - self->SetVar(LauncherSpawner, "Launcher"); - self->SetVar(InstancerSpawner, "Instancer"); + self->SetVar(EnemiesSpawner, "SpiderBoss"); + self->SetVar>(BossSensorSpawner, { "Zone1Vol", "Zone2Vol", "Zone3Vol", "Zone4Vol", "Zone5Vol", "Zone6Vol", "Zone7Vol", "Zone8Vol", "RFS_Targets", "AggroVol", "TeleVol" }); + self->SetVar(LandTargetSpawner, "Land_Target"); + self->SetVar(SpiderScreamSpawner, "Spider_Scream"); + self->SetVar>(ROFTargetsSpawner, { "ROF_Targets_00", "ROF_Targets_01", "ROF_Targets_02", "ROF_Targets_03", "ROF_Targets_04" }); + self->SetVar(PropertyMGSpawner, "PropertyGuard"); + self->SetVar(FXManagerSpawner, "FXObject"); + self->SetVar(PropObjsSpawner, "BankObj"); + self->SetVar(SpiderEggsSpawner, "SpiderEggs"); + self->SetVar(RocksSpawner, "Rocks"); + self->SetVar>(AmbientFXSpawner, { "BirdFX", "SunBeam" }); + self->SetVar>(SpiderRocketSpawner, { "SpiderRocket_Bot", "SpiderRocket_Mid", "SpiderRocket_Top" }); + self->SetVar(MailboxSpawner, "Mailbox"); + self->SetVar(LauncherSpawner, "Launcher"); + self->SetVar(InstancerSpawner, "Instancer"); - self->SetVar(defeatedProperyFlag, 71); - self->SetVar(placedModelFlag, 73); - self->SetVar(guardFirstMissionFlag, 891); - self->SetVar(guardMissionFlag, 320); - self->SetVar(brickLinkMissionIDFlag, 951); + self->SetVar(defeatedProperyFlag, 71); + self->SetVar(placedModelFlag, 73); + self->SetVar(guardFirstMissionFlag, 891); + self->SetVar(guardMissionFlag, 320); + self->SetVar(brickLinkMissionIDFlag, 951); } -void ZoneAgProperty::OnStartup(Entity *self) { - LoadProperty(self); +void ZoneAgProperty::OnStartup(Entity* self) { + LoadProperty(self); } void ZoneAgProperty::OnPlayerLoaded(Entity* self, Entity* player) { @@ -59,15 +59,15 @@ void ZoneAgProperty::OnPlayerLoaded(Entity* self, Entity* player) { self->SetVar(u"numberOfPlayers", numberOfPlayers + 1); } - if (dZoneManager::Instance()->GetZone()->GetZoneID().GetMapID() == 1102) { - GameMessages::SendPlay2DAmbientSound(player, GUIDMaelstrom); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, - LWOOBJID_EMPTY, "", player->GetSystemAddress()); - - self->SetNetworkVar(u"unclaimed", true); + if (dZoneManager::Instance()->GetZone()->GetZoneID().GetMapID() == 1102) { + GameMessages::SendPlay2DAmbientSound(player, GUIDMaelstrom); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, + LWOOBJID_EMPTY, "", player->GetSystemAddress()); - return; - } + self->SetNetworkVar(u"unclaimed", true); + + return; + } BasePlayerLoaded(self, player); } @@ -75,13 +75,13 @@ void ZoneAgProperty::OnPlayerLoaded(Entity* self, Entity* player) { void ZoneAgProperty::PropGuardCheck(Entity* self, Entity* player) { auto* missionComponent = player->GetComponent(); if (missionComponent == nullptr) - return; + return; const auto state = missionComponent->GetMissionState(self->GetVar(guardMissionFlag)); const auto firstState = missionComponent->GetMissionState(self->GetVar(guardFirstMissionFlag)); if (firstState < MissionState::MISSION_STATE_COMPLETE || (state != MissionState::MISSION_STATE_COMPLETE && state != MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE)) - ActivateSpawner(self->GetVar(PropertyMGSpawner)); + ActivateSpawner(self->GetVar(PropertyMGSpawner)); } void ZoneAgProperty::OnZoneLoadedInfo(Entity* self) { @@ -89,24 +89,24 @@ void ZoneAgProperty::OnZoneLoadedInfo(Entity* self) { } void ZoneAgProperty::LoadInstance(Entity* self) { - SetGameVariables(self); + SetGameVariables(self); - for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(self->GetVar(InstancerSpawner))) { - for (auto* spawnerNode : spawner->m_Info.nodes) { - spawnerNode->config.push_back( - new LDFData(u"custom_script_server", - R"(scripts\ai\GENERAL\L_INSTANCE_EXIT_TRANSFER_PLAYER_TO_LAST_NON_INSTANCE.lua)")); - spawnerNode->config.push_back(new LDFData(u"transferText", u"SPIDER_QUEEN_EXIT_QUESTION")); - } - } + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(self->GetVar(InstancerSpawner))) { + for (auto* spawnerNode : spawner->m_Info.nodes) { + spawnerNode->config.push_back( + new LDFData(u"custom_script_server", + R"(scripts\ai\GENERAL\L_INSTANCE_EXIT_TRANSFER_PLAYER_TO_LAST_NON_INSTANCE.lua)")); + spawnerNode->config.push_back(new LDFData(u"transferText", u"SPIDER_QUEEN_EXIT_QUESTION")); + } + } - ActivateSpawner(self->GetVar(InstancerSpawner)); + ActivateSpawner(self->GetVar(InstancerSpawner)); } void ZoneAgProperty::LoadProperty(Entity* self) { - SetGameVariables(self); - ActivateSpawner(self->GetVar(LauncherSpawner)); - ActivateSpawner(self->GetVar(MailboxSpawner)); + SetGameVariables(self); + ActivateSpawner(self->GetVar(LauncherSpawner)); + ActivateSpawner(self->GetVar(MailboxSpawner)); } void ZoneAgProperty::ProcessGroupObjects(Entity* self, std::string group) { @@ -114,7 +114,7 @@ void ZoneAgProperty::ProcessGroupObjects(Entity* self, std::string group) { void ZoneAgProperty::SpawnSpots(Entity* self) { for (const auto& spot : self->GetVar>(ROFTargetsSpawner)) { - ActivateSpawner(spot); + ActivateSpawner(spot); } ActivateSpawner(self->GetVar(LandTargetSpawner)); @@ -122,18 +122,18 @@ void ZoneAgProperty::SpawnSpots(Entity* self) { void ZoneAgProperty::KillSpots(Entity* self) { for (const auto& spot : self->GetVar>(ROFTargetsSpawner)) { - DeactivateSpawner(spot); + DeactivateSpawner(spot); } for (const auto& groupName : self->GetVar>(ROFTargetsGroup)) { - for (auto* spot : EntityManager::Instance()->GetEntitiesInGroup(groupName)) { - spot->Kill(); - } + for (auto* spot : EntityManager::Instance()->GetEntitiesInGroup(groupName)) { + spot->Kill(); + } } DeactivateSpawner(self->GetVar(LandTargetSpawner)); for (auto* landTarget : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(LandTargetSpawner))) { - landTarget->Kill(); + landTarget->Kill(); } } @@ -145,13 +145,12 @@ void ZoneAgProperty::SpawnCrashedRocket(Entity* self) { void ZoneAgProperty::KillCrashedRocket(Entity* self) { for (const auto& rocket : self->GetVar>(SpiderRocketSpawner)) { - DeactivateSpawner(rocket); + DeactivateSpawner(rocket); DestroySpawner(rocket); } } -void ZoneAgProperty::StartMaelstrom(Entity* self, Entity* player) -{ +void ZoneAgProperty::StartMaelstrom(Entity* self, Entity* player) { ActivateSpawner(self->GetVar(EnemiesSpawner)); for (const auto& sensor : self->GetVar>(BossSensorSpawner)) { ActivateSpawner(sensor); @@ -163,18 +162,18 @@ void ZoneAgProperty::StartMaelstrom(Entity* self, Entity* player) ActivateSpawner(self->GetVar(RocksSpawner)); SpawnCrashedRocket(self); - + for (const auto& ambient : self->GetVar>(AmbientFXSpawner)) { - DeactivateSpawner(ambient); + DeactivateSpawner(ambient); DestroySpawner(ambient); ResetSpawner(ambient); } - StartTornadoFx(self); + StartTornadoFx(self); if (player != nullptr) { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, LWOOBJID_EMPTY, - "", player->GetSystemAddress()); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, LWOOBJID_EMPTY, + "", player->GetSystemAddress()); } } @@ -186,111 +185,111 @@ uint32_t ZoneAgProperty::RetrieveSpawnerId(Entity* self, const std::string& spaw return spawnerIDs[0]->m_Info.spawnerID; } -void ZoneAgProperty::OnTimerDone(Entity *self, std::string timerName) { - BaseTimerDone(self, timerName); +void ZoneAgProperty::OnTimerDone(Entity* self, std::string timerName) { + BaseTimerDone(self, timerName); } -void ZoneAgProperty::BaseTimerDone(Entity *self, const std::string &timerName) { - if (timerName == "GuardFlyAway") { - const auto zoneId = dZoneManager::Instance()->GetZone()->GetWorldID(); - if (zoneId != 1150) - return; +void ZoneAgProperty::BaseTimerDone(Entity* self, const std::string& timerName) { + if (timerName == "GuardFlyAway") { + const auto zoneId = dZoneManager::Instance()->GetZone()->GetWorldID(); + if (zoneId != 1150) + return; - const auto entities = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(GuardGroup)); - if (entities.empty()) - return; + const auto entities = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(GuardGroup)); + if (entities.empty()) + return; - auto* entity = entities[0]; + auto* entity = entities[0]; - GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), u"GuardChat", 0, 0, entity->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); - LoadProperty(self); + GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), u"GuardChat", 0, 0, entity->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); + LoadProperty(self); - self->AddTimer("KillGuard", 5); - } else if (timerName == "KillGuard") { - KillGuard(self); - } else if (timerName == "tornadoOff") { - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup))) { - auto* renderComponent = entity->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("TornadoDebris", false); - renderComponent->StopEffect("TornadoVortex", false); - renderComponent->StopEffect("silhouette", false); - } - } + self->AddTimer("KillGuard", 5); + } else if (timerName == "KillGuard") { + KillGuard(self); + } else if (timerName == "tornadoOff") { + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup))) { + auto* renderComponent = entity->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("TornadoDebris", false); + renderComponent->StopEffect("TornadoVortex", false); + renderComponent->StopEffect("silhouette", false); + } + } - self->AddTimer("ShowVendor", 1.2f); - self->AddTimer("ShowClearEffects", 2); - } else if (timerName == "ShowClearEffects") { - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup))) { - auto* renderComponent = entity->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->PlayEffect(-1, u"beamOn", "beam"); - } - } + self->AddTimer("ShowVendor", 1.2f); + self->AddTimer("ShowClearEffects", 2); + } else if (timerName == "ShowClearEffects") { + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup))) { + auto* renderComponent = entity->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->PlayEffect(-1, u"beamOn", "beam"); + } + } - self->AddTimer("killSpider", 2); - self->AddTimer("turnSkyOff", 1.5f); - self->AddTimer("killFXObject", 8); - } else if (timerName == "turnSkyOff") { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SkyOff", 0, 0, LWOOBJID_EMPTY, - "", UNASSIGNED_SYSTEM_ADDRESS); - } else if (timerName == "killSpider") { - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(EnemiesGroup))) { - entity->Kill(); - } + self->AddTimer("killSpider", 2); + self->AddTimer("turnSkyOff", 1.5f); + self->AddTimer("killFXObject", 8); + } else if (timerName == "turnSkyOff") { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SkyOff", 0, 0, LWOOBJID_EMPTY, + "", UNASSIGNED_SYSTEM_ADDRESS); + } else if (timerName == "killSpider") { + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(EnemiesGroup))) { + entity->Kill(); + } - for (const auto& sensor : self->GetVar>(BossSensorSpawner)) { - DeactivateSpawner(sensor); - DestroySpawner(sensor); - } + for (const auto& sensor : self->GetVar>(BossSensorSpawner)) { + DeactivateSpawner(sensor); + DestroySpawner(sensor); + } - DeactivateSpawner(self->GetVar(SpiderEggsSpawner)); - DestroySpawner(self->GetVar(SpiderEggsSpawner)); + DeactivateSpawner(self->GetVar(SpiderEggsSpawner)); + DestroySpawner(self->GetVar(SpiderEggsSpawner)); - DeactivateSpawner(self->GetVar(RocksSpawner)); - DestroySpawner(self->GetVar(RocksSpawner)); + DeactivateSpawner(self->GetVar(RocksSpawner)); + DestroySpawner(self->GetVar(RocksSpawner)); - KillSpots(self); - KillCrashedRocket(self); + KillSpots(self); + KillCrashedRocket(self); - DeactivateSpawner(self->GetVar(SpiderScreamSpawner)); - DestroySpawner(self->GetVar(SpiderScreamSpawner)); + DeactivateSpawner(self->GetVar(SpiderScreamSpawner)); + DestroySpawner(self->GetVar(SpiderScreamSpawner)); - for (auto* player : EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER)) { - GameMessages::SendStop2DAmbientSound(player, true, GUIDMaelstrom); - GameMessages::SendPlay2DAmbientSound(player, GUIDPeaceful); - } - } else if (timerName == "ShowVendor") { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"vendorOn", 0, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - for (const auto& ambient : self->GetVar>(AmbientFXSpawner)) { - ActivateSpawner(ambient); - } - } else if (timerName == "BoundsVisOn") { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"boundsAnim", 0, 0, - LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - } else if (timerName == "runPlayerLoadedAgain") { - CheckForOwner(self); - } else if (timerName == "pollTornadoFX") { - StartTornadoFx(self); - } else if (timerName == "killFXObject") { - for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup))) { - auto* renderComponent = entity->GetComponent(); - if (renderComponent != nullptr) { - renderComponent->StopEffect("beam"); - } - } + for (auto* player : EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER)) { + GameMessages::SendStop2DAmbientSound(player, true, GUIDMaelstrom); + GameMessages::SendPlay2DAmbientSound(player, GUIDPeaceful); + } + } else if (timerName == "ShowVendor") { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"vendorOn", 0, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + for (const auto& ambient : self->GetVar>(AmbientFXSpawner)) { + ActivateSpawner(ambient); + } + } else if (timerName == "BoundsVisOn") { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"boundsAnim", 0, 0, + LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); + } else if (timerName == "runPlayerLoadedAgain") { + CheckForOwner(self); + } else if (timerName == "pollTornadoFX") { + StartTornadoFx(self); + } else if (timerName == "killFXObject") { + for (auto* entity : EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(FXManagerGroup))) { + auto* renderComponent = entity->GetComponent(); + if (renderComponent != nullptr) { + renderComponent->StopEffect("beam"); + } + } - DestroySpawner(self->GetVar(FXManagerSpawner)); + DestroySpawner(self->GetVar(FXManagerSpawner)); - self->SetVar(u"FXObjectGone", true); - } else if (timerName == "ProcessGroupObj") { - // TODO - } + self->SetVar(u"FXObjectGone", true); + } else if (timerName == "ProcessGroupObj") { + // TODO + } } void ZoneAgProperty::OnZonePropertyRented(Entity* self, Entity* player) { BaseZonePropertyRented(self, player); - + auto* character = player->GetCharacter(); if (character == nullptr) return; @@ -303,7 +302,7 @@ void ZoneAgProperty::OnZonePropertyModelPlaced(Entity* self, Entity* player) { auto* missionComponent = player->GetComponent(); if (!character->GetPlayerFlag(101)) { - BaseZonePropertyModelPlaced(self, player); + BaseZonePropertyModelPlaced(self, player); character->SetPlayerFlag(101, true); if (missionComponent->GetMissionState(871) == MissionState::MISSION_STATE_ACTIVE) { self->SetNetworkVar(u"Tooltip", u"AnotherModel"); @@ -374,52 +373,52 @@ void ZoneAgProperty::OnZonePropertyEditEnd(Entity* self) { } void ZoneAgProperty::OnPlayerExit(Entity* self) { - // TODO: Destroy stuff + // TODO: Destroy stuff } void ZoneAgProperty::RemovePlayerRef(Entity* self) { - // TODO: Destroy stuff + // TODO: Destroy stuff } -void ZoneAgProperty::BaseOnFireEventServerSide(Entity *self, Entity *sender, std::string args) { - if (args == "propertyRented") { - const auto playerId = self->GetVar(u"playerID"); - auto* player = EntityManager::Instance()->GetEntity(playerId); - if (player == nullptr) - return; +void ZoneAgProperty::BaseOnFireEventServerSide(Entity* self, Entity* sender, std::string args) { + if (args == "propertyRented") { + const auto playerId = self->GetVar(u"playerID"); + auto* player = EntityManager::Instance()->GetEntity(playerId); + if (player == nullptr) + return; - OnZonePropertyRented(self, player); - } else if (args == "RetrieveZoneData") { - self->SetVar(u"SpiderBossID", sender->GetObjectID()); - sender->SetVar(u"SpiderEggNetworkID", RetrieveSpawnerId(self, self->GetVar(SpiderEggsSpawner))); + OnZonePropertyRented(self, player); + } else if (args == "RetrieveZoneData") { + self->SetVar(u"SpiderBossID", sender->GetObjectID()); + sender->SetVar(u"SpiderEggNetworkID", RetrieveSpawnerId(self, self->GetVar(SpiderEggsSpawner))); - std::vector table; + std::vector table; - for (const auto& target : self->GetVar>(ROFTargetsSpawner)) { - table.push_back(RetrieveSpawnerId(self, target)); - } + for (const auto& target : self->GetVar>(ROFTargetsSpawner)) { + table.push_back(RetrieveSpawnerId(self, target)); + } - ROFTargetGroupIdTable = table; + ROFTargetGroupIdTable = table; - ProcessGroupObjects(self, self->GetVar(LandTargetGroup)); - ProcessGroupObjects(self, self->GetVar(SpiderScreamGroup)); -// ProcessGroupObjects(self, groups.ZoneVolumes); - } else if (args == "CheckForPropertyOwner") { - sender->SetNetworkVar(u"PropertyOwnerID", std::to_string(self->GetVar(u"PropertyOwner"))); - } else if (args == "ClearProperty") { - const auto playerId = self->GetVar(u"playerID"); - auto* player = EntityManager::Instance()->GetEntity(playerId); - if (player == nullptr) - return; + ProcessGroupObjects(self, self->GetVar(LandTargetGroup)); + ProcessGroupObjects(self, self->GetVar(SpiderScreamGroup)); + // ProcessGroupObjects(self, groups.ZoneVolumes); + } else if (args == "CheckForPropertyOwner") { + sender->SetNetworkVar(u"PropertyOwnerID", std::to_string(self->GetVar(u"PropertyOwner"))); + } else if (args == "ClearProperty") { + const auto playerId = self->GetVar(u"playerID"); + auto* player = EntityManager::Instance()->GetEntity(playerId); + if (player == nullptr) + return; - player->GetCharacter()->SetPlayerFlag(self->GetVar(defeatedProperyFlag), true); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayCinematic", 0, 0, - LWOOBJID_EMPTY,destroyedCinematic, UNASSIGNED_SYSTEM_ADDRESS); + player->GetCharacter()->SetPlayerFlag(self->GetVar(defeatedProperyFlag), true); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayCinematic", 0, 0, + LWOOBJID_EMPTY, destroyedCinematic, UNASSIGNED_SYSTEM_ADDRESS); - self->AddTimer("tornadoOff", 0.5f); - } + self->AddTimer("tornadoOff", 0.5f); + } } -void ZoneAgProperty::NotifyDie(Entity *self) { - // TODO +void ZoneAgProperty::NotifyDie(Entity* self) { + // TODO } diff --git a/dScripts/ZoneAgProperty.h b/dScripts/ZoneAgProperty.h index 4044be57..b1720783 100644 --- a/dScripts/ZoneAgProperty.h +++ b/dScripts/ZoneAgProperty.h @@ -3,26 +3,28 @@ class ZoneAgProperty : public BasePropertyServer { public: - void SetGameVariables(Entity *self) override; - void OnStartup(Entity* self) override; + void SetGameVariables(Entity* self) override; + void OnStartup(Entity* self) override; void OnPlayerLoaded(Entity* self, Entity* player) override; void OnZoneLoadedInfo(Entity* self); - void OnZonePropertyRented(Entity* self, Entity* player) override; - void OnZonePropertyModelPlaced(Entity* self, Entity* player) override; - void OnZonePropertyModelPickedUp(Entity* self, Entity* player) override; - void OnZonePropertyModelRemoved(Entity* self, Entity* player) override; - void OnZonePropertyModelRemovedWhileEquipped(Entity* self, Entity* player) override; - void OnZonePropertyModelRotated(Entity* self, Entity* player) override; - void OnZonePropertyEditBegin(Entity* self) override; - void OnZonePropertyModelEquipped(Entity* self) override; - void OnZonePropertyEditEnd(Entity* self) override; - void OnPlayerExit(Entity* self); - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override { BaseOnFireEventServerSide(self, sender, args); } - virtual void BaseOnFireEventServerSide(Entity* self, Entity* sender, std::string args); - void OnTimerDone(Entity* self, std::string timerName) override; + void OnZonePropertyRented(Entity* self, Entity* player) override; + void OnZonePropertyModelPlaced(Entity* self, Entity* player) override; + void OnZonePropertyModelPickedUp(Entity* self, Entity* player) override; + void OnZonePropertyModelRemoved(Entity* self, Entity* player) override; + void OnZonePropertyModelRemovedWhileEquipped(Entity* self, Entity* player) override; + void OnZonePropertyModelRotated(Entity* self, Entity* player) override; + void OnZonePropertyEditBegin(Entity* self) override; + void OnZonePropertyModelEquipped(Entity* self) override; + void OnZonePropertyEditEnd(Entity* self) override; + void OnPlayerExit(Entity* self); + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override { + BaseOnFireEventServerSide(self, sender, args); + } + virtual void BaseOnFireEventServerSide(Entity* self, Entity* sender, std::string args); + void OnTimerDone(Entity* self, std::string timerName) override; - void BaseTimerDone(Entity *self, const std::string &timerName) override; + void BaseTimerDone(Entity* self, const std::string& timerName) override; void PropGuardCheck(Entity* self, Entity* player) override; void LoadInstance(Entity* self); @@ -42,23 +44,23 @@ public: void RemovePlayerRef(Entity* self); protected: std::string destroyedCinematic = "DestroyMaelstrom"; - std::vector ROFTargetGroupIdTable {}; - std::u16string LandTargetGroup = u"LandTargetGroup"; - std::u16string SpiderScreamGroup = u"SpiderScreamGroup"; - std::u16string ROFTargetsGroup = u"ROFTargetsGroup"; - std::u16string SpiderEggsGroup = u"SpiderEggsGroup"; - std::u16string RocksGroup = u"RocksGroup"; - std::u16string ZoneVolumesGroup = u"ZoneVolumesGroup"; + std::vector ROFTargetGroupIdTable{}; + std::u16string LandTargetGroup = u"LandTargetGroup"; + std::u16string SpiderScreamGroup = u"SpiderScreamGroup"; + std::u16string ROFTargetsGroup = u"ROFTargetsGroup"; + std::u16string SpiderEggsGroup = u"SpiderEggsGroup"; + std::u16string RocksGroup = u"RocksGroup"; + std::u16string ZoneVolumesGroup = u"ZoneVolumesGroup"; - std::u16string EnemiesSpawner = u"EnemiesSpawner"; - std::u16string BossSensorSpawner = u"BossSensorSpawner"; - std::u16string LandTargetSpawner = u"LandTargetSpawner"; - std::u16string SpiderScreamSpawner = u"SpiderScreamSpawner"; - std::u16string ROFTargetsSpawner = u"ROFTargetsSpawner"; - std::u16string SpiderEggsSpawner = u"SpiderEggsSpawner"; - std::u16string RocksSpawner = u"RocksSpawner"; - std::u16string SpiderRocketSpawner = u"SpiderRocketSpawner"; - std::u16string MailboxSpawner = u"MailboxSpawner"; - std::u16string LauncherSpawner = u"LauncherSpawner"; - std::u16string InstancerSpawner = u"InstancerSpawner"; + std::u16string EnemiesSpawner = u"EnemiesSpawner"; + std::u16string BossSensorSpawner = u"BossSensorSpawner"; + std::u16string LandTargetSpawner = u"LandTargetSpawner"; + std::u16string SpiderScreamSpawner = u"SpiderScreamSpawner"; + std::u16string ROFTargetsSpawner = u"ROFTargetsSpawner"; + std::u16string SpiderEggsSpawner = u"SpiderEggsSpawner"; + std::u16string RocksSpawner = u"RocksSpawner"; + std::u16string SpiderRocketSpawner = u"SpiderRocketSpawner"; + std::u16string MailboxSpawner = u"MailboxSpawner"; + std::u16string LauncherSpawner = u"LauncherSpawner"; + std::u16string InstancerSpawner = u"InstancerSpawner"; }; diff --git a/dScripts/ZoneAgSpiderQueen.cpp b/dScripts/ZoneAgSpiderQueen.cpp index 27c11aa7..ea517448 100644 --- a/dScripts/ZoneAgSpiderQueen.cpp +++ b/dScripts/ZoneAgSpiderQueen.cpp @@ -4,80 +4,80 @@ #include "ZoneAgProperty.h" #include "DestroyableComponent.h" -void ZoneAgSpiderQueen::SetGameVariables(Entity *self) { - ZoneAgProperty::SetGameVariables(self); +void ZoneAgSpiderQueen::SetGameVariables(Entity* self) { + ZoneAgProperty::SetGameVariables(self); - // Disable property flags - self->SetVar(defeatedProperyFlag, 0); - self->SetVar(placedModelFlag, 0); - self->SetVar(guardFirstMissionFlag, 0); - self->SetVar(guardMissionFlag, 0); - self->SetVar(brickLinkMissionIDFlag, 0); + // Disable property flags + self->SetVar(defeatedProperyFlag, 0); + self->SetVar(placedModelFlag, 0); + self->SetVar(guardFirstMissionFlag, 0); + self->SetVar(guardMissionFlag, 0); + self->SetVar(brickLinkMissionIDFlag, 0); } -void ZoneAgSpiderQueen::OnStartup(Entity *self) { - LoadInstance(self); +void ZoneAgSpiderQueen::OnStartup(Entity* self) { + LoadInstance(self); - SpawnSpots(self); - StartMaelstrom(self, nullptr); + SpawnSpots(self); + StartMaelstrom(self, nullptr); } -void ZoneAgSpiderQueen::BasePlayerLoaded(Entity *self, Entity *player) { - ActivityManager::UpdatePlayer(self, player->GetObjectID()); - ActivityManager::TakeActivityCost(self, player->GetObjectID()); +void ZoneAgSpiderQueen::BasePlayerLoaded(Entity* self, Entity* player) { + ActivityManager::UpdatePlayer(self, player->GetObjectID()); + ActivityManager::TakeActivityCost(self, player->GetObjectID()); - // Make sure the player has full stats when they join - auto* playerDestroyableComponent = player->GetComponent(); - if (playerDestroyableComponent != nullptr) { - playerDestroyableComponent->SetImagination(playerDestroyableComponent->GetMaxImagination()); - playerDestroyableComponent->SetArmor(playerDestroyableComponent->GetMaxArmor()); - playerDestroyableComponent->SetHealth(playerDestroyableComponent->GetMaxHealth()); - } + // Make sure the player has full stats when they join + auto* playerDestroyableComponent = player->GetComponent(); + if (playerDestroyableComponent != nullptr) { + playerDestroyableComponent->SetImagination(playerDestroyableComponent->GetMaxImagination()); + playerDestroyableComponent->SetArmor(playerDestroyableComponent->GetMaxArmor()); + playerDestroyableComponent->SetHealth(playerDestroyableComponent->GetMaxHealth()); + } - self->SetNetworkVar(u"unclaimed", true); - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, LWOOBJID_EMPTY, - "", player->GetSystemAddress()); + self->SetNetworkVar(u"unclaimed", true); + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"maelstromSkyOn", 0, 0, LWOOBJID_EMPTY, + "", player->GetSystemAddress()); } void -ZoneAgSpiderQueen::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { - if (args == "ClearProperty") { - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayCinematic", 0, 0, - LWOOBJID_EMPTY, destroyedCinematic, UNASSIGNED_SYSTEM_ADDRESS); - self->AddTimer("tornadoOff", 0.5f); - } else { - ZoneAgProperty::BaseOnFireEventServerSide(self, sender, args); - } +ZoneAgSpiderQueen::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { + if (args == "ClearProperty") { + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayCinematic", 0, 0, + LWOOBJID_EMPTY, destroyedCinematic, UNASSIGNED_SYSTEM_ADDRESS); + self->AddTimer("tornadoOff", 0.5f); + } else { + ZoneAgProperty::BaseOnFireEventServerSide(self, sender, args); + } } -void ZoneAgSpiderQueen::OnPlayerExit(Entity *self, Entity *player) { - UpdatePlayer(self, player->GetObjectID(), true); +void ZoneAgSpiderQueen::OnPlayerExit(Entity* self, Entity* player) { + UpdatePlayer(self, player->GetObjectID(), true); } -void ZoneAgSpiderQueen::OnTimerDone(Entity *self, std::string timerName) { +void ZoneAgSpiderQueen::OnTimerDone(Entity* self, std::string timerName) { - // Disable some stuff from the regular property - if (timerName == "BoundsVisOn" || timerName == "GuardFlyAway" || timerName == "ShowVendor") - return; + // Disable some stuff from the regular property + if (timerName == "BoundsVisOn" || timerName == "GuardFlyAway" || timerName == "ShowVendor") + return; - if (timerName == "killSpider") { - auto spawnTargets = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(LandTargetGroup)); - for (auto* spawnTarget : spawnTargets) { - EntityInfo info{}; + if (timerName == "killSpider") { + auto spawnTargets = EntityManager::Instance()->GetEntitiesInGroup(self->GetVar(LandTargetGroup)); + for (auto* spawnTarget : spawnTargets) { + EntityInfo info{}; - info.spawnerID = spawnTarget->GetObjectID(); - info.pos = spawnTarget->GetPosition(); - info.rot = spawnTarget->GetRotation(); - info.lot = chestObject; - info.settings = { - new LDFData(u"parent_tag", self->GetObjectID()) - }; + info.spawnerID = spawnTarget->GetObjectID(); + info.pos = spawnTarget->GetPosition(); + info.rot = spawnTarget->GetRotation(); + info.lot = chestObject; + info.settings = { + new LDFData(u"parent_tag", self->GetObjectID()) + }; - auto* chest = EntityManager::Instance()->CreateEntity(info); - EntityManager::Instance()->ConstructEntity(chest); - } - } + auto* chest = EntityManager::Instance()->CreateEntity(info); + EntityManager::Instance()->ConstructEntity(chest); + } + } - ZoneAgProperty::BaseTimerDone(self, timerName); -} \ No newline at end of file + ZoneAgProperty::BaseTimerDone(self, timerName); +} diff --git a/dScripts/ZoneAgSpiderQueen.h b/dScripts/ZoneAgSpiderQueen.h index 5536f47a..d7ab1d71 100644 --- a/dScripts/ZoneAgSpiderQueen.h +++ b/dScripts/ZoneAgSpiderQueen.h @@ -4,14 +4,14 @@ class ZoneAgSpiderQueen : ZoneAgProperty, ActivityManager { public: - void OnStartup(Entity* self) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; - void OnTimerDone(Entity *self, std::string timerName) override; - void OnPlayerExit(Entity* self, Entity* player) override; - void BasePlayerLoaded(Entity* self, Entity* player) override; - void SetGameVariables(Entity *self) override; + void OnStartup(Entity* self) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnPlayerExit(Entity* self, Entity* player) override; + void BasePlayerLoaded(Entity* self, Entity* player) override; + void SetGameVariables(Entity* self) override; protected: - std::string destroyedCinematic = "DesMaelstromInstance"; - const LOT chestObject = 16318; + std::string destroyedCinematic = "DesMaelstromInstance"; + const LOT chestObject = 16318; }; diff --git a/dScripts/ZoneAgSurvival.cpp b/dScripts/ZoneAgSurvival.cpp index 5be11f99..79f54c06 100644 --- a/dScripts/ZoneAgSurvival.cpp +++ b/dScripts/ZoneAgSurvival.cpp @@ -1,127 +1,127 @@ #include "ZoneAgSurvival.h" Constants ZoneAgSurvival::GetConstants() { - return Constants { - 60, - 2, - 7, - 5, - 10, - 5, - 15, - 10, - 0, - true, - std::vector {8, 13, 18, 23, 28, 32}, - std::vector {2, 10, 15, 20, 25, 30} - }; + return Constants{ + 60, + 2, + 7, + 5, + 10, + 5, + 15, + 10, + 0, + true, + std::vector {8, 13, 18, 23, 28, 32}, + std::vector {2, 10, 15, 20, 25, 30} + }; } MobSets ZoneAgSurvival::GetMobSets() { - return MobSets { - std::map> { - {"MobA", {6351, 8088, 8089} }, - {"MobB", {6668, 8090, 8091} }, - {"MobC", {6454, 8096, 8097} }, - }, - std::map>>> { - { BaseMobSet, { - { {3, 0, 0}, }, - { {2, 1, 0}, }, - { {4, 1, 0}, }, - { {1, 2, 0}, }, - { {0, 1, 1}, }, - { {0, 2, 2}, } - }}, - { RandMobSet, { - { {4, 0, 0}, {4, 0, 0}, {4, 0, 0}, {4, 0, 0}, {3, 1, 0} }, - { {4, 1, 0}, {4, 1, 0}, {4, 1, 0}, {4, 1, 0}, {2, 1, 1} }, - { {1, 2, 0}, {1, 2, 0}, {1, 2, 0}, {1, 2, 0}, {0, 1, 1} }, - { {1, 2, 1}, {1, 2, 1}, {1, 2, 1}, {0, 2, 1}, {0, 2, 2} }, - { {0, 1, 2}, {0, 1, 2}, {0, 1, 2}, {0, 1, 3}, {0, 1, 3} }, - { {0, 2, 3}, {0, 2, 3}, {0, 2, 3}, {0, 2, 3}, {0, 2, 3} }, - }} - } - }; + return MobSets{ + std::map> { + {"MobA", {6351, 8088, 8089} }, + {"MobB", {6668, 8090, 8091} }, + {"MobC", {6454, 8096, 8097} }, + }, + std::map>>> { + { BaseMobSet, { + { {3, 0, 0}, }, + { {2, 1, 0}, }, + { {4, 1, 0}, }, + { {1, 2, 0}, }, + { {0, 1, 1}, }, + { {0, 2, 2}, } + }}, + { RandMobSet, { + { {4, 0, 0}, {4, 0, 0}, {4, 0, 0}, {4, 0, 0}, {3, 1, 0} }, + { {4, 1, 0}, {4, 1, 0}, {4, 1, 0}, {4, 1, 0}, {2, 1, 1} }, + { {1, 2, 0}, {1, 2, 0}, {1, 2, 0}, {1, 2, 0}, {0, 1, 1} }, + { {1, 2, 1}, {1, 2, 1}, {1, 2, 1}, {0, 2, 1}, {0, 2, 2} }, + { {0, 1, 2}, {0, 1, 2}, {0, 1, 2}, {0, 1, 3}, {0, 1, 3} }, + { {0, 2, 3}, {0, 2, 3}, {0, 2, 3}, {0, 2, 3}, {0, 2, 3} }, + }} + } + }; } SpawnerNetworks ZoneAgSurvival::GetSpawnerNetworks() { - return SpawnerNetworks { - SpawnerNetworkCollection { - BaseMobSet, - { - SpawnerNetwork { - std::vector { "Base_MobA", "Base_MobB", "Base_MobC" }, - "", - false, - false - }, - } - }, - SpawnerNetworkCollection { - RandMobSet, - { - SpawnerNetwork { - std::vector {"MobA_", "MobB_", "MobC_"}, - "01", - false, - false - }, - SpawnerNetwork { - std::vector {"MobA_", "MobB_", "MobC_"}, - "02", - false, - false - }, - SpawnerNetwork { - std::vector {"MobA_", "MobB_", "MobC_"}, - "03", - true, - false - }, - } - }, - SpawnerNetworkCollection { - "", - { - SpawnerNetwork { - std::vector { "Rewards_" }, - "01", - false, - false - }, - } - }, - SpawnerNetworkCollection { - "", - { - SpawnerNetwork { - std::vector { "Smash_" }, - "01", - false, - false - }, - } - } - }; + return SpawnerNetworks{ + SpawnerNetworkCollection { + BaseMobSet, + { + SpawnerNetwork { + std::vector { "Base_MobA", "Base_MobB", "Base_MobC" }, + "", + false, + false + }, + } + }, + SpawnerNetworkCollection { + RandMobSet, + { + SpawnerNetwork { + std::vector {"MobA_", "MobB_", "MobC_"}, + "01", + false, + false + }, + SpawnerNetwork { + std::vector {"MobA_", "MobB_", "MobC_"}, + "02", + false, + false + }, + SpawnerNetwork { + std::vector {"MobA_", "MobB_", "MobC_"}, + "03", + true, + false + }, + } + }, + SpawnerNetworkCollection { + "", + { + SpawnerNetwork { + std::vector { "Rewards_" }, + "01", + false, + false + }, + } + }, + SpawnerNetworkCollection { + "", + { + SpawnerNetwork { + std::vector { "Smash_" }, + "01", + false, + false + }, + } + } + }; } std::map ZoneAgSurvival::GetMissionsToUpdate() { - return std::map { - { 479, 60 }, - { 1153, 180 }, - { 1618, 420 }, - { 1628, 420 }, - { 1638, 420 }, - { 1648, 420 }, - { 1412, 120 }, - { 1510, 120 }, - { 1547, 120 }, - { 1584, 120 }, - { 1426, 300 }, - { 1524, 300 }, - { 1561, 300 }, - { 1598, 300 }, - { 1865, 180 } - }; + return std::map { + { 479, 60 }, + { 1153, 180 }, + { 1618, 420 }, + { 1628, 420 }, + { 1638, 420 }, + { 1648, 420 }, + { 1412, 120 }, + { 1510, 120 }, + { 1547, 120 }, + { 1584, 120 }, + { 1426, 300 }, + { 1524, 300 }, + { 1561, 300 }, + { 1598, 300 }, + { 1865, 180 } + }; } diff --git a/dScripts/ZoneAgSurvival.h b/dScripts/ZoneAgSurvival.h index c5d803ae..4447b6b8 100644 --- a/dScripts/ZoneAgSurvival.h +++ b/dScripts/ZoneAgSurvival.h @@ -4,8 +4,8 @@ #include class ZoneAgSurvival : public BaseSurvivalServer { - Constants GetConstants() override; - SpawnerNetworks GetSpawnerNetworks() override; - MobSets GetMobSets() override; - std::map GetMissionsToUpdate() override; + Constants GetConstants() override; + SpawnerNetworks GetSpawnerNetworks() override; + MobSets GetMobSets() override; + std::map GetMissionsToUpdate() override; }; diff --git a/dScripts/ZoneFvProperty.cpp b/dScripts/ZoneFvProperty.cpp index 64aaad9e..67ada039 100644 --- a/dScripts/ZoneFvProperty.cpp +++ b/dScripts/ZoneFvProperty.cpp @@ -1,40 +1,40 @@ #include "ZoneFvProperty.h" #include "Entity.h" -void ZoneFvProperty::SetGameVariables(Entity *self) { - self->SetVar(ClaimMarkerGroup, "Platform"); - self->SetVar(GeneratorGroup, "Generator"); - self->SetVar(GuardGroup, "Guard"); - self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); - self->SetVar(PropertyVendorGroup, "PropertyVendor"); - self->SetVar(SpotsGroup, "Spots"); - self->SetVar(MSCloudsGroup, "Clouds"); - self->SetVar(EnemiesGroup, "Enemies"); - self->SetVar(FXManagerGroup, "FXManager"); - self->SetVar(ImagOrbGroup, "Orb"); - self->SetVar(GeneratorFXGroup, "GeneratorFX"); +void ZoneFvProperty::SetGameVariables(Entity* self) { + self->SetVar(ClaimMarkerGroup, "Platform"); + self->SetVar(GeneratorGroup, "Generator"); + self->SetVar(GuardGroup, "Guard"); + self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); + self->SetVar(PropertyVendorGroup, "PropertyVendor"); + self->SetVar(SpotsGroup, "Spots"); + self->SetVar(MSCloudsGroup, "Clouds"); + self->SetVar(EnemiesGroup, "Enemies"); + self->SetVar(FXManagerGroup, "FXManager"); + self->SetVar(ImagOrbGroup, "Orb"); + self->SetVar(GeneratorFXGroup, "GeneratorFX"); - self->SetVar>(EnemiesSpawner, - { "RoninWander", "RoninGen", "HorsemenGen" }); - self->SetVar(ClaimMarkerSpawner, "Platform"); - self->SetVar(GeneratorSpawner, "Generator"); - self->SetVar(DamageFXSpawner, "Clouds"); - self->SetVar(FXSpotsSpawner, "Spots"); - self->SetVar(PropertyMGSpawner, "Guard"); - self->SetVar(ImageOrbSpawner, "Orb"); - self->SetVar(GeneratorFXSpawner, "GeneratorFX"); - self->SetVar(SmashablesSpawner, "Smashables"); - self->SetVar(FXManagerSpawner, "FXManager"); - self->SetVar(PropObjsSpawner, "BankObj"); - self->SetVar>(AmbientFXSpawner, { "Ash", "FX", "Fog"}); - self->SetVar>(BehaviorObjsSpawner, {}); + self->SetVar>(EnemiesSpawner, + { "RoninWander", "RoninGen", "HorsemenGen" }); + self->SetVar(ClaimMarkerSpawner, "Platform"); + self->SetVar(GeneratorSpawner, "Generator"); + self->SetVar(DamageFXSpawner, "Clouds"); + self->SetVar(FXSpotsSpawner, "Spots"); + self->SetVar(PropertyMGSpawner, "Guard"); + self->SetVar(ImageOrbSpawner, "Orb"); + self->SetVar(GeneratorFXSpawner, "GeneratorFX"); + self->SetVar(SmashablesSpawner, "Smashables"); + self->SetVar(FXManagerSpawner, "FXManager"); + self->SetVar(PropObjsSpawner, "BankObj"); + self->SetVar>(AmbientFXSpawner, { "Ash", "FX", "Fog" }); + self->SetVar>(BehaviorObjsSpawner, {}); - self->SetVar(defeatedProperyFlag, 99); - self->SetVar(placedModelFlag, 107); - self->SetVar(guardMissionFlag, 874); - self->SetVar(brickLinkMissionIDFlag, 950); - self->SetVar(passwordFlag, "s3kratK1ttN"); - self->SetVar(generatorIdFlag, 11023); - self->SetVar(orbIDFlag, 10226); - self->SetVar(behaviorQBID, 11011); + self->SetVar(defeatedProperyFlag, 99); + self->SetVar(placedModelFlag, 107); + self->SetVar(guardMissionFlag, 874); + self->SetVar(brickLinkMissionIDFlag, 950); + self->SetVar(passwordFlag, "s3kratK1ttN"); + self->SetVar(generatorIdFlag, 11023); + self->SetVar(orbIDFlag, 10226); + self->SetVar(behaviorQBID, 11011); } diff --git a/dScripts/ZoneFvProperty.h b/dScripts/ZoneFvProperty.h index 44ec9f85..d456ef11 100644 --- a/dScripts/ZoneFvProperty.h +++ b/dScripts/ZoneFvProperty.h @@ -2,5 +2,5 @@ #include "BasePropertyServer.h" class ZoneFvProperty : public BasePropertyServer { - void SetGameVariables(Entity *self) override; + void SetGameVariables(Entity* self) override; }; diff --git a/dScripts/ZoneGfProperty.cpp b/dScripts/ZoneGfProperty.cpp index 925320c3..565d8cd6 100644 --- a/dScripts/ZoneGfProperty.cpp +++ b/dScripts/ZoneGfProperty.cpp @@ -1,40 +1,40 @@ #include "ZoneGfProperty.h" #include "Entity.h" -void ZoneGfProperty::SetGameVariables(Entity *self) { - self->SetVar(ClaimMarkerGroup, "BehavQB"); - self->SetVar(GeneratorGroup, "Generator"); - self->SetVar(GuardGroup, "Guard"); - self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); - self->SetVar(PropertyVendorGroup, "PropertyVendor"); - self->SetVar(SpotsGroup, "Spots"); - self->SetVar(MSCloudsGroup, "Clouds"); - self->SetVar(EnemiesGroup, "Enemies"); - self->SetVar(FXManagerGroup, "FXManager"); - self->SetVar(ImagOrbGroup, "Orb"); - self->SetVar(GeneratorFXGroup, "GeneratorFX"); +void ZoneGfProperty::SetGameVariables(Entity* self) { + self->SetVar(ClaimMarkerGroup, "BehavQB"); + self->SetVar(GeneratorGroup, "Generator"); + self->SetVar(GuardGroup, "Guard"); + self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); + self->SetVar(PropertyVendorGroup, "PropertyVendor"); + self->SetVar(SpotsGroup, "Spots"); + self->SetVar(MSCloudsGroup, "Clouds"); + self->SetVar(EnemiesGroup, "Enemies"); + self->SetVar(FXManagerGroup, "FXManager"); + self->SetVar(ImagOrbGroup, "Orb"); + self->SetVar(GeneratorFXGroup, "GeneratorFX"); - self->SetVar>(EnemiesSpawner, - { "PiratesWander", "PiratesGen", "AdmiralsWander", "AdmiralsGen" }); - self->SetVar(ClaimMarkerSpawner, "BehavPlat"); - self->SetVar(GeneratorSpawner, "Generator"); - self->SetVar(DamageFXSpawner, "Clouds"); - self->SetVar(FXSpotsSpawner, "Spots"); - self->SetVar(PropertyMGSpawner, "Guard"); - self->SetVar(ImageOrbSpawner, "Orb"); - self->SetVar(GeneratorFXSpawner, "GeneratorFX"); - self->SetVar(SmashablesSpawner, "Smashables"); - self->SetVar(FXManagerSpawner, "FXManager"); - self->SetVar(PropObjsSpawner, "BankObj"); - self->SetVar>(AmbientFXSpawner, { "Birds", "Falls", "Sunbeam" }); - self->SetVar>(BehaviorObjsSpawner, { "TrappedPlatform", "IceBarrier", "FireBeast" }); + self->SetVar>(EnemiesSpawner, + { "PiratesWander", "PiratesGen", "AdmiralsWander", "AdmiralsGen" }); + self->SetVar(ClaimMarkerSpawner, "BehavPlat"); + self->SetVar(GeneratorSpawner, "Generator"); + self->SetVar(DamageFXSpawner, "Clouds"); + self->SetVar(FXSpotsSpawner, "Spots"); + self->SetVar(PropertyMGSpawner, "Guard"); + self->SetVar(ImageOrbSpawner, "Orb"); + self->SetVar(GeneratorFXSpawner, "GeneratorFX"); + self->SetVar(SmashablesSpawner, "Smashables"); + self->SetVar(FXManagerSpawner, "FXManager"); + self->SetVar(PropObjsSpawner, "BankObj"); + self->SetVar>(AmbientFXSpawner, { "Birds", "Falls", "Sunbeam" }); + self->SetVar>(BehaviorObjsSpawner, { "TrappedPlatform", "IceBarrier", "FireBeast" }); - self->SetVar(defeatedProperyFlag, 98); - self->SetVar(placedModelFlag, 106); - self->SetVar(guardMissionFlag, 873); - self->SetVar(brickLinkMissionIDFlag, 949); - self->SetVar(passwordFlag, "s3kratK1ttN"); - self->SetVar(generatorIdFlag, 11109); - self->SetVar(orbIDFlag, 10226); - self->SetVar(behaviorQBID, 11001); + self->SetVar(defeatedProperyFlag, 98); + self->SetVar(placedModelFlag, 106); + self->SetVar(guardMissionFlag, 873); + self->SetVar(brickLinkMissionIDFlag, 949); + self->SetVar(passwordFlag, "s3kratK1ttN"); + self->SetVar(generatorIdFlag, 11109); + self->SetVar(orbIDFlag, 10226); + self->SetVar(behaviorQBID, 11001); } diff --git a/dScripts/ZoneGfProperty.h b/dScripts/ZoneGfProperty.h index 9b3a8a30..74ffd3b6 100644 --- a/dScripts/ZoneGfProperty.h +++ b/dScripts/ZoneGfProperty.h @@ -2,5 +2,5 @@ #include "BasePropertyServer.h" class ZoneGfProperty : public BasePropertyServer { - void SetGameVariables(Entity *self) override; + void SetGameVariables(Entity* self) override; }; diff --git a/dScripts/ZoneNsMedProperty.cpp b/dScripts/ZoneNsMedProperty.cpp index feaadf31..30e597ee 100644 --- a/dScripts/ZoneNsMedProperty.cpp +++ b/dScripts/ZoneNsMedProperty.cpp @@ -1,40 +1,40 @@ #include "ZoneNsMedProperty.h" #include "Entity.h" -void ZoneNsMedProperty::SetGameVariables(Entity *self) { - self->SetVar(ClaimMarkerGroup, "ClaimMarker"); - self->SetVar(GeneratorGroup, "Generator"); - self->SetVar(GuardGroup, "Guard"); - self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); - self->SetVar(PropertyVendorGroup, "PropertyVendor"); - self->SetVar(SpotsGroup, "Spots"); - self->SetVar(MSCloudsGroup, "maelstrom"); - self->SetVar(EnemiesGroup, "Enemies"); - self->SetVar(FXManagerGroup, "FXObject"); - self->SetVar(ImagOrbGroup, "Orb"); - self->SetVar(GeneratorFXGroup, "GeneratorFX"); +void ZoneNsMedProperty::SetGameVariables(Entity* self) { + self->SetVar(ClaimMarkerGroup, "ClaimMarker"); + self->SetVar(GeneratorGroup, "Generator"); + self->SetVar(GuardGroup, "Guard"); + self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); + self->SetVar(PropertyVendorGroup, "PropertyVendor"); + self->SetVar(SpotsGroup, "Spots"); + self->SetVar(MSCloudsGroup, "maelstrom"); + self->SetVar(EnemiesGroup, "Enemies"); + self->SetVar(FXManagerGroup, "FXObject"); + self->SetVar(ImagOrbGroup, "Orb"); + self->SetVar(GeneratorFXGroup, "GeneratorFX"); - self->SetVar>(EnemiesSpawner, - { "Admirals", "AdmiralsWander", "Mechs", "Ronin", "RoninWander" }); - self->SetVar(ClaimMarkerSpawner, "ClaimMarker"); - self->SetVar(GeneratorSpawner, "Generator"); - self->SetVar(DamageFXSpawner, "MaelstromFX"); - self->SetVar(FXSpotsSpawner, "MaelstromSpots"); - self->SetVar(PropertyMGSpawner, "PropertyGuard"); - self->SetVar(ImageOrbSpawner, "Orb"); - self->SetVar(GeneratorFXSpawner, "GeneratorFX"); - self->SetVar(SmashablesSpawner, "Smashables"); - self->SetVar(FXManagerSpawner, "FXObject"); - self->SetVar(PropObjsSpawner, "BankObj"); - self->SetVar>(AmbientFXSpawner, { "Rockets" }); - self->SetVar>(BehaviorObjsSpawner, { }); + self->SetVar>(EnemiesSpawner, + { "Admirals", "AdmiralsWander", "Mechs", "Ronin", "RoninWander" }); + self->SetVar(ClaimMarkerSpawner, "ClaimMarker"); + self->SetVar(GeneratorSpawner, "Generator"); + self->SetVar(DamageFXSpawner, "MaelstromFX"); + self->SetVar(FXSpotsSpawner, "MaelstromSpots"); + self->SetVar(PropertyMGSpawner, "PropertyGuard"); + self->SetVar(ImageOrbSpawner, "Orb"); + self->SetVar(GeneratorFXSpawner, "GeneratorFX"); + self->SetVar(SmashablesSpawner, "Smashables"); + self->SetVar(FXManagerSpawner, "FXObject"); + self->SetVar(PropObjsSpawner, "BankObj"); + self->SetVar>(AmbientFXSpawner, { "Rockets" }); + self->SetVar>(BehaviorObjsSpawner, { }); - self->SetVar(defeatedProperyFlag, 122); - self->SetVar(placedModelFlag, 123); - self->SetVar(guardMissionFlag, 1322); - self->SetVar(brickLinkMissionIDFlag, 1294); - self->SetVar(passwordFlag, "s3kratK1ttN"); - self->SetVar(generatorIdFlag, 11031); - self->SetVar(orbIDFlag, 10226); - self->SetVar(behaviorQBID, 10445); + self->SetVar(defeatedProperyFlag, 122); + self->SetVar(placedModelFlag, 123); + self->SetVar(guardMissionFlag, 1322); + self->SetVar(brickLinkMissionIDFlag, 1294); + self->SetVar(passwordFlag, "s3kratK1ttN"); + self->SetVar(generatorIdFlag, 11031); + self->SetVar(orbIDFlag, 10226); + self->SetVar(behaviorQBID, 10445); } diff --git a/dScripts/ZoneNsMedProperty.h b/dScripts/ZoneNsMedProperty.h index d25974e1..3aaf6bd8 100644 --- a/dScripts/ZoneNsMedProperty.h +++ b/dScripts/ZoneNsMedProperty.h @@ -2,5 +2,5 @@ #include "BasePropertyServer.h" class ZoneNsMedProperty : public BasePropertyServer { - void SetGameVariables(Entity *self) override; + void SetGameVariables(Entity* self) override; }; diff --git a/dScripts/ZoneNsProperty.cpp b/dScripts/ZoneNsProperty.cpp index 72eb1ead..49364ee8 100644 --- a/dScripts/ZoneNsProperty.cpp +++ b/dScripts/ZoneNsProperty.cpp @@ -1,41 +1,41 @@ #include "ZoneNsProperty.h" #include "Entity.h" -void ZoneNsProperty::SetGameVariables(Entity *self) { - self->SetVar(ClaimMarkerGroup, "Rhino"); - self->SetVar(GeneratorGroup, "Generator"); - self->SetVar(GuardGroup, "Guard"); - self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); - self->SetVar(PropertyVendorGroup, "PropertyVendor"); - self->SetVar(SpotsGroup, "Spots"); - self->SetVar(MSCloudsGroup, "Clouds"); - self->SetVar(EnemiesGroup, "Enemies"); - self->SetVar(FXManagerGroup, "FXManager"); - self->SetVar(ImagOrbGroup, "Orb"); - self->SetVar(GeneratorFXGroup, "GeneratorFX"); +void ZoneNsProperty::SetGameVariables(Entity* self) { + self->SetVar(ClaimMarkerGroup, "Rhino"); + self->SetVar(GeneratorGroup, "Generator"); + self->SetVar(GuardGroup, "Guard"); + self->SetVar(PropertyPlaqueGroup, "PropertyPlaque"); + self->SetVar(PropertyVendorGroup, "PropertyVendor"); + self->SetVar(SpotsGroup, "Spots"); + self->SetVar(MSCloudsGroup, "Clouds"); + self->SetVar(EnemiesGroup, "Enemies"); + self->SetVar(FXManagerGroup, "FXManager"); + self->SetVar(ImagOrbGroup, "Orb"); + self->SetVar(GeneratorFXGroup, "GeneratorFX"); - self->SetVar>(EnemiesSpawner, { - "StrombieWander", "StrombieGen", "PirateWander", "PirateGen", "RoninGen" - }); - self->SetVar(ClaimMarkerSpawner, "ClaimMarker"); - self->SetVar(GeneratorSpawner, "Generator"); - self->SetVar(DamageFXSpawner, "MSClouds"); - self->SetVar(FXSpotsSpawner, "Spots"); - self->SetVar(PropertyMGSpawner, "Guard"); - self->SetVar(ImageOrbSpawner, "Orb"); - self->SetVar(GeneratorFXSpawner, "GeneratorFX"); - self->SetVar(SmashablesSpawner, "Smashables"); - self->SetVar(FXManagerSpawner, "FXManager"); - self->SetVar(PropObjsSpawner, "BankObj"); - self->SetVar>(AmbientFXSpawner, { "Rockets" }); - self->SetVar>(BehaviorObjsSpawner,{ "Cage", "Platform", "Door" }); + self->SetVar>(EnemiesSpawner, { + "StrombieWander", "StrombieGen", "PirateWander", "PirateGen", "RoninGen" + }); + self->SetVar(ClaimMarkerSpawner, "ClaimMarker"); + self->SetVar(GeneratorSpawner, "Generator"); + self->SetVar(DamageFXSpawner, "MSClouds"); + self->SetVar(FXSpotsSpawner, "Spots"); + self->SetVar(PropertyMGSpawner, "Guard"); + self->SetVar(ImageOrbSpawner, "Orb"); + self->SetVar(GeneratorFXSpawner, "GeneratorFX"); + self->SetVar(SmashablesSpawner, "Smashables"); + self->SetVar(FXManagerSpawner, "FXManager"); + self->SetVar(PropObjsSpawner, "BankObj"); + self->SetVar>(AmbientFXSpawner, { "Rockets" }); + self->SetVar>(BehaviorObjsSpawner, { "Cage", "Platform", "Door" }); - self->SetVar(defeatedProperyFlag, 97); - self->SetVar(placedModelFlag, 105); - self->SetVar(guardMissionFlag, 872); - self->SetVar(brickLinkMissionIDFlag, 948); - self->SetVar(passwordFlag, "s3kratK1ttN"); - self->SetVar(generatorIdFlag, 11031); - self->SetVar(orbIDFlag, 10226); - self->SetVar(behaviorQBID, 11009); + self->SetVar(defeatedProperyFlag, 97); + self->SetVar(placedModelFlag, 105); + self->SetVar(guardMissionFlag, 872); + self->SetVar(brickLinkMissionIDFlag, 948); + self->SetVar(passwordFlag, "s3kratK1ttN"); + self->SetVar(generatorIdFlag, 11031); + self->SetVar(orbIDFlag, 10226); + self->SetVar(behaviorQBID, 11009); } diff --git a/dScripts/ZoneNsProperty.h b/dScripts/ZoneNsProperty.h index 353f4d72..bee8fd4c 100644 --- a/dScripts/ZoneNsProperty.h +++ b/dScripts/ZoneNsProperty.h @@ -2,5 +2,5 @@ #include "BasePropertyServer.h" class ZoneNsProperty : public BasePropertyServer { - void SetGameVariables(Entity *self) override; + void SetGameVariables(Entity* self) override; }; diff --git a/dScripts/ZoneNsWaves.cpp b/dScripts/ZoneNsWaves.cpp index 9f54ae49..6f78acb6 100644 --- a/dScripts/ZoneNsWaves.cpp +++ b/dScripts/ZoneNsWaves.cpp @@ -1,500 +1,500 @@ #include "ZoneNsWaves.h" WaveConstants ZoneNsWaves::GetConstants() { - return { - 60, - 2, - 6, - 2, - "surprise", - "intro" - }; + return { + 60, + 2, + 6, + 2, + "surprise", + "intro" + }; } std::vector ZoneNsWaves::GetSpawnerNames() { - return { - "Base_MobA", - "Base_MobB", - "Base_MobC", - "MobA_01", - "MobB_01", - "MobC_01", - "MobA_02", - "MobB_02", - "MobC_02", - "MobA_03", - "MobB_03", - "MobC_03", - "Reward_01", - "Base_Reward", - "Obstacle_01", - "Boss", - "Ape_Boss", - "Geyser_01", - "Treasure_01", - "Cavalry_Boss", - "Horseman_01", - "Horseman_02", - "Horseman_03", - "Horseman_04" - }; + return { + "Base_MobA", + "Base_MobB", + "Base_MobC", + "MobA_01", + "MobB_01", + "MobC_01", + "MobA_02", + "MobB_02", + "MobC_02", + "MobA_03", + "MobB_03", + "MobC_03", + "Reward_01", + "Base_Reward", + "Obstacle_01", + "Boss", + "Ape_Boss", + "Geyser_01", + "Treasure_01", + "Cavalry_Boss", + "Horseman_01", + "Horseman_02", + "Horseman_03", + "Horseman_04" + }; } std::vector ZoneNsWaves::GetWaveMissions() { - return { - {190, 7, 1242}, - {240, 7, 1226}, - {450, 15, 1243}, - {600, 15, 1227}, - {720, 22, 1244}, - {840, 22, 1228}, - {1080, 29, 1245}, - {1200, 29, 1229}, - }; + return { + {190, 7, 1242}, + {240, 7, 1226}, + {450, 15, 1243}, + {600, 15, 1227}, + {720, 22, 1244}, + {840, 22, 1228}, + {1080, 29, 1245}, + {1200, 29, 1229}, + }; } std::vector ZoneNsWaves::GetWaves() { - return { - // Wave 1 - Wave { - std::vector { - { SpawnLOTS::stromling_minifig, 8, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::stromling_minifig, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::stromling_minifig, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::stromling_minifig, 2, GetSpawnerName(SpawnerName::gf_A) }, - } - }, + return { + // Wave 1 + Wave { + std::vector { + { SpawnLOTS::stromling_minifig, 8, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::stromling_minifig, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::stromling_minifig, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::stromling_minifig, 2, GetSpawnerName(SpawnerName::gf_A) }, + } + }, - // Wave 2 - Wave { - std::vector { - { SpawnLOTS::stromling, 8, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::gf_A) }, - } - }, + // Wave 2 + Wave { + std::vector { + { SpawnLOTS::stromling, 8, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::gf_A) }, + } + }, - // Wave 3 - Wave { - std::vector { - { SpawnLOTS::stromling, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::gf_A) }, - }, - }, + // Wave 3 + Wave { + std::vector { + { SpawnLOTS::stromling, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::gf_A) }, + }, + }, - // Wave 4 - Wave { - std::vector { - { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 4 + Wave { + std::vector { + { SpawnLOTS::stromling, 3, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 5 - Wave { - std::vector { - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::stromling, 1, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::stromling, 1, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 5 + Wave { + std::vector { + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::stromling, 1, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::stromling, 1, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 6 - Wave { - std::vector { - { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 6 + Wave { + std::vector { + { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::stromling, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 7 - Wave { - std::vector { - { SpawnLOTS::stromling_boss, 1, GetSpawnerName(SpawnerName::Boss) }, - }, - {1885}, - {}, - "Stromling_Boss", - 5.0f - }, + // Wave 7 + Wave { + std::vector { + { SpawnLOTS::stromling_boss, 1, GetSpawnerName(SpawnerName::Boss) }, + }, + {1885}, + {}, + "Stromling_Boss", + 5.0f + }, - // Wave 8 - Wave { - std::vector { - {SpawnLOTS::mushroom, 6, GetSpawnerName(SpawnerName::Reward_01) }, - {SpawnLOTS::mushroom, 3, GetSpawnerName(SpawnerName::interior_Reward) }, - }, {}, {}, "", -1.0f, - 25, - }, + // Wave 8 + Wave { + std::vector { + {SpawnLOTS::mushroom, 6, GetSpawnerName(SpawnerName::Reward_01) }, + {SpawnLOTS::mushroom, 3, GetSpawnerName(SpawnerName::interior_Reward) }, + }, {}, {}, "", -1.0f, + 25, + }, - // Wave 9 - Wave { - std::vector { - { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 9 + Wave { + std::vector { + { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 10 - Wave { - std::vector { - { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 10 + Wave { + std::vector { + { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 11 - Wave { - std::vector { - { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::concert_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::gf_C) }, - } - }, + // Wave 11 + Wave { + std::vector { + { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::concert_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::gf_C) }, + } + }, - // Wave 12 - Wave { - std::vector { - { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_C) }, - } - }, + // Wave 12 + Wave { + std::vector { + { SpawnLOTS::pirate, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_C) }, + } + }, - // Wave 13 - Wave { - std::vector { - { SpawnLOTS::pirate, 3, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 13 + Wave { + std::vector { + { SpawnLOTS::pirate, 3, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 14 - Wave { - std::vector { - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_C) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_B) }, - { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_C) }, - } - }, + // Wave 14 + Wave { + std::vector { + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::mech, 2, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::concert_C) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_B) }, + { SpawnLOTS::mech, 1, GetSpawnerName(SpawnerName::gf_C) }, + } + }, - // Wave 15 - Wave { - std::vector { - { SpawnLOTS::ape_boss, 1, GetSpawnerName(SpawnerName::Ape_Boss) }, + // Wave 15 + Wave { + std::vector { + { SpawnLOTS::ape_boss, 1, GetSpawnerName(SpawnerName::Ape_Boss) }, - }, - {1886}, - {}, - "Gorilla_Boss", - 5.0f - }, + }, + {1886}, + {}, + "Gorilla_Boss", + 5.0f + }, - // Wave 16 - Wave { - std::vector { - {SpawnLOTS::outhouse, 3, GetSpawnerName(SpawnerName::interior_Reward) }, - {SpawnLOTS::mushroom, 6, GetSpawnerName(SpawnerName::Reward_01) }, - }, {}, {}, "", -1.0f, - 25, - }, + // Wave 16 + Wave { + std::vector { + {SpawnLOTS::outhouse, 3, GetSpawnerName(SpawnerName::interior_Reward) }, + {SpawnLOTS::mushroom, 6, GetSpawnerName(SpawnerName::Reward_01) }, + }, {}, {}, "", -1.0f, + 25, + }, - // Wave 17 - Wave { - std::vector { - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 17 + Wave { + std::vector { + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::hammerling_melee, 1, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 18 - Wave { - std::vector { - { SpawnLOTS::hammerling_melee, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 18 + Wave { + std::vector { + { SpawnLOTS::hammerling_melee, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::hammerling_melee, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 19 - Wave { - std::vector { - { SpawnLOTS::hammerling, 4, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::sentry, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::gf_B) }, - } - }, + // Wave 19 + Wave { + std::vector { + { SpawnLOTS::hammerling, 4, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::sentry, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::hammerling, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::gf_B) }, + } + }, - // Wave 20 - Wave { - std::vector { - { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::sentry, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::concert_C) }, - { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::gf_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::gf_C) }, - } - }, + // Wave 20 + Wave { + std::vector { + { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::sentry, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::concert_C) }, + { SpawnLOTS::hammerling, 1, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::sentry, 1, GetSpawnerName(SpawnerName::gf_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::gf_C) }, + } + }, - // Wave 21 - Wave { - std::vector { - { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::ronin, 2, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::spiderling_ve, 2, GetSpawnerName(SpawnerName::interior_C) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::ronin, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::ronin, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::concert_C) }, - { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::ronin, 1, GetSpawnerName(SpawnerName::gf_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::gf_C) }, - } - }, + // Wave 21 + Wave { + std::vector { + { SpawnLOTS::admiral, 2, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::ronin, 2, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::spiderling_ve, 2, GetSpawnerName(SpawnerName::interior_C) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::ronin, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::ronin, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::concert_C) }, + { SpawnLOTS::admiral, 1, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::ronin, 1, GetSpawnerName(SpawnerName::gf_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::gf_C) }, + } + }, - // Wave 22 - Wave { - std::vector { - { SpawnLOTS::spiderling_boss, 1, GetSpawnerName(SpawnerName::Cavalry_Boss) }, - }, - {1887}, - {}, - "Spiderling_Boss", - 5.0f - }, + // Wave 22 + Wave { + std::vector { + { SpawnLOTS::spiderling_boss, 1, GetSpawnerName(SpawnerName::Cavalry_Boss) }, + }, + {1887}, + {}, + "Spiderling_Boss", + 5.0f + }, - // Wave 23 - Wave { - std::vector { - { SpawnLOTS::outhouse, 6, GetSpawnerName(SpawnerName::Reward_01) }, - { SpawnLOTS::outhouse, 3, GetSpawnerName(SpawnerName::interior_Reward) }, - { SpawnLOTS::maelstrom_chest, 4, GetSpawnerName(SpawnerName::Obstacle) }, - }, {}, {}, "", -1.0f, - 25, - }, + // Wave 23 + Wave { + std::vector { + { SpawnLOTS::outhouse, 6, GetSpawnerName(SpawnerName::Reward_01) }, + { SpawnLOTS::outhouse, 3, GetSpawnerName(SpawnerName::interior_Reward) }, + { SpawnLOTS::maelstrom_chest, 4, GetSpawnerName(SpawnerName::Obstacle) }, + }, {}, {}, "", -1.0f, + 25, + }, - // Wave 24 - Wave { - std::vector { - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::pirate, 3, GetSpawnerName(SpawnerName::ag_A) }, - { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::ronin, 2, GetSpawnerName(SpawnerName::interior_B) }, - } - }, + // Wave 24 + Wave { + std::vector { + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::pirate, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::pirate, 3, GetSpawnerName(SpawnerName::ag_A) }, + { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::ronin, 2, GetSpawnerName(SpawnerName::interior_B) }, + } + }, - // Wave 25 - Wave { - std::vector { - { SpawnLOTS::cavalry, 2, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::gf_B) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::gf_A) }, - { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::concert_A) }, - { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_A) }, - } - }, + // Wave 25 + Wave { + std::vector { + { SpawnLOTS::cavalry, 2, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::gf_B) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::gf_A) }, + { SpawnLOTS::spiderling, 2, GetSpawnerName(SpawnerName::concert_A) }, + { SpawnLOTS::spiderling, 1, GetSpawnerName(SpawnerName::ag_A) }, + } + }, - // Wave 26 - Wave { - std::vector { - { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::gf_B) }, - { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::concert_B) }, - { SpawnLOTS::admiral_cp, 2, GetSpawnerName(SpawnerName::gf_C) }, - { SpawnLOTS::admiral_cp, 2, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::concert_C) }, - } - }, + // Wave 26 + Wave { + std::vector { + { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::ronin, 3, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::gf_B) }, + { SpawnLOTS::spiderling_ve, 1, GetSpawnerName(SpawnerName::concert_B) }, + { SpawnLOTS::admiral_cp, 2, GetSpawnerName(SpawnerName::gf_C) }, + { SpawnLOTS::admiral_cp, 2, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::concert_C) }, + } + }, - // Wave 27 - Wave { - std::vector { - { SpawnLOTS::ronin, 5, GetSpawnerName(SpawnerName::interior_A) }, - { SpawnLOTS::ronin, 4, GetSpawnerName(SpawnerName::interior_B) }, - { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::ag_C) }, - { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::gf_C) }, - { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::concert_C) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::ag_B) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::gf_B) }, - { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::concert_B) }, - } - }, + // Wave 27 + Wave { + std::vector { + { SpawnLOTS::ronin, 5, GetSpawnerName(SpawnerName::interior_A) }, + { SpawnLOTS::ronin, 4, GetSpawnerName(SpawnerName::interior_B) }, + { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::ag_C) }, + { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::gf_C) }, + { SpawnLOTS::cavalry, 1, GetSpawnerName(SpawnerName::concert_C) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::ag_B) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::gf_B) }, + { SpawnLOTS::admiral_cp, 1, GetSpawnerName(SpawnerName::concert_B) }, + } + }, - // Wave 28 - Wave { - std::vector { - { SpawnLOTS::dragon_statue, 12, GetSpawnerName(SpawnerName::Reward_01) }, - }, {}, {}, "", -1.0f, - 30, - }, + // Wave 28 + Wave { + std::vector { + { SpawnLOTS::dragon_statue, 12, GetSpawnerName(SpawnerName::Reward_01) }, + }, {}, {}, "", -1.0f, + 30, + }, - // Wave 29 - Wave { - std::vector { - { SpawnLOTS::horseman_boss01, 1, GetSpawnerName(SpawnerName::Horseman_01) }, - { SpawnLOTS::horseman_boss02, 1, GetSpawnerName(SpawnerName::Horseman_02) }, - { SpawnLOTS::horseman_boss03, 1, GetSpawnerName(SpawnerName::Horseman_03) }, - { SpawnLOTS::horseman_boss04, 1, GetSpawnerName(SpawnerName::Horseman_04) }, - }, - {1888}, - {1236, 1237, 1249}, - "Horsemen_Boss", - 5.0f - }, + // Wave 29 + Wave { + std::vector { + { SpawnLOTS::horseman_boss01, 1, GetSpawnerName(SpawnerName::Horseman_01) }, + { SpawnLOTS::horseman_boss02, 1, GetSpawnerName(SpawnerName::Horseman_02) }, + { SpawnLOTS::horseman_boss03, 1, GetSpawnerName(SpawnerName::Horseman_03) }, + { SpawnLOTS::horseman_boss04, 1, GetSpawnerName(SpawnerName::Horseman_04) }, + }, + {1888}, + {1236, 1237, 1249}, + "Horsemen_Boss", + 5.0f + }, - // Wave 30 (treasure) - Wave { - std::vector { - { SpawnLOTS::treasure_chest, 1, GetSpawnerName(SpawnerName::Treasure_01) }, - }, {}, {}, - "Treasure_Camera", - 5.0f, - (uint32_t) -1, - true, - 30, - }, - }; + // Wave 30 (treasure) + Wave { + std::vector { + { SpawnLOTS::treasure_chest, 1, GetSpawnerName(SpawnerName::Treasure_01) }, + }, {}, {}, + "Treasure_Camera", + 5.0f, + (uint32_t)-1, + true, + 30, + }, + }; } std::string ZoneNsWaves::GetSpawnerName(SpawnerName spawnerName) { - switch (spawnerName) { - case interior_A: - return "Base_MobA"; - case interior_B: - return "Base_MobB"; - case interior_C: - return "Base_MobC"; - case gf_A: - return "MobA_01"; - case gf_B: - return "MobB_01"; - case gf_C: - return "MobC_01"; - case concert_A: - return "MobA_02"; - case concert_B: - return "MobB_02"; - case concert_C: - return "MobC_02"; - case ag_A: - return "MobA_03"; - case ag_B: - return "MobB_03"; - case ag_C: - return "MobC_03"; - case Reward_01: - return "Reward_01"; - case interior_Reward: - return "Base_Reward"; - case Obstacle: - return "Obstacle_01"; - case Boss: - return "Boss"; - case Ape_Boss: - return "Ape_Boss"; - case Geyser: - return "Geyser_01"; - case Treasure_01: - return "Treasure_01"; - case Cavalry_Boss: - return "Cavalry_Boss"; - case Horseman_01: - return "Horseman_01"; - case Horseman_02: - return "Horseman_02"; - case Horseman_03: - return "Horseman_03"; - case Horseman_04: - return "Horseman_04"; - default: - return ""; - } + switch (spawnerName) { + case interior_A: + return "Base_MobA"; + case interior_B: + return "Base_MobB"; + case interior_C: + return "Base_MobC"; + case gf_A: + return "MobA_01"; + case gf_B: + return "MobB_01"; + case gf_C: + return "MobC_01"; + case concert_A: + return "MobA_02"; + case concert_B: + return "MobB_02"; + case concert_C: + return "MobC_02"; + case ag_A: + return "MobA_03"; + case ag_B: + return "MobB_03"; + case ag_C: + return "MobC_03"; + case Reward_01: + return "Reward_01"; + case interior_Reward: + return "Base_Reward"; + case Obstacle: + return "Obstacle_01"; + case Boss: + return "Boss"; + case Ape_Boss: + return "Ape_Boss"; + case Geyser: + return "Geyser_01"; + case Treasure_01: + return "Treasure_01"; + case Cavalry_Boss: + return "Cavalry_Boss"; + case Horseman_01: + return "Horseman_01"; + case Horseman_02: + return "Horseman_02"; + case Horseman_03: + return "Horseman_03"; + case Horseman_04: + return "Horseman_04"; + default: + return ""; + } } diff --git a/dScripts/ZoneNsWaves.h b/dScripts/ZoneNsWaves.h index c1a63db6..06503d19 100644 --- a/dScripts/ZoneNsWaves.h +++ b/dScripts/ZoneNsWaves.h @@ -2,68 +2,68 @@ #include "BaseWavesServer.h" enum SpawnerName { - interior_A, - interior_B, - interior_C, - gf_A, - gf_B, - gf_C, - concert_A, - concert_B, - concert_C, - ag_A, - ag_B, - ag_C, - Reward_01, - interior_Reward, - Obstacle, - Boss, - Ape_Boss, - Geyser, - Treasure_01, - Cavalry_Boss, - Horseman_01, - Horseman_02, - Horseman_03, - Horseman_04, + interior_A, + interior_B, + interior_C, + gf_A, + gf_B, + gf_C, + concert_A, + concert_B, + concert_C, + ag_A, + ag_B, + ag_C, + Reward_01, + interior_Reward, + Obstacle, + Boss, + Ape_Boss, + Geyser, + Treasure_01, + Cavalry_Boss, + Horseman_01, + Horseman_02, + Horseman_03, + Horseman_04, }; enum SpawnLOTS : LOT { - stromling = 12586, - mech = 12587, - spiderling = 12588, - pirate = 12589, - admiral = 12590, - ape_boss = 12591, - stromling_boss = 12600, - hammerling = 12602, - sentry = 12604, - spiderling_ve = 12605, - spiderling_boss = 12609, - ronin = 12610, - cavalry = 12611, - dragon_boss = 12612, - stromling_minifig = 12586, - mushroom = 12614, - maelstrom_chest = 4894, - outhouse = 12616, - dragon_statue = 12617, - treasure_chest = 12423, - hammerling_melee = 12653, - maelstrom_geyser = 10314, - ronin_statue = 12611, - horseman_boss01 = 11999, - horseman_boss02 = 12467, - horseman_boss03 = 12468, - horseman_boss04 = 12469, - admiral_cp = 13523, + stromling = 12586, + mech = 12587, + spiderling = 12588, + pirate = 12589, + admiral = 12590, + ape_boss = 12591, + stromling_boss = 12600, + hammerling = 12602, + sentry = 12604, + spiderling_ve = 12605, + spiderling_boss = 12609, + ronin = 12610, + cavalry = 12611, + dragon_boss = 12612, + stromling_minifig = 12586, + mushroom = 12614, + maelstrom_chest = 4894, + outhouse = 12616, + dragon_statue = 12617, + treasure_chest = 12423, + hammerling_melee = 12653, + maelstrom_geyser = 10314, + ronin_statue = 12611, + horseman_boss01 = 11999, + horseman_boss02 = 12467, + horseman_boss03 = 12468, + horseman_boss04 = 12469, + admiral_cp = 13523, }; class ZoneNsWaves : public BaseWavesServer { - WaveConstants GetConstants() override; - std::vector GetSpawnerNames() override; - std::vector GetWaveMissions() override; - std::vector GetWaves() override; + WaveConstants GetConstants() override; + std::vector GetSpawnerNames() override; + std::vector GetWaveMissions() override; + std::vector GetWaves() override; private: - static std::string GetSpawnerName(SpawnerName spawnerName); + static std::string GetSpawnerName(SpawnerName spawnerName); }; diff --git a/dScripts/ZoneSGServer.cpp b/dScripts/ZoneSGServer.cpp index 8149ec55..6822abda 100644 --- a/dScripts/ZoneSGServer.cpp +++ b/dScripts/ZoneSGServer.cpp @@ -1,26 +1,26 @@ #include "ZoneSGServer.h" #include "EntityManager.h" -void ZoneSGServer::OnStartup(Entity *self) { - const auto cannons = EntityManager::Instance()->GetEntitiesByLOT(1864); - for (const auto& cannon : cannons) - self->SetVar(CannonIDVariable, cannon->GetObjectID()); +void ZoneSGServer::OnStartup(Entity* self) { + const auto cannons = EntityManager::Instance()->GetEntitiesByLOT(1864); + for (const auto& cannon : cannons) + self->SetVar(CannonIDVariable, cannon->GetObjectID()); } -void ZoneSGServer::OnActivityStateChangeRequest(Entity *self, const LWOOBJID senderID, const int32_t value1, - const int32_t value2, const std::u16string &stringValue) { +void ZoneSGServer::OnActivityStateChangeRequest(Entity* self, const LWOOBJID senderID, const int32_t value1, + const int32_t value2, const std::u16string& stringValue) { - auto* cannon = EntityManager::Instance()->GetEntity(self->GetVar(CannonIDVariable)); - if (cannon != nullptr) { - cannon->OnActivityStateChangeRequest(senderID, value1, value2, stringValue); - } + auto* cannon = EntityManager::Instance()->GetEntity(self->GetVar(CannonIDVariable)); + if (cannon != nullptr) { + cannon->OnActivityStateChangeRequest(senderID, value1, value2, stringValue); + } } -void ZoneSGServer::OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) { +void ZoneSGServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) { - auto* cannon = EntityManager::Instance()->GetEntity(self->GetVar(CannonIDVariable)); - if (cannon != nullptr) { - cannon->OnFireEventServerSide(sender, args, param1, param2, param3); - } + auto* cannon = EntityManager::Instance()->GetEntity(self->GetVar(CannonIDVariable)); + if (cannon != nullptr) { + cannon->OnFireEventServerSide(sender, args, param1, param2, param3); + } } diff --git a/dScripts/ZoneSGServer.h b/dScripts/ZoneSGServer.h index 4198157f..eaa7c909 100644 --- a/dScripts/ZoneSGServer.h +++ b/dScripts/ZoneSGServer.h @@ -3,11 +3,11 @@ class ZoneSGServer : public CppScripts::Script { public: - void OnStartup(Entity *self) override; - void OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, - int32_t value2, const std::u16string& stringValue) override; - void OnFireEventServerSide(Entity *self, Entity *sender, std::string args, int32_t param1, int32_t param2, - int32_t param3) override; + void OnStartup(Entity* self) override; + void OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int32_t value1, + int32_t value2, const std::u16string& stringValue) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, + int32_t param3) override; private: - std::u16string CannonIDVariable = u"CannonID"; + std::u16string CannonIDVariable = u"CannonID"; }; diff --git a/dWorldServer/ObjectIDManager.cpp b/dWorldServer/ObjectIDManager.cpp index bf8f770f..ef5fb9a5 100644 --- a/dWorldServer/ObjectIDManager.cpp +++ b/dWorldServer/ObjectIDManager.cpp @@ -10,54 +10,53 @@ #include "Game.h" // Static Variables -ObjectIDManager * ObjectIDManager::m_Address = nullptr; +ObjectIDManager* ObjectIDManager::m_Address = nullptr; static std::uniform_int_distribution uni(10000000, INT32_MAX); //! Initializes the manager void ObjectIDManager::Initialize(void) { - //this->currentRequestID = 0; - this->currentObjectID = uint32_t(1152921508165007067); //Initial value for this server's objectIDs + //this->currentRequestID = 0; + this->currentObjectID = uint32_t(1152921508165007067); //Initial value for this server's objectIDs } //! Requests a persistent ID void ObjectIDManager::RequestPersistentID(std::function callback) { - PersistentIDRequest * request = new PersistentIDRequest(); - request->requestID = ++this->currentRequestID; - request->callback = callback; + PersistentIDRequest* request = new PersistentIDRequest(); + request->requestID = ++this->currentRequestID; + request->callback = callback; - this->requests.push_back(request); + this->requests.push_back(request); - MasterPackets::SendPersistentIDRequest(Game::server, request->requestID); + MasterPackets::SendPersistentIDRequest(Game::server, request->requestID); } //! Handles a persistent ID response void ObjectIDManager::HandleRequestPersistentIDResponse(uint64_t requestID, uint32_t persistentID) { - for (uint32_t i = 0; i < this->requests.size(); ++i) { - if (this->requests[i]->requestID == requestID) { + for (uint32_t i = 0; i < this->requests.size(); ++i) { + if (this->requests[i]->requestID == requestID) { - // Call the callback function - this->requests[i]->callback(persistentID); + // Call the callback function + this->requests[i]->callback(persistentID); - // Then delete the request - delete this->requests[i]; - this->requests.erase(this->requests.begin() + i); - return; - } - } + // Then delete the request + delete this->requests[i]; + this->requests.erase(this->requests.begin() + i); + return; + } + } } //! Handles cases where we have to get a unique object ID synchronously -uint32_t ObjectIDManager::GenerateRandomObjectID() -{ - std::random_device rd; - - std::mt19937 rng(rd()); +uint32_t ObjectIDManager::GenerateRandomObjectID() { + std::random_device rd; - return uni(rng); + std::mt19937 rng(rd()); + + return uni(rng); } //! Generates an object ID server-sided (used for regular entities like smashables) uint32_t ObjectIDManager::GenerateObjectID(void) { - return ++this->currentObjectID; + return ++this->currentObjectID; } diff --git a/dWorldServer/ObjectIDManager.h b/dWorldServer/ObjectIDManager.h index 7bfc1d27..deef89fd 100644 --- a/dWorldServer/ObjectIDManager.h +++ b/dWorldServer/ObjectIDManager.h @@ -10,66 +10,66 @@ \brief A manager for handling object ID generation */ -//! The persistent ID request + //! The persistent ID request struct PersistentIDRequest { - uint64_t requestID; + uint64_t requestID; - std::function callback; + std::function callback; }; //! The Object ID Manager class ObjectIDManager { private: - static ObjectIDManager * m_Address; //!< The singleton instance + static ObjectIDManager* m_Address; //!< The singleton instance - std::vector requests; //!< All outstanding persistent ID requests - uint64_t currentRequestID; //!< The current request ID + std::vector requests; //!< All outstanding persistent ID requests + uint64_t currentRequestID; //!< The current request ID - uint32_t currentObjectID; //!< The current object ID + uint32_t currentObjectID; //!< The current object ID public: - //! The singleton instance - static ObjectIDManager * Instance() { - if (m_Address == 0) { - m_Address = new ObjectIDManager; - } + //! The singleton instance + static ObjectIDManager* Instance() { + if (m_Address == 0) { + m_Address = new ObjectIDManager; + } - return m_Address; - } + return m_Address; + } - //! Initializes the manager - void Initialize(void); + //! Initializes the manager + void Initialize(void); - //! Requests a persistent ID - /*! - \param callback The callback function - */ - void RequestPersistentID(std::function callback); + //! Requests a persistent ID + /*! + \param callback The callback function + */ + void RequestPersistentID(std::function callback); - //! Handles a persistent ID response - /*! - \param requestID The request ID - \param persistentID The persistent ID - */ - void HandleRequestPersistentIDResponse(uint64_t requestID, uint32_t persistentID); + //! Handles a persistent ID response + /*! + \param requestID The request ID + \param persistentID The persistent ID + */ + void HandleRequestPersistentIDResponse(uint64_t requestID, uint32_t persistentID); - //! Generates an object ID server-sided - /*! - \return A generated object ID - */ - uint32_t GenerateObjectID(void); + //! Generates an object ID server-sided + /*! + \return A generated object ID + */ + uint32_t GenerateObjectID(void); //! Generates a random object ID server-sided /*! \return A generated object ID */ - static uint32_t GenerateRandomObjectID(); + static uint32_t GenerateRandomObjectID(); - //! Generates a persistent object ID server-sided - /*! - \return A generated object ID - */ - uint32_t GeneratePersistentObjectID(void); + //! Generates a persistent object ID server-sided + /*! + \return A generated object ID + */ + uint32_t GeneratePersistentObjectID(void); }; diff --git a/dWorldServer/PerformanceManager.cpp b/dWorldServer/PerformanceManager.cpp index 6809fec0..85546f28 100644 --- a/dWorldServer/PerformanceManager.cpp +++ b/dWorldServer/PerformanceManager.cpp @@ -97,4 +97,4 @@ uint32_t PerformanceManager::GetServerFramerate() { } return m_CurrentProfile.serverFramerate; -} \ No newline at end of file +} diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 6d85b2cd..df5484fd 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -103,8 +103,8 @@ int main(int argc, char** argv) { // Triggers the shutdown sequence at application exit std::atexit(WorldShutdownSequence); - signal(SIGINT, [](int){ WorldShutdownSequence(); }); - signal(SIGTERM, [](int){ WorldShutdownSequence(); }); + signal(SIGINT, [](int) { WorldShutdownSequence(); }); + signal(SIGTERM, [](int) { WorldShutdownSequence(); }); int zoneID = 1000; int cloneID = 0; @@ -143,14 +143,14 @@ int main(int argc, char** argv) { if (config.GetValue("disable_chat") == "1") chatDisabled = true; // Connect to CDClient - try { - CDClientDatabase::Connect("./res/CDServer.sqlite"); - } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); - Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); - return -1; - } + try { + CDClientDatabase::Connect("./res/CDServer.sqlite"); + } catch (CppSQLite3Exception& e) { + Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); + Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); + return -1; + } CDClientManager::Instance()->Initialize(); @@ -162,17 +162,16 @@ int main(int argc, char** argv) { Diagnostics::SetProduceMemoryDump(config.GetValue("generate_dump") == "1"); - if (!config.GetValue("dump_folder").empty()) - { + if (!config.GetValue("dump_folder").empty()) { Diagnostics::SetOutDirectory(config.GetValue("dump_folder")); } try { - Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); - } catch (sql::SQLException& ex) { + Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); + } catch (sql::SQLException& ex) { Game::logger->Log("WorldServer", "Got an error while connecting to the database: %s", ex.what()); return 0; - } + } //Find out the master's IP: std::string masterIP = "localhost"; @@ -241,44 +240,44 @@ int main(int argc, char** argv) { // pre calculate the FDB checksum if (Game::config->GetValue("check_fdb") == "1") { - std::ifstream fileStream; + std::ifstream fileStream; - static const std::vector aliases = { - "res/CDServers.fdb", - "res/cdserver.fdb", - "res/CDClient.fdb", - "res/cdclient.fdb", - }; + static const std::vector aliases = { + "res/CDServers.fdb", + "res/cdserver.fdb", + "res/CDClient.fdb", + "res/cdclient.fdb", + }; - for (const auto& file : aliases) { - fileStream.open(file, std::ios::binary | std::ios::in); - if (fileStream.is_open()) { - break; - } + for (const auto& file : aliases) { + fileStream.open(file, std::ios::binary | std::ios::in); + if (fileStream.is_open()) { + break; } - - const int bufferSize = 1024; - MD5* md5 = new MD5(); - - char fileStreamBuffer[1024] = {}; - - while (!fileStream.eof()) { - memset(fileStreamBuffer, 0, bufferSize); - fileStream.read(fileStreamBuffer, bufferSize); - md5->update(fileStreamBuffer, fileStream.gcount()); - } - - fileStream.close(); - - const char* nullTerminateBuffer = "\0"; - md5->update(nullTerminateBuffer, 1); // null terminate the data - md5->finalize(); - databaseChecksum = md5->hexdigest(); - - delete md5; - - Game::logger->Log("WorldServer", "FDB Checksum calculated as: %s", databaseChecksum.c_str()); } + + const int bufferSize = 1024; + MD5* md5 = new MD5(); + + char fileStreamBuffer[1024] = {}; + + while (!fileStream.eof()) { + memset(fileStreamBuffer, 0, bufferSize); + fileStream.read(fileStreamBuffer, bufferSize); + md5->update(fileStreamBuffer, fileStream.gcount()); + } + + fileStream.close(); + + const char* nullTerminateBuffer = "\0"; + md5->update(nullTerminateBuffer, 1); // null terminate the data + md5->finalize(); + databaseChecksum = md5->hexdigest(); + + delete md5; + + Game::logger->Log("WorldServer", "FDB Checksum calculated as: %s", databaseChecksum.c_str()); + } } while (true) { @@ -293,12 +292,9 @@ int main(int argc, char** argv) { const auto occupied = UserManager::Instance()->GetUserCount() != 0; - if (!ready) - { + if (!ready) { currentFramerate = highFrameRate; - } - else - { + } else { currentFramerate = PerformanceManager::GetServerFramerate(); } @@ -316,8 +312,7 @@ int main(int argc, char** argv) { Game::logger->Log("WorldServer", "Game loop running but no connection to master for %d frames, shutting down", framesToWaitForMaster); worldShutdownSequenceStarted = true; } - } - else framesSinceMasterDisconnect = 0; + } else framesSinceMasterDisconnect = 0; // Check if we're still connected to chat: if (!chatConnected) { @@ -329,8 +324,7 @@ int main(int argc, char** argv) { Game::chatServer->Connect(masterIP.c_str(), chatPort, "3.25 ND1", 8); } - } - else framesSinceChatDisconnect = 0; + } else framesSinceChatDisconnect = 0; //In world we'd update our other systems here. @@ -387,8 +381,7 @@ int main(int argc, char** argv) { timeSpent += std::chrono::duration_cast(t2 - t1).count(); Game::server->DeallocatePacket(packet); packet = nullptr; - } - else { + } else { break; } } @@ -408,18 +401,14 @@ int main(int argc, char** argv) { framesSinceLastFlush = 0; } else framesSinceLastFlush++; - if (zoneID != 0 && !occupied) - { + if (zoneID != 0 && !occupied) { framesSinceLastUser++; //If we haven't had any players for a while, time out and shut down: - if (framesSinceLastUser == (cloneID != 0 ? 4000 : 40000)) - { + if (framesSinceLastUser == (cloneID != 0 ? 4000 : 40000)) { worldShutdownSequenceStarted = true; } - } - else - { + } else { framesSinceLastUser = 0; } @@ -431,8 +420,7 @@ int main(int argc, char** argv) { if (PropertyManagementComponent::Instance() != nullptr) { PropertyManagementComponent::Instance()->Save(); } - } - else framesSinceLastUsersSave++; + } else framesSinceLastUsersSave++; //Every 10 min we ping our sql server to keep it alive hopefully: if (framesSinceLastSQLPing >= 40000) { @@ -450,8 +438,7 @@ int main(int argc, char** argv) { delete stmt; framesSinceLastSQLPing = 0; - } - else framesSinceLastSQLPing++; + } else framesSinceLastSQLPing++; Metrics::EndMeasurement(MetricVariable::GameLoop); @@ -462,14 +449,12 @@ int main(int argc, char** argv) { Metrics::EndMeasurement(MetricVariable::Sleep); - if (!ready && Game::server->GetIsConnectedToMaster()) - { + if (!ready && Game::server->GetIsConnectedToMaster()) { // Some delay is required here or else we crash the client? framesSinceMasterStatus++; - if (framesSinceMasterStatus >= 200) - { + if (framesSinceMasterStatus >= 200) { Game::logger->Log("WorldServer", "Finished loading world with zone (%i), ready up!", Game::server->GetZoneID()); MasterPackets::SendWorldReady(Game::server, Game::server->GetZoneID(), Game::server->GetInstanceID()); @@ -490,7 +475,7 @@ int main(int argc, char** argv) { return EXIT_SUCCESS; } -dLogger * SetupLogger(int zoneID, int instanceID) { +dLogger* SetupLogger(int zoneID, int instanceID) { std::string logPath = "./logs/WorldServer_" + std::to_string(zoneID) + "_" + std::to_string(instanceID) + "_" + std::to_string(time(nullptr)) + ".log"; bool logToConsole = false; bool logDebugStatements = false; @@ -504,13 +489,13 @@ dLogger * SetupLogger(int zoneID, int instanceID) { void HandlePacketChat(Packet* packet) { if (packet->data[0] == ID_DISCONNECTION_NOTIFICATION || packet->data[0] == ID_CONNECTION_LOST) { - Game::logger->Log("WorldServer", "Lost our connection to chat, zone(%i), instance(%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); + Game::logger->Log("WorldServer", "Lost our connection to chat, zone(%i), instance(%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); chatConnected = false; } if (packet->data[0] == ID_CONNECTION_REQUEST_ACCEPTED) { - Game::logger->Log("WorldServer", "Established connection to chat, zone(%i), instance (%i)",Game::server -> GetZoneID(), Game::server -> GetInstanceID()); + Game::logger->Log("WorldServer", "Established connection to chat, zone(%i), instance (%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); Game::chatSysAddr = packet->systemAddress; chatConnected = true; @@ -590,8 +575,7 @@ void HandlePacketChat(Packet* packet) { auto* entity = EntityManager::Instance()->GetEntity(playerId); - if (entity != nullptr) - { + if (entity != nullptr) { entity->GetParentUser()->SetMuteExpire(expire); entity->GetCharacter()->SendMuteNotice(); @@ -613,8 +597,7 @@ void HandlePacketChat(Packet* packet) { inStream.Read(teamID); bool deleteTeam = inStream.ReadBit(); - if (deleteTeam) - { + if (deleteTeam) { TeamManager::Instance()->DeleteTeam(teamID); Game::logger->Log("WorldServer", "Deleting team (%llu)", teamID); @@ -625,8 +608,7 @@ void HandlePacketChat(Packet* packet) { inStream.Read(lootOption); inStream.Read(memberCount); Game::logger->Log("WorldServer", "Updating team (%llu), (%i), (%i)", teamID, lootOption, memberCount); - for (char i = 0; i < memberCount; i++) - { + for (char i = 0; i < memberCount; i++) { LWOOBJID member = LWOOBJID_EMPTY; inStream.Read(member); members.push_back(member); @@ -659,16 +641,14 @@ void HandlePacket(Packet* packet) { auto* entity = EntityManager::Instance()->GetEntity(c->GetObjectID()); - if (!entity) - { + if (!entity) { entity = Player::GetPlayer(packet->systemAddress); } if (entity) { auto* skillComponent = entity->GetComponent(); - if (skillComponent != nullptr) - { + if (skillComponent != nullptr) { skillComponent->Reset(); } @@ -708,139 +688,138 @@ void HandlePacket(Packet* packet) { if (packet->data[1] == MASTER) { switch (packet->data[3]) { - case MSG_MASTER_REQUEST_PERSISTENT_ID_RESPONSE: { - uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); - uint32_t objectID = PacketUtils::ReadPacketU32(16, packet); - ObjectIDManager::Instance()->HandleRequestPersistentIDResponse(requestID, objectID); - break; - } + case MSG_MASTER_REQUEST_PERSISTENT_ID_RESPONSE: { + uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); + uint32_t objectID = PacketUtils::ReadPacketU32(16, packet); + ObjectIDManager::Instance()->HandleRequestPersistentIDResponse(requestID, objectID); + break; + } - case MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE: { - uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); - ZoneInstanceManager::Instance()->HandleRequestZoneTransferResponse(requestID, packet); - break; - } + case MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE: { + uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); + ZoneInstanceManager::Instance()->HandleRequestZoneTransferResponse(requestID, packet); + break; + } - case MSG_MASTER_SESSION_KEY_RESPONSE: { - //Read our session key and to which user it belongs: - RakNet::BitStream inStream(packet->data, packet->length, false); - uint64_t header = inStream.Read(header); - uint32_t sessionKey = 0; - std::string username; + case MSG_MASTER_SESSION_KEY_RESPONSE: { + //Read our session key and to which user it belongs: + RakNet::BitStream inStream(packet->data, packet->length, false); + uint64_t header = inStream.Read(header); + uint32_t sessionKey = 0; + std::string username; - inStream.Read(sessionKey); - username = PacketUtils::ReadString(12, packet, false); + inStream.Read(sessionKey); + username = PacketUtils::ReadString(12, packet, false); - //Find them: - auto it = m_PendingUsers.find(username); - if (it == m_PendingUsers.end()) return; + //Find them: + auto it = m_PendingUsers.find(username); + if (it == m_PendingUsers.end()) return; - //Convert our key: - std::string userHash = std::to_string(sessionKey); - userHash = md5(userHash); + //Convert our key: + std::string userHash = std::to_string(sessionKey); + userHash = md5(userHash); - //Verify it: - if (userHash != it->second.hash) { - Game::logger->Log("WorldServer", "SOMEONE IS TRYING TO HACK? SESSION KEY MISMATCH: ours: %s != master: %s", userHash.c_str(), it->second.hash.c_str()); - Game::server->Disconnect(it->second.sysAddr, SERVER_DISCON_INVALID_SESSION_KEY); - return; - } - else { - Game::logger->Log("WorldServer", "User %s authenticated with correct key.", username.c_str()); + //Verify it: + if (userHash != it->second.hash) { + Game::logger->Log("WorldServer", "SOMEONE IS TRYING TO HACK? SESSION KEY MISMATCH: ours: %s != master: %s", userHash.c_str(), it->second.hash.c_str()); + Game::server->Disconnect(it->second.sysAddr, SERVER_DISCON_INVALID_SESSION_KEY); + return; + } else { + Game::logger->Log("WorldServer", "User %s authenticated with correct key.", username.c_str()); - UserManager::Instance()->DeleteUser(packet->systemAddress); + UserManager::Instance()->DeleteUser(packet->systemAddress); - //Create our user and send them in: - UserManager::Instance()->CreateUser(it->second.sysAddr, username, userHash); + //Create our user and send them in: + UserManager::Instance()->CreateUser(it->second.sysAddr, username, userHash); - auto zone = dZoneManager::Instance()->GetZone(); - if (zone) { - float x = 0.0f; - float y = 0.0f; - float z = 0.0f; + auto zone = dZoneManager::Instance()->GetZone(); + if (zone) { + float x = 0.0f; + float y = 0.0f; + float z = 0.0f; - if (zone->GetZoneID().GetMapID() == 1100) { - auto pos = zone->GetSpawnPos(); - x = pos.x; - y = pos.y; - z = pos.z; - } - - WorldPackets::SendLoadStaticZone(it->second.sysAddr, x, y, z, zone->GetChecksum()); + if (zone->GetZoneID().GetMapID() == 1100) { + auto pos = zone->GetSpawnPos(); + x = pos.x; + y = pos.y; + z = pos.z; } - if (Game::server->GetZoneID() == 0) { - //Since doing this reroute breaks the client's request, we have to call this manually. - UserManager::Instance()->RequestCharacterList(it->second.sysAddr); - } - - m_PendingUsers.erase(username); - - //Notify master: - { - CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_PLAYER_ADDED); - bitStream.Write((LWOMAPID)Game::server->GetZoneID()); - bitStream.Write((LWOINSTANCEID)instanceID); - Game::server->SendToMaster(&bitStream); - } + WorldPackets::SendLoadStaticZone(it->second.sysAddr, x, y, z, zone->GetChecksum()); } - break; + if (Game::server->GetZoneID() == 0) { + //Since doing this reroute breaks the client's request, we have to call this manually. + UserManager::Instance()->RequestCharacterList(it->second.sysAddr); + } + + m_PendingUsers.erase(username); + + //Notify master: + { + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_PLAYER_ADDED); + bitStream.Write((LWOMAPID)Game::server->GetZoneID()); + bitStream.Write((LWOINSTANCEID)instanceID); + Game::server->SendToMaster(&bitStream); + } } - case MSG_MASTER_AFFIRM_TRANSFER_REQUEST: { - const uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); - Game::logger->Log("MasterServer", "Got affirmation request of transfer %llu", requestID); + break; + } + case MSG_MASTER_AFFIRM_TRANSFER_REQUEST: { + const uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); - CBITSTREAM + Game::logger->Log("MasterServer", "Got affirmation request of transfer %llu", requestID); + + CBITSTREAM PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_AFFIRM_TRANSFER_RESPONSE); - bitStream.Write(requestID); - Game::server->SendToMaster(&bitStream); + bitStream.Write(requestID); + Game::server->SendToMaster(&bitStream); - break; + break; + } + + case MSG_MASTER_SHUTDOWN: { + worldShutdownSequenceStarted = true; + Game::logger->Log("WorldServer", "Got shutdown request from master, zone (%i), instance (%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); + break; + } + + case MSG_MASTER_NEW_SESSION_ALERT: { + RakNet::BitStream inStream(packet->data, packet->length, false); + uint64_t header = inStream.Read(header); + uint32_t sessionKey = inStream.Read(sessionKey); + + std::string username; + + uint32_t len; + inStream.Read(len); + + for (int i = 0; i < len; i++) { + char character; inStream.Read(character); + username += character; } - case MSG_MASTER_SHUTDOWN: { - worldShutdownSequenceStarted = true; - Game::logger->Log("WorldServer", "Got shutdown request from master, zone (%i), instance (%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); - break; + //Find them: + User* user = UserManager::Instance()->GetUser(username.c_str()); + if (!user) { + Game::logger->Log("WorldServer", "Got new session alert for user %s, but they're not logged in.", username.c_str()); + return; } - case MSG_MASTER_NEW_SESSION_ALERT: { - RakNet::BitStream inStream(packet->data, packet->length, false); - uint64_t header = inStream.Read(header); - uint32_t sessionKey = inStream.Read(sessionKey); - - std::string username; - - uint32_t len; - inStream.Read(len); - - for (int i = 0; i < len; i++) { - char character; inStream.Read(character); - username += character; - } - - //Find them: - User* user = UserManager::Instance()->GetUser(username.c_str()); - if (!user) { - Game::logger->Log("WorldServer", "Got new session alert for user %s, but they're not logged in.", username.c_str()); - return; - } - - //Check the key: - if (sessionKey != std::atoi(user->GetSessionKey().c_str())) { - Game::logger->Log("WorldServer", "Got new session alert for user %s, but the session key is invalid.", username.c_str()); - Game::server->Disconnect(user->GetSystemAddress(), SERVER_DISCON_INVALID_SESSION_KEY); - return; - } - break; + //Check the key: + if (sessionKey != std::atoi(user->GetSessionKey().c_str())) { + Game::logger->Log("WorldServer", "Got new session alert for user %s, but the session key is invalid.", username.c_str()); + Game::server->Disconnect(user->GetSystemAddress(), SERVER_DISCON_INVALID_SESSION_KEY); + return; } + break; + } - default: - Game::logger->Log("WorldServer", "Unknown packet ID from master %i", int(packet->data[3])); + default: + Game::logger->Log("WorldServer", "Unknown packet ID from master %i", int(packet->data[3])); } return; @@ -849,403 +828,397 @@ void HandlePacket(Packet* packet) { if (packet->data[1] != WORLD) return; switch (packet->data[3]) { - case MSG_WORLD_CLIENT_VALIDATION: { - std::string username = PacketUtils::ReadString(0x08, packet, true); - std::string sessionKey = PacketUtils::ReadString(74, packet, true); - std::string clientDatabaseChecksum = PacketUtils::ReadString(packet->length - 33, packet, false); + case MSG_WORLD_CLIENT_VALIDATION: { + std::string username = PacketUtils::ReadString(0x08, packet, true); + std::string sessionKey = PacketUtils::ReadString(74, packet, true); + std::string clientDatabaseChecksum = PacketUtils::ReadString(packet->length - 33, packet, false); - // sometimes client puts a null terminator at the end of the checksum and sometimes doesn't, weird - clientDatabaseChecksum = clientDatabaseChecksum.substr(0, 32); + // sometimes client puts a null terminator at the end of the checksum and sometimes doesn't, weird + clientDatabaseChecksum = clientDatabaseChecksum.substr(0, 32); - // If the check is turned on, validate the client's database checksum. - if (Game::config->GetValue("check_fdb") == "1" && !databaseChecksum.empty()) { - uint32_t gmLevel = 0; - auto* stmt = Database::CreatePreppedStmt("SELECT gm_level FROM accounts WHERE name=? LIMIT 1;"); - stmt->setString(1, username.c_str()); + // If the check is turned on, validate the client's database checksum. + if (Game::config->GetValue("check_fdb") == "1" && !databaseChecksum.empty()) { + uint32_t gmLevel = 0; + auto* stmt = Database::CreatePreppedStmt("SELECT gm_level FROM accounts WHERE name=? LIMIT 1;"); + stmt->setString(1, username.c_str()); - auto* res = stmt->executeQuery(); - while (res->next()) { - gmLevel = res->getInt(1); - } + auto* res = stmt->executeQuery(); + while (res->next()) { + gmLevel = res->getInt(1); + } - delete stmt; - delete res; + delete stmt; + delete res; - // Developers may skip this check - if (gmLevel < 8 && clientDatabaseChecksum != databaseChecksum) { - Game::logger->Log("WorldServer", "Client's database checksum does not match the server's, aborting connection."); - Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_KICK); + // Developers may skip this check + if (gmLevel < 8 && clientDatabaseChecksum != databaseChecksum) { + Game::logger->Log("WorldServer", "Client's database checksum does not match the server's, aborting connection."); + Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_KICK); + return; + } + } + + //Request the session info from Master: + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_SESSION_KEY); + PacketUtils::WriteString(bitStream, username, 64); + Game::server->SendToMaster(&bitStream); + + //Insert info into our pending list + tempSessionInfo info; + info.sysAddr = SystemAddress(packet->systemAddress); + info.hash = sessionKey; + m_PendingUsers.insert(std::make_pair(username, info)); + + break; + } + + case MSG_WORLD_CLIENT_CHARACTER_LIST_REQUEST: { + //We need to delete the entity first, otherwise the char list could delete it while it exists in the world! + if (Game::server->GetZoneID() != 0) { + auto user = UserManager::Instance()->GetUser(packet->systemAddress); + if (!user) return; + EntityManager::Instance()->DestroyEntity(user->GetLastUsedChar()->GetEntity()); + } + + //This loops prevents users who aren't authenticated to double-request the char list, which + //would make the login screen freeze sometimes. + if (m_PendingUsers.size() > 0) { + for (auto it : m_PendingUsers) { + if (it.second.sysAddr == packet->systemAddress) { return; } } - - //Request the session info from Master: - CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_SESSION_KEY); - PacketUtils::WriteString(bitStream, username, 64); - Game::server->SendToMaster(&bitStream); - - //Insert info into our pending list - tempSessionInfo info; - info.sysAddr = SystemAddress(packet->systemAddress); - info.hash = sessionKey; - m_PendingUsers.insert(std::make_pair(username, info)); - - break; } - case MSG_WORLD_CLIENT_CHARACTER_LIST_REQUEST: { - //We need to delete the entity first, otherwise the char list could delete it while it exists in the world! - if (Game::server->GetZoneID() != 0) { - auto user = UserManager::Instance()->GetUser(packet->systemAddress); - if (!user) return; - EntityManager::Instance()->DestroyEntity(user->GetLastUsedChar()->GetEntity()); - } + UserManager::Instance()->RequestCharacterList(packet->systemAddress); + break; + } - //This loops prevents users who aren't authenticated to double-request the char list, which - //would make the login screen freeze sometimes. - if (m_PendingUsers.size() > 0) { - for (auto it : m_PendingUsers) { - if (it.second.sysAddr == packet->systemAddress) { - return; - } + case MSG_WORLD_CLIENT_GAME_MSG: { + RakNet::BitStream bitStream(packet->data, packet->length, false); + + uint64_t header; + LWOOBJID objectID; + uint16_t messageID; + + bitStream.Read(header); + bitStream.Read(objectID); + bitStream.Read(messageID); + + RakNet::BitStream dataStream; + bitStream.Read(dataStream, bitStream.GetNumberOfUnreadBits()); + + GameMessageHandler::HandleMessage(&dataStream, packet->systemAddress, objectID, GAME_MSG(messageID)); + break; + } + + case MSG_WORLD_CLIENT_CHARACTER_CREATE_REQUEST: { + UserManager::Instance()->CreateCharacter(packet->systemAddress, packet); + break; + } + + case MSG_WORLD_CLIENT_LOGIN_REQUEST: { + RakNet::BitStream inStream(packet->data, packet->length, false); + uint64_t header = inStream.Read(header); + + LWOOBJID playerID = 0; + inStream.Read(playerID); + playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_CHARACTER); + playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_PERSISTENT); + + auto user = UserManager::Instance()->GetUser(packet->systemAddress); + + if (user) { + auto lastCharacter = user->GetLoggedInChar(); + // This means we swapped characters and we need to remove the previous player from the container. + if (static_cast(lastCharacter) != playerID) { + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); + bitStream.Write(lastCharacter); + Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); + } + } + + UserManager::Instance()->LoginCharacter(packet->systemAddress, static_cast(playerID)); + break; + } + + case MSG_WORLD_CLIENT_CHARACTER_DELETE_REQUEST: { + UserManager::Instance()->DeleteCharacter(packet->systemAddress, packet); + UserManager::Instance()->RequestCharacterList(packet->systemAddress); + break; + } + + case MSG_WORLD_CLIENT_CHARACTER_RENAME_REQUEST: { + UserManager::Instance()->RenameCharacter(packet->systemAddress, packet); + break; + } + + case MSG_WORLD_CLIENT_LEVEL_LOAD_COMPLETE: { + Game::logger->Log("WorldServer", "Received level load complete from user."); + User* user = UserManager::Instance()->GetUser(packet->systemAddress); + if (user) { + Character* c = user->GetLastUsedChar(); + if (c != nullptr) { + std::u16string username = GeneralUtils::ASCIIToUTF16(c->GetName()); + Game::server->GetReplicaManager()->AddParticipant(packet->systemAddress); + + EntityInfo info{}; + info.lot = 1; + Entity* player = EntityManager::Instance()->CreateEntity(info, UserManager::Instance()->GetUser(packet->systemAddress)); + + WorldPackets::SendCreateCharacter(packet->systemAddress, player, c->GetXMLData(), username, c->GetGMLevel()); + WorldPackets::SendServerState(packet->systemAddress); + + const auto respawnPoint = player->GetCharacter()->GetRespawnPoint(dZoneManager::Instance()->GetZone()->GetWorldID()); + + EntityManager::Instance()->ConstructEntity(player, UNASSIGNED_SYSTEM_ADDRESS, true); + + if (respawnPoint != NiPoint3::ZERO) { + GameMessages::SendPlayerReachedRespawnCheckpoint(player, respawnPoint, NiQuaternion::IDENTITY); } - } - UserManager::Instance()->RequestCharacterList(packet->systemAddress); - break; - } + EntityManager::Instance()->ConstructAllEntities(packet->systemAddress); - case MSG_WORLD_CLIENT_GAME_MSG: { - RakNet::BitStream bitStream(packet->data, packet->length, false); + auto* characterComponent = player->GetComponent(); + if (characterComponent) { + player->GetComponent()->RocketUnEquip(player); + } - uint64_t header; - LWOOBJID objectID; - uint16_t messageID; + c->SetRetroactiveFlags(); - bitStream.Read(header); - bitStream.Read(objectID); - bitStream.Read(messageID); + player->RetroactiveVaultSize(); - RakNet::BitStream dataStream; - bitStream.Read(dataStream, bitStream.GetNumberOfUnreadBits()); + player->GetCharacter()->SetTargetScene(""); - GameMessageHandler::HandleMessage(&dataStream, packet->systemAddress, objectID, GAME_MSG(messageID)); - break; - } + // Fix the destroyable component + auto* destroyableComponent = player->GetComponent(); - case MSG_WORLD_CLIENT_CHARACTER_CREATE_REQUEST: { - UserManager::Instance()->CreateCharacter(packet->systemAddress, packet); - break; - } + if (destroyableComponent != nullptr) { + destroyableComponent->FixStats(); + } - case MSG_WORLD_CLIENT_LOGIN_REQUEST: { - RakNet::BitStream inStream(packet->data, packet->length, false); - uint64_t header = inStream.Read(header); + //Tell the player to generate BBB models, if any: + if (g_CloneID != 0) { + const auto& worldId = dZoneManager::Instance()->GetZone()->GetZoneID(); - LWOOBJID playerID = 0; - inStream.Read(playerID); - playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_CHARACTER); - playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_PERSISTENT); + const auto zoneId = Game::server->GetZoneID(); + const auto cloneId = g_CloneID; - auto user = UserManager::Instance()->GetUser(packet->systemAddress); + auto query = CDClientDatabase::CreatePreppedStmt( + "SELECT id FROM PropertyTemplate WHERE mapID = ?;"); + query.bind(1, (int)zoneId); + + auto result = query.execQuery(); + + if (result.eof() || result.fieldIsNull(0)) { + Game::logger->Log("WorldServer", "No property templates found for zone %d, not sending BBB", zoneId); + goto noBBB; + } + + //Check for BBB models: + auto stmt = Database::CreatePreppedStmt("SELECT ugc_id FROM properties_contents WHERE lot=14 AND property_id=?"); + + int templateId = result.getIntField(0); + + result.finalize(); + + auto* propertyLookup = Database::CreatePreppedStmt("SELECT * FROM properties WHERE template_id = ? AND clone_id = ?;"); + + propertyLookup->setInt(1, templateId); + propertyLookup->setInt64(2, g_CloneID); + + auto* propertyEntry = propertyLookup->executeQuery(); + uint64_t propertyId = 0; + + if (propertyEntry->next()) { + propertyId = propertyEntry->getUInt64(1); + } + + delete propertyLookup; + + stmt->setUInt64(1, propertyId); + auto res = stmt->executeQuery(); + while (res->next()) { + Game::logger->Log("UGC", "Getting lxfml ugcID: %u", res->getUInt(1)); + + //Get lxfml: + auto stmtL = Database::CreatePreppedStmt("SELECT lxfml from ugc where id=?"); + stmtL->setUInt(1, res->getUInt(1)); + + auto lxres = stmtL->executeQuery(); + + while (lxres->next()) { + auto lxfml = lxres->getBlob(1); + + lxfml->seekg(0, std::ios::end); + size_t lxfmlSize = lxfml->tellg(); + lxfml->seekg(0); + + //Send message: + { + LWOOBJID blueprintID = res->getUInt(1); + blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_CHARACTER); + blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_PERSISTENT); + + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); + bitStream.Write(0); //always zero so that a check on the client passes + bitStream.Write(0); + bitStream.Write(1); + bitStream.Write(blueprintID); + + bitStream.Write(lxfmlSize + 9); + + //Write a fake sd0 header: + bitStream.Write(0x73); //s + bitStream.Write(0x64); //d + bitStream.Write(0x30); //0 + bitStream.Write(0x01); //1 + bitStream.Write(0xFF); //end magic + + bitStream.Write(lxfmlSize); + + for (size_t i = 0; i < lxfmlSize; ++i) + bitStream.Write(lxfml->get()); + + SystemAddress sysAddr = packet->systemAddress; + SEND_PACKET; + PacketUtils::SavePacket("lxfml packet " + std::to_string(res->getUInt(1)) + ".bin", (char*)bitStream.GetData(), bitStream.GetNumberOfBytesUsed()); + } + } + + delete stmtL; + delete lxres; + } + + delete stmt; + delete res; + } + + noBBB: + + // Tell the client it's done loading: + GameMessages::SendInvalidZoneTransferList(player, packet->systemAddress, GeneralUtils::ASCIIToUTF16(Game::config->GetValue("source")), u"", false, false); + GameMessages::SendServerDoneLoadingAllObjects(player, packet->systemAddress); + + //Send the player it's mail count: + //update: this might not be needed so im going to try disabling this here. + //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()); - if (user) { - auto lastCharacter = user->GetLoggedInChar(); - // This means we swapped characters and we need to remove the previous player from the container. - if (static_cast(lastCharacter) != playerID) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); - bitStream.Write(lastCharacter); + PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_ADDED_NOTIFICATION); + bitStream.Write(player->GetObjectID()); + bitStream.Write(playerName.size()); + for (size_t i = 0; i < playerName.size(); i++) { + bitStream.Write(playerName[i]); + } + + auto zone = dZoneManager::Instance()->GetZone()->GetZoneID(); + bitStream.Write(zone.GetMapID()); + bitStream.Write(zone.GetInstanceID()); + bitStream.Write(zone.GetCloneID()); + bitStream.Write(player->GetParentUser()->GetMuteExpire()); + Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); } + } else { + Game::logger->Log("WorldServer", "Couldn't find character to log in with for user %s (%i)!", user->GetUsername().c_str(), user->GetAccountID()); + Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_CHARACTER_NOT_FOUND); } + } else { + Game::logger->Log("WorldServer", "Couldn't get user for level load complete!"); + } + break; + } - UserManager::Instance()->LoginCharacter(packet->systemAddress, static_cast(playerID)); - break; + case MSG_WORLD_CLIENT_POSITION_UPDATE: { + ClientPackets::HandleClientPositionUpdate(packet->systemAddress, packet); + break; + } + + case MSG_WORLD_CLIENT_MAIL: { + RakNet::BitStream bitStream(packet->data, packet->length, false); + LWOOBJID space; + bitStream.Read(space); + Mail::HandleMailStuff(&bitStream, packet->systemAddress, UserManager::Instance()->GetUser(packet->systemAddress)->GetLastUsedChar()->GetEntity()); + break; + } + + case MSG_WORLD_CLIENT_ROUTE_PACKET: { + //Yeet to chat + CINSTREAM; + uint64_t header = 0; + uint32_t size = 0; + inStream.Read(header); + inStream.Read(size); + + if (size > 20000) { + Game::logger->Log("WorldServer", "Tried to route a packet with a read size > 20000, so likely a false packet."); + return; } - case MSG_WORLD_CLIENT_CHARACTER_DELETE_REQUEST: { - UserManager::Instance()->DeleteCharacter(packet->systemAddress, packet); - UserManager::Instance()->RequestCharacterList(packet->systemAddress); - break; + CBITSTREAM; + + PacketUtils::WriteHeader(bitStream, CHAT, packet->data[14]); + + //We need to insert the player's objectID so the chat server can find who originated this request: + LWOOBJID objectID = 0; + auto user = UserManager::Instance()->GetUser(packet->systemAddress); + if (user) { + objectID = user->GetLastUsedChar()->GetObjectID(); } - case MSG_WORLD_CLIENT_CHARACTER_RENAME_REQUEST: { - UserManager::Instance()->RenameCharacter(packet->systemAddress, packet); - break; + bitStream.Write(objectID); + + //Now write the rest of the data: + auto data = inStream.GetData(); + for (uint32_t i = 0; i < size; ++i) { + bitStream.Write(data[i + 23]); } - case MSG_WORLD_CLIENT_LEVEL_LOAD_COMPLETE: { - Game::logger->Log("WorldServer", "Received level load complete from user."); - User* user = UserManager::Instance()->GetUser(packet->systemAddress); - if (user) { - Character* c = user->GetLastUsedChar(); - if (c != nullptr) { - std::u16string username = GeneralUtils::ASCIIToUTF16(c->GetName()); - Game::server->GetReplicaManager()->AddParticipant(packet->systemAddress); + Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE_ORDERED, 0, Game::chatSysAddr, false); + break; + } - EntityInfo info {}; - info.lot = 1; - Entity* player = EntityManager::Instance()->CreateEntity(info, UserManager::Instance()->GetUser(packet->systemAddress)); + case MSG_WORLD_CLIENT_STRING_CHECK: { + ClientPackets::HandleChatModerationRequest(packet->systemAddress, packet); + break; + } - WorldPackets::SendCreateCharacter(packet->systemAddress, player, c->GetXMLData(), username, c->GetGMLevel()); - WorldPackets::SendServerState(packet->systemAddress); - - const auto respawnPoint = player->GetCharacter()->GetRespawnPoint(dZoneManager::Instance()->GetZone()->GetWorldID()); - - EntityManager::Instance()->ConstructEntity(player, UNASSIGNED_SYSTEM_ADDRESS, true); - - if (respawnPoint != NiPoint3::ZERO) - { - GameMessages::SendPlayerReachedRespawnCheckpoint(player, respawnPoint, NiQuaternion::IDENTITY); - } - - EntityManager::Instance()->ConstructAllEntities(packet->systemAddress); - - auto* characterComponent = player->GetComponent(); - if (characterComponent) { - player->GetComponent()->RocketUnEquip(player); - } - - c->SetRetroactiveFlags(); - - player->RetroactiveVaultSize(); - - player->GetCharacter()->SetTargetScene(""); - - // Fix the destroyable component - auto* destroyableComponent = player->GetComponent(); - - if (destroyableComponent != nullptr) - { - destroyableComponent->FixStats(); - } - - //Tell the player to generate BBB models, if any: - if (g_CloneID != 0) { - const auto& worldId = dZoneManager::Instance()->GetZone()->GetZoneID(); - - const auto zoneId = Game::server->GetZoneID(); - const auto cloneId = g_CloneID; - - auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT id FROM PropertyTemplate WHERE mapID = ?;"); - query.bind(1, (int) zoneId); - - auto result = query.execQuery(); - - if (result.eof() || result.fieldIsNull(0)) { - Game::logger->Log("WorldServer", "No property templates found for zone %d, not sending BBB", zoneId); - goto noBBB; - } - - //Check for BBB models: - auto stmt = Database::CreatePreppedStmt("SELECT ugc_id FROM properties_contents WHERE lot=14 AND property_id=?"); - - int templateId = result.getIntField(0); - - result.finalize(); - - auto* propertyLookup = Database::CreatePreppedStmt("SELECT * FROM properties WHERE template_id = ? AND clone_id = ?;"); - - propertyLookup->setInt(1, templateId); - propertyLookup->setInt64(2, g_CloneID); - - auto* propertyEntry = propertyLookup->executeQuery(); - uint64_t propertyId = 0; - - if (propertyEntry->next()) { - propertyId = propertyEntry->getUInt64(1); - } - - delete propertyLookup; - - stmt->setUInt64(1, propertyId); - auto res = stmt->executeQuery(); - while (res->next()) { - Game::logger->Log("UGC", "Getting lxfml ugcID: %u", res->getUInt(1)); - - //Get lxfml: - auto stmtL = Database::CreatePreppedStmt("SELECT lxfml from ugc where id=?"); - stmtL->setUInt(1, res->getUInt(1)); - - auto lxres = stmtL->executeQuery(); - - while (lxres->next()) { - auto lxfml = lxres->getBlob(1); - - lxfml->seekg(0, std::ios::end); - size_t lxfmlSize = lxfml->tellg(); - lxfml->seekg(0); - - //Send message: - { - LWOOBJID blueprintID = res->getUInt(1); - blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_CHARACTER); - blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_PERSISTENT); - - CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); - bitStream.Write(0); //always zero so that a check on the client passes - bitStream.Write(0); - bitStream.Write(1); - bitStream.Write(blueprintID); - - bitStream.Write(lxfmlSize + 9); - - //Write a fake sd0 header: - bitStream.Write(0x73); //s - bitStream.Write(0x64); //d - bitStream.Write(0x30); //0 - bitStream.Write(0x01); //1 - bitStream.Write(0xFF); //end magic - - bitStream.Write(lxfmlSize); - - for (size_t i = 0; i < lxfmlSize; ++i) - bitStream.Write(lxfml->get()); - - SystemAddress sysAddr = packet->systemAddress; - SEND_PACKET; - PacketUtils::SavePacket("lxfml packet " + std::to_string(res->getUInt(1)) + ".bin", (char*)bitStream.GetData(), bitStream.GetNumberOfBytesUsed()); - } - } - - delete stmtL; - delete lxres; - } - - delete stmt; - delete res; - } - - noBBB: - - // Tell the client it's done loading: - GameMessages::SendInvalidZoneTransferList(player, packet->systemAddress, GeneralUtils::ASCIIToUTF16(Game::config->GetValue("source")), u"", false, false); - GameMessages::SendServerDoneLoadingAllObjects(player, packet->systemAddress); - - //Send the player it's mail count: - //update: this might not be needed so im going to try disabling this here. - //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()); - - CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_ADDED_NOTIFICATION); - bitStream.Write(player->GetObjectID()); - bitStream.Write(playerName.size()); - for (size_t i = 0; i < playerName.size(); i++) - { - bitStream.Write(playerName[i]); - } - - auto zone = dZoneManager::Instance()->GetZone()->GetZoneID(); - bitStream.Write(zone.GetMapID()); - bitStream.Write(zone.GetInstanceID()); - bitStream.Write(zone.GetCloneID()); - bitStream.Write(player->GetParentUser()->GetMuteExpire()); - - Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); - } - } - else { - Game::logger->Log("WorldServer", "Couldn't find character to log in with for user %s (%i)!", user->GetUsername().c_str(), user->GetAccountID()); - Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_CHARACTER_NOT_FOUND); - } - } else { - Game::logger->Log("WorldServer", "Couldn't get user for level load complete!"); - } - break; - } - - case MSG_WORLD_CLIENT_POSITION_UPDATE: { - ClientPackets::HandleClientPositionUpdate(packet->systemAddress, packet); - break; + case MSG_WORLD_CLIENT_GENERAL_CHAT_MESSAGE: { + if (chatDisabled) { + ChatPackets::SendMessageFail(packet->systemAddress); + } else { + ClientPackets::HandleChatMessage(packet->systemAddress, packet); } - case MSG_WORLD_CLIENT_MAIL: { - RakNet::BitStream bitStream(packet->data, packet->length, false); - LWOOBJID space; - bitStream.Read(space); - Mail::HandleMailStuff(&bitStream, packet->systemAddress, UserManager::Instance()->GetUser(packet->systemAddress)->GetLastUsedChar()->GetEntity()); - break; + break; + } + + case MSG_WORLD_CLIENT_HANDLE_FUNNESS: { + //This means the client is running slower or faster than it should. + //Could be insane lag, but I'mma just YEET them as it's usually speedhacking. + //This is updated to now count the amount of times we've been caught "speedhacking" to kick with a delay + //This is hopefully going to fix the random disconnects people face sometimes. + if (Game::config->GetValue("disable_anti_speedhack") == "1") { + return; } - case MSG_WORLD_CLIENT_ROUTE_PACKET: { - //Yeet to chat - CINSTREAM; - uint64_t header = 0; - uint32_t size = 0; - inStream.Read(header); - inStream.Read(size); - - if (size > 20000) { - Game::logger->Log("WorldServer", "Tried to route a packet with a read size > 20000, so likely a false packet."); - return; - } - - CBITSTREAM; - - PacketUtils::WriteHeader(bitStream, CHAT, packet->data[14]); - - //We need to insert the player's objectID so the chat server can find who originated this request: - LWOOBJID objectID = 0; - auto user = UserManager::Instance()->GetUser(packet->systemAddress); - if (user) { - objectID = user->GetLastUsedChar()->GetObjectID(); - } - - bitStream.Write(objectID); - - //Now write the rest of the data: - auto data = inStream.GetData(); - for (uint32_t i = 0; i < size; ++i) { - bitStream.Write(data[i+23]); - } - - Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE_ORDERED, 0, Game::chatSysAddr, false); - break; - } - - case MSG_WORLD_CLIENT_STRING_CHECK: { - ClientPackets::HandleChatModerationRequest(packet->systemAddress, packet); - break; - } - - case MSG_WORLD_CLIENT_GENERAL_CHAT_MESSAGE: { - if (chatDisabled) { - ChatPackets::SendMessageFail(packet->systemAddress); - } - else { - ClientPackets::HandleChatMessage(packet->systemAddress, packet); - } - - break; - } - - case MSG_WORLD_CLIENT_HANDLE_FUNNESS: { - //This means the client is running slower or faster than it should. - //Could be insane lag, but I'mma just YEET them as it's usually speedhacking. - //This is updated to now count the amount of times we've been caught "speedhacking" to kick with a delay - //This is hopefully going to fix the random disconnects people face sometimes. - if (Game::config->GetValue("disable_anti_speedhack") == "1") { - return; - } - - User* user = UserManager::Instance()->GetUser(packet->systemAddress); - if (user) { - user->UserOutOfSync(); - } - else { - Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_KICK); - } - break; + User* user = UserManager::Instance()->GetUser(packet->systemAddress); + if (user) { + user->UserOutOfSync(); + } else { + Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_KICK); } + break; + } default: Game::server->GetLogger()->Log("HandlePacket", "Unknown world packet received: %i", int(packet->data[3])); @@ -1254,48 +1227,48 @@ void HandlePacket(Packet* packet) { void WorldShutdownProcess(uint32_t zoneId) { Game::logger->Log("WorldServer", "Saving map %i instance %i", zoneId, instanceID); - for (auto i = 0; i < Game::server->GetReplicaManager()->GetParticipantCount(); ++i) { - const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(i); + for (auto i = 0; i < Game::server->GetReplicaManager()->GetParticipantCount(); ++i) { + const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(i); - auto* entity = Player::GetPlayer(player); - Game::logger->Log("WorldServer", "Saving data!"); - if (entity != nullptr && entity->GetCharacter() != nullptr) { - auto* skillComponent = entity->GetComponent(); + auto* entity = Player::GetPlayer(player); + Game::logger->Log("WorldServer", "Saving data!"); + if (entity != nullptr && entity->GetCharacter() != nullptr) { + auto* skillComponent = entity->GetComponent(); - if (skillComponent != nullptr) { - skillComponent->Reset(); - } - Game::logger->Log("WorldServer", "Saving character %s...", entity->GetCharacter()->GetName().c_str()); - entity->GetCharacter()->SaveXMLToDatabase(); - Game::logger->Log("WorldServer", "Character data for %s was saved!", entity->GetCharacter()->GetName().c_str()); - } - } + if (skillComponent != nullptr) { + skillComponent->Reset(); + } + Game::logger->Log("WorldServer", "Saving character %s...", entity->GetCharacter()->GetName().c_str()); + entity->GetCharacter()->SaveXMLToDatabase(); + Game::logger->Log("WorldServer", "Character data for %s was saved!", entity->GetCharacter()->GetName().c_str()); + } + } - if (PropertyManagementComponent::Instance() != nullptr) { - Game::logger->Log("WorldServer", "Saving ALL property data for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); - PropertyManagementComponent::Instance()->Save(); - Game::logger->Log("WorldServer", "ALL property data saved for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); - } + if (PropertyManagementComponent::Instance() != nullptr) { + Game::logger->Log("WorldServer", "Saving ALL property data for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); + PropertyManagementComponent::Instance()->Save(); + Game::logger->Log("WorldServer", "ALL property data saved for zone %i clone %i!", zoneId, PropertyManagementComponent::Instance()->GetCloneId()); + } - Game::logger->Log("WorldServer", "ALL DATA HAS BEEN SAVED FOR ZONE %i INSTANCE %i!", zoneId, instanceID); + Game::logger->Log("WorldServer", "ALL DATA HAS BEEN SAVED FOR ZONE %i INSTANCE %i!", zoneId, instanceID); - while (Game::server->GetReplicaManager()->GetParticipantCount() > 0) { - const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(0); + while (Game::server->GetReplicaManager()->GetParticipantCount() > 0) { + const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(0); - Game::server->Disconnect(player, SERVER_DISCON_KICK); - } + Game::server->Disconnect(player, SERVER_DISCON_KICK); + } SendShutdownMessageToMaster(); } void WorldShutdownSequence() { - if (worldShutdownSequenceStarted || worldShutdownSequenceComplete) { - return; - } + if (worldShutdownSequenceStarted || worldShutdownSequenceComplete) { + return; + } - worldShutdownSequenceStarted = true; + worldShutdownSequenceStarted = true; - Game::logger->Log("WorldServer", "Zone (%i) instance (%i) shutting down outside of main loop!", Game::server->GetZoneID(), instanceID); - WorldShutdownProcess(Game::server->GetZoneID()); + Game::logger->Log("WorldServer", "Zone (%i) instance (%i) shutting down outside of main loop!", Game::server->GetZoneID(), instanceID); + WorldShutdownProcess(Game::server->GetZoneID()); FinalizeShutdown(); } diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index afd2413e..ebfca4cc 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -15,12 +15,11 @@ #include "CDClientManager.h" Level::Level(Zone* parentZone, const std::string& filepath) { - m_ParentZone = parentZone; + m_ParentZone = parentZone; std::ifstream file(filepath, std::ios_base::in | std::ios_base::binary); if (file) { ReadChunks(file); - } - else { + } else { Game::logger->Log("Level", "Failed to load %s", filepath.c_str()); } @@ -42,7 +41,7 @@ const void Level::PrintAllObjects() { } } -void Level::ReadChunks(std::ifstream & file) { +void Level::ReadChunks(std::ifstream& file) { const uint32_t CHNK_HEADER = ('C' + ('H' << 8) + ('N' << 16) + ('K' << 24)); while (!file.eof()) { @@ -63,15 +62,13 @@ void Level::ReadChunks(std::ifstream & file) { //We're currently not loading env or particle data if (header.id == ChunkTypeID::FileInfo) { ReadFileInfoChunk(file, header); - } - else if (header.id == ChunkTypeID::SceneObjectData) { + } else if (header.id == ChunkTypeID::SceneObjectData) { ReadSceneObjectDataChunk(file, header); } m_ChunkHeaders.insert(std::make_pair(header.id, header)); file.seekg(target); - } - else { + } else { if (initPos == std::streamoff(0)) { //Really old chunk version file.seekg(0); Header header; @@ -98,8 +95,7 @@ void Level::ReadChunks(std::ifstream & file) { file.ignore(4); } } - } - else { + } else { file.ignore(8); } @@ -143,7 +139,7 @@ void Level::ReadChunks(std::ifstream & file) { } } -void Level::ReadFileInfoChunk(std::ifstream & file, Header & header) { +void Level::ReadFileInfoChunk(std::ifstream& file, Header& header) { FileInfoChunk* fi = new FileInfoChunk; BinaryIO::BinaryRead(file, fi->version); BinaryIO::BinaryRead(file, fi->revision); @@ -156,7 +152,7 @@ void Level::ReadFileInfoChunk(std::ifstream & file, Header & header) { if (header.fileInfo->revision == 3452816845 && m_ParentZone->GetZoneID().GetMapID() == 1100) header.fileInfo->revision = 26; } -void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { +void Level::ReadSceneObjectDataChunk(std::ifstream& file, Header& header) { SceneObjectDataChunk* chunk = new SceneObjectDataChunk; uint32_t objectsCount = 0; BinaryIO::BinaryRead(file, objectsCount); @@ -182,25 +178,25 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { dZoneManager::Instance()->GetZone()->SetSpawnRot(obj.rotation); } - std::u16string ldfString = u""; - uint32_t length = 0; - BinaryIO::BinaryRead(file, length); + std::u16string ldfString = u""; + uint32_t length = 0; + BinaryIO::BinaryRead(file, length); - for (uint32_t i = 0; i < length; ++i) { - uint16_t data; - BinaryIO::BinaryRead(file, data); - ldfString.push_back(data); - } + for (uint32_t i = 0; i < length; ++i) { + uint16_t data; + BinaryIO::BinaryRead(file, data); + ldfString.push_back(data); + } - std::string sData = GeneralUtils::UTF16ToWTF8(ldfString); - std::stringstream ssData(sData); - std::string token; - char deliminator = '\n'; + std::string sData = GeneralUtils::UTF16ToWTF8(ldfString); + std::stringstream ssData(sData); + std::string token; + char deliminator = '\n'; - while (std::getline(ssData, token, deliminator)) { - LDFBaseData * ldfData = LDFBaseData::DataFromString(token); - obj.settings.push_back(ldfData); - } + while (std::getline(ssData, token, deliminator)) { + LDFBaseData* ldfData = LDFBaseData::DataFromString(token); + obj.settings.push_back(ldfData); + } BinaryIO::BinaryRead(file, obj.value3); @@ -228,7 +224,7 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { continue; } - if (obj.lot == 176) { //Spawner + if (obj.lot == 176) { //Spawner SpawnerInfo spawnInfo = SpawnerInfo(); SpawnerNode* node = new SpawnerNode(); spawnInfo.templateID = obj.lot; @@ -268,8 +264,7 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { if (data->GetValueType() == eLDFType::LDF_TYPE_FLOAT) // Floats are in seconds { spawnInfo.respawnTime = std::stof(data->GetValueAsString()); - } - else if (data->GetValueType() == eLDFType::LDF_TYPE_U32) // Ints are in ms? + } else if (data->GetValueType() == eLDFType::LDF_TYPE_U32) // Ints are in ms? { spawnInfo.respawnTime = std::stoi(data->GetValueAsString()) / 1000; } @@ -296,9 +291,9 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { } } } - Spawner* spawner = new Spawner(spawnInfo); - dZoneManager::Instance()->AddSpawner(obj.id, spawner); - } else { //Regular object + Spawner* spawner = new Spawner(spawnInfo); + dZoneManager::Instance()->AddSpawner(obj.id, spawner); + } else { //Regular object EntityInfo info; info.spawnerID = 0; info.id = obj.id; @@ -327,16 +322,14 @@ void Level::ReadSceneObjectDataChunk(std::ifstream & file, Header & header) { if (!clientOnly) { - // We should never have more than 1 zone control object - const auto zoneControlObject = dZoneManager::Instance()->GetZoneControlObject(); + // We should never have more than 1 zone control object + const auto zoneControlObject = dZoneManager::Instance()->GetZoneControlObject(); if (zoneControlObject != nullptr && info.lot == zoneControlObject->GetLOT()) goto deleteSettings; - EntityManager::Instance()->CreateEntity(info, nullptr); - } - else - { - deleteSettings: + EntityManager::Instance()->CreateEntity(info, nullptr); + } else { + deleteSettings: for (auto* setting : info.settings) { delete setting; diff --git a/dZoneManager/Level.h b/dZoneManager/Level.h index 05839759..e724363f 100644 --- a/dZoneManager/Level.h +++ b/dZoneManager/Level.h @@ -29,7 +29,7 @@ public: struct SceneObjectDataChunk { std::map objects; - + SceneObject& GetObject(LWOOBJID id) { for (std::map::iterator it = objects.begin(); it != objects.end(); ++it) { if (it->first == id) return it->second; diff --git a/dZoneManager/Spawner.cpp b/dZoneManager/Spawner.cpp index 3e69d785..57b4e988 100644 --- a/dZoneManager/Spawner.cpp +++ b/dZoneManager/Spawner.cpp @@ -15,8 +15,7 @@ Spawner::Spawner(const SpawnerInfo info) { if (!m_Info.emulated) { m_EntityInfo.spawnerID = m_Info.spawnerID; - } - else { + } else { m_EntityInfo.spawnerID = m_Info.emulator; m_Info.isNetwork = false; } @@ -46,8 +45,7 @@ Spawner::Spawner(const SpawnerInfo info) { m_WaitTimes.push_back(m_Info.respawnTime); } - if (m_Info.spawnOnSmashGroupName != "") - { + if (m_Info.spawnOnSmashGroupName != "") { std::vector spawnSmashEntities = EntityManager::Instance()->GetEntitiesInGroup(m_Info.spawnOnSmashGroupName); std::vector spawnSmashSpawners = dZoneManager::Instance()->GetSpawnersInGroup(m_Info.spawnOnSmashGroupName); std::vector spawnSmashSpawnersN = dZoneManager::Instance()->GetSpawnersByName(m_Info.spawnOnSmashGroupName); @@ -55,20 +53,20 @@ Spawner::Spawner(const SpawnerInfo info) { m_SpawnSmashFoundGroup = true; ssEntity->AddDieCallback([=]() { Spawn(); - }); + }); } for (Spawner* ssSpawner : spawnSmashSpawners) { m_SpawnSmashFoundGroup = true; ssSpawner->AddSpawnedEntityDieCallback([=]() { Spawn(); - }); + }); } for (Spawner* ssSpawner : spawnSmashSpawnersN) { m_SpawnSmashFoundGroup = true; m_SpawnOnSmash = ssSpawner; ssSpawner->AddSpawnedEntityDieCallback([=]() { Spawn(); - }); + }); } } } @@ -77,8 +75,7 @@ Spawner::~Spawner() { } -Entity* Spawner::Spawn() -{ +Entity* Spawner::Spawn() { std::vector freeNodes; for (SpawnerNode* node : m_Info.nodes) { if (node->entities.size() < node->nodeMax) { @@ -131,18 +128,15 @@ void Spawner::AddSpawnedEntityDieCallback(std::function callback) { m_SpawnedEntityDieCallbacks.push_back(callback); } -void Spawner::AddEntitySpawnedCallback(std::function callback) { +void Spawner::AddEntitySpawnedCallback(std::function callback) { m_EntitySpawnedCallbacks.push_back(callback); } -void Spawner::Reset() -{ +void Spawner::Reset() { m_Start = true; - - for (auto* node : m_Info.nodes) - { - for (const auto& spawned : node->entities) - { + + for (auto* node : m_Info.nodes) { + for (const auto& spawned : node->entities) { auto* entity = EntityManager::Instance()->GetEntity(spawned); if (entity == nullptr) continue; @@ -159,9 +153,9 @@ void Spawner::Reset() } void Spawner::SoftReset() { - m_Start = true; - m_AmountSpawned = 0; - m_NeedsUpdate = true; + m_Start = true; + m_AmountSpawned = 0; + m_NeedsUpdate = true; } void Spawner::SetRespawnTime(float time) { @@ -171,8 +165,8 @@ void Spawner::SetRespawnTime(float time) { m_WaitTimes[i] = 0; }; - m_Start = true; - m_NeedsUpdate = true; + m_Start = true; + m_NeedsUpdate = true; } void Spawner::SetNumToMaintain(int32_t value) { @@ -180,21 +174,19 @@ void Spawner::SetNumToMaintain(int32_t value) { } void Spawner::Update(const float deltaTime) { - if (m_Start && m_Active) - { + if (m_Start && m_Active) { m_Start = false; const auto toSpawn = m_Info.amountMaintained - m_AmountSpawned; - for (auto i = 0; i < toSpawn; ++i) - { + for (auto i = 0; i < toSpawn; ++i) { Spawn(); } - + m_WaitTimes.clear(); - + return; } - + if (!m_NeedsUpdate) return; if (!m_Active) return; //if (m_Info.noTimedSpawn) return; @@ -223,7 +215,7 @@ void Spawner::NotifyOfEntityDeath(const LWOOBJID& objectID) { //m_RespawnTime = 10.0f; m_WaitTimes.push_back(0.0f); SpawnerNode* node; - + auto it = m_Entities.find(objectID); if (it != m_Entities.end()) node = it->second; else return; @@ -233,29 +225,26 @@ void Spawner::NotifyOfEntityDeath(const LWOOBJID& objectID) { } for (size_t i = 0; i < node->entities.size(); ++i) { - if (node->entities[i] && node->entities[i] == objectID) + if (node->entities[i] && node->entities[i] == objectID) node->entities.erase(node->entities.begin() + i); } m_Entities.erase(objectID); - if (m_SpawnOnSmash != nullptr) - { + if (m_SpawnOnSmash != nullptr) { m_SpawnOnSmash->Reset(); } } -void Spawner::Activate() -{ +void Spawner::Activate() { m_Active = true; m_NeedsUpdate = true; - for (auto& time : m_WaitTimes) - { + for (auto& time : m_WaitTimes) { time = 0; } } void Spawner::SetSpawnLot(LOT lot) { - m_EntityInfo.lot = lot; + m_EntityInfo.lot = lot; } diff --git a/dZoneManager/Spawner.h b/dZoneManager/Spawner.h index 17e2e126..908bb3a3 100644 --- a/dZoneManager/Spawner.h +++ b/dZoneManager/Spawner.h @@ -37,15 +37,15 @@ struct SpawnerInfo { bool noTimedSpawn = false; std::string grpNameQBShowBricks = ""; bool spawnActivator = true; - + bool emulated = false; LWOOBJID emulator = LWOOBJID_EMPTY; }; class Spawner { public: - Spawner(SpawnerInfo info); - ~Spawner(); + Spawner(SpawnerInfo info); + ~Spawner(); Entity* Spawn(); Entity* Spawn(std::vector freeNodes, bool force = false); @@ -69,7 +69,7 @@ public: bool m_Active = true; private: std::vector> m_SpawnedEntityDieCallbacks = {}; - std::vector> m_EntitySpawnedCallbacks = {}; + std::vector> m_EntitySpawnedCallbacks = {}; bool m_SpawnSmashFoundGroup = false; diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 36245df4..54246c28 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -12,9 +12,8 @@ #include "Spawner.h" #include "dZoneManager.h" -Zone::Zone(const LWOMAPID & mapID, const LWOINSTANCEID & instanceID, const LWOCLONEID & cloneID) : - m_ZoneID(mapID, instanceID, cloneID) -{ +Zone::Zone(const LWOMAPID& mapID, const LWOINSTANCEID& instanceID, const LWOCLONEID& cloneID) : + m_ZoneID(mapID, instanceID, cloneID) { m_NumberOfScenesLoaded = 0; m_NumberOfObjectsLoaded = 0; m_NumberOfSceneTransitionsLoaded = 0; @@ -30,8 +29,7 @@ Zone::~Zone() { } } -void Zone::Initalize() -{ +void Zone::Initalize() { LoadZoneIntoMemory(); LoadLevelsIntoMemory(); m_CheckSum = CalculateChecksum(); @@ -63,8 +61,7 @@ void Zone::LoadZoneIntoMemory() { uint8_t sceneCount; BinaryIO::BinaryRead(file, sceneCount); m_SceneCount = sceneCount; - } - else BinaryIO::BinaryRead(file, m_SceneCount); + } else BinaryIO::BinaryRead(file, m_SceneCount); for (uint32_t i = 0; i < m_SceneCount; ++i) { LoadScene(file); @@ -117,23 +114,18 @@ void Zone::LoadZoneIntoMemory() { if (data) { if (data->GetKey() == u"spawner_node_id") { node->nodeID = std::stoi(data->GetValueAsString()); - } - else if (data->GetKey() == u"spawner_max_per_node") { + } else if (data->GetKey() == u"spawner_max_per_node") { node->nodeMax = std::stoi(data->GetValueAsString()); - } - else if (data->GetKey() == u"groupID") { // Load object group + } else if (data->GetKey() == u"groupID") { // Load object group std::string groupStr = data->GetValueAsString(); info.groups = GeneralUtils::SplitString(groupStr, ';'); info.groups.erase(info.groups.end() - 1); - } - else if (data->GetKey() == u"grpNameQBShowBricks") { + } else if (data->GetKey() == u"grpNameQBShowBricks") { if (data->GetValueAsString() == "") continue; /*std::string groupStr = data->GetValueAsString(); info.groups.push_back(groupStr);*/ info.grpNameQBShowBricks = data->GetValueAsString(); - } - else if (data->GetKey() == u"spawner_name") - { + } else if (data->GetKey() == u"spawner_name") { info.name = data->GetValueAsString(); } } @@ -157,8 +149,7 @@ void Zone::LoadZoneIntoMemory() { //m_PathData.resize(m_PathDataLength); //file.read((char*)&m_PathData[0], m_PathDataLength); } - } - else { + } else { Game::logger->Log("Zone", "Failed to open: %s", m_ZoneFilePath.c_str()); } m_ZonePath = m_ZoneFilePath.substr(0, m_ZoneFilePath.rfind('/') + 1); @@ -168,11 +159,11 @@ 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("ZoneTable"); + CDZoneTableTable* zoneTable = CDClientManager::Instance()->GetTable("ZoneTable"); const CDZoneTable* zone = zoneTable->Query(this->GetZoneID().GetMapID()); if (zone != nullptr) { - std::string toReturn = "./res/maps/" + zone->zoneName; - std::transform(toReturn.begin(), toReturn.end(), toReturn.begin(), ::tolower); + std::string toReturn = "./res/maps/" + zone->zoneName; + std::transform(toReturn.begin(), toReturn.end(), toReturn.begin(), ::tolower); return toReturn; } @@ -231,7 +222,7 @@ const void Zone::PrintAllGameObjects() { } } -void Zone::LoadScene(std::ifstream & file) { +void Zone::LoadScene(std::ifstream& file) { SceneRef scene; scene.level = nullptr; LWOSCENEID lwoSceneID(LWOZONEID_INVALID, 0); @@ -284,8 +275,7 @@ std::vector Zone::LoadLUTriggers(std::string triggerFile, if (doc->Parse(data.str().c_str(), data.str().size()) == 0) { //Game::logger->Log("Zone", "Loaded LUTriggers from file %s!", triggerFile.c_str()); - } - else { + } else { Game::logger->Log("Zone", "Failed to load LUTriggers from file %s", triggerFile.c_str()); return lvlTriggers; } @@ -295,7 +285,7 @@ std::vector Zone::LoadLUTriggers(std::string triggerFile, auto currentTrigger = triggers->FirstChildElement("trigger"); while (currentTrigger) { - LUTriggers::Trigger *newTrigger = new LUTriggers::Trigger(); + LUTriggers::Trigger* newTrigger = new LUTriggers::Trigger(); currentTrigger->QueryAttribute("enabled", &newTrigger->enabled); currentTrigger->QueryAttribute("id", &newTrigger->id); @@ -336,12 +326,9 @@ LUTriggers::Trigger* Zone::GetTrigger(uint32_t sceneID, uint32_t triggerID) { return m_Scenes[sceneID].triggers[triggerID]; } -const Path* Zone::GetPath(std::string name) const -{ - for (const auto& path : m_Paths) - { - if (name == path.pathName) - { +const Path* Zone::GetPath(std::string name) const { + for (const auto& path : m_Paths) { + if (name == path.pathName) { return &path; } } @@ -349,7 +336,7 @@ const Path* Zone::GetPath(std::string name) const return nullptr; } -void Zone::LoadSceneTransition(std::ifstream & file) { +void Zone::LoadSceneTransition(std::ifstream& file) { SceneTransition sceneTrans; if (m_ZoneFileFormatVersion < Zone::ZoneFileFormatVersion::LateAlpha) { uint8_t length; @@ -367,14 +354,14 @@ void Zone::LoadSceneTransition(std::ifstream & file) { m_SceneTransitions.push_back(sceneTrans); } -SceneTransitionInfo Zone::LoadSceneTransitionInfo(std::ifstream & file) { +SceneTransitionInfo Zone::LoadSceneTransitionInfo(std::ifstream& file) { SceneTransitionInfo info; BinaryIO::BinaryRead(file, info.sceneID); BinaryIO::BinaryRead(file, info.position); return info; } -void Zone::LoadPath(std::ifstream & file) { +void Zone::LoadPath(std::ifstream& file) { // Currently only spawner (type 4) paths are supported Path path = Path(); @@ -400,8 +387,7 @@ void Zone::LoadPath(std::ifstream & file) { if (path.pathVersion >= 18) { uint8_t unknown; BinaryIO::BinaryRead(file, unknown); - } - else if (path.pathVersion >= 13) { + } else if (path.pathVersion >= 13) { uint8_t count; BinaryIO::BinaryRead(file, count); for (uint8_t i = 0; i < count; ++i) { @@ -410,8 +396,7 @@ void Zone::LoadPath(std::ifstream & file) { path.movingPlatform.platformTravelSound.push_back(character); } } - } - else if (path.pathType == PathType::Property) { + } else if (path.pathType == PathType::Property) { int32_t unknown; BinaryIO::BinaryRead(file, unknown); BinaryIO::BinaryRead(file, path.property.price); @@ -441,8 +426,7 @@ void Zone::LoadPath(std::ifstream & file) { BinaryIO::BinaryRead(file, path.property.playerZoneCoords.y); BinaryIO::BinaryRead(file, path.property.playerZoneCoords.z); BinaryIO::BinaryRead(file, path.property.maxBuildHeight); - } - else if (path.pathType == PathType::Camera) { + } else if (path.pathType == PathType::Camera) { uint8_t count; BinaryIO::BinaryRead(file, count); for (uint8_t i = 0; i < count; ++i) { @@ -503,8 +487,7 @@ void Zone::LoadPath(std::ifstream & file) { waypoint.movingPlatform.arriveSound.push_back(character); } } - } - else if (path.pathType == PathType::Camera) { + } else if (path.pathType == PathType::Camera) { float unknown; BinaryIO::BinaryRead(file, unknown); BinaryIO::BinaryRead(file, unknown); @@ -515,8 +498,7 @@ void Zone::LoadPath(std::ifstream & file) { BinaryIO::BinaryRead(file, waypoint.camera.tension); BinaryIO::BinaryRead(file, waypoint.camera.continuity); BinaryIO::BinaryRead(file, waypoint.camera.bias); - } - else if (path.pathType == PathType::Race) { + } else if (path.pathType == PathType::Race) { uint8_t unknown; BinaryIO::BinaryRead(file, unknown); BinaryIO::BinaryRead(file, unknown); @@ -524,8 +506,7 @@ void Zone::LoadPath(std::ifstream & file) { BinaryIO::BinaryRead(file, unknown1); BinaryIO::BinaryRead(file, unknown1); BinaryIO::BinaryRead(file, unknown1); - } - else if (path.pathType == PathType::Rail) { + } else if (path.pathType == PathType::Rail) { float unknown; BinaryIO::BinaryRead(file, unknown); BinaryIO::BinaryRead(file, unknown); diff --git a/dZoneManager/Zone.h b/dZoneManager/Zone.h index 0d30415d..5d3dc424 100644 --- a/dZoneManager/Zone.h +++ b/dZoneManager/Zone.h @@ -9,7 +9,7 @@ class Level; class LUTriggers { - public: +public: struct Command { std::string id; @@ -89,7 +89,7 @@ enum class PathBehavior : uint32_t { Once = 2 }; -enum class PropertyRentalTimeUnit : int32_t{ +enum class PropertyRentalTimeUnit : int32_t { Forever = 0, Seconds = 1, Minutes = 2, diff --git a/dZoneManager/dZMCommon.h b/dZoneManager/dZMCommon.h index 6ee23a61..635faaae 100644 --- a/dZoneManager/dZMCommon.h +++ b/dZoneManager/dZMCommon.h @@ -19,8 +19,8 @@ struct SceneObject { float scale = 1.0f; //std::string settings; uint32_t value3; - std::vector settings; + std::vector settings; }; #define LOT_MARKER_PLAYER_START 1931 -#define LOT_MARKET_CAMERA_TARGET 2182 \ No newline at end of file +#define LOT_MARKET_CAMERA_TARGET 2182 diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index 89f4b6f8..52d56f3c 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -17,17 +17,17 @@ dZoneManager* dZoneManager::m_Address = nullptr; void dZoneManager::Initialize(const LWOZONEID& zoneID) { Game::logger->Log("dZoneManager", "Preparing zone: %i/%i/%i", zoneID.GetMapID(), zoneID.GetInstanceID(), zoneID.GetCloneID()); - int64_t startTime = 0; - int64_t endTime = 0; + int64_t startTime = 0; + int64_t endTime = 0; - startTime = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); + startTime = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); - LoadZone(zoneID); + LoadZone(zoneID); LOT zoneControlTemplate = 2365; CDZoneTableTable* zoneTable = CDClientManager::Instance()->GetTable("ZoneTable"); - if (zoneTable != nullptr){ + if (zoneTable != nullptr) { const CDZoneTable* zone = zoneTable->Query(zoneID.GetMapID()); if (zone != nullptr) { @@ -37,7 +37,7 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { EntityManager::Instance()->SetGhostDistanceMax(max + min); EntityManager::Instance()->SetGhostDistanceMin(max); m_PlayerLoseCoinsOnDeath = zone->PlayerLoseCoinsOnDeath; - } + } } Game::logger->Log("dZoneManager", "Creating zone control object %i", zoneControlTemplate); @@ -51,9 +51,9 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { m_pZone->Initalize(); - endTime = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); + endTime = std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count(); - Game::logger->Log("dZoneManager", "Zone prepared in: %llu ms", (endTime - startTime)); + Game::logger->Log("dZoneManager", "Zone prepared in: %llu ms", (endTime - startTime)); VanityUtilities::SpawnVanity(); } @@ -61,17 +61,17 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { dZoneManager::~dZoneManager() { if (m_pZone) delete m_pZone; - for (std::pair p : m_Spawners) { - if (p.second) { - delete p.second; - p.second = nullptr; - } + for (std::pair p : m_Spawners) { + if (p.second) { + delete p.second; + p.second = nullptr; + } - m_Spawners.erase(p.first); - } + m_Spawners.erase(p.first); + } } -Zone * dZoneManager::GetZone() { +Zone* dZoneManager::GetZone() { return m_pZone; } @@ -82,14 +82,14 @@ void dZoneManager::LoadZone(const LWOZONEID& zoneID) { m_pZone = new Zone(zoneID.GetMapID(), zoneID.GetInstanceID(), zoneID.GetCloneID()); } -void dZoneManager::NotifyZone(const dZoneNotifier & notifier, const LWOOBJID& objectID) { +void dZoneManager::NotifyZone(const dZoneNotifier& notifier, const LWOOBJID& objectID) { switch (notifier) { case dZoneNotifier::SpawnedObjectDestroyed: break; case dZoneNotifier::SpawnedChildObjectDestroyed: break; case dZoneNotifier::ReloadZone: - Game::logger->Log("dZoneManager", "Forcing reload of zone %i", m_ZoneID.GetMapID()); + Game::logger->Log("dZoneManager", "Forcing reload of zone %i", m_ZoneID.GetMapID()); LoadZone(m_ZoneID); m_pZone->Initalize(); @@ -109,21 +109,19 @@ void dZoneManager::NotifyZone(const dZoneNotifier & notifier, const LWOOBJID& ob } } -void dZoneManager::AddSpawner(LWOOBJID id, Spawner* spawner) -{ +void dZoneManager::AddSpawner(LWOOBJID id, Spawner* spawner) { m_Spawners.insert_or_assign(id, spawner); } -LWOZONEID dZoneManager::GetZoneID() const -{ +LWOZONEID dZoneManager::GetZoneID() const { return m_ZoneID; } uint32_t dZoneManager::GetMaxLevel() { if (m_MaxLevel == 0) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT LevelCap FROM WorldConfig WHERE WorldConfigID = 1 LIMIT 1;"); - m_MaxLevel = tableData.getIntField(0, -1); - tableData.finalize(); + m_MaxLevel = tableData.getIntField(0, -1); + tableData.finalize(); } return m_MaxLevel; } @@ -131,8 +129,8 @@ uint32_t dZoneManager::GetMaxLevel() { int32_t dZoneManager::GetLevelCapCurrencyConversion() { if (m_CurrencyConversionRate == 0) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT LevelCapCurrencyConversion FROM WorldConfig WHERE WorldConfigID = 1 LIMIT 1;"); - m_CurrencyConversionRate = tableData.getIntField(0, -1); - tableData.finalize(); + m_CurrencyConversionRate = tableData.getIntField(0, -1); + tableData.finalize(); } return m_CurrencyConversionRate; } @@ -143,12 +141,10 @@ void dZoneManager::Update(float deltaTime) { } } -LWOOBJID dZoneManager::MakeSpawner(SpawnerInfo info) -{ +LWOOBJID dZoneManager::MakeSpawner(SpawnerInfo info) { auto objectId = info.spawnerID; - if (objectId == LWOOBJID_EMPTY) - { + if (objectId == LWOOBJID_EMPTY) { objectId = ObjectIDManager::Instance()->GenerateObjectID(); objectId = GeneralUtils::SetBit(objectId, OBJECT_BIT_CLIENT); @@ -172,8 +168,7 @@ LWOOBJID dZoneManager::MakeSpawner(SpawnerInfo info) return objectId; } -Spawner* dZoneManager::GetSpawner(const LWOOBJID id) -{ +Spawner* dZoneManager::GetSpawner(const LWOOBJID id) { const auto& index = m_Spawners.find(id); if (index == m_Spawners.end()) { @@ -183,8 +178,7 @@ Spawner* dZoneManager::GetSpawner(const LWOOBJID id) return index->second; } -void dZoneManager::RemoveSpawner(const LWOOBJID id) -{ +void dZoneManager::RemoveSpawner(const LWOOBJID id) { auto* spawner = GetSpawner(id); if (spawner == nullptr) { @@ -196,16 +190,13 @@ void dZoneManager::RemoveSpawner(const LWOOBJID id) if (entity != nullptr) { entity->Kill(); - } - else { + } else { Game::logger->Log("dZoneManager", "Failed to find spawner entity (%llu)", id); } - for (auto* node : spawner->m_Info.nodes) - { - for (const auto& element : node->entities) - { + for (auto* node : spawner->m_Info.nodes) { + for (const auto& element : node->entities) { auto* nodeEntity = EntityManager::Instance()->GetEntity(element); if (nodeEntity == nullptr) continue; diff --git a/dZoneManager/dZoneManager.h b/dZoneManager/dZoneManager.h index 3171c81f..66e56820 100644 --- a/dZoneManager/dZoneManager.h +++ b/dZoneManager/dZoneManager.h @@ -17,14 +17,14 @@ public: }; public: - static dZoneManager* Instance() { + static dZoneManager* Instance() { if (!m_Address) { m_Address = new dZoneManager(); } - + return m_Address; } - + void Initialize(const LWOZONEID& zoneID); ~dZoneManager(); @@ -54,12 +54,12 @@ private: * The ratio of LEGO Score to currency when the character has hit the max level. */ int32_t m_CurrencyConversionRate = 0; - - static dZoneManager* m_Address; //Singleton + + static dZoneManager* m_Address; //Singleton Zone* m_pZone; LWOZONEID m_ZoneID; - bool m_PlayerLoseCoinsOnDeath; //Do players drop coins in this zone when smashed - std::map m_Spawners; + bool m_PlayerLoseCoinsOnDeath; //Do players drop coins in this zone when smashed + std::map m_Spawners; Entity* m_ZoneControlObject; }; diff --git a/tests/AMFDeserializeTests.cpp b/tests/AMFDeserializeTests.cpp index 58d7eea4..71a0b265 100644 --- a/tests/AMFDeserializeTests.cpp +++ b/tests/AMFDeserializeTests.cpp @@ -15,7 +15,7 @@ std::unique_ptr ReadFromBitStream(RakNet::BitStream* bitStream) { int ReadAMFUndefinedFromBitStream() { CBITSTREAM - bitStream.Write(0x00); + bitStream.Write(0x00); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFUndefined); return 0; @@ -23,7 +23,7 @@ int ReadAMFUndefinedFromBitStream() { int ReadAMFNullFromBitStream() { CBITSTREAM - bitStream.Write(0x01); + bitStream.Write(0x01); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFNull); return 0; @@ -31,7 +31,7 @@ int ReadAMFNullFromBitStream() { int ReadAMFFalseFromBitStream() { CBITSTREAM - bitStream.Write(0x02); + bitStream.Write(0x02); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFFalse); return 0; @@ -39,7 +39,7 @@ int ReadAMFFalseFromBitStream() { int ReadAMFTrueFromBitStream() { CBITSTREAM - bitStream.Write(0x03); + bitStream.Write(0x03); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFTrue); return 0; @@ -49,12 +49,12 @@ int ReadAMFIntegerFromBitStream() { CBITSTREAM { bitStream.Write(0x04); - // 127 == 01111111 - bitStream.Write(127); - std::unique_ptr res(ReadFromBitStream(&bitStream)); - ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); - // Check that the max value of a byte can be read correctly - ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 127); + // 127 == 01111111 + bitStream.Write(127); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); + // Check that the max value of a byte can be read correctly + ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 127); } bitStream.Reset(); { @@ -96,7 +96,7 @@ int ReadAMFIntegerFromBitStream() { int ReadAMFDoubleFromBitStream() { CBITSTREAM - bitStream.Write(0x05); + bitStream.Write(0x05); bitStream.Write(25346.4f); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFDouble); @@ -106,7 +106,7 @@ int ReadAMFDoubleFromBitStream() { int ReadAMFStringFromBitStream() { CBITSTREAM - bitStream.Write(0x06); + bitStream.Write(0x06); bitStream.Write(0x0F); std::string toWrite = "stateID"; for (auto e : toWrite) bitStream.Write(e); @@ -118,8 +118,8 @@ int ReadAMFStringFromBitStream() { int ReadAMFArrayFromBitStream() { CBITSTREAM - // Test empty AMFArray - bitStream.Write(0x09); + // Test empty AMFArray + bitStream.Write(0x09); bitStream.Write(0x01); bitStream.Write(0x01); { @@ -154,7 +154,7 @@ int ReadAMFArrayFromBitStream() { } /** - * This test checks that if we recieve an unimplemented AMFValueType + * This test checks that if we recieve an unimplemented AMFValueType * we correctly throw an error and can actch it. */ int TestUnimplementedAMFValues() { @@ -169,7 +169,7 @@ int TestUnimplementedAMFValues() { AMFValueType::AMFVectorDouble, AMFValueType::AMFVectorObject, AMFValueType::AMFDictionary - }; + }; // Run unimplemented tests to check that errors are thrown if // unimplemented AMF values are attempted to be parsed. std::ifstream fileStream; @@ -222,8 +222,8 @@ int TestLiveCapture() { ASSERT_EQ(dynamic_cast(result->FindValue("BehaviorID"))->GetStringValue(), "10447"); ASSERT_EQ(dynamic_cast(result->FindValue("objectID"))->GetStringValue(), "288300744895913279") - // Test the execution state array - auto executionState = dynamic_cast(result->FindValue("executionState")); + // Test the execution state array + auto executionState = dynamic_cast(result->FindValue("executionState")); ASSERT_NE(executionState, nullptr); auto strips = dynamic_cast(executionState->FindValue("strips"))->GetDenseArray(); @@ -268,7 +268,7 @@ int TestLiveCapture() { ASSERT_EQ(actionID->GetDoubleValue(), 0.0f) - auto uiArray = dynamic_cast(firstStrip->FindValue("ui")); + auto uiArray = dynamic_cast(firstStrip->FindValue("ui")); auto xPos = dynamic_cast(uiArray->FindValue("x")); auto yPos = dynamic_cast(uiArray->FindValue("y")); @@ -280,7 +280,7 @@ int TestLiveCapture() { ASSERT_EQ(stripID->GetDoubleValue(), 0.0f) - auto firstAction = dynamic_cast(actionsInFirstStrip[0]); + auto firstAction = dynamic_cast(actionsInFirstStrip[0]); auto firstType = dynamic_cast(firstAction->FindValue("Type")); @@ -348,17 +348,17 @@ int AMFDeserializeTests(int argc, char** const argv) { } /** - * Below is the AMF that is in the AMFBitStreamTest.bin file that we are reading in + * Below is the AMF that is in the AMFBitStreamTest.bin file that we are reading in * from a bitstream to test. args: amf3! { "objectID": "288300744895913279", "BehaviorID": "10447", - "executionState": amf3! + "executionState": amf3! { - "strips": amf3! + "strips": amf3! [ - amf3! + amf3! { "actionIndex": 0.0, "id": 0.0, diff --git a/tests/TestEncoding.cpp b/tests/TestEncoding.cpp index 1e676ec3..c23e2db6 100644 --- a/tests/TestEncoding.cpp +++ b/tests/TestEncoding.cpp @@ -4,49 +4,49 @@ #include "GeneralUtils.h" #include "CommonCxxTests.h" -int TestEncoding(int argc, char* *const argv) { - std::string x = "Hello World!"; - std::string_view v(x); +int TestEncoding(int argc, char** const argv) { + std::string x = "Hello World!"; + std::string_view v(x); - uint32_t out; - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'H'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'e'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'o'); - ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), true); + uint32_t out; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'H'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'e'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'o'); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), true); - x = u8"Frühling"; - v = x; - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'F'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'r'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'ü'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'h'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'l'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'i'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'n'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'g'); - ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); + x = u8"Frühling"; + v = x; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'F'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'r'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'ü'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'h'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'l'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'i'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'n'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'g'); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); - x = "中文字"; - v = x; - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'中'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'文'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'字'); - ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); + x = "中文字"; + v = x; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'中'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'文'); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'字'); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); - x = "👨‍⚖️"; - v = x; - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x1F468); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x200D); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x2696); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0xFE0F); - ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); + x = "👨‍⚖️"; + v = x; + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x1F468); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x200D); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x2696); + GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0xFE0F); + ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); - ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Hello World!"), u"Hello World!"); - ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Frühling"), u"Frühling"); - ASSERT_EQ(GeneralUtils::UTF8ToUTF16("中文字"), u"中文字"); - ASSERT_EQ(GeneralUtils::UTF8ToUTF16("👨‍⚖️"), u"👨‍⚖️"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Hello World!"), u"Hello World!"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Frühling"), u"Frühling"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("中文字"), u"中文字"); + ASSERT_EQ(GeneralUtils::UTF8ToUTF16("👨‍⚖️"), u"👨‍⚖️"); - return 0; + return 0; } diff --git a/tests/TestLDFFormat.cpp b/tests/TestLDFFormat.cpp index 7ba31420..a7433e96 100644 --- a/tests/TestLDFFormat.cpp +++ b/tests/TestLDFFormat.cpp @@ -3,15 +3,15 @@ /** * @brief Test parsing an LDF value - * + * * @param argc Number of command line arguments for this test * @param argv Command line arguments * @return 0 on success, non-zero on failure */ -int TestLDFFormat(int argc, char* *const argv) { +int TestLDFFormat(int argc, char** const argv) { // Create auto* data = LDFBaseData::DataFromString("KEY=0:VALUE"); - + // Check that the data type is correct ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_16); @@ -19,7 +19,7 @@ int TestLDFFormat(int argc, char* *const argv) { ASSERT_EQ(data->GetKey(), u"KEY"); // Check that the value is correct - ASSERT_EQ(((LDFData* )data)->GetValue(), u"VALUE"); + ASSERT_EQ(((LDFData*)data)->GetValue(), u"VALUE"); // Check that the serialization is correct ASSERT_EQ(data->GetString(), "KEY=0:VALUE"); diff --git a/tests/TestNiPoint3.cpp b/tests/TestNiPoint3.cpp index 076b186d..d1588b8b 100644 --- a/tests/TestNiPoint3.cpp +++ b/tests/TestNiPoint3.cpp @@ -3,9 +3,9 @@ #include "NiPoint3.h" #include "CommonCxxTests.h" -int TestNiPoint3(int argc, char* *const argv) { +int TestNiPoint3(int argc, char** const argv) { // Check that Unitize works - ASSERT_EQ(NiPoint3(3,0,0).Unitize(), NiPoint3::UNIT_X); + ASSERT_EQ(NiPoint3(3, 0, 0).Unitize(), NiPoint3::UNIT_X); // Check what unitize does to a vector of length 0 ASSERT_EQ(NiPoint3::ZERO.Unitize(), NiPoint3::ZERO); // If we get here, all was successful From 0e46b875a5f318ce6c00ceed780aea647ec7386b Mon Sep 17 00:00:00 2001 From: aronwk-aaron Date: Thu, 28 Jul 2022 08:47:28 -0500 Subject: [PATCH 050/322] blame ignore and contributing update --- .git-blame-ignore-revs.txt | 2 ++ CONTRIBUTING.md | 11 ++++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 .git-blame-ignore-revs.txt diff --git a/.git-blame-ignore-revs.txt b/.git-blame-ignore-revs.txt new file mode 100644 index 00000000..2fa44c8c --- /dev/null +++ b/.git-blame-ignore-revs.txt @@ -0,0 +1,2 @@ +# format codebase +19e77a38d837ce781ba0ca6ea8e78b67a6e3b5a5 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 64fcbc9f..a44629f8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -123,6 +123,15 @@ added, which produced InvalidScript errors. Check out a compiled list of development resources and tools [here](https://lu-dev.net/). + +Please use [.editorconfig](https://editorconfig.org/#pre-installed) with your preferred IDE. + +And run: +```bash +git config blame.ignoreRevsFile .git-blame-ignore-revs +``` +to ignore the gitblame of mass formatting commits + ## Coding Style This project has gone through multiple iterations of coding style. In the code you'll find a number of different coding styles in use. What follows is the preferred style for this project. @@ -154,7 +163,7 @@ if (x) { } ``` -Instead of +Instead of ```cpp if ( x ) { From f284e5a6e169765ed8eaabb01a88b75105c6c4f8 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre Date: Thu, 28 Jul 2022 11:35:57 -0500 Subject: [PATCH 051/322] fix filename --- .git-blame-ignore-revs.txt => .git-blame-ignore-revs | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .git-blame-ignore-revs.txt => .git-blame-ignore-revs (100%) diff --git a/.git-blame-ignore-revs.txt b/.git-blame-ignore-revs similarity index 100% rename from .git-blame-ignore-revs.txt rename to .git-blame-ignore-revs From 26ddeaa4292b9c01c6a9dbf9f9503f61258c667f Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 29 Jul 2022 17:00:36 -0700 Subject: [PATCH 052/322] Fix NPC Proxy items (#684) * Fix racing lap times * Address NPC proxies NPCs are supposed to equip the sub items of items they equip and were not doing so. This PR adds this functionality and fixes and issue where Neido on Crux Prime was not wearing their sword. Tested that Neido has their sword and that other NPCs that wear proxies also get their proxies equipped. Had no issues with any other world crashing. --- dGame/dComponents/InventoryComponent.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index a48173bb..6dbb3bd8 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -62,6 +62,25 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do const auto& info = Inventory::FindItemComponent(item.itemid); UpdateSlot(info.equipLocation, { id, static_cast(item.itemid), item.count, slot++ }); + + // Equip this items proxies. + auto subItems = info.subItems; + + subItems.erase(std::remove_if(subItems.begin(), subItems.end(), ::isspace), subItems.end()); + + if (!subItems.empty()) { + const auto subItemsSplit = GeneralUtils::SplitString(subItems, ','); + + for (auto proxyLotAsString : subItemsSplit) { + const auto proxyLOT = static_cast(std::stoi(proxyLotAsString)); + + const auto& proxyInfo = Inventory::FindItemComponent(proxyLOT); + const LWOOBJID proxyId = ObjectIDManager::Instance()->GenerateObjectID(); + + // Use item.count since we equip item.count number of the item this is a requested proxy of + UpdateSlot(proxyInfo.equipLocation, { proxyId, proxyLOT, item.count, slot++ } ); + } + } } } From f80a26a9448c661453b353d38fe5fe8480b8ed30 Mon Sep 17 00:00:00 2001 From: eddytronpie <55319774+PyEddy@users.noreply.github.com> Date: Sat, 30 Jul 2022 04:41:14 +0100 Subject: [PATCH 053/322] Fix integer issue with BricksCollected (#679) This fixes an issue where BricksCollected goes to an insane number after selling more bricks than you collected in the area --- dGame/dComponents/CharacterComponent.cpp | 3 ++- dGame/dComponents/CharacterComponent.h | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 91666014..3b4b8db8 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -211,7 +211,7 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { ZoneStatistics statistics = {}; child->QueryUnsigned64Attribute("ac", &statistics.m_AchievementsCollected); - child->QueryUnsigned64Attribute("bc", &statistics.m_BricksCollected); + child->QueryInt64Attribute("bc", &statistics.m_BricksCollected); child->QueryUnsigned64Attribute("cc", &statistics.m_CoinsCollected); child->QueryUnsigned64Attribute("es", &statistics.m_EnemiesSmashed); child->QueryUnsigned64Attribute("qbc", &statistics.m_QuickBuildsCompleted); @@ -226,6 +226,7 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { } const tinyxml2::XMLAttribute* rocketConfig = character->FindAttribute("lcbp"); + if (rocketConfig) { m_LastRocketConfig = GeneralUtils::ASCIIToUTF16(std::string(rocketConfig->Value())); } else { diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index f6bf1e70..8efb4ef5 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -15,7 +15,7 @@ */ struct ZoneStatistics { uint64_t m_AchievementsCollected; - uint64_t m_BricksCollected; + int64_t m_BricksCollected; uint64_t m_CoinsCollected; uint64_t m_EnemiesSmashed; uint64_t m_QuickBuildsCompleted; @@ -431,7 +431,7 @@ private: /** * The total amount of bricks collected by this character */ - uint64_t m_BricksCollected; + int64_t m_BricksCollected; /** * The total amount of entities smashed by this character From d64fa1680d707add7ce2a650e84c525e8dcfb9d4 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 30 Jul 2022 20:56:21 -0700 Subject: [PATCH 054/322] Fix missions re-ordering on reload (#686) * Fix missions re-ordering on reload Check for success rather than failure * Add a comment * Get base value from database * Update Mission.h --- dGame/dComponents/MissionComponent.cpp | 21 +++++++++++++++++---- dGame/dComponents/MissionComponent.h | 7 +++++++ dGame/dMission/Mission.cpp | 3 +++ dGame/dMission/Mission.h | 17 +++++++++++++++++ dZoneManager/dZoneManager.cpp | 9 +++++++++ dZoneManager/dZoneManager.h | 6 ++++++ 6 files changed, 59 insertions(+), 4 deletions(-) diff --git a/dGame/dComponents/MissionComponent.cpp b/dGame/dComponents/MissionComponent.cpp index ad77cf34..96f213e5 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -24,6 +24,7 @@ std::unordered_map> MissionComponent::m_Achievemen //! Initializer MissionComponent::MissionComponent(Entity* parent) : Component(parent) { + m_LastUsedMissionOrderUID = dZoneManager::Instance()->GetUniqueMissionIdStartingValue(); } //! Destructor @@ -83,6 +84,7 @@ void MissionComponent::AcceptMission(const uint32_t missionId, const bool skipCh if (mission != nullptr) { if (mission->GetClientInfo().repeatable) { mission->Accept(); + if (mission->IsMission()) mission->SetUniqueMissionOrderID(++m_LastUsedMissionOrderUID); } return; @@ -90,6 +92,8 @@ void MissionComponent::AcceptMission(const uint32_t missionId, const bool skipCh mission = new Mission(this, missionId); + if (mission->IsMission()) mission->SetUniqueMissionOrderID(++m_LastUsedMissionOrderUID); + mission->Accept(); this->m_Missions.insert_or_assign(missionId, mission); @@ -299,6 +303,8 @@ bool MissionComponent::LookForAchievements(MissionTaskType type, int32_t value, m_Missions.insert_or_assign(missionID, instance); + if (instance->IsMission()) instance->SetUniqueMissionOrderID(++m_LastUsedMissionOrderUID); + instance->Accept(); any = true; @@ -368,6 +374,8 @@ bool MissionComponent::LookForAchievements(MissionTaskType type, int32_t value, m_Missions.insert_or_assign(mission.id, instance); + if (instance->IsMission()) instance->SetUniqueMissionOrderID(++m_LastUsedMissionOrderUID); + instance->Accept(); any = true; @@ -523,6 +531,7 @@ void MissionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { auto* currentM = cur->FirstChildElement(); + uint32_t missionOrder{}; while (currentM) { int missionId; @@ -532,6 +541,11 @@ void MissionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { mission->LoadFromXml(currentM); + if (currentM->QueryAttribute("o", &missionOrder) == tinyxml2::XML_SUCCESS && mission->IsMission()) { + mission->SetUniqueMissionOrderID(missionOrder); + if (missionOrder > m_LastUsedMissionOrderUID) m_LastUsedMissionOrderUID = missionOrder; + } + currentM = currentM->NextSiblingElement(); m_Missions.insert_or_assign(missionId, mission); @@ -565,17 +579,16 @@ void MissionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { if (mission) { const auto complete = mission->IsComplete(); - if (complete) { - auto* m = doc->NewElement("m"); + auto* m = doc->NewElement("m"); + if (complete) { mission->UpdateXml(m); done->LinkEndChild(m); continue; } - - auto* m = doc->NewElement("m"); + if (mission->IsMission()) m->SetAttribute("o", mission->GetUniqueMissionOrderID()); mission->UpdateXml(m); diff --git a/dGame/dComponents/MissionComponent.h b/dGame/dComponents/MissionComponent.h index b4e53001..58185a68 100644 --- a/dGame/dComponents/MissionComponent.h +++ b/dGame/dComponents/MissionComponent.h @@ -193,6 +193,13 @@ private: * combination of tasks and values, so that they can be easily re-queried later */ static std::unordered_map> m_AchievementCache; + + /** + * Order of missions in the UI. This value is incremented by 1 + * for each mission the Entity that owns this component accepts. + * In live this value started at 745. + */ + uint32_t m_LastUsedMissionOrderUID = 746U; }; #endif // MISSIONCOMPONENT_H diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index bb02c4c8..6020e51c 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -26,6 +26,8 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { m_Timestamp = 0; + m_UniqueMissionID = dZoneManager::Instance()->GetUniqueMissionIdStartingValue(); + m_Reward = 0; m_State = MissionState::MISSION_STATE_UNKNOWN; @@ -283,6 +285,7 @@ void Mission::Accept() { void Mission::Complete(const bool yieldRewards) { if (m_State != MissionState::MISSION_STATE_ACTIVE && m_State != MissionState::MISSION_STATE_COMPLETE_ACTIVE) { + // If we are accepting a mission here there is no point to giving it a unique ID since we just complete it immediately. Accept(); } diff --git a/dGame/dMission/Mission.h b/dGame/dMission/Mission.h index 94920cba..43b2a96c 100644 --- a/dGame/dMission/Mission.h +++ b/dGame/dMission/Mission.h @@ -220,6 +220,18 @@ public: * @return true if the mission exists, false otherwise */ static bool IsValidMission(uint32_t missionId, CDMissions& info); + + /** + * @brief Returns the unique mission order ID + * + * @return The unique order ID + */ + uint32_t GetUniqueMissionOrderID() { return m_UniqueMissionID; }; + + /** + * Sets the unique mission order ID of this mission + */ + void SetUniqueMissionOrderID(uint32_t value) { m_UniqueMissionID = value; }; private: /** * Progresses all the newly accepted tasks for this mission after it has been accepted to reflect the state of the @@ -261,6 +273,11 @@ private: * All the tasks that can be progressed for this mission */ std::vector m_Tasks; + + /** + * The unique ID what order this mission was accepted in. + */ + uint32_t m_UniqueMissionID; }; #endif diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index 52d56f3c..102fb3af 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -240,3 +240,12 @@ std::vector dZoneManager::GetSpawnersInGroup(std::string group) { return spawnersInGroup; } + +uint32_t dZoneManager::GetUniqueMissionIdStartingValue() { + if (m_UniqueMissionIdStart == 0) { + auto tableData = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM Missions WHERE isMission = 0 GROUP BY isMission;"); + m_UniqueMissionIdStart = tableData.getIntField(0, -1); + tableData.finalize(); + } + return m_UniqueMissionIdStart; +} diff --git a/dZoneManager/dZoneManager.h b/dZoneManager/dZoneManager.h index 66e56820..b2fef1e3 100644 --- a/dZoneManager/dZoneManager.h +++ b/dZoneManager/dZoneManager.h @@ -43,6 +43,7 @@ public: void Update(float deltaTime); Entity* GetZoneControlObject() { return m_ZoneControlObject; } bool GetPlayerLoseCoinOnDeath() { return m_PlayerLoseCoinsOnDeath; } + uint32_t GetUniqueMissionIdStartingValue(); private: /** @@ -55,6 +56,11 @@ private: */ int32_t m_CurrencyConversionRate = 0; + /** + * The starting unique mission ID. + */ + uint32_t m_UniqueMissionIdStart = 0; + static dZoneManager* m_Address; //Singleton Zone* m_pZone; LWOZONEID m_ZoneID; From 0b9e97625e0414707cd39e5411758d14de0c25ea Mon Sep 17 00:00:00 2001 From: avery Date: Sat, 30 Jul 2022 22:09:45 -0700 Subject: [PATCH 055/322] Remove parentheses from ADD reporter_id --- migrations/dlu/2_reporter_id.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/migrations/dlu/2_reporter_id.sql b/migrations/dlu/2_reporter_id.sql index dc2a9a7e..26103342 100644 --- a/migrations/dlu/2_reporter_id.sql +++ b/migrations/dlu/2_reporter_id.sql @@ -1 +1 @@ -ALTER TABLE bug_reports ADD (reporter_id) INT NOT NULL DEFAULT 0; +ALTER TABLE bug_reports ADD reporter_id INT NOT NULL DEFAULT 0; From 7ec458421fd917bd617bdf7c3f4ecfc324497d9c Mon Sep 17 00:00:00 2001 From: Daniel Seiler Date: Sun, 31 Jul 2022 13:58:50 +0200 Subject: [PATCH 056/322] Create SECURITY.md --- SECURITY.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..c1126dba --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,51 @@ +# Security Policy + +## Supported Versions + +At the moment, only the latest commit on the `main` branch will be supported for security vulnerabilities. Private server operators +should keep their instances up to date and forks should regularily rebase on `main`. + +| Branch | Supported | +| ------- | ------------------ | +| `main` | :white_check_mark: | + +## Reporting a Vulnerability + +If you found a security vulnerability in DLU, please send a message to [darkflame-security@googlegroups.com][darkflame-security]. You should get a +reply within *72 hours* that we have received your report and a tentative [CVSS score](https://nvd.nist.gov/vuln-metrics/cvss/v3-calculator). +We will do a preliminary analysis to confirm that the vulnerability is a plausible claim and decline the report otherwise. + +If possible, please include + +1. reproducible steps on how to trigger the vulnerability +2. a description on why you are convinced that it exists. +3. any information you may have on active exploitation of the vulnerability (zero-day). + +## Security Advisories + +The project will release advisories on resolved vulnerabilities at + +## Receiving Security Updates + +We set up [darkflame-security-announce@googlegroups.com][darkflame-security-announce] for private server operators to receive updates on vulnerabilities +such as the release of [Security Advisories](#security-advisories) or early workarounds and recommendations to mitigate ongoing +vulnerabilities. + +Unfortunately, we cannot guarantee that announcements will be sent for every vulnerability. + +## Embargo + +We propose a 90 day (approx. 3 months) embargo on security vulnerabilities. That is, we ask everyone not to disclose the vulnerabilty +publicly until either: + +1. 90 days have passed from the time the first related email is sent to `darkflame-security@` +2. a security advisory related to the vulnerability has been published by the project. + +if you fail to comply with this embargo, you might be exluded from [receiving security updates](#receiving-security-updates). + +## Bug Bounty + +Unfortunately we cannot provide bug bounties at this time. + +[darkflame-security]: mailto:darkflame-security@googlegroups.com +[darkflame-security-announce]: mailto:darkflame-security-announce@googlegroups.com From e97dc6fbff9dbffd7cfac8f42ab23bc81080e1ec Mon Sep 17 00:00:00 2001 From: Daniel Seiler Date: Sun, 31 Jul 2022 14:06:05 +0200 Subject: [PATCH 057/322] [no ci] update link to darkflame-security-announce --- SECURITY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SECURITY.md b/SECURITY.md index c1126dba..aaa3fe07 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -48,4 +48,4 @@ if you fail to comply with this embargo, you might be exluded from [receiving se Unfortunately we cannot provide bug bounties at this time. [darkflame-security]: mailto:darkflame-security@googlegroups.com -[darkflame-security-announce]: mailto:darkflame-security-announce@googlegroups.com +[darkflame-security-announce]: https://groups.google.com/g/darkflame-security-announce From 17d77db1c63840c59b6e9acf95369baea79fb194 Mon Sep 17 00:00:00 2001 From: "Gie \"Max\" Vanommeslaeghe" Date: Sun, 31 Jul 2022 15:14:16 +0200 Subject: [PATCH 058/322] Update SECURITY.md --- SECURITY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SECURITY.md b/SECURITY.md index aaa3fe07..c4b40c5a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -41,7 +41,7 @@ publicly until either: 1. 90 days have passed from the time the first related email is sent to `darkflame-security@` 2. a security advisory related to the vulnerability has been published by the project. -if you fail to comply with this embargo, you might be exluded from [receiving security updates](#receiving-security-updates). +If you fail to comply with this embargo, you might be exluded from [receiving security updates](#receiving-security-updates). ## Bug Bounty From c11a4a67d19cc4ce8fa323b281d513fdd455e12d Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Mon, 1 Aug 2022 21:23:01 +0100 Subject: [PATCH 059/322] Replace the vsprintf used in the logger with vsnprintf. (#694) --- dCommon/dLogger.cpp | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/dCommon/dLogger.cpp b/dCommon/dLogger.cpp index 3a91e31d..d4e6a96e 100644 --- a/dCommon/dLogger.cpp +++ b/dCommon/dLogger.cpp @@ -26,13 +26,6 @@ dLogger::~dLogger() { } void dLogger::vLog(const char* format, va_list args) { - const char* tempPtr = format; // strlen_s implementation for Linux and Windows - for (; *tempPtr != '\0'; ++tempPtr) { - size_t size = tempPtr - format; - if (size > 600) { - return; - } - } #ifdef _WIN32 time_t t = time(NULL); struct tm time; @@ -40,7 +33,7 @@ void dLogger::vLog(const char* format, va_list args) { char timeStr[70]; strftime(timeStr, sizeof(timeStr), "%d-%m-%y %H:%M:%S", &time); char message[2048]; - vsprintf_s(message, format, args); + vsnprintf(message, 2048, format, args); if (m_logToConsole) std::cout << "[" << timeStr << "] " << message; mFile << "[" << timeStr << "] " << message; @@ -50,7 +43,7 @@ void dLogger::vLog(const char* format, va_list args) { char timeStr[70]; strftime(timeStr, sizeof(timeStr), "%d-%m-%y %H:%M:%S", time); char message[2048]; - vsprintf(message, format, args); + vsnprintf(message, 2048, format, args); if (m_logToConsole) { fputs("[", stdout); From a0aa8b28544dbd6ac3153caa3060eb7a94637f1a Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell Date: Mon, 1 Aug 2022 22:37:28 -0500 Subject: [PATCH 060/322] standardize line endings (#700) --- .gitattributes | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitattributes b/.gitattributes index 8218efdb..6313b56c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1 @@ -*.sh eol=lf \ No newline at end of file +* text=auto eol=lf From 9ee219ea42403466559b11da883f8ed5de45f2ec Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Tue, 2 Aug 2022 06:30:19 +0100 Subject: [PATCH 061/322] Move Navmesh code away from dPhysics (#701) --- CMakeLists.txt | 38 +-- dGame/dComponents/BaseCombatAIComponent.cpp | 2 +- dGame/dComponents/MovementAIComponent.cpp | 8 +- dGame/dComponents/PetComponent.cpp | 6 +- dGame/dUtilities/SlashCommandHandler.cpp | 2 +- dNavigation/CMakeLists.txt | 4 + dNavigation/DetourExtensions.h | 25 ++ dNavigation/dNavMesh.cpp | 228 +++++++++++++++++ dNavigation/dNavMesh.h | 38 +++ dPhysics/dpWorld.cpp | 269 ++------------------ dPhysics/dpWorld.h | 46 +--- dScripts/BaseEnemyMech.cpp | 2 +- dWorldServer/CMakeLists.txt | 4 +- 13 files changed, 349 insertions(+), 323 deletions(-) create mode 100644 dNavigation/CMakeLists.txt create mode 100644 dNavigation/DetourExtensions.h create mode 100644 dNavigation/dNavMesh.cpp create mode 100644 dNavigation/dNavMesh.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 65df9a35..cdc73d69 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,7 +14,7 @@ string(REPLACE "\n" ";" variables ${variables}) foreach(variable ${variables}) # If the string contains a #, skip it if(NOT "${variable}" MATCHES "#") - + # Split the variable into name and value string(REPLACE "=" ";" variable ${variable}) @@ -43,7 +43,7 @@ set(PROJECT_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT message(STATUS "Version: ${PROJECT_VERSION}") # Compiler flags: -# Disabled deprecated warnings as the MySQL includes have deprecated code in them. +# Disabled deprecated warnings as the MySQL includes have deprecated code in them. # Disabled misleading indentation as DL_LinkedList from RakNet has a weird indent. # Disabled no-register # Disabled unknown pragmas because Linux doesn't understand Windows pragmas. @@ -118,17 +118,18 @@ endforeach() set(INCLUDED_DIRECTORIES "dCommon" "dChatFilter" - "dGame" - "dGame/dBehaviors" - "dGame/dComponents" - "dGame/dGameMessages" - "dGame/dInventory" - "dGame/dMission" - "dGame/dEntity" - "dGame/dUtilities" - "dPhysics" - "dZoneManager" - "dDatabase" + "dGame" + "dGame/dBehaviors" + "dGame/dComponents" + "dGame/dGameMessages" + "dGame/dInventory" + "dGame/dMission" + "dGame/dEntity" + "dGame/dUtilities" + "dPhysics" + "dNavigation" + "dZoneManager" + "dDatabase" "dDatabase/Tables" "dNet" "dScripts" @@ -192,7 +193,7 @@ file( file( GLOB HEADERS_DGAME LIST_DIRECTORIES false - ${PROJECT_SOURCE_DIR}/dGame/Entity.h + ${PROJECT_SOURCE_DIR}/dGame/Entity.h ${PROJECT_SOURCE_DIR}/dGame/dGameMessages/GameMessages.h ${PROJECT_SOURCE_DIR}/dGame/EntityManager.h ${PROJECT_SOURCE_DIR}/dScripts/CppScripts.h @@ -206,6 +207,7 @@ add_subdirectory(dNet) add_subdirectory(dScripts) # Add for dGame to use add_subdirectory(dGame) add_subdirectory(dZoneManager) +add_subdirectory(dNavigation) add_subdirectory(dPhysics) # Create a list of common libraries shared between all binaries @@ -230,18 +232,18 @@ add_subdirectory(dMasterServer) # Add MasterServer last so it can rely on the ot # Add our precompiled headers target_precompile_headers( - dGame PRIVATE + dGame PRIVATE ${HEADERS_DGAME} ) target_precompile_headers( - dZoneManager PRIVATE + dZoneManager PRIVATE ${HEADERS_DZONEMANAGER} ) # Need to specify to use the CXX compiler language here or else we get errors including . target_precompile_headers( - dDatabase PRIVATE + dDatabase PRIVATE "$<$:${HEADERS_DDATABASE}>" ) @@ -253,4 +255,4 @@ target_precompile_headers( target_precompile_headers( tinyxml2 PRIVATE "$<$:${PROJECT_SOURCE_DIR}/thirdparty/tinyxml2/tinyxml2.h>" -) \ No newline at end of file +) diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 2ac2cf04..c035a807 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -654,7 +654,7 @@ void BaseCombatAIComponent::Wander() { auto destination = m_StartPosition + delta; if (dpWorld::Instance().IsLoaded()) { - destination.y = dpWorld::Instance().GetHeightAtPoint(destination); + destination.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(destination); } if (Vector3::DistanceSquared(destination, m_MovementAI->GetCurrentPosition()) < 2 * 2) { diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index 9c76b286..43231abf 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -196,7 +196,7 @@ NiPoint3 MovementAIComponent::ApproximateLocation() const { NiPoint3 approximation = NiPoint3(x, y, z); if (dpWorld::Instance().IsLoaded()) { - approximation.y = dpWorld::Instance().GetHeightAtPoint(approximation); + approximation.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(approximation); } return approximation; @@ -208,7 +208,7 @@ bool MovementAIComponent::Warp(const NiPoint3& point) { NiPoint3 destination = point; if (dpWorld::Instance().IsLoaded()) { - destination.y = dpWorld::Instance().GetHeightAtPoint(point); + destination.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(point); if (std::abs(destination.y - point.y) > 3) { return false; @@ -387,7 +387,7 @@ void MovementAIComponent::SetDestination(const NiPoint3& value) { std::vector computedPath; if (dpWorld::Instance().IsLoaded()) { - computedPath = dpWorld::Instance().GetPath(GetCurrentPosition(), value, m_Info.wanderSpeed); + computedPath = dpWorld::Instance().GetNavMesh()->GetPath(GetCurrentPosition(), value, m_Info.wanderSpeed); } else { // Than take 10 points between the current position and the destination and make that the path @@ -416,7 +416,7 @@ void MovementAIComponent::SetDestination(const NiPoint3& value) { // Simply path for (auto point : computedPath) { if (dpWorld::Instance().IsLoaded()) { - point.y = dpWorld::Instance().GetHeightAtPoint(point); + point.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(point); } m_CurrentPath.push_back(point); diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 42aceaf3..7e637ab7 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -267,14 +267,14 @@ void PetComponent::OnUse(Entity* originator) { if (dpWorld::Instance().IsLoaded()) { NiPoint3 attempt = petPosition + forward * interactionDistance; - float y = dpWorld::Instance().GetHeightAtPoint(attempt); + float y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(attempt); while (std::abs(y - petPosition.y) > 4 && interactionDistance > 10) { const NiPoint3 forward = m_Parent->GetRotation().GetForwardVector(); attempt = originatorPosition + forward * interactionDistance; - y = dpWorld::Instance().GetHeightAtPoint(attempt); + y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(attempt); interactionDistance -= 0.5f; } @@ -819,7 +819,7 @@ void PetComponent::Wander() { auto destination = m_StartPosition + delta; if (dpWorld::Instance().IsLoaded()) { - destination.y = dpWorld::Instance().GetHeightAtPoint(destination); + destination.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(destination); } if (Vector3::DistanceSquared(destination, m_MovementAI->GetCurrentPosition()) < 2 * 2) { diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 16cdddbb..6ef1632b 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -733,7 +733,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto control = static_cast(entity->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); if (!control) return; - float y = dpWorld::Instance().GetHeightAtPoint(control->GetPosition()); + float y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(control->GetPosition()); std::u16string msg = u"Navmesh height: " + (GeneralUtils::to_u16string(y)); ChatPackets::SendSystemMessage(sysAddr, msg); } diff --git a/dNavigation/CMakeLists.txt b/dNavigation/CMakeLists.txt new file mode 100644 index 00000000..beb498e3 --- /dev/null +++ b/dNavigation/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DNAVIGATION_SOURCES "dNavMesh.cpp") + +add_library(dNavigation STATIC ${DNAVIGATION_SOURCES}) +target_link_libraries(dNavigation detour recast) diff --git a/dNavigation/DetourExtensions.h b/dNavigation/DetourExtensions.h new file mode 100644 index 00000000..55d3e29c --- /dev/null +++ b/dNavigation/DetourExtensions.h @@ -0,0 +1,25 @@ +#pragma once + +#include "Recast.h" +#include "DetourCommon.h" +#include "DetourNavMesh.h" +#include "DetourNavMeshBuilder.h" +#include "DetourNavMeshQuery.h" + +static const int NAVMESHSET_MAGIC = 'M' << 24 | 'S' << 16 | 'E' << 8 | 'T'; // char[4] of 'MSET' +static const int NAVMESHSET_VERSION = 1; + +struct NavMeshSetHeader { + int magic; + int version; + int numTiles; + dtNavMeshParams params; +}; + +struct NavMeshTileHeader { + dtTileRef tileRef; + int dataSize; +}; + +static const int MAX_POLYS = 256; +static const int MAX_SMOOTH = 2048; diff --git a/dNavigation/dNavMesh.cpp b/dNavigation/dNavMesh.cpp new file mode 100644 index 00000000..da471882 --- /dev/null +++ b/dNavigation/dNavMesh.cpp @@ -0,0 +1,228 @@ +#include "dNavMesh.h" + +#include "Game.h" +#include "dLogger.h" +#include "dPlatforms.h" +#include "NiPoint3.h" +#include "BinaryIO.h" + +dNavMesh::dNavMesh(uint32_t zoneId) { + m_ZoneId = zoneId; + + this->LoadNavmesh(); + + if (m_NavMesh) { + m_NavQuery = dtAllocNavMeshQuery(); + m_NavQuery->init(m_NavMesh, 2048); + + Game::logger->Log("dNavMesh", "Navmesh loaded successfully!"); + } else { + Game::logger->Log("dNavMesh", "Navmesh loading failed (This may be intended)."); + } +} + +dNavMesh::~dNavMesh() { + // Clean up Recast information + + rcFreeHeightField(m_Solid); + rcFreeCompactHeightfield(m_CHF); + rcFreeContourSet(m_CSet); + rcFreePolyMesh(m_PMesh); + rcFreePolyMeshDetail(m_PMDMesh); + dtFreeNavMesh(m_NavMesh); + dtFreeNavMeshQuery(m_NavQuery); + + if (m_Ctx) delete m_Ctx; + if (m_Triareas) delete[] m_Triareas; +} + + +void dNavMesh::LoadNavmesh() { + + std::string path = "./res/maps/navmeshes/" + std::to_string(m_ZoneId) + ".bin"; + + if (!BinaryIO::DoesFileExist(path)) { + return; + } + + FILE* fp; + +#ifdef _WIN32 + fopen_s(&fp, path.c_str(), "rb"); +#elif __APPLE__ + // macOS has 64bit file IO by default + fp = fopen(path.c_str(), "rb"); +#else + fp = fopen64(path.c_str(), "rb"); +#endif + + if (!fp) { + return; + } + + // Read header. + NavMeshSetHeader header; + size_t readLen = fread(&header, sizeof(NavMeshSetHeader), 1, fp); + if (readLen != 1) { + fclose(fp); + return; + } + + if (header.magic != NAVMESHSET_MAGIC) { + fclose(fp); + return; + } + + if (header.version != NAVMESHSET_VERSION) { + fclose(fp); + return; + } + + dtNavMesh* mesh = dtAllocNavMesh(); + if (!mesh) { + fclose(fp); + return; + } + + dtStatus status = mesh->init(&header.params); + if (dtStatusFailed(status)) { + fclose(fp); + return; + } + + // Read tiles. + for (int i = 0; i < header.numTiles; ++i) { + NavMeshTileHeader tileHeader; + readLen = fread(&tileHeader, sizeof(tileHeader), 1, fp); + if (readLen != 1) return; + + if (!tileHeader.tileRef || !tileHeader.dataSize) + break; + + unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM); + if (!data) break; + memset(data, 0, tileHeader.dataSize); + readLen = fread(data, tileHeader.dataSize, 1, fp); + if (readLen != 1) return; + + mesh->addTile(data, tileHeader.dataSize, DT_TILE_FREE_DATA, tileHeader.tileRef, 0); + } + + fclose(fp); + + m_NavMesh = mesh; +} + +float dNavMesh::GetHeightAtPoint(const NiPoint3& location) { + if (m_NavMesh == nullptr) { + return location.y; + } + + float toReturn = 0.0f; + float pos[3]; + pos[0] = location.x; + pos[1] = location.y; + pos[2] = location.z; + + dtPolyRef nearestRef = 0; + float polyPickExt[3] = { 32.0f, 32.0f, 32.0f }; + dtQueryFilter filter{}; + + m_NavQuery->findNearestPoly(pos, polyPickExt, &filter, &nearestRef, 0); + m_NavQuery->getPolyHeight(nearestRef, pos, &toReturn); + + if (toReturn == 0.0f) { + toReturn = location.y; + } + + return toReturn; +} + +std::vector dNavMesh::GetPath(const NiPoint3& startPos, const NiPoint3& endPos, float speed) { + std::vector path; + + // Allows for non-navmesh maps (like new custom maps) to have "basic" enemies. + if (m_NavMesh == nullptr) { + // How many points to generate between start/end? + // Note: not actually 100% accurate due to rounding, but worst case it causes them to go a tiny bit faster + // than their speed value would normally allow at the end. + int numPoints = startPos.Distance(startPos, endPos) / speed; + + path.push_back(startPos); //insert the start pos + + // Linearly interpolate between these two points: + for (int i = 0; i < numPoints; i++) { + NiPoint3 newPoint{ startPos }; + + newPoint.x += speed; + newPoint.y = newPoint.y + (((endPos.y - startPos.y) / (endPos.x - startPos.x)) * (newPoint.x - startPos.x)); + + path.push_back(newPoint); + } + + path.push_back(endPos); //finally insert our end pos + + return path; + } + + float sPos[3]; + float ePos[3]; + sPos[0] = startPos.x; + sPos[1] = startPos.y; + sPos[2] = startPos.z; + + ePos[0] = endPos.x; + ePos[1] = endPos.y; + ePos[2] = endPos.z; + + dtStatus pathFindStatus; + dtPolyRef startRef; + dtPolyRef endRef; + float polyPickExt[3] = { 32.0f, 32.0f, 32.0f }; + dtQueryFilter filter{}; + + //Find our start poly + m_NavQuery->findNearestPoly(sPos, polyPickExt, &filter, &startRef, 0); + + //Find our end poly + m_NavQuery->findNearestPoly(ePos, polyPickExt, &filter, &endRef, 0); + + pathFindStatus = DT_FAILURE; + int m_nstraightPath = 0; + int m_npolys = 0; + dtPolyRef m_polys[MAX_POLYS]; + float m_straightPath[MAX_POLYS * 3]; + unsigned char m_straightPathFlags[MAX_POLYS]; + dtPolyRef m_straightPathPolys[MAX_POLYS]; + int m_straightPathOptions = 0; + + if (startRef && endRef) { + m_NavQuery->findPath(startRef, endRef, sPos, ePos, &filter, m_polys, &m_npolys, MAX_POLYS); + + if (m_npolys) { + // In case of partial path, make sure the end point is clamped to the last polygon. + float epos[3]; + dtVcopy(epos, ePos); + + if (m_polys[m_npolys - 1] != endRef) { + m_NavQuery->closestPointOnPoly(m_polys[m_npolys - 1], ePos, epos, 0); + } + + m_NavQuery->findStraightPath(sPos, epos, m_polys, m_npolys, + m_straightPath, m_straightPathFlags, + m_straightPathPolys, &m_nstraightPath, MAX_POLYS, m_straightPathOptions); + + // At this point we have our path. Copy it to the path store + int nIndex = 0; + for (int nVert = 0; nVert < m_nstraightPath; nVert++) { + NiPoint3 newPoint{ m_straightPath[nIndex++], m_straightPath[nIndex++], m_straightPath[nIndex++] }; + path.push_back(newPoint); + } + } + } else { + m_npolys = 0; + m_nstraightPath = 0; + } + + return path; +} diff --git a/dNavigation/dNavMesh.h b/dNavigation/dNavMesh.h new file mode 100644 index 00000000..09e9c895 --- /dev/null +++ b/dNavigation/dNavMesh.h @@ -0,0 +1,38 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "DetourExtensions.h" + +class NiPoint3; + +class dNavMesh { +public: + dNavMesh(uint32_t zoneId); + ~dNavMesh(); + + float GetHeightAtPoint(const NiPoint3& location); + std::vector GetPath(const NiPoint3& startPos, const NiPoint3& endPos, float speed = 10.0f); +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; + uint8_t m_NavMeshDrawFlags; + rcContext* m_Ctx = nullptr; +}; diff --git a/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index 666171c0..0a7e0df0 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -21,12 +21,9 @@ void dpWorld::Initialize(unsigned int zoneID) { m_Grid = new dpGrid(phys_sp_tilecount, phys_sp_tilesize); } - Game::logger->Log("dpWorld", "Physics world initialized!"); + m_NavMesh = new dNavMesh(zoneID); - if (ShouldLoadNavmesh(zoneID)) { - if (LoadNavmeshByZoneID(zoneID)) Game::logger->Log("dpWorld", "Loaded navmesh!"); - else Game::logger->Log("dpWorld", "Error(s) occurred during navmesh load."); - } + Game::logger->Log("dpWorld", "Physics world initialized!"); } dpWorld::~dpWorld() { @@ -35,7 +32,9 @@ dpWorld::~dpWorld() { m_Grid = nullptr; } - RecastCleanup(); + m_NavMesh->~dNavMesh(); + delete m_NavMesh; + m_NavMesh = nullptr; } void dpWorld::StepWorld(float deltaTime) { @@ -98,256 +97,20 @@ void dpWorld::RemoveEntity(dpEntity* entity) { } } -void dpWorld::RecastCleanup() { - if (m_triareas) delete[] m_triareas; - m_triareas = 0; - - rcFreeHeightField(m_solid); - m_solid = 0; - rcFreeCompactHeightfield(m_chf); - m_chf = 0; - rcFreeContourSet(m_cset); - m_cset = 0; - rcFreePolyMesh(m_pmesh); - m_pmesh = 0; - rcFreePolyMeshDetail(m_dmesh); - m_dmesh = 0; - dtFreeNavMesh(m_navMesh); - m_navMesh = 0; - - dtFreeNavMeshQuery(m_navQuery); - m_navQuery = 0; - - if (m_ctx) delete m_ctx; -} - -bool dpWorld::LoadNavmeshByZoneID(unsigned int zoneID) { - std::string path = "./res/maps/navmeshes/" + std::to_string(zoneID) + ".bin"; - m_navMesh = LoadNavmesh(path.c_str()); - - if (m_navMesh) { m_navQuery = dtAllocNavMeshQuery(); m_navQuery->init(m_navMesh, 2048); } else return false; - - return true; -} - -dtNavMesh* dpWorld::LoadNavmesh(const char* path) { - FILE* fp; - -#ifdef _WIN32 - fopen_s(&fp, path, "rb"); -#elif __APPLE__ - // macOS has 64bit file IO by default - fp = fopen(path, "rb"); -#else - fp = fopen64(path, "rb"); -#endif - - if (!fp) { - return 0; - } - - // Read header. - NavMeshSetHeader header; - size_t readLen = fread(&header, sizeof(NavMeshSetHeader), 1, fp); - if (readLen != 1) { - fclose(fp); - return 0; - } - - if (header.magic != NAVMESHSET_MAGIC) { - fclose(fp); - return 0; - } - - if (header.version != NAVMESHSET_VERSION) { - fclose(fp); - return 0; - } - - dtNavMesh* mesh = dtAllocNavMesh(); - if (!mesh) { - fclose(fp); - return 0; - } - - dtStatus status = mesh->init(&header.params); - if (dtStatusFailed(status)) { - fclose(fp); - return 0; - } - - // Read tiles. - for (int i = 0; i < header.numTiles; ++i) { - NavMeshTileHeader tileHeader; - readLen = fread(&tileHeader, sizeof(tileHeader), 1, fp); - if (readLen != 1) - return 0; - - if (!tileHeader.tileRef || !tileHeader.dataSize) - break; - - unsigned char* data = (unsigned char*)dtAlloc(tileHeader.dataSize, DT_ALLOC_PERM); - if (!data) break; - memset(data, 0, tileHeader.dataSize); - readLen = fread(data, tileHeader.dataSize, 1, fp); - if (readLen != 1) - return 0; - - mesh->addTile(data, tileHeader.dataSize, DT_TILE_FREE_DATA, tileHeader.tileRef, 0); - } - - fclose(fp); - - return mesh; -} - -bool dpWorld::ShouldLoadNavmesh(unsigned int zoneID) { - return true; //We use default paths now. Might re-tool this function later. - - //TODO: Add to this list as the navmesh folder grows. - switch (zoneID) { - case 1100: - case 1150: - case 1151: - case 1200: - case 1201: - case 1300: - case 1400: - case 1603: - return true; - } - - return false; -} - bool dpWorld::ShouldUseSP(unsigned int zoneID) { - //TODO: Add to this list as needed. Only large maps should be added as tiling likely makes little difference on small maps. + // TODO: Add to this list as needed. + // Only large maps should be added as tiling likely makes little difference on small maps. + switch (zoneID) { - case 1100: //Avant Gardens - case 1200: //Nimbus Station - case 1300: //Gnarled Forest - case 1400: //Forbidden Valley - case 1800: //Crux Prime - case 1900: //Nexus Tower - case 2000: //Ninjago - return true; + case 1100: // Avant Gardens + case 1200: // Nimbus Station + case 1300: // Gnarled Forest + case 1400: // Forbidden Valley + case 1800: // Crux Prime + case 1900: // Nexus Tower + case 2000: // Ninjago + return true; } return false; } - -float dpWorld::GetHeightAtPoint(const NiPoint3& location) { - if (m_navMesh == nullptr) { - return location.y; - } - - float toReturn = 0.0f; - float pos[3]; - pos[0] = location.x; - pos[1] = location.y; - pos[2] = location.z; - - dtPolyRef nearestRef = 0; - float polyPickExt[3] = { 32.0f, 32.0f, 32.0f }; - dtQueryFilter filter{}; - - m_navQuery->findNearestPoly(pos, polyPickExt, &filter, &nearestRef, 0); - m_navQuery->getPolyHeight(nearestRef, pos, &toReturn); - - if (toReturn == 0.0f) { - toReturn = location.y; - } - - return toReturn; -} - -std::vector dpWorld::GetPath(const NiPoint3& startPos, const NiPoint3& endPos, float speed) { - std::vector path; - - //allows for non-navmesh maps (like new custom maps) to have "basic" enemies. - if (m_navMesh == nullptr) { - //how many points to generate between start/end? - //note: not actually 100% accurate due to rounding, but worst case it causes them to go a tiny bit faster - //than their speed value would normally allow at the end. - int numPoints = startPos.Distance(startPos, endPos) / speed; - - path.push_back(startPos); //insert the start pos - - //Linearly interpolate between these two points: - for (int i = 0; i < numPoints; i++) { - NiPoint3 newPoint{ startPos }; - - newPoint.x += speed; - newPoint.y = newPoint.y + (((endPos.y - startPos.y) / (endPos.x - startPos.x)) * (newPoint.x - startPos.x)); - - path.push_back(newPoint); - } - - path.push_back(endPos); //finally insert our end pos - - return path; - } - - float sPos[3]; - float ePos[3]; - sPos[0] = startPos.x; - sPos[1] = startPos.y; - sPos[2] = startPos.z; - - ePos[0] = endPos.x; - ePos[1] = endPos.y; - ePos[2] = endPos.z; - - dtStatus pathFindStatus; - dtPolyRef startRef; - dtPolyRef endRef; - float polyPickExt[3] = { 32.0f, 32.0f, 32.0f }; - dtQueryFilter filter{}; - - //Find our start poly - m_navQuery->findNearestPoly(sPos, polyPickExt, &filter, &startRef, 0); - - //Find our end poly - m_navQuery->findNearestPoly(ePos, polyPickExt, &filter, &endRef, 0); - - pathFindStatus = DT_FAILURE; - int m_nstraightPath = 0; - int m_npolys = 0; - dtPolyRef m_polys[MAX_POLYS]; - float m_straightPath[MAX_POLYS * 3]; - unsigned char m_straightPathFlags[MAX_POLYS]; - dtPolyRef m_straightPathPolys[MAX_POLYS]; - int m_straightPathOptions = 0; - - if (startRef && endRef) { - m_navQuery->findPath(startRef, endRef, sPos, ePos, &filter, m_polys, &m_npolys, MAX_POLYS); - - if (m_npolys) { - // In case of partial path, make sure the end point is clamped to the last polygon. - float epos[3]; - dtVcopy(epos, ePos); - if (m_polys[m_npolys - 1] != endRef) - m_navQuery->closestPointOnPoly(m_polys[m_npolys - 1], ePos, epos, 0); - - m_navQuery->findStraightPath(sPos, epos, m_polys, m_npolys, - m_straightPath, m_straightPathFlags, - m_straightPathPolys, &m_nstraightPath, MAX_POLYS, m_straightPathOptions); - - // At this point we have our path. Copy it to the path store - int nIndex = 0; - for (int nVert = 0; nVert < m_nstraightPath; nVert++) { - /*m_PathStore[nPathSlot].PosX[nVert] = StraightPath[nIndex++]; - m_PathStore[nPathSlot].PosY[nVert] = StraightPath[nIndex++]; - m_PathStore[nPathSlot].PosZ[nVert] = StraightPath[nIndex++];*/ - - NiPoint3 newPoint{ m_straightPath[nIndex++], m_straightPath[nIndex++], m_straightPath[nIndex++] }; - path.push_back(newPoint); - } - } - } else { - m_npolys = 0; - m_nstraightPath = 0; - } - - return path; -} diff --git a/dPhysics/dpWorld.h b/dPhysics/dpWorld.h index 5362803f..9f13f7a9 100644 --- a/dPhysics/dpWorld.h +++ b/dPhysics/dpWorld.h @@ -1,6 +1,6 @@ #pragma once + #include "Singleton.h" -#include //Navmesh includes: #include "Recast.h" @@ -11,23 +11,7 @@ #include #include -static const int NAVMESHSET_MAGIC = 'M' << 24 | 'S' << 16 | 'E' << 8 | 'T'; //'MSET'; -static const int NAVMESHSET_VERSION = 1; - -struct NavMeshSetHeader { - int magic; - int version; - int numTiles; - dtNavMeshParams params; -}; - -struct NavMeshTileHeader { - dtTileRef tileRef; - int dataSize; -}; - -static const int MAX_POLYS = 256; -static const int MAX_SMOOTH = 2048; +#include "dNavMesh.h" class NiPoint3; class dpEntity; @@ -38,22 +22,17 @@ public: void Initialize(unsigned int zoneID); ~dpWorld(); - void RecastCleanup(); - bool LoadNavmeshByZoneID(unsigned int zoneID); - dtNavMesh* LoadNavmesh(const char* path); - bool ShouldLoadNavmesh(unsigned int zoneID); bool ShouldUseSP(unsigned int zoneID); - - float GetHeightAtPoint(const NiPoint3& location); - std::vector GetPath(const NiPoint3& startPos, const NiPoint3& endPos, float speed = 10.0f); - bool IsLoaded() const { return m_navMesh != nullptr; } + bool IsLoaded() const { return m_NavMesh != nullptr; } void StepWorld(float deltaTime); void AddEntity(dpEntity* entity); void RemoveEntity(dpEntity* entity); + dNavMesh* GetNavMesh() { return m_NavMesh; } + private: dpGrid* m_Grid; bool phys_spatial_partitioning = 1; @@ -63,18 +42,5 @@ private: std::vector m_StaticEntities; std::vector m_DynamicEntites; - //Navmesh stuffs: - unsigned char* m_triareas; - rcHeightfield* m_solid; - rcCompactHeightfield* m_chf; - rcContourSet* m_cset; - rcPolyMesh* m_pmesh; - rcConfig m_cfg; - rcPolyMeshDetail* m_dmesh; - - class InputGeom* m_geom; - class dtNavMesh* m_navMesh; - class dtNavMeshQuery* m_navQuery; - unsigned char m_navMeshDrawFlags; - rcContext* m_ctx; + dNavMesh* m_NavMesh; }; diff --git a/dScripts/BaseEnemyMech.cpp b/dScripts/BaseEnemyMech.cpp index 32dc38dd..8017be2c 100644 --- a/dScripts/BaseEnemyMech.cpp +++ b/dScripts/BaseEnemyMech.cpp @@ -17,7 +17,7 @@ void BaseEnemyMech::OnDie(Entity* self, Entity* killer) { ControllablePhysicsComponent* controlPhys = static_cast(self->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); if (!controlPhys) return; - NiPoint3 newLoc = { controlPhys->GetPosition().x, dpWorld::Instance().GetHeightAtPoint(controlPhys->GetPosition()), controlPhys->GetPosition().z }; + NiPoint3 newLoc = { controlPhys->GetPosition().x, dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(controlPhys->GetPosition()), controlPhys->GetPosition().z }; EntityInfo info = EntityInfo(); std::vector cfg; diff --git a/dWorldServer/CMakeLists.txt b/dWorldServer/CMakeLists.txt index 3df808a2..05338960 100644 --- a/dWorldServer/CMakeLists.txt +++ b/dWorldServer/CMakeLists.txt @@ -1,6 +1,6 @@ set(DWORLDSERVER_SOURCES "ObjectIDManager.cpp" "PerformanceManager.cpp" "WorldServer.cpp") - + add_executable(WorldServer ${DWORLDSERVER_SOURCES}) -target_link_libraries(WorldServer ${COMMON_LIBRARIES} dChatFilter dGame dZoneManager dPhysics detour recast tinyxml2) +target_link_libraries(WorldServer ${COMMON_LIBRARIES} dChatFilter dGame dZoneManager dPhysics detour recast tinyxml2 dNavigation) From a429489846d847c1457f49bbda793da4539357de Mon Sep 17 00:00:00 2001 From: Daniel Seiler Date: Tue, 2 Aug 2022 15:56:20 +0200 Subject: [PATCH 062/322] use UTF8ToUTF16 more (#695) --- dChatServer/ChatPacketHandler.cpp | 4 +- dChatServer/PlayerContainer.cpp | 12 ++--- dCommon/LDFFormat.cpp | 2 +- dDatabase/Tables/CDRailActivatorComponent.cpp | 23 +++------- dGame/LeaderboardManager.cpp | 2 +- dGame/dComponents/CharacterComponent.cpp | 4 +- dGame/dComponents/PetComponent.cpp | 20 ++++---- dGame/dGameMessages/GameMessages.cpp | 7 ++- dGame/dGameMessages/PropertyDataMessage.cpp | 8 ++-- .../PropertySelectQueryProperty.cpp | 6 +-- dGame/dUtilities/Mail.cpp | 6 +-- dGame/dUtilities/SlashCommandHandler.cpp | 46 ++++++++++--------- 12 files changed, 68 insertions(+), 72 deletions(-) diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index 83678525..b5db597f 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -599,7 +599,7 @@ void ChatPacketHandler::HandleTeamKick(Packet* packet) { if (kicked != nullptr) { kickedId = kicked->playerID; } else { - kickedId = playerContainer.GetId(GeneralUtils::ASCIIToUTF16(kickedPlayer)); + kickedId = playerContainer.GetId(GeneralUtils::UTF8ToUTF16(kickedPlayer)); } if (kickedId == LWOOBJID_EMPTY) return; @@ -690,7 +690,7 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) { playerContainer.TeamStatusUpdate(team); - const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(data->playerName.c_str())); + const auto leaderName = GeneralUtils::UTF8ToUTF16(data->playerName); for (const auto memberId : team->memberIDs) { auto* otherMember = playerContainer.GetPlayerData(memberId); diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index d8c2e067..6bf3ccd1 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -35,7 +35,7 @@ void PlayerContainer::InsertPlayer(Packet* packet) { inStream.Read(data->muteExpire); data->sysAddr = packet->systemAddress; - mNames[data->playerID] = GeneralUtils::ASCIIToUTF16(std::string(data->playerName.c_str())); + mNames[data->playerID] = GeneralUtils::UTF8ToUTF16(data->playerName); mPlayers.insert(std::make_pair(data->playerID, data)); Game::logger->Log("PlayerContainer", "Added user: %s (%llu), zone: %i", data->playerName.c_str(), data->playerID, data->zoneID.GetMapID()); @@ -71,7 +71,7 @@ void PlayerContainer::RemovePlayer(Packet* packet) { auto* team = GetTeam(playerID); if (team != nullptr) { - const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(player->playerName.c_str())); + const auto memberName = GeneralUtils::UTF8ToUTF16(std::string(player->playerName.c_str())); for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); @@ -221,8 +221,8 @@ void PlayerContainer::AddMember(TeamData* team, LWOOBJID playerID) { if (leader == nullptr || member == nullptr) return; - const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(leader->playerName.c_str())); - const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(member->playerName.c_str())); + const auto leaderName = GeneralUtils::UTF8ToUTF16(leader->playerName); + const auto memberName = GeneralUtils::UTF8ToUTF16(member->playerName); ChatPacketHandler::SendTeamInviteConfirm(member, false, leader->playerID, leader->zoneID, team->lootFlag, 0, 0, leaderName); @@ -309,7 +309,7 @@ void PlayerContainer::DisbandTeam(TeamData* team) { if (otherMember == nullptr) continue; - const auto memberName = GeneralUtils::ASCIIToUTF16(std::string(otherMember->playerName.c_str())); + const auto memberName = GeneralUtils::UTF8ToUTF16(otherMember->playerName); ChatPacketHandler::SendTeamSetLeader(otherMember, LWOOBJID_EMPTY); ChatPacketHandler::SendTeamRemovePlayer(otherMember, true, false, false, team->local, team->leaderID, otherMember->playerID, memberName); @@ -331,7 +331,7 @@ void PlayerContainer::TeamStatusUpdate(TeamData* team) { if (leader == nullptr) return; - const auto leaderName = GeneralUtils::ASCIIToUTF16(std::string(leader->playerName.c_str())); + const auto leaderName = GeneralUtils::UTF8ToUTF16(leader->playerName); for (const auto memberId : team->memberIDs) { auto* otherMember = GetPlayerData(memberId); diff --git a/dCommon/LDFFormat.cpp b/dCommon/LDFFormat.cpp index b6ea21a4..767ec81a 100644 --- a/dCommon/LDFFormat.cpp +++ b/dCommon/LDFFormat.cpp @@ -49,7 +49,7 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string& format) { switch (type) { case LDF_TYPE_UTF_16: { - std::u16string data = GeneralUtils::ASCIIToUTF16(dataArray[1]); + std::u16string data = GeneralUtils::UTF8ToUTF16(dataArray[1]); return new LDFData(key, data); } diff --git a/dDatabase/Tables/CDRailActivatorComponent.cpp b/dDatabase/Tables/CDRailActivatorComponent.cpp index ef72859b..4c141256 100644 --- a/dDatabase/Tables/CDRailActivatorComponent.cpp +++ b/dDatabase/Tables/CDRailActivatorComponent.cpp @@ -8,23 +8,12 @@ CDRailActivatorComponentTable::CDRailActivatorComponentTable() { entry.id = tableData.getIntField(0); - std::string startAnimation(tableData.getStringField(1, "")); - entry.startAnimation = GeneralUtils::ASCIIToUTF16(startAnimation); - - std::string loopAnimation(tableData.getStringField(2, "")); - entry.loopAnimation = GeneralUtils::ASCIIToUTF16(loopAnimation); - - std::string stopAnimation(tableData.getStringField(3, "")); - entry.stopAnimation = GeneralUtils::ASCIIToUTF16(stopAnimation); - - std::string startSound(tableData.getStringField(4, "")); - entry.startSound = GeneralUtils::ASCIIToUTF16(startSound); - - std::string loopSound(tableData.getStringField(5, "")); - entry.loopSound = GeneralUtils::ASCIIToUTF16(loopSound); - - std::string stopSound(tableData.getStringField(6, "")); - entry.stopSound = GeneralUtils::ASCIIToUTF16(stopSound); + entry.startAnimation = GeneralUtils::ASCIIToUTF16(tableData.getStringField(1, "")); + entry.loopAnimation = GeneralUtils::ASCIIToUTF16(tableData.getStringField(2, "")); + entry.stopAnimation = GeneralUtils::ASCIIToUTF16(tableData.getStringField(3, "")); + entry.startSound = GeneralUtils::ASCIIToUTF16(tableData.getStringField(4, "")); + entry.loopSound = GeneralUtils::ASCIIToUTF16(tableData.getStringField(5, "")); + entry.stopSound = GeneralUtils::ASCIIToUTF16(tableData.getStringField(6, "")); std::string loopEffectString(tableData.getStringField(7, "")); entry.loopEffectID = EffectPairFromString(loopEffectString); diff --git a/dGame/LeaderboardManager.cpp b/dGame/LeaderboardManager.cpp index 71a154bd..b069e761 100644 --- a/dGame/LeaderboardManager.cpp +++ b/dGame/LeaderboardManager.cpp @@ -45,7 +45,7 @@ std::u16string Leaderboard::ToString() const { index++; } - return GeneralUtils::ASCIIToUTF16(leaderboard); + return GeneralUtils::UTF8ToUTF16(leaderboard); } std::vector Leaderboard::GetEntries() { diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 3b4b8db8..42b8ed34 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -228,7 +228,7 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { const tinyxml2::XMLAttribute* rocketConfig = character->FindAttribute("lcbp"); if (rocketConfig) { - m_LastRocketConfig = GeneralUtils::ASCIIToUTF16(std::string(rocketConfig->Value())); + m_LastRocketConfig = GeneralUtils::ASCIIToUTF16(rocketConfig->Value()); } else { m_LastRocketConfig = u""; } @@ -262,7 +262,7 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { character->QueryInt64Attribute("gid", &gid); if (gid != 0) { std::string guildname(gn); - m_GuildName = GeneralUtils::ASCIIToUTF16(guildname); + m_GuildName = GeneralUtils::UTF8ToUTF16(guildname); m_GuildID = gid; m_DirtySocialInfo = true; } diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 7e637ab7..ef882555 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -121,8 +121,8 @@ void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpd if (tamed) { outBitStream->Write(m_ModerationStatus); - const auto nameData = GeneralUtils::ASCIIToUTF16(m_Name); - const auto ownerNameData = GeneralUtils::ASCIIToUTF16(m_OwnerName); + const auto nameData = GeneralUtils::UTF8ToUTF16(m_Name); + const auto ownerNameData = GeneralUtils::UTF8ToUTF16(m_OwnerName); outBitStream->Write(static_cast(nameData.size())); for (const auto c : nameData) { @@ -567,7 +567,7 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { std::string petName = tamer->GetCharacter()->GetName(); petName += "'s Pet"; - GameMessages::SendAddPetToPlayer(m_Tamer, 0, GeneralUtils::ASCIIToUTF16(petName), petSubKey, m_Parent->GetLOT(), tamer->GetSystemAddress()); + GameMessages::SendAddPetToPlayer(m_Tamer, 0, GeneralUtils::UTF8ToUTF16(petName), petSubKey, m_Parent->GetLOT(), tamer->GetSystemAddress()); GameMessages::SendRegisterPetID(m_Tamer, m_Parent->GetObjectID(), tamer->GetSystemAddress()); @@ -634,7 +634,7 @@ void PetComponent::RequestSetPetName(std::u16string name) { //Save our pet's new name to the db: SetPetNameForModeration(GeneralUtils::UTF16ToWTF8(name)); - GameMessages::SendSetPetName(m_Owner, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); + GameMessages::SendSetPetName(m_Owner, GeneralUtils::UTF8ToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); } @@ -665,9 +665,11 @@ void PetComponent::RequestSetPetName(std::u16string name) { EntityManager::Instance()->SerializeEntity(m_Parent); - GameMessages::SendSetPetName(m_Tamer, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, tamer->GetSystemAddress()); - GameMessages::SendSetPetName(m_Tamer, GeneralUtils::ASCIIToUTF16(m_Name), LWOOBJID_EMPTY, tamer->GetSystemAddress()); - GameMessages::SendPetNameChanged(m_Parent->GetObjectID(), m_ModerationStatus, GeneralUtils::ASCIIToUTF16(m_Name), GeneralUtils::ASCIIToUTF16(m_OwnerName), UNASSIGNED_SYSTEM_ADDRESS); + std::u16string u16name = GeneralUtils::UTF8ToUTF16(m_Name); + std::u16string u16ownerName = GeneralUtils::UTF8ToUTF16(m_OwnerName); + GameMessages::SendSetPetName(m_Tamer, u16name, m_DatabaseId, tamer->GetSystemAddress()); + GameMessages::SendSetPetName(m_Tamer, u16name, LWOOBJID_EMPTY, tamer->GetSystemAddress()); + GameMessages::SendPetNameChanged(m_Parent->GetObjectID(), m_ModerationStatus, u16name, u16ownerName, UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendSetPetNameModerated(m_Tamer, m_DatabaseId, m_ModerationStatus, tamer->GetSystemAddress()); GameMessages::SendNotifyPetTamingMinigame( @@ -877,7 +879,7 @@ void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) { m_OwnerName = owner->GetCharacter()->GetName(); if (updatedModerationStatus) { - GameMessages::SendSetPetName(m_Owner, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); + GameMessages::SendSetPetName(m_Owner, GeneralUtils::UTF8ToUTF16(m_Name), m_DatabaseId, owner->GetSystemAddress()); GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); } @@ -892,7 +894,7 @@ void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) { owner->GetCharacter()->SetPlayerFlag(69, true); if (registerPet) { - GameMessages::SendAddPetToPlayer(m_Owner, 0, GeneralUtils::ASCIIToUTF16(m_Name), m_DatabaseId, m_Parent->GetLOT(), owner->GetSystemAddress()); + GameMessages::SendAddPetToPlayer(m_Owner, 0, GeneralUtils::UTF8ToUTF16(m_Name), m_DatabaseId, m_Parent->GetLOT(), owner->GetSystemAddress()); GameMessages::SendRegisterPetID(m_Owner, m_Parent->GetObjectID(), owner->GetSystemAddress()); diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index f4546416..1b98381a 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -978,6 +978,8 @@ void GameMessages::SendSetNetworkScriptVar(Entity* entity, const SystemAddress& bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_SET_NETWORK_SCRIPT_VAR); + // FIXME: this is a bad place to need to do a conversion because we have no clue whether data is utf8 or plain ascii + // an this has performance implications const auto u16Data = GeneralUtils::ASCIIToUTF16(data); uint32_t dataSize = static_cast(u16Data.size()); @@ -3188,7 +3190,7 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* i64Invitee, bNeedInvitePopUp, entity->GetObjectID(), - GeneralUtils::ASCIIToUTF16(entity->GetCharacter()->GetName()), + GeneralUtils::UTF8ToUTF16(entity->GetCharacter()->GetName()), invitee->GetSystemAddress() ); } @@ -5086,7 +5088,8 @@ void GameMessages::HandleNotifyServerLevelProcessingComplete(RakNet::BitStream* wss << "name=0:"; wss << character->GetName(); - std::u16string attrs = GeneralUtils::ASCIIToUTF16(wss.str()); + // FIXME: only really need utf8 conversion for the name, so move that up? + std::u16string attrs = GeneralUtils::UTF8ToUTF16(wss.str()); std::u16string wsText = u"UI_LEVEL_PROGRESSION_LEVELUP_MESSAGE"; GameMessages::SendBroadcastTextToChatbox(entity, UNASSIGNED_SYSTEM_ADDRESS, attrs, wsText); diff --git a/dGame/dGameMessages/PropertyDataMessage.cpp b/dGame/dGameMessages/PropertyDataMessage.cpp index 853151c9..c30285fd 100644 --- a/dGame/dGameMessages/PropertyDataMessage.cpp +++ b/dGame/dGameMessages/PropertyDataMessage.cpp @@ -14,19 +14,19 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con stream.Write(VendorMapId); // - vendor map id stream.Write(cloneId); // clone id - const auto& name = GeneralUtils::ASCIIToUTF16(Name); + const auto& name = GeneralUtils::UTF8ToUTF16(Name); stream.Write(uint32_t(name.size())); for (uint32_t i = 0; i < name.size(); ++i) { stream.Write(uint16_t(name[i])); } - const auto& description = GeneralUtils::ASCIIToUTF16(Description); + const auto& description = GeneralUtils::UTF8ToUTF16(Description); stream.Write(uint32_t(description.size())); for (uint32_t i = 0; i < description.size(); ++i) { stream.Write(uint16_t(description[i])); } - const auto& owner = GeneralUtils::ASCIIToUTF16(OwnerName); + const auto& owner = GeneralUtils::UTF8ToUTF16(OwnerName); stream.Write(uint32_t(owner.size())); for (uint32_t i = 0; i < owner.size(); ++i) { stream.Write(uint16_t(owner[i])); @@ -68,7 +68,7 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con else stream.Write(REJECTION_STATUS_PENDING); // Does this go here??? - // const auto& rejectionReasonConverted = GeneralUtils::ASCIIToUTF16(rejectionReason); + // const auto& rejectionReasonConverted = GeneralUtils::UTF8ToUTF16(rejectionReason); // stream.Write(uint32_t(rejectionReasonConverted.size())); // for (uint32_t i = 0; i < rejectionReasonConverted.size(); ++i) { // stream.Write(uint16_t(rejectionReasonConverted[i])); diff --git a/dGame/dGameMessages/PropertySelectQueryProperty.cpp b/dGame/dGameMessages/PropertySelectQueryProperty.cpp index 18d23d2b..cd17a58b 100644 --- a/dGame/dGameMessages/PropertySelectQueryProperty.cpp +++ b/dGame/dGameMessages/PropertySelectQueryProperty.cpp @@ -3,19 +3,19 @@ void PropertySelectQueryProperty::Serialize(RakNet::BitStream& stream) const { stream.Write(CloneId); - const auto& owner = GeneralUtils::ASCIIToUTF16(OwnerName); + const auto& owner = GeneralUtils::UTF8ToUTF16(OwnerName); stream.Write(uint32_t(owner.size())); for (uint32_t i = 0; i < owner.size(); ++i) { stream.Write(static_cast(owner[i])); } - const auto& name = GeneralUtils::ASCIIToUTF16(Name); + const auto& name = GeneralUtils::UTF8ToUTF16(Name); stream.Write(uint32_t(name.size())); for (uint32_t i = 0; i < name.size(); ++i) { stream.Write(static_cast(name[i])); } - const auto& description = GeneralUtils::ASCIIToUTF16(Description); + const auto& description = GeneralUtils::UTF8ToUTF16(Description); stream.Write(uint32_t(description.size())); for (uint32_t i = 0; i < description.size(); ++i) { stream.Write(static_cast(description[i])); diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index 59ce8444..8280b627 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -290,9 +290,9 @@ void Mail::HandleDataRequest(RakNet::BitStream* packet, const SystemAddress& sys while (res->next()) { bitStream.Write(res->getUInt64(1)); //MailID - /*std::u16string subject = GeneralUtils::ASCIIToUTF16(res->getString(7)); - std::u16string body = GeneralUtils::ASCIIToUTF16(res->getString(8)); - std::u16string sender = GeneralUtils::ASCIIToUTF16(res->getString(3)); + /*std::u16string subject = GeneralUtils::UTF8ToUTF16(res->getString(7)); + std::u16string body = GeneralUtils::UTF8ToUTF16(res->getString(8)); + std::u16string sender = GeneralUtils::UTF8ToUTF16(res->getString(3)); WriteToPacket(&bitStream, subject, 50); WriteToPacket(&bitStream, body, 400); diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 6ef1632b..0bf37288 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -173,7 +173,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit std::stringstream message; message << character->GetName() << " changed their PVP flag to " << std::to_string(character->GetPvpEnabled()) << "!"; - ChatPackets::SendSystemMessage(UNASSIGNED_SYSTEM_ADDRESS, GeneralUtils::ASCIIToUTF16(message.str()), true); + ChatPackets::SendSystemMessage(UNASSIGNED_SYSTEM_ADDRESS, GeneralUtils::UTF8ToUTF16(message.str()), true); return; } @@ -189,7 +189,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage( sysAddr, - GeneralUtils::ASCIIToUTF16(player == entity ? name + " (you)" : name) + GeneralUtils::UTF8ToUTF16(player == entity ? name + " (you)" : name) ); } } @@ -678,6 +678,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } + // FIXME: use fallible ASCIIToUTF16 conversion, because non-ascii isn't valid anyway GameMessages::SendPlayFXEffect(entity->GetObjectID(), effectID, GeneralUtils::ASCIIToUTF16(args[1]), args[2]); } @@ -829,7 +830,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit name += arg + " "; } - GameMessages::SendSetName(entity->GetObjectID(), GeneralUtils::ASCIIToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendSetName(entity->GetObjectID(), GeneralUtils::UTF8ToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); } if (chatCommand == "title" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { @@ -839,7 +840,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit name += arg + " "; } - GameMessages::SendSetName(entity->GetObjectID(), GeneralUtils::ASCIIToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendSetName(entity->GetObjectID(), GeneralUtils::UTF8ToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); } if ((chatCommand == "teleport" || chatCommand == "tele") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_JUNIOR_MODERATOR) { @@ -971,7 +972,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit delete result; if (accountId == 0) { - ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::ASCIIToUTF16(args[0])); + ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::UTF8ToUTF16(args[0])); return; } @@ -1023,7 +1024,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit const auto timeStr = GeneralUtils::ASCIIToUTF16(std::string(buffer)); - ChatPackets::SendSystemMessage(sysAddr, u"Muted: " + GeneralUtils::ASCIIToUTF16(args[0]) + u" until " + timeStr); + ChatPackets::SendSystemMessage(sysAddr, u"Muted: " + GeneralUtils::UTF8ToUTF16(args[0]) + u" until " + timeStr); //Notify chat about it CBITSTREAM; @@ -1042,15 +1043,15 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (args.size() == 1) { auto* player = Player::GetPlayer(args[0]); + std::u16string username = GeneralUtils::UTF8ToUTF16(args[0]); if (player == nullptr) { - ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::ASCIIToUTF16(args[0])); - + ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + username); return; } Game::server->Disconnect(player->GetSystemAddress(), SERVER_DISCON_KICK); - ChatPackets::SendSystemMessage(sysAddr, u"Kicked: " + GeneralUtils::ASCIIToUTF16(args[0])); + ChatPackets::SendSystemMessage(sysAddr, u"Kicked: " + username); } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /kick "); } @@ -1077,7 +1078,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit delete result; if (accountId == 0) { - ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::ASCIIToUTF16(args[0])); + ChatPackets::SendSystemMessage(sysAddr, u"Count not find player of name: " + GeneralUtils::UTF8ToUTF16(args[0])); return; } @@ -1165,7 +1166,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit while (!tables.eof()) { std::string message = std::to_string(tables.getIntField(0)) + " - " + tables.getStringField(1); - ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(message, message.size())); + ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::UTF8ToUTF16(message, message.size())); tables.nextRow(); } } @@ -1222,12 +1223,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto requestedPlayer = Player::GetPlayer(requestedPlayerToSetLevelOf); if (!requestedPlayer) { - ChatPackets::SendSystemMessage(sysAddr, u"No player found with username: (" + GeneralUtils::ASCIIToUTF16(requestedPlayerToSetLevelOf) + u")."); + ChatPackets::SendSystemMessage(sysAddr, u"No player found with username: (" + GeneralUtils::UTF8ToUTF16(requestedPlayerToSetLevelOf) + u")."); return; } if (!requestedPlayer->GetOwner()) { - ChatPackets::SendSystemMessage(sysAddr, u"No entity found with username: (" + GeneralUtils::ASCIIToUTF16(requestedPlayerToSetLevelOf) + u")."); + ChatPackets::SendSystemMessage(sysAddr, u"No entity found with username: (" + GeneralUtils::UTF8ToUTF16(requestedPlayerToSetLevelOf) + u")."); return; } @@ -1269,7 +1270,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (requestedPlayerToSetLevelOf != "") { ChatPackets::SendSystemMessage( - sysAddr, u"Set " + GeneralUtils::ASCIIToUTF16(requestedPlayerToSetLevelOf) + u"'s level to " + GeneralUtils::to_u16string(requestedLevel) + + sysAddr, u"Set " + GeneralUtils::UTF8ToUTF16(requestedPlayerToSetLevelOf) + u"'s level to " + GeneralUtils::to_u16string(requestedLevel) + u" and UScore to " + GeneralUtils::to_u16string(characterComponent->GetUScore()) + u". Relog to see changes."); } else { @@ -1437,8 +1438,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit }); } else { std::string msg = "ZoneID not found or allowed: "; - msg.append(args[0]); - ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(msg, msg.size())); + msg.append(args[0]); // FIXME: unnecessary utf16 re-encoding just for error + ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::UTF8ToUTF16(msg, msg.size())); } } @@ -1572,17 +1573,18 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameConfig::SetValue(args[0], args[1]); ChatPackets::SendSystemMessage( - sysAddr, u"Set config value: " + GeneralUtils::ASCIIToUTF16(args[0]) + u" to " + GeneralUtils::ASCIIToUTF16(args[1]) + sysAddr, u"Set config value: " + GeneralUtils::UTF8ToUTF16(args[0]) + u" to " + GeneralUtils::UTF8ToUTF16(args[1]) ); } if (chatCommand == "config-get" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { const auto& value = GameConfig::GetValue(args[0]); + std::u16string u16key = GeneralUtils::UTF8ToUTF16(args[0]); if (value.empty()) { - ChatPackets::SendSystemMessage(sysAddr, u"No value found for " + GeneralUtils::ASCIIToUTF16(args[0])); + ChatPackets::SendSystemMessage(sysAddr, u"No value found for " + u16key); } else { - ChatPackets::SendSystemMessage(sysAddr, u"Value for " + GeneralUtils::ASCIIToUTF16(args[0]) + u": " + GeneralUtils::ASCIIToUTF16(value)); + ChatPackets::SendSystemMessage(sysAddr, u"Value for " + u16key + u": " + GeneralUtils::UTF8ToUTF16(value)); } } @@ -1672,7 +1674,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (!GeneralUtils::TryParse(args[0], component)) { component = -1; - ldf = GeneralUtils::ASCIIToUTF16(args[0]); + ldf = GeneralUtils::UTF8ToUTF16(args[0]); isLDF = true; } @@ -1755,10 +1757,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit EntityManager::Instance()->SerializeEntity(closest); } else if (args[1] == "-a" && args.size() >= 3) { - GameMessages::SendPlayAnimation(closest, GeneralUtils::ASCIIToUTF16(args[2])); + GameMessages::SendPlayAnimation(closest, GeneralUtils::UTF8ToUTF16(args[2])); } else if (args[1] == "-s") { for (auto* entry : closest->GetSettings()) { - ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(entry->GetString())); + ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::UTF8ToUTF16(entry->GetString())); } ChatPackets::SendSystemMessage(sysAddr, u"------"); From d2b05a1ac51f4e11421d92053b476766c4f35d82 Mon Sep 17 00:00:00 2001 From: Daniel Seiler Date: Tue, 2 Aug 2022 15:56:50 +0200 Subject: [PATCH 063/322] Update Diagnostics.cpp (#697) --- dCommon/Diagnostics.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dCommon/Diagnostics.cpp b/dCommon/Diagnostics.cpp index bfde2d9a..4c2c8beb 100644 --- a/dCommon/Diagnostics.cpp +++ b/dCommon/Diagnostics.cpp @@ -142,12 +142,12 @@ void CatchUnhandled(int sig) { demangled = demangle(functionName.c_str()); if (demangled.empty()) { - printf("[%02d] %s\n", i, demangled.c_str()); + printf("[%02zu] %s\n", i, demangled.c_str()); } else { - printf("[%02d] %s\n", i, functionName.c_str()); + printf("[%02zu] %s\n", i, functionName.c_str()); } } else { - printf("[%02d] %s\n", i, functionName.c_str()); + printf("[%02zu] %s\n", i, functionName.c_str()); } } #else From e6c7f744b5530ef1bdd50f7ba4548b452efcd676 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Thu, 4 Aug 2022 01:59:47 +0100 Subject: [PATCH 064/322] Implement terrain file reading to generate navmeshes in the future (#703) * Implement terrain file reading to generate navmeshes in the future * Make Emo's suggested changes. --- CMakeLists.txt | 1 + dNavigation/CMakeLists.txt | 6 ++ dNavigation/dNavMesh.cpp | 4 ++ dNavigation/dTerrain/CMakeLists.txt | 3 + dNavigation/dTerrain/RawChunk.cpp | 92 +++++++++++++++++++++++++++ dNavigation/dTerrain/RawChunk.h | 24 +++++++ dNavigation/dTerrain/RawFile.cpp | 82 ++++++++++++++++++++++++ dNavigation/dTerrain/RawFile.h | 27 ++++++++ dNavigation/dTerrain/RawHeightMap.cpp | 27 ++++++++ dNavigation/dTerrain/RawHeightMap.h | 21 ++++++ dNavigation/dTerrain/RawMesh.h | 10 +++ dWorldServer/WorldServer.cpp | 2 +- dZoneManager/Zone.h | 2 + 13 files changed, 300 insertions(+), 1 deletion(-) create mode 100644 dNavigation/dTerrain/CMakeLists.txt create mode 100644 dNavigation/dTerrain/RawChunk.cpp create mode 100644 dNavigation/dTerrain/RawChunk.h create mode 100644 dNavigation/dTerrain/RawFile.cpp create mode 100644 dNavigation/dTerrain/RawFile.h create mode 100644 dNavigation/dTerrain/RawHeightMap.cpp create mode 100644 dNavigation/dTerrain/RawHeightMap.h create mode 100644 dNavigation/dTerrain/RawMesh.h diff --git a/CMakeLists.txt b/CMakeLists.txt index cdc73d69..6acca4d8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -128,6 +128,7 @@ set(INCLUDED_DIRECTORIES "dGame/dUtilities" "dPhysics" "dNavigation" + "dNavigation/dTerrain" "dZoneManager" "dDatabase" "dDatabase/Tables" diff --git a/dNavigation/CMakeLists.txt b/dNavigation/CMakeLists.txt index beb498e3..5891c77d 100644 --- a/dNavigation/CMakeLists.txt +++ b/dNavigation/CMakeLists.txt @@ -1,4 +1,10 @@ set(DNAVIGATION_SOURCES "dNavMesh.cpp") +add_subdirectory(dTerrain) + +foreach(file ${DNAVIGATIONS_DTERRAIN_SOURCES}) + set(DNAVIGATION_SOURCES ${DNAVIGATION_SOURCES} "dTerrain/${file}") +endforeach() + add_library(dNavigation STATIC ${DNAVIGATION_SOURCES}) target_link_libraries(dNavigation detour recast) diff --git a/dNavigation/dNavMesh.cpp b/dNavigation/dNavMesh.cpp index da471882..c0bbf4b2 100644 --- a/dNavigation/dNavMesh.cpp +++ b/dNavigation/dNavMesh.cpp @@ -1,11 +1,15 @@ #include "dNavMesh.h" +#include "RawFile.h" + #include "Game.h" #include "dLogger.h" #include "dPlatforms.h" #include "NiPoint3.h" #include "BinaryIO.h" +#include "dZoneManager.h" + dNavMesh::dNavMesh(uint32_t zoneId) { m_ZoneId = zoneId; diff --git a/dNavigation/dTerrain/CMakeLists.txt b/dNavigation/dTerrain/CMakeLists.txt new file mode 100644 index 00000000..91d0741b --- /dev/null +++ b/dNavigation/dTerrain/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DNAVIGATIONS_DTERRAIN_SOURCES "RawFile.cpp" + "RawChunk.cpp" + "RawHeightMap.cpp" PARENT_SCOPE) diff --git a/dNavigation/dTerrain/RawChunk.cpp b/dNavigation/dTerrain/RawChunk.cpp new file mode 100644 index 00000000..e4f753cd --- /dev/null +++ b/dNavigation/dTerrain/RawChunk.cpp @@ -0,0 +1,92 @@ +#include "RawChunk.h" + +#include "BinaryIO.h" + +#include "RawMesh.h" +#include "RawHeightMap.h" + +RawChunk::RawChunk(std::ifstream& stream) { + // Read the chunk index and info + + BinaryIO::BinaryRead(stream, m_ChunkIndex); + BinaryIO::BinaryRead(stream, m_Width); + BinaryIO::BinaryRead(stream, m_Height); + BinaryIO::BinaryRead(stream, m_X); + BinaryIO::BinaryRead(stream, m_Z); + + m_HeightMap = new RawHeightMap(stream, m_Height, m_Width); + + // We can just skip the rest of the data so we can read the next chunks, we don't need anymore data + + uint32_t colorMapSize; + BinaryIO::BinaryRead(stream, colorMapSize); + stream.seekg((uint32_t)stream.tellg() + (colorMapSize * colorMapSize * 4)); + + uint32_t lightmapSize; + BinaryIO::BinaryRead(stream, lightmapSize); + stream.seekg((uint32_t)stream.tellg() + (lightmapSize)); + + uint32_t colorMapSize2; + BinaryIO::BinaryRead(stream, colorMapSize2); + stream.seekg((uint32_t)stream.tellg() + (colorMapSize2 * colorMapSize2 * 4)); + + uint8_t unknown; + BinaryIO::BinaryRead(stream, unknown); + + uint32_t blendmapSize; + BinaryIO::BinaryRead(stream, blendmapSize); + stream.seekg((uint32_t)stream.tellg() + (blendmapSize)); + + uint32_t pointSize; + BinaryIO::BinaryRead(stream, pointSize); + stream.seekg((uint32_t)stream.tellg() + (pointSize * 9 * 4)); + + stream.seekg((uint32_t)stream.tellg() + (colorMapSize * colorMapSize)); + + uint32_t endCounter; + BinaryIO::BinaryRead(stream, endCounter); + stream.seekg((uint32_t)stream.tellg() + (endCounter * 2)); + + if (endCounter != 0) { + stream.seekg((uint32_t)stream.tellg() + (32)); + + for (int i = 0; i < 0x10; i++) { + uint16_t finalCountdown; + BinaryIO::BinaryRead(stream, finalCountdown); + stream.seekg((uint32_t)stream.tellg() + (finalCountdown * 2)); + } + } + + // Generate our mesh/geo data for this chunk + + this->GenerateMesh(); +} + +RawChunk::~RawChunk() { + if (m_Mesh) delete m_Mesh; + if (m_HeightMap) delete m_HeightMap; +} + +void RawChunk::GenerateMesh() { + RawMesh* meshData = new RawMesh(); + + for (int i = 0; i < m_Width; ++i) { + for (int j = 0; j < m_Height; ++j) { + float y = *std::next(m_HeightMap->m_FloatMap.begin(), m_Width * i + j); + + meshData->m_Vertices.push_back(NiPoint3(i, y, j)); + + if (i == 0 || j == 0) continue; + + meshData->m_Triangles.push_back(m_Width * i + j); + meshData->m_Triangles.push_back(m_Width * i + j - 1); + meshData->m_Triangles.push_back(m_Width * (i - 1) + j - 1); + + meshData->m_Triangles.push_back(m_Width * (i - 1) + j - 1); + meshData->m_Triangles.push_back(m_Width * (i - 1) + j); + meshData->m_Triangles.push_back(m_Width * i + j); + } + } + + m_Mesh = meshData; +} diff --git a/dNavigation/dTerrain/RawChunk.h b/dNavigation/dTerrain/RawChunk.h new file mode 100644 index 00000000..1e26f11d --- /dev/null +++ b/dNavigation/dTerrain/RawChunk.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include + +struct RawMesh; +class RawHeightMap; + +class RawChunk { +public: + RawChunk(std::ifstream& stream); + ~RawChunk(); + + void GenerateMesh(); + + uint32_t m_ChunkIndex; + uint32_t m_Width; + uint32_t m_Height; + float m_X; + float m_Z; + + RawHeightMap* m_HeightMap; + RawMesh* m_Mesh; +}; diff --git a/dNavigation/dTerrain/RawFile.cpp b/dNavigation/dTerrain/RawFile.cpp new file mode 100644 index 00000000..d4496b2f --- /dev/null +++ b/dNavigation/dTerrain/RawFile.cpp @@ -0,0 +1,82 @@ +#include "RawFile.h" + +#include "BinaryIO.h" +#include "RawChunk.h" +#include "RawMesh.h" +#include "RawHeightMap.h" + +RawFile::RawFile(std::string fileName) { + if (!BinaryIO::DoesFileExist(fileName)) return; + + std::ifstream file(fileName, std::ios::binary); + + // Read header + + BinaryIO::BinaryRead(file, m_Version); + BinaryIO::BinaryRead(file, m_Padding); + BinaryIO::BinaryRead(file, m_ChunkCount); + BinaryIO::BinaryRead(file, m_Width); + BinaryIO::BinaryRead(file, m_Height); + + + if (m_Version < 0x20) { + return; // Version too crusty to handle + } + + // Read in chunks + + m_Chunks = {}; + + for (uint32_t i = 0; i < m_ChunkCount; i++) { + RawChunk* chunk = new RawChunk(file); + m_Chunks.push_back(chunk); + } + + this->GenerateFinalMeshFromChunks(); +} + +RawFile::~RawFile() { + delete m_FinalMesh; + for (const auto* item : m_Chunks) { + delete item; + } +} + +void RawFile::GenerateFinalMeshFromChunks() { + uint32_t lenOfLastChunk = 0; // index of last vert set in the last chunk + + for (const auto& chunk : m_Chunks) { + for (const auto& vert : chunk->m_Mesh->m_Vertices) { + auto tempVert = vert; + + tempVert.SetX(tempVert.GetX() + (chunk->m_X / 4)); + tempVert.SetZ(tempVert.GetZ() + (chunk->m_Z / 4)); + + tempVert* chunk->m_HeightMap->m_ScaleFactor; + + m_FinalMesh->m_Vertices.push_back(tempVert); + } + + for (const auto& tri : chunk->m_Mesh->m_Triangles) { + m_FinalMesh->m_Triangles.push_back(tri + lenOfLastChunk); + } + + lenOfLastChunk += chunk->m_Mesh->m_Vertices.size(); + } +} + +void RawFile::WriteFinalMeshToOBJ(std::string path) { + std::ofstream file(path); + std::string vertData; + + for (const auto& v : m_FinalMesh->m_Vertices) { + vertData += "v " + std::to_string(v.x) + " " + std::to_string(v.y) + " " + std::to_string(v.z) + "\n"; + } + + for (int i = 0; i < m_FinalMesh->m_Triangles.size(); i += 3) { + vertData += "f " + std::to_string(*std::next(m_FinalMesh->m_Triangles.begin(), i) + 1) + " " + std::to_string(*std::next(m_FinalMesh->m_Triangles.begin(), i + 1) + 1) + " " + std::to_string(*std::next(m_FinalMesh->m_Triangles.begin(), i + 2) + 1) + "\n"; + } + + file.write(vertData.c_str(), vertData.size()); + file.close(); +} diff --git a/dNavigation/dTerrain/RawFile.h b/dNavigation/dTerrain/RawFile.h new file mode 100644 index 00000000..84afae94 --- /dev/null +++ b/dNavigation/dTerrain/RawFile.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include + +class RawChunk; +struct RawMesh; + +class RawFile { +public: + RawFile(std::string filePath); + ~RawFile(); + +private: + + void GenerateFinalMeshFromChunks(); + void WriteFinalMeshToOBJ(std::string path); + + uint8_t m_Version; + uint16_t m_Padding; + uint32_t m_ChunkCount; + uint32_t m_Width; + uint32_t m_Height; + + std::vector m_Chunks; + RawMesh* m_FinalMesh; +}; diff --git a/dNavigation/dTerrain/RawHeightMap.cpp b/dNavigation/dTerrain/RawHeightMap.cpp new file mode 100644 index 00000000..e1310669 --- /dev/null +++ b/dNavigation/dTerrain/RawHeightMap.cpp @@ -0,0 +1,27 @@ +#include "RawHeightMap.h" + +#include "BinaryIO.h" + +RawHeightMap::RawHeightMap() {} + +RawHeightMap::RawHeightMap(std::ifstream& stream, float height, float width) { + // Read in height map data header and scale + + BinaryIO::BinaryRead(stream, m_Unknown1); + BinaryIO::BinaryRead(stream, m_Unknown2); + BinaryIO::BinaryRead(stream, m_Unknown3); + BinaryIO::BinaryRead(stream, m_Unknown4); + BinaryIO::BinaryRead(stream, m_ScaleFactor); + + // read all vertices in + + for (uint64_t i = 0; i < width * height; i++) { + float value; + BinaryIO::BinaryRead(stream, value); + m_FloatMap.push_back(value); + } +} + +RawHeightMap::~RawHeightMap() { + +} diff --git a/dNavigation/dTerrain/RawHeightMap.h b/dNavigation/dTerrain/RawHeightMap.h new file mode 100644 index 00000000..9a4bda3b --- /dev/null +++ b/dNavigation/dTerrain/RawHeightMap.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include +#include + +class RawHeightMap { +public: + RawHeightMap(); + RawHeightMap(std::ifstream& stream, float height, float width); + ~RawHeightMap(); + + uint32_t m_Unknown1; + uint32_t m_Unknown2; + uint32_t m_Unknown3; + uint32_t m_Unknown4; + + float m_ScaleFactor; + + std::vector m_FloatMap = {}; +}; diff --git a/dNavigation/dTerrain/RawMesh.h b/dNavigation/dTerrain/RawMesh.h new file mode 100644 index 00000000..ed8eb4f3 --- /dev/null +++ b/dNavigation/dTerrain/RawMesh.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +#include "NiPoint3.h" + +struct RawMesh { + std::vector m_Vertices; + std::vector m_Triangles; +}; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index df5484fd..74c730f6 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -233,9 +233,9 @@ int main(int argc, char** argv) { //Load our level: if (zoneID != 0) { + dZoneManager::Instance()->Initialize(LWOZONEID(zoneID, instanceID, cloneID)); dpWorld::Instance().Initialize(zoneID); Game::physicsWorld = &dpWorld::Instance(); //just in case some old code references it - dZoneManager::Instance()->Initialize(LWOZONEID(zoneID, instanceID, cloneID)); g_CloneID = cloneID; // pre calculate the FDB checksum diff --git a/dZoneManager/Zone.h b/dZoneManager/Zone.h index 5d3dc424..50530273 100644 --- a/dZoneManager/Zone.h +++ b/dZoneManager/Zone.h @@ -190,6 +190,8 @@ public: uint32_t GetWorldID() const { return m_WorldID; } [[nodiscard]] std::string GetZoneName() const { return m_ZoneName; } + std::string GetZoneRawPath() const { return m_ZoneRawPath;} + std::string GetZonePath() const { return m_ZonePath; } const NiPoint3& GetSpawnPos() const { return m_Spawnpoint; } const NiQuaternion& GetSpawnRot() const { return m_SpawnpointRotation; } From 88f316bf93228a847ddfd03180a63091ef6e01cd Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Thu, 4 Aug 2022 14:54:14 +0100 Subject: [PATCH 065/322] Add null checks to all free calls to prevent crash on server close. (#709) --- dNavigation/dNavMesh.cpp | 14 +++++++------- dPhysics/dpWorld.cpp | 7 ++++--- dPhysics/dpWorld.h | 2 +- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/dNavigation/dNavMesh.cpp b/dNavigation/dNavMesh.cpp index c0bbf4b2..b3c8a229 100644 --- a/dNavigation/dNavMesh.cpp +++ b/dNavigation/dNavMesh.cpp @@ -28,13 +28,13 @@ dNavMesh::dNavMesh(uint32_t zoneId) { dNavMesh::~dNavMesh() { // Clean up Recast information - rcFreeHeightField(m_Solid); - rcFreeCompactHeightfield(m_CHF); - rcFreeContourSet(m_CSet); - rcFreePolyMesh(m_PMesh); - rcFreePolyMeshDetail(m_PMDMesh); - dtFreeNavMesh(m_NavMesh); - dtFreeNavMeshQuery(m_NavQuery); + 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/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index 0a7e0df0..510da518 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -32,9 +32,10 @@ dpWorld::~dpWorld() { m_Grid = nullptr; } - m_NavMesh->~dNavMesh(); - delete m_NavMesh; - m_NavMesh = nullptr; + if (m_NavMesh) { + delete m_NavMesh; + m_NavMesh = nullptr; + } } void dpWorld::StepWorld(float deltaTime) { diff --git a/dPhysics/dpWorld.h b/dPhysics/dpWorld.h index 9f13f7a9..3878cd12 100644 --- a/dPhysics/dpWorld.h +++ b/dPhysics/dpWorld.h @@ -42,5 +42,5 @@ private: std::vector m_StaticEntities; std::vector m_DynamicEntites; - dNavMesh* m_NavMesh; + dNavMesh* m_NavMesh = nullptr; }; From 4556f1347443e227e2b154980271f391a4104957 Mon Sep 17 00:00:00 2001 From: aequabit Date: Fri, 5 Aug 2022 10:04:45 +0200 Subject: [PATCH 066/322] Mention option to use Docker in README.md (#702) --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 9acd9abf..403f14a4 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,9 @@ This was done make sure that older and incomplete clients wouldn't produce false If you're using a DLU client you'll have to go into the "CMakeVariables.txt" file and change the NET_VERSION variable to 171023 to match the modified client's version number. +### Using Docker +Refer to [Docker.md](/Docker.md). + ### Linux builds Make sure packages like `gcc`, `cmake`, and `zlib` are installed. Depending on the distribution, these packages might already be installed. Note that on systems like Ubuntu, you will need the `zlib1g-dev` package so that the header files are available. `libssl-dev` will also be required as well as `openssl`. From 408163ed3578a59733fd468192d8b6cca3fd6b54 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 5 Aug 2022 05:40:27 -0700 Subject: [PATCH 067/322] Add windows docker setup guide to README (#712) * Add docker windows * Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 403f14a4..321e1b36 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,8 @@ If you're using a DLU client you'll have to go into the "CMakeVariables.txt" fil ### Using Docker Refer to [Docker.md](/Docker.md). +For Windows, refer to [Docker_Windows.md](/Docker_Windows.md). + ### Linux builds Make sure packages like `gcc`, `cmake`, and `zlib` are installed. Depending on the distribution, these packages might already be installed. Note that on systems like Ubuntu, you will need the `zlib1g-dev` package so that the header files are available. `libssl-dev` will also be required as well as `openssl`. From 4112a85906f4dc5f55693c0f444a797a2cf80bcb Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Fri, 5 Aug 2022 13:41:07 +0100 Subject: [PATCH 068/322] Fix checks for if the physics world is loaded (#711) --- dNavigation/dNavMesh.h | 3 +++ dPhysics/dpWorld.h | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/dNavigation/dNavMesh.h b/dNavigation/dNavMesh.h index 09e9c895..dc3db854 100644 --- a/dNavigation/dNavMesh.h +++ b/dNavigation/dNavMesh.h @@ -17,6 +17,9 @@ public: float GetHeightAtPoint(const NiPoint3& location); std::vector GetPath(const NiPoint3& startPos, const NiPoint3& endPos, float speed = 10.0f); + + class dtNavMesh* GetdtNavMesh() { return m_NavMesh; } + private: void LoadNavmesh(); diff --git a/dPhysics/dpWorld.h b/dPhysics/dpWorld.h index 3878cd12..45e550cb 100644 --- a/dPhysics/dpWorld.h +++ b/dPhysics/dpWorld.h @@ -24,7 +24,7 @@ public: ~dpWorld(); bool ShouldUseSP(unsigned int zoneID); - bool IsLoaded() const { return m_NavMesh != nullptr; } + bool IsLoaded() const { return m_NavMesh->GetdtNavMesh() != nullptr; } void StepWorld(float deltaTime); From 9e4ce24fd2851e65df776dd9c57bcb0d45f4453a Mon Sep 17 00:00:00 2001 From: Aaron Kimbre Date: Fri, 5 Aug 2022 08:40:12 -0500 Subject: [PATCH 069/322] add semi-colons to macros consistently --- dChatServer/ChatPacketHandler.cpp | 24 +- dGame/dGameMessages/GameMessageHandler.cpp | 6 +- dGame/dGameMessages/GameMessages.cpp | 542 ++++++++++----------- dNet/ChatPackets.cpp | 10 +- dNet/MasterPackets.cpp | 4 +- dNet/WorldPackets.cpp | 30 +- dWorldServer/WorldServer.cpp | 4 +- tests/AMFDeserializeTests.cpp | 44 +- 8 files changed, 332 insertions(+), 332 deletions(-) diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index b5db597f..a51716ca 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -730,9 +730,9 @@ void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeader bitStream.Write(receiver->playerID); //portion that will get routed: - CMSGHEADER + CMSGHEADER; - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_INVITE_CONFIRM); bitStream.Write(bLeaderIsFreeTrial); @@ -757,9 +757,9 @@ void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderI bitStream.Write(receiver->playerID); //portion that will get routed: - CMSGHEADER + CMSGHEADER; - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_GET_STATUS_RESPONSE); bitStream.Write(i64LeaderID); @@ -782,9 +782,9 @@ void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64Play bitStream.Write(receiver->playerID); //portion that will get routed: - CMSGHEADER + CMSGHEADER; - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_SET_LEADER); bitStream.Write(i64PlayerID); @@ -799,9 +799,9 @@ void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTria bitStream.Write(receiver->playerID); //portion that will get routed: - CMSGHEADER + CMSGHEADER; - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_ADD_PLAYER); bitStream.Write(bIsFreeTrial); @@ -828,9 +828,9 @@ void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband bitStream.Write(receiver->playerID); //portion that will get routed: - CMSGHEADER + CMSGHEADER; - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_REMOVE_PLAYER); bitStream.Write(bDisband); @@ -854,9 +854,9 @@ void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i bitStream.Write(receiver->playerID); //portion that will get routed: - CMSGHEADER + CMSGHEADER; - bitStream.Write(receiver->playerID); + bitStream.Write(receiver->playerID); bitStream.Write(GAME_MSG::GAME_MSG_TEAM_SET_OFF_WORLD_FLAG); bitStream.Write(i64PlayerID); diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index b9115e50..b3b60fe7 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -31,10 +31,10 @@ using namespace std; void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, GAME_MSG messageID) { - CBITSTREAM + CBITSTREAM; - // Get the entity - Entity* entity = EntityManager::Instance()->GetEntity(objectID); + // Get the entity + Entity* entity = EntityManager::Instance()->GetEntity(objectID); User* usr = UserManager::Instance()->GetUser(sysAddr); diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 1b98381a..105bb526 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -69,10 +69,10 @@ #include "TradingManager.h" void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_FIRE_EVENT_CLIENT_SIDE); //bitStream.Write(args); @@ -88,13 +88,13 @@ void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const Syste //bitStream.Write(param2); bitStream.Write(sender); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendTeleport(const LWOOBJID& objectID, const NiPoint3& pos, const NiQuaternion& rot, const SystemAddress& sysAddr, bool bSetRotation, bool noGravTeleport) { - CBITSTREAM - CMSGHEADER - bitStream.Write(objectID); + CBITSTREAM; + CMSGHEADER; + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_TELEPORT); bool bIgnoreY = (pos.y == 0.0f); @@ -121,7 +121,7 @@ void GameMessages::SendTeleport(const LWOOBJID& objectID, const NiPoint3& pos, c bitStream.Write(rot.y); bitStream.Write(rot.z); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendPlayAnimation(Entity* entity, const std::u16string& animationName, float fPriority, float fScale) { @@ -171,8 +171,8 @@ void GameMessages::SendPlayerReady(Entity* entity, const SystemAddress& sysAddr) } void GameMessages::SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptRespawn, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER; + CBITSTREAM; + CMSGHEADER; bitStream.Write(entityID); bitStream.Write(GAME_MSG::GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN); @@ -182,10 +182,10 @@ void GameMessages::SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptR } void GameMessages::SendInvalidZoneTransferList(Entity* entity, const SystemAddress& sysAddr, const std::u16string& feedbackURL, const std::u16string& invalidMapTransferList, bool feedbackOnExit, bool feedbackOnInvalidTransfer) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_INVALID_ZONE_TRANSFER_LIST); uint32_t CustomerFeedbackURLLength = feedbackURL.size(); @@ -203,14 +203,14 @@ void GameMessages::SendInvalidZoneTransferList(Entity* entity, const SystemAddre bitStream.Write(feedbackOnExit); bitStream.Write(feedbackOnInvalidTransfer); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendKnockback(const LWOOBJID& objectID, const LWOOBJID& caster, const LWOOBJID& originator, int knockBackTimeMS, const NiPoint3& vector) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG_KNOCKBACK); bool casterFlag = caster != LWOOBJID_EMPTY; @@ -225,7 +225,7 @@ void GameMessages::SendKnockback(const LWOOBJID& objectID, const LWOOBJID& caste if (knockBackTimeMSFlag) bitStream.Write(knockBackTimeMS); bitStream.Write(vector); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendStartArrangingWithItem( @@ -243,10 +243,10 @@ void GameMessages::SendStartArrangingWithItem( NiPoint3 targetPOS, int targetTYPE ) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_START_ARRANGING_WITH_ITEM); bitStream.Write(bFirstTime); @@ -262,15 +262,15 @@ void GameMessages::SendStartArrangingWithItem( bitStream.Write(targetPOS); bitStream.Write(targetTYPE); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, const SystemAddress& sysAddr, bool bAllowCyclingWhileDeadOnly, eCyclingMode cyclingMode) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG_PLAYER_SET_CAMERA_CYCLING_MODE); bitStream.Write(bAllowCyclingWhileDeadOnly); @@ -280,14 +280,14 @@ void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, cons bitStream.Write(cyclingMode); } - SEND_PACKET + SEND_PACKET; } void GameMessages::SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& sysAddr, std::string audioGUID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY_ND_AUDIO_EMITTER); bitStream.Write0(); bitStream.Write0(); @@ -309,7 +309,7 @@ void GameMessages::SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& s bitStream.Write0(); bitStream.Write0(); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendStartPathing(Entity* entity) { @@ -325,10 +325,10 @@ void GameMessages::SendStartPathing(Entity* entity) { void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAddr, bool bStopAtDesiredWaypoint, int iIndex, int iDesiredWaypointIndex, int nextIndex, MovementPlatformState movementState) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - const auto lot = entity->GetLOT(); + const auto lot = entity->GetLOT(); if (lot == 12341 || lot == 5027 || lot == 5028 || lot == 14335 || lot == 14447 || lot == 14449) { iDesiredWaypointIndex = 0; @@ -373,49 +373,49 @@ void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAd bitStream.Write(qUnexpectedRotation.w); } - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendRestoreToPostLoadStats(Entity* entity, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER - bitStream.Write(entity->GetObjectID()); + CBITSTREAM; + CMSGHEADER; + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_RESTORE_TO_POST_LOAD_STATS); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendServerDoneLoadingAllObjects(Entity* entity, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER - bitStream.Write(entity->GetObjectID()); + CBITSTREAM; + CMSGHEADER; + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_SERVER_DONE_LOADING_ALL_OBJECTS); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level) { - CBITSTREAM - CMSGHEADER - bitStream.Write(objectID); + CBITSTREAM; + CMSGHEADER; + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_UPDATE_CHAT_MODE); bitStream.Write(level); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level) { - CBITSTREAM - CMSGHEADER - bitStream.Write(objectID); + CBITSTREAM; + CMSGHEADER; + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_SET_GM_LEVEL); bitStream.Write1(); bitStream.Write(level); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const SystemAddress& sysAddr, Item* item, const LWOOBJID& objectID, bool showFlyingLoot, int itemCount, LWOOBJID subKey, eLootSourceType lootSourceType) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(static_cast(GAME_MSG_ADD_ITEM_TO_INVENTORY_CLIENT_SYNC)); bitStream.Write(item->GetBound()); bitStream.Write(item->GetInfo().isBOE); @@ -467,31 +467,31 @@ void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const System bitStream.Write(showFlyingLoot); bitStream.Write(item->GetSlot()); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFlagID, bool bFlag, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_NOTIFY_CLIENT_FLAG_CHANGE); bitStream.Write(bFlag); bitStream.Write(iFlagID); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendChangeObjectWorldState(const LWOOBJID& objectID, int state, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_CHANGE_OBJECT_WORLD_STATE); bitStream.Write(state); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST - SEND_PACKET + SEND_PACKET; } void GameMessages::SendOfferMission(const LWOOBJID& entity, const SystemAddress& sysAddr, int32_t missionID, const LWOOBJID& offererID) { @@ -501,47 +501,47 @@ void GameMessages::SendOfferMission(const LWOOBJID& entity, const SystemAddress& //The second, actually makes the UI pop up so you can be offered the mission. //Why is it like this? Because LU isn't just a clown, it's the entire circus. - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(offererID); + bitStream.Write(offererID); bitStream.Write(uint16_t(GAME_MSG_OFFER_MISSION)); bitStream.Write(missionID); bitStream.Write(offererID); - SEND_PACKET + SEND_PACKET; { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; bitStream.Write(entity); bitStream.Write(uint16_t(GAME_MSG_OFFER_MISSION)); bitStream.Write(missionID); bitStream.Write(offererID); - SEND_PACKET + SEND_PACKET; } } void GameMessages::SendNotifyMission(Entity* entity, const SystemAddress& sysAddr, int missionID, int missionState, bool sendingRewards) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_NOTIFY_MISSION)); bitStream.Write(missionID); bitStream.Write(missionState); bitStream.Write(sendingRewards); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendNotifyMissionTask(Entity* entity, const SystemAddress& sysAddr, int missionID, int taskMask, std::vector updates) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_NOTIFY_MISSION_TASK); bitStream.Write(missionID); @@ -552,28 +552,28 @@ void GameMessages::SendNotifyMissionTask(Entity* entity, const SystemAddress& sy bitStream.Write(updates[i]); } - SEND_PACKET + SEND_PACKET; } void GameMessages::SendModifyLEGOScore(Entity* entity, const SystemAddress& sysAddr, int64_t score, eLootSourceType sourceType) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_MODIFY_LEGO_SCORE); bitStream.Write(score); bitStream.Write(sourceType != eLootSourceType::LOOT_SOURCE_NONE); if (sourceType != eLootSourceType::LOOT_SOURCE_NONE) bitStream.Write(sourceType); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendUIMessageServerToSingleClient(Entity* entity, const SystemAddress& sysAddr, const std::string& message, NDGFxValue args) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_UI_MESSAGE_SERVER_TO_SINGLE_CLIENT); bitStream.Write(args); @@ -584,7 +584,7 @@ void GameMessages::SendUIMessageServerToSingleClient(Entity* entity, const Syste bitStream.Write(static_cast(message[k])); } - SEND_PACKET + SEND_PACKET; } void GameMessages::SendUIMessageServerToAllClients(const std::string& message, NDGFxValue args) { @@ -607,10 +607,10 @@ void GameMessages::SendUIMessageServerToAllClients(const std::string& message, N } void GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(Entity* entity, std::u16string effectName, const LWOOBJID& fromObjectID, float radius) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY_EMBEDDED_EFFECT_ON_ALL_CLIENTS_NEAR_OBJECT); bitStream.Write(static_cast(effectName.length())); @@ -620,7 +620,7 @@ void GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(Entity* entity, bitStream.Write(fromObjectID); bitStream.Write(radius); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendPlayFXEffect(Entity* entity, int32_t effectID, const std::u16string& effectType, const std::string& name, LWOOBJID secondary, float priority, float scale, bool serialize) { @@ -658,28 +658,28 @@ void GameMessages::SendPlayFXEffect(const LWOOBJID& entity, int32_t effectID, co bitStream.Write(serialize); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendStopFXEffect(Entity* entity, bool killImmediate, std::string name) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_STOP_FX_EFFECT); bitStream.Write(killImmediate); bitStream.Write(name.size()); bitStream.Write(name.c_str(), name.size()); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendBroadcastTextToChatbox(Entity* entity, const SystemAddress& sysAddr, const std::u16string& attrs, const std::u16string& wsText) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG::GAME_MSG_BROADCAST_TEXT_TO_CHATBOX); LWONameValue attribs; @@ -698,14 +698,14 @@ void GameMessages::SendBroadcastTextToChatbox(Entity* entity, const SystemAddres bitStream.Write(static_cast(wsText[k])); } - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendSetCurrency(Entity* entity, int64_t currency, int lootType, const LWOOBJID& sourceID, const LOT& sourceLOT, int sourceTradeID, bool overrideCurrent, eLootSourceType sourceType) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_CURRENCY)); bitStream.Write(currency); @@ -728,28 +728,28 @@ void GameMessages::SendSetCurrency(Entity* entity, int64_t currency, int lootTyp if (sourceType != LOOTTYPE_NONE) bitStream.Write(sourceType); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendRebuildNotifyState(Entity* entity, int prevState, int state, const LWOOBJID& playerID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_REBUILD_NOTIFY_STATE); bitStream.Write(prevState); bitStream.Write(state); bitStream.Write(playerID); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, bool success, int failReason, float duration, const LWOOBJID& playerID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_ENABLE_REBUILD); bitStream.Write(enable); @@ -762,27 +762,27 @@ void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, boo bitStream.Write(duration); bitStream.Write(playerID); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendTerminateInteraction(const LWOOBJID& objectID, eTerminateType type, const LWOOBJID& terminator) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG_TERMINATE_INTERACTION); bitStream.Write(terminator); bitStream.Write(type); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendDieNoImplCode(Entity* entity, const LWOOBJID& killerID, const LWOOBJID& lootOwnerID, eKillType killType, std::u16string deathType, float directionRelative_AngleY, float directionRelative_AngleXZ, float directionRelative_Force, bool bClientDeath, bool bSpawnLoot) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_DIE)); bitStream.Write(bClientDeath); bitStream.Write(bSpawnLoot); @@ -797,7 +797,7 @@ void GameMessages::SendDieNoImplCode(Entity* entity, const LWOOBJID& killerID, c bitStream.Write(killerID); bitStream.Write(lootOwnerID); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendDie(Entity* entity, const LWOOBJID& killerID, const LWOOBJID& lootOwnerID, bool bDieAccepted, eKillType killType, std::u16string deathType, float directionRelative_AngleY, float directionRelative_AngleXZ, float directionRelative_Force, bool bClientDeath, bool bSpawnLoot, float coinSpawnTime) { @@ -838,29 +838,29 @@ void GameMessages::SendDie(Entity* entity, const LWOOBJID& killerID, const LWOOB } void GameMessages::SendSetInventorySize(Entity* entity, int invType, int size) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_INVENTORY_SIZE)); bitStream.Write(invType); bitStream.Write(size); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendSetEmoteLockState(Entity* entity, bool bLock, int emoteID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_EMOTE_LOCK_STATE)); bitStream.Write(bLock); bitStream.Write(emoteID); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendSetJetPackMode(Entity* entity, bool use, bool bypassChecks, bool doHover, int effectID, float airspeed, float maxAirspeed, float verticalVelocity, int warningEffectID) { @@ -872,10 +872,10 @@ void GameMessages::SendSetJetPackMode(Entity* entity, bool use, bool bypassCheck } */ - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(uint16_t(GAME_MSG_SET_JET_PACK_MODE)); bitStream.Write(bypassChecks); @@ -897,7 +897,7 @@ void GameMessages::SendSetJetPackMode(Entity* entity, bool use, bool bypassCheck bitStream.Write(warningEffectID != -1); if (warningEffectID != -1) bitStream.Write(warningEffectID); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendResurrect(Entity* entity) { @@ -930,10 +930,10 @@ void GameMessages::SendResurrect(Entity* entity) { } void GameMessages::SendStop2DAmbientSound(Entity* entity, bool force, std::string audioGUID, bool result) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY2_DAMBIENT_SOUND); uint32_t audioGUIDSize = audioGUID.size(); @@ -949,14 +949,14 @@ void GameMessages::SendStop2DAmbientSound(Entity* entity, bool force, std::strin SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendPlay2DAmbientSound(Entity* entity, std::string audioGUID, bool result) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_PLAY2_DAMBIENT_SOUND); uint32_t audioGUIDSize = audioGUID.size(); @@ -968,14 +968,14 @@ void GameMessages::SendPlay2DAmbientSound(Entity* entity, std::string audioGUID, bitStream.Write(result); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendSetNetworkScriptVar(Entity* entity, const SystemAddress& sysAddr, std::string data) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write((uint16_t)GAME_MSG_SET_NETWORK_SCRIPT_VAR); // FIXME: this is a bad place to need to do a conversion because we have no clue whether data is utf8 or plain ascii @@ -1177,10 +1177,10 @@ void GameMessages::SendRemoveSkill(Entity* entity, TSkillID skillID) { } void GameMessages::SendFinishArrangingWithItem(Entity* entity, const LWOOBJID& buildArea) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bool bFirstTime = true; + bool bFirstTime = true; const LWOOBJID& buildAreaID = buildArea; int newSourceBAG = 0; const LWOOBJID& newSourceID = LWOOBJID_EMPTY; @@ -1215,35 +1215,35 @@ void GameMessages::SendFinishArrangingWithItem(Entity* entity, const LWOOBJID& b bitStream.Write(oldItemTYPE); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendModularBuildEnd(Entity* entity) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_MODULAR_BUILD_END); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendVendorOpenWindow(Entity* entity, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_VENDOR_OPEN_WINDOW); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendVendorStatusUpdate(Entity* entity, const SystemAddress& sysAddr, bool bUpdateOnly) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - VendorComponent* vendor = static_cast(entity->GetComponent(COMPONENT_TYPE_VENDOR)); + VendorComponent* vendor = static_cast(entity->GetComponent(COMPONENT_TYPE_VENDOR)); if (!vendor) return; std::map vendorItems = vendor->GetInventory(); @@ -1260,27 +1260,27 @@ void GameMessages::SendVendorStatusUpdate(Entity* entity, const SystemAddress& s } if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST - SEND_PACKET + SEND_PACKET; } void GameMessages::SendVendorTransactionResult(Entity* entity, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - int iResult = 0x02; // success, seems to be the only relevant one + int iResult = 0x02; // success, seems to be the only relevant one bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_VENDOR_TRANSACTION_RESULT); bitStream.Write(iResult); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendRemoveItemFromInventory(Entity* entity, const SystemAddress& sysAddr, LWOOBJID objectID, LOT templateID, int inventoryType, uint32_t stackCount, uint32_t stackRemaining) { - CBITSTREAM - CMSGHEADER - // this is used for a lot more than just inventory trashing (trades, vendors, etc.) but for now since it's just used for that, that's all im going to implement - bool bConfirmed = true; + CBITSTREAM; + CMSGHEADER; + // this is used for a lot more than just inventory trashing (trades, vendors, etc.) but for now since it's just used for that, that's all im going to implement + bool bConfirmed = true; bool bDeleteItem = true; bool bOutSuccess = false; int eInvType = inventoryType; @@ -1320,52 +1320,52 @@ void GameMessages::SendRemoveItemFromInventory(Entity* entity, const SystemAddre bitStream.Write0(); bitStream.Write0(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendConsumeClientItem(Entity* entity, bool bSuccess, LWOOBJID item) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG_CONSUME_CLIENT_ITEM); bitStream.Write(bSuccess); bitStream.Write(item); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendUseItemResult(Entity* entity, LOT templateID, bool useItemResult) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG_USE_ITEM_RESULT); bitStream.Write(templateID); bitStream.Write(useItemResult); SystemAddress sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendUseItemRequirementsResponse(LWOOBJID objectID, const SystemAddress& sysAddr, UseItemResponse itemResponse) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_USE_ITEM_REQUIREMENTS_RESPONSE); bitStream.Write(itemResponse); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, int srcInv, int dstInv, const LWOOBJID& iObjID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - InventoryComponent* inv = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); if (!inv) return; Item* itemStack = inv->FindItemById(iObjID); @@ -1408,25 +1408,25 @@ void GameMessages::SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, i auto sysAddr = entity->GetSystemAddress(); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendMatchResponse(Entity* entity, const SystemAddress& sysAddr, int response) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_MATCH_RESPONSE); bitStream.Write(response); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, std::string data, int type) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_MATCH_UPDATE); bitStream.Write(uint32_t(data.size())); for (char character : data) { @@ -1435,17 +1435,17 @@ void GameMessages::SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, if (data.size() > 0) bitStream.Write(uint16_t(0)); bitStream.Write(type); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendRequestActivitySummaryLeaderboardData(const LWOOBJID& objectID, const LWOOBJID& targetID, const SystemAddress& sysAddr, const int32_t& gameID, const int32_t& queryType, const int32_t& resultsEnd, const int32_t& resultsStart, bool weekly) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA); bitStream.Write(gameID != 0); @@ -1471,57 +1471,57 @@ void GameMessages::SendRequestActivitySummaryLeaderboardData(const LWOOBJID& obj bitStream.Write(targetID); bitStream.Write(weekly); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendActivityPause(LWOOBJID objectId, bool pause, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_ACTIVITY_PAUSE); bitStream.Write(pause); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + SEND_PACKET; } void GameMessages::SendStartActivityTime(LWOOBJID objectId, float_t startTime, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_START_ACTIVITY_TIME); bitStream.Write(startTime); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + SEND_PACKET; } void GameMessages::SendRequestActivityEnter(LWOOBJID objectId, const SystemAddress& sysAddr, bool bStart, LWOOBJID userID) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_ENTER); bitStream.Write(bStart); bitStream.Write(userID); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + SEND_PACKET; } void GameMessages::NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sysAddr, int level, bool sending_rewards) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write((uint16_t)GAME_MSG::GAME_MSG_NOTIFY_LEVEL_REWARDS); bitStream.Write(level); bitStream.Write(sending_rewards); - SEND_PACKET + SEND_PACKET; } void GameMessages::SendSetShootingGalleryParams(LWOOBJID objectId, const SystemAddress& sysAddr, @@ -1533,10 +1533,10 @@ void GameMessages::SendSetShootingGalleryParams(LWOOBJID objectId, const SystemA float projectileVelocity, float timeLimit, bool bUseLeaderboards) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_SET_SHOOTING_GALLERY_PARAMS); /* bitStream.Write(cameraFOV); @@ -1559,7 +1559,7 @@ void GameMessages::SendSetShootingGalleryParams(LWOOBJID objectId, const SystemA bitStream.Write(timeLimit); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + SEND_PACKET; } @@ -1568,10 +1568,10 @@ void GameMessages::SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const int32_t score, LWOOBJID target, NiPoint3 targetPos) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectId); + bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_CLIENT_SHOOTING_GALLERY_SCORE); bitStream.Write(addTime); bitStream.Write(score); @@ -1579,7 +1579,7 @@ void GameMessages::SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const bitStream.Write(targetPos); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; - SEND_PACKET + SEND_PACKET; } @@ -1599,10 +1599,10 @@ void GameMessages::HandleActivitySummaryLeaderboardData(RakNet::BitStream* instr } void GameMessages::SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(objectID); + bitStream.Write(objectID); bitStream.Write(GAME_MSG::GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA); bitStream.Write(leaderboard->GetGameID()); @@ -1619,7 +1619,7 @@ void GameMessages::SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, bitStream.Write0(); bitStream.Write0(); - SEND_PACKET + SEND_PACKET; } void GameMessages::HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { @@ -1942,10 +1942,10 @@ void GameMessages::SendOpenPropertyVendor(const LWOOBJID objectId, const SystemA } void GameMessages::SendOpenPropertyManagment(const LWOOBJID objectId, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(PropertyManagementComponent::Instance()->GetParent()->GetObjectID()); + bitStream.Write(PropertyManagementComponent::Instance()->GetParent()->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_OPEN_PROPERTY_MANAGEMENT); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; @@ -2364,10 +2364,10 @@ void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* } void GameMessages::SendSmash(Entity* entity, float force, float ghostOpacity, LWOOBJID killerID, bool ignoreObjectVisibility) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_SMASH); bitStream.Write(ignoreObjectVisibility); @@ -2375,14 +2375,14 @@ void GameMessages::SendSmash(Entity* entity, float force, float ghostOpacity, LW bitStream.Write(ghostOpacity); bitStream.Write(killerID); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::SendUnSmash(Entity* entity, LWOOBJID builderID, float duration) { - CBITSTREAM - CMSGHEADER + CBITSTREAM; + CMSGHEADER; - bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_UNSMASH); bitStream.Write(builderID != LWOOBJID_EMPTY); @@ -2391,7 +2391,7 @@ void GameMessages::SendUnSmash(Entity* entity, LWOOBJID builderID, float duratio bitStream.Write(duration != 3.0f); if (duration != 3.0f) bitStream.Write(duration); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { @@ -5723,44 +5723,44 @@ void GameMessages::HandleGetHotPropertyData(RakNet::BitStream* inStream, Entity* } void GameMessages::SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - CBITSTREAM - CMSGHEADER - /** - * [u32] - Number of properties - * [objid] - property id - * [objid] - property owner id - * [wstring] - property owner name - * [u64] - total reputation - * [i32] - property template id - * [wstring] - property name - * [wstring] - property description - * [float] - performance cost - * [timestamp] - time last published - * [cloneid] - clone id - * - */ - // TODO This needs to be implemented when reputation is implemented for getting hot properties. - /** - bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_SEND_HOT_PROPERTY_DATA); - std::vector t = {25166, 25188, 25191, 25194}; - bitStream.Write(4); - for (uint8_t i = 0; i < 4; i++) { - bitStream.Write(entity->GetObjectID()); - bitStream.Write(entity->GetObjectID()); - bitStream.Write(1); - bitStream.Write('c'); - bitStream.Write(42069); - bitStream.Write(t[i]); - bitStream.Write(1); - bitStream.Write('c'); - bitStream.Write(1); - bitStream.Write('c'); - bitStream.Write(420.69f); - bitStream.Write(1658376385); - bitStream.Write(25166); - } - SEND_PACKET*/ + CBITSTREAM; + CMSGHEADER; + /** + * [u32] - Number of properties + * [objid] - property id + * [objid] - property owner id + * [wstring] - property owner name + * [u64] - total reputation + * [i32] - property template id + * [wstring] - property name + * [wstring] - property description + * [float] - performance cost + * [timestamp] - time last published + * [cloneid] - clone id + * + */ + // TODO This needs to be implemented when reputation is implemented for getting hot properties. + /** + bitStream.Write(entity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_SEND_HOT_PROPERTY_DATA); + std::vector t = {25166, 25188, 25191, 25194}; + bitStream.Write(4); + for (uint8_t i = 0; i < 4; i++) { + bitStream.Write(entity->GetObjectID()); + bitStream.Write(entity->GetObjectID()); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(42069); + bitStream.Write(t[i]); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(1); + bitStream.Write('c'); + bitStream.Write(420.69f); + bitStream.Write(1658376385); + bitStream.Write(25166); + } + SEND_PACKET*/ } void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) { diff --git a/dNet/ChatPackets.cpp b/dNet/ChatPackets.cpp index eb3bda71..2d592c9b 100644 --- a/dNet/ChatPackets.cpp +++ b/dNet/ChatPackets.cpp @@ -12,8 +12,8 @@ #include "dServer.h" void ChatPackets::SendChatMessage(const SystemAddress& sysAddr, char chatChannel, const std::string& senderName, LWOOBJID playerObjectID, bool senderMythran, const std::u16string& message) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); bitStream.Write(static_cast(0)); bitStream.Write(chatChannel); @@ -30,12 +30,12 @@ void ChatPackets::SendChatMessage(const SystemAddress& sysAddr, char chatChannel } bitStream.Write(static_cast(0)); - SEND_PACKET_BROADCAST + SEND_PACKET_BROADCAST; } void ChatPackets::SendSystemMessage(const SystemAddress& sysAddr, const std::u16string& message, const bool broadcast) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); bitStream.Write(static_cast(0)); bitStream.Write(static_cast(4)); diff --git a/dNet/MasterPackets.cpp b/dNet/MasterPackets.cpp index 6c55b7dc..e5b80e05 100644 --- a/dNet/MasterPackets.cpp +++ b/dNet/MasterPackets.cpp @@ -8,8 +8,8 @@ #include void MasterPackets::SendPersistentIDRequest(dServer* server, uint64_t requestID) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_PERSISTENT_ID); + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_PERSISTENT_ID); bitStream.Write(requestID); server->SendToMaster(&bitStream); } diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index 04a7940c..23d2c010 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -34,7 +34,7 @@ void WorldPackets::SendLoadStaticZone(const SystemAddress& sysAddr, float x, flo bitStream.Write(static_cast(0)); // Change this to eventually use 4 on activity worlds - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendCharacterList(const SystemAddress& sysAddr, User* user) { @@ -85,28 +85,28 @@ void WorldPackets::SendCharacterList(const SystemAddress& sysAddr, User* user) { } } - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendCharacterCreationResponse(const SystemAddress& sysAddr, eCreationResponse response) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_CREATE_RESPONSE); bitStream.Write(response); - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendCharacterRenameResponse(const SystemAddress& sysAddr, eRenameResponse response) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_RENAME_RESPONSE); bitStream.Write(response); - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendCharacterDeleteResponse(const SystemAddress& sysAddr, bool response) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_DELETE_CHARACTER_RESPONSE); bitStream.Write(static_cast(response)); - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendTransferToWorld(const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift) { @@ -117,14 +117,14 @@ void WorldPackets::SendTransferToWorld(const SystemAddress& sysAddr, const std:: bitStream.Write(static_cast(serverPort)); bitStream.Write(static_cast(mythranShift)); - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendServerState(const SystemAddress& sysAddr) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_SERVER_STATES); bitStream.Write(static_cast(1)); //If the server is receiving this request, it probably is ready anyway. - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm) { @@ -184,13 +184,13 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent #endif PacketUtils::SavePacket("chardata.bin", (const char*)bitStream.GetData(), static_cast(bitStream.GetNumberOfBytesUsed())); - SEND_PACKET - Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu", entity->GetObjectID()); + SEND_PACKET; + Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu", entity->GetObjectID()); } void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector> unacceptedItems) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); bitStream.Write(unacceptedItems.empty()); // Is sentence ok? bitStream.Write(0x16); // Source ID, unknown @@ -209,17 +209,17 @@ void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool bitStream.Write(0); } - SEND_PACKET + SEND_PACKET; } void WorldPackets::SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel) { - CBITSTREAM - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAKE_GM_RESPONSE); + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAKE_GM_RESPONSE); bitStream.Write(success); bitStream.Write(highestLevel); bitStream.Write(prevLevel); bitStream.Write(newLevel); - SEND_PACKET + SEND_PACKET; } diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 74c730f6..b4b6c966 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -772,9 +772,9 @@ void HandlePacket(Packet* packet) { Game::logger->Log("MasterServer", "Got affirmation request of transfer %llu", requestID); - CBITSTREAM + CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_AFFIRM_TRANSFER_RESPONSE); + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_AFFIRM_TRANSFER_RESPONSE); bitStream.Write(requestID); Game::server->SendToMaster(&bitStream); diff --git a/tests/AMFDeserializeTests.cpp b/tests/AMFDeserializeTests.cpp index 71a0b265..03941a85 100644 --- a/tests/AMFDeserializeTests.cpp +++ b/tests/AMFDeserializeTests.cpp @@ -14,47 +14,47 @@ std::unique_ptr ReadFromBitStream(RakNet::BitStream* bitStream) { } int ReadAMFUndefinedFromBitStream() { - CBITSTREAM - bitStream.Write(0x00); + CBITSTREAM; + bitStream.Write(0x00); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFUndefined); return 0; } int ReadAMFNullFromBitStream() { - CBITSTREAM - bitStream.Write(0x01); + CBITSTREAM; + bitStream.Write(0x01); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFNull); return 0; } int ReadAMFFalseFromBitStream() { - CBITSTREAM - bitStream.Write(0x02); + CBITSTREAM; + bitStream.Write(0x02); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFFalse); return 0; } int ReadAMFTrueFromBitStream() { - CBITSTREAM - bitStream.Write(0x03); + CBITSTREAM; + bitStream.Write(0x03); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFTrue); return 0; } int ReadAMFIntegerFromBitStream() { - CBITSTREAM + CBITSTREAM; { bitStream.Write(0x04); - // 127 == 01111111 - bitStream.Write(127); - std::unique_ptr res(ReadFromBitStream(&bitStream)); - ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); - // Check that the max value of a byte can be read correctly - ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 127); + // 127 == 01111111 + bitStream.Write(127); + std::unique_ptr res(ReadFromBitStream(&bitStream)); + ASSERT_EQ(res->GetValueType(), AMFValueType::AMFInteger); + // Check that the max value of a byte can be read correctly + ASSERT_EQ(static_cast(res.get())->GetIntegerValue(), 127); } bitStream.Reset(); { @@ -95,8 +95,8 @@ int ReadAMFIntegerFromBitStream() { } int ReadAMFDoubleFromBitStream() { - CBITSTREAM - bitStream.Write(0x05); + CBITSTREAM; + bitStream.Write(0x05); bitStream.Write(25346.4f); std::unique_ptr res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFDouble); @@ -105,8 +105,8 @@ int ReadAMFDoubleFromBitStream() { } int ReadAMFStringFromBitStream() { - CBITSTREAM - bitStream.Write(0x06); + CBITSTREAM; + bitStream.Write(0x06); bitStream.Write(0x0F); std::string toWrite = "stateID"; for (auto e : toWrite) bitStream.Write(e); @@ -117,9 +117,9 @@ int ReadAMFStringFromBitStream() { } int ReadAMFArrayFromBitStream() { - CBITSTREAM - // Test empty AMFArray - bitStream.Write(0x09); + CBITSTREAM; + // Test empty AMFArray + bitStream.Write(0x09); bitStream.Write(0x01); bitStream.Write(0x01); { From 168f837b94a76ef45b849692131a2b31cc64e639 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre Date: Fri, 5 Aug 2022 08:40:59 -0500 Subject: [PATCH 070/322] add blame ignore --- .git-blame-ignore-revs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 2fa44c8c..78e9475c 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -1,2 +1,5 @@ # format codebase 19e77a38d837ce781ba0ca6ea8e78b67a6e3b5a5 + +# add semi-colons to macros consistently +9e4ce24fd2851e65df776dd9c57bcb0d45f4453a From ea869885214cf621077f3fafe76539f4c705e7be Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 5 Aug 2022 19:20:11 -0700 Subject: [PATCH 071/322] Revert dZoneManager Initialization order (#717) --- dWorldServer/WorldServer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index b4b6c966..495053fa 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -233,9 +233,9 @@ int main(int argc, char** argv) { //Load our level: if (zoneID != 0) { - dZoneManager::Instance()->Initialize(LWOZONEID(zoneID, instanceID, cloneID)); dpWorld::Instance().Initialize(zoneID); Game::physicsWorld = &dpWorld::Instance(); //just in case some old code references it + dZoneManager::Instance()->Initialize(LWOZONEID(zoneID, instanceID, cloneID)); g_CloneID = cloneID; // pre calculate the FDB checksum From 72477e01e2711e0f61cdb192ee266e5e21b8846f Mon Sep 17 00:00:00 2001 From: Aaron Kimbre Date: Fri, 5 Aug 2022 22:01:59 -0500 Subject: [PATCH 072/322] convert to unix line endings --- dCommon/ZCompression.cpp | 2 +- dCommon/ZCompression.h | 2 +- dGame/Player.cpp | 2 +- dGame/Player.h | 2 +- dGame/dBehaviors/AirMovementBehavior.cpp | 2 +- dGame/dBehaviors/AirMovementBehavior.h | 2 +- dGame/dBehaviors/AndBehavior.cpp | 2 +- dGame/dBehaviors/AndBehavior.h | 2 +- dGame/dBehaviors/AreaOfEffectBehavior.cpp | 2 +- dGame/dBehaviors/AreaOfEffectBehavior.h | 2 +- dGame/dBehaviors/AttackDelayBehavior.cpp | 2 +- dGame/dBehaviors/AttackDelayBehavior.h | 2 +- dGame/dBehaviors/BasicAttackBehavior.cpp | 2 +- dGame/dBehaviors/BasicAttackBehavior.h | 2 +- dGame/dBehaviors/Behavior.cpp | 2 +- dGame/dBehaviors/Behavior.h | 2 +- dGame/dBehaviors/BehaviorBranchContext.cpp | 2 +- dGame/dBehaviors/BehaviorBranchContext.h | 2 +- dGame/dBehaviors/BehaviorContext.cpp | 2 +- dGame/dBehaviors/BehaviorContext.h | 2 +- dGame/dBehaviors/BehaviorSlot.h | 2 +- dGame/dBehaviors/BehaviorTemplates.cpp | 2 +- dGame/dBehaviors/BehaviorTemplates.h | 2 +- dGame/dBehaviors/BlockBehavior.cpp | 2 +- dGame/dBehaviors/BlockBehavior.h | 2 +- dGame/dBehaviors/BuffBehavior.cpp | 2 +- dGame/dBehaviors/BuffBehavior.h | 2 +- dGame/dBehaviors/ChainBehavior.cpp | 2 +- dGame/dBehaviors/ChainBehavior.h | 2 +- dGame/dBehaviors/ChargeUpBehavior.cpp | 2 +- dGame/dBehaviors/ChargeUpBehavior.h | 2 +- dGame/dBehaviors/ClearTargetBehavior.cpp | 2 +- dGame/dBehaviors/ClearTargetBehavior.h | 2 +- dGame/dBehaviors/DamageAbsorptionBehavior.cpp | 2 +- dGame/dBehaviors/DamageAbsorptionBehavior.h | 2 +- dGame/dBehaviors/DurationBehavior.cpp | 2 +- dGame/dBehaviors/DurationBehavior.h | 2 +- dGame/dBehaviors/EmptyBehavior.cpp | 2 +- dGame/dBehaviors/EmptyBehavior.h | 2 +- dGame/dBehaviors/EndBehavior.cpp | 2 +- dGame/dBehaviors/EndBehavior.h | 2 +- dGame/dBehaviors/ForceMovementBehavior.cpp | 2 +- dGame/dBehaviors/ForceMovementBehavior.h | 2 +- dGame/dBehaviors/HealBehavior.cpp | 2 +- dGame/dBehaviors/HealBehavior.h | 2 +- dGame/dBehaviors/ImaginationBehavior.cpp | 2 +- dGame/dBehaviors/ImaginationBehavior.h | 2 +- dGame/dBehaviors/ImmunityBehavior.cpp | 2 +- dGame/dBehaviors/ImmunityBehavior.h | 2 +- dGame/dBehaviors/InterruptBehavior.cpp | 2 +- dGame/dBehaviors/InterruptBehavior.h | 2 +- dGame/dBehaviors/KnockbackBehavior.cpp | 2 +- dGame/dBehaviors/KnockbackBehavior.h | 2 +- dGame/dBehaviors/MovementSwitchBehavior.cpp | 2 +- dGame/dBehaviors/MovementSwitchBehavior.h | 2 +- dGame/dBehaviors/NpcCombatSkillBehavior.cpp | 2 +- dGame/dBehaviors/NpcCombatSkillBehavior.h | 2 +- dGame/dBehaviors/PlayEffectBehavior.cpp | 2 +- dGame/dBehaviors/PlayEffectBehavior.h | 2 +- dGame/dBehaviors/ProjectileAttackBehavior.cpp | 2 +- dGame/dBehaviors/ProjectileAttackBehavior.h | 2 +- dGame/dBehaviors/PullToPointBehavior.cpp | 2 +- dGame/dBehaviors/PullToPointBehavior.h | 2 +- dGame/dBehaviors/RepairBehavior.cpp | 2 +- dGame/dBehaviors/RepairBehavior.h | 2 +- dGame/dBehaviors/SkillCastFailedBehavior.cpp | 2 +- dGame/dBehaviors/SkillCastFailedBehavior.h | 2 +- dGame/dBehaviors/SpawnBehavior.cpp | 2 +- dGame/dBehaviors/SpawnBehavior.h | 2 +- dGame/dBehaviors/SpawnQuickbuildBehavior.cpp | 2 +- dGame/dBehaviors/SpawnQuickbuildBehavior.h | 2 +- dGame/dBehaviors/StartBehavior.cpp | 2 +- dGame/dBehaviors/StartBehavior.h | 2 +- dGame/dBehaviors/StunBehavior.cpp | 2 +- dGame/dBehaviors/StunBehavior.h | 2 +- dGame/dBehaviors/SwitchBehavior.cpp | 2 +- dGame/dBehaviors/SwitchBehavior.h | 2 +- dGame/dBehaviors/SwitchMultipleBehavior.cpp | 2 +- dGame/dBehaviors/SwitchMultipleBehavior.h | 2 +- dGame/dBehaviors/TacArcBehavior.cpp | 2 +- dGame/dBehaviors/TacArcBehavior.h | 2 +- dGame/dBehaviors/TargetCasterBehavior.cpp | 2 +- dGame/dBehaviors/TargetCasterBehavior.h | 2 +- dGame/dBehaviors/VerifyBehavior.cpp | 2 +- dGame/dBehaviors/VerifyBehavior.h | 2 +- dGame/dComponents/MovementAIComponent.cpp | 2 +- dGame/dComponents/PropertyEntranceComponent.h | 2 +- dGame/dComponents/PropertyManagementComponent.cpp | 2 +- dGame/dComponents/PropertyManagementComponent.h | 2 +- dGame/dComponents/PropertyVendorComponent.cpp | 2 +- dGame/dComponents/PropertyVendorComponent.h | 2 +- dGame/dGameMessages/PropertyDataMessage.cpp | 2 +- dGame/dGameMessages/PropertyDataMessage.h | 2 +- dGame/dGameMessages/PropertySelectQueryProperty.cpp | 2 +- dGame/dGameMessages/PropertySelectQueryProperty.h | 2 +- dGame/dInventory/EquippedItem.cpp | 2 +- dGame/dInventory/Inventory.h | 2 +- dGame/dInventory/Item.cpp | 2 +- dGame/dInventory/Item.h | 2 +- dGame/dInventory/ItemSet.cpp | 2 +- dGame/dInventory/ItemSet.h | 2 +- dGame/dMission/Mission.h | 2 +- dGame/dMission/MissionLockState.h | 2 +- dGame/dMission/MissionPrerequisites.cpp | 2 +- dGame/dMission/MissionPrerequisites.h | 2 +- dGame/dMission/MissionState.h | 2 +- dGame/dMission/MissionTask.cpp | 2 +- dGame/dMission/MissionTask.h | 2 +- dGame/dMission/MissionTaskType.h | 2 +- dGame/dUtilities/Preconditions.h | 2 +- dScripts/AgJetEffectServer.cpp | 2 +- dScripts/AgJetEffectServer.h | 2 +- dScripts/AgPropGuard.cpp | 2 +- dScripts/AgPropGuard.h | 2 +- dScripts/AgSalutingNpcs.cpp | 2 +- dScripts/AgSalutingNpcs.h | 2 +- dScripts/BossSpiderQueenEnemyServer.cpp | 2 +- dScripts/BossSpiderQueenEnemyServer.h | 2 +- dScripts/FvNinjaGuard.cpp | 2 +- dScripts/FvNinjaGuard.h | 2 +- dScripts/GfBanana.cpp | 2 +- dScripts/GfBanana.h | 2 +- dScripts/GfBananaCluster.cpp | 2 +- dScripts/GfBananaCluster.h | 2 +- dScripts/GfJailkeepMission.cpp | 2 +- dScripts/GfJailkeepMission.h | 2 +- dScripts/NtSleepingGuard.cpp | 2 +- dScripts/NtSleepingGuard.h | 2 +- dScripts/SpecialImaginePowerupSpawner.cpp | 2 +- dScripts/SpecialImaginePowerupSpawner.h | 2 +- dScripts/TriggerAmbush.cpp | 2 +- dScripts/TriggerAmbush.h | 2 +- 132 files changed, 132 insertions(+), 132 deletions(-) diff --git a/dCommon/ZCompression.cpp b/dCommon/ZCompression.cpp index a82dc3c9..70f23500 100644 --- a/dCommon/ZCompression.cpp +++ b/dCommon/ZCompression.cpp @@ -1,4 +1,4 @@ -#include "ZCompression.h" +#include "ZCompression.h" #ifndef _WIN32 diff --git a/dCommon/ZCompression.h b/dCommon/ZCompression.h index a4ac9193..7b987cfa 100644 --- a/dCommon/ZCompression.h +++ b/dCommon/ZCompression.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include diff --git a/dGame/Player.cpp b/dGame/Player.cpp index dd269f95..5306584e 100644 --- a/dGame/Player.cpp +++ b/dGame/Player.cpp @@ -1,4 +1,4 @@ -#include "Player.h" +#include "Player.h" #include diff --git a/dGame/Player.h b/dGame/Player.h index caad5361..287ee613 100644 --- a/dGame/Player.h +++ b/dGame/Player.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Entity.h" diff --git a/dGame/dBehaviors/AirMovementBehavior.cpp b/dGame/dBehaviors/AirMovementBehavior.cpp index 188d743d..469ac6e4 100644 --- a/dGame/dBehaviors/AirMovementBehavior.cpp +++ b/dGame/dBehaviors/AirMovementBehavior.cpp @@ -1,4 +1,4 @@ -#include "AirMovementBehavior.h" +#include "AirMovementBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "EntityManager.h" diff --git a/dGame/dBehaviors/AirMovementBehavior.h b/dGame/dBehaviors/AirMovementBehavior.h index 6c3a2abf..323edf37 100644 --- a/dGame/dBehaviors/AirMovementBehavior.h +++ b/dGame/dBehaviors/AirMovementBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class AirMovementBehavior final : public Behavior diff --git a/dGame/dBehaviors/AndBehavior.cpp b/dGame/dBehaviors/AndBehavior.cpp index d54d9ec5..67c88679 100644 --- a/dGame/dBehaviors/AndBehavior.cpp +++ b/dGame/dBehaviors/AndBehavior.cpp @@ -1,4 +1,4 @@ -#include "AndBehavior.h" +#include "AndBehavior.h" #include "BehaviorBranchContext.h" #include "Game.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/AndBehavior.h b/dGame/dBehaviors/AndBehavior.h index 17d1e51e..0ef7c0fd 100644 --- a/dGame/dBehaviors/AndBehavior.h +++ b/dGame/dBehaviors/AndBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.cpp b/dGame/dBehaviors/AreaOfEffectBehavior.cpp index ba0f69a5..898d1f99 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.cpp +++ b/dGame/dBehaviors/AreaOfEffectBehavior.cpp @@ -1,4 +1,4 @@ -#include "AreaOfEffectBehavior.h" +#include "AreaOfEffectBehavior.h" #include diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.h b/dGame/dBehaviors/AreaOfEffectBehavior.h index 863ce8f7..b5a48ddf 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.h +++ b/dGame/dBehaviors/AreaOfEffectBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class AreaOfEffectBehavior final : public Behavior diff --git a/dGame/dBehaviors/AttackDelayBehavior.cpp b/dGame/dBehaviors/AttackDelayBehavior.cpp index 9d1eb872..450741ec 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.cpp +++ b/dGame/dBehaviors/AttackDelayBehavior.cpp @@ -1,4 +1,4 @@ -#include "AttackDelayBehavior.h" +#include "AttackDelayBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "Game.h" diff --git a/dGame/dBehaviors/AttackDelayBehavior.h b/dGame/dBehaviors/AttackDelayBehavior.h index 4223aba4..64271ba5 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.h +++ b/dGame/dBehaviors/AttackDelayBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class AttackDelayBehavior final : public Behavior diff --git a/dGame/dBehaviors/BasicAttackBehavior.cpp b/dGame/dBehaviors/BasicAttackBehavior.cpp index 0c0b0d56..fe773f36 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.cpp +++ b/dGame/dBehaviors/BasicAttackBehavior.cpp @@ -1,4 +1,4 @@ -#include "BasicAttackBehavior.h" +#include "BasicAttackBehavior.h" #include "BehaviorBranchContext.h" #include "Game.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/BasicAttackBehavior.h b/dGame/dBehaviors/BasicAttackBehavior.h index 9e6874b9..8e23d443 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.h +++ b/dGame/dBehaviors/BasicAttackBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class BasicAttackBehavior final : public Behavior diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index ed8f2f8c..046df117 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include "Behavior.h" diff --git a/dGame/dBehaviors/Behavior.h b/dGame/dBehaviors/Behavior.h index bf656e1b..ca1c23e5 100644 --- a/dGame/dBehaviors/Behavior.h +++ b/dGame/dBehaviors/Behavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include #include diff --git a/dGame/dBehaviors/BehaviorBranchContext.cpp b/dGame/dBehaviors/BehaviorBranchContext.cpp index 7793eb54..3237997a 100644 --- a/dGame/dBehaviors/BehaviorBranchContext.cpp +++ b/dGame/dBehaviors/BehaviorBranchContext.cpp @@ -1,4 +1,4 @@ -#include "BehaviorBranchContext.h" +#include "BehaviorBranchContext.h" BehaviorBranchContext::BehaviorBranchContext() { diff --git a/dGame/dBehaviors/BehaviorBranchContext.h b/dGame/dBehaviors/BehaviorBranchContext.h index dfd76fad..5b2ec595 100644 --- a/dGame/dBehaviors/BehaviorBranchContext.h +++ b/dGame/dBehaviors/BehaviorBranchContext.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "dCommonVars.h" #include "NiPoint3.h" diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index 54325bac..4cd9e415 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -1,4 +1,4 @@ -#include "BehaviorContext.h" +#include "BehaviorContext.h" #include "Behavior.h" #include "BehaviorBranchContext.h" #include "EntityManager.h" diff --git a/dGame/dBehaviors/BehaviorContext.h b/dGame/dBehaviors/BehaviorContext.h index af8e66b4..0462d97f 100644 --- a/dGame/dBehaviors/BehaviorContext.h +++ b/dGame/dBehaviors/BehaviorContext.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "RakPeerInterface.h" #include "dCommonVars.h" diff --git a/dGame/dBehaviors/BehaviorSlot.h b/dGame/dBehaviors/BehaviorSlot.h index af0d4e03..51219b80 100644 --- a/dGame/dBehaviors/BehaviorSlot.h +++ b/dGame/dBehaviors/BehaviorSlot.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef BEHAVIORSLOT_H #define BEHAVIORSLOT_H diff --git a/dGame/dBehaviors/BehaviorTemplates.cpp b/dGame/dBehaviors/BehaviorTemplates.cpp index 85d0074f..8719fbe7 100644 --- a/dGame/dBehaviors/BehaviorTemplates.cpp +++ b/dGame/dBehaviors/BehaviorTemplates.cpp @@ -1 +1 @@ -#include "BehaviorTemplates.h" +#include "BehaviorTemplates.h" diff --git a/dGame/dBehaviors/BehaviorTemplates.h b/dGame/dBehaviors/BehaviorTemplates.h index af7ab376..87cde694 100644 --- a/dGame/dBehaviors/BehaviorTemplates.h +++ b/dGame/dBehaviors/BehaviorTemplates.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once enum class BehaviorTemplates : unsigned int { BEHAVIOR_EMPTY, // Not a real behavior, indicates invalid behaviors diff --git a/dGame/dBehaviors/BlockBehavior.cpp b/dGame/dBehaviors/BlockBehavior.cpp index 25650b2a..cdbb3d80 100644 --- a/dGame/dBehaviors/BlockBehavior.cpp +++ b/dGame/dBehaviors/BlockBehavior.cpp @@ -1,4 +1,4 @@ -#include "BlockBehavior.h" +#include "BlockBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/BlockBehavior.h b/dGame/dBehaviors/BlockBehavior.h index 139fa0af..e0d639ed 100644 --- a/dGame/dBehaviors/BlockBehavior.h +++ b/dGame/dBehaviors/BlockBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class BlockBehavior final : public Behavior diff --git a/dGame/dBehaviors/BuffBehavior.cpp b/dGame/dBehaviors/BuffBehavior.cpp index 8bd14529..a39fd165 100644 --- a/dGame/dBehaviors/BuffBehavior.cpp +++ b/dGame/dBehaviors/BuffBehavior.cpp @@ -1,4 +1,4 @@ -#include "BuffBehavior.h" +#include "BuffBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/BuffBehavior.h b/dGame/dBehaviors/BuffBehavior.h index ffc853fa..b7c805b3 100644 --- a/dGame/dBehaviors/BuffBehavior.h +++ b/dGame/dBehaviors/BuffBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class BuffBehavior final : public Behavior diff --git a/dGame/dBehaviors/ChainBehavior.cpp b/dGame/dBehaviors/ChainBehavior.cpp index df8b223f..3ef8c15b 100644 --- a/dGame/dBehaviors/ChainBehavior.cpp +++ b/dGame/dBehaviors/ChainBehavior.cpp @@ -1,4 +1,4 @@ -#include "ChainBehavior.h" +#include "ChainBehavior.h" #include "BehaviorBranchContext.h" #include "Game.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/ChainBehavior.h b/dGame/dBehaviors/ChainBehavior.h index 626ecbe3..c31d5358 100644 --- a/dGame/dBehaviors/ChainBehavior.h +++ b/dGame/dBehaviors/ChainBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" diff --git a/dGame/dBehaviors/ChargeUpBehavior.cpp b/dGame/dBehaviors/ChargeUpBehavior.cpp index 5fc9822e..fa9fa34b 100644 --- a/dGame/dBehaviors/ChargeUpBehavior.cpp +++ b/dGame/dBehaviors/ChargeUpBehavior.cpp @@ -1,4 +1,4 @@ -#include "ChargeUpBehavior.h" +#include "ChargeUpBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/ChargeUpBehavior.h b/dGame/dBehaviors/ChargeUpBehavior.h index a80026c5..d753895e 100644 --- a/dGame/dBehaviors/ChargeUpBehavior.h +++ b/dGame/dBehaviors/ChargeUpBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class ChargeUpBehavior final : public Behavior diff --git a/dGame/dBehaviors/ClearTargetBehavior.cpp b/dGame/dBehaviors/ClearTargetBehavior.cpp index e37161f3..ec0c0db6 100644 --- a/dGame/dBehaviors/ClearTargetBehavior.cpp +++ b/dGame/dBehaviors/ClearTargetBehavior.cpp @@ -1,4 +1,4 @@ -#include "ClearTargetBehavior.h" +#include "ClearTargetBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/ClearTargetBehavior.h b/dGame/dBehaviors/ClearTargetBehavior.h index e1235eea..0ed57fb4 100644 --- a/dGame/dBehaviors/ClearTargetBehavior.h +++ b/dGame/dBehaviors/ClearTargetBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class ClearTargetBehavior final : public Behavior diff --git a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp index 4f4e5b81..48dbf705 100644 --- a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp +++ b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp @@ -1,4 +1,4 @@ -#include "DamageAbsorptionBehavior.h" +#include "DamageAbsorptionBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/DamageAbsorptionBehavior.h b/dGame/dBehaviors/DamageAbsorptionBehavior.h index 533fe554..1b865e87 100644 --- a/dGame/dBehaviors/DamageAbsorptionBehavior.h +++ b/dGame/dBehaviors/DamageAbsorptionBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class DamageAbsorptionBehavior final : public Behavior diff --git a/dGame/dBehaviors/DurationBehavior.cpp b/dGame/dBehaviors/DurationBehavior.cpp index 6fc1b4d9..c0bc5585 100644 --- a/dGame/dBehaviors/DurationBehavior.cpp +++ b/dGame/dBehaviors/DurationBehavior.cpp @@ -1,4 +1,4 @@ -#include "DurationBehavior.h" +#include "DurationBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/DurationBehavior.h b/dGame/dBehaviors/DurationBehavior.h index b8533700..164754b1 100644 --- a/dGame/dBehaviors/DurationBehavior.h +++ b/dGame/dBehaviors/DurationBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class DurationBehavior final : public Behavior diff --git a/dGame/dBehaviors/EmptyBehavior.cpp b/dGame/dBehaviors/EmptyBehavior.cpp index 4f8a5266..8828f5de 100644 --- a/dGame/dBehaviors/EmptyBehavior.cpp +++ b/dGame/dBehaviors/EmptyBehavior.cpp @@ -1,2 +1,2 @@ -#include "EmptyBehavior.h" +#include "EmptyBehavior.h" diff --git a/dGame/dBehaviors/EmptyBehavior.h b/dGame/dBehaviors/EmptyBehavior.h index 64990ec4..52121f6c 100644 --- a/dGame/dBehaviors/EmptyBehavior.h +++ b/dGame/dBehaviors/EmptyBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" diff --git a/dGame/dBehaviors/EndBehavior.cpp b/dGame/dBehaviors/EndBehavior.cpp index bf35932f..c67f3215 100644 --- a/dGame/dBehaviors/EndBehavior.cpp +++ b/dGame/dBehaviors/EndBehavior.cpp @@ -1,4 +1,4 @@ -#include "EndBehavior.h" +#include "EndBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/EndBehavior.h b/dGame/dBehaviors/EndBehavior.h index 8503f7ba..e1c06068 100644 --- a/dGame/dBehaviors/EndBehavior.h +++ b/dGame/dBehaviors/EndBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class EndBehavior final : public Behavior diff --git a/dGame/dBehaviors/ForceMovementBehavior.cpp b/dGame/dBehaviors/ForceMovementBehavior.cpp index 8074dbcc..55cda622 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.cpp +++ b/dGame/dBehaviors/ForceMovementBehavior.cpp @@ -1,4 +1,4 @@ -#include "ForceMovementBehavior.h" +#include "ForceMovementBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "ControllablePhysicsComponent.h" diff --git a/dGame/dBehaviors/ForceMovementBehavior.h b/dGame/dBehaviors/ForceMovementBehavior.h index 26b5ce89..8d5fd9f4 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.h +++ b/dGame/dBehaviors/ForceMovementBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class ForceMovementBehavior final : public Behavior diff --git a/dGame/dBehaviors/HealBehavior.cpp b/dGame/dBehaviors/HealBehavior.cpp index da0d4a3b..2799d2e2 100644 --- a/dGame/dBehaviors/HealBehavior.cpp +++ b/dGame/dBehaviors/HealBehavior.cpp @@ -1,4 +1,4 @@ -#include "HealBehavior.h" +#include "HealBehavior.h" #include "BehaviorBranchContext.h" #include "Game.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/HealBehavior.h b/dGame/dBehaviors/HealBehavior.h index 0a719b6c..e967135a 100644 --- a/dGame/dBehaviors/HealBehavior.h +++ b/dGame/dBehaviors/HealBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class HealBehavior final : public Behavior diff --git a/dGame/dBehaviors/ImaginationBehavior.cpp b/dGame/dBehaviors/ImaginationBehavior.cpp index cf2cd757..59b192b0 100644 --- a/dGame/dBehaviors/ImaginationBehavior.cpp +++ b/dGame/dBehaviors/ImaginationBehavior.cpp @@ -1,4 +1,4 @@ -#include "ImaginationBehavior.h" +#include "ImaginationBehavior.h" #include "BehaviorBranchContext.h" #include "DestroyableComponent.h" #include "dpWorld.h" diff --git a/dGame/dBehaviors/ImaginationBehavior.h b/dGame/dBehaviors/ImaginationBehavior.h index 59d864f9..a35c2ddd 100644 --- a/dGame/dBehaviors/ImaginationBehavior.h +++ b/dGame/dBehaviors/ImaginationBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class ImaginationBehavior final : public Behavior diff --git a/dGame/dBehaviors/ImmunityBehavior.cpp b/dGame/dBehaviors/ImmunityBehavior.cpp index 93110cde..69c652f9 100644 --- a/dGame/dBehaviors/ImmunityBehavior.cpp +++ b/dGame/dBehaviors/ImmunityBehavior.cpp @@ -1,4 +1,4 @@ -#include "ImmunityBehavior.h" +#include "ImmunityBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/ImmunityBehavior.h b/dGame/dBehaviors/ImmunityBehavior.h index 8a66b3d2..f9409e4c 100644 --- a/dGame/dBehaviors/ImmunityBehavior.h +++ b/dGame/dBehaviors/ImmunityBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class ImmunityBehavior final : public Behavior diff --git a/dGame/dBehaviors/InterruptBehavior.cpp b/dGame/dBehaviors/InterruptBehavior.cpp index b0695430..b42eadb0 100644 --- a/dGame/dBehaviors/InterruptBehavior.cpp +++ b/dGame/dBehaviors/InterruptBehavior.cpp @@ -1,4 +1,4 @@ -#include "InterruptBehavior.h" +#include "InterruptBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "Game.h" diff --git a/dGame/dBehaviors/InterruptBehavior.h b/dGame/dBehaviors/InterruptBehavior.h index 35a2def9..9ba272c7 100644 --- a/dGame/dBehaviors/InterruptBehavior.h +++ b/dGame/dBehaviors/InterruptBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class InterruptBehavior final : public Behavior diff --git a/dGame/dBehaviors/KnockbackBehavior.cpp b/dGame/dBehaviors/KnockbackBehavior.cpp index 0b1fc5d7..83c82010 100644 --- a/dGame/dBehaviors/KnockbackBehavior.cpp +++ b/dGame/dBehaviors/KnockbackBehavior.cpp @@ -1,4 +1,4 @@ -#define _USE_MATH_DEFINES +#define _USE_MATH_DEFINES #include #include "KnockbackBehavior.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/KnockbackBehavior.h b/dGame/dBehaviors/KnockbackBehavior.h index 4feb592c..c952bb41 100644 --- a/dGame/dBehaviors/KnockbackBehavior.h +++ b/dGame/dBehaviors/KnockbackBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class KnockbackBehavior final : public Behavior diff --git a/dGame/dBehaviors/MovementSwitchBehavior.cpp b/dGame/dBehaviors/MovementSwitchBehavior.cpp index de1b0b50..17ed5c40 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.cpp +++ b/dGame/dBehaviors/MovementSwitchBehavior.cpp @@ -1,4 +1,4 @@ -#include "MovementSwitchBehavior.h" +#include "MovementSwitchBehavior.h" #include "BehaviorBranchContext.h" #include "Game.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/MovementSwitchBehavior.h b/dGame/dBehaviors/MovementSwitchBehavior.h index 8a1e83a3..82e1a9e9 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.h +++ b/dGame/dBehaviors/MovementSwitchBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class MovementSwitchBehavior final : public Behavior diff --git a/dGame/dBehaviors/NpcCombatSkillBehavior.cpp b/dGame/dBehaviors/NpcCombatSkillBehavior.cpp index d541033c..5a8d03cf 100644 --- a/dGame/dBehaviors/NpcCombatSkillBehavior.cpp +++ b/dGame/dBehaviors/NpcCombatSkillBehavior.cpp @@ -1,4 +1,4 @@ -#include "NpcCombatSkillBehavior.h" +#include "NpcCombatSkillBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/NpcCombatSkillBehavior.h b/dGame/dBehaviors/NpcCombatSkillBehavior.h index f2ed60b9..19ff3483 100644 --- a/dGame/dBehaviors/NpcCombatSkillBehavior.h +++ b/dGame/dBehaviors/NpcCombatSkillBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class NpcCombatSkillBehavior final : public Behavior diff --git a/dGame/dBehaviors/PlayEffectBehavior.cpp b/dGame/dBehaviors/PlayEffectBehavior.cpp index 9793c1db..acd606a9 100644 --- a/dGame/dBehaviors/PlayEffectBehavior.cpp +++ b/dGame/dBehaviors/PlayEffectBehavior.cpp @@ -1,4 +1,4 @@ -#include "PlayEffectBehavior.h" +#include "PlayEffectBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/PlayEffectBehavior.h b/dGame/dBehaviors/PlayEffectBehavior.h index d6069305..5ef49161 100644 --- a/dGame/dBehaviors/PlayEffectBehavior.h +++ b/dGame/dBehaviors/PlayEffectBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class PlayEffectBehavior final : public Behavior diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.cpp b/dGame/dBehaviors/ProjectileAttackBehavior.cpp index 861837e7..350234e2 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.cpp +++ b/dGame/dBehaviors/ProjectileAttackBehavior.cpp @@ -1,4 +1,4 @@ -#include "ProjectileAttackBehavior.h" +#include "ProjectileAttackBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "EntityManager.h" diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.h b/dGame/dBehaviors/ProjectileAttackBehavior.h index 0003c2dc..17353a2a 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.h +++ b/dGame/dBehaviors/ProjectileAttackBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" #include "NiPoint3.h" diff --git a/dGame/dBehaviors/PullToPointBehavior.cpp b/dGame/dBehaviors/PullToPointBehavior.cpp index 2cdbaa7e..7427ccc4 100644 --- a/dGame/dBehaviors/PullToPointBehavior.cpp +++ b/dGame/dBehaviors/PullToPointBehavior.cpp @@ -1,4 +1,4 @@ -#include "PullToPointBehavior.h" +#include "PullToPointBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/PullToPointBehavior.h b/dGame/dBehaviors/PullToPointBehavior.h index 09e4310c..d448ad8d 100644 --- a/dGame/dBehaviors/PullToPointBehavior.h +++ b/dGame/dBehaviors/PullToPointBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class PullToPointBehavior final : public Behavior diff --git a/dGame/dBehaviors/RepairBehavior.cpp b/dGame/dBehaviors/RepairBehavior.cpp index 470fb4d4..a48141d3 100644 --- a/dGame/dBehaviors/RepairBehavior.cpp +++ b/dGame/dBehaviors/RepairBehavior.cpp @@ -1,4 +1,4 @@ -#include "RepairBehavior.h" +#include "RepairBehavior.h" #include "BehaviorBranchContext.h" #include "DestroyableComponent.h" #include "dpWorld.h" diff --git a/dGame/dBehaviors/RepairBehavior.h b/dGame/dBehaviors/RepairBehavior.h index 38f97b05..8d2f14e4 100644 --- a/dGame/dBehaviors/RepairBehavior.h +++ b/dGame/dBehaviors/RepairBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class RepairBehavior final : public Behavior diff --git a/dGame/dBehaviors/SkillCastFailedBehavior.cpp b/dGame/dBehaviors/SkillCastFailedBehavior.cpp index 7a0166f9..a663e709 100644 --- a/dGame/dBehaviors/SkillCastFailedBehavior.cpp +++ b/dGame/dBehaviors/SkillCastFailedBehavior.cpp @@ -1,4 +1,4 @@ -#include "SkillCastFailedBehavior.h" +#include "SkillCastFailedBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/SkillCastFailedBehavior.h b/dGame/dBehaviors/SkillCastFailedBehavior.h index 1f414f90..5359cb42 100644 --- a/dGame/dBehaviors/SkillCastFailedBehavior.h +++ b/dGame/dBehaviors/SkillCastFailedBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class SkillCastFailedBehavior final : public Behavior diff --git a/dGame/dBehaviors/SpawnBehavior.cpp b/dGame/dBehaviors/SpawnBehavior.cpp index 592a8a22..ac7bb797 100644 --- a/dGame/dBehaviors/SpawnBehavior.cpp +++ b/dGame/dBehaviors/SpawnBehavior.cpp @@ -1,4 +1,4 @@ -#include "SpawnBehavior.h" +#include "SpawnBehavior.h" #include "BehaviorContext.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/SpawnBehavior.h b/dGame/dBehaviors/SpawnBehavior.h index 0617f781..875e0a2b 100644 --- a/dGame/dBehaviors/SpawnBehavior.h +++ b/dGame/dBehaviors/SpawnBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class SpawnBehavior final : public Behavior diff --git a/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp b/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp index 2b78f12e..514ae27a 100644 --- a/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp +++ b/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp @@ -1,4 +1,4 @@ -#include "SpawnQuickbuildBehavior.h" +#include "SpawnQuickbuildBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/SpawnQuickbuildBehavior.h b/dGame/dBehaviors/SpawnQuickbuildBehavior.h index d1ed2e53..653c60e8 100644 --- a/dGame/dBehaviors/SpawnQuickbuildBehavior.h +++ b/dGame/dBehaviors/SpawnQuickbuildBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class SpawnQuickbuildBehavior final : public Behavior diff --git a/dGame/dBehaviors/StartBehavior.cpp b/dGame/dBehaviors/StartBehavior.cpp index 436984d1..2bcaf325 100644 --- a/dGame/dBehaviors/StartBehavior.cpp +++ b/dGame/dBehaviors/StartBehavior.cpp @@ -1,4 +1,4 @@ -#include "StartBehavior.h" +#include "StartBehavior.h" #include "BehaviorBranchContext.h" void StartBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { diff --git a/dGame/dBehaviors/StartBehavior.h b/dGame/dBehaviors/StartBehavior.h index 9ee461fc..384fe64a 100644 --- a/dGame/dBehaviors/StartBehavior.h +++ b/dGame/dBehaviors/StartBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class StartBehavior final : public Behavior diff --git a/dGame/dBehaviors/StunBehavior.cpp b/dGame/dBehaviors/StunBehavior.cpp index 3cbfe9c4..59a81440 100644 --- a/dGame/dBehaviors/StunBehavior.cpp +++ b/dGame/dBehaviors/StunBehavior.cpp @@ -1,4 +1,4 @@ -#include "StunBehavior.h" +#include "StunBehavior.h" #include "BaseCombatAIComponent.h" #include "BehaviorBranchContext.h" diff --git a/dGame/dBehaviors/StunBehavior.h b/dGame/dBehaviors/StunBehavior.h index a512528d..f4851b47 100644 --- a/dGame/dBehaviors/StunBehavior.h +++ b/dGame/dBehaviors/StunBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class StunBehavior final : public Behavior diff --git a/dGame/dBehaviors/SwitchBehavior.cpp b/dGame/dBehaviors/SwitchBehavior.cpp index ff3d7baf..78271b99 100644 --- a/dGame/dBehaviors/SwitchBehavior.cpp +++ b/dGame/dBehaviors/SwitchBehavior.cpp @@ -1,4 +1,4 @@ -#include "SwitchBehavior.h" +#include "SwitchBehavior.h" #include "BehaviorBranchContext.h" #include "EntityManager.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/SwitchBehavior.h b/dGame/dBehaviors/SwitchBehavior.h index 675c1a35..5e40d659 100644 --- a/dGame/dBehaviors/SwitchBehavior.h +++ b/dGame/dBehaviors/SwitchBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class SwitchBehavior final : public Behavior diff --git a/dGame/dBehaviors/SwitchMultipleBehavior.cpp b/dGame/dBehaviors/SwitchMultipleBehavior.cpp index b34b1144..946e5e0f 100644 --- a/dGame/dBehaviors/SwitchMultipleBehavior.cpp +++ b/dGame/dBehaviors/SwitchMultipleBehavior.cpp @@ -1,4 +1,4 @@ -#include "SwitchMultipleBehavior.h" +#include "SwitchMultipleBehavior.h" #include diff --git a/dGame/dBehaviors/SwitchMultipleBehavior.h b/dGame/dBehaviors/SwitchMultipleBehavior.h index c60fcd6d..1e3dfe64 100644 --- a/dGame/dBehaviors/SwitchMultipleBehavior.h +++ b/dGame/dBehaviors/SwitchMultipleBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" #include diff --git a/dGame/dBehaviors/TacArcBehavior.cpp b/dGame/dBehaviors/TacArcBehavior.cpp index 21885624..8789f9b6 100644 --- a/dGame/dBehaviors/TacArcBehavior.cpp +++ b/dGame/dBehaviors/TacArcBehavior.cpp @@ -1,4 +1,4 @@ -#include "TacArcBehavior.h" +#include "TacArcBehavior.h" #include "BehaviorBranchContext.h" #include "Game.h" #include "dLogger.h" diff --git a/dGame/dBehaviors/TacArcBehavior.h b/dGame/dBehaviors/TacArcBehavior.h index 211ed6b7..87a22051 100644 --- a/dGame/dBehaviors/TacArcBehavior.h +++ b/dGame/dBehaviors/TacArcBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" #include "dCommonVars.h" #include "NiPoint3.h" diff --git a/dGame/dBehaviors/TargetCasterBehavior.cpp b/dGame/dBehaviors/TargetCasterBehavior.cpp index fb76b90d..ff9cfc03 100644 --- a/dGame/dBehaviors/TargetCasterBehavior.cpp +++ b/dGame/dBehaviors/TargetCasterBehavior.cpp @@ -1,4 +1,4 @@ -#include "TargetCasterBehavior.h" +#include "TargetCasterBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" diff --git a/dGame/dBehaviors/TargetCasterBehavior.h b/dGame/dBehaviors/TargetCasterBehavior.h index 4f2a0f5f..387d2732 100644 --- a/dGame/dBehaviors/TargetCasterBehavior.h +++ b/dGame/dBehaviors/TargetCasterBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class TargetCasterBehavior final : public Behavior diff --git a/dGame/dBehaviors/VerifyBehavior.cpp b/dGame/dBehaviors/VerifyBehavior.cpp index cbc3c6df..608e965b 100644 --- a/dGame/dBehaviors/VerifyBehavior.cpp +++ b/dGame/dBehaviors/VerifyBehavior.cpp @@ -1,4 +1,4 @@ -#include "VerifyBehavior.h" +#include "VerifyBehavior.h" #include "BehaviorBranchContext.h" #include "EntityManager.h" #include "NiPoint3.h" diff --git a/dGame/dBehaviors/VerifyBehavior.h b/dGame/dBehaviors/VerifyBehavior.h index b38d1953..a91ff7cf 100644 --- a/dGame/dBehaviors/VerifyBehavior.h +++ b/dGame/dBehaviors/VerifyBehavior.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Behavior.h" class VerifyBehavior final : public Behavior diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index 43231abf..ed6ed483 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -1,4 +1,4 @@ -#include "MovementAIComponent.h" +#include "MovementAIComponent.h" #include #include diff --git a/dGame/dComponents/PropertyEntranceComponent.h b/dGame/dComponents/PropertyEntranceComponent.h index 6087faf2..4110e7d9 100644 --- a/dGame/dComponents/PropertyEntranceComponent.h +++ b/dGame/dComponents/PropertyEntranceComponent.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index bc3d8395..f6954e4d 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -1,4 +1,4 @@ -#include "PropertyManagementComponent.h" +#include "PropertyManagementComponent.h" #include diff --git a/dGame/dComponents/PropertyManagementComponent.h b/dGame/dComponents/PropertyManagementComponent.h index c22adc21..d9526015 100644 --- a/dGame/dComponents/PropertyManagementComponent.h +++ b/dGame/dComponents/PropertyManagementComponent.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include #include "Entity.h" diff --git a/dGame/dComponents/PropertyVendorComponent.cpp b/dGame/dComponents/PropertyVendorComponent.cpp index 4ad24af5..ed89bfc7 100644 --- a/dGame/dComponents/PropertyVendorComponent.cpp +++ b/dGame/dComponents/PropertyVendorComponent.cpp @@ -1,4 +1,4 @@ -#include "PropertyVendorComponent.h" +#include "PropertyVendorComponent.h" #include "PropertyDataMessage.h" #include "GameMessages.h" diff --git a/dGame/dComponents/PropertyVendorComponent.h b/dGame/dComponents/PropertyVendorComponent.h index 4641b38d..f947d745 100644 --- a/dGame/dComponents/PropertyVendorComponent.h +++ b/dGame/dComponents/PropertyVendorComponent.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "Entity.h" #include "Component.h" diff --git a/dGame/dGameMessages/PropertyDataMessage.cpp b/dGame/dGameMessages/PropertyDataMessage.cpp index c30285fd..e0b792ad 100644 --- a/dGame/dGameMessages/PropertyDataMessage.cpp +++ b/dGame/dGameMessages/PropertyDataMessage.cpp @@ -1,4 +1,4 @@ -#include "PropertyDataMessage.h" +#include "PropertyDataMessage.h" #include "GeneralUtils.h" diff --git a/dGame/dGameMessages/PropertyDataMessage.h b/dGame/dGameMessages/PropertyDataMessage.h index 819c5dbb..f7c9e2d5 100644 --- a/dGame/dGameMessages/PropertyDataMessage.h +++ b/dGame/dGameMessages/PropertyDataMessage.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include #include diff --git a/dGame/dGameMessages/PropertySelectQueryProperty.cpp b/dGame/dGameMessages/PropertySelectQueryProperty.cpp index cd17a58b..6e975879 100644 --- a/dGame/dGameMessages/PropertySelectQueryProperty.cpp +++ b/dGame/dGameMessages/PropertySelectQueryProperty.cpp @@ -1,4 +1,4 @@ -#include "PropertySelectQueryProperty.h" +#include "PropertySelectQueryProperty.h" void PropertySelectQueryProperty::Serialize(RakNet::BitStream& stream) const { stream.Write(CloneId); diff --git a/dGame/dGameMessages/PropertySelectQueryProperty.h b/dGame/dGameMessages/PropertySelectQueryProperty.h index 7826900d..47d795a7 100644 --- a/dGame/dGameMessages/PropertySelectQueryProperty.h +++ b/dGame/dGameMessages/PropertySelectQueryProperty.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef PROPERTYSELECTQUERY_H #define PROPERTYSELECTQUERY_H diff --git a/dGame/dInventory/EquippedItem.cpp b/dGame/dInventory/EquippedItem.cpp index df5639de..9eaed5fc 100644 --- a/dGame/dInventory/EquippedItem.cpp +++ b/dGame/dInventory/EquippedItem.cpp @@ -1 +1 @@ -#include "EquippedItem.h" +#include "EquippedItem.h" diff --git a/dGame/dInventory/Inventory.h b/dGame/dInventory/Inventory.h index 1f7bb425..30f753da 100644 --- a/dGame/dInventory/Inventory.h +++ b/dGame/dInventory/Inventory.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef INVENTORY_H #define INVENTORY_H diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index b502d5eb..62e198a3 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -1,4 +1,4 @@ -#include "Item.h" +#include "Item.h" #include diff --git a/dGame/dInventory/Item.h b/dGame/dInventory/Item.h index 3987471c..0613ca85 100644 --- a/dGame/dInventory/Item.h +++ b/dGame/dInventory/Item.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "dCommonVars.h" #include "Inventory.h" diff --git a/dGame/dInventory/ItemSet.cpp b/dGame/dInventory/ItemSet.cpp index 5d8ea226..5063139e 100644 --- a/dGame/dInventory/ItemSet.cpp +++ b/dGame/dInventory/ItemSet.cpp @@ -1,4 +1,4 @@ -#include "ItemSet.h" +#include "ItemSet.h" #include "InventoryComponent.h" #include "Entity.h" diff --git a/dGame/dInventory/ItemSet.h b/dGame/dInventory/ItemSet.h index 2ed3be14..7c713f03 100644 --- a/dGame/dInventory/ItemSet.h +++ b/dGame/dInventory/ItemSet.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include diff --git a/dGame/dMission/Mission.h b/dGame/dMission/Mission.h index 43b2a96c..b8892f3d 100644 --- a/dGame/dMission/Mission.h +++ b/dGame/dMission/Mission.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef MISSION_H #define MISSION_H diff --git a/dGame/dMission/MissionLockState.h b/dGame/dMission/MissionLockState.h index e2dcedd7..9fd2252a 100644 --- a/dGame/dMission/MissionLockState.h +++ b/dGame/dMission/MissionLockState.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef MISSIONLOCKSTATE_H #define MISSIONLOCKSTATE_H diff --git a/dGame/dMission/MissionPrerequisites.cpp b/dGame/dMission/MissionPrerequisites.cpp index 3d4e6355..46fa73a6 100644 --- a/dGame/dMission/MissionPrerequisites.cpp +++ b/dGame/dMission/MissionPrerequisites.cpp @@ -1,4 +1,4 @@ -#include "MissionPrerequisites.h" +#include "MissionPrerequisites.h" #include #include diff --git a/dGame/dMission/MissionPrerequisites.h b/dGame/dMission/MissionPrerequisites.h index dd349cb1..13b8e903 100644 --- a/dGame/dMission/MissionPrerequisites.h +++ b/dGame/dMission/MissionPrerequisites.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include #include #include diff --git a/dGame/dMission/MissionState.h b/dGame/dMission/MissionState.h index 5ee480da..fb1841d3 100644 --- a/dGame/dMission/MissionState.h +++ b/dGame/dMission/MissionState.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef __MISSIONSTATE__H__ #define __MISSIONSTATE__H__ diff --git a/dGame/dMission/MissionTask.cpp b/dGame/dMission/MissionTask.cpp index e08dc146..dc2cb149 100644 --- a/dGame/dMission/MissionTask.cpp +++ b/dGame/dMission/MissionTask.cpp @@ -1,4 +1,4 @@ -#include +#include #include "MissionTask.h" diff --git a/dGame/dMission/MissionTask.h b/dGame/dMission/MissionTask.h index 14d885c3..ea4b8a05 100644 --- a/dGame/dMission/MissionTask.h +++ b/dGame/dMission/MissionTask.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef MISSIONTASK_H #define MISSIONTASK_H diff --git a/dGame/dMission/MissionTaskType.h b/dGame/dMission/MissionTaskType.h index 08f1bff9..6c9b2668 100644 --- a/dGame/dMission/MissionTaskType.h +++ b/dGame/dMission/MissionTaskType.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #ifndef MISSIONTASKTYPE_H #define MISSIONTASKTYPE_H diff --git a/dGame/dUtilities/Preconditions.h b/dGame/dUtilities/Preconditions.h index 08e564bf..2b6e1216 100644 --- a/dGame/dUtilities/Preconditions.h +++ b/dGame/dUtilities/Preconditions.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include #include "Entity.h" diff --git a/dScripts/AgJetEffectServer.cpp b/dScripts/AgJetEffectServer.cpp index 748b947b..8c7eca3b 100644 --- a/dScripts/AgJetEffectServer.cpp +++ b/dScripts/AgJetEffectServer.cpp @@ -1,4 +1,4 @@ -#include "AgJetEffectServer.h" +#include "AgJetEffectServer.h" #include "GameMessages.h" #include "EntityManager.h" #include "SkillComponent.h" diff --git a/dScripts/AgJetEffectServer.h b/dScripts/AgJetEffectServer.h index 094c73d2..3cb3bd83 100644 --- a/dScripts/AgJetEffectServer.h +++ b/dScripts/AgJetEffectServer.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class AgJetEffectServer final : public CppScripts::Script diff --git a/dScripts/AgPropGuard.cpp b/dScripts/AgPropGuard.cpp index c8376b3e..51f76a27 100644 --- a/dScripts/AgPropGuard.cpp +++ b/dScripts/AgPropGuard.cpp @@ -1,4 +1,4 @@ -#include "AgPropGuard.h" +#include "AgPropGuard.h" #include "Entity.h" #include "Character.h" #include "EntityManager.h" diff --git a/dScripts/AgPropGuard.h b/dScripts/AgPropGuard.h index 4f6a96d9..f68573dd 100644 --- a/dScripts/AgPropGuard.h +++ b/dScripts/AgPropGuard.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class AgPropGuard final : public CppScripts::Script diff --git a/dScripts/AgSalutingNpcs.cpp b/dScripts/AgSalutingNpcs.cpp index 28495f58..4e4d8b2c 100644 --- a/dScripts/AgSalutingNpcs.cpp +++ b/dScripts/AgSalutingNpcs.cpp @@ -1,4 +1,4 @@ -#include "AgSalutingNpcs.h" +#include "AgSalutingNpcs.h" #include "GameMessages.h" diff --git a/dScripts/AgSalutingNpcs.h b/dScripts/AgSalutingNpcs.h index 7dd20316..c53d03b2 100644 --- a/dScripts/AgSalutingNpcs.h +++ b/dScripts/AgSalutingNpcs.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class AgSalutingNpcs final : public CppScripts::Script diff --git a/dScripts/BossSpiderQueenEnemyServer.cpp b/dScripts/BossSpiderQueenEnemyServer.cpp index 438493fe..ef81c888 100644 --- a/dScripts/BossSpiderQueenEnemyServer.cpp +++ b/dScripts/BossSpiderQueenEnemyServer.cpp @@ -1,4 +1,4 @@ -#include "BossSpiderQueenEnemyServer.h" +#include "BossSpiderQueenEnemyServer.h" #include "GeneralUtils.h" diff --git a/dScripts/BossSpiderQueenEnemyServer.h b/dScripts/BossSpiderQueenEnemyServer.h index e41b878d..8f73d99f 100644 --- a/dScripts/BossSpiderQueenEnemyServer.h +++ b/dScripts/BossSpiderQueenEnemyServer.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" /* diff --git a/dScripts/FvNinjaGuard.cpp b/dScripts/FvNinjaGuard.cpp index 0a3cb19c..6a841ccf 100644 --- a/dScripts/FvNinjaGuard.cpp +++ b/dScripts/FvNinjaGuard.cpp @@ -1,4 +1,4 @@ -#include "FvNinjaGuard.h" +#include "FvNinjaGuard.h" #include "GameMessages.h" #include "MissionComponent.h" diff --git a/dScripts/FvNinjaGuard.h b/dScripts/FvNinjaGuard.h index f3deb140..8a87e8bc 100644 --- a/dScripts/FvNinjaGuard.h +++ b/dScripts/FvNinjaGuard.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class FvNinjaGuard final : public CppScripts::Script diff --git a/dScripts/GfBanana.cpp b/dScripts/GfBanana.cpp index d64f1620..3a71eded 100644 --- a/dScripts/GfBanana.cpp +++ b/dScripts/GfBanana.cpp @@ -1,4 +1,4 @@ -#include "GfBanana.h" +#include "GfBanana.h" #include "Entity.h" #include "DestroyableComponent.h" diff --git a/dScripts/GfBanana.h b/dScripts/GfBanana.h index 8deb2396..a33bddf6 100644 --- a/dScripts/GfBanana.h +++ b/dScripts/GfBanana.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class GfBanana final : public CppScripts::Script diff --git a/dScripts/GfBananaCluster.cpp b/dScripts/GfBananaCluster.cpp index 19d1b489..6e5e91db 100644 --- a/dScripts/GfBananaCluster.cpp +++ b/dScripts/GfBananaCluster.cpp @@ -1,4 +1,4 @@ -#include "GfBananaCluster.h" +#include "GfBananaCluster.h" #include "Entity.h" void GfBananaCluster::OnStartup(Entity* self) { diff --git a/dScripts/GfBananaCluster.h b/dScripts/GfBananaCluster.h index 05e5ee0a..81bb8b0b 100644 --- a/dScripts/GfBananaCluster.h +++ b/dScripts/GfBananaCluster.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class GfBananaCluster final : public CppScripts::Script diff --git a/dScripts/GfJailkeepMission.cpp b/dScripts/GfJailkeepMission.cpp index 59f8db0e..eaa8c73d 100644 --- a/dScripts/GfJailkeepMission.cpp +++ b/dScripts/GfJailkeepMission.cpp @@ -1,4 +1,4 @@ -#include "GfJailkeepMission.h" +#include "GfJailkeepMission.h" #include "MissionComponent.h" #include "Character.h" diff --git a/dScripts/GfJailkeepMission.h b/dScripts/GfJailkeepMission.h index f9410032..a120d29b 100644 --- a/dScripts/GfJailkeepMission.h +++ b/dScripts/GfJailkeepMission.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class GfJailkeepMission final : public CppScripts::Script diff --git a/dScripts/NtSleepingGuard.cpp b/dScripts/NtSleepingGuard.cpp index 597b5997..145df6c8 100644 --- a/dScripts/NtSleepingGuard.cpp +++ b/dScripts/NtSleepingGuard.cpp @@ -1,4 +1,4 @@ -#include "NtSleepingGuard.h" +#include "NtSleepingGuard.h" #include "GameMessages.h" #include "MissionComponent.h" diff --git a/dScripts/NtSleepingGuard.h b/dScripts/NtSleepingGuard.h index 42f7391e..5129ae4f 100644 --- a/dScripts/NtSleepingGuard.h +++ b/dScripts/NtSleepingGuard.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class NtSleepingGuard final : public CppScripts::Script diff --git a/dScripts/SpecialImaginePowerupSpawner.cpp b/dScripts/SpecialImaginePowerupSpawner.cpp index 0a13fc2b..c6cab294 100644 --- a/dScripts/SpecialImaginePowerupSpawner.cpp +++ b/dScripts/SpecialImaginePowerupSpawner.cpp @@ -1,4 +1,4 @@ -#include "SpecialImaginePowerupSpawner.h" +#include "SpecialImaginePowerupSpawner.h" #include "GameMessages.h" #include "SkillComponent.h" diff --git a/dScripts/SpecialImaginePowerupSpawner.h b/dScripts/SpecialImaginePowerupSpawner.h index 6cfe2c6e..eb628951 100644 --- a/dScripts/SpecialImaginePowerupSpawner.h +++ b/dScripts/SpecialImaginePowerupSpawner.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class SpecialImaginePowerupSpawner final : public CppScripts::Script diff --git a/dScripts/TriggerAmbush.cpp b/dScripts/TriggerAmbush.cpp index 8c408b32..726b45d7 100644 --- a/dScripts/TriggerAmbush.cpp +++ b/dScripts/TriggerAmbush.cpp @@ -1,4 +1,4 @@ -#include "TriggerAmbush.h" +#include "TriggerAmbush.h" #include "dZoneManager.h" diff --git a/dScripts/TriggerAmbush.h b/dScripts/TriggerAmbush.h index 0544f3cb..e4388fbe 100644 --- a/dScripts/TriggerAmbush.h +++ b/dScripts/TriggerAmbush.h @@ -1,4 +1,4 @@ -#pragma once +#pragma once #include "CppScripts.h" class TriggerAmbush : public CppScripts::Script From 6c97ea820876ce10e4a6197dc1cd3739fef116a5 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Sat, 6 Aug 2022 09:19:34 +0100 Subject: [PATCH 073/322] Implement flying command (#713) * Implement flying command * Add documentation. --- dGame/Character.h | 17 ++++++++++++ dGame/dBehaviors/JetPackBehavior.cpp | 18 +++++++++++++ dGame/dUtilities/SlashCommandHandler.cpp | 34 ++++++++++++++++++++++++ docs/Commands.md | 1 + 4 files changed, 70 insertions(+) diff --git a/dGame/Character.h b/dGame/Character.h index 1a1d4cd0..52bff83d 100644 --- a/dGame/Character.h +++ b/dGame/Character.h @@ -425,6 +425,18 @@ public: */ const std::vector& GetEquippedItems() const { return m_EquippedItems; } + /** + * @brief Get the flying state + * @return value of the flying state + */ + bool GetIsFlying() { return m_IsFlying; } + + /** + * @brief Set the value of the flying state + * @param isFlying the flying state + */ + void SetIsFlying(bool isFlying) { m_IsFlying = isFlying; } + private: /** * The ID of this character. First 32 bits of the ObjectID. @@ -621,6 +633,11 @@ private: */ std::string m_TargetScene; + /** + * Bool that tracks the flying state of the user. + */ + bool m_IsFlying = false; + /** * Queries the character XML and updates all the fields of this object * NOTE: quick as there's no DB lookups diff --git a/dGame/dBehaviors/JetPackBehavior.cpp b/dGame/dBehaviors/JetPackBehavior.cpp index 00900735..e7d76560 100644 --- a/dGame/dBehaviors/JetPackBehavior.cpp +++ b/dGame/dBehaviors/JetPackBehavior.cpp @@ -3,16 +3,34 @@ #include "BehaviorBranchContext.h" #include "GameMessages.h" +#include "Character.h" + void JetPackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); GameMessages::SendSetJetPackMode(entity, true, this->m_BypassChecks, this->m_EnableHover, this->m_effectId, this->m_Airspeed, this->m_MaxAirspeed, this->m_VerticalVelocity, this->m_WarningEffectID); + + if (entity->IsPlayer()) { + auto* character = entity->GetCharacter(); + + if (character) { + character->SetIsFlying(true); + } + } } void JetPackBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); GameMessages::SendSetJetPackMode(entity, false); + + if (entity->IsPlayer()) { + auto* character = entity->GetCharacter(); + + if (character) { + character->SetIsFlying(false); + } + } } void JetPackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 0bf37288..b91021de 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -942,6 +942,40 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } + if (chatCommand == "fly" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_JUNIOR_DEVELOPER) { + auto* character = entity->GetCharacter(); + + if (character) { + bool isFlying = character->GetIsFlying(); + + if (isFlying) { + GameMessages::SendSetJetPackMode(entity, false); + + character->SetIsFlying(false); + } else { + float speedScale = 1.0f; + + if (args.size() >= 1) { + float tempScaleStore; + + if (GeneralUtils::TryParse(args[0], tempScaleStore)) { + speedScale = tempScaleStore; + } else { + ChatPackets::SendSystemMessage(sysAddr, u"Failed to parse speed scale argument."); + } + } + + float airSpeed = 20 * speedScale; + float maxAirSpeed = 30 * speedScale; + float verticalVelocity = 1.5 * speedScale; + + GameMessages::SendSetJetPackMode(entity, true, true, false, 167, airSpeed, maxAirSpeed, verticalVelocity); + + character->SetIsFlying(true); + } + } + } + //------- GM COMMANDS TO ACTUALLY MODERATE -------- if (chatCommand == "mute" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_JUNIOR_DEVELOPER) { diff --git a/docs/Commands.md b/docs/Commands.md index b5588f68..8cefaa14 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -32,6 +32,7 @@ Here is a summary of the commands available in-game. All commands are prefixed b |gminvis|`/gminvis`|Toggles invisibility for the character, though it's currently a bit buggy. Requires nonzero GM Level for the character, but the account must have a GM level of 8.|8| |setname|`/setname `|Sets a temporary name for your player. The name resets when you log out.|8| |title|`/title `|Temporarily appends your player's name with " - <title>". This resets when you log out.|8| +|fly|`/fly <speed>`|This toggles your flying state with an optional parameter for the speed scale.|4| ## Server Operation Commands From 7f5ab8b9faf55d03a4f2b99152bfffb537bd811b Mon Sep 17 00:00:00 2001 From: Zac Hayes <zrev2220@gmail.com> Date: Sun, 7 Aug 2022 01:59:27 -0400 Subject: [PATCH 074/322] Dockerfile: Copy dNavigation to build dir (#722) Fixes an issue where new directory was not copied over to the correct folder for Docker --- docker/Dockerfile | 1 + 1 file changed, 1 insertion(+) diff --git a/docker/Dockerfile b/docker/Dockerfile index 27387e22..50f5b083 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -21,6 +21,7 @@ COPY dPhysics/ /build/dPhysics COPY dScripts/ /build/dScripts COPY dWorldServer/ /build/dWorldServer COPY dZoneManager/ /build/dZoneManager +COPY dNavigation/ /build/dNavigation COPY migrations/ /build/migrations COPY resources/ /build/resources COPY thirdparty/ /build/thirdparty From 932d8030f0c966592fcc9f8f3105ec86cdea1b07 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Mon, 8 Aug 2022 08:31:44 -0500 Subject: [PATCH 075/322] update git blame ignore --- .git-blame-ignore-revs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 78e9475c..37567a02 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -3,3 +3,6 @@ # add semi-colons to macros consistently 9e4ce24fd2851e65df776dd9c57bcb0d45f4453a + +# convert to unix line endings +72477e01e2711e0f61cdb192ee266e5e21b8846f From dc960cb99cf8026a4e8335821ea3f7ed51dd9b32 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 8 Aug 2022 07:34:33 -0700 Subject: [PATCH 076/322] Fix landing animation (#720) --- dGame/dComponents/CharacterComponent.cpp | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 42b8ed34..d425c066 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -36,15 +36,6 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C m_CurrentActivity = 0; m_CountryCode = 0; m_LastUpdateTimestamp = std::time(nullptr); - - //Check to see if we're landing: - if (character->GetZoneID() != Game::server->GetZoneID()) { - m_IsLanding = true; - } - - if (LandingAnimDisabled(character->GetZoneID()) || LandingAnimDisabled(Game::server->GetZoneID()) || m_LastRocketConfig.empty()) { - m_IsLanding = false; //Don't make us land on VE/minigames lol - } } bool CharacterComponent::LandingAnimDisabled(int zoneID) { @@ -273,6 +264,17 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { } else { m_TotalTimePlayed = 0; } + + if (!m_Character) return; + + //Check to see if we're landing: + if (m_Character->GetZoneID() != Game::server->GetZoneID()) { + m_IsLanding = true; + } + + if (LandingAnimDisabled(m_Character->GetZoneID()) || LandingAnimDisabled(Game::server->GetZoneID()) || m_LastRocketConfig.empty()) { + m_IsLanding = false; //Don't make us land on VE/minigames lol + } } void CharacterComponent::UpdateXml(tinyxml2::XMLDocument* doc) { From 008f953003abdf25d23c52c515fcd63272b3efdc Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 8 Aug 2022 07:34:56 -0700 Subject: [PATCH 077/322] Add physics volume for property orb (#718) --- dGame/dComponents/PhantomPhysicsComponent.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index 8cafec52..430acf3c 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -205,6 +205,12 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par m_dpEntity->SetRotation(m_Rotation); m_dpEntity->SetPosition(m_Position); dpWorld::Instance().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::Instance().AddEntity(m_dpEntity); } else { //Game::logger->Log("PhantomPhysicsComponent", "This one is supposed to have %s", info->physicsAsset.c_str()); From 1e1b6aaa0befd86c0d3fe1609958699812b3fdc2 Mon Sep 17 00:00:00 2001 From: Emmett <EmmettPeck@gmail.com> Date: Sun, 14 Aug 2022 11:05:07 -0700 Subject: [PATCH 078/322] Update Docker.md submodule note (#730) * Update Docker.md Changed note to recursively update git submodules, otherwise would lead users into #728 --- Docker.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Docker.md b/Docker.md index 7d5f7bc6..54d0ce19 100644 --- a/Docker.md +++ b/Docker.md @@ -25,8 +25,7 @@ **NOTE #4**: Make sure to run the following in the repo root directory after cloning so submodules are also downloaded. ``` -git submodule init -git submodule update +git submodule update --init --recursive ``` **NOTE #5**: If DarkflameSetup fails due to not having cdclient.fdb, rename CDClient.fdb (in the same folder) to cdclient.fdb From 54021458bd807774e2db4e60891abfbeaa30bdf8 Mon Sep 17 00:00:00 2001 From: Demetri Van Sickle <demetriv.s.7@gmail.com> Date: Tue, 16 Aug 2022 01:49:44 -0700 Subject: [PATCH 079/322] Change build command in build script (#729) The script now uses the cmake build as to be compatible with all platforms as opposed to just platforms that supported gnu make. --- build.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.sh b/build.sh index 31eaa2c7..e61c1cb4 100755 --- a/build.sh +++ b/build.sh @@ -5,8 +5,8 @@ cd build # Run cmake to generate make files cmake .. -# Run make to build the project. To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `make -j8` -make +# To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `cmake --build . --config Release -j8' +cmake --build . --config Release # Run migrations ./MasterServer -m From 3b7f1dad5472c8ee52b6890768d87710e8c49bbe Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 16 Aug 2022 18:53:01 -0700 Subject: [PATCH 080/322] Fix death planes (#733) * Correct death plane size The death plane file size is not in units but is actually in 4x2 tiles. * Make it a bit bigger for now --- dGame/dComponents/PhantomPhysicsComponent.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index 430acf3c..ea88c16d 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -162,7 +162,8 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par dpWorld::Instance().AddEntity(m_dpEntity); } else if (info->physicsAsset == "miscellaneous\\misc_phys_640x640.hkx") { - m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 640.0f, 20.0f, 640.0f); + // 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); From 976bd3c41b7fcd0262db40b010c365449bb9c94e Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Tue, 16 Aug 2022 20:53:28 -0500 Subject: [PATCH 081/322] Selective saving for map and location (#732) * Don't save the map and char location info if we are in an instanced * LUP worlds will be handled in a future PR * simplify check --- dGame/Character.cpp | 4 ++-- .../ControllablePhysicsComponent.cpp | 19 ++++++++++++------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/dGame/Character.cpp b/dGame/Character.cpp index 0b92f0aa..440c30c1 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -301,9 +301,9 @@ void Character::SaveXMLToDatabase() { character->SetAttribute("gm", m_GMLevel); character->SetAttribute("cc", m_Coins); + auto zoneInfo = dZoneManager::Instance()->GetZone()->GetZoneID(); // lzid garbage, binary concat of zoneID, zoneInstance and zoneClone - if (Game::server->GetZoneID() != 0) { - auto zoneInfo = dZoneManager::Instance()->GetZone()->GetZoneID(); + if (zoneInfo.GetMapID() != 0 && zoneInfo.GetCloneID() == 0) { uint64_t lzidConcat = zoneInfo.GetCloneID(); lzidConcat = (lzidConcat << 16) | uint16_t(zoneInfo.GetInstanceID()); lzidConcat = (lzidConcat << 16) | uint16_t(zoneInfo.GetMapID()); diff --git a/dGame/dComponents/ControllablePhysicsComponent.cpp b/dGame/dComponents/ControllablePhysicsComponent.cpp index 19c17035..471b9ca1 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/ControllablePhysicsComponent.cpp @@ -11,6 +11,7 @@ #include "CDClientManager.h" #include "EntityManager.h" #include "Character.h" +#include "dZoneManager.h" ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Component(entity) { m_Position = {}; @@ -163,13 +164,17 @@ void ControllablePhysicsComponent::UpdateXml(tinyxml2::XMLDocument* doc) { return; } - character->SetAttribute("lzx", m_Position.x); - character->SetAttribute("lzy", m_Position.y); - character->SetAttribute("lzz", m_Position.z); - character->SetAttribute("lzrx", m_Rotation.x); - character->SetAttribute("lzry", m_Rotation.y); - character->SetAttribute("lzrz", m_Rotation.z); - character->SetAttribute("lzrw", m_Rotation.w); + auto zoneInfo = dZoneManager::Instance()->GetZone()->GetZoneID(); + + if (zoneInfo.GetMapID() != 0 && zoneInfo.GetCloneID() == 0) { + character->SetAttribute("lzx", m_Position.x); + character->SetAttribute("lzy", m_Position.y); + character->SetAttribute("lzz", m_Position.z); + character->SetAttribute("lzrx", m_Rotation.x); + character->SetAttribute("lzry", m_Rotation.y); + character->SetAttribute("lzrz", m_Rotation.z); + character->SetAttribute("lzrw", m_Rotation.w); + } } void ControllablePhysicsComponent::SetPosition(const NiPoint3& pos) { From 50b3946548b0279a4316137c894291bc3f58d7a8 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 16 Aug 2022 20:28:50 -0700 Subject: [PATCH 082/322] Fix death planes (#735) * Correct death plane size The death plane file size is not in units but is actually in 4x2 tiles. * Make it a bit bigger for now * Enjoy your crust "These things add flavor they said" Move the position of the death barrier down 13.521004 units so we effectively only extend its hitbox in the -Y direction as opposed to the +Y direction, resolving an issue in Battle of Nimbus Station where the death plane was too tall --- dGame/dComponents/PhantomPhysicsComponent.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index ea88c16d..cef9cc36 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -162,6 +162,8 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par dpWorld::Instance().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; // 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); From dd8091f60e5088e48a2d8487b58033b63b393115 Mon Sep 17 00:00:00 2001 From: Daniel Seiler <me@xiphoseer.de> Date: Wed, 17 Aug 2022 10:43:54 +0200 Subject: [PATCH 083/322] Hide dependency compilation warnings (#696) * Hide raknet compilation warnings * Move out MariaDB Connector/C++ logic * remove mariadb warnings? * hide mariadb cmake warnings? --- thirdparty/CMakeLists.txt | 160 +------------------------------ thirdparty/CMakeMariaDBLists.txt | 149 ++++++++++++++++++++++++++++ thirdparty/raknet/CMakeLists.txt | 27 +++--- 3 files changed, 169 insertions(+), 167 deletions(-) create mode 100644 thirdparty/CMakeMariaDBLists.txt diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt index 119ce4fd..c04e418e 100644 --- a/thirdparty/CMakeLists.txt +++ b/thirdparty/CMakeLists.txt @@ -1,11 +1,3 @@ -# Source Code for raknet -file( - GLOB SOURCES_RAKNET - LIST_DIRECTORIES false - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" - ${CMAKE_CURRENT_SOURCE_DIR}/raknet/Source/*.cpp -) - # Source Code for recast file( GLOB SOURCES_RECAST @@ -47,167 +39,23 @@ file( ${CMAKE_CURRENT_SOURCE_DIR}/SQLite/*.c ) -# mariadb connector cpp -# On Windows ClangCL can't compile the connector from source but can link to an msvc compiled one, -# so prefer the prebuilt binaries unless MARIADB_BUILD_SOURCE is specified -if(WIN32 AND NOT MARIADB_BUILD_SOURCE) - set(MARIADB_MSI_DIR "${PROJECT_BINARY_DIR}/msi") - set(MARIADB_CONNECTOR_DIR "${PROJECT_BINARY_DIR}/mariadbcpp") - set(MARIADB_C_CONNECTOR_DIR "${MARIADB_CONNECTOR_DIR}/MariaDB/MariaDB Connector C 64-bit") - set(MARIADB_CPP_CONNECTOR_DIR "${MARIADB_CONNECTOR_DIR}/MariaDB/MariaDB C++ Connector 64-bit") - - file(MAKE_DIRECTORY "${MARIADB_MSI_DIR}") - file(MAKE_DIRECTORY "${MARIADB_CONNECTOR_DIR}") - - if(NOT EXISTS "${MARIADB_MSI_DIR}/mariadb-connector-c-3.2.5-win64.msi" ) - message("Downloading mariadb connector/c") - file(DOWNLOAD https://dlm.mariadb.com/1936366/connectors/c/connector-c-3.2.5/mariadb-connector-c-3.2.5-win64.msi - "${MARIADB_MSI_DIR}/mariadb-connector-c-3.2.5-win64.msi" - EXPECTED_HASH MD5=09d418c290109068a5bea136dafca36b) - endif() - - if(NOT EXISTS "${MARIADB_MSI_DIR}/mariadb-connector-cpp-1.0.1-win64.msi" ) - message("Downloading mariadb connector/c++") - file(DOWNLOAD https://dlm.mariadb.com/1683453/connectors/cpp/connector-cpp-1.0.1/mariadb-connector-cpp-1.0.1-win64.msi - "${MARIADB_MSI_DIR}/mariadb-connector-cpp-1.0.1-win64.msi" - EXPECTED_HASH MD5=548e743fbf067d21d42b81d958bf4ed7) - endif() - - - file(TO_NATIVE_PATH "${MARIADB_CONNECTOR_DIR}" MSIEXEC_TARGETDIR) - # extract msi files without installing to users system - if(NOT EXISTS "${MARIADB_C_CONNECTOR_DIR}") - file(TO_NATIVE_PATH "${MARIADB_MSI_DIR}/mariadb-connector-c-3.2.5-win64.msi" MSI_DIR) - execute_process(COMMAND msiexec /a ${MSI_DIR} /qn TARGETDIR=${MSIEXEC_TARGETDIR}) - endif() - - if(NOT EXISTS "${MARIADB_CPP_CONNECTOR_DIR}") - file(TO_NATIVE_PATH "${MARIADB_MSI_DIR}/mariadb-connector-cpp-1.0.1-win64.msi" MSI_DIR) - execute_process(COMMAND msiexec /a ${MSI_DIR} /qn TARGETDIR=${MSIEXEC_TARGETDIR}) - endif() - - set(MARIADB_SHARED_LIBRARY_LOCATION "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.dll") - set(MARIADB_IMPLIB_LOCATION "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.lib") - set(MARIADB_INCLUDE_DIR "${MARIADB_CPP_CONNECTOR_DIR}/include/mariadb") - - add_custom_target(mariadb_connector_cpp) - add_custom_command(TARGET mariadb_connector_cpp POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.dll" - "${MARIADB_C_CONNECTOR_DIR}/lib/libmariadb.dll" - "${PROJECT_BINARY_DIR}") - - # MariaDB uses plugins that the database needs to load, the prebuilt binaries by default will try to find the libraries in system directories, - # so set this define and the servers will set the MARIADB_PLUGIN_DIR environment variable to the appropriate directory. - # Plugin directory is determined at dll load time (this will happen before main()) so we need to delay the dll load so that we can set the environment variable - add_link_options(/DELAYLOAD:${MARIADB_SHARED_LIBRARY_LOCATION}) - add_compile_definitions(MARIADB_PLUGIN_DIR_OVERRIDE="${MARIADB_CPP_CONNECTOR_DIR}/plugin") -else() # Build from source - - include(ExternalProject) - if(WIN32) - set(MARIADB_EXTRA_COMPILE_FLAGS /EHsc) - set(MARIADB_EXTRA_CMAKE_ARGS -DWITH_MSI=OFF) - elseif(APPLE) - set(MARIADB_EXTRA_COMPILE_FLAGS -D_GLIBCXX_USE_CXX11_ABI=0) - set(MARIADB_EXTRA_CMAKE_ARGS -DWITH_EXTERNAL_ZLIB=ON -DOPENSSL_ROOT_DIR=${OPENSSL_ROOT_DIR}) - else() - set(MARIADB_EXTRA_COMPILE_FLAGS -D_GLIBCXX_USE_CXX11_ABI=0) - endif() - - ExternalProject_Add(mariadb_connector_cpp - SOURCE_DIR ${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp - CMAKE_ARGS "-DCMAKE_CXX_FLAGS:STRING= ${MARIADB_EXTRA_COMPILE_FLAGS}" - -DCMAKE_BUILD_RPATH_USE_ORIGIN=${CMAKE_BUILD_RPATH_USE_ORIGIN} - -DCMAKE_INSTALL_PREFIX=./mariadbcpp # Points the connector to the correct plugin directory - -DINSTALL_PLUGINDIR=plugin - ${MARIADB_EXTRA_CMAKE_ARGS} - PREFIX "${PROJECT_BINARY_DIR}/mariadbcpp" - BUILD_COMMAND cmake --build . --config RelWithDebInfo -j${__maria_db_connector_compile_jobs__} - INSTALL_COMMAND "") - - ExternalProject_Get_Property(mariadb_connector_cpp BINARY_DIR) - - if(WIN32) - set(MARIADB_SHARED_LIBRARY_NAME mariadbcpp.dll) - set(MARIADB_PLUGIN_SUFFIX .dll) - set(MARIADB_IMPLIB_LOCATION "${BINARY_DIR}/RelWithDebInfo/mariadbcpp.lib") - - # When built from source windows only seems to check same folder as exe instead specified folder, so use - # environment variable to force it - add_link_options(/DELAYLOAD:mariadbcpp.dll) - add_compile_definitions(MARIADB_PLUGIN_DIR_OVERRIDE="${PROJECT_BINARY_DIR}/mariadbcpp/plugin") - else() - set(MARIADB_SHARED_LIBRARY_NAME libmariadbcpp${CMAKE_SHARED_LIBRARY_SUFFIX}) - set(MARIADB_PLUGIN_SUFFIX .so) - endif() - - get_property(isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) - if(isMultiConfig) - set(MARIADB_SHARED_LIBRARY_LOCATION "${BINARY_DIR}/RelWithDebInfo/${MARIADB_SHARED_LIBRARY_NAME}") - set(MARIADB_SHARED_LIBRARY_COPY_LOCATION "${PROJECT_BINARY_DIR}/$<CONFIG>") - set(MARIADB_PLUGINS_LOCATION "${BINARY_DIR}/libmariadb/RelWithDebInfo") - else() - set(MARIADB_SHARED_LIBRARY_LOCATION "${BINARY_DIR}/${MARIADB_SHARED_LIBRARY_NAME}") - set(MARIADB_SHARED_LIBRARY_COPY_LOCATION "${PROJECT_BINARY_DIR}") - set(MARIADB_PLUGINS_LOCATION "${BINARY_DIR}/libmariadb") - endif() - - set(MARIADB_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/include/") - - add_custom_command(TARGET mariadb_connector_cpp POST_BUILD - COMMAND ${CMAKE_COMMAND} -E make_directory - ${BINARY_DIR}/mariadbcpp/plugin - ${MARIADB_SHARED_LIBRARY_COPY_LOCATION} - - COMMAND ${CMAKE_COMMAND} -E copy_if_different - ${MARIADB_SHARED_LIBRARY_LOCATION} - ${MARIADB_SHARED_LIBRARY_COPY_LOCATION} - - COMMAND ${CMAKE_COMMAND} -E copy_if_different - ${MARIADB_PLUGINS_LOCATION}/caching_sha2_password${MARIADB_PLUGIN_SUFFIX} - ${MARIADB_PLUGINS_LOCATION}/client_ed25519${MARIADB_PLUGIN_SUFFIX} - ${MARIADB_PLUGINS_LOCATION}/dialog${MARIADB_PLUGIN_SUFFIX} - ${MARIADB_PLUGINS_LOCATION}/mysql_clear_password${MARIADB_PLUGIN_SUFFIX} - ${MARIADB_PLUGINS_LOCATION}/sha256_password${MARIADB_PLUGIN_SUFFIX} - ${BINARY_DIR}/mariadbcpp/plugin) -endif() - -# Remove the CMakeLists.txt file from the tests folder for the maria-db-connector so we dont compile the tests. -if(EXISTS "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/test/CMakeLists.txt") - file(REMOVE "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/test/CMakeLists.txt") -endif() - -# Create mariadb connector library object -add_library(mariadbConnCpp SHARED IMPORTED GLOBAL) -set_property(TARGET mariadbConnCpp PROPERTY IMPORTED_LOCATION ${MARIADB_SHARED_LIBRARY_LOCATION}) - -if(WIN32) - set_property(TARGET mariadbConnCpp PROPERTY IMPORTED_IMPLIB ${MARIADB_IMPLIB_LOCATION}) -endif() - -# Add directories to include lists -target_include_directories(mariadbConnCpp INTERFACE ${MARIADB_INCLUDE_DIR}) -add_dependencies(mariadbConnCpp mariadb_connector_cpp) +# MariaDB C++ Connector +include(CMakeMariaDBLists.txt) # Create our third party library objects -add_library(raknet ${SOURCES_RAKNET}) +add_subdirectory(raknet) add_library(tinyxml2 ${SOURCES_TINYXML2}) add_library(detour ${SOURCES_DETOUR}) add_library(recast ${SOURCES_RECAST}) add_library(libbcrypt ${SOURCES_LIBBCRYPT}) add_library(sqlite3 ${SOURCES_SQLITE3}) -if(WIN32) - # Link Win Sockets 2 to RakNet - target_link_libraries(raknet ws2_32) -elseif(UNIX) +if(UNIX) # Add warning disable flags and link Unix libraries to sqlite3 target_link_libraries(sqlite3 pthread dl m) # -Wno-unused-result -Wno-unknown-pragmas -fpermissive target_compile_options(sqlite3 PRIVATE "-Wno-return-local-addr" "-Wno-maybe-uninitialized") - target_compile_options(raknet PRIVATE "-Wno-write-strings" "-Wformat-overflow=0" "-Wformat=0") target_compile_options(libbcrypt PRIVATE "-Wno-implicit-function-declaration" "-Wno-int-conversion") endif() diff --git a/thirdparty/CMakeMariaDBLists.txt b/thirdparty/CMakeMariaDBLists.txt new file mode 100644 index 00000000..55e95c4d --- /dev/null +++ b/thirdparty/CMakeMariaDBLists.txt @@ -0,0 +1,149 @@ +# mariadb connector cpp +# On Windows ClangCL can't compile the connector from source but can link to an msvc compiled one, +# so prefer the prebuilt binaries unless MARIADB_BUILD_SOURCE is specified +if(WIN32 AND NOT MARIADB_BUILD_SOURCE) + set(MARIADB_MSI_DIR "${PROJECT_BINARY_DIR}/msi") + set(MARIADB_CONNECTOR_DIR "${PROJECT_BINARY_DIR}/mariadbcpp") + set(MARIADB_C_CONNECTOR_DIR "${MARIADB_CONNECTOR_DIR}/MariaDB/MariaDB Connector C 64-bit") + set(MARIADB_CPP_CONNECTOR_DIR "${MARIADB_CONNECTOR_DIR}/MariaDB/MariaDB C++ Connector 64-bit") + + file(MAKE_DIRECTORY "${MARIADB_MSI_DIR}") + file(MAKE_DIRECTORY "${MARIADB_CONNECTOR_DIR}") + + if(NOT EXISTS "${MARIADB_MSI_DIR}/mariadb-connector-c-3.2.5-win64.msi" ) + message("Downloading mariadb connector/c") + file(DOWNLOAD https://dlm.mariadb.com/1936366/connectors/c/connector-c-3.2.5/mariadb-connector-c-3.2.5-win64.msi + "${MARIADB_MSI_DIR}/mariadb-connector-c-3.2.5-win64.msi" + EXPECTED_HASH MD5=09d418c290109068a5bea136dafca36b) + endif() + + if(NOT EXISTS "${MARIADB_MSI_DIR}/mariadb-connector-cpp-1.0.1-win64.msi" ) + message("Downloading mariadb connector/c++") + file(DOWNLOAD https://dlm.mariadb.com/1683453/connectors/cpp/connector-cpp-1.0.1/mariadb-connector-cpp-1.0.1-win64.msi + "${MARIADB_MSI_DIR}/mariadb-connector-cpp-1.0.1-win64.msi" + EXPECTED_HASH MD5=548e743fbf067d21d42b81d958bf4ed7) + endif() + + + file(TO_NATIVE_PATH "${MARIADB_CONNECTOR_DIR}" MSIEXEC_TARGETDIR) + # extract msi files without installing to users system + if(NOT EXISTS "${MARIADB_C_CONNECTOR_DIR}") + file(TO_NATIVE_PATH "${MARIADB_MSI_DIR}/mariadb-connector-c-3.2.5-win64.msi" MSI_DIR) + execute_process(COMMAND msiexec /a ${MSI_DIR} /qn TARGETDIR=${MSIEXEC_TARGETDIR}) + endif() + + if(NOT EXISTS "${MARIADB_CPP_CONNECTOR_DIR}") + file(TO_NATIVE_PATH "${MARIADB_MSI_DIR}/mariadb-connector-cpp-1.0.1-win64.msi" MSI_DIR) + execute_process(COMMAND msiexec /a ${MSI_DIR} /qn TARGETDIR=${MSIEXEC_TARGETDIR}) + endif() + + set(MARIADB_SHARED_LIBRARY_LOCATION "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.dll") + set(MARIADB_IMPLIB_LOCATION "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.lib") + set(MARIADB_INCLUDE_DIR "${MARIADB_CPP_CONNECTOR_DIR}/include/mariadb") + + add_custom_target(mariadb_connector_cpp) + add_custom_command(TARGET mariadb_connector_cpp POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.dll" + "${MARIADB_C_CONNECTOR_DIR}/lib/libmariadb.dll" + "${PROJECT_BINARY_DIR}") + + # MariaDB uses plugins that the database needs to load, the prebuilt binaries by default will try to find the libraries in system directories, + # so set this define and the servers will set the MARIADB_PLUGIN_DIR environment variable to the appropriate directory. + # Plugin directory is determined at dll load time (this will happen before main()) so we need to delay the dll load so that we can set the environment variable + add_link_options(/DELAYLOAD:${MARIADB_SHARED_LIBRARY_LOCATION}) + add_compile_definitions(MARIADB_PLUGIN_DIR_OVERRIDE="${MARIADB_CPP_CONNECTOR_DIR}/plugin") +else() # Build from source + + include(ExternalProject) + if(WIN32) + set(MARIADB_EXTRA_CMAKE_ARGS + -DCMAKE_C_FLAGS=/w # disable zlib warnings + -DCMAKE_CXX_FLAGS=/EHsc + -DWITH_MSI=OFF) + elseif(APPLE) + set(MARIADB_EXTRA_CMAKE_ARGS + -DWITH_EXTERNAL_ZLIB=ON + -DOPENSSL_ROOT_DIR=${OPENSSL_ROOT_DIR} + -DCMAKE_C_FLAGS=-w # disable zlib warnings + -DCMAKE_CXX_FLAGS=-D_GLIBCXX_USE_CXX11_ABI=0) + else() + set(MARIADB_EXTRA_CMAKE_ARGS + -DCMAKE_C_FLAGS=-w # disable zlib warnings + -DCMAKE_CXX_FLAGS=-D_GLIBCXX_USE_CXX11_ABI=0) + endif() + + ExternalProject_Add(mariadb_connector_cpp + SOURCE_DIR ${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp + CMAKE_ARGS -Wno-dev + -DCMAKE_BUILD_RPATH_USE_ORIGIN=${CMAKE_BUILD_RPATH_USE_ORIGIN} + -DCMAKE_INSTALL_PREFIX=./mariadbcpp # Points the connector to the correct plugin directory + -DINSTALL_PLUGINDIR=plugin + ${MARIADB_EXTRA_CMAKE_ARGS} + PREFIX "${PROJECT_BINARY_DIR}/mariadbcpp" + BUILD_COMMAND cmake --build . --config RelWithDebInfo -j${__maria_db_connector_compile_jobs__} + INSTALL_COMMAND "") + + ExternalProject_Get_Property(mariadb_connector_cpp BINARY_DIR) + + if(WIN32) + set(MARIADB_SHARED_LIBRARY_NAME mariadbcpp.dll) + set(MARIADB_PLUGIN_SUFFIX .dll) + set(MARIADB_IMPLIB_LOCATION "${BINARY_DIR}/RelWithDebInfo/mariadbcpp.lib") + + # When built from source windows only seems to check same folder as exe instead specified folder, so use + # environment variable to force it + add_link_options(/DELAYLOAD:mariadbcpp.dll) + add_compile_definitions(MARIADB_PLUGIN_DIR_OVERRIDE="${PROJECT_BINARY_DIR}/mariadbcpp/plugin") + else() + set(MARIADB_SHARED_LIBRARY_NAME libmariadbcpp${CMAKE_SHARED_LIBRARY_SUFFIX}) + set(MARIADB_PLUGIN_SUFFIX .so) + endif() + + get_property(isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + if(isMultiConfig) + set(MARIADB_SHARED_LIBRARY_LOCATION "${BINARY_DIR}/RelWithDebInfo/${MARIADB_SHARED_LIBRARY_NAME}") + set(MARIADB_SHARED_LIBRARY_COPY_LOCATION "${PROJECT_BINARY_DIR}/$<CONFIG>") + set(MARIADB_PLUGINS_LOCATION "${BINARY_DIR}/libmariadb/RelWithDebInfo") + else() + set(MARIADB_SHARED_LIBRARY_LOCATION "${BINARY_DIR}/${MARIADB_SHARED_LIBRARY_NAME}") + set(MARIADB_SHARED_LIBRARY_COPY_LOCATION "${PROJECT_BINARY_DIR}") + set(MARIADB_PLUGINS_LOCATION "${BINARY_DIR}/libmariadb") + endif() + + set(MARIADB_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/include/") + + add_custom_command(TARGET mariadb_connector_cpp POST_BUILD + COMMAND ${CMAKE_COMMAND} -E make_directory + ${BINARY_DIR}/mariadbcpp/plugin + ${MARIADB_SHARED_LIBRARY_COPY_LOCATION} + + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${MARIADB_SHARED_LIBRARY_LOCATION} + ${MARIADB_SHARED_LIBRARY_COPY_LOCATION} + + COMMAND ${CMAKE_COMMAND} -E copy_if_different + ${MARIADB_PLUGINS_LOCATION}/caching_sha2_password${MARIADB_PLUGIN_SUFFIX} + ${MARIADB_PLUGINS_LOCATION}/client_ed25519${MARIADB_PLUGIN_SUFFIX} + ${MARIADB_PLUGINS_LOCATION}/dialog${MARIADB_PLUGIN_SUFFIX} + ${MARIADB_PLUGINS_LOCATION}/mysql_clear_password${MARIADB_PLUGIN_SUFFIX} + ${MARIADB_PLUGINS_LOCATION}/sha256_password${MARIADB_PLUGIN_SUFFIX} + ${BINARY_DIR}/mariadbcpp/plugin) +endif() + +# Remove the CMakeLists.txt file from the tests folder for the maria-db-connector so we dont compile the tests. +if(EXISTS "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/test/CMakeLists.txt") + file(REMOVE "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/test/CMakeLists.txt") +endif() + +# Create mariadb connector library object +add_library(mariadbConnCpp SHARED IMPORTED GLOBAL) +set_property(TARGET mariadbConnCpp PROPERTY IMPORTED_LOCATION ${MARIADB_SHARED_LIBRARY_LOCATION}) + +if(WIN32) + set_property(TARGET mariadbConnCpp PROPERTY IMPORTED_IMPLIB ${MARIADB_IMPLIB_LOCATION}) +endif() + +# Add directories to include lists +target_include_directories(mariadbConnCpp INTERFACE ${MARIADB_INCLUDE_DIR}) +add_dependencies(mariadbConnCpp mariadb_connector_cpp) diff --git a/thirdparty/raknet/CMakeLists.txt b/thirdparty/raknet/CMakeLists.txt index 8d90f329..417e24dd 100644 --- a/thirdparty/raknet/CMakeLists.txt +++ b/thirdparty/raknet/CMakeLists.txt @@ -1,6 +1,4 @@ - - -PROJECT(RakNetStaticLib) +project(RakNetStaticLib) SET(RAKNET_SOURCES @@ -27,7 +25,7 @@ Source/FileList.cpp Source/RakMemoryOverride.cpp Source/ Source/FileListTransfer.cpp Source/RakNetCommandParser.cpp Source/TCPInterface.cpp Source/FileOperations.cpp Source/RakNetStatistics.cpp Source/TelnetTransport.cpp Source/_FindFirst.cpp Source/RakNetTransport.cpp Source/ThreadsafePacketLogger.cpp -Source/RakThread.cpp Source/SuperFastHash.cpp Source/Itoa.cpp +Source/RakThread.cpp Source/SuperFastHash.cpp Source/Itoa.cpp Source/HTTPConnection.cpp ) @@ -70,18 +68,25 @@ Source/DS_Tree.h Source/RakNetCommandParser.h S Source/DS_WeightedGraph.h Source/RakNetDefines.h Source/ThreadsafePacketLogger.h Source/EmailSender.h Source/RakNetStatistics.h Source/TransportInterface.h Source/EpochTimeToString.h Source/RakNetTransport.h Source/Types.h -Source/RakThread.h Source/SuperFastHash.h Source/Itoa.h -Source/HTTPConnection.h Kbhit.h\ +Source/RakThread.h Source/SuperFastHash.h Source/Itoa.h +Source/HTTPConnection.h Kbhit.h ) -ADD_LIBRARY(RakNet STATIC ${RAKNET_SOURCES}) +add_library(raknet STATIC ${RAKNET_SOURCES}) +target_compile_options(raknet PRIVATE + $<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>,$<CXX_COMPILER_ID:GNU>>: + -w> + $<$<CXX_COMPILER_ID:MSVC>: + /w>) +if(WIN32) + # Link Win Sockets 2 to RakNet + target_link_libraries(raknet ws2_32) +endif() -INSTALL(TARGETS RakNet +install(TARGETS raknet DESTINATION lib) -INSTALL(FILES ${RAKNET_HEADERS} +install(FILES ${RAKNET_HEADERS} DESTINATION include/raknet) - - From e4a15a0f2efcfc7a668e939fc361b30a3b7db5a9 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 18 Aug 2022 00:09:14 -0500 Subject: [PATCH 084/322] Add imagimeter visibility script (#738) --- dCommon/dCommonVars.h | 1 + dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 4 ++++ dScripts/NtImagimeterVisibility.cpp | 11 +++++++++++ dScripts/NtImagimeterVisibility.h | 7 +++++++ 5 files changed, 24 insertions(+) create mode 100644 dScripts/NtImagimeterVisibility.cpp create mode 100644 dScripts/NtImagimeterVisibility.h diff --git a/dCommon/dCommonVars.h b/dCommon/dCommonVars.h index 986f1c18..4c0e15fa 100644 --- a/dCommon/dCommonVars.h +++ b/dCommon/dCommonVars.h @@ -628,6 +628,7 @@ enum ePlayerFlags { GF_BINOC_IN_CROC_AREA = 1308, GF_BINOC_IN_JAIL_AREA = 1309, GF_BINOC_TELESCOPE_NEXT_TO_CAPTAIN_JACK = 1310, + NT_PLINTH_REBUILD = 1919, NT_FACTION_SPY_DUKE = 1974, NT_FACTION_SPY_OVERBUILD = 1976, NT_FACTION_SPY_HAEL = 1977, diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 1fa177ba..50b41a14 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -177,6 +177,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "NtFactionSpyServer.cpp" "NtHaelServer.cpp" "NtImagBeamBuffer.cpp" + "NtImagimeterVisibility.cpp" "NtOverbuildServer.cpp" "NtParadoxPanelServer.cpp" "NtParadoxTeleServer.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index fbcb660a..de39fbb7 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -201,6 +201,7 @@ #include "ForceVolumeServer.h" #include "NtXRayServer.h" #include "NtSleepingGuard.h" +#include "NtImagimeterVisibility.h" // DLU Scripts #include "DLUVanityNPC.h" @@ -661,6 +662,9 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new NtXRayServer(); else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_SLEEPING_GUARD.lua") script = new NtSleepingGuard(); + else if (scriptName == "scripts\\02_server\\Map\\NT\\L_NT_IMAGIMETER_VISIBILITY_SERVER.lua") { + script = new NTImagimeterVisibility(); + } //AM: else if (scriptName == "scripts\\02_server\\Map\\AM\\L_AM_CONSOLE_TELEPORT_SERVER.lua") diff --git a/dScripts/NtImagimeterVisibility.cpp b/dScripts/NtImagimeterVisibility.cpp new file mode 100644 index 00000000..c0f9bf51 --- /dev/null +++ b/dScripts/NtImagimeterVisibility.cpp @@ -0,0 +1,11 @@ +#include "NtImagimeterVisibility.h" +#include "GameMessages.h" +#include "Entity.h" +#include "Character.h" + +void NTImagimeterVisibility::OnRebuildComplete(Entity* self, Entity* target) { + auto* character = target->GetCharacter(); + if (character) character->SetPlayerFlag(ePlayerFlags::NT_PLINTH_REBUILD, true); + + GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlinthBuilt", 0, 0, LWOOBJID_EMPTY, "", target->GetSystemAddress()); +} diff --git a/dScripts/NtImagimeterVisibility.h b/dScripts/NtImagimeterVisibility.h new file mode 100644 index 00000000..04669d4b --- /dev/null +++ b/dScripts/NtImagimeterVisibility.h @@ -0,0 +1,7 @@ +#pragma once +#include "CppScripts.h" + +class NTImagimeterVisibility : public CppScripts::Script { +public: + void OnRebuildComplete(Entity* self, Entity* target) override; +}; From f8c1e2fb5298bc45a98c1a0f3deffd9562709b1d Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 18 Aug 2022 15:33:32 -0500 Subject: [PATCH 085/322] Script for when archway rebuild is done (#739) --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 4 ++++ dScripts/GfArchway.cpp | 8 ++++++++ dScripts/GfArchway.h | 10 ++++++++++ 4 files changed, 23 insertions(+) create mode 100644 dScripts/GfArchway.cpp create mode 100644 dScripts/GfArchway.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 50b41a14..4476ad7c 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -106,6 +106,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "FvPassThroughWall.cpp" "FvRaceSmashEggImagineServer.cpp" "GfApeSmashingQB.cpp" + "GfArchway.cpp" "GfBanana.cpp" "GfBananaCluster.cpp" "GfCampfire.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index de39fbb7..82cd2ebc 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -116,6 +116,7 @@ #include "BaseEnemyApe.h" #include "GfApeSmashingQB.h" #include "ZoneGfProperty.h" +#include "GfArchway.h" // SG Scripts #include "SGCannon.h" @@ -494,6 +495,9 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new GfApeSmashingQB(); else if (scriptName == "scripts\\zone\\PROPERTY\\GF\\L_ZONE_GF_PROPERTY.lua") script = new ZoneGfProperty(); + else if (scriptName == "scripts\\ai\\GF\\L_GF_ARCHWAY.lua") { + script = new GfArchway(); + } // SG else if (scriptName == "scripts\\ai\\MINIGAME\\SG_GF\\SERVER\\SG_CANNON.lua") diff --git a/dScripts/GfArchway.cpp b/dScripts/GfArchway.cpp new file mode 100644 index 00000000..429f62ae --- /dev/null +++ b/dScripts/GfArchway.cpp @@ -0,0 +1,8 @@ +#include "GfArchway.h" +#include "Entity.h" +#include "SkillComponent.h" + +void GfArchway::OnRebuildComplete(Entity* self, Entity* target) { + auto* skillComponent = target->GetComponent<SkillComponent>(); + if (skillComponent) skillComponent->CalculateBehavior(SHIELDING_SKILL, SHIELDING_BEHAVIOR, target->GetObjectID(), true); +} diff --git a/dScripts/GfArchway.h b/dScripts/GfArchway.h new file mode 100644 index 00000000..b60b2a9f --- /dev/null +++ b/dScripts/GfArchway.h @@ -0,0 +1,10 @@ +#pragma once +#include "CppScripts.h" + +class GfArchway : public CppScripts::Script { +public: + void OnRebuildComplete(Entity* self, Entity* target) override; +private: + const uint32_t SHIELDING_SKILL = 863; + const uint32_t SHIELDING_BEHAVIOR = 3788; +}; From c05562a227eab32f4b613f5f096f7098a416e1f1 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 18 Aug 2022 19:23:42 -0700 Subject: [PATCH 086/322] Modularize CMakeLists for submodules (#736) * Use RecastNavigation CMakeLists * Use tinyxml2 CMakeLists * Use bcrypt CMakeLists * Move variable init to CMakeLists This has to be done here to prevent missing dependency errors. * General improvements Only link dynamic if on gnu use more thirdparty cmakes * Disable tinyxml2 testing --- CMakeLists.txt | 11 ++++-- dCommon/CMakeLists.txt | 2 +- dGame/CMakeLists.txt | 2 +- dNavigation/CMakeLists.txt | 2 +- dPhysics/CMakeLists.txt | 1 + dWorldServer/CMakeLists.txt | 2 +- thirdparty/CMakeLists.txt | 62 +++++++------------------------- thirdparty/SQLite/CMakeLists.txt | 14 ++++++++ 8 files changed, 40 insertions(+), 56 deletions(-) create mode 100644 thirdparty/SQLite/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 6acca4d8..1a977a64 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,6 +42,12 @@ set(PROJECT_VERSION "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT # Echo the version message(STATUS "Version: ${PROJECT_VERSION}") +# Disable demo, tests and examples for recastNavigation. Turn these to ON if you want to use them +# This has to be done here to prevent a rare build error due to missing dependencies on the initial generations. +set(RECASTNAVIGATION_DEMO OFF CACHE BOOL "" FORCE) +set(RECASTNAVIGATION_TESTS OFF CACHE BOOL "" FORCE) +set(RECASTNAVIGATION_EXAMPLES OFF CACHE BOOL "" FORCE) + # Compiler flags: # Disabled deprecated warnings as the MySQL includes have deprecated code in them. # Disabled misleading indentation as DL_LinkedList from RakNet has a weird indent. @@ -54,7 +60,7 @@ if(UNIX) else() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++17 -O2 -Wuninitialized -D_GLIBCXX_USE_CXX11_ABI=0 -D_GLIBCXX_USE_CXX17_ABI=0 -static-libgcc -fPIC") endif() - if (__dynamic) + if (__dynamic AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -rdynamic") endif() if (__ggdb) @@ -137,8 +143,7 @@ set(INCLUDED_DIRECTORIES "thirdparty/raknet/Source" "thirdparty/tinyxml2" - "thirdparty/recastnavigation/Recast/Include" - "thirdparty/recastnavigation/Detour/Include" + "thirdparty/recastnavigation" "thirdparty/SQLite" "thirdparty/cpplinq" ) diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 7262bfef..028eb29f 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -19,7 +19,7 @@ include_directories(${PROJECT_SOURCE_DIR}/dCommon/) add_library(dCommon STATIC ${DCOMMON_SOURCES}) -target_link_libraries(dCommon libbcrypt) +target_link_libraries(dCommon bcrypt) if (UNIX) find_package(ZLIB REQUIRED) diff --git a/dGame/CMakeLists.txt b/dGame/CMakeLists.txt index 5acdba31..6b31802e 100644 --- a/dGame/CMakeLists.txt +++ b/dGame/CMakeLists.txt @@ -56,4 +56,4 @@ endforeach() add_library(dGame STATIC ${DGAME_SOURCES}) -target_link_libraries(dGame dDatabase) +target_link_libraries(dGame dDatabase Recast Detour) diff --git a/dNavigation/CMakeLists.txt b/dNavigation/CMakeLists.txt index 5891c77d..4c03d24b 100644 --- a/dNavigation/CMakeLists.txt +++ b/dNavigation/CMakeLists.txt @@ -7,4 +7,4 @@ foreach(file ${DNAVIGATIONS_DTERRAIN_SOURCES}) endforeach() add_library(dNavigation STATIC ${DNAVIGATION_SOURCES}) -target_link_libraries(dNavigation detour recast) +target_link_libraries(dNavigation Detour Recast) diff --git a/dPhysics/CMakeLists.txt b/dPhysics/CMakeLists.txt index 383393cc..5fe6adaa 100644 --- a/dPhysics/CMakeLists.txt +++ b/dPhysics/CMakeLists.txt @@ -7,3 +7,4 @@ set(DPHYSICS_SOURCES "dpCollisionChecks.cpp" "dpWorld.cpp") add_library(dPhysics STATIC ${DPHYSICS_SOURCES}) +target_link_libraries(dPhysics Recast Detour) diff --git a/dWorldServer/CMakeLists.txt b/dWorldServer/CMakeLists.txt index 05338960..fcf29838 100644 --- a/dWorldServer/CMakeLists.txt +++ b/dWorldServer/CMakeLists.txt @@ -3,4 +3,4 @@ set(DWORLDSERVER_SOURCES "ObjectIDManager.cpp" "WorldServer.cpp") add_executable(WorldServer ${DWORLDSERVER_SOURCES}) -target_link_libraries(WorldServer ${COMMON_LIBRARIES} dChatFilter dGame dZoneManager dPhysics detour recast tinyxml2 dNavigation) +target_link_libraries(WorldServer ${COMMON_LIBRARIES} dChatFilter dGame dZoneManager Detour Recast dPhysics tinyxml2 dNavigation) diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt index c04e418e..c7a27510 100644 --- a/thirdparty/CMakeLists.txt +++ b/thirdparty/CMakeLists.txt @@ -1,63 +1,27 @@ # Source Code for recast -file( - GLOB SOURCES_RECAST - LIST_DIRECTORIES false - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" - ${CMAKE_CURRENT_SOURCE_DIR}/recastnavigation/Recast/Source/*.cpp -) - -# Source Code for detour -file( - GLOB SOURCES_DETOUR - LIST_DIRECTORIES false - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" - ${CMAKE_CURRENT_SOURCE_DIR}/recastnavigation/Detour/Source/*.cpp -) +add_subdirectory(recastnavigation) +# Turn off tinyxml2 testing +set(tinyxml2_BUILD_TESTING OFF) # Source Code for tinyxml2 -file( - GLOB SOURCES_TINYXML2 - LIST_DIRECTORIES false - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" - ${CMAKE_CURRENT_SOURCE_DIR}/tinyxml2/tinyxml2.cpp -) +add_subdirectory(tinyxml2) # Source Code for libbcrypt -file( - GLOB SOURCES_LIBBCRYPT - LIST_DIRECTORIES false - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" - ${CMAKE_CURRENT_SOURCE_DIR}/libbcrypt/*.c - ${CMAKE_CURRENT_SOURCE_DIR}/libbcrypt/src/*.c -) +# Disable warning about no project version. +set(CMAKE_POLICY_DEFAULT_CMP0048 NEW) +# Disable warning about the minimum version of cmake used for bcrypt being deprecated in the future +set(CMAKE_WARN_DEPRECATED OFF CACHE BOOL "" FORCE) -file( - GLOB SOURCES_SQLITE3 - LIST_DIRECTORIES false - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" - ${CMAKE_CURRENT_SOURCE_DIR}/SQLite/*.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/SQLite/*.c -) +add_subdirectory(libbcrypt) + +# Source code for sqlite +add_subdirectory(SQLite) # MariaDB C++ Connector include(CMakeMariaDBLists.txt) # Create our third party library objects add_subdirectory(raknet) -add_library(tinyxml2 ${SOURCES_TINYXML2}) -add_library(detour ${SOURCES_DETOUR}) -add_library(recast ${SOURCES_RECAST}) -add_library(libbcrypt ${SOURCES_LIBBCRYPT}) -add_library(sqlite3 ${SOURCES_SQLITE3}) - -if(UNIX) - # Add warning disable flags and link Unix libraries to sqlite3 - target_link_libraries(sqlite3 pthread dl m) - - # -Wno-unused-result -Wno-unknown-pragmas -fpermissive - target_compile_options(sqlite3 PRIVATE "-Wno-return-local-addr" "-Wno-maybe-uninitialized") - target_compile_options(libbcrypt PRIVATE "-Wno-implicit-function-declaration" "-Wno-int-conversion") -endif() # Download Backtrace if configured if(UNIX AND NOT APPLE) @@ -81,4 +45,4 @@ if(UNIX AND NOT APPLE) link_directories(${backtrace_SOURCE_DIR}/.libs/) include_directories(${backtrace_SOURCE_DIR}) endif() -endif() \ No newline at end of file +endif() diff --git a/thirdparty/SQLite/CMakeLists.txt b/thirdparty/SQLite/CMakeLists.txt new file mode 100644 index 00000000..aa7a6423 --- /dev/null +++ b/thirdparty/SQLite/CMakeLists.txt @@ -0,0 +1,14 @@ +set (SQLITE3_SOURCES + "CppSQLite3.cpp" + "sqlite3.c" +) + +add_library (sqlite3 ${SQLITE3_SOURCES}) + +if(UNIX) + # Add warning disable flags and link Unix libraries to sqlite3 + target_link_libraries(sqlite3 pthread dl m) + + # -Wno-unused-result -Wno-unknown-pragmas -fpermissive + target_compile_options(sqlite3 PRIVATE "-Wno-return-local-addr" "-Wno-maybe-uninitialized") +endif() From ceb374591fbe25eb21ae3db1029e080983d7f806 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 18 Aug 2022 19:42:52 -0700 Subject: [PATCH 087/322] Move mailbox closing to its script (#740) --- dGame/dGameMessages/GameMessages.cpp | 6 ------ dScripts/MailBoxServer.cpp | 8 ++++++++ dScripts/MailBoxServer.h | 1 + 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 105bb526..1645afc8 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -4745,12 +4745,6 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity return; } - if (args == u"toggleMail") { - AMFArrayValue args; - args.InsertValue("visible", new AMFFalseValue()); - GameMessages::SendUIMessageServerToSingleClient(entity, sysAddr, "ToggleMail", &args); - } - // This should probably get it's own "ServerEvents" system or something at some point if (args == u"ZonePlayer") { // Should probably check to make sure they're using a launcher at some point before someone makes a hack that lets you testmap diff --git a/dScripts/MailBoxServer.cpp b/dScripts/MailBoxServer.cpp index 81156835..c2534f3e 100644 --- a/dScripts/MailBoxServer.cpp +++ b/dScripts/MailBoxServer.cpp @@ -9,3 +9,11 @@ void MailBoxServer::OnUse(Entity* self, Entity* user) { args.InsertValue("state", value); GameMessages::SendUIMessageServerToSingleClient(user, user->GetSystemAddress(), "pushGameState", &args); } + +void MailBoxServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args == "toggleMail") { + AMFArrayValue args; + args.InsertValue("visible", new AMFFalseValue()); + GameMessages::SendUIMessageServerToSingleClient(sender, sender->GetSystemAddress(), "ToggleMail", &args); + } +} diff --git a/dScripts/MailBoxServer.h b/dScripts/MailBoxServer.h index f459e8b3..9ada6a0e 100644 --- a/dScripts/MailBoxServer.h +++ b/dScripts/MailBoxServer.h @@ -12,4 +12,5 @@ public: * @param user The user that interacted with this Entity. */ void OnUse(Entity* self, Entity* user) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; }; From e707207ffafcd07682e040a7677c0def01e61d34 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 25 Aug 2022 15:50:13 -0500 Subject: [PATCH 088/322] Add FV Geyser script (#748) * Add FV Geyser script * remove uneeded include * const --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 4 ++++ dScripts/FvMaelstromGeyser.cpp | 18 ++++++++++++++++++ dScripts/FvMaelstromGeyser.h | 18 ++++++++++++++++++ 4 files changed, 41 insertions(+) create mode 100644 dScripts/FvMaelstromGeyser.cpp create mode 100644 dScripts/FvMaelstromGeyser.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 4476ad7c..9bc088cb 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -99,6 +99,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "FvFreeGfNinjas.cpp" "FvHorsemenTrigger.cpp" "FvMaelstromCavalry.cpp" + "FvMaelstromGeyser.cpp" "FvMaelstromDragon.cpp" "FvNinjaGuard.cpp" "FvPandaServer.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 82cd2ebc..5f10a2a5 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -147,6 +147,7 @@ #include "FvPassThroughWall.h" #include "FvBounceOverWall.h" #include "FvFong.h" +#include "FvMaelstromGeyser.h" // FB Scripts #include "AgJetEffectServer.h" @@ -576,6 +577,9 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new FvBounceOverWall(); else if (scriptName == "scripts\\02_server\\Map\\FV\\L_NPC_FONG.lua") script = new FvFong(); + else if (scriptName == "scripts\\ai\\FV\\L_FV_MAELSTROM_GEYSER.lua") { + script = new FvMaelstromGeyser(); + } //Misc: if (scriptName == "scripts\\02_server\\Map\\General\\L_EXPLODING_ASSET.lua") diff --git a/dScripts/FvMaelstromGeyser.cpp b/dScripts/FvMaelstromGeyser.cpp new file mode 100644 index 00000000..66aa43dc --- /dev/null +++ b/dScripts/FvMaelstromGeyser.cpp @@ -0,0 +1,18 @@ +#include "FvMaelstromGeyser.h" +#include "SkillComponent.h" + +void FvMaelstromGeyser::OnStartup(Entity* self) { + self->AddTimer(m_StartSkillTimerName, m_StartSkillTimerTime); + self->AddTimer(m_KillSelfTimerName, m_KillSelfTimerTime); +} + +void FvMaelstromGeyser::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == m_StartSkillTimerName) { + auto* skillComponent = self->GetComponent<SkillComponent>(); + skillComponent->CalculateBehavior(m_SkillID, m_BehaviorID, LWOOBJID_EMPTY, true); + } + if (timerName == m_KillSelfTimerName) { + self->Smash(LWOOBJID_EMPTY, eKillType::SILENT); + } +} + diff --git a/dScripts/FvMaelstromGeyser.h b/dScripts/FvMaelstromGeyser.h new file mode 100644 index 00000000..245eb56e --- /dev/null +++ b/dScripts/FvMaelstromGeyser.h @@ -0,0 +1,18 @@ +#pragma once +#include "CppScripts.h" + +class FvMaelstromGeyser final : public CppScripts::Script +{ +public: + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; + + +private: + const std::string m_StartSkillTimerName = "startSkill"; + const float m_StartSkillTimerTime = 2.0; + const std::string m_KillSelfTimerName = "killSelf"; + const float m_KillSelfTimerTime = 5.5; + const uint32_t m_SkillID = 831; + const uint32_t m_BehaviorID = 15500; +}; From 47f0830483ac1c82cee2ea74b20de7f8b3d7f8f4 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 25 Aug 2022 15:51:22 -0500 Subject: [PATCH 089/322] Add GF geyser script (#749) * Add GF geyser script * remove uneeeded include * const --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 6 ++++-- dScripts/GfMaelstromGeyser.cpp | 18 ++++++++++++++++++ dScripts/GfMaelstromGeyser.h | 17 +++++++++++++++++ 4 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 dScripts/GfMaelstromGeyser.cpp create mode 100644 dScripts/GfMaelstromGeyser.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 9bc088cb..47400891 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -114,6 +114,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "GfCaptainsCannon.cpp" "GfJailkeepMission.cpp" "GfJailWalls.cpp" + "GfMaelstromGeyser.cpp" "GfOrgan.cpp" "GfTikiTorch.cpp" "GrowingFlower.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 5f10a2a5..f8481de1 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -117,6 +117,7 @@ #include "GfApeSmashingQB.h" #include "ZoneGfProperty.h" #include "GfArchway.h" +#include "GfMaelstromGeyser.h" // SG Scripts #include "SGCannon.h" @@ -496,9 +497,10 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new GfApeSmashingQB(); else if (scriptName == "scripts\\zone\\PROPERTY\\GF\\L_ZONE_GF_PROPERTY.lua") script = new ZoneGfProperty(); - else if (scriptName == "scripts\\ai\\GF\\L_GF_ARCHWAY.lua") { + else if (scriptName == "scripts\\ai\\GF\\L_GF_ARCHWAY.lua") script = new GfArchway(); - } + else if (scriptName == "scripts\\ai\\GF\\L_GF_MAELSTROM_GEYSER.lua") + script = new GfMaelstromGeyser(); // SG else if (scriptName == "scripts\\ai\\MINIGAME\\SG_GF\\SERVER\\SG_CANNON.lua") diff --git a/dScripts/GfMaelstromGeyser.cpp b/dScripts/GfMaelstromGeyser.cpp new file mode 100644 index 00000000..825307a7 --- /dev/null +++ b/dScripts/GfMaelstromGeyser.cpp @@ -0,0 +1,18 @@ +#include "GfMaelstromGeyser.h" +#include "SkillComponent.h" + +void GfMaelstromGeyser::OnStartup(Entity* self) { + self->AddTimer(m_StartSkillTimerName, m_StartSkillTimerTime); + self->AddTimer(m_KillSelfTimerName, m_KillSelfTimerTime); +} + +void GfMaelstromGeyser::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == m_StartSkillTimerName) { + auto* skillComponent = self->GetComponent<SkillComponent>(); + skillComponent->CalculateBehavior(m_SkillID, m_BehaviorID, LWOOBJID_EMPTY, true); + } + if (timerName == m_KillSelfTimerName) { + self->Smash(LWOOBJID_EMPTY, eKillType::SILENT); + } +} + diff --git a/dScripts/GfMaelstromGeyser.h b/dScripts/GfMaelstromGeyser.h new file mode 100644 index 00000000..60e42798 --- /dev/null +++ b/dScripts/GfMaelstromGeyser.h @@ -0,0 +1,17 @@ +#pragma once +#include "CppScripts.h" + +class GfMaelstromGeyser final : public CppScripts::Script +{ +public: + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; + +private: + const std::string m_StartSkillTimerName = "startSkill"; + const float m_StartSkillTimerTime = 2.0; + const std::string m_KillSelfTimerName = "killSelf"; + const float m_KillSelfTimerTime = 7.5; + const uint32_t m_SkillID = 607; + const uint32_t m_BehaviorID = 10500; +}; From bc132487e983a45e5374c0a3ce6c0c7670f21819 Mon Sep 17 00:00:00 2001 From: Demetri Van Sickle <demetriv.s.7@gmail.com> Date: Thu, 25 Aug 2022 14:16:20 -0700 Subject: [PATCH 090/322] Updated README (Formatting and flow) (#744) * Updated flow of database section * Changed bolded headers to actual headers Will now allow you to link to them * Updated Linux build command to match build script * Updated database wording --- README.md | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 321e1b36..de20e7ad 100644 --- a/README.md +++ b/README.md @@ -27,11 +27,11 @@ Darkflame Universe is a server emulator and does not distribute any LEGO® Unive Development of the latest iteration of Darkflame Universe has been done primarily in a Unix-like environment and is where it has been tested and designed for deployment. It is therefore highly recommended that Darkflame Universe be built and deployed using a Unix-like environment for the most streamlined experience. ### Prerequisites -**Clone the repository** +#### Clone the repository ```bash git clone --recursive https://github.com/DarkflameUniverse/DarkflameServer ``` -**Python** +#### Python Some tools utilized to streamline the setup process require Python 3, make sure you have it installed. @@ -52,7 +52,7 @@ Make sure packages like `gcc`, `cmake`, and `zlib` are installed. Depending on t CMake must be version 3.14 or higher! -**Build the repository** +#### Build the repository You can either run `build.sh` when in the root folder of the repository: @@ -70,8 +70,8 @@ cd build # Run CMake to generate make files cmake .. -# Run make to build the project. To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `make -j8` -make +# To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `cmake --build . --config Release -j8' +cmake --build . --config Release ``` ### MacOS builds @@ -93,7 +93,7 @@ cmake --build . --config Release ### Windows builds (native) Ensure that you have either the [MSVC](https://visualstudio.microsoft.com/vs/) or the [Clang](https://github.com/llvm/llvm-project/releases/) (recommended) compiler installed. You will also need to install [CMake](https://cmake.org/download/). Currently on native Windows the server will only work in Release mode. -**Build the repository** +#### Build the repository ```batch :: Create the build directory mkdir build @@ -105,7 +105,7 @@ cmake .. :: Run CMake with build flag to build cmake --build . --config Release ``` -**Windows for ARM** has not been tested but should build by doing the following +#### Windows for ARM has not been tested but should build by doing the following ```batch :: Create the build directory mkdir build @@ -121,13 +121,13 @@ cmake --build . --config Release ### Windows builds (WSL) This section will go through how to install [WSL](https://docs.microsoft.com/en-us/windows/wsl/install) and building in a Linux environment under Windows. WSL requires Windows 10 version 2004 and higher (Build 19041 and higher) or Windows 11. -**Open the Command Prompt application with Administrator permissions and run the following:** +#### Open the Command Prompt application with Administrator permissions and run the following: ```bash # Installing Windows Subsystem for Linux wsl --install ``` -**Open the Ubuntu application and run the following:** +#### Open the Ubuntu application and run the following: ```bash # Make sure the install is up to date apt update && apt upgrade @@ -159,7 +159,7 @@ now follow the build section for your system ### Resources -**LEGO® Universe 1.10.64** +#### LEGO® Universe 1.10.64 This repository does not distribute any LEGO® Universe files. A full install of LEGO® Universe version 1.10.64 (latest) is required to finish setting up Darkflame Universe. @@ -182,20 +182,20 @@ shasum -a 256 <file> certutil -hashfile <file> SHA256 ``` -**Unpacking the client** +#### Unpacking the client * Clone lcdr's utilities repository [here](https://github.com/lcdr/utils) * Use `pkextractor.pyw` to unpack the client files if they are not already unpacked -**Setup resource directory** +#### Setup resource directory * In the `build` directory create a `res` directory if it does not already exist. * Copy over or create symlinks from `macros`, `BrickModels`, `chatplus_en_us.txt`, `names`, and `maps` in your client `res` directory to the server `build/res` directory * Unzip the navmeshes [here](./resources/navmeshes.zip) and place them in `build/res/maps/navmeshes` -**Setup locale** +#### Setup locale * In the `build` directory create a `locale` directory if it does not already exist * Copy over or create symlinks from `locale.xml` in your client `locale` directory to the `build/locale` directory -**Client database** +#### Client database * Use `fdb_to_sqlite.py` in lcdr's utilities on `res/cdclient.fdb` in the unpacked client to convert the client database to `cdclient.sqlite` * Move and rename `cdclient.sqlite` into `build/res/CDServer.sqlite` * Run each SQL file in the order at which they appear [here](migrations/cdserver/) on the SQLite database @@ -205,13 +205,16 @@ Darkflame Universe utilizes a MySQL/MariaDB database for account and character i Initial setup can vary drastically based on which operating system or distribution you are running; there are instructions out there for most setups, follow those and come back here when you have a database up and running. * Create a database for Darkflame Universe to use -* Use the command `./MasterServer -m` to automatically run them. -**Configuration** +#### Configuration After the server has been built there should be four `ini` files in the build director: `authconfig.ini`, `chatconfig.ini`, `masterconfig.ini`, and `worldconfig.ini`. Go through them and fill in the database credentials and configure other settings if necessary. -**Verify** +#### Setup and Migrations + +Use the command `./MasterServer -m` to setup the tables in the database. The first time this command is run on a database, the tables will be up to date with the most recent version. To update your database tables, run this command again. Multiple invocations will not affect any functionality. + +#### Verify Your build directory should now look like this: * AuthServer From 500b7885e25146e6033ca2c3acb6447626162e75 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 25 Aug 2022 21:09:08 -0500 Subject: [PATCH 091/322] Add pirate rep script (#751) * Add pirate rep script * fix formattimg --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 3 +++ dScripts/PirateRep.cpp | 11 +++++++++++ dScripts/PirateRep.h | 9 +++++++++ 4 files changed, 24 insertions(+) create mode 100644 dScripts/PirateRep.cpp create mode 100644 dScripts/PirateRep.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 47400891..13b14ad8 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -195,6 +195,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "PetDigServer.cpp" "PetFromDigServer.cpp" "PetFromObjectServer.cpp" + "PirateRep.cpp" "PropertyBankInteract.cpp" "PropertyDeathPlane.cpp" "PropertyDevice.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index f8481de1..44b79d9b 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -118,6 +118,7 @@ #include "ZoneGfProperty.h" #include "GfArchway.h" #include "GfMaelstromGeyser.h" +#include "PirateRep.h" // SG Scripts #include "SGCannon.h" @@ -501,6 +502,8 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new GfArchway(); else if (scriptName == "scripts\\ai\\GF\\L_GF_MAELSTROM_GEYSER.lua") script = new GfMaelstromGeyser(); + else if (scriptName == "scripts\\ai\\GF\\L_PIRATE_REP.lua") + script = new PirateRep(); // SG else if (scriptName == "scripts\\ai\\MINIGAME\\SG_GF\\SERVER\\SG_CANNON.lua") diff --git a/dScripts/PirateRep.cpp b/dScripts/PirateRep.cpp new file mode 100644 index 00000000..eb4cf510 --- /dev/null +++ b/dScripts/PirateRep.cpp @@ -0,0 +1,11 @@ +#include "PirateRep.h" +#include "Character.h" + +void PirateRep::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { + if (missionID == m_PirateRepMissionID && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { + auto* character = target->GetCharacter(); + if (character) { + character->SetPlayerFlag(ePlayerFlags::GF_PIRATE_REP, true); + } + } +} diff --git a/dScripts/PirateRep.h b/dScripts/PirateRep.h new file mode 100644 index 00000000..8fc82c5e --- /dev/null +++ b/dScripts/PirateRep.h @@ -0,0 +1,9 @@ +#pragma once +#include "CppScripts.h" + +class PirateRep : public CppScripts::Script { +public: + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; +private: + const int m_PirateRepMissionID = 301; +}; From b70e7334e87800330ab549a4e8f653e1a878a594 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 26 Aug 2022 22:58:41 -0500 Subject: [PATCH 092/322] Parrot crash script to become a sneaky ninja and steal the pirate's booty (#752) --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 3 +++ dScripts/GfParrotCrash.cpp | 13 +++++++++++++ dScripts/GfParrotCrash.h | 13 +++++++++++++ 4 files changed, 30 insertions(+) create mode 100644 dScripts/GfParrotCrash.cpp create mode 100644 dScripts/GfParrotCrash.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 13b14ad8..440ca69f 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -116,6 +116,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "GfJailWalls.cpp" "GfMaelstromGeyser.cpp" "GfOrgan.cpp" + "GfParrotCrash.cpp" "GfTikiTorch.cpp" "GrowingFlower.cpp" "HydrantBroken.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 44b79d9b..37a0ecf7 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -119,6 +119,7 @@ #include "GfArchway.h" #include "GfMaelstromGeyser.h" #include "PirateRep.h" +#include "GfParrotCrash.h" // SG Scripts #include "SGCannon.h" @@ -504,6 +505,8 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new GfMaelstromGeyser(); else if (scriptName == "scripts\\ai\\GF\\L_PIRATE_REP.lua") script = new PirateRep(); + else if (scriptName == "scripts\\ai\\GF\\L_GF_PARROT_CRASH.lua") + script = new GfParrotCrash(); // SG else if (scriptName == "scripts\\ai\\MINIGAME\\SG_GF\\SERVER\\SG_CANNON.lua") diff --git a/dScripts/GfParrotCrash.cpp b/dScripts/GfParrotCrash.cpp new file mode 100644 index 00000000..6b76a51d --- /dev/null +++ b/dScripts/GfParrotCrash.cpp @@ -0,0 +1,13 @@ +#include "GfParrotCrash.h" +#include "SkillComponent.h" +#include "Entity.h" +#include "dLogger.h" + +void GfParrotCrash::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + auto* skillComponent = self->GetComponent<SkillComponent>(); + if (args == "Slow") { + skillComponent->CalculateBehavior(m_SlowSkillID, m_SlowBehaviorID, sender->GetObjectID()); + } else if (args == "Unslow") { + skillComponent->CalculateBehavior(m_UnslowSkillID, m_UnslowBehaviorID, sender->GetObjectID()); + } +} diff --git a/dScripts/GfParrotCrash.h b/dScripts/GfParrotCrash.h new file mode 100644 index 00000000..fe70a16c --- /dev/null +++ b/dScripts/GfParrotCrash.h @@ -0,0 +1,13 @@ +#pragma once +#include "CppScripts.h" + +class GfParrotCrash : public CppScripts::Script { +public: + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; +private: + const uint32_t m_SlowSkillID = 795; + const uint32_t m_SlowBehaviorID = 14214; + const uint32_t m_UnslowSkillID = 796; + const uint32_t m_UnslowBehaviorID = 14215; +}; + From 3b75ecc0b431c840f3776ed0d5a936ee6ea94238 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 27 Aug 2022 21:48:03 -0500 Subject: [PATCH 093/322] Add script to playfx on canisters before consoles are active (#754) * Add script to playfx on canisters before consoles are active * remove debug stuff --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 3 +++ dScripts/FvFacilityPipes.cpp | 10 ++++++++++ dScripts/FvFacilityPipes.h | 15 +++++++++++++++ 4 files changed, 29 insertions(+) create mode 100644 dScripts/FvFacilityPipes.cpp create mode 100644 dScripts/FvFacilityPipes.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 440ca69f..ac35b76d 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -94,6 +94,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "FvConsoleRightQuickbuild.cpp" "FvDragonSmashingGolemQb.cpp" "FvFacilityBrick.cpp" + "FvFacilityPipes.cpp" "FvFlyingCreviceDragon.cpp" "FvFong.cpp" "FvFreeGfNinjas.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 37a0ecf7..73c50d62 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -144,6 +144,7 @@ #include "FvConsoleLeftQuickbuild.h" #include "FvConsoleRightQuickbuild.h" #include "FvFacilityBrick.h" +#include "FvFacilityPipes.h" #include "ImgBrickConsoleQB.h" #include "ActParadoxPipeFix.h" #include "FvNinjaGuard.h" @@ -573,6 +574,8 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new FvConsoleRightQuickbuild(); else if (scriptName == "scripts\\ai\\FV\\L_FV_FACILITY_BRICK.lua") script = new FvFacilityBrick(); + else if (scriptName == "scripts\\ai\\FV\\L_FV_FACILITY_PIPES.lua") + script = new FvFacilityPipes(); else if (scriptName == "scripts\\02_server\\Map\\FV\\L_IMG_BRICK_CONSOLE_QB.lua") script = new ImgBrickConsoleQB(); else if (scriptName == "scripts\\ai\\FV\\L_ACT_PARADOX_PIPE_FIX.lua") diff --git a/dScripts/FvFacilityPipes.cpp b/dScripts/FvFacilityPipes.cpp new file mode 100644 index 00000000..dd35ffe1 --- /dev/null +++ b/dScripts/FvFacilityPipes.cpp @@ -0,0 +1,10 @@ +#include "FvFacilityPipes.h" +#include "GameMessages.h" + +void FvFacilityPipes::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args == "startFX") { + GameMessages::SendPlayFXEffect(self->GetObjectID(), m_LeftPipeEffectID, m_EffectType, m_LeftPipeEffectName); + GameMessages::SendPlayFXEffect(self->GetObjectID(), m_RightPipeEffectID, m_EffectType, m_RightPipeEffectName); + GameMessages::SendPlayFXEffect(self->GetObjectID(), m_ImaginationCanisterEffectID, m_EffectType, m_ImaginationCanisterEffectName); + } +} diff --git a/dScripts/FvFacilityPipes.h b/dScripts/FvFacilityPipes.h new file mode 100644 index 00000000..8a33976c --- /dev/null +++ b/dScripts/FvFacilityPipes.h @@ -0,0 +1,15 @@ +#pragma once +#include "CppScripts.h" + +class FvFacilityPipes : public CppScripts::Script { +public: + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; +private: + const std::u16string m_EffectType = u"create"; + const std::string m_LeftPipeEffectName = "LeftPipeOff"; + const int32_t m_LeftPipeEffectID = 2774; + const std::string m_RightPipeEffectName = "RightPipeOff"; + const int32_t m_RightPipeEffectID = 2777; + const std::string m_ImaginationCanisterEffectName = "imagination_canister"; + const int32_t m_ImaginationCanisterEffectID = 2750; +}; From e3077aa4102e5e0254adac7a47b5c3e5f5a6b6f7 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 1 Sep 2022 19:24:00 -0700 Subject: [PATCH 094/322] Fix Windows not working due to libbcrypt not working on Ninja (#765) --- thirdparty/CMakeLists.txt | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt index c7a27510..978c5532 100644 --- a/thirdparty/CMakeLists.txt +++ b/thirdparty/CMakeLists.txt @@ -6,13 +6,15 @@ set(tinyxml2_BUILD_TESTING OFF) # Source Code for tinyxml2 add_subdirectory(tinyxml2) -# Source Code for libbcrypt -# Disable warning about no project version. -set(CMAKE_POLICY_DEFAULT_CMP0048 NEW) -# Disable warning about the minimum version of cmake used for bcrypt being deprecated in the future -set(CMAKE_WARN_DEPRECATED OFF CACHE BOOL "" FORCE) - -add_subdirectory(libbcrypt) +# Source Code for libbcrypt. Uses a file glob instead to get around Windows build issues. +file( + GLOB SOURCES_LIBBCRYPT + LIST_DIRECTORIES false + RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" + ${CMAKE_CURRENT_SOURCE_DIR}/libbcrypt/*.c + ${CMAKE_CURRENT_SOURCE_DIR}/libbcrypt/src/*.c +) +add_library(bcrypt ${SOURCES_LIBBCRYPT}) # Source code for sqlite add_subdirectory(SQLite) From 1af3e59348c34a74902bafa929a737c7bb6d3cda Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 1 Sep 2022 21:44:26 -0500 Subject: [PATCH 095/322] Scripts for the AG sentinel camp QB wall (#761) * Scripts for the AG sentinel camp QB wall * use lookat * Address feedback * Fix stromling spawner * fix aggro and remove logs Co-authored-by: Jett <55758076+Jettford@users.noreply.github.com> --- dScripts/AgQbWall.cpp | 15 +++++ dScripts/AgQbWall.h | 7 +++ dScripts/CMakeLists.txt | 2 + dScripts/CppScripts.cpp | 6 ++ dScripts/QbSpawner.cpp | 136 ++++++++++++++++++++++++++++++++++++++++ dScripts/QbSpawner.h | 17 +++++ 6 files changed, 183 insertions(+) create mode 100644 dScripts/AgQbWall.cpp create mode 100644 dScripts/AgQbWall.h create mode 100644 dScripts/QbSpawner.cpp create mode 100644 dScripts/QbSpawner.h diff --git a/dScripts/AgQbWall.cpp b/dScripts/AgQbWall.cpp new file mode 100644 index 00000000..d6222419 --- /dev/null +++ b/dScripts/AgQbWall.cpp @@ -0,0 +1,15 @@ +#include "AgQbWall.h" + +void AgQbWall::OnRebuildComplete(Entity* self, Entity* player) { + self->SetVar(u"player", player->GetObjectID()); + auto targetWallSpawners = GeneralUtils::UTF16ToWTF8(self->GetVar<std::u16string>(u"spawner")); + if (targetWallSpawners != "") { + auto groupObjs = EntityManager::Instance()->GetEntitiesInGroup(targetWallSpawners); + for (auto* obj : groupObjs) { + if (obj) { + obj->SetVar(u"player", player->GetObjectID()); + obj->OnFireEventServerSide(self, "spawnMobs"); + } + } + } +} diff --git a/dScripts/AgQbWall.h b/dScripts/AgQbWall.h new file mode 100644 index 00000000..93187e0e --- /dev/null +++ b/dScripts/AgQbWall.h @@ -0,0 +1,7 @@ +#pragma once +#include "CppScripts.h" + +class AgQbWall : public CppScripts::Script { +public: + void OnRebuildComplete(Entity* self, Entity* player) override; +}; diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index ac35b76d..66e3b65b 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -21,6 +21,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "AgPropGuard.cpp" "AgPropguards.cpp" "AgQbElevator.cpp" + "AgQbWall.cpp" "AgSalutingNpcs.cpp" "AgShipPlayerDeathTrigger.cpp" "AgShipPlayerShockServer.cpp" @@ -206,6 +207,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "PrSeagullFly.cpp" "PrWhistle.cpp" "QbEnemyStunner.cpp" + "QbSpawner.cpp" "RaceImagineCrateServer.cpp" "RaceImaginePowerup.cpp" "RaceMaelstromGeiser.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 73c50d62..7d114cd3 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -61,6 +61,8 @@ #include "VeMissionConsole.h" #include "VeEpsilonServer.h" #include "AgSurvivalBuffStation.h" +#include "QbSpawner.h" +#include "AgQbWall.h" // NS Scripts #include "NsModularBuild.h" @@ -466,6 +468,10 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new WildAmbients(); else if (scriptName == "scripts\\ai\\NS\\NS_PP_01\\L_NS_PP_01_TELEPORT.lua") script = new PropertyDeathPlane(); + else if (scriptName == "scripts\\02_server\\Map\\General\\L_QB_SPAWNER.lua") + script = new QbSpawner(); + else if (scriptName == "scripts\\ai\\AG\\L_AG_QB_Wall.lua") + script = new AgQbWall(); //GF: else if (scriptName == "scripts\\02_server\\Map\\GF\\L_GF_TORCH.lua") diff --git a/dScripts/QbSpawner.cpp b/dScripts/QbSpawner.cpp new file mode 100644 index 00000000..edee6148 --- /dev/null +++ b/dScripts/QbSpawner.cpp @@ -0,0 +1,136 @@ +#include "QbSpawner.h" +#include "BaseCombatAIComponent.h" +#include "MovementAIComponent.h" + +void QbSpawner::OnStartup(Entity* self) { + auto mobNum = self->GetVar<int>(u"mobNum"); + auto spawnDist = self->GetVar<float>(u"spawnDist"); + auto mobTemplate = self->GetVar<LWOOBJID>(u"mobTemplate"); + auto spawnTime = self->GetVar<float>(u"spawnTime"); + + if (!mobNum) self->SetVar<int>(u"mobNum", m_DefaultMobNum); + if (!spawnDist) self->SetVar<float>(u"spawnDist", m_DefaultSpawnDist); + if (!mobTemplate) self->SetVar<LWOOBJID>(u"mobTemplate", m_DefaultMobTemplate); + if (!spawnTime) self->SetVar<float>(u"spawnTime", m_DefaultSpawnTime); + + // go ahead and setup the mob table here + std::vector<LWOOBJID> mobTable; + mobTable.assign(self->GetVar<int>(u"mobNum"), LWOOBJID_EMPTY); + + self->SetVar<std::vector<LWOOBJID>>(u"mobTable", mobTable); +} + +void QbSpawner::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + auto gateObjID = sender->GetObjectID(); + if (!gateObjID) return; + if (args == "spawnMobs") { + self->SetVar(u"gateObj", gateObjID); + auto spawnTime = self->GetVar<float>(u"spawnTime"); + self->AddTimer("SpawnMobEnemies", spawnTime); + } +} + +void QbSpawner::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "SpawnMobEnemies") { + auto mobTable = self->GetVar<std::vector<LWOOBJID>>(u"mobTable"); + + auto spawnDist = self->GetVar<float>(u"spawnDist"); + auto mobTemplate = self->GetVar<LWOOBJID>(u"mobTemplate"); + + auto gateObjID = self->GetVar<LWOOBJID>(u"gateObj"); + if (!gateObjID) return; + + auto* gate = EntityManager::Instance()->GetEntity(gateObjID); + if (!gate) return; + + auto oPos = gate->GetPosition(); + auto oDir = gate->GetRotation().GetForwardVector(); + NiPoint3 newPos( + oPos.x + (oDir.x * spawnDist), + oPos.y, + oPos.z + (oDir.z * spawnDist) + ); + auto newRot = NiQuaternion::LookAt(newPos, oPos); + + for (int i = 0; i < mobTable.size(); i++) { + int posOffset = -10; + if (mobTable[i] == LWOOBJID_EMPTY) { + posOffset = posOffset + 5 * i; + auto newOffset = newPos; + newOffset.z = newOffset.z + posOffset; + + EntityInfo info{}; + info.lot = mobTemplate; + info.pos = newOffset; + info.rot = newRot; + info.spawnerID = self->GetObjectID(); + info.spawnerNodeID = 0; + info.settings = { + new LDFData<bool>(u"no_timed_spawn", true), + new LDFData<float>(u"aggroRadius", 70), + new LDFData<float>(u"softtetherRadius", 80), + new LDFData<float>(u"tetherRadius", 90), + new LDFData<float>(u"wanderRadius", 5), + new LDFData<int>(u"mobTableLoc", i) + }; + + auto* child = EntityManager::Instance()->CreateEntity(info, nullptr, self); + EntityManager::Instance()->ConstructEntity(child); + + OnChildLoaded(self, child); + } else { + auto* mob = EntityManager::Instance()->GetEntity(mobTable[i]); + AggroTargetObject(self, mob); + } + } + + } +} + +void QbSpawner::OnChildLoaded(Entity* self, Entity* child) { + auto mobTable = self->GetVar<std::vector<LWOOBJID>>(u"mobTable"); + auto tableLoc = child->GetVar<int>(u"mobTableLoc"); + + mobTable[tableLoc] = child->GetObjectID(); + self->SetVar<std::vector<LWOOBJID>>(u"mobTable", mobTable); + + AggroTargetObject(self, child); + + const auto selfID = self->GetObjectID(); + + child->AddDieCallback([this, selfID, child]() { + auto* self = EntityManager::Instance()->GetEntity(selfID); + OnChildRemoved(self, child); + } + ); +} + +void QbSpawner::OnChildRemoved(Entity* self, Entity* child) { + auto mobTable = self->GetVar<std::vector<LWOOBJID>>(u"mobTable"); + auto tableLoc = child->GetVar<int>(u"mobTableLoc"); + + mobTable[tableLoc] = LWOOBJID_EMPTY; + self->SetVar<std::vector<LWOOBJID>>(u"mobTable", mobTable); +} + +void QbSpawner::AggroTargetObject(Entity* self, Entity* enemy) { + auto* baseCombatAIComponent = enemy->GetComponent<BaseCombatAIComponent>(); + if (!baseCombatAIComponent) return; + + auto gateObjID = self->GetVar<LWOOBJID>(u"gateObj"); + if (gateObjID) { + auto* gate = EntityManager::Instance()->GetEntity(gateObjID); + if (gate) { + auto* movementAIComponent = enemy->GetComponent<MovementAIComponent>(); + if (movementAIComponent) movementAIComponent->SetDestination(gate->GetPosition()); + baseCombatAIComponent->Taunt(gateObjID, 1000); + } + } + + auto playerObjID = self->GetVar<LWOOBJID>(u"player"); + if (playerObjID) { + baseCombatAIComponent->Taunt(playerObjID, 100); + } + +} + diff --git a/dScripts/QbSpawner.h b/dScripts/QbSpawner.h new file mode 100644 index 00000000..105d0835 --- /dev/null +++ b/dScripts/QbSpawner.h @@ -0,0 +1,17 @@ +#pragma once +#include "CppScripts.h" + +class QbSpawner : public CppScripts::Script { +public: + void OnStartup(Entity* self) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnChildLoaded(Entity* self, Entity* child); + void OnChildRemoved(Entity* self, Entity* child); + void AggroTargetObject(Entity* self, Entity* enemy); +private: + const int m_DefaultMobNum = 3; + const float m_DefaultSpawnDist = 25.0; + const LWOOBJID m_DefaultMobTemplate = 4712; + const float m_DefaultSpawnTime = 2.0; +}; From 26f2eb409ffb50b011d892bbfc029214f635f8a2 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 2 Sep 2022 13:49:19 -0500 Subject: [PATCH 096/322] Mounts v2 (#726) * Mounts -v2 * fix stun state and make comments a bit nicer * remove extra serilization * update the char position a bit more correctly * make vehicles face thr player's direction * address feedback * fix compiling for real this time * removed uneeded check --- dCommon/eUnequippableActiveType.h | 14 ++ dDatabase/Tables/CDItemComponentTable.cpp | 4 +- dGame/Entity.cpp | 7 + dGame/dComponents/CharacterComponent.h | 17 -- .../ControllablePhysicsComponent.cpp | 6 +- .../ControllablePhysicsComponent.h | 17 ++ dGame/dComponents/DestroyableComponent.cpp | 20 ++ dGame/dComponents/InventoryComponent.cpp | 194 ++++++++---------- dGame/dComponents/InventoryComponent.h | 7 + dGame/dComponents/PetComponent.cpp | 5 +- dGame/dComponents/PossessableComponent.cpp | 17 +- dGame/dComponents/PossessableComponent.h | 30 ++- dGame/dComponents/PossessorComponent.cpp | 67 +++++- dGame/dComponents/PossessorComponent.h | 59 ++++-- dGame/dGameMessages/GameMessageHandler.cpp | 4 + dGame/dGameMessages/GameMessages.cpp | 53 +++-- dGame/dGameMessages/GameMessages.h | 3 +- dGame/dInventory/Item.cpp | 64 +++--- dGame/dInventory/Item.h | 3 +- dGame/dUtilities/SlashCommandHandler.cpp | 95 ++++++--- dNet/ClientPackets.cpp | 34 ++- docs/Commands.md | 5 +- 22 files changed, 480 insertions(+), 245 deletions(-) create mode 100644 dCommon/eUnequippableActiveType.h diff --git a/dCommon/eUnequippableActiveType.h b/dCommon/eUnequippableActiveType.h new file mode 100644 index 00000000..8a6d29ba --- /dev/null +++ b/dCommon/eUnequippableActiveType.h @@ -0,0 +1,14 @@ +#pragma once + +#ifndef __EUNEQUIPPABLEACTIVETYPE__H__ +#define __EUNEQUIPPABLEACTIVETYPE__H__ + +#include <cstdint> + +enum class eUnequippableActiveType : int32_t { + INVALID = -1, + PET = 0, + MOUNT +}; + +#endif //!__EUNEQUIPPABLEACTIVETYPE__H__ diff --git a/dDatabase/Tables/CDItemComponentTable.cpp b/dDatabase/Tables/CDItemComponentTable.cpp index 703497ff..6ff192fd 100644 --- a/dDatabase/Tables/CDItemComponentTable.cpp +++ b/dDatabase/Tables/CDItemComponentTable.cpp @@ -45,7 +45,7 @@ CDItemComponentTable::CDItemComponentTable(void) { entry.offsetGroupID = tableData.getIntField(19, -1); entry.buildTypes = tableData.getIntField(20, -1); entry.reqPrecondition = tableData.getStringField(21, ""); - entry.animationFlag = tableData.getIntField(22, -1); + entry.animationFlag = tableData.getIntField(22, 0); entry.equipEffects = tableData.getIntField(23, -1); entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; entry.itemRating = tableData.getIntField(25, -1); @@ -123,7 +123,7 @@ const CDItemComponent& CDItemComponentTable::GetItemComponentByID(unsigned int s entry.offsetGroupID = tableData.getIntField(19, -1); entry.buildTypes = tableData.getIntField(20, -1); entry.reqPrecondition = tableData.getStringField(21, ""); - entry.animationFlag = tableData.getIntField(22, -1); + entry.animationFlag = tableData.getIntField(22, 0); entry.equipEffects = tableData.getIntField(23, -1); entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; entry.itemRating = tableData.getIntField(25, -1); diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 89289004..52eddd06 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -1454,6 +1454,13 @@ void Entity::Smash(const LWOOBJID source, const eKillType killType, const std::u Kill(EntityManager::Instance()->GetEntity(source)); return; } + auto* possessorComponent = GetComponent<PossessorComponent>(); + if (possessorComponent) { + if (possessorComponent->GetPossessable() != LWOOBJID_EMPTY) { + auto* mount = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + if (mount) possessorComponent->Dismount(mount, true); + } + } destroyableComponent->Smash(source, killType, deathType); } diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index 8efb4ef5..196dfa01 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -167,18 +167,6 @@ public: */ void SetLastRocketItemID(LWOOBJID lastRocketItemID) { m_LastRocketItemID = lastRocketItemID; } - /** - * Gets the object ID of the mount item that is being used - * @return the object ID of the mount item that is being used - */ - LWOOBJID GetMountItemID() const { return m_MountItemID; } - - /** - * Sets the object ID of the mount item that is being used - * @param m_MountItemID the object ID of the mount item that is being used - */ - void SetMountItemID(LWOOBJID mountItemID) { m_MountItemID = mountItemID; } - /** * Gets the name of this character * @return the name of this character @@ -569,11 +557,6 @@ private: * ID of the last rocket used */ LWOOBJID m_LastRocketItemID = LWOOBJID_EMPTY; - - /** - * Mount Item ID - */ - LWOOBJID m_MountItemID = LWOOBJID_EMPTY; }; #endif // CHARACTERCOMPONENT_H diff --git a/dGame/dComponents/ControllablePhysicsComponent.cpp b/dGame/dComponents/ControllablePhysicsComponent.cpp index 471b9ca1..d7caf6a9 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/ControllablePhysicsComponent.cpp @@ -32,6 +32,7 @@ ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Com m_IgnoreMultipliers = false; m_PickupRadius = 0.0f; m_DirtyPickupRadiusScale = true; + m_IsTeleporting = false; if (entity->GetLOT() != 1) // Other physics entities we care about will be added by BaseCombatAI return; @@ -128,7 +129,10 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bo outBitStream->Write0(); } - if (!bIsInitialUpdate) outBitStream->Write0(); + if (!bIsInitialUpdate) { + outBitStream->Write(m_IsTeleporting); + m_IsTeleporting = false; + } } void ControllablePhysicsComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { diff --git a/dGame/dComponents/ControllablePhysicsComponent.h b/dGame/dComponents/ControllablePhysicsComponent.h index bc05657c..ac481b9f 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.h +++ b/dGame/dComponents/ControllablePhysicsComponent.h @@ -220,6 +220,18 @@ public: */ bool GetStatic() const { return m_Static; } + /** + * Sets if the entity is Teleporting, + * @param value whether or not the entity is Is Teleporting + */ + void SetIsTeleporting(const bool value) { m_IsTeleporting = value; } + + /** + * Returns whether or not this entity is currently is teleporting + * @return whether or not this entity is currently is teleporting + */ + bool GetIsTeleporting() const { return m_IsTeleporting; } + /** * Returns the Physics entity for the component * @return Physics entity for the component @@ -355,6 +367,11 @@ private: * The active pickup radius for this entity */ float m_PickupRadius; + + /** + * If the entity is teleporting + */ + bool m_IsTeleporting; }; #endif // CONTROLLABLEPHYSICSCOMPONENT_H diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 1cbf7aad..8b9ae42d 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -26,6 +26,8 @@ #include "MissionComponent.h" #include "CharacterComponent.h" +#include "PossessableComponent.h" +#include "PossessorComponent.h" #include "dZoneManager.h" DestroyableComponent::DestroyableComponent(Entity* parent) : Component(parent) { @@ -608,6 +610,24 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 SetHealth(health); SetIsShielded(absorb > 0); + // Dismount on the possessable hit + auto possessable = m_Parent->GetComponent<PossessableComponent>(); + if (possessable && possessable->GetDepossessOnHit()) { + possessable->Dismount(); + } + + // Dismount on the possessor hit + auto possessor = m_Parent->GetComponent<PossessorComponent>(); + if (possessor) { + auto possessableId = possessor->GetPossessable(); + if (possessableId != LWOOBJID_EMPTY) { + auto possessable = EntityManager::Instance()->GetEntity(possessableId); + if (possessable) { + possessor->Dismount(possessable); + } + } + } + if (m_Parent->GetLOT() != 1) { echo = true; } diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 6dbb3bd8..930ace8d 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -26,6 +26,7 @@ #include "DestroyableComponent.h" #include "dConfig.h" #include "eItemType.h" +#include "eUnequippableActiveType.h" InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document) : Component(parent) { this->m_Dirty = true; @@ -62,23 +63,23 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do const auto& info = Inventory::FindItemComponent(item.itemid); UpdateSlot(info.equipLocation, { id, static_cast<LOT>(item.itemid), item.count, slot++ }); - + // Equip this items proxies. auto subItems = info.subItems; - + subItems.erase(std::remove_if(subItems.begin(), subItems.end(), ::isspace), subItems.end()); - + if (!subItems.empty()) { const auto subItemsSplit = GeneralUtils::SplitString(subItems, ','); - + for (auto proxyLotAsString : subItemsSplit) { const auto proxyLOT = static_cast<LOT>(std::stoi(proxyLotAsString)); - + const auto& proxyInfo = Inventory::FindItemComponent(proxyLOT); const LWOOBJID proxyId = ObjectIDManager::Instance()->GenerateObjectID(); - + // Use item.count since we equip item.count number of the item this is a requested proxy of - UpdateSlot(proxyInfo.equipLocation, { proxyId, proxyLOT, item.count, slot++ } ); + UpdateSlot(proxyInfo.equipLocation, { proxyId, proxyLOT, item.count, slot++ }); } } } @@ -795,9 +796,7 @@ void InventoryComponent::RemoveSlot(const std::string& location) { } void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { - if (!Inventory::IsValidItem(item->GetLot())) { - return; - } + if (!Inventory::IsValidItem(item->GetLot())) return; // Temp items should be equippable but other transfer items shouldn't be (for example the instruments in RB) if (item->IsEquipped() @@ -820,9 +819,7 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { auto* characterComponent = m_Parent->GetComponent<CharacterComponent>(); - if (characterComponent != nullptr) { - characterComponent->SetLastRocketItemID(item->GetId()); - } + if (characterComponent != nullptr) characterComponent->SetLastRocketItemID(item->GetId()); lauchPad->OnUse(m_Parent); @@ -836,94 +833,8 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { const auto type = static_cast<eItemType>(item->GetInfo().itemType); - if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == false) { - auto startPosition = m_Parent->GetPosition(); - auto startRotation = NiQuaternion::LookAt(startPosition, startPosition + NiPoint3::UNIT_X); - auto angles = startRotation.GetEulerAngles(); - angles.y -= PI; - startRotation = NiQuaternion::FromEulerAngles(angles); - - GameMessages::SendTeleport(m_Parent->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); - - EntityInfo info{}; - info.lot = 8092; - info.pos = startPosition; - info.rot = startRotation; - info.spawnerID = m_Parent->GetObjectID(); - - auto* carEntity = EntityManager::Instance()->CreateEntity(info, nullptr, m_Parent); - m_Parent->AddChild(carEntity); - - auto* destroyableComponent = carEntity->GetComponent<DestroyableComponent>(); - - // Setup the vehicle stats. - if (destroyableComponent != nullptr) { - destroyableComponent->SetIsSmashable(false); - destroyableComponent->SetIsImmune(true); - } - // #108 - auto* possessableComponent = carEntity->GetComponent<PossessableComponent>(); - - if (possessableComponent != nullptr) { - previousPossessableID = possessableComponent->GetPossessor(); - possessableComponent->SetPossessor(m_Parent->GetObjectID()); - } - - auto* moduleAssemblyComponent = carEntity->GetComponent<ModuleAssemblyComponent>(); - - if (moduleAssemblyComponent != nullptr) { - moduleAssemblyComponent->SetSubKey(item->GetSubKey()); - moduleAssemblyComponent->SetUseOptionalParts(false); - - for (auto* config : item->GetConfig()) { - if (config->GetKey() == u"assemblyPartLOTs") { - moduleAssemblyComponent->SetAssemblyPartsLOTs(GeneralUtils::ASCIIToUTF16(config->GetValueAsString())); - } - } - } - // #107 - auto* possessorComponent = m_Parent->GetComponent<PossessorComponent>(); - - if (possessorComponent) possessorComponent->SetPossessable(carEntity->GetObjectID()); - - auto* characterComponent = m_Parent->GetComponent<CharacterComponent>(); - - if (characterComponent) characterComponent->SetIsRacing(true); - - EntityManager::Instance()->ConstructEntity(carEntity); - EntityManager::Instance()->SerializeEntity(m_Parent); - GameMessages::SendSetJetPackMode(m_Parent, false); - - GameMessages::SendNotifyVehicleOfRacingObject(carEntity->GetObjectID(), m_Parent->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendRacingPlayerLoaded(LWOOBJID_EMPTY, m_Parent->GetObjectID(), carEntity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendVehicleUnlockInput(carEntity->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendTeleport(m_Parent->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); - GameMessages::SendTeleport(carEntity->GetObjectID(), startPosition, startRotation, m_Parent->GetSystemAddress(), true, true); - EntityManager::Instance()->SerializeEntity(m_Parent); - - hasCarEquipped = true; - equippedCarEntity = carEntity; - return; - } else if (item->GetLot() == 8092 && m_Parent->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && hasCarEquipped == true) { - GameMessages::SendNotifyRacingClient(LWOOBJID_EMPTY, 3, 0, LWOOBJID_EMPTY, u"", m_Parent->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - auto player = dynamic_cast<Player*>(m_Parent); - player->SendToZone(player->GetCharacter()->GetZoneID()); - equippedCarEntity->Kill(); - hasCarEquipped = false; - equippedCarEntity = nullptr; - return; - } - - if (!building) { - if (item->GetLot() == 6086) { - return; - } - - if (type == eItemType::ITEM_TYPE_LOOT_MODEL || type == eItemType::ITEM_TYPE_VEHICLE) { - return; - } - } + if (!building && (item->GetLot() == 6086 || type == eItemType::ITEM_TYPE_LOOT_MODEL || type == eItemType::ITEM_TYPE_VEHICLE)) return; if (type != eItemType::ITEM_TYPE_LOOT_MODEL && type != eItemType::ITEM_TYPE_MODEL) { if (!item->GetBound() && !item->GetPreconditionExpression()->Check(m_Parent)) { @@ -940,9 +851,7 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { set->OnEquip(lot); } - if (item->GetInfo().isBOE) { - item->SetBound(true); - } + if (item->GetInfo().isBOE) item->SetBound(true); GenerateProxies(item); @@ -989,6 +898,85 @@ void InventoryComponent::UnEquipItem(Item* item) { } } +void InventoryComponent::HandlePossession(Item* item) { + auto* characterComponent = m_Parent->GetComponent<CharacterComponent>(); + if (!characterComponent) return; + + auto* possessorComponent = m_Parent->GetComponent<PossessorComponent>(); + if (!possessorComponent) return; + + // Don't do anything if we are busy dismounting + if (possessorComponent->GetIsDismounting()) return; + + // Check to see if we are already mounting something + auto* currentlyPossessedEntity = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + auto currentlyPossessedItem = possessorComponent->GetMountItemID(); + + if (currentlyPossessedItem) { + if (currentlyPossessedEntity) possessorComponent->Dismount(currentlyPossessedEntity); + return; + } + + GameMessages::SendSetStunned(m_Parent->GetObjectID(), eStunState::PUSH, m_Parent->GetSystemAddress(), LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); + + // Set the mount Item ID so that we know what were handling + possessorComponent->SetMountItemID(item->GetId()); + GameMessages::SendSetMountInventoryID(m_Parent, item->GetId(), UNASSIGNED_SYSTEM_ADDRESS); + + // Create entity to mount + auto startRotation = m_Parent->GetRotation(); + + EntityInfo info{}; + info.lot = item->GetLot(); + info.pos = m_Parent->GetPosition(); + info.rot = startRotation; + info.spawnerID = m_Parent->GetObjectID(); + + auto* mount = EntityManager::Instance()->CreateEntity(info, nullptr, m_Parent); + + // Check to see if the mount is a vehicle, if so, flip it + auto* vehicleComponent = mount->GetComponent<VehiclePhysicsComponent>(); + if (vehicleComponent) { + auto angles = startRotation.GetEulerAngles(); + // Make it right side up + angles.x -= PI; + // Make it going in the direction of the player + angles.y -= PI; + startRotation = NiQuaternion::FromEulerAngles(angles); + mount->SetRotation(startRotation); + // We're pod racing now + characterComponent->SetIsRacing(true); + } + + // Setup the destroyable stats + auto* destroyableComponent = mount->GetComponent<DestroyableComponent>(); + if (destroyableComponent) { + destroyableComponent->SetIsSmashable(false); + destroyableComponent->SetIsImmune(true); + } + + // Mount it + auto* possessableComponent = mount->GetComponent<PossessableComponent>(); + if (possessableComponent) { + possessableComponent->SetIsItemSpawned(true); + possessableComponent->SetPossessor(m_Parent->GetObjectID()); + // Possess it + possessorComponent->SetPossessable(mount->GetObjectID()); + possessorComponent->SetPossessableType(possessableComponent->GetPossessionType()); + } + + GameMessages::SendSetJetPackMode(m_Parent, false); + + // Make it go to the client + EntityManager::Instance()->ConstructEntity(mount); + // Update the possessor + EntityManager::Instance()->SerializeEntity(m_Parent); + + // have to unlock the input so it vehicle can be driven + if (vehicleComponent) GameMessages::SendVehicleUnlockInput(mount->GetObjectID(), false, m_Parent->GetSystemAddress()); + GameMessages::SendMarkInventoryItemAsActive(m_Parent->GetObjectID(), true, eUnequippableActiveType::MOUNT, item->GetId(), m_Parent->GetSystemAddress()); +} + void InventoryComponent::ApplyBuff(Item* item) const { const auto buffs = FindBuffs(item, true); diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index 01b4ca86..394cb801 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -198,6 +198,13 @@ public: */ void UnEquipItem(Item* item); + /** + * Unequips an Item from the inventory + * @param item the Item to unequip + * @return if we were successful + */ + void HandlePossession(Item* item); + /** * Adds a buff related to equipping a lot to the entity * @param item the item to find buffs for diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index ef882555..8863f9be 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -14,6 +14,7 @@ #include "dpWorld.h" #include "PetDigServer.h" #include "../dWorldServer/ObjectIDManager.h" +#include "eUnequippableActiveType.h" #include "Game.h" #include "dConfig.h" @@ -883,7 +884,7 @@ void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) { GameMessages::SendSetPetNameModerated(m_Owner, m_DatabaseId, m_ModerationStatus, owner->GetSystemAddress()); } - GameMessages::SendMarkInventoryItemAsActive(m_Owner, true, 0, m_ItemId, GetOwner()->GetSystemAddress()); + GameMessages::SendMarkInventoryItemAsActive(m_Owner, true, eUnequippableActiveType::PET, m_ItemId, GetOwner()->GetSystemAddress()); activePets[m_Owner] = m_Parent->GetObjectID(); @@ -945,7 +946,7 @@ void PetComponent::AddDrainImaginationTimer(Item* item, bool fromTaming) { void PetComponent::Deactivate() { GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), -1, u"despawn", "", LWOOBJID_EMPTY, 1, 1, true); - GameMessages::SendMarkInventoryItemAsActive(m_Owner, false, 0, m_ItemId, GetOwner()->GetSystemAddress()); + GameMessages::SendMarkInventoryItemAsActive(m_Owner, false, eUnequippableActiveType::PET, m_ItemId, GetOwner()->GetSystemAddress()); activePets.erase(m_Owner); diff --git a/dGame/dComponents/PossessableComponent.cpp b/dGame/dComponents/PossessableComponent.cpp index be31914b..37591532 100644 --- a/dGame/dComponents/PossessableComponent.cpp +++ b/dGame/dComponents/PossessableComponent.cpp @@ -18,7 +18,7 @@ PossessableComponent::PossessableComponent(Entity* parent, uint32_t componentId) // Should a result not exist for this default to attached visible if (!result.eof()) { - m_PossessionType = static_cast<ePossessionType>(result.getIntField(0, 0)); + m_PossessionType = static_cast<ePossessionType>(result.getIntField(0, 1)); // Default to Attached Visible m_DepossessOnHit = static_cast<bool>(result.getIntField(1, 0)); } else { m_PossessionType = ePossessionType::ATTACHED_VISIBLE; @@ -30,7 +30,7 @@ PossessableComponent::PossessableComponent(Entity* parent, uint32_t componentId) void PossessableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { outBitStream->Write(m_DirtyPossessable || bIsInitialUpdate); if (m_DirtyPossessable || bIsInitialUpdate) { - m_DirtyPossessable = false; + m_DirtyPossessable = false; // reset flag outBitStream->Write(m_Possessor != LWOOBJID_EMPTY); if (m_Possessor != LWOOBJID_EMPTY) outBitStream->Write(m_Possessor); @@ -38,9 +38,18 @@ void PossessableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIn if (m_AnimationFlag != eAnimationFlags::IDLE_INVALID) outBitStream->Write(m_AnimationFlag); outBitStream->Write(m_ImmediatelyDepossess); + m_ImmediatelyDepossess = false; // reset flag } } -void PossessableComponent::OnUse(Entity* originator) { - // TODO: Implement this +void PossessableComponent::Dismount() { + SetPossessor(LWOOBJID_EMPTY); + if (m_ItemSpawned) m_Parent->ScheduleKillAfterUpdate(); +} + +void PossessableComponent::OnUse(Entity* originator) { + auto* possessor = originator->GetComponent<PossessorComponent>(); + if (possessor) { + possessor->Mount(m_Parent); + } } diff --git a/dGame/dComponents/PossessableComponent.h b/dGame/dComponents/PossessableComponent.h index 77905c9c..43ce8610 100644 --- a/dGame/dComponents/PossessableComponent.h +++ b/dGame/dComponents/PossessableComponent.h @@ -20,14 +20,24 @@ public: void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); /** - * Sets the possessor of this entity + * @brief mounts the Entity + */ + void Mount(); + + /** + * @brief dismounts the Entity + */ + void Dismount(); + + /** + * Sets the possessor of this Entity * @param value the ID of the possessor to set */ void SetPossessor(LWOOBJID value) { m_Possessor = value; m_DirtyPossessable = true; }; /** - * Returns the possessor of this entity - * @return the possessor of this entity + * Returns the possessor of this Entity + * @return the possessor of this Entity */ LWOOBJID GetPossessor() const { return m_Possessor; }; @@ -38,19 +48,19 @@ public: void SetAnimationFlag(eAnimationFlags value) { m_AnimationFlag = value; m_DirtyPossessable = true; }; /** - * Returns the possession type of this entity - * @return the possession type of this entity + * Returns the possession type of this Entity + * @return the possession type of this Entity */ ePossessionType GetPossessionType() const { return m_PossessionType; }; /** - * Returns if the entity should deposses on hit - * @return if the entity should deposses on hit + * Returns if the Entity should deposses on hit + * @return if the Entity should deposses on hit */ bool GetDepossessOnHit() const { return m_DepossessOnHit; }; /** - * Forcibly depossess the entity + * Forcibly depossess the Entity */ void ForceDepossess() { m_ImmediatelyDepossess = true; m_DirtyPossessable = true; }; @@ -58,13 +68,13 @@ public: * Set if the parent entity was spawned from an item * @param value if the parent entity was spawned from an item */ - void SetItemSpawned(bool value) { m_ItemSpawned = value; }; + void SetIsItemSpawned(bool value) { m_ItemSpawned = value; }; /** * Returns if the parent entity was spawned from an item * @return if the parent entity was spawned from an item */ - LWOOBJID GetItemSpawned() const { return m_ItemSpawned; }; + LWOOBJID GetIsItemSpawned() const { return m_ItemSpawned; }; /** * Handles an OnUsed event by some other entity, if said entity has a Possessor it becomes the possessor diff --git a/dGame/dComponents/PossessorComponent.cpp b/dGame/dComponents/PossessorComponent.cpp index 4ace324b..f0cad5ca 100644 --- a/dGame/dComponents/PossessorComponent.cpp +++ b/dGame/dComponents/PossessorComponent.cpp @@ -1,12 +1,28 @@ #include "PossessorComponent.h" +#include "PossessableComponent.h" +#include "CharacterComponent.h" +#include "EntityManager.h" +#include "GameMessages.h" +#include "eUnequippableActiveType.h" PossessorComponent::PossessorComponent(Entity* parent) : Component(parent) { m_Possessable = LWOOBJID_EMPTY; } -PossessorComponent::~PossessorComponent() {} - - +PossessorComponent::~PossessorComponent() { + if (m_Possessable != LWOOBJID_EMPTY) { + auto* mount = EntityManager::Instance()->GetEntity(m_Possessable); + if (mount) { + auto* possessable = mount->GetComponent<PossessableComponent>(); + if (possessable) { + if (possessable->GetIsItemSpawned()) { + GameMessages::SendMarkInventoryItemAsActive(m_Parent->GetObjectID(), false, eUnequippableActiveType::MOUNT, GetMountItemID(), m_Parent->GetSystemAddress()); + } + possessable->Dismount(); + } + } + } +} void PossessorComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { outBitStream->Write(m_DirtyPossesor || bIsInitialUpdate); @@ -19,3 +35,48 @@ void PossessorComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInit outBitStream->Write(m_PossessableType); } } + +void PossessorComponent::Mount(Entity* mount) { + // Don't do anything if we are busy dismounting + if (GetIsDismounting() || !mount) return; + + GameMessages::SendSetMountInventoryID(m_Parent, mount->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + auto* possessableComponent = mount->GetComponent<PossessableComponent>(); + if (possessableComponent) { + possessableComponent->SetPossessor(m_Parent->GetObjectID()); + SetPossessable(mount->GetObjectID()); + SetPossessableType(possessableComponent->GetPossessionType()); + } + + auto characterComponent = m_Parent->GetComponent<CharacterComponent>(); + if (characterComponent) characterComponent->SetIsRacing(true); + + // GM's to send + GameMessages::SendSetJetPackMode(m_Parent, false); + GameMessages::SendVehicleUnlockInput(mount->GetObjectID(), false, m_Parent->GetSystemAddress()); + GameMessages::SendSetStunned(m_Parent->GetObjectID(), eStunState::PUSH, m_Parent->GetSystemAddress(), LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); + + EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(mount); +} + +void PossessorComponent::Dismount(Entity* mount, bool forceDismount) { + // Don't do anything if we are busy dismounting + if (GetIsDismounting() || !mount) return; + SetIsDismounting(true); + + if (mount) { + auto* possessableComponent = mount->GetComponent<PossessableComponent>(); + if (possessableComponent) { + possessableComponent->SetPossessor(LWOOBJID_EMPTY); + if (forceDismount) possessableComponent->ForceDepossess(); + } + EntityManager::Instance()->SerializeEntity(m_Parent); + EntityManager::Instance()->SerializeEntity(mount); + + auto characterComponent = m_Parent->GetComponent<CharacterComponent>(); + if (characterComponent) characterComponent->SetIsRacing(false); + } + // Make sure we don't have wacky controls + GameMessages::SendSetPlayerControlScheme(m_Parent, eControlSceme::SCHEME_A); +} diff --git a/dGame/dComponents/PossessorComponent.h b/dGame/dComponents/PossessorComponent.h index 2735adac..00b24445 100644 --- a/dGame/dComponents/PossessorComponent.h +++ b/dGame/dComponents/PossessorComponent.h @@ -25,35 +25,63 @@ public: void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); /** - * Sets the entity that this entity is possessing - * @param value the ID of the entity this ID should posess + * @brief Mounts the entity + * + * @param mount Entity to be mounted + */ + void Mount(Entity* mount); + + /** + * @brief Dismounts the entity + * + * @param mount Entity to be dismounted + * @param forceDismount Should we forcibly dismount the entity + */ + void Dismount(Entity* mount, bool forceDismount = false); + + /** + * Sets the ID that this entity is possessing + * @param value The ID that this entity is possessing */ void SetPossessable(LWOOBJID value) { m_Possessable = value; m_DirtyPossesor = true; } /** * Returns the entity that this entity is currently posessing - * @return the entity that this entity is currently posessing + * @return The entity that this entity is currently posessing */ LWOOBJID GetPossessable() const { return m_Possessable; } /** - * Sets if we are busy mounting or dismounting - * @param value if we are busy mounting or dismounting + * Sets if we are busy dismounting + * @param value If we are busy dismounting */ - void SetIsBusy(bool value) { m_IsBusy = value; } + void SetIsDismounting(bool value) { m_IsDismounting = value; } /** - * Returns if we are busy mounting or dismounting - * @return if we are busy mounting or dismounting + * Returns if we are busy dismounting + * @return If we are busy dismounting */ - bool GetIsBusy() const { return m_IsBusy; } + bool GetIsDismounting() const { return m_IsDismounting; } /** * Sets the possesible type that's currently used, merely used by the shooting gallery if it's 0 - * @param value the possesible type to set + * @param value The possesible type to set */ void SetPossessableType(ePossessionType value) { m_PossessableType = value; m_DirtyPossesor = true; } + + /** + * Gets the object ID of the mount item that is being used + * @return The object ID of the mount item that is being used + */ + LWOOBJID GetMountItemID() const { return m_MountItemID; } + + /** + * Sets the object ID of the mount item that is being used + * @param m_MountItemID The object ID of the mount item that is being used + */ + void SetMountItemID(LWOOBJID mountItemID) { m_MountItemID = mountItemID; } + private: /** @@ -68,14 +96,19 @@ private: ePossessionType m_PossessableType = ePossessionType::NO_POSSESSION; /** - * @brief if the possessor is dirty + * @brief If the possessor is dirty * */ bool m_DirtyPossesor = false; /** - * @brief if the possessor is busy mounting or dismounting + * @brief If the possessor is busy dismounting * */ - bool m_IsBusy = false; + bool m_IsDismounting = false; + + /** + * Mount Item ID + */ + LWOOBJID m_MountItemID = LWOOBJID_EMPTY; }; diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index b3b60fe7..9cf09bbc 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -653,6 +653,10 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System GameMessages::HandleUpdatePlayerStatistic(inStream, entity); break; + case GAME_MSG_DISMOUNT_COMPLETE: + GameMessages::HandleDismountComplete(inStream, entity, sysAddr); + break; + default: //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X", messageID); break; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 1645afc8..772cb691 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -27,6 +27,7 @@ #include "ChatPackets.h" #include "GameConfig.h" #include "RocketLaunchLupComponent.h" +#include "eUnequippableActiveType.h" #include <sstream> #include <future> @@ -3414,7 +3415,7 @@ void GameMessages::SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, cons SEND_PACKET; } -void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, int32_t iType, LWOOBJID itemID, const SystemAddress& sysAddr) { +void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, eUnequippableActiveType iType, LWOOBJID itemID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -3423,8 +3424,8 @@ void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive bitStream.Write(bActive); - bitStream.Write(iType != 0); - if (iType != 0) bitStream.Write(iType); + bitStream.Write(iType != eUnequippableActiveType::INVALID); + if (iType != eUnequippableActiveType::INVALID) bitStream.Write(iType); bitStream.Write(itemID != LWOOBJID_EMPTY); if (itemID != LWOOBJID_EMPTY) bitStream.Write(itemID); @@ -3861,7 +3862,6 @@ void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objectID, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; - bitStream.Write(entity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_SET_MOUNT_INVENTORY_ID); bitStream.Write(objectID); @@ -3871,30 +3871,53 @@ void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objec void GameMessages::HandleDismountComplete(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + // Get the objectID from the bitstream LWOOBJID objectId{}; inStream->Read(objectId); - auto* mount = EntityManager::Instance()->GetEntity(objectId); + // If we aren't possessing somethings, the don't do anything if (objectId != LWOOBJID_EMPTY) { - PossessorComponent* possessor; - if (entity->TryGetComponent(COMPONENT_TYPE_POSSESSOR, possessor)) { - if (mount) { - possessor->SetIsBusy(false); - possessor->SetPossessable(LWOOBJID_EMPTY); - possessor->SetPossessableType(ePossessionType::NO_POSSESSION); + auto* possessorComponent = entity->GetComponent<PossessorComponent>(); + auto* mount = EntityManager::Instance()->GetEntity(objectId); + // make sure we have the things we need and they aren't null + if (possessorComponent && mount) { + if (!possessorComponent->GetIsDismounting()) return; + possessorComponent->SetIsDismounting(false); + possessorComponent->SetPossessable(LWOOBJID_EMPTY); + possessorComponent->SetPossessableType(ePossessionType::NO_POSSESSION); - GameMessages::SendSetStunned(entity->GetObjectID(), eStunState::POP, UNASSIGNED_SYSTEM_ADDRESS, LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); - - EntityManager::Instance()->SerializeEntity(entity); + // character related things + auto* character = entity->GetComponent<CharacterComponent>(); + if (character) { + // If we had an active item turn it off + if (possessorComponent->GetMountItemID() != LWOOBJID_EMPTY) GameMessages::SendMarkInventoryItemAsActive(entity->GetObjectID(), false, eUnequippableActiveType::MOUNT, possessorComponent->GetMountItemID(), entity->GetSystemAddress()); + possessorComponent->SetMountItemID(LWOOBJID_EMPTY); } + + // Set that the controllabel phsyics comp is teleporting + auto* controllablePhysicsComponent = entity->GetComponent<ControllablePhysicsComponent>(); + if (controllablePhysicsComponent) controllablePhysicsComponent->SetIsTeleporting(true); + + // Call dismoint on the possessable comp to let it handle killing the possessable + auto* possessableComponent = mount->GetComponent<PossessableComponent>(); + if (possessableComponent) possessableComponent->Dismount(); + + // Update the entity that was possessing + EntityManager::Instance()->SerializeEntity(entity); + + // We aren't mounted so remove the stun + GameMessages::SendSetStunned(entity->GetObjectID(), eStunState::POP, UNASSIGNED_SYSTEM_ADDRESS, LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); } } } void GameMessages::HandleAcknowledgePossession(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - Game::logger->Log("HandleAcknowledgePossession", "Got AcknowledgePossession from %i", entity->GetLOT()); EntityManager::Instance()->SerializeEntity(entity); + LWOOBJID objectId{}; + inStream->Read(objectId); + auto* mount = EntityManager::Instance()->GetEntity(objectId); + if (mount) EntityManager::Instance()->SerializeEntity(mount); } //Racing diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 47e5f41c..31bdebb3 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -19,6 +19,7 @@ class NiQuaternion; class User; class Entity; class NiPoint3; +enum class eUnequippableActiveType; namespace GameMessages { class PropertyDataMessage; @@ -318,7 +319,7 @@ namespace GameMessages { void SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, const SystemAddress& sysAddr); - void SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, int32_t iType, LWOOBJID itemID, const SystemAddress& sysAddr); + void SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive, eUnequippableActiveType iType, LWOOBJID itemID, const SystemAddress& sysAddr); void SendClientExitTamingMinigame(LWOOBJID objectId, bool bVoluntaryExit, const SystemAddress& sysAddr); diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 62e198a3..695ab47b 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -10,6 +10,9 @@ #include "dLogger.h" #include "EntityManager.h" #include "RenderComponent.h" +#include "PossessableComponent.h" +#include "CharacterComponent.h" +#include "eItemType.h" class Inventory; @@ -71,6 +74,12 @@ Item::Item( id = GeneralUtils::SetBit(id, OBJECT_BIT_CHARACTER); id = GeneralUtils::SetBit(id, OBJECT_BIT_PERSISTENT); + const auto type = static_cast<eItemType>(info->itemType); + + if (type == eItemType::ITEM_TYPE_MOUNT) { + id = GeneralUtils::SetBit(id, OBJECT_BIT_CLIENT); + } + this->id = id; inventory->AddManagedItem(this); @@ -254,49 +263,34 @@ bool Item::Consume() { return success; } -bool Item::UseNonEquip() { - auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - - const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_PACKAGE); - - auto* packCompTable = CDClientManager::Instance()->GetTable<CDPackageComponentTable>("PackageComponent"); - - auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast<uint32_t>(packageComponentId); }); - - const auto success = !packages.empty(); - - auto inventoryComponent = inventory->GetComponent(); - - auto playerEntity = inventoryComponent->GetParent(); - - if (subKey != LWOOBJID_EMPTY) { +void Item::UseNonEquip() { + const auto type = static_cast<eItemType>(info->itemType); + if (type == eItemType::ITEM_TYPE_MOUNT) { + GetInventory()->GetComponent()->HandlePossession(this); + } else if (type == eItemType::ITEM_TYPE_PET_INVENTORY_ITEM && subKey != LWOOBJID_EMPTY) { const auto& databasePet = GetInventory()->GetComponent()->GetDatabasePet(subKey); - if (databasePet.lot != LOT_NULL) { GetInventory()->GetComponent()->SpawnPet(this); - - return true; } - } - if (success && (playerEntity->GetGMLevel() >= eGameMasterLevel::GAME_MASTER_LEVEL_JUNIOR_DEVELOPER || this->GetPreconditionExpression()->Check(playerEntity))) { - auto* entityParent = inventory->GetComponent()->GetParent(); + } else if (type == eItemType::ITEM_TYPE_PACKAGE) { + auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_PACKAGE); + auto* packCompTable = CDClientManager::Instance()->GetTable<CDPackageComponentTable>("PackageComponent"); + auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast<uint32_t>(packageComponentId); }); - for (auto& pack : packages) { - std::unordered_map<LOT, int32_t> result{}; - - result = LootGenerator::Instance().RollLootMatrix(entityParent, pack.LootMatrixIndex); - - if (!inventory->GetComponent()->HasSpaceForLoot(result)) { - return false; + const auto success = !packages.empty(); + if (success) { + auto* entityParent = inventory->GetComponent()->GetParent(); + for (auto& pack : packages) { + std::unordered_map<LOT, int32_t> result{}; + result = LootGenerator::Instance().RollLootMatrix(entityParent, pack.LootMatrixIndex); + if (!inventory->GetComponent()->HasSpaceForLoot(result)) { + } + LootGenerator::Instance().GiveLoot(inventory->GetComponent()->GetParent(), result, eLootSourceType::LOOT_SOURCE_CONSUMPTION); } - - LootGenerator::Instance().GiveLoot(inventory->GetComponent()->GetParent(), result, eLootSourceType::LOOT_SOURCE_CONSUMPTION); + inventory->GetComponent()->RemoveItem(lot, 1); } - Game::logger->Log("Item", "Used (%i)", lot); - inventory->GetComponent()->RemoveItem(lot, 1); } - - return success; } void Item::Disassemble(const eInventoryType inventoryType) { diff --git a/dGame/dInventory/Item.h b/dGame/dInventory/Item.h index 0613ca85..db7e246a 100644 --- a/dGame/dInventory/Item.h +++ b/dGame/dInventory/Item.h @@ -193,9 +193,8 @@ public: /** * Uses this item if its non equip, essentially an interface for the linked GM - * @return whether the use was successful, e.g. the skill was cast */ - bool UseNonEquip(); + void UseNonEquip(); /** * Disassembles the part LOTs of this item back into the inventory, if it has any diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index b91021de..c6f1da9f 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -419,6 +419,11 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "playanimation" || chatCommand == "playanim") && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { std::u16string anim = GeneralUtils::ASCIIToUTF16(args[0], args[0].size()); GameMessages::SendPlayAnimation(entity, anim); + auto* possessorComponent = entity->GetComponent<PossessorComponent>(); + if (possessorComponent) { + auto* possessedComponent = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + if (possessedComponent) GameMessages::SendPlayAnimation(possessedComponent, anim); + } } if (chatCommand == "list-spawns" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { @@ -471,12 +476,24 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto* controllablePhysicsComponent = entity->GetComponent<ControllablePhysicsComponent>(); - if (controllablePhysicsComponent == nullptr) { - return; - } - + if (!controllablePhysicsComponent) return; controllablePhysicsComponent->SetSpeedMultiplier(boost); + // speedboost possesables + auto possessor = entity->GetComponent<PossessorComponent>(); + if (possessor) { + auto possessedID = possessor->GetPossessable(); + if (possessedID != LWOOBJID_EMPTY) { + auto possessable = EntityManager::Instance()->GetEntity(possessedID); + if (possessable) { + auto* possessControllablePhysicsComponent = possessable->GetComponent<ControllablePhysicsComponent>(); + if (possessControllablePhysicsComponent) { + possessControllablePhysicsComponent->SetSpeedMultiplier(boost); + } + } + } + } + EntityManager::Instance()->SerializeEntity(entity); } @@ -894,21 +911,17 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /teleport <x> (<y>) <z> - if no Y given, will teleport to the height of the terrain (or any physics object)."); } - auto* possessorComponent = entity->GetComponent<PossessorComponent>(); - if (possessorComponent != nullptr) { + auto* possessorComponent = entity->GetComponent<PossessorComponent>(); + if (possessorComponent) { auto* possassableEntity = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); if (possassableEntity != nullptr) { auto* vehiclePhysicsComponent = possassableEntity->GetComponent<VehiclePhysicsComponent>(); - - if (vehiclePhysicsComponent != nullptr) { + if (vehiclePhysicsComponent) { vehiclePhysicsComponent->SetPosition(pos); - EntityManager::Instance()->SerializeEntity(possassableEntity); - - Game::logger->Log("ClientPackets", "Forced updated vehicle position"); - } + } else GameMessages::SendTeleport(possassableEntity->GetObjectID(), pos, NiQuaternion(), sysAddr); } } } @@ -926,18 +939,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "dismount" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { - PossessorComponent* possessorComponent; - if (entity->TryGetComponent(COMPONENT_TYPE_POSSESSOR, possessorComponent)) { - Entity* vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); - if (!vehicle) return; - - PossessableComponent* possessableComponent; - if (vehicle->TryGetComponent(COMPONENT_TYPE_POSSESSABLE, possessableComponent)) { - possessableComponent->SetPossessor(LWOOBJID_EMPTY); - possessorComponent->SetPossessable(LWOOBJID_EMPTY); - - EntityManager::Instance()->SerializeEntity(vehicle); - EntityManager::Instance()->SerializeEntity(entity); + auto* possessorComponent = entity->GetComponent<PossessorComponent>(); + if (possessorComponent) { + auto possessableId = possessorComponent->GetPossessable(); + if (possessableId != LWOOBJID_EMPTY) { + auto* possessableEntity = EntityManager::Instance()->GetEntity(possessableId); + if (possessableEntity) possessorComponent->Dismount(possessableEntity, true); } } } @@ -1231,6 +1238,18 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } + auto vehiclePhysicsComponent = newEntity->GetComponent<VehiclePhysicsComponent>(); + if (vehiclePhysicsComponent) { + auto newRot = newEntity->GetRotation(); + auto angles = newRot.GetEulerAngles(); + // make it right side up + angles.x -= PI; + // make it going in the direction of the player + angles.y -= PI; + newRot = NiQuaternion::FromEulerAngles(angles); + newEntity->SetRotation(newRot); + } + EntityManager::Instance()->ConstructEntity(newEntity); } @@ -1520,7 +1539,33 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - GameMessages::SendVehicleAddPassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + if (args.size() >= 1) { + float time; + + if (!GeneralUtils::TryParse(args[0], time)) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid boost time."); + return; + } else { + GameMessages::SendVehicleAddPassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + entity->AddCallbackTimer(time, [vehicle]() { + if (!vehicle) return; + GameMessages::SendVehicleRemovePassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + }); + } + } else { + GameMessages::SendVehicleAddPassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); + } + + } + + if ((chatCommand == "unboost") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + auto* possessorComponent = entity->GetComponent<PossessorComponent>(); + + if (possessorComponent == nullptr) return; + auto* vehicle = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); + + if (vehicle == nullptr) return; + GameMessages::SendVehicleRemovePassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); } if (chatCommand == "activatespawner" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index b49801cc..39e835d2 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -140,14 +140,19 @@ void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Pac inStream.Read(angVelocity.z); } - bool hasVehicle = false; + bool updateChar = true; if (possessorComponent != nullptr) { auto* possassableEntity = EntityManager::Instance()->GetEntity(possessorComponent->GetPossessable()); if (possassableEntity != nullptr) { - auto* vehiclePhysicsComponent = possassableEntity->GetComponent<VehiclePhysicsComponent>(); + auto* possessableComponent = possassableEntity->GetComponent<PossessableComponent>(); + if (possessableComponent) { + // While possessing something, only update char if we are attached to the thing we are possessing + if (possessableComponent->GetPossessionType() != ePossessionType::ATTACHED_VISIBLE) updateChar = false; + } + auto* vehiclePhysicsComponent = possassableEntity->GetComponent<VehiclePhysicsComponent>(); if (vehiclePhysicsComponent != nullptr) { // This is flipped for whatever reason rotation = NiQuaternion(rotation.z, rotation.y, rotation.x, rotation.w); @@ -160,19 +165,30 @@ void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Pac vehiclePhysicsComponent->SetDirtyVelocity(velocityFlag); vehiclePhysicsComponent->SetAngularVelocity(angVelocity); vehiclePhysicsComponent->SetDirtyAngularVelocity(angVelocityFlag); - - EntityManager::Instance()->SerializeEntity(possassableEntity); - - hasVehicle = true; + } else { + // Need to get the mount's controllable physics + auto* controllablePhysicsComponent = possassableEntity->GetComponent<ControllablePhysicsComponent>(); + if (!controllablePhysicsComponent) return; + controllablePhysicsComponent->SetPosition(position); + controllablePhysicsComponent->SetRotation(rotation); + controllablePhysicsComponent->SetIsOnGround(onGround); + controllablePhysicsComponent->SetIsOnRail(onRail); + controllablePhysicsComponent->SetVelocity(velocity); + controllablePhysicsComponent->SetDirtyVelocity(velocityFlag); + controllablePhysicsComponent->SetAngularVelocity(angVelocity); + controllablePhysicsComponent->SetDirtyAngularVelocity(angVelocityFlag); } + EntityManager::Instance()->SerializeEntity(possassableEntity); } } - if (hasVehicle) { + if (!updateChar) { velocity = NiPoint3::ZERO; angVelocity = NiPoint3::ZERO; } + + // Handle statistics auto* characterComponent = entity->GetComponent<CharacterComponent>(); if (characterComponent != nullptr) { @@ -192,9 +208,7 @@ void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Pac player->SetGhostReferencePoint(position); EntityManager::Instance()->QueueGhostUpdate(player->GetObjectID()); - if (!hasVehicle) { - EntityManager::Instance()->SerializeEntity(entity); - } + if (updateChar) EntityManager::Instance()->SerializeEntity(entity); //TODO: add moving platform stuffs /*bool movingPlatformFlag; diff --git a/docs/Commands.md b/docs/Commands.md index 8cefaa14..95ec28f9 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -63,7 +63,8 @@ These commands are primarily for development and testing. The usage of many of t |teleport|`/teleport <x> (y) <z>`|Teleports you. If no Y is given, you are teleported to the height of the terrain or physics object at (x, z). Alias: `/tele`.|6| |activatespawner|`/activatespawner <spawner name>`|Activates spawner by name.|8| |addmission|`/addmission <mission id>`|Accepts the mission, adding it to your journal.|8| -|boost|`/boost`|Adds a passive boost action if you are in a vehicle.|8| +|boost|`/boost (time)`|Adds a passive boost action if you are in a vehicle. If time is given it will end after that amount of time|8| +|unboost|`/unboost`|Removes a passive vehicle boost|8| |buff|`/buff <id> <duration>`|Applies the buff with the given id for the given number of seconds.|8| |buffme|`/buffme`|Sets health, armor, and imagination to 999.|8| |buffmed|`/buffmed`|Sets health, armor, and imagination to 9.|8| @@ -71,7 +72,7 @@ These commands are primarily for development and testing. The usage of many of t |completemission|`/completemission <mission id>`|Completes the mission, removing it from your journal.|8| |createprivate|`/createprivate <zone id> <clone id> <password>`|Creates a private zone with password.|8| |debugui|`/debugui`|Toggle Debug UI.|8| -|dismount|`/dismount`|Dismounts you from the vehicle.|8| +|dismount|`/dismount`|Dismounts you from the vehicle or mount.|8| |force-save|`/force-save`|While saving to database usually happens on regular intervals and when you disconnect from the server, this command saves your player's data to the database.|8| |freecam|`/freecam`|Toggles freecam mode.|8| |freemoney|`/freemoney <coins>`|Gives coins.|8| From 14d4bf3cc512786eb70ac2553c2f2439221c766c Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 2 Sep 2022 13:49:38 -0500 Subject: [PATCH 097/322] Script for aborting a wbl zone transfer (#766) --- dScripts/CMakeLists.txt | 1 + dScripts/CppScripts.cpp | 8 ++++++++ dScripts/WblGenericZone.cpp | 10 ++++++++++ dScripts/WblGenericZone.h | 10 ++++++++++ 4 files changed, 29 insertions(+) create mode 100644 dScripts/WblGenericZone.cpp create mode 100644 dScripts/WblGenericZone.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 66e3b65b..0a907a05 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -247,6 +247,7 @@ set(DSCRIPT_SOURCES "ActivityManager.cpp" "WaveBossHammerling.cpp" "WaveBossHorsemen.cpp" "WaveBossSpiderling.cpp" + "WblGenericZone.cpp" "WhFans.cpp" "WildAmbients.cpp" "WishingWellServer.cpp" diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 7d114cd3..d313f2f9 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -288,6 +288,9 @@ #include "RockHydrantBroken.h" #include "WhFans.h" +// WBL scripts +#include "WblGenericZone.h" + //Big bad global bc this is a namespace and not a class: InvalidScript* invalidToReturn = new InvalidScript(); std::map<std::string, CppScripts::Script*> m_Scripts; @@ -834,12 +837,17 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new BuccaneerValiantShip(); else if (scriptName == "scripts\\EquipmentScripts\\FireFirstSkillonStartup.lua") script = new FireFirstSkillonStartup(); + // FB else if (scriptName == "scripts\\ai\\NS\\WH\\L_ROCKHYDRANT_BROKEN.lua") script = new RockHydrantBroken(); else if (scriptName == "scripts\\ai\\NS\\L_NS_WH_FANS.lua") script = new WhFans(); + // WBL + else if (scriptName == "scripts\\zone\\LUPs\\WBL_generic_zone.lua") + script = new WblGenericZone(); + //Ignore these scripts: else if (scriptName == "scripts\\02_server\\Enemy\\General\\L_SUSPEND_LUA_AI.lua") script = invalidToReturn; diff --git a/dScripts/WblGenericZone.cpp b/dScripts/WblGenericZone.cpp new file mode 100644 index 00000000..5a670d8e --- /dev/null +++ b/dScripts/WblGenericZone.cpp @@ -0,0 +1,10 @@ +#include "WblGenericZone.h" +#include "Player.h" + +void WblGenericZone::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args == m_WblAbortMsg) { + if (!sender) return; + auto player = dynamic_cast<Player*>(sender); + if (player) player->SendToZone(m_WblMainZone); + } +} diff --git a/dScripts/WblGenericZone.h b/dScripts/WblGenericZone.h new file mode 100644 index 00000000..55b66e81 --- /dev/null +++ b/dScripts/WblGenericZone.h @@ -0,0 +1,10 @@ +#pragma once +#include "CppScripts.h" +class WblGenericZone : public CppScripts::Script +{ +public: + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; +private: + const LWOMAPID m_WblMainZone = 1600; + const std::string m_WblAbortMsg = "AbortWBLZone"; +}; From c552f46780276ee50e3c632a9b7dbbb9c95f28e4 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sun, 4 Sep 2022 21:43:16 -0500 Subject: [PATCH 098/322] ignore empty.lua and empty scripts (#769) * ignore empty.lua and empty scripts and return early if it's an ignored script * return it else if logic --- dScripts/CppScripts.cpp | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index d313f2f9..dce77e4b 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -848,17 +848,13 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\zone\\LUPs\\WBL_generic_zone.lua") script = new WblGenericZone(); - //Ignore these scripts: - else if (scriptName == "scripts\\02_server\\Enemy\\General\\L_SUSPEND_LUA_AI.lua") - script = invalidToReturn; - else if (scriptName == "scripts\\02_server\\Enemy\\General\\L_BASE_ENEMY_SPIDERLING.lua") - script = invalidToReturn; + // handle invalid script reporting if the path is greater than zero and it's not an ignored script + // information not really needed for sys admins but is for developers else if (script == invalidToReturn) { - if (scriptName.length() > 0) - Game::logger->LogDebug("CppScripts", "Attempted to load CppScript for '%s', but returned InvalidScript.", scriptName.c_str()); - // information not really needed for sys admins but is for developers - - script = invalidToReturn; + if ((scriptName.length() > 0) && !((scriptName == "scripts\\02_server\\Enemy\\General\\L_SUSPEND_LUA_AI.lua") || + (scriptName == "scripts\\02_server\\Enemy\\General\\L_BASE_ENEMY_SPIDERLING.lua") || + (scriptName == "scripts\\empty.lua") + )) Game::logger->LogDebug("CppScripts", "LOT %i attempted to load CppScript for '%s', but returned InvalidScript.", parent->GetLOT(), scriptName.c_str()); } m_Scripts[scriptName] = script; From ce2e6f595b974ce534a695b50657a27d0998a691 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Mon, 5 Sep 2022 23:28:32 +0100 Subject: [PATCH 099/322] Resolve incorrectly marked consumables being unusable (#770) A change was made in the mounts pull request that broke consumables without correctly marked types such as the picnic basket --- dGame/dInventory/Item.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 695ab47b..4d4f2686 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -272,9 +272,12 @@ void Item::UseNonEquip() { if (databasePet.lot != LOT_NULL) { GetInventory()->GetComponent()->SpawnPet(this); } - } else if (type == eItemType::ITEM_TYPE_PACKAGE) { + } else { auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_PACKAGE); + + if (packageComponentId == 0) return; + auto* packCompTable = CDClientManager::Instance()->GetTable<CDPackageComponentTable>("PackageComponent"); auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast<uint32_t>(packageComponentId); }); From 63af2c8da74cbddf5b754fa6ee150c702effadfa Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 5 Sep 2022 20:28:47 -0700 Subject: [PATCH 100/322] Add ZLIB for Windows (#768) Added ZLIB for Windows. Packets for character creation are now compressed on windows before sending and ZCompression can now be used on Windows. --- CMakeLists.txt | 1 - CMakePresets.json | 11 ++++++++--- dCommon/CMakeLists.txt | 30 ++++++++++++++++++++++++++++-- dCommon/ZCompression.cpp | 23 ----------------------- dCommon/ZCompression.h | 5 ----- dNet/WorldPackets.cpp | 26 +++++++++++++++++--------- 6 files changed, 53 insertions(+), 43 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 1a977a64..721140a6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -160,7 +160,6 @@ elseif (UNIX) set(INCLUDED_DIRECTORIES ${INCLUDED_DIRECTORIES} "thirdparty/libbcrypt/include/bcrypt") endif() -include_directories(${ZLIB_INCLUDE_DIRS}) # Add binary directory as an include directory include_directories(${PROJECT_BINARY_DIR}) diff --git a/CMakePresets.json b/CMakePresets.json index 133d6a3c..badb161d 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -115,9 +115,14 @@ "displayName": "CI Tests on windows", "description": "Runs all tests on a windows configuration", "configuration": "RelWithDebInfo", - "execution": { - "jobs": 2 - }, + "execution": { + "jobs": 2 + }, + "filter": { + "exclude": { + "name": "((example)|(minigzip))+" + } + }, "output": { "outputOnFailure": true } diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 028eb29f..18fe582c 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -23,5 +23,31 @@ target_link_libraries(dCommon bcrypt) if (UNIX) find_package(ZLIB REQUIRED) - target_link_libraries(dCommon ZLIB::ZLIB) -endif() +elseif (WIN32) + include(FetchContent) + + # TODO Keep an eye on the zlib repository for an update to disable testing. Don't forget to update CMakePresets + FetchContent_Declare( + zlib + URL https://github.com/madler/zlib/archive/refs/tags/v1.2.11.zip + URL_HASH MD5=9d6a627693163bbbf3f26403a3a0b0b1 + ) + + # Disable warning about no project version. + set(CMAKE_POLICY_DEFAULT_CMP0048 NEW) + # Disable warning about the minimum version of cmake used for bcrypt being deprecated in the future + set(CMAKE_WARN_DEPRECATED OFF CACHE BOOL "" FORCE) + + FetchContent_MakeAvailable(zlib) + + set(ZLIB_INCLUDE_DIRS ${zlib_SOURCE_DIR} ${zlib_BINARY_DIR}) + set_target_properties(zlib PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${ZLIB_INCLUDE_DIRS}") + add_library(ZLIB::ZLIB ALIAS zlib) +else () + message( + FATAL_ERROR + "This platform does not have a way to use zlib.\nCreate an issue on GitHub with your build system so it can be configured." + ) +endif () + +target_link_libraries(dCommon ZLIB::ZLIB) diff --git a/dCommon/ZCompression.cpp b/dCommon/ZCompression.cpp index 70f23500..d5d4c126 100644 --- a/dCommon/ZCompression.cpp +++ b/dCommon/ZCompression.cpp @@ -1,7 +1,5 @@ #include "ZCompression.h" -#ifndef _WIN32 - #include <zlib.h> namespace ZCompression { @@ -27,7 +25,6 @@ namespace ZCompression { } deflateEnd(&zInfo); // zlib function return(nRet); - } int32_t Decompress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst, int32_t& nErr) { @@ -48,26 +45,6 @@ namespace ZCompression { } inflateEnd(&zInfo); // zlib function return(nRet); - - /* - z_stream zInfo = { 0 }; - zInfo.total_in = zInfo.avail_in = nLenSrc; - zInfo.total_out = zInfo.avail_out = nLenDst; - zInfo.next_in = const_cast<Bytef*>(abSrc); - zInfo.next_out = const_cast<Bytef*>(abDst); - - int nRet = -1; - nErr = inflateInit(&zInfo); // zlib function - if (nErr == Z_OK) { - nErr = inflate(&zInfo, Z_FINISH); // zlib function - if (nErr == Z_STREAM_END) { - nRet = zInfo.total_out; - } - } - inflateEnd(&zInfo); // zlib function - return(nRet); // -1 or len of output - */ } } -#endif diff --git a/dCommon/ZCompression.h b/dCommon/ZCompression.h index 7b987cfa..22a5ff86 100644 --- a/dCommon/ZCompression.h +++ b/dCommon/ZCompression.h @@ -2,10 +2,6 @@ #include <cstdint> -#include "dPlatforms.h" - -#ifndef DARKFLAME_PLATFORM_WIN32 - namespace ZCompression { int32_t GetMaxCompressedLength(int32_t nLenSrc); @@ -14,4 +10,3 @@ namespace ZCompression { int32_t Decompress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst, int32_t& nErr); } -#endif diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index 23d2c010..f6a8f558 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -164,27 +164,35 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent delete name; delete reputation; -#ifdef _WIN32 - bitStream.Write<uint32_t>(data.GetNumberOfBytesUsed() + 1); - bitStream.Write<uint8_t>(0); - bitStream.Write((char*)data.GetData(), data.GetNumberOfBytesUsed()); -#else //Compress the data before sending: - const int reservedSize = 5 * 1024 * 1024; - uint8_t compressedData[reservedSize]; + const uint32_t reservedSize = ZCompression::GetMaxCompressedLength(data.GetNumberOfBytesUsed()); + uint8_t* compressedData = new uint8_t[reservedSize]; + + // TODO There should be better handling here for not enough memory... + if (!compressedData) return; + size_t size = ZCompression::Compress(data.GetData(), data.GetNumberOfBytesUsed(), compressedData, reservedSize); + assert(size <= reservedSize); + bitStream.Write<uint32_t>(size + 9); //size of data + header bytes (8) bitStream.Write<uint8_t>(1); //compressed boolean, true bitStream.Write<uint32_t>(data.GetNumberOfBytesUsed()); bitStream.Write<uint32_t>(size); + /** + * In practice, this warning serves no purpose for us. We allocate the max memory needed on the heap + * and then compress the data. In the off chance that the compression actually increases the size, + * an assertion is done to prevent bad data from being saved or sent. + */ +#pragma warning(disable:6385) // C6385 Reading invalid data from 'compressedData'. for (size_t i = 0; i < size; i++) bitStream.Write(compressedData[i]); -#endif +#pragma warning(default:6385) - PacketUtils::SavePacket("chardata.bin", (const char*)bitStream.GetData(), static_cast<uint32_t>(bitStream.GetNumberOfBytesUsed())); + // PacketUtils::SavePacket("chardata.bin", (const char*)bitStream.GetData(), static_cast<uint32_t>(bitStream.GetNumberOfBytesUsed())); SEND_PACKET; + delete[] compressedData; Game::logger->Log("WorldPackets", "Sent CreateCharacter for ID: %llu", entity->GetObjectID()); } From 409d682c9d3d43510999f36d213d3f02da9bc456 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 21 Oct 2022 19:34:38 -0500 Subject: [PATCH 101/322] fix loading scenes in some older formats (#782) This fix is based on lcdr's luzviewer --- dZoneManager/Zone.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 54246c28..9072080a 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -338,10 +338,11 @@ const Path* Zone::GetPath(std::string name) const { void Zone::LoadSceneTransition(std::ifstream& file) { SceneTransition sceneTrans; - if (m_ZoneFileFormatVersion < Zone::ZoneFileFormatVersion::LateAlpha) { + if (m_ZoneFileFormatVersion < Zone::ZoneFileFormatVersion::Auramar) { uint8_t length; BinaryIO::BinaryRead(file, length); sceneTrans.name = BinaryIO::ReadString(file, length); + file.ignore(4); } //BR�THER MAY I HAVE SOME L��PS? From f02e9c0f6a5439ba468a4a6b247d3a2a2a228c7e Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 21 Oct 2022 17:35:12 -0700 Subject: [PATCH 102/322] Address being able to friend yourself (#779) * Address being able to friend yourself Fix an issue where players could friend themselves. Also stops yourself as appearing as a friend on your own friends list. * Send a Response instead Send a MYTHRAN response since the player is attempting to friend a Mythran. --- dChatServer/ChatPacketHandler.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index a51716ca..0f7f6919 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -33,9 +33,10 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { "WHEN friend_id = ? THEN player_id " "END AS requested_player, best_friend FROM friends) AS fr " "JOIN charinfo AS ci ON ci.id = fr.requested_player " - "WHERE fr.requested_player IS NOT NULL;")); + "WHERE fr.requested_player IS NOT NULL AND fr.requested_player != ?;")); stmt->setUInt(1, static_cast<uint32_t>(playerID)); stmt->setUInt(2, static_cast<uint32_t>(playerID)); + stmt->setUInt(3, static_cast<uint32_t>(playerID)); std::vector<FriendData> friends; @@ -113,6 +114,10 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { inStream.Read(isBestFriendRequest); auto requestor = playerContainer.GetPlayerData(requestorPlayerID); + if (requestor->playerName == playerName) { + SendFriendResponse(requestor, requestor, AddFriendResponseType::MYTHRAN); + return; + }; std::unique_ptr<PlayerData> requestee(playerContainer.GetPlayerData(playerName)); // Check if player is online first From 366c3db7fe1b50852df5deebe8cbcec3cacc0bc6 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sun, 23 Oct 2022 21:54:59 -0500 Subject: [PATCH 103/322] fix reading respawn for older maps (#784) --- dZoneManager/Level.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index ebfca4cc..f12adc56 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -266,7 +266,7 @@ void Level::ReadSceneObjectDataChunk(std::ifstream& file, Header& header) { spawnInfo.respawnTime = std::stof(data->GetValueAsString()); } else if (data->GetValueType() == eLDFType::LDF_TYPE_U32) // Ints are in ms? { - spawnInfo.respawnTime = std::stoi(data->GetValueAsString()) / 1000; + spawnInfo.respawnTime = std::stoul(data->GetValueAsString()) / 1000; } } if (data->GetKey() == u"spawnsGroupOnSmash") { From 8d44f2f5da762b245afcadffbc5c1d6b8ab9fe5d Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Mon, 24 Oct 2022 00:54:21 -0500 Subject: [PATCH 104/322] Add missing property path checks for new zones (#783) Co-authored-by: Jett <55758076+Jettford@users.noreply.github.com> --- dZoneManager/Zone.cpp | 56 ++++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 22 deletions(-) diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 9072080a..b670849b 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -403,30 +403,42 @@ void Zone::LoadPath(std::ifstream& file) { BinaryIO::BinaryRead(file, path.property.price); BinaryIO::BinaryRead(file, path.property.rentalTime); BinaryIO::BinaryRead(file, path.property.associatedZone); - uint8_t count1; - BinaryIO::BinaryRead(file, count1); - for (uint8_t i = 0; i < count1; ++i) { - uint16_t character; - BinaryIO::BinaryRead(file, character); - path.property.displayName.push_back(character); + + if (path.pathVersion >= 5) { + uint8_t count1; + BinaryIO::BinaryRead(file, count1); + for (uint8_t i = 0; i < count1; ++i) { + uint16_t character; + BinaryIO::BinaryRead(file, character); + path.property.displayName.push_back(character); + } + uint32_t count2; + BinaryIO::BinaryRead(file, count2); + for (uint8_t i = 0; i < count2; ++i) { + uint16_t character; + BinaryIO::BinaryRead(file, character); + path.property.displayDesc.push_back(character); + } } - uint32_t count2; - BinaryIO::BinaryRead(file, count2); - for (uint8_t i = 0; i < count2; ++i) { - uint16_t character; - BinaryIO::BinaryRead(file, character); - path.property.displayDesc.push_back(character); + + if (path.pathVersion >= 6) { + int32_t unknown1; + BinaryIO::BinaryRead(file, unknown1); + } + + if (path.pathVersion >= 7) { + BinaryIO::BinaryRead(file, path.property.cloneLimit); + BinaryIO::BinaryRead(file, path.property.repMultiplier); + BinaryIO::BinaryRead(file, path.property.rentalTimeUnit); + } + + if (path.pathVersion >= 8) { + BinaryIO::BinaryRead(file, path.property.achievementRequired); + BinaryIO::BinaryRead(file, path.property.playerZoneCoords.x); + BinaryIO::BinaryRead(file, path.property.playerZoneCoords.y); + BinaryIO::BinaryRead(file, path.property.playerZoneCoords.z); + BinaryIO::BinaryRead(file, path.property.maxBuildHeight); } - int32_t unknown1; - BinaryIO::BinaryRead(file, unknown1); - BinaryIO::BinaryRead(file, path.property.cloneLimit); - BinaryIO::BinaryRead(file, path.property.repMultiplier); - BinaryIO::BinaryRead(file, path.property.rentalTimeUnit); - BinaryIO::BinaryRead(file, path.property.achievementRequired); - BinaryIO::BinaryRead(file, path.property.playerZoneCoords.x); - BinaryIO::BinaryRead(file, path.property.playerZoneCoords.y); - BinaryIO::BinaryRead(file, path.property.playerZoneCoords.z); - BinaryIO::BinaryRead(file, path.property.maxBuildHeight); } else if (path.pathType == PathType::Camera) { uint8_t count; BinaryIO::BinaryRead(file, count); From c13937bd1f00f1c747b3ba6614bce884a9cc5f9a Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 24 Oct 2022 15:20:36 -0700 Subject: [PATCH 105/322] Address Brick-By-Brick builds not properly saving and make migrations automatic (#725) * Properly store BBB in database Store the BBB data in the database as the received SD0 packet as opposed to just the raw lxfml. Addressed several memory leaks as well. * Add Sd0Conversion Add brick by brick conversion commands with 2 parameters to tell the program what to do with the data. Add zlib -> sd0 conversion. Files look good at a glance but should be tested in game to ensure stability. Tests to come. * moving to laptop ignore this commit. I need to move this to my laptop * Add functionality to delete bad models Adds functionality to delete bad models. Models are batched together and deleted in one commit. More testing is needed to ensure data safety. Positive tests on a live database reveal the broken models were truncated and complete ones were kept around successfully. Tests should be done to ensure larger sd0 models are properly saved and not truncated since this command should be able to be run any time. Valgrind tests need to be run as well to ensure no memory leaks exist. * Delete from query change Changed from delete to delete cascade and instead deleting from properties_contents as opposed to ugc. * Address numerous bugs DELETE CASCADE is not a valid SQL command so this was changed to a better delete statement. Added user confirmation before deleting a broken model. Address appending the string model appending bad data, causing excess deletion. Addressed memory leaks with sql::Blob * Error handling for string * Even more proper handling... * Add bounds check for cli command Output a message if a bad command is used. Update MasterServer.cpp * Remove user interference -Add back in mariadb build jobs so i dont nuke others systems - Remove all user interference and consolidate work into one command since 1 depends on the next. * Add comments test Revert "test" This reverts commit fb831f268b7a2f0ccd20595aff64902ab4f4b4ee. * Update CMakeMariaDBLists.txt Test * Improve migration runner Migration runner now runs automatically. - Resolved an issue where extremely large sql queries caused the database to go into an invalid state. - Made migrations run automatically on server start. - Resolved a tiny memory leak in migration runner? (discarded returned pointer) - Moved sd0 migrations of brick models to be run automatically with migration runner. - Created dummy file to tell when brick migrations have been run. * Update README Updated the README to reflect the new server migration state. * Make model deleter actually delete models My complicated sql actually did nothing... Tested that this new SQL properly gets rid of bad data. * Revert "Update CMakeMariaDBLists.txt" This reverts commit 8b859d8529755d7132cef072b2532589c098f683. --- CMakeVariables.txt | 2 +- README.md | 7 +- dCommon/BrickByBrickFix.cpp | 180 +++++++++++++++++++++++++++ dCommon/BrickByBrickFix.h | 26 ++++ dCommon/CMakeLists.txt | 6 +- dDatabase/Database.cpp | 12 ++ dDatabase/Database.h | 2 + dDatabase/MigrationRunner.cpp | 47 ++++--- dGame/dGameMessages/GameMessages.cpp | 106 ++++------------ dMasterServer/MasterServer.cpp | 110 +++++++--------- dWorldServer/WorldServer.cpp | 9 -- migrations/dlu/5_brick_model_sd0.sql | 1 + 12 files changed, 334 insertions(+), 174 deletions(-) create mode 100644 dCommon/BrickByBrickFix.cpp create mode 100644 dCommon/BrickByBrickFix.h create mode 100644 migrations/dlu/5_brick_model_sd0.sql diff --git a/CMakeVariables.txt b/CMakeVariables.txt index 7a8d6b71..e68e826e 100644 --- a/CMakeVariables.txt +++ b/CMakeVariables.txt @@ -15,6 +15,6 @@ __dynamic=1 # __include_backtrace__=1 # Set __include_backtrace__ to 1 to includes the backtrace library for better crashlogs. # __compile_backtrace__=1 -# Set __compile_backtrace__ to 1 to compile the backtrace library instead of using system libraries. +# Set __compile_backtrace__ to 1 to compile the backtrace library instead of using system libraries. __maria_db_connector_compile_jobs__=1 # Set to the number of jobs (make -j equivalent) to compile the mariadbconn files with. diff --git a/README.md b/README.md index de20e7ad..dfae2bab 100644 --- a/README.md +++ b/README.md @@ -204,15 +204,16 @@ certutil -hashfile <file> SHA256 Darkflame Universe utilizes a MySQL/MariaDB database for account and character information. Initial setup can vary drastically based on which operating system or distribution you are running; there are instructions out there for most setups, follow those and come back here when you have a database up and running. -* Create a database for Darkflame Universe to use + +* All that you need to do is create a database to connect to. As long as the server can connect to the database, the schema will always be kept up to date when you start the server. #### Configuration After the server has been built there should be four `ini` files in the build director: `authconfig.ini`, `chatconfig.ini`, `masterconfig.ini`, and `worldconfig.ini`. Go through them and fill in the database credentials and configure other settings if necessary. -#### Setup and Migrations +#### Migrations -Use the command `./MasterServer -m` to setup the tables in the database. The first time this command is run on a database, the tables will be up to date with the most recent version. To update your database tables, run this command again. Multiple invocations will not affect any functionality. +The database is automatically setup and migrated to what it should look like for the latest commit whenever you start the server. #### Verify diff --git a/dCommon/BrickByBrickFix.cpp b/dCommon/BrickByBrickFix.cpp new file mode 100644 index 00000000..f0c4e824 --- /dev/null +++ b/dCommon/BrickByBrickFix.cpp @@ -0,0 +1,180 @@ +#include "BrickByBrickFix.h" + +#include <memory> +#include <iostream> +#include <sstream> + +#include "tinyxml2.h" + +#include "Database.h" +#include "Game.h" +#include "ZCompression.h" +#include "dLogger.h" + +//! Forward declarations + +std::unique_ptr<sql::ResultSet> GetModelsFromDatabase(); +void WriteSd0Magic(char* input, uint32_t chunkSize); +bool CheckSd0Magic(sql::Blob* streamToCheck); + +/** + * @brief Truncates all models with broken data from the database. + * + * @return The number of models deleted + */ +uint32_t BrickByBrickFix::TruncateBrokenBrickByBrickXml() { + uint32_t modelsTruncated{}; + auto modelsToTruncate = GetModelsFromDatabase(); + bool previousCommitValue = Database::GetAutoCommit(); + Database::SetAutoCommit(false); + while (modelsToTruncate->next()) { + std::unique_ptr<sql::PreparedStatement> ugcModelToDelete(Database::CreatePreppedStmt("DELETE FROM ugc WHERE ugc.id = ?;")); + std::unique_ptr<sql::PreparedStatement> pcModelToDelete(Database::CreatePreppedStmt("DELETE FROM properties_contents WHERE ugc_id = ?;")); + std::string completeUncompressedModel{}; + uint32_t chunkCount{}; + uint64_t modelId = modelsToTruncate->getInt(1); + std::unique_ptr<sql::Blob> modelAsSd0(modelsToTruncate->getBlob(2)); + // Check that header is sd0 by checking for the sd0 magic. + if (CheckSd0Magic(modelAsSd0.get())) { + while (true) { + uint32_t chunkSize{}; + modelAsSd0->read(reinterpret_cast<char*>(&chunkSize), sizeof(uint32_t)); // Extract chunk size from istream + + // Check if good here since if at the end of an sd0 file, this will have eof flagged. + if (!modelAsSd0->good()) break; + + std::unique_ptr<uint8_t[]> compressedChunk(new uint8_t[chunkSize]); + for (uint32_t i = 0; i < chunkSize; i++) { + compressedChunk[i] = modelAsSd0->get(); + } + + // Ignore the valgrind warning about uninitialized values. These are discarded later when we know the actual uncompressed size. + std::unique_ptr<uint8_t[]> uncompressedChunk(new uint8_t[MAX_SD0_CHUNK_SIZE]); + int32_t err{}; + int32_t actualUncompressedSize = ZCompression::Decompress( + compressedChunk.get(), chunkSize, uncompressedChunk.get(), MAX_SD0_CHUNK_SIZE, err); + + if (actualUncompressedSize != -1) { + uint32_t previousSize = completeUncompressedModel.size(); + completeUncompressedModel.append((char*)uncompressedChunk.get()); + completeUncompressedModel.resize(previousSize + actualUncompressedSize); + } else { + Game::logger->Log("BrickByBrickFix", "Failed to inflate chunk %i for model %llu. Error: %i", chunkCount, modelId, err); + break; + } + chunkCount++; + } + std::unique_ptr<tinyxml2::XMLDocument> document = std::make_unique<tinyxml2::XMLDocument>(); + if (!document) { + Game::logger->Log("BrickByBrickFix", "Failed to initialize tinyxml document. Aborting."); + return 0; + } + + if (!(document->Parse(completeUncompressedModel.c_str(), completeUncompressedModel.size()) == tinyxml2::XML_SUCCESS)) { + if (completeUncompressedModel.find( + "</LXFML>", + completeUncompressedModel.length() >= 15 ? completeUncompressedModel.length() - 15 : 0) == std::string::npos + ) { + Game::logger->Log("BrickByBrickFix", + "Brick-by-brick model %llu will be deleted!", modelId); + ugcModelToDelete->setInt64(1, modelsToTruncate->getInt64(1)); + pcModelToDelete->setInt64(1, modelsToTruncate->getInt64(1)); + ugcModelToDelete->execute(); + pcModelToDelete->execute(); + modelsTruncated++; + } + } + } else { + Game::logger->Log("BrickByBrickFix", + "Brick-by-brick model %llu will be deleted!", modelId); + ugcModelToDelete->setInt64(1, modelsToTruncate->getInt64(1)); + pcModelToDelete->setInt64(1, modelsToTruncate->getInt64(1)); + ugcModelToDelete->execute(); + pcModelToDelete->execute(); + modelsTruncated++; + } + } + + Database::Commit(); + Database::SetAutoCommit(previousCommitValue); + return modelsTruncated; +} + +/** + * @brief Updates all current models in the database to have the Segmented Data 0 (SD0) format. + * Any models that do not start with zlib and best compression magic will not be updated. + * + * @return The number of models updated to SD0 + */ +uint32_t BrickByBrickFix::UpdateBrickByBrickModelsToSd0() { + uint32_t updatedModels = 0; + auto modelsToUpdate = GetModelsFromDatabase(); + auto previousAutoCommitState = Database::GetAutoCommit(); + Database::SetAutoCommit(false); + std::unique_ptr<sql::PreparedStatement> insertionStatement(Database::CreatePreppedStmt("UPDATE ugc SET lxfml = ? WHERE id = ?;")); + while (modelsToUpdate->next()) { + int64_t modelId = modelsToUpdate->getInt64(1); + std::unique_ptr<sql::Blob> oldLxfml(modelsToUpdate->getBlob(2)); + // Check if the stored blob starts with zlib magic (0x78 0xDA - best compression of zlib) + // If it does, convert it to sd0. + if (oldLxfml->get() == 0x78 && oldLxfml->get() == 0xDA) { + + // Get and save size of zlib compressed chunk. + oldLxfml->seekg(0, std::ios::end); + uint32_t oldLxfmlSize = static_cast<uint32_t>(oldLxfml->tellg()); + oldLxfml->seekg(0); + + // Allocate 9 extra bytes. 5 for sd0 magic, 4 for the only zlib compressed size. + uint32_t oldLxfmlSizeWithHeader = oldLxfmlSize + 9; + std::unique_ptr<char[]> sd0ConvertedModel(new char[oldLxfmlSizeWithHeader]); + + WriteSd0Magic(sd0ConvertedModel.get(), oldLxfmlSize); + for (uint32_t i = 9; i < oldLxfmlSizeWithHeader; i++) { + sd0ConvertedModel.get()[i] = oldLxfml->get(); + } + + std::string outputString(sd0ConvertedModel.get(), oldLxfmlSizeWithHeader); + std::istringstream outputStringStream(outputString); + + insertionStatement->setBlob(1, static_cast<std::istream*>(&outputStringStream)); + insertionStatement->setInt64(2, modelId); + try { + insertionStatement->executeUpdate(); + Game::logger->Log("BrickByBrickFix", "Updated model %i to sd0", modelId); + updatedModels++; + } catch (sql::SQLException exception) { + Game::logger->Log( + "BrickByBrickFix", + "Failed to update model %i. This model should be inspected manually to see why." + "The database error is %s", modelId, exception.what()); + } + } + } + Database::Commit(); + Database::SetAutoCommit(previousAutoCommitState); + return updatedModels; +} + +std::unique_ptr<sql::ResultSet> GetModelsFromDatabase() { + std::unique_ptr<sql::PreparedStatement> modelsRawDataQuery(Database::CreatePreppedStmt("SELECT id, lxfml FROM ugc;")); + return std::unique_ptr<sql::ResultSet>(modelsRawDataQuery->executeQuery()); +} + +/** + * @brief Writes sd0 magic at the front of a char* + * + * @param input the char* to write at the front of + * @param chunkSize The size of the first chunk to write the size of + */ +void WriteSd0Magic(char* input, uint32_t chunkSize) { + input[0] = 's'; + input[1] = 'd'; + input[2] = '0'; + input[3] = 0x01; + input[4] = 0xFF; + *reinterpret_cast<uint32_t*>(input + 5) = chunkSize; // Write the integer to the character array +} + +bool CheckSd0Magic(sql::Blob* streamToCheck) { + return streamToCheck->get() == 's' && streamToCheck->get() == 'd' && streamToCheck->get() == '0' && streamToCheck->get() == 0x01 && streamToCheck->get() == 0xFF; +} diff --git a/dCommon/BrickByBrickFix.h b/dCommon/BrickByBrickFix.h new file mode 100644 index 00000000..0c7e314c --- /dev/null +++ b/dCommon/BrickByBrickFix.h @@ -0,0 +1,26 @@ +#pragma once + +#include <cstdint> + +namespace BrickByBrickFix { + /** + * @brief Deletes all broken BrickByBrick models that have invalid XML + * + * @return The number of BrickByBrick models that were truncated + */ + uint32_t TruncateBrokenBrickByBrickXml(); + + /** + * @brief Updates all BrickByBrick models in the database to be + * in the sd0 format as opposed to a zlib compressed format. + * + * @return The number of BrickByBrick models that were updated + */ + uint32_t UpdateBrickByBrickModelsToSd0(); + + /** + * @brief Max size of an inflated sd0 zlib chunk + * + */ + constexpr uint32_t MAX_SD0_CHUNK_SIZE = 1024 * 256; +}; diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 18fe582c..cb73bf6a 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -13,13 +13,15 @@ set(DCOMMON_SOURCES "AMFFormat.cpp" "NiQuaternion.cpp" "SHA512.cpp" "Type.cpp" - "ZCompression.cpp") + "ZCompression.cpp" + "BrickByBrickFix.cpp" +) include_directories(${PROJECT_SOURCE_DIR}/dCommon/) add_library(dCommon STATIC ${DCOMMON_SOURCES}) -target_link_libraries(dCommon bcrypt) +target_link_libraries(dCommon bcrypt dDatabase tinyxml2) if (UNIX) find_package(ZLIB REQUIRED) diff --git a/dDatabase/Database.cpp b/dDatabase/Database.cpp index f955bd43..c301cbd9 100644 --- a/dDatabase/Database.cpp +++ b/dDatabase/Database.cpp @@ -83,3 +83,15 @@ sql::PreparedStatement* Database::CreatePreppedStmt(const std::string& query) { void Database::Commit() { Database::con->commit(); } + +bool Database::GetAutoCommit() { + // TODO This should not just access a pointer. A future PR should update this + // to check for null and throw an error if the connection is not valid. + return con->getAutoCommit(); +} + +void Database::SetAutoCommit(bool value) { + // TODO This should not just access a pointer. A future PR should update this + // to check for null and throw an error if the connection is not valid. + Database::con->setAutoCommit(value); +} diff --git a/dDatabase/Database.h b/dDatabase/Database.h index a15ba856..f4d13da3 100644 --- a/dDatabase/Database.h +++ b/dDatabase/Database.h @@ -23,6 +23,8 @@ public: static sql::Statement* CreateStmt(); static sql::PreparedStatement* CreatePreppedStmt(const std::string& query); static void Commit(); + static bool GetAutoCommit(); + static void SetAutoCommit(bool value); static std::string GetDatabase() { return database; } static sql::Properties GetProperties() { return props; } diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index 30a63896..1eb03887 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -1,5 +1,6 @@ #include "MigrationRunner.h" +#include "BrickByBrickFix.h" #include "GeneralUtils.h" #include <fstream> @@ -7,13 +8,13 @@ #include <thread> void MigrationRunner::RunMigrations() { - auto stmt = Database::CreatePreppedStmt("CREATE TABLE IF NOT EXISTS migration_history (name TEXT NOT NULL, date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP());"); - stmt->executeQuery(); + auto* stmt = Database::CreatePreppedStmt("CREATE TABLE IF NOT EXISTS migration_history (name TEXT NOT NULL, date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP());"); + stmt->execute(); delete stmt; sql::SQLString finalSQL = ""; Migration checkMigration{}; - + bool runSd0Migrations = false; for (const auto& entry : GeneralUtils::GetFileNamesFromFolder("./migrations/")) { auto migration = LoadMigration(entry); @@ -25,16 +26,18 @@ void MigrationRunner::RunMigrations() { stmt = Database::CreatePreppedStmt("SELECT name FROM migration_history WHERE name = ?;"); stmt->setString(1, migration.name); - auto res = stmt->executeQuery(); + auto* res = stmt->executeQuery(); bool doExit = res->next(); delete res; delete stmt; if (doExit) continue; Game::logger->Log("MigrationRunner", "Running migration: %s", migration.name.c_str()); - - finalSQL.append(migration.data); - finalSQL.append('\n'); + if (migration.name == "5_brick_model_sd0.sql") { + runSd0Migrations = true; + } else { + finalSQL.append(migration.data); + } stmt = Database::CreatePreppedStmt("INSERT INTO migration_history (name) VALUES (?);"); stmt->setString(1, entry); @@ -42,15 +45,31 @@ void MigrationRunner::RunMigrations() { delete stmt; } + if (finalSQL.empty() && !runSd0Migrations) { + Game::logger->Log("MigrationRunner", "Server database is up to date."); + return; + } + if (!finalSQL.empty()) { - try { - auto simpleStatement = Database::CreateStmt(); - simpleStatement->execute(finalSQL); - delete simpleStatement; - } catch (sql::SQLException e) { - Game::logger->Log("MigrationRunner", "Encountered error running migration: %s", e.what()); + auto migration = GeneralUtils::SplitString(static_cast<std::string>(finalSQL), ';'); + std::unique_ptr<sql::Statement> simpleStatement(Database::CreateStmt()); + for (auto& query : migration) { + try { + if (query.empty()) continue; + simpleStatement->execute(query); + } catch (sql::SQLException& e) { + Game::logger->Log("MigrationRunner", "Encountered error running migration: %s", e.what()); + } } } + + // Do this last on the off chance none of the other migrations have been run yet. + if (runSd0Migrations) { + uint32_t numberOfUpdatedModels = BrickByBrickFix::UpdateBrickByBrickModelsToSd0(); + Game::logger->Log("MasterServer", "%i models were updated from zlib to sd0.", numberOfUpdatedModels); + uint32_t numberOfTruncatedModels = BrickByBrickFix::TruncateBrokenBrickByBrickXml(); + Game::logger->Log("MasterServer", "%i models were truncated from the database.", numberOfTruncatedModels); + } } Migration MigrationRunner::LoadMigration(std::string path) { @@ -58,8 +77,6 @@ Migration MigrationRunner::LoadMigration(std::string path) { std::ifstream file("./migrations/" + path); if (file.is_open()) { - std::hash<std::string> hash; - std::string line; std::string total = ""; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 772cb691..48b2a508 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -2401,63 +2401,25 @@ void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* e } void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - /* - ___ ___ - /\ /\___ _ __ ___ / __\ ___ / \_ __ __ _ __ _ ___ _ __ ___ - / /_/ / _ \ '__/ _ \ /__\/// _ \ / /\ / '__/ _` |/ _` |/ _ \| '_ \/ __| - / __ / __/ | | __/ / \/ \ __/ / /_//| | | (_| | (_| | (_) | | | \__ \ - \/ /_/ \___|_| \___| \_____/\___| /___,' |_| \__,_|\__, |\___/|_| |_|___/ - |___/ - ___ _ - / __\ _____ ____ _ _ __ ___ / \ - /__\/// _ \ \ /\ / / _` | '__/ _ \/ / - / \/ \ __/\ V V / (_| | | | __/\_/ - \_____/\___| \_/\_/ \__,_|_| \___\/ - - <>=======() - (/\___ /|\\ ()==========<>_ - \_/ | \\ //|\ ______/ \) - \_| \\ // | \_/ - \|\/|\_ // /\/ - (oo)\ \_// / - //_/\_\/ / | - @@/ |=\ \ | - \_=\_ \ | - \==\ \|\_ snd - __(\===\( )\ - (((~) __(_/ | - (((~) \ / - ______/ / - '------' - */ - - //First, we have Wincent's clean methods of reading in the data received from the client. LWOOBJID localId; - uint32_t timeTaken; inStream->Read(localId); - uint32_t ld0Size; - inStream->Read(ld0Size); - for (auto i = 0; i < 5; ++i) { - uint8_t c; - inStream->Read(c); - } + uint32_t sd0Size; + inStream->Read(sd0Size); + std::shared_ptr<char[]> sd0Data(new char[sd0Size]); - uint32_t lxfmlSize; - inStream->Read(lxfmlSize); - uint8_t* inData = static_cast<uint8_t*>(std::malloc(lxfmlSize)); - - if (inData == nullptr) { + if (sd0Data == nullptr) { return; } - for (uint32_t i = 0; i < lxfmlSize; ++i) { + for (uint32_t i = 0; i < sd0Size; ++i) { uint8_t c; inStream->Read(c); - inData[i] = c; + sd0Data[i] = c; } + uint32_t timeTaken; inStream->Read(timeTaken); /* @@ -2469,6 +2431,8 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent Note, in the live client it'll still display the bricks going out as they're being used, but on relog/world change, they reappear as we didn't take them. + + TODO Apparently the bricks are supposed to be taken via MoveInventoryBatch? */ ////Decompress the SD0 from the client so we can process the lxfml properly @@ -2513,9 +2477,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent auto result = query.execQuery(); - if (result.eof() || result.fieldIsNull(0)) { - return; - } + if (result.eof() || result.fieldIsNull(0)) return; int templateId = result.getIntField(0); @@ -2533,6 +2495,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent propertyId = propertyEntry->getUInt64(1); } + delete propertyEntry; delete propertyLookup; //Insert into ugc: @@ -2543,7 +2506,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent ugcs->setInt(4, 0); //whacky stream biz - std::string s((char*)inData, lxfmlSize); + std::string s(sd0Data.get(), sd0Size); std::istringstream iss(s); std::istream& stream = iss; @@ -2558,14 +2521,14 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent stmt->setUInt64(1, newIDL); stmt->setUInt64(2, propertyId); stmt->setUInt(3, blueprintIDSmall); - stmt->setUInt(4, 14); //14 is the lot the BBB models use - stmt->setDouble(5, 0.0f); //x - stmt->setDouble(6, 0.0f); //y - stmt->setDouble(7, 0.0f); //z - stmt->setDouble(8, 0.0f); - stmt->setDouble(9, 0.0f); - stmt->setDouble(10, 0.0f); - stmt->setDouble(11, 0.0f); + stmt->setUInt(4, 14); // 14 is the lot the BBB models use + stmt->setDouble(5, 0.0f); // x + stmt->setDouble(6, 0.0f); // y + stmt->setDouble(7, 0.0f); // z + stmt->setDouble(8, 0.0f); // rx + stmt->setDouble(9, 0.0f); // ry + stmt->setDouble(10, 0.0f); // rz + stmt->setDouble(11, 0.0f); // rw stmt->execute(); delete stmt; @@ -2591,38 +2554,22 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //Tell the client their model is saved: (this causes us to actually pop out of our current state): CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); + PacketUtils::WriteHeader(bitStream, CLIENT, CLIENT::MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); bitStream.Write(localId); bitStream.Write<unsigned int>(0); bitStream.Write<unsigned int>(1); bitStream.Write(blueprintID); - bitStream.Write(lxfmlSize + 9); + bitStream.Write<uint32_t>(sd0Size); - //Write a fake sd0 header: - bitStream.Write<unsigned char>(0x73); //s - bitStream.Write<unsigned char>(0x64); //d - bitStream.Write<unsigned char>(0x30); //0 - bitStream.Write<unsigned char>(0x01); //1 - bitStream.Write<unsigned char>(0xFF); //end magic - - bitStream.Write(lxfmlSize); - - for (size_t i = 0; i < lxfmlSize; ++i) - bitStream.Write(inData[i]); + for (size_t i = 0; i < sd0Size; ++i) { + bitStream.Write(sd0Data[i]); + } SEND_PACKET; - PacketUtils::SavePacket("MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE.bin", (char*)bitStream.GetData(), bitStream.GetNumberOfBytesUsed()); + // PacketUtils::SavePacket("MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE.bin", (char*)bitStream.GetData(), bitStream.GetNumberOfBytesUsed()); //Now we have to construct this object: - /* - * This needs to be sent as config data, but I don't know how to right now. - 'blueprintid': (9, 1152921508346399522), - 'componentWhitelist': (1, 1), - 'modelType': (1, 2), - 'propertyObjectID': (7, True), - 'userModelID': (9, 1152921510759098799) - */ EntityInfo info; info.lot = 14; @@ -2653,6 +2600,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //there was an issue with builds not appearing since it was placed above ConstructEntity. PropertyManagementComponent::Instance()->AddModel(newEntity->GetObjectID(), newIDL); } + }); }); }); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index a692e826..538fb749 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -85,71 +85,51 @@ int main(int argc, char** argv) { Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); - if (argc > 1 && (strcmp(argv[1], "-m") == 0 || strcmp(argv[1], "--migrations") == 0)) { - //Connect to the MySQL Database - std::string mysql_host = config.GetValue("mysql_host"); - std::string mysql_database = config.GetValue("mysql_database"); - std::string mysql_username = config.GetValue("mysql_username"); - std::string mysql_password = config.GetValue("mysql_password"); + //Connect to the MySQL Database + std::string mysql_host = config.GetValue("mysql_host"); + std::string mysql_database = config.GetValue("mysql_database"); + std::string mysql_username = config.GetValue("mysql_username"); + std::string mysql_password = config.GetValue("mysql_password"); - try { - Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); - } catch (sql::SQLException& ex) { - Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s", ex.what()); - Game::logger->Log("MigrationRunner", "Migrations not run"); - return EXIT_FAILURE; - } - - MigrationRunner::RunMigrations(); - Game::logger->Log("MigrationRunner", "Finished running migrations"); - - return EXIT_SUCCESS; - } else { - - //Check CDClient exists - const std::string cdclient_path = "./res/CDServer.sqlite"; - std::ifstream cdclient_fd(cdclient_path); - if (!cdclient_fd.good()) { - Game::logger->Log("WorldServer", "%s could not be opened", cdclient_path.c_str()); - return EXIT_FAILURE; - } - cdclient_fd.close(); - - //Connect to CDClient - try { - CDClientDatabase::Connect(cdclient_path); - } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); - Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); - return EXIT_FAILURE; - } - - //Get CDClient initial information - try { - CDClientManager::Instance()->Initialize(); - } catch (CppSQLite3Exception& e) { - Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database"); - Game::logger->Log("WorldServer", "May be caused by corrupted file: %s", cdclient_path.c_str()); - Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); - Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); - return EXIT_FAILURE; - } - - //Connect to the MySQL Database - std::string mysql_host = config.GetValue("mysql_host"); - std::string mysql_database = config.GetValue("mysql_database"); - std::string mysql_username = config.GetValue("mysql_username"); - std::string mysql_password = config.GetValue("mysql_password"); - - try { - Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); - } catch (sql::SQLException& ex) { - Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s", ex.what()); - return EXIT_FAILURE; - } + try { + Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); + } catch (sql::SQLException& ex) { + Game::logger->Log("MasterServer", "Got an error while connecting to the database: %s", ex.what()); + Game::logger->Log("MigrationRunner", "Migrations not run"); + return EXIT_FAILURE; } + MigrationRunner::RunMigrations(); + + //Check CDClient exists + const std::string cdclient_path = "./res/CDServer.sqlite"; + std::ifstream cdclient_fd(cdclient_path); + if (!cdclient_fd.good()) { + Game::logger->Log("WorldServer", "%s could not be opened", cdclient_path.c_str()); + return EXIT_FAILURE; + } + cdclient_fd.close(); + + //Connect to CDClient + try { + CDClientDatabase::Connect(cdclient_path); + } catch (CppSQLite3Exception& e) { + Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); + Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); + Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); + return EXIT_FAILURE; + } + + //Get CDClient initial information + try { + CDClientManager::Instance()->Initialize(); + } catch (CppSQLite3Exception& e) { + Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database"); + Game::logger->Log("WorldServer", "May be caused by corrupted file: %s", cdclient_path.c_str()); + Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); + Game::logger->Log("WorldServer", "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. @@ -825,9 +805,9 @@ void ShutdownSequence() { int FinalizeShutdown() { //Delete our objects here: Database::Destroy("MasterServer"); - delete Game::im; - delete Game::server; - delete Game::logger; + if (Game::im) delete Game::im; + if (Game::server) delete Game::server; + if (Game::logger) delete Game::logger; exit(EXIT_SUCCESS); return EXIT_SUCCESS; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 495053fa..89243d59 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -1069,15 +1069,6 @@ void HandlePacket(Packet* packet) { bitStream.Write<unsigned int>(1); bitStream.Write(blueprintID); - bitStream.Write<uint32_t>(lxfmlSize + 9); - - //Write a fake sd0 header: - bitStream.Write<unsigned char>(0x73); //s - bitStream.Write<unsigned char>(0x64); //d - bitStream.Write<unsigned char>(0x30); //0 - bitStream.Write<unsigned char>(0x01); //1 - bitStream.Write<unsigned char>(0xFF); //end magic - bitStream.Write<uint32_t>(lxfmlSize); for (size_t i = 0; i < lxfmlSize; ++i) diff --git a/migrations/dlu/5_brick_model_sd0.sql b/migrations/dlu/5_brick_model_sd0.sql new file mode 100644 index 00000000..895f8b34 --- /dev/null +++ b/migrations/dlu/5_brick_model_sd0.sql @@ -0,0 +1 @@ +# This file is here as a mock. The real migration is located in BrickByBrickFix.cpp From 2bdbf129cf6b801d4e95892103b83778d3bcd91b Mon Sep 17 00:00:00 2001 From: Demetri Van Sickle <demetriv.s.7@gmail.com> Date: Tue, 25 Oct 2022 13:32:46 -0700 Subject: [PATCH 106/322] removed migration runner from build script (#788) --- build.sh | 2 -- 1 file changed, 2 deletions(-) diff --git a/build.sh b/build.sh index e61c1cb4..4a476cc1 100755 --- a/build.sh +++ b/build.sh @@ -8,5 +8,3 @@ cmake .. # To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `cmake --build . --config Release -j8' cmake --build . --config Release -# Run migrations -./MasterServer -m From d8e73def9dad6b130de9dec2c09fbdfa7b356d37 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 29 Oct 2022 01:12:29 -0700 Subject: [PATCH 107/322] Update GameMessages.cpp (#793) --- dGame/dGameMessages/GameMessages.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 48b2a508..4efbd286 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -2401,6 +2401,34 @@ void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* e } void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + /* + ___ ___ + /\ /\___ _ __ ___ / __\ ___ / \_ __ __ _ __ _ ___ _ __ ___ + / /_/ / _ \ '__/ _ \ /__\/// _ \ / /\ / '__/ _` |/ _` |/ _ \| '_ \/ __| + / __ / __/ | | __/ / \/ \ __/ / /_//| | | (_| | (_| | (_) | | | \__ \ + \/ /_/ \___|_| \___| \_____/\___| /___,' |_| \__,_|\__, |\___/|_| |_|___/ + |___/ + ___ _ + / __\ _____ ____ _ _ __ ___ / \ + /__\/// _ \ \ /\ / / _` | '__/ _ \/ / + / \/ \ __/\ V V / (_| | | | __/\_/ + \_____/\___| \_/\_/ \__,_|_| \___\/ + <>=======() + (/\___ /|\\ ()==========<>_ + \_/ | \\ //|\ ______/ \) + \_| \\ // | \_/ + \|\/|\_ // /\/ + (oo)\ \_// / + //_/\_\/ / | + @@/ |=\ \ | + \_=\_ \ | + \==\ \|\_ snd + __(\===\( )\ + (((~) __(_/ | + (((~) \ / + ______/ / + '------' + */ LWOOBJID localId; inStream->Read(localId); From a745cdb727c67c8a8fd27d1779adad68d68197b0 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Sun, 30 Oct 2022 00:17:35 +0100 Subject: [PATCH 108/322] Implement a shared config between servers (#795) * Implement a shared config between servers * Auto move config file on CMake run --- CMakeLists.txt | 2 +- README.md | 2 +- dCommon/dConfig.cpp | 15 +++++++++++++++ resources/authconfig.ini | 21 --------------------- resources/chatconfig.ini | 24 ------------------------ resources/masterconfig.ini | 21 --------------------- resources/sharedconfig.ini | 23 +++++++++++++++++++++++ resources/worldconfig.ini | 23 +---------------------- 8 files changed, 41 insertions(+), 90 deletions(-) create mode 100644 resources/sharedconfig.ini diff --git a/CMakeLists.txt b/CMakeLists.txt index 721140a6..8a4c5140 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -90,7 +90,7 @@ make_directory(${CMAKE_BINARY_DIR}/locale) make_directory(${CMAKE_BINARY_DIR}/logs) # Copy resource files on first build -set(RESOURCE_FILES "authconfig.ini" "chatconfig.ini" "worldconfig.ini" "masterconfig.ini" "blacklist.dcf") +set(RESOURCE_FILES "sharedconfig.ini" "authconfig.ini" "chatconfig.ini" "worldconfig.ini" "masterconfig.ini" "blacklist.dcf") foreach(resource_file ${RESOURCE_FILES}) if (NOT EXISTS ${PROJECT_BINARY_DIR}/${resource_file}) configure_file( diff --git a/README.md b/README.md index dfae2bab..cdb1d343 100644 --- a/README.md +++ b/README.md @@ -209,7 +209,7 @@ Initial setup can vary drastically based on which operating system or distributi #### Configuration -After the server has been built there should be four `ini` files in the build director: `authconfig.ini`, `chatconfig.ini`, `masterconfig.ini`, and `worldconfig.ini`. Go through them and fill in the database credentials and configure other settings if necessary. +After the server has been built there should be four `ini` files in the build director: `sharedconfig.ini`, `authconfig.ini`, `chatconfig.ini`, `masterconfig.ini`, and `worldconfig.ini`. Go through them and fill in the database credentials and configure other settings if necessary. #### Migrations diff --git a/dCommon/dConfig.cpp b/dCommon/dConfig.cpp index 9750238a..c22c91cc 100644 --- a/dCommon/dConfig.cpp +++ b/dCommon/dConfig.cpp @@ -12,6 +12,15 @@ dConfig::dConfig(const std::string& filepath) { if (line[0] != '#') ProcessLine(line); } } + + std::ifstream sharedConfig("sharedconfig.ini", std::ios::in); + if (!sharedConfig.good()) return; + + while (std::getline(sharedConfig, line)) { + if (line.length() > 0) { + if (line[0] != '#') ProcessLine(line); + } + } } dConfig::~dConfig(void) { @@ -40,6 +49,12 @@ void dConfig::ProcessLine(const std::string& line) { if (!seglist[1].empty() && seglist[1][seglist[1].size() - 1] == '\r') seglist[1].erase(seglist[1].size() - 1); + for (const auto& key : m_Keys) { + if (seglist[0] == key) { + return; // first loaded key is preferred due to loading shared config secondarily + } + } + m_Keys.push_back(seglist[0]); m_Values.push_back(seglist[1]); } diff --git a/resources/authconfig.ini b/resources/authconfig.ini index 40ca146e..ec414bc0 100644 --- a/resources/authconfig.ini +++ b/resources/authconfig.ini @@ -1,27 +1,6 @@ -# MySQL connection info: -mysql_host= -mysql_database= -mysql_username= -mysql_password= - -# The public facing IP address. Can be 'localhost' for locally hosted servers -external_ip=localhost - # Port number. The client has the authserver port hardcoded to 1001 port=1001 -# Where to put crashlogs -dump_folder= - -# How many clients can be connected to the server at once -max_clients=999 - -# 0 or 1, should log to console -log_to_console=1 - -# 0 or 1, should log debug (developer only) statements to console for debugging, not needed for normal operation -log_debug_statements=0 - # 0 or 1, should ignore playkeys # If 1 everyone with an account will be able to login, regardless of if they have a key or not dont_use_keys=0 diff --git a/resources/chatconfig.ini b/resources/chatconfig.ini index f30fb8f9..26b26cc7 100644 --- a/resources/chatconfig.ini +++ b/resources/chatconfig.ini @@ -1,26 +1,2 @@ -# MySQL connection info: -mysql_host= -mysql_database= -mysql_username= -mysql_password= - -# The public facing IP address. Can be 'localhost' for locally hosted servers -external_ip=localhost - # Port number port=2005 - -# Where to put crashlogs -dump_folder= - -# How many clients can be connected to the server at once -max_clients=999 - -# 0 or 1, should log to console -log_to_console=1 - -# 0 or 1, should log debug (developer only) statements to console for debugging, not needed for normal operation -log_debug_statements=0 - -# 0 or 1, should not compile chat hash map to file -dont_generate_dcf=0 diff --git a/resources/masterconfig.ini b/resources/masterconfig.ini index c2d884a5..4864d8cb 100644 --- a/resources/masterconfig.ini +++ b/resources/masterconfig.ini @@ -1,12 +1,3 @@ -# MySQL connection info: -mysql_host= -mysql_database= -mysql_username= -mysql_password= - -# The public facing IP address. Can be 'localhost' for locally hosted servers -external_ip=localhost - # The internal ip of the master server master_ip=localhost @@ -26,17 +17,5 @@ use_sudo_chat=0 # Use sudo when launching world servers use_sudo_world=0 -# Where to put crashlogs -dump_folder= - -# How many clients can be connected to the server at once -max_clients=999 - -# 0 or 1, should log to console -log_to_console=1 - -# 0 or 1, should log debug (developer only) statements to console for debugging, not needed for normal operation -log_debug_statements=0 - # 0 or 1, should autostart auth, chat, and char servers prestart_servers=1 diff --git a/resources/sharedconfig.ini b/resources/sharedconfig.ini new file mode 100644 index 00000000..1a377d28 --- /dev/null +++ b/resources/sharedconfig.ini @@ -0,0 +1,23 @@ +# MySQL connection info: +mysql_host= +mysql_database= +mysql_username= +mysql_password= + +# 0 or 1, should log to console +log_to_console=1 + +# 0 or 1, should log debug (developer only) statements to console for debugging, not needed for normal operation +log_debug_statements=0 + +# The public facing IP address. Can be 'localhost' for locally hosted servers +external_ip=localhost + +# 0 or 1, should not compile chat hash map to file +dont_generate_dcf=0 + +# How many clients can be connected to the server at once +max_clients=999 + +# Where to put crashlogs +dump_folder= diff --git a/resources/worldconfig.ini b/resources/worldconfig.ini index 931da28c..ee6b6651 100644 --- a/resources/worldconfig.ini +++ b/resources/worldconfig.ini @@ -1,9 +1,3 @@ -# MySQL connection info: -mysql_host= -mysql_database= -mysql_username= -mysql_password= - # URL to the code repository for the hosted server # If you fork this repository and/or make changes to the code, reflect that here to comply with AGPLv3 source=https://github.com/DarkflameUniverse/DarkflameServer @@ -11,21 +5,6 @@ source=https://github.com/DarkflameUniverse/DarkflameServer # Port to the chat server, same as in chatconfig.ini chat_server_port=2005 -# Where to put crashlogs -dump_folder= - -# How many clients can be connected to the server at once -max_clients=999 - -# 0 or 1, should log to console -log_to_console=1 - -# 0 or 1, should log debug (developer only) statements to console for debugging, not needed for normal operation -log_debug_statements=0 - -# 0 or 1, should not compile chat hash map to file -dont_generate_dcf=0 - # 0 or 1, should disable chat disable_chat=0 @@ -63,4 +42,4 @@ pets_take_imagination=1 # If you would like to increase the maximum number of best friends a player can have on the server # Change the value below to what you would like this to be (5 is live accurate) -max_number_of_best_friends=5 \ No newline at end of file +max_number_of_best_friends=5 From 906887bda9d2f0d0b115ba07b10bc27b3a1e6863 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 30 Oct 2022 00:38:43 -0700 Subject: [PATCH 109/322] Add automatic cdclient migration runner support and setup (#789) * Add automatic migrations for CDServer Add support to automatically migrate and update CDServers with new migrations. Also adds support to simplify the setup process by simply putting the fdb in the res folder and letting the server convert it to sqlite. This reduces the amount of back and forth when setting up a server. * Remove transaction language * Add DML execution `poggers` Add a way to execute DML commands through the sqlite connection on the server. * Make DML Commands more robust On the off chance the server is shutdown before the whole migration is run, lets just not add it to our "finished list" until the whole file is done. * Update README --- CMakeLists.txt | 18 +++++- README.md | 9 +-- dDatabase/CDClientDatabase.cpp | 5 ++ dDatabase/CDClientDatabase.h | 8 +++ dDatabase/MigrationRunner.cpp | 84 +++++++++++++++++++-------- dDatabase/MigrationRunner.h | 14 ++--- dMasterServer/MasterServer.cpp | 33 ++++++++++- migrations/cdserver/0_nt_footrace.sql | 4 -- 8 files changed, 127 insertions(+), 48 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8a4c5140..b147b200 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -108,13 +108,25 @@ foreach(file ${VANITY_FILES}) endforeach() # Move our migrations for MasterServer to run -file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/migrations/) +file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/migrations/dlu/) file(GLOB SQL_FILES ${CMAKE_SOURCE_DIR}/migrations/dlu/*.sql) foreach(file ${SQL_FILES}) get_filename_component(file ${file} NAME) - if (NOT EXISTS ${PROJECT_BINARY_DIR}/migrations/${file}) + if (NOT EXISTS ${PROJECT_BINARY_DIR}/migrations/dlu/${file}) configure_file( - ${CMAKE_SOURCE_DIR}/migrations/dlu/${file} ${PROJECT_BINARY_DIR}/migrations/${file} + ${CMAKE_SOURCE_DIR}/migrations/dlu/${file} ${PROJECT_BINARY_DIR}/migrations/dlu/${file} + COPYONLY + ) + endif() +endforeach() + +file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/migrations/cdserver/) +file(GLOB SQL_FILES ${CMAKE_SOURCE_DIR}/migrations/cdserver/*.sql) +foreach(file ${SQL_FILES}) + get_filename_component(file ${file} NAME) + if (NOT EXISTS ${PROJECT_BINARY_DIR}/migrations/cdserver/${file}) + configure_file( + ${CMAKE_SOURCE_DIR}/migrations/cdserver/${file} ${PROJECT_BINARY_DIR}/migrations/cdserver/${file} COPYONLY ) endif() diff --git a/README.md b/README.md index cdb1d343..8f9eaf8d 100644 --- a/README.md +++ b/README.md @@ -196,9 +196,10 @@ certutil -hashfile <file> SHA256 * Copy over or create symlinks from `locale.xml` in your client `locale` directory to the `build/locale` directory #### Client database -* Use `fdb_to_sqlite.py` in lcdr's utilities on `res/cdclient.fdb` in the unpacked client to convert the client database to `cdclient.sqlite` -* Move and rename `cdclient.sqlite` into `build/res/CDServer.sqlite` -* Run each SQL file in the order at which they appear [here](migrations/cdserver/) on the SQLite database +* Move the file `res/cdclient.fdb` from the unpacked client to the `build/res` folder on the server. +* The server will automatically copy and convert the file from fdb to sqlite should `CDServer.sqlite` not already exist. +* You can also convert the database manually using `fdb_to_sqlite.py` using lcdr's utilities. Just make sure to rename the file to `CDServer.sqlite` instead of `cdclient.sqlite`. +* Migrations to the database are automatically run on server start. When migrations are needed to be ran, the server may take a bit longer to start. ### Database Darkflame Universe utilizes a MySQL/MariaDB database for account and character information. @@ -229,7 +230,7 @@ Your build directory should now look like this: * **locale/** * locale.xml * **res/** - * CDServer.sqlite + * cdclient.fdb * chatplus_en_us.txt * **macros/** * ... diff --git a/dDatabase/CDClientDatabase.cpp b/dDatabase/CDClientDatabase.cpp index bf8485d6..4c2df1d2 100644 --- a/dDatabase/CDClientDatabase.cpp +++ b/dDatabase/CDClientDatabase.cpp @@ -14,6 +14,11 @@ CppSQLite3Query CDClientDatabase::ExecuteQuery(const std::string& query) { return conn->execQuery(query.c_str()); } +//! Updates the CDClient file with Data Manipulation Language (DML) commands. +int CDClientDatabase::ExecuteDML(const std::string& query) { + return conn->execDML(query.c_str()); +} + //! Makes prepared statements CppSQLite3Statement CDClientDatabase::CreatePreppedStmt(const std::string& query) { return conn->compileStatement(query.c_str()); diff --git a/dDatabase/CDClientDatabase.h b/dDatabase/CDClientDatabase.h index 6b254ebb..96f67d64 100644 --- a/dDatabase/CDClientDatabase.h +++ b/dDatabase/CDClientDatabase.h @@ -40,6 +40,14 @@ namespace CDClientDatabase { */ CppSQLite3Query ExecuteQuery(const std::string& query); + //! Updates the CDClient file with Data Manipulation Language (DML) commands. + /*! + \param query The DML command to run. DML command can be multiple queries in one string but only + the last one will return its number of updated rows. + \return The number of updated rows. + */ + int ExecuteDML(const std::string& query); + //! Queries the CDClient and parses arguments /*! \param query The query with formatted arguments diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index 1eb03887..017ebe32 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -1,11 +1,34 @@ #include "MigrationRunner.h" #include "BrickByBrickFix.h" +#include "CDClientDatabase.h" +#include "Database.h" +#include "Game.h" #include "GeneralUtils.h" +#include "dLogger.h" -#include <fstream> -#include <algorithm> -#include <thread> +#include <istream> + +Migration LoadMigration(std::string path) { + Migration migration{}; + std::ifstream file("./migrations/" + path); + + if (file.is_open()) { + std::string line; + std::string total = ""; + + while (std::getline(file, line)) { + total += line; + } + + file.close(); + + migration.name = path; + migration.data = total; + } + + return migration; +} void MigrationRunner::RunMigrations() { auto* stmt = Database::CreatePreppedStmt("CREATE TABLE IF NOT EXISTS migration_history (name TEXT NOT NULL, date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP());"); @@ -13,17 +36,14 @@ void MigrationRunner::RunMigrations() { delete stmt; sql::SQLString finalSQL = ""; - Migration checkMigration{}; bool runSd0Migrations = false; - for (const auto& entry : GeneralUtils::GetFileNamesFromFolder("./migrations/")) { - auto migration = LoadMigration(entry); + for (const auto& entry : GeneralUtils::GetFileNamesFromFolder("./migrations/dlu/")) { + auto migration = LoadMigration("dlu/" + entry); if (migration.data.empty()) { continue; } - checkMigration = migration; - stmt = Database::CreatePreppedStmt("SELECT name FROM migration_history WHERE name = ?;"); stmt->setString(1, migration.name); auto* res = stmt->executeQuery(); @@ -40,7 +60,7 @@ void MigrationRunner::RunMigrations() { } stmt = Database::CreatePreppedStmt("INSERT INTO migration_history (name) VALUES (?);"); - stmt->setString(1, entry); + stmt->setString(1, migration.name); stmt->execute(); delete stmt; } @@ -72,23 +92,39 @@ void MigrationRunner::RunMigrations() { } } -Migration MigrationRunner::LoadMigration(std::string path) { - Migration migration{}; - std::ifstream file("./migrations/" + path); +void MigrationRunner::RunSQLiteMigrations() { + auto* stmt = Database::CreatePreppedStmt("CREATE TABLE IF NOT EXISTS migration_history (name TEXT NOT NULL, date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP());"); + stmt->execute(); + delete stmt; - if (file.is_open()) { - std::string line; - std::string total = ""; + for (const auto& entry : GeneralUtils::GetFileNamesFromFolder("./migrations/cdserver/")) { + auto migration = LoadMigration("cdserver/" + entry); - while (std::getline(file, line)) { - total += line; + if (migration.data.empty()) continue; + + stmt = Database::CreatePreppedStmt("SELECT name FROM migration_history WHERE name = ?;"); + stmt->setString(1, migration.name); + auto* res = stmt->executeQuery(); + bool doExit = res->next(); + delete res; + delete stmt; + if (doExit) continue; + + // Doing these 1 migration at a time since one takes a long time and some may think it is crashing. + // This will at the least guarentee that the full migration needs to be run in order to be counted as "migrated". + Game::logger->Log("MigrationRunner", "Executing migration: %s. This may take a while. Do not shut down server.", migration.name.c_str()); + for (const auto& dml : GeneralUtils::SplitString(migration.data, ';')) { + if (dml.empty()) continue; + try { + CDClientDatabase::ExecuteDML(dml.c_str()); + } catch (CppSQLite3Exception& e) { + Game::logger->Log("MigrationRunner", "Encountered error running DML command: (%i) : %s", e.errorCode(), e.errorMessage()); + } } - - file.close(); - - migration.name = path; - migration.data = total; + stmt = Database::CreatePreppedStmt("INSERT INTO migration_history (name) VALUES (?);"); + stmt->setString(1, migration.name); + stmt->execute(); + delete stmt; } - - return migration; + Game::logger->Log("MigrationRunner", "CDServer database is up to date."); } diff --git a/dDatabase/MigrationRunner.h b/dDatabase/MigrationRunner.h index f5d1325a..0cb36d53 100644 --- a/dDatabase/MigrationRunner.h +++ b/dDatabase/MigrationRunner.h @@ -1,19 +1,13 @@ #pragma once -#include "Database.h" - -#include "dCommonVars.h" -#include "Game.h" -#include "dCommonVars.h" -#include "dLogger.h" +#include <string> struct Migration { std::string data; std::string name; }; -class MigrationRunner { -public: - static void RunMigrations(); - static Migration LoadMigration(std::string path); +namespace MigrationRunner { + void RunMigrations(); + void RunSQLiteMigrations(); }; diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 538fb749..cd54913a 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -105,10 +105,34 @@ int main(int argc, char** argv) { const std::string cdclient_path = "./res/CDServer.sqlite"; std::ifstream cdclient_fd(cdclient_path); if (!cdclient_fd.good()) { - Game::logger->Log("WorldServer", "%s could not be opened", cdclient_path.c_str()); - return EXIT_FAILURE; + Game::logger->Log("WorldServer", "%s could not be opened. Looking for cdclient.fdb to convert to sqlite.", cdclient_path.c_str()); + cdclient_fd.close(); + + const std::string cdclientFdbPath = "./res/cdclient.fdb"; + cdclient_fd.open(cdclientFdbPath); + if (!cdclient_fd.good()) { + Game::logger->Log( + "WorldServer", "%s could not be opened." + "Please move a cdclient.fdb or an already converted database to build/res.", cdclientFdbPath.c_str()); + return EXIT_FAILURE; + } + Game::logger->Log("WorldServer", "Found %s. Clearing cdserver migration_history then copying and converting to sqlite.", cdclientFdbPath.c_str()); + auto stmt = Database::CreatePreppedStmt(R"#(DELETE FROM migration_history WHERE name LIKE "%cdserver%";)#"); + stmt->executeUpdate(); + delete stmt; + cdclient_fd.close(); + + std::string res = "python3 ../thirdparty/docker-utils/utils/fdb_to_sqlite.py " + cdclientFdbPath; + int r = system(res.c_str()); + if (r != 0) { + Game::logger->Log("MasterServer", "Failed to convert fdb to sqlite"); + return EXIT_FAILURE; + } + if (std::rename("./cdclient.sqlite", "./res/CDServer.sqlite") != 0) { + Game::logger->Log("MasterServer", "failed to move cdclient file."); + return EXIT_FAILURE; + } } - cdclient_fd.close(); //Connect to CDClient try { @@ -120,6 +144,9 @@ int main(int argc, char** argv) { return EXIT_FAILURE; } + // Run migrations should any need to be run. + MigrationRunner::RunSQLiteMigrations(); + //Get CDClient initial information try { CDClientManager::Instance()->Initialize(); diff --git a/migrations/cdserver/0_nt_footrace.sql b/migrations/cdserver/0_nt_footrace.sql index fd37599e..0a40cfef 100644 --- a/migrations/cdserver/0_nt_footrace.sql +++ b/migrations/cdserver/0_nt_footrace.sql @@ -1,6 +1,2 @@ -BEGIN TRANSACTION; - UPDATE ComponentsRegistry SET component_id = 1901 WHERE id = 12916 AND component_type = 39; INSERT INTO ActivityRewards (objectTemplate, ActivityRewardIndex, activityRating, LootMatrixIndex, CurrencyIndex, ChallengeRating, description) VALUES (1901, 166, -1, 598, 1, 4, 'NT Foot Race'); - -COMMIT; From 89fb66c4a980020f6f0284ec60ed8d69ff773483 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 30 Oct 2022 13:06:05 -0700 Subject: [PATCH 110/322] Change AMFArray getters to use Templates and fix CI halting when one matrix fails (#796) * Change AMFArray getters to use Templates Move Template definition to header * Add more tests Add tests for casting to wrong template type Add tests for going out of bounds in the array. * Try continue-on-error * Update build-and-test.yml * Try continue-on-error Update build-and-test.yml * change version * Update CMakeMariaDBLists.txt Update CMakeMariaDBLists.txt --- .github/workflows/build-and-test.yml | 1 + dCommon/AMFFormat.cpp | 15 ----- dCommon/AMFFormat.h | 55 ++++++++++++---- tests/AMFDeserializeTests.cpp | 93 ++++++++++++++++++++-------- thirdparty/CMakeMariaDBLists.txt | 4 +- 5 files changed, 111 insertions(+), 57 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 5a36df4b..8f65fd8e 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -10,6 +10,7 @@ jobs: build-and-test: name: Build & Test (${{ matrix.os }}) runs-on: ${{ matrix.os }} + continue-on-error: true strategy: matrix: os: [ windows-2022, ubuntu-20.04, macos-11 ] diff --git a/dCommon/AMFFormat.cpp b/dCommon/AMFFormat.cpp index 822f994d..4407b29c 100644 --- a/dCommon/AMFFormat.cpp +++ b/dCommon/AMFFormat.cpp @@ -58,16 +58,6 @@ void AMFArrayValue::RemoveValue(const std::string& key) { } } -// AMFArray Find Value -AMFValue* AMFArrayValue::FindValue(const std::string& key) { - _AMFArrayMap_::iterator it = this->associative.find(key); - if (it != this->associative.end()) { - return it->second; - } - - return nullptr; -} - // AMFArray Get Associative Iterator Begin _AMFArrayMap_::iterator AMFArrayValue::GetAssociativeIteratorValueBegin() { return this->associative.begin(); @@ -93,11 +83,6 @@ uint32_t AMFArrayValue::GetDenseValueSize() { return (uint32_t)this->dense.size(); } -// AMFArray Get value at index in Dense List -AMFValue* AMFArrayValue::GetValueAt(uint32_t index) { - return this->dense.at(index); -} - // AMFArray Get Dense Iterator Begin _AMFArrayList_::iterator AMFArrayValue::GetDenseIteratorBegin() { return this->dense.begin(); diff --git a/dCommon/AMFFormat.h b/dCommon/AMFFormat.h index eaa342cd..2b423abd 100644 --- a/dCommon/AMFFormat.h +++ b/dCommon/AMFFormat.h @@ -75,7 +75,9 @@ private: /*! \return The AMF value type */ - AMFValueType GetValueType() { return AMFUndefined; } + AMFValueType GetValueType() { return ValueType; } +public: + static const AMFValueType ValueType = AMFUndefined; }; //! The null value AMF type @@ -85,7 +87,9 @@ private: /*! \return The AMF value type */ - AMFValueType GetValueType() { return AMFNull; } + AMFValueType GetValueType() { return ValueType; } +public: + static const AMFValueType ValueType = AMFNull; }; //! The false value AMF type @@ -95,7 +99,9 @@ private: /*! \return The AMF value type */ - AMFValueType GetValueType() { return AMFFalse; } + AMFValueType GetValueType() { return ValueType; } +public: + static const AMFValueType ValueType = AMFFalse; }; //! The true value AMF type @@ -105,7 +111,9 @@ private: /*! \return The AMF value type */ - AMFValueType GetValueType() { return AMFTrue; } + AMFValueType GetValueType() { return ValueType; } +public: + static const AMFValueType ValueType = AMFTrue; }; //! The integer value AMF type @@ -117,9 +125,10 @@ private: /*! \return The AMF value type */ - AMFValueType GetValueType() { return AMFInteger; } + AMFValueType GetValueType() { return ValueType; } public: + static const AMFValueType ValueType = AMFInteger; //! Sets the integer value /*! \param value The value to set @@ -142,9 +151,10 @@ private: /*! \return The AMF value type */ - AMFValueType GetValueType() { return AMFDouble; } + AMFValueType GetValueType() { return ValueType; } public: + static const AMFValueType ValueType = AMFDouble; //! Sets the double value /*! \param value The value to set to @@ -167,9 +177,10 @@ private: /*! \return The AMF value type */ - AMFValueType GetValueType() { return AMFString; } + AMFValueType GetValueType() { return ValueType; } public: + static const AMFValueType ValueType = AMFString; //! Sets the string value /*! \param value The string value to set to @@ -192,9 +203,10 @@ private: /*! \return The AMF value type */ - AMFValueType GetValueType() { return AMFXMLDoc; } + AMFValueType GetValueType() { return ValueType; } public: + static const AMFValueType ValueType = AMFXMLDoc; //! Sets the XML Doc value /*! \param value The value to set to @@ -217,9 +229,10 @@ private: /*! \return The AMF value type */ - AMFValueType GetValueType() { return AMFDate; } + AMFValueType GetValueType() { return ValueType; } public: + static const AMFValueType ValueType = AMFDate; //! Sets the date time /*! \param value The value to set to @@ -244,9 +257,11 @@ private: /*! \return The AMF value type */ - AMFValueType GetValueType() { return AMFArray; } + AMFValueType GetValueType() { return ValueType; } public: + static const AMFValueType ValueType = AMFArray; + ~AMFArrayValue() override; //! Inserts an item into the array map for a specific key /*! @@ -265,7 +280,15 @@ public: /*! \return The AMF value if found, nullptr otherwise */ - AMFValue* FindValue(const std::string& key); + template <typename T> + T* FindValue(const std::string& key) const { + _AMFArrayMap_::const_iterator it = this->associative.find(key); + if (it != this->associative.end() && T::ValueType == it->second->GetValueType()) { + return dynamic_cast<T*>(it->second); + } + + return nullptr; + }; //! Returns where the associative iterator begins /*! @@ -298,7 +321,12 @@ public: /*! \param index The index to get */ - AMFValue* GetValueAt(uint32_t index); + template <typename T> + T* GetValueAt(uint32_t index) { + if (index >= this->dense.size()) return nullptr; + AMFValue* foundValue = this->dense.at(index); + return T::ValueType == foundValue->GetValueType() ? dynamic_cast<T*>(foundValue) : nullptr; + }; //! Returns where the dense iterator begins /*! @@ -334,10 +362,11 @@ private: /*! \return The AMF value type */ - AMFValueType GetValueType() { return AMFObject; } + AMFValueType GetValueType() { return ValueType; } ~AMFObjectValue() override; public: + static const AMFValueType ValueType = AMFObject; //! Constructor /*! \param traits The traits to set diff --git a/tests/AMFDeserializeTests.cpp b/tests/AMFDeserializeTests.cpp index 03941a85..8d4974a3 100644 --- a/tests/AMFDeserializeTests.cpp +++ b/tests/AMFDeserializeTests.cpp @@ -146,8 +146,8 @@ int ReadAMFArrayFromBitStream() { ASSERT_EQ(res->GetValueType(), AMFValueType::AMFArray); ASSERT_EQ(static_cast<AMFArrayValue*>(res.get())->GetAssociativeMap().size(), 1); ASSERT_EQ(static_cast<AMFArrayValue*>(res.get())->GetDenseArray().size(), 1); - ASSERT_EQ(static_cast<AMFStringValue*>(static_cast<AMFArrayValue*>(res.get())->FindValue("BehaviorID"))->GetStringValue(), "10447"); - ASSERT_EQ(static_cast<AMFStringValue*>(static_cast<AMFArrayValue*>(res.get())->GetDenseArray()[0])->GetStringValue(), "10447"); + ASSERT_EQ(static_cast<AMFArrayValue*>(res.get())->FindValue<AMFStringValue>("BehaviorID")->GetStringValue(), "10447"); + ASSERT_EQ(static_cast<AMFArrayValue*>(res.get())->GetValueAt<AMFStringValue>(0)->GetStringValue(), "10447"); } // Test a dense array return 0; @@ -219,102 +219,103 @@ int TestLiveCapture() { auto result = static_cast<AMFArrayValue*>(resultFromFn.get()); // Test the outermost array - ASSERT_EQ(dynamic_cast<AMFStringValue*>(result->FindValue("BehaviorID"))->GetStringValue(), "10447"); - ASSERT_EQ(dynamic_cast<AMFStringValue*>(result->FindValue("objectID"))->GetStringValue(), "288300744895913279") + ASSERT_EQ(result->FindValue<AMFStringValue>("BehaviorID")->GetStringValue(), "10447"); + ASSERT_EQ(result->FindValue<AMFStringValue>("objectID")->GetStringValue(), "288300744895913279"); + + // Test the execution state array + auto executionState = result->FindValue<AMFArrayValue>("executionState"); - // Test the execution state array - auto executionState = dynamic_cast<AMFArrayValue*>(result->FindValue("executionState")); ASSERT_NE(executionState, nullptr); - auto strips = dynamic_cast<AMFArrayValue*>(executionState->FindValue("strips"))->GetDenseArray(); + auto strips = executionState->FindValue<AMFArrayValue>("strips")->GetDenseArray(); ASSERT_EQ(strips.size(), 1); auto stripsPosition0 = dynamic_cast<AMFArrayValue*>(strips[0]); - auto actionIndex = dynamic_cast<AMFDoubleValue*>(stripsPosition0->FindValue("actionIndex")); + auto actionIndex = stripsPosition0->FindValue<AMFDoubleValue>("actionIndex"); ASSERT_EQ(actionIndex->GetDoubleValue(), 0.0f); - auto stripIDExecution = dynamic_cast<AMFDoubleValue*>(stripsPosition0->FindValue("id")); + auto stripIDExecution = stripsPosition0->FindValue<AMFDoubleValue>("id"); ASSERT_EQ(stripIDExecution->GetDoubleValue(), 0.0f); - auto stateIDExecution = dynamic_cast<AMFDoubleValue*>(executionState->FindValue("stateID")); + auto stateIDExecution = executionState->FindValue<AMFDoubleValue>("stateID"); ASSERT_EQ(stateIDExecution->GetDoubleValue(), 0.0f); - auto states = dynamic_cast<AMFArrayValue*>(result->FindValue("states"))->GetDenseArray(); + auto states = result->FindValue<AMFArrayValue>("states")->GetDenseArray(); ASSERT_EQ(states.size(), 1); auto firstState = dynamic_cast<AMFArrayValue*>(states[0]); - auto stateID = dynamic_cast<AMFDoubleValue*>(firstState->FindValue("id")); + auto stateID = firstState->FindValue<AMFDoubleValue>("id"); ASSERT_EQ(stateID->GetDoubleValue(), 0.0f); - auto stripsInState = dynamic_cast<AMFArrayValue*>(firstState->FindValue("strips"))->GetDenseArray(); + auto stripsInState = firstState->FindValue<AMFArrayValue>("strips")->GetDenseArray(); ASSERT_EQ(stripsInState.size(), 1); auto firstStrip = dynamic_cast<AMFArrayValue*>(stripsInState[0]); - auto actionsInFirstStrip = dynamic_cast<AMFArrayValue*>(firstStrip->FindValue("actions"))->GetDenseArray(); + auto actionsInFirstStrip = firstStrip->FindValue<AMFArrayValue>("actions")->GetDenseArray(); ASSERT_EQ(actionsInFirstStrip.size(), 3); - auto actionID = dynamic_cast<AMFDoubleValue*>(firstStrip->FindValue("id")); + auto actionID = firstStrip->FindValue<AMFDoubleValue>("id"); ASSERT_EQ(actionID->GetDoubleValue(), 0.0f) - auto uiArray = dynamic_cast<AMFArrayValue*>(firstStrip->FindValue("ui")); + auto uiArray = firstStrip->FindValue<AMFArrayValue>("ui"); - auto xPos = dynamic_cast<AMFDoubleValue*>(uiArray->FindValue("x")); - auto yPos = dynamic_cast<AMFDoubleValue*>(uiArray->FindValue("y")); + auto xPos = uiArray->FindValue<AMFDoubleValue>("x"); + auto yPos = uiArray->FindValue<AMFDoubleValue>("y"); ASSERT_EQ(xPos->GetDoubleValue(), 103.0f); ASSERT_EQ(yPos->GetDoubleValue(), 82.0f); - auto stripID = dynamic_cast<AMFDoubleValue*>(firstStrip->FindValue("id")); + auto stripID = firstStrip->FindValue<AMFDoubleValue>("id"); ASSERT_EQ(stripID->GetDoubleValue(), 0.0f) auto firstAction = dynamic_cast<AMFArrayValue*>(actionsInFirstStrip[0]); - auto firstType = dynamic_cast<AMFStringValue*>(firstAction->FindValue("Type")); + auto firstType = firstAction->FindValue<AMFStringValue>("Type"); ASSERT_EQ(firstType->GetStringValue(), "OnInteract"); - auto firstCallback = dynamic_cast<AMFStringValue*>(firstAction->FindValue("__callbackID__")); + auto firstCallback = firstAction->FindValue<AMFStringValue>("__callbackID__"); ASSERT_EQ(firstCallback->GetStringValue(), ""); auto secondAction = dynamic_cast<AMFArrayValue*>(actionsInFirstStrip[1]); - auto secondType = dynamic_cast<AMFStringValue*>(secondAction->FindValue("Type")); + auto secondType = secondAction->FindValue<AMFStringValue>("Type"); ASSERT_EQ(secondType->GetStringValue(), "FlyUp"); - auto secondCallback = dynamic_cast<AMFStringValue*>(secondAction->FindValue("__callbackID__")); + auto secondCallback = secondAction->FindValue<AMFStringValue>("__callbackID__"); ASSERT_EQ(secondCallback->GetStringValue(), ""); - auto secondDistance = dynamic_cast<AMFDoubleValue*>(secondAction->FindValue("Distance")); + auto secondDistance = secondAction->FindValue<AMFDoubleValue>("Distance"); ASSERT_EQ(secondDistance->GetDoubleValue(), 25.0f); auto thirdAction = dynamic_cast<AMFArrayValue*>(actionsInFirstStrip[2]); - auto thirdType = dynamic_cast<AMFStringValue*>(thirdAction->FindValue("Type")); + auto thirdType = thirdAction->FindValue<AMFStringValue>("Type"); ASSERT_EQ(thirdType->GetStringValue(), "FlyDown"); - auto thirdCallback = dynamic_cast<AMFStringValue*>(thirdAction->FindValue("__callbackID__")); + auto thirdCallback = thirdAction->FindValue<AMFStringValue>("__callbackID__"); ASSERT_EQ(thirdCallback->GetStringValue(), ""); - auto thirdDistance = dynamic_cast<AMFDoubleValue*>(thirdAction->FindValue("Distance")); + auto thirdDistance = thirdAction->FindValue<AMFDoubleValue>("Distance"); ASSERT_EQ(thirdDistance->GetDoubleValue(), 25.0f); @@ -327,6 +328,42 @@ int TestNullStream() { return 0; } +int TestBadConversion() { + std::ifstream testFileStream; + testFileStream.open("AMFBitStreamTest.bin", std::ios::binary); + + // Read a test BitStream from a file + RakNet::BitStream testBitStream; + char byte = 0; + while (testFileStream.get(byte)) { + testBitStream.Write<char>(byte); + } + + testFileStream.close(); + + auto resultFromFn = ReadFromBitStream(&testBitStream); + auto result = static_cast<AMFArrayValue*>(resultFromFn.get()); + + // Actually a string value. + ASSERT_EQ(result->FindValue<AMFDoubleValue>("BehaviorID"), nullptr); + + // Does not exist in the associative portion + ASSERT_EQ(result->FindValue<AMFNullValue>("DOES_NOT_EXIST"), nullptr); + + result->PushBackValue(new AMFTrueValue()); + + // Exists and is correct type + ASSERT_NE(result->GetValueAt<AMFTrueValue>(0), nullptr); + + // Value exists but is wrong typing + ASSERT_EQ(result->GetValueAt<AMFFalseValue>(0), nullptr); + + // Value is out of bounds + ASSERT_EQ(result->GetValueAt<AMFTrueValue>(1), nullptr); + + return 0; +} + int AMFDeserializeTests(int argc, char** const argv) { std::cout << "Checking that using a null bitstream doesnt cause exception" << std::endl; if (TestNullStream()) return 1; @@ -343,6 +380,8 @@ int AMFDeserializeTests(int argc, char** const argv) { if (TestLiveCapture() != 0) return 1; std::cout << "Passed live capture, checking unimplemented amf values" << std::endl; if (TestUnimplementedAMFValues() != 0) return 1; + std::cout << "Passed unimplemented values, checking poor casting" << std::endl; + if (TestBadConversion() != 0) return 1; std::cout << "Passed all tests." << std::endl; return 0; } diff --git a/thirdparty/CMakeMariaDBLists.txt b/thirdparty/CMakeMariaDBLists.txt index 55e95c4d..cb1e28e7 100644 --- a/thirdparty/CMakeMariaDBLists.txt +++ b/thirdparty/CMakeMariaDBLists.txt @@ -43,7 +43,7 @@ if(WIN32 AND NOT MARIADB_BUILD_SOURCE) add_custom_target(mariadb_connector_cpp) add_custom_command(TARGET mariadb_connector_cpp POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.dll" "${MARIADB_C_CONNECTOR_DIR}/lib/libmariadb.dll" "${PROJECT_BINARY_DIR}") @@ -118,7 +118,7 @@ else() # Build from source ${BINARY_DIR}/mariadbcpp/plugin ${MARIADB_SHARED_LIBRARY_COPY_LOCATION} - COMMAND ${CMAKE_COMMAND} -E copy_if_different + COMMAND ${CMAKE_COMMAND} -E copy_if_different ${MARIADB_SHARED_LIBRARY_LOCATION} ${MARIADB_SHARED_LIBRARY_COPY_LOCATION} From d4af7d76a272daeb6ee35b78fc4dd7b2fb337a19 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 31 Oct 2022 15:31:49 -0700 Subject: [PATCH 111/322] Add property behaviors migration (#790) * Add behaviors migration Add migration for behaviors. Tested that the tables get altered correctly, names are set correctly. Tested that I can place models, both regular and Brick-by-Brick ones and that they get deleted properly. Tested that picking up models and re-placing them down properly updates them in the tables. * Only update when empty --- dGame/dComponents/PropertyManagementComponent.cpp | 9 ++++++++- dGame/dGameMessages/GameMessages.cpp | 9 ++++++++- migrations/dlu/6_property_behaviors.sql | 11 +++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 migrations/dlu/6_property_behaviors.sql diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index f6954e4d..1e90e8db 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -656,7 +656,7 @@ void PropertyManagementComponent::Save() { return; } - auto* insertion = Database::CreatePreppedStmt("INSERT INTO properties_contents VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); + auto* insertion = Database::CreatePreppedStmt("INSERT INTO properties_contents VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); auto* update = Database::CreatePreppedStmt("UPDATE properties_contents SET x = ?, y = ?, z = ?, rx = ?, ry = ?, rz = ?, rw = ? WHERE id = ?;"); auto* lookup = Database::CreatePreppedStmt("SELECT id FROM properties_contents WHERE property_id = ?;"); auto* remove = Database::CreatePreppedStmt("DELETE FROM properties_contents WHERE id = ?;"); @@ -706,6 +706,13 @@ void PropertyManagementComponent::Save() { insertion->setDouble(9, rotation.y); insertion->setDouble(10, rotation.z); insertion->setDouble(11, rotation.w); + insertion->setString(12, "Objects_" + std::to_string(entity->GetLOT()) + "_name"); // Model name. TODO make this customizable + insertion->setString(13, ""); // Model description. TODO implement this. + insertion->setDouble(14, 0); // behavior 1. TODO implement this. + insertion->setDouble(15, 0); // behavior 2. TODO implement this. + insertion->setDouble(16, 0); // behavior 3. TODO implement this. + insertion->setDouble(17, 0); // behavior 4. TODO implement this. + insertion->setDouble(18, 0); // behavior 5. TODO implement this. try { insertion->execute(); } catch (sql::SQLException& ex) { diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 4efbd286..5ad8e207 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -2545,7 +2545,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent delete ugcs; //Insert into the db as a BBB model: - auto* stmt = Database::CreatePreppedStmt("INSERT INTO `properties_contents`(`id`, `property_id`, `ugc_id`, `lot`, `x`, `y`, `z`, `rx`, `ry`, `rz`, `rw`) VALUES (?,?,?,?,?,?,?,?,?,?,?)"); + auto* stmt = Database::CreatePreppedStmt("INSERT INTO `properties_contents` VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); stmt->setUInt64(1, newIDL); stmt->setUInt64(2, propertyId); stmt->setUInt(3, blueprintIDSmall); @@ -2557,6 +2557,13 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent stmt->setDouble(9, 0.0f); // ry stmt->setDouble(10, 0.0f); // rz stmt->setDouble(11, 0.0f); // rw + stmt->setString(12, "Objects_14_name"); // Model name. TODO make this customizable + stmt->setString(13, ""); // Model description. TODO implement this. + stmt->setDouble(14, 0); // behavior 1. TODO implement this. + stmt->setDouble(15, 0); // behavior 2. TODO implement this. + stmt->setDouble(16, 0); // behavior 3. TODO implement this. + stmt->setDouble(17, 0); // behavior 4. TODO implement this. + stmt->setDouble(18, 0); // behavior 5. TODO implement this. stmt->execute(); delete stmt; diff --git a/migrations/dlu/6_property_behaviors.sql b/migrations/dlu/6_property_behaviors.sql new file mode 100644 index 00000000..b858db67 --- /dev/null +++ b/migrations/dlu/6_property_behaviors.sql @@ -0,0 +1,11 @@ +ALTER TABLE properties_contents + ADD COLUMN model_name TEXT NOT NULL DEFAULT "", + ADD COLUMN model_description TEXT NOT NULL DEFAULT "", + ADD COLUMN behavior_1 INT NOT NULL DEFAULT 0, + ADD COLUMN behavior_2 INT NOT NULL DEFAULT 0, + ADD COLUMN behavior_3 INT NOT NULL DEFAULT 0, + ADD COLUMN behavior_4 INT NOT NULL DEFAULT 0, + ADD COLUMN behavior_5 INT NOT NULL DEFAULT 0; + +UPDATE properties_contents SET model_name = CONCAT("Objects_", lot, "_name") WHERE model_name = ""; +CREATE TABLE IF NOT EXISTS behaviors (id INT NOT NULL, behavior_info TEXT NOT NULL); From 62213cd701be00ca6a58de120a0bfa5c68d627c9 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 31 Oct 2022 15:32:07 -0700 Subject: [PATCH 112/322] Implement basic functionality (#794) Implements the basic functionality and parsing of property behaviors. Unhandled messages and logged and discarded for the time being. The only implemented message is a basic one that sends the needed info the the client side User Interface to pop up. Tested that the User Interface properly shows up with zero behaviors on it. No other functionality is changed. --- CMakeLists.txt | 1 + dGame/CMakeLists.txt | 7 ++ dGame/dGameMessages/GameMessages.cpp | 22 ++++- dGame/dPropertyBehaviors/CMakeLists.txt | 4 + dGame/dPropertyBehaviors/ControlBehaviors.cpp | 81 +++++++++++++++++++ dGame/dPropertyBehaviors/ControlBehaviors.h | 35 ++++++++ 6 files changed, 148 insertions(+), 2 deletions(-) create mode 100644 dGame/dPropertyBehaviors/CMakeLists.txt create mode 100644 dGame/dPropertyBehaviors/ControlBehaviors.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviors.h diff --git a/CMakeLists.txt b/CMakeLists.txt index b147b200..33efbdc9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -143,6 +143,7 @@ set(INCLUDED_DIRECTORIES "dGame/dInventory" "dGame/dMission" "dGame/dEntity" + "dGame/dPropertyBehaviors" "dGame/dUtilities" "dPhysics" "dNavigation" diff --git a/dGame/CMakeLists.txt b/dGame/CMakeLists.txt index 6b31802e..eb02eef2 100644 --- a/dGame/CMakeLists.txt +++ b/dGame/CMakeLists.txt @@ -44,6 +44,13 @@ foreach(file ${DGAME_DMISSION_SOURCES}) set(DGAME_SOURCES ${DGAME_SOURCES} "dMission/${file}") endforeach() +add_subdirectory(dPropertyBehaviors) + +foreach(file ${DGAME_DPROPERTYBEHAVIORS_SOURCES}) + set(DGAME_SOURCES ${DGAME_SOURCES} "dPropertyBehaviors/${file}") +endforeach() + + add_subdirectory(dUtilities) foreach(file ${DGAME_DUTILITIES_SOURCES}) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 5ad8e207..18d7e0f6 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -68,6 +68,8 @@ #include "PropertyVendorComponent.h" #include "PropertySelectQueryProperty.h" #include "TradingManager.h" +#include "ControlBehaviors.h" +#include "AMFDeserialize.h" void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender) { CBITSTREAM; @@ -2396,8 +2398,24 @@ void GameMessages::SendUnSmash(Entity* entity, LWOOBJID builderID, float duratio } void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - // TODO - Game::logger->Log("GameMessages", "Recieved Control Behavior GameMessage, but property behaviors are unimplemented."); + AMFDeserialize reader; + std::unique_ptr<AMFValue> amfArguments(reader.Read(inStream)); + if (amfArguments->GetValueType() != AMFValueType::AMFArray) return; + + uint32_t commandLength{}; + inStream->Read(commandLength); + + std::string command; + for (uint32_t i = 0; i < commandLength; i++) { + unsigned char character; + inStream->Read(character); + command.push_back(character); + } + + auto owner = PropertyManagementComponent::Instance()->GetOwner(); + if (!owner) return; + + ControlBehaviors::ProcessCommand(entity, sysAddr, static_cast<AMFArrayValue*>(amfArguments.get()), command, owner); } void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { diff --git a/dGame/dPropertyBehaviors/CMakeLists.txt b/dGame/dPropertyBehaviors/CMakeLists.txt new file mode 100644 index 00000000..4f5d60aa --- /dev/null +++ b/dGame/dPropertyBehaviors/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DGAME_DPROPERTYBEHAVIORS_SOURCES + "ControlBehaviors.cpp" + PARENT_SCOPE +) diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.cpp b/dGame/dPropertyBehaviors/ControlBehaviors.cpp new file mode 100644 index 00000000..4e922ee0 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviors.cpp @@ -0,0 +1,81 @@ +#include "ControlBehaviors.h" + +#include "AMFFormat.h" +#include "Entity.h" +#include "Game.h" +#include "GameMessages.h" +#include "ModelComponent.h" +#include "dLogger.h" + +void ControlBehaviors::ProcessCommand(Entity* modelEntity, const SystemAddress& sysAddr, AMFArrayValue* arguments, std::string command, Entity* modelOwner) { + if (!modelEntity || !modelOwner || !arguments) return; + + if (command == "sendBehaviorListToClient") + SendBehaviorListToClient(modelEntity, sysAddr, modelOwner); + else if (command == "modelTypeChanged") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "toggleExecutionUpdates") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "addStrip") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "removeStrip") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "mergeStrips") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "splitStrip") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "updateStripUI") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "addAction") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "migrateActions") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "rearrangeStrip") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "add") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "removeActions") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "rename") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "sendBehaviorBlocksToClient") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "moveToInventory") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else if (command == "updateAction") + Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); + else + Game::logger->Log("ControlBehaviors", "Unknown behavior command (%s)\n", command.c_str()); +} + +void ControlBehaviors::SendBehaviorListToClient( + Entity* modelEntity, + const SystemAddress& sysAddr, + Entity* modelOwner + ) { + auto* modelComponent = modelEntity->GetComponent<ModelComponent>(); + + if (!modelComponent) return; + + AMFArrayValue behaviorsToSerialize; + + AMFArrayValue* behaviors = new AMFArrayValue(); // Empty for now + + /** + * The behaviors AMFArray will have up to 5 elements in the dense portion. + * Each element in the dense portion will be made up of another AMFArray + * with the following information mapped in the associative portion + * "id": Behavior ID cast to an AMFString + * "isLocked": AMFTrue or AMFFalse of whether or not the behavior is locked + * "isLoot": AMFTrue or AMFFalse of whether or not the behavior is a custom behavior (true if custom) + * "name": The name of the behavior formatted as an AMFString + */ + + behaviorsToSerialize.InsertValue("behaviors", behaviors); + + AMFStringValue* amfStringValueForObjectID = new AMFStringValue(); + amfStringValueForObjectID->SetStringValue(std::to_string(modelComponent->GetParent()->GetObjectID())); + + behaviorsToSerialize.InsertValue("objectID", amfStringValueForObjectID); + GameMessages::SendUIMessageServerToSingleClient(modelOwner, sysAddr, "UpdateBehaviorList", &behaviorsToSerialize); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.h b/dGame/dPropertyBehaviors/ControlBehaviors.h new file mode 100644 index 00000000..7c24da68 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviors.h @@ -0,0 +1,35 @@ +#pragma once + +#ifndef __CONTROLBEHAVIORS__H__ +#define __CONTROLBEHAVIORS__H__ + +#include <string> + +#include "RakNetTypes.h" + +class Entity; +class AMFArrayValue; + +namespace ControlBehaviors { + /** + * @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); + + /** + * @brief Helper function to send the behavior list to the client + * + * @param modelEntity The model that sent this command + * @param sysAddr The SystemAddress to respond to + * @param modelOwner The owner of the model which sent this command + */ + void SendBehaviorListToClient(Entity* modelEntity, const SystemAddress& sysAddr, Entity* modelOwner); +}; + +#endif //!__CONTROLBEHAVIORS__H__ From 971e0fb3b63a36854d6cd395c0dfe0eb21b1a21d Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 31 Oct 2022 15:32:17 -0700 Subject: [PATCH 113/322] Modularize gargantuan objects (#797) --- dPhysics/dpEntity.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/dPhysics/dpEntity.cpp b/dPhysics/dpEntity.cpp index 42c195f2..c7ed56f8 100644 --- a/dPhysics/dpEntity.cpp +++ b/dPhysics/dpEntity.cpp @@ -34,7 +34,6 @@ dpEntity::dpEntity(const LWOOBJID& objectID, NiPoint3 boxDimensions, bool isStat m_CollisionGroup = COLLISION_GROUP_ALL; m_CollisionShape = new dpShapeBox(this, boxDimensions.x, boxDimensions.y, boxDimensions.z); - if (boxDimensions.x > 100.0f) m_IsGargantuan = true; } dpEntity::dpEntity(const LWOOBJID& objectID, float width, float height, float depth, bool isStatic) { @@ -45,7 +44,6 @@ dpEntity::dpEntity(const LWOOBJID& objectID, float width, float height, float de m_CollisionGroup = COLLISION_GROUP_ALL; m_CollisionShape = new dpShapeBox(this, width, height, depth); - if (width > 100.0f) m_IsGargantuan = true; } dpEntity::dpEntity(const LWOOBJID& objectID, float radius, bool isStatic) { @@ -56,7 +54,6 @@ dpEntity::dpEntity(const LWOOBJID& objectID, float radius, bool isStatic) { m_CollisionGroup = COLLISION_GROUP_ALL; m_CollisionShape = new dpShapeSphere(this, radius); - if (radius > 200.0f) m_IsGargantuan = true; } dpEntity::~dpEntity() { @@ -146,5 +143,12 @@ void dpEntity::SetAngularVelocity(const NiPoint3& newAngularVelocity) { void dpEntity::SetGrid(dpGrid* grid) { m_Grid = grid; + + if (m_CollisionShape->GetShapeType() == dpShapeType::Sphere && static_cast<dpShapeSphere*>(m_CollisionShape)->GetRadius() * 2.0f > static_cast<float>(m_Grid->CELL_SIZE)) { + m_IsGargantuan = true; + } else if (m_CollisionShape->GetShapeType() == dpShapeType::Box && static_cast<dpShapeBox*>(m_CollisionShape)->GetWidth() > static_cast<float>(m_Grid->CELL_SIZE)) { + m_IsGargantuan = true; + } + m_Grid->Add(this); } From 4a6f3e44eeef2a8f97f0a7c942358e6d77fa7df5 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Tue, 1 Nov 2022 18:21:26 +0000 Subject: [PATCH 114/322] Add support for packed clients (#802) * First iteration of pack reader and interface * Fix memory leak and remove logs * Complete packed asset interface and begin on file loading replacement * Implement proper BinaryIO error * Improve AssetMemoryBuffer for reading and implement more reading * Repair more file loading code and improve how navmeshes are loaded * Missing checks implementation * Revert addition of Manifest class and migration changes * Resolved all feedback. --- CMakeLists.txt | 12 ++ dChatServer/ChatServer.cpp | 14 +- dCommon/BinaryIO.cpp | 6 +- dCommon/BinaryIO.h | 9 +- dCommon/BrickByBrickFix.cpp | 4 +- dCommon/BrickByBrickFix.h | 6 - dCommon/CMakeLists.txt | 6 + dCommon/Game.h | 2 + dCommon/GeneralUtils.cpp | 1 + dCommon/ZCompression.h | 6 + dCommon/dClient/AssetManager.cpp | 201 +++++++++++++++++++++++ dCommon/dClient/AssetManager.h | 78 +++++++++ dCommon/dClient/CMakeLists.txt | 6 + dCommon/dClient/Pack.cpp | 118 +++++++++++++ dCommon/dClient/Pack.h | 38 +++++ dCommon/dClient/PackIndex.cpp | 50 ++++++ dCommon/dClient/PackIndex.h | 40 +++++ dGame/dInventory/Item.cpp | 10 +- dGame/dUtilities/BrickDatabase.cpp | 7 +- dGame/dUtilities/SlashCommandHandler.cpp | 11 +- dMasterServer/MasterServer.cpp | 49 +++--- dNavigation/dNavMesh.cpp | 2 +- dWorldServer/WorldServer.cpp | 27 ++- dZoneManager/Level.cpp | 21 ++- dZoneManager/Level.h | 6 +- dZoneManager/Zone.cpp | 29 ++-- dZoneManager/Zone.h | 8 +- resources/sharedconfig.ini | 4 + 28 files changed, 690 insertions(+), 81 deletions(-) create mode 100644 dCommon/dClient/AssetManager.cpp create mode 100644 dCommon/dClient/AssetManager.h create mode 100644 dCommon/dClient/CMakeLists.txt create mode 100644 dCommon/dClient/Pack.cpp create mode 100644 dCommon/dClient/Pack.h create mode 100644 dCommon/dClient/PackIndex.cpp create mode 100644 dCommon/dClient/PackIndex.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 33efbdc9..9437bc63 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -101,6 +101,17 @@ foreach(resource_file ${RESOURCE_FILES}) endif() endforeach() +# Copy navmesh data on first build and extract it +if (NOT EXISTS ${PROJECT_BINARY_DIR}/navmeshes/) + configure_file( + ${CMAKE_SOURCE_DIR}/resources/navmeshes.zip ${PROJECT_BINARY_DIR}/navmeshes.zip + COPYONLY + ) + + file(ARCHIVE_EXTRACT INPUT ${PROJECT_BINARY_DIR}/navmeshes.zip) + file(REMOVE ${PROJECT_BINARY_DIR}/navmeshes.zip) +endif() + # Copy vanity files on first build set(VANITY_FILES "CREDITS.md" "INFO.md" "TESTAMENT.md" "NPC.xml") foreach(file ${VANITY_FILES}) @@ -145,6 +156,7 @@ set(INCLUDED_DIRECTORIES "dGame/dEntity" "dGame/dPropertyBehaviors" "dGame/dUtilities" + "dCommon/dClient" "dPhysics" "dNavigation" "dNavigation/dTerrain" diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index 273921eb..5a60e494 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -12,6 +12,7 @@ #include "dMessageIdentifiers.h" #include "dChatFilter.h" #include "Diagnostics.h" +#include "AssetManager.h" #include "PlayerContainer.h" #include "ChatPacketHandler.h" @@ -22,6 +23,7 @@ namespace Game { dServer* server; dConfig* config; dChatFilter* chatFilter; + AssetManager* assetManager; } //RakNet includes: @@ -50,6 +52,16 @@ int main(int argc, char** argv) { Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); + try { + std::string client_path = config.GetValue("client_location"); + if (client_path.empty()) client_path = "./res"; + Game::assetManager = new AssetManager(config.GetValue("client_location")); + } catch (std::runtime_error& ex) { + Game::logger->Log("ChatServer", "Got an error while setting up assets: %s", ex.what()); + + return EXIT_FAILURE; + } + //Connect to the MySQL Database std::string mysql_host = config.GetValue("mysql_host"); std::string mysql_database = config.GetValue("mysql_database"); @@ -87,7 +99,7 @@ int main(int argc, char** argv) { Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat); - Game::chatFilter = new dChatFilter("./res/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); + Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); //Run it until server gets a kill message from Master: auto t = std::chrono::high_resolution_clock::now(); diff --git a/dCommon/BinaryIO.cpp b/dCommon/BinaryIO.cpp index 7cb18331..22e4de60 100644 --- a/dCommon/BinaryIO.cpp +++ b/dCommon/BinaryIO.cpp @@ -10,7 +10,7 @@ void BinaryIO::WriteString(const std::string& stringToWrite, std::ofstream& outs } //For reading null-terminated strings -std::string BinaryIO::ReadString(std::ifstream& instream) { +std::string BinaryIO::ReadString(std::istream& instream) { std::string toReturn; char buffer; @@ -25,7 +25,7 @@ std::string BinaryIO::ReadString(std::ifstream& instream) { } //For reading strings of a specific size -std::string BinaryIO::ReadString(std::ifstream& instream, size_t size) { +std::string BinaryIO::ReadString(std::istream& instream, size_t size) { std::string toReturn; char buffer; @@ -37,7 +37,7 @@ std::string BinaryIO::ReadString(std::ifstream& instream, size_t size) { return toReturn; } -std::string BinaryIO::ReadWString(std::ifstream& instream) { +std::string BinaryIO::ReadWString(std::istream& instream) { size_t size; BinaryRead(instream, size); //toReturn.resize(size); diff --git a/dCommon/BinaryIO.h b/dCommon/BinaryIO.h index 1f9aaefd..a117ad0d 100644 --- a/dCommon/BinaryIO.h +++ b/dCommon/BinaryIO.h @@ -10,16 +10,15 @@ namespace BinaryIO { template<typename T> std::istream& BinaryRead(std::istream& stream, T& value) { - if (!stream.good()) - printf("bla"); + if (!stream.good()) throw std::runtime_error("Failed to read from istream."); return stream.read(reinterpret_cast<char*>(&value), sizeof(T)); } void WriteString(const std::string& stringToWrite, std::ofstream& outstream); - std::string ReadString(std::ifstream& instream); - std::string ReadString(std::ifstream& instream, size_t size); - std::string ReadWString(std::ifstream& instream); + std::string ReadString(std::istream& instream); + std::string ReadString(std::istream& instream, size_t size); + std::string ReadWString(std::istream& instream); inline bool DoesFileExist(const std::string& name) { std::ifstream f(name.c_str()); diff --git a/dCommon/BrickByBrickFix.cpp b/dCommon/BrickByBrickFix.cpp index f0c4e824..15194bf9 100644 --- a/dCommon/BrickByBrickFix.cpp +++ b/dCommon/BrickByBrickFix.cpp @@ -49,10 +49,10 @@ uint32_t BrickByBrickFix::TruncateBrokenBrickByBrickXml() { } // Ignore the valgrind warning about uninitialized values. These are discarded later when we know the actual uncompressed size. - std::unique_ptr<uint8_t[]> uncompressedChunk(new uint8_t[MAX_SD0_CHUNK_SIZE]); + std::unique_ptr<uint8_t[]> uncompressedChunk(new uint8_t[ZCompression::MAX_SD0_CHUNK_SIZE]); int32_t err{}; int32_t actualUncompressedSize = ZCompression::Decompress( - compressedChunk.get(), chunkSize, uncompressedChunk.get(), MAX_SD0_CHUNK_SIZE, err); + compressedChunk.get(), chunkSize, uncompressedChunk.get(), ZCompression::MAX_SD0_CHUNK_SIZE, err); if (actualUncompressedSize != -1) { uint32_t previousSize = completeUncompressedModel.size(); diff --git a/dCommon/BrickByBrickFix.h b/dCommon/BrickByBrickFix.h index 0c7e314c..7450fb71 100644 --- a/dCommon/BrickByBrickFix.h +++ b/dCommon/BrickByBrickFix.h @@ -17,10 +17,4 @@ namespace BrickByBrickFix { * @return The number of BrickByBrick models that were updated */ uint32_t UpdateBrickByBrickModelsToSd0(); - - /** - * @brief Max size of an inflated sd0 zlib chunk - * - */ - constexpr uint32_t MAX_SD0_CHUNK_SIZE = 1024 * 256; }; diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index cb73bf6a..46102b74 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -17,6 +17,12 @@ set(DCOMMON_SOURCES "AMFFormat.cpp" "BrickByBrickFix.cpp" ) +add_subdirectory(dClient) + +foreach(file ${DCOMMON_DCLIENT_SOURCES}) + set(DCOMMON_SOURCES ${DCOMMON_SOURCES} "dClient/${file}") +endforeach() + include_directories(${PROJECT_SOURCE_DIR}/dCommon/) add_library(dCommon STATIC ${DCOMMON_SOURCES}) diff --git a/dCommon/Game.h b/dCommon/Game.h index f4862602..616c7fbf 100644 --- a/dCommon/Game.h +++ b/dCommon/Game.h @@ -10,6 +10,7 @@ class dChatFilter; class dConfig; class dLocale; class RakPeerInterface; +class AssetManager; struct SystemAddress; namespace Game { @@ -22,5 +23,6 @@ namespace Game { extern dLocale* locale; extern std::mt19937 randomEngine; extern RakPeerInterface* chatServer; + extern AssetManager* assetManager; extern SystemAddress chatSysAddr; } diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index 4a6c4739..24ea72a0 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -50,6 +50,7 @@ bool _IsSuffixChar(uint8_t c) { bool GeneralUtils::_NextUTF8Char(std::string_view& slice, uint32_t& out) { size_t rem = slice.length(); + if (slice.empty()) return false; const uint8_t* bytes = (const uint8_t*)&slice.front(); if (rem > 0) { uint8_t first = bytes[0]; diff --git a/dCommon/ZCompression.h b/dCommon/ZCompression.h index 22a5ff86..84e8a9b4 100644 --- a/dCommon/ZCompression.h +++ b/dCommon/ZCompression.h @@ -8,5 +8,11 @@ namespace ZCompression { int32_t Compress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst); int32_t Decompress(const uint8_t* abSrc, int32_t nLenSrc, uint8_t* abDst, int32_t nLenDst, int32_t& nErr); + + /** + * @brief Max size of an inflated sd0 zlib chunk + * + */ + constexpr uint32_t MAX_SD0_CHUNK_SIZE = 1024 * 256; } diff --git a/dCommon/dClient/AssetManager.cpp b/dCommon/dClient/AssetManager.cpp new file mode 100644 index 00000000..3319bad7 --- /dev/null +++ b/dCommon/dClient/AssetManager.cpp @@ -0,0 +1,201 @@ +#include "AssetManager.h" + +#include <zlib.h> + +AssetManager::AssetManager(const std::string& path) { + if (!std::filesystem::is_directory(path)) { + throw std::runtime_error("Attempted to load asset bundle (" + path + ") however it is not a valid directory."); + } + + m_Path = std::filesystem::path(path); + + if (std::filesystem::exists(m_Path / "client") && std::filesystem::exists(m_Path / "versions")) { + m_AssetBundleType = eAssetBundleType::Packed; + + m_RootPath = m_Path; + m_ResPath = (m_Path / "client" / "res"); + } else if (std::filesystem::exists(m_Path / ".." / "versions") && std::filesystem::exists(m_Path / "res")) { + m_AssetBundleType = eAssetBundleType::Packed; + + m_RootPath = (m_Path / ".."); + m_ResPath = (m_Path / "res"); + } else if (std::filesystem::exists(m_Path / "pack") && std::filesystem::exists(m_Path / ".." / ".." / "versions")) { + m_AssetBundleType = eAssetBundleType::Packed; + + m_RootPath = (m_Path / ".." / ".."); + m_ResPath = m_Path; + } else if (std::filesystem::exists(m_Path / "res" / "cdclient.fdb") && !std::filesystem::exists(m_Path / "res" / "pack")) { + m_AssetBundleType = eAssetBundleType::Unpacked; + + m_ResPath = (m_Path / "res"); + } else if (std::filesystem::exists(m_Path / "cdclient.fdb") && !std::filesystem::exists(m_Path / "pack")) { + m_AssetBundleType = eAssetBundleType::Unpacked; + + m_ResPath = m_Path; + } + + if (m_AssetBundleType == eAssetBundleType::None) { + throw std::runtime_error("Failed to identify client type, cannot read client data."); + } + + switch (m_AssetBundleType) { + case eAssetBundleType::Packed: { + this->LoadPackIndex(); + + this->UnpackRequiredAssets(); + + break; + } + } +} + +void AssetManager::LoadPackIndex() { + m_PackIndex = new PackIndex(m_RootPath); +} + +std::filesystem::path AssetManager::GetResPath() { + return m_ResPath; +} + +eAssetBundleType AssetManager::GetAssetBundleType() { + return m_AssetBundleType; +} + +bool AssetManager::HasFile(const char* name) { + auto fixedName = std::string(name); + std::transform(fixedName.begin(), fixedName.end(), fixedName.begin(), [](uint8_t c) { return std::tolower(c); }); + std::replace(fixedName.begin(), fixedName.end(), '/', '\\'); + + auto realPathName = fixedName; + + if (fixedName.rfind("client\\res\\", 0) != 0) { + fixedName = "client\\res\\" + fixedName; + } + + if (std::filesystem::exists(m_ResPath / realPathName)) { + return true; + } + + uint32_t crc = crc32b(0xFFFFFFFF, (uint8_t*)fixedName.c_str(), fixedName.size()); + crc = crc32b(crc, (Bytef*)"\0\0\0\0", 4); + + for (const auto& item : this->m_PackIndex->GetPackFileIndices()) { + if (item.m_Crc == crc) { + return true; + } + } + + return false; +} + +bool AssetManager::GetFile(const char* name, char** data, uint32_t* len) { + auto fixedName = std::string(name); + std::transform(fixedName.begin(), fixedName.end(), fixedName.begin(), [](uint8_t c) { return std::tolower(c); }); + std::replace(fixedName.begin(), fixedName.end(), '/', '\\'); + + auto realPathName = fixedName; + + if (fixedName.rfind("client\\res\\", 0) != 0) { + fixedName = "client\\res\\" + fixedName; + } + + if (std::filesystem::exists(m_ResPath / realPathName)) { + FILE* file; +#ifdef _WIN32 + fopen_s(&file, (m_ResPath / realPathName).string().c_str(), "rb"); +#elif __APPLE__ + // macOS has 64bit file IO by default + file = fopen((m_ResPath / realPathName).string().c_str(), "rb"); +#else + file = fopen64((m_ResPath / realPathName).string().c_str(), "rb"); +#endif + fseek(file, 0, SEEK_END); + *len = ftell(file); + *data = (char*)malloc(*len); + fseek(file, 0, SEEK_SET); + fread(*data, sizeof(uint8_t), *len, file); + fclose(file); + + return true; + } + + if (this->m_AssetBundleType == eAssetBundleType::Unpacked) return false; + + int32_t packIndex = -1; + uint32_t crc = crc32b(0xFFFFFFFF, (uint8_t*)fixedName.c_str(), fixedName.size()); + crc = crc32b(crc, (Bytef*)"\0\0\0\0", 4); + + for (const auto& item : this->m_PackIndex->GetPackFileIndices()) { + if (item.m_Crc == crc) { + packIndex = item.m_PackFileIndex; + crc = item.m_Crc; + break; + } + } + + if (packIndex == -1 || !crc) { + return false; + } + + auto packs = this->m_PackIndex->GetPacks(); + auto* pack = packs.at(packIndex); + + bool success = pack->ReadFileFromPack(crc, data, len); + + return success; +} + +AssetMemoryBuffer AssetManager::GetFileAsBuffer(const char* name) { + char* buf; + uint32_t len; + + bool success = this->GetFile(name, &buf, &len); + + return AssetMemoryBuffer(buf, len, success); +} + +void AssetManager::UnpackRequiredAssets() { + if (std::filesystem::exists(m_ResPath / "cdclient.fdb")) return; + + char* data; + uint32_t size; + + bool success = this->GetFile("cdclient.fdb", &data, &size); + + if (!success) { + Game::logger->Log("AssetManager", "Failed to extract required files from the packs."); + + delete data; + + return; + } + + std::ofstream cdclientOutput(m_ResPath / "cdclient.fdb", std::ios::out | std::ios::binary); + cdclientOutput.write(data, size); + cdclientOutput.close(); + + delete data; + + return; +} + +uint32_t AssetManager::crc32b(uint32_t base, uint8_t* message, size_t l) { + size_t i, j; + uint32_t crc, msb; + + crc = base; + for (i = 0; i < l; i++) { + // xor next byte to upper bits of crc + crc ^= (((unsigned int)message[i]) << 24); + for (j = 0; j < 8; j++) { // Do eight times. + msb = crc >> 31; + crc <<= 1; + crc ^= (0 - msb) & 0x04C11DB7; + } + } + return crc; // don't complement crc on output +} + +AssetManager::~AssetManager() { + delete m_PackIndex; +} diff --git a/dCommon/dClient/AssetManager.h b/dCommon/dClient/AssetManager.h new file mode 100644 index 00000000..87653845 --- /dev/null +++ b/dCommon/dClient/AssetManager.h @@ -0,0 +1,78 @@ +#pragma once + +#include <string> +#include <vector> +#include <unordered_map> +#include <filesystem> + +#include "Pack.h" +#include "PackIndex.h" + +enum class eAssetBundleType { + None, + Unpacked, + Packed +}; + +struct AssetMemoryBuffer : std::streambuf { + char* m_Base; + bool m_Success; + + AssetMemoryBuffer(char* base, std::ptrdiff_t n, bool success) { + m_Base = base; + m_Success = success; + if (!m_Success) return; + this->setg(base, base, base + n); + } + + pos_type seekpos(pos_type sp, std::ios_base::openmode which) override { + return seekoff(sp - pos_type(off_type(0)), std::ios_base::beg, which); + } + + pos_type seekoff(off_type off, + std::ios_base::seekdir dir, + std::ios_base::openmode which = std::ios_base::in) override { + if (dir == std::ios_base::cur) + gbump(off); + else if (dir == std::ios_base::end) + setg(eback(), egptr() + off, egptr()); + else if (dir == std::ios_base::beg) + setg(eback(), eback() + off, egptr()); + return gptr() - eback(); + } + + void close() { + delete m_Base; + } +}; + +class AssetManager { +public: + AssetManager(const std::string& path); + ~AssetManager(); + + std::filesystem::path GetResPath(); + eAssetBundleType GetAssetBundleType(); + + bool HasFile(const char* name); + bool GetFile(const char* name, char** data, uint32_t* len); + AssetMemoryBuffer GetFileAsBuffer(const char* name); + +private: + void LoadPackIndex(); + void UnpackRequiredAssets(); + + // Modified crc algorithm (mpeg2) + // Reference: https://stackoverflow.com/questions/54339800/how-to-modify-crc-32-to-crc-32-mpeg-2 + inline uint32_t crc32b(uint32_t base, uint8_t* message, size_t l); + + bool m_SuccessfullyLoaded; + + std::filesystem::path m_Path; + std::filesystem::path m_RootPath; + std::filesystem::path m_ResPath; + + eAssetBundleType m_AssetBundleType = eAssetBundleType::None; + + PackIndex* m_PackIndex; +}; diff --git a/dCommon/dClient/CMakeLists.txt b/dCommon/dClient/CMakeLists.txt new file mode 100644 index 00000000..69bb1712 --- /dev/null +++ b/dCommon/dClient/CMakeLists.txt @@ -0,0 +1,6 @@ +set(DCOMMON_DCLIENT_SOURCES + "PackIndex.cpp" + "Pack.cpp" + "AssetManager.cpp" + PARENT_SCOPE +) diff --git a/dCommon/dClient/Pack.cpp b/dCommon/dClient/Pack.cpp new file mode 100644 index 00000000..d7716bc9 --- /dev/null +++ b/dCommon/dClient/Pack.cpp @@ -0,0 +1,118 @@ +#include "Pack.h" + +#include "ZCompression.h" + +Pack::Pack(const std::filesystem::path& filePath) { + m_FilePath = filePath; + + if (!std::filesystem::exists(filePath)) { + return; + } + + m_FileStream = std::ifstream(filePath, std::ios::in | std::ios::binary); + + m_FileStream.read(m_Version, 7); + + m_FileStream.seekg(-8, std::ios::end); // move file pointer to 8 bytes before the end (location of the address of the record count) + + uint32_t recordCountPos = 0; + BinaryIO::BinaryRead<uint32_t>(m_FileStream, recordCountPos); + + m_FileStream.seekg(recordCountPos, std::ios::beg); + + BinaryIO::BinaryRead<uint32_t>(m_FileStream, m_RecordCount); + + for (int i = 0; i < m_RecordCount; i++) { + PackRecord record; + BinaryIO::BinaryRead<PackRecord>(m_FileStream, record); + + m_Records.push_back(record); + } + + m_FileStream.close(); +} + +bool Pack::HasFile(uint32_t crc) { + for (const auto& record : m_Records) { + if (record.m_Crc == crc) { + return true; + } + } + + return false; +} + +bool Pack::ReadFileFromPack(uint32_t crc, char** data, uint32_t* len) { + // Time for some wacky C file reading for speed reasons + + PackRecord pkRecord{}; + + for (const auto& record : m_Records) { + if (record.m_Crc == crc) { + pkRecord = record; + break; + } + } + + if (pkRecord.m_Crc == 0) return false; + + size_t pos = 0; + pos += pkRecord.m_FilePointer; + + bool isCompressed = (pkRecord.m_IsCompressed & 0xff) > 0; + auto inPackSize = isCompressed ? pkRecord.m_CompressedSize : pkRecord.m_UncompressedSize; + + FILE* file; +#ifdef _WIN32 + fopen_s(&file, m_FilePath.string().c_str(), "rb"); +#elif __APPLE__ + // macOS has 64bit file IO by default + file = fopen(m_FilePath.string().c_str(), "rb"); +#else + file = fopen64(m_FilePath.string().c_str(), "rb"); +#endif + + fseek(file, pos, SEEK_SET); + + if (!isCompressed) { + char* tempData = (char*)malloc(pkRecord.m_UncompressedSize); + fread(tempData, sizeof(uint8_t), pkRecord.m_UncompressedSize, file); + + *data = tempData; + *len = pkRecord.m_UncompressedSize; + fclose(file); + + return true; + } + + pos += 5; // skip header + + fseek(file, pos, SEEK_SET); + + char* decompressedData = (char*)malloc(pkRecord.m_UncompressedSize); + uint32_t currentReadPos = 0; + + while (true) { + if (currentReadPos >= pkRecord.m_UncompressedSize) break; + + uint32_t size; + fread(&size, sizeof(uint32_t), 1, file); + pos += 4; // Move pointer position 4 to the right + + char* chunk = (char*)malloc(size); + fread(chunk, sizeof(int8_t), size, file); + pos += size; // Move pointer position the amount of bytes read to the right + + int32_t err; + currentReadPos += ZCompression::Decompress((uint8_t*)chunk, size, reinterpret_cast<uint8_t*>(decompressedData + currentReadPos), ZCompression::MAX_SD0_CHUNK_SIZE, err); + + free(chunk); + } + + *data = decompressedData; + *len = pkRecord.m_UncompressedSize; + + fclose(file); + + return true; +} diff --git a/dCommon/dClient/Pack.h b/dCommon/dClient/Pack.h new file mode 100644 index 00000000..3e95b00a --- /dev/null +++ b/dCommon/dClient/Pack.h @@ -0,0 +1,38 @@ +#pragma once + +#include <vector> +#include <string> +#include <filesystem> + +#pragma pack(push, 1) +struct PackRecord { + uint32_t m_Crc; + int32_t m_LowerCrc; + int32_t m_UpperCrc; + uint32_t m_UncompressedSize; + char m_UncompressedHash[32]; + uint32_t m_Padding1; + uint32_t m_CompressedSize; + char m_CompressedHash[32]; + uint32_t m_Padding2; + uint32_t m_FilePointer; + uint32_t m_IsCompressed; // u32 bool +}; +#pragma pack(pop) + +class Pack { +public: + Pack(const std::filesystem::path& filePath); + ~Pack() = default; + + bool HasFile(uint32_t crc); + bool ReadFileFromPack(uint32_t crc, char** data, uint32_t* len); +private: + std::ifstream m_FileStream; + std::filesystem::path m_FilePath; + + char m_Version[7]; + + uint32_t m_RecordCount; + std::vector<PackRecord> m_Records; +}; diff --git a/dCommon/dClient/PackIndex.cpp b/dCommon/dClient/PackIndex.cpp new file mode 100644 index 00000000..49ce61d1 --- /dev/null +++ b/dCommon/dClient/PackIndex.cpp @@ -0,0 +1,50 @@ +#include "PackIndex.h" + + +PackIndex::PackIndex(const std::filesystem::path& filePath) { + m_FileStream = std::ifstream(filePath / "versions" / "primary.pki", std::ios::in | std::ios::binary); + + BinaryIO::BinaryRead<uint32_t>(m_FileStream, m_Version); + BinaryIO::BinaryRead<uint32_t>(m_FileStream, m_PackPathCount); + + for (int i = 0; i < m_PackPathCount; i++) { + uint32_t stringLen = 0; + BinaryIO::BinaryRead<uint32_t>(m_FileStream, stringLen); + + std::string path; + + for (int j = 0; j < stringLen; j++) { + char inChar; + BinaryIO::BinaryRead<char>(m_FileStream, inChar); + + path += inChar; + } + + m_PackPaths.push_back(path); + } + + BinaryIO::BinaryRead<uint32_t>(m_FileStream, m_PackFileIndexCount); + + for (int i = 0; i < m_PackFileIndexCount; i++) { + PackFileIndex packFileIndex; + BinaryIO::BinaryRead<PackFileIndex>(m_FileStream, packFileIndex); + + m_PackFileIndices.push_back(packFileIndex); + } + + Game::logger->Log("PackIndex", "Loaded pack catalog with %i pack files and %i files", m_PackPaths.size(), m_PackFileIndices.size()); + + for (const auto& item : m_PackPaths) { + auto* pack = new Pack(filePath / item); + + m_Packs.push_back(pack); + } + + m_FileStream.close(); +} + +PackIndex::~PackIndex() { + for (const auto* item : m_Packs) { + delete item; + } +} diff --git a/dCommon/dClient/PackIndex.h b/dCommon/dClient/PackIndex.h new file mode 100644 index 00000000..bf10b809 --- /dev/null +++ b/dCommon/dClient/PackIndex.h @@ -0,0 +1,40 @@ +#pragma once + +#include <cstdint> + +#include <string> +#include <vector> +#include <filesystem> + +#include "Pack.h" + +#pragma pack(push, 1) +struct PackFileIndex { + uint32_t m_Crc; + int32_t m_LowerCrc; + int32_t m_UpperCrc; + uint32_t m_PackFileIndex; + uint32_t m_IsCompressed; // u32 bool? +}; +#pragma pack(pop) + +class PackIndex { +public: + PackIndex(const std::filesystem::path& filePath); + ~PackIndex(); + + const std::vector<std::string>& GetPackPaths() { return m_PackPaths; } + const std::vector<PackFileIndex>& GetPackFileIndices() { return m_PackFileIndices; } + const std::vector<Pack*>& GetPacks() { return m_Packs; } +private: + std::ifstream m_FileStream; + + uint32_t m_Version; + + uint32_t m_PackPathCount; + std::vector<std::string> m_PackPaths; + uint32_t m_PackFileIndexCount; + std::vector<PackFileIndex> m_PackFileIndices; + + std::vector<Pack*> m_Packs; +}; diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 4d4f2686..655af84e 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -13,6 +13,7 @@ #include "PossessableComponent.h" #include "CharacterComponent.h" #include "eItemType.h" +#include "AssetManager.h" class Inventory; @@ -340,18 +341,23 @@ void Item::DisassembleModel() { std::string renderAsset = result.fieldIsNull(0) ? "" : std::string(result.getStringField(0)); std::vector<std::string> renderAssetSplit = GeneralUtils::SplitString(renderAsset, '\\'); - std::string lxfmlPath = "res/BrickModels/" + GeneralUtils::SplitString(renderAssetSplit.back(), '.')[0] + ".lxfml"; - std::ifstream file(lxfmlPath); + std::string lxfmlPath = "BrickModels/" + GeneralUtils::SplitString(renderAssetSplit.back(), '.').at(0) + ".lxfml"; + auto buffer = Game::assetManager->GetFileAsBuffer(lxfmlPath.c_str()); + + std::istream file(&buffer); result.finalize(); if (!file.good()) { + buffer.close(); return; } std::stringstream data; data << file.rdbuf(); + buffer.close(); + if (data.str().empty()) { return; } diff --git a/dGame/dUtilities/BrickDatabase.cpp b/dGame/dUtilities/BrickDatabase.cpp index 7ff0febb..4e873278 100644 --- a/dGame/dUtilities/BrickDatabase.cpp +++ b/dGame/dUtilities/BrickDatabase.cpp @@ -3,6 +3,7 @@ #include "BrickDatabase.h" #include "Game.h" +#include "AssetManager.h" std::vector<Brick> BrickDatabase::emptyCache{}; BrickDatabase* BrickDatabase::m_Address = nullptr; @@ -17,7 +18,8 @@ std::vector<Brick>& BrickDatabase::GetBricks(const std::string& lxfmlPath) { return cached->second; } - std::ifstream file(lxfmlPath); + AssetMemoryBuffer buffer = Game::assetManager->GetFileAsBuffer(("client/" + lxfmlPath).c_str()); + std::istream file(&buffer); if (!file.good()) { return emptyCache; } @@ -25,9 +27,12 @@ std::vector<Brick>& BrickDatabase::GetBricks(const std::string& lxfmlPath) { std::stringstream data; data << file.rdbuf(); if (data.str().empty()) { + buffer.close(); return emptyCache; } + buffer.close(); + auto* doc = new tinyxml2::XMLDocument(); if (doc->Parse(data.str().c_str(), data.str().size()) != 0) { delete doc; diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index c6f1da9f..e8f1659e 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -63,6 +63,7 @@ #include "GameConfig.h" #include "ScriptedActivityComponent.h" #include "LevelProgressionComponent.h" +#include "AssetManager.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { std::string chatCommand; @@ -582,7 +583,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (args[0].find("/") != std::string::npos) return; if (args[0].find("\\") != std::string::npos) return; - std::ifstream infile("./res/macros/" + args[0] + ".scm"); + auto buf = Game::assetManager->GetFileAsBuffer(("macros/" + args[0] + ".scm").c_str()); + std::istream infile(&buf); if (infile.good()) { std::string line; @@ -593,6 +595,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Unknown macro! Is the filename right?"); } + buf.close(); + return; } @@ -1904,10 +1908,7 @@ bool SlashCommandHandler::CheckIfAccessibleZone(const unsigned int zoneID) { CDZoneTableTable* zoneTable = CDClientManager::Instance()->GetTable<CDZoneTableTable>("ZoneTable"); const CDZoneTable* zone = zoneTable->Query(zoneID); if (zone != nullptr) { - std::string zonePath = "./res/maps/" + zone->zoneName; - std::transform(zonePath.begin(), zonePath.end(), zonePath.begin(), ::tolower); - std::ifstream f(zonePath.c_str()); - return f.good(); + return Game::assetManager->HasFile(("maps/" + zone->zoneName).c_str()); } else { return false; } diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index cd54913a..5aac3743 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -25,6 +25,7 @@ #include "dConfig.h" #include "dLogger.h" #include "dServer.h" +#include "AssetManager.h" //RakNet includes: #include "RakNetDefines.h" @@ -44,6 +45,7 @@ namespace Game { dServer* server; InstanceManager* im; dConfig* config; + AssetManager* assetManager; } //namespace Game bool shutdownSequenceStarted = false; @@ -99,44 +101,49 @@ int main(int argc, char** argv) { return EXIT_FAILURE; } + try { + std::string client_path = config.GetValue("client_location"); + if (client_path.empty()) client_path = "./res"; + Game::assetManager = new AssetManager(config.GetValue("client_location")); + } catch (std::runtime_error& ex) { + Game::logger->Log("MasterServer", "Got an error while setting up assets: %s", ex.what()); + + return EXIT_FAILURE; + } + MigrationRunner::RunMigrations(); - //Check CDClient exists - const std::string cdclient_path = "./res/CDServer.sqlite"; - std::ifstream cdclient_fd(cdclient_path); - if (!cdclient_fd.good()) { - Game::logger->Log("WorldServer", "%s could not be opened. Looking for cdclient.fdb to convert to sqlite.", cdclient_path.c_str()); - cdclient_fd.close(); + // Check CDClient exists + if (!std::filesystem::exists(Game::assetManager->GetResPath() / "CDServer.sqlite")) { + Game::logger->Log("WorldServer", "CDServer.sqlite could not be opened. Looking for cdclient.fdb to convert to sqlite."); - const std::string cdclientFdbPath = "./res/cdclient.fdb"; - cdclient_fd.open(cdclientFdbPath); - if (!cdclient_fd.good()) { - Game::logger->Log( - "WorldServer", "%s could not be opened." - "Please move a cdclient.fdb or an already converted database to build/res.", cdclientFdbPath.c_str()); + if (!std::filesystem::exists(Game::assetManager->GetResPath() / "cdclient.fdb")) { + Game::logger->Log("WorldServer", "cdclient.fdb could not be opened. Please move a cdclient.fdb or an already converted database to build/res."); return EXIT_FAILURE; } - Game::logger->Log("WorldServer", "Found %s. Clearing cdserver migration_history then copying and converting to sqlite.", cdclientFdbPath.c_str()); + + Game::logger->Log("WorldServer", "Found cdclient.fdb. Clearing cdserver migration_history then copying and converting to sqlite."); auto stmt = Database::CreatePreppedStmt(R"#(DELETE FROM migration_history WHERE name LIKE "%cdserver%";)#"); stmt->executeUpdate(); delete stmt; - cdclient_fd.close(); - std::string res = "python3 ../thirdparty/docker-utils/utils/fdb_to_sqlite.py " + cdclientFdbPath; - int r = system(res.c_str()); - if (r != 0) { + std::string res = "python3 ../thirdparty/docker-utils/utils/fdb_to_sqlite.py " + (Game::assetManager->GetResPath() / "cdclient.fdb").string(); + + int result = system(res.c_str()); + if (result != 0) { Game::logger->Log("MasterServer", "Failed to convert fdb to sqlite"); return EXIT_FAILURE; } - if (std::rename("./cdclient.sqlite", "./res/CDServer.sqlite") != 0) { - Game::logger->Log("MasterServer", "failed to move cdclient file."); + + if (std::rename("./cdclient.sqlite", (Game::assetManager->GetResPath() / "CDServer.sqlite").string().c_str()) != 0) { + Game::logger->Log("MasterServer", "Failed to move cdclient file."); return EXIT_FAILURE; } } //Connect to CDClient try { - CDClientDatabase::Connect(cdclient_path); + CDClientDatabase::Connect((Game::assetManager->GetResPath() / "CDServer.sqlite").string()); } catch (CppSQLite3Exception& e) { Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); @@ -152,7 +159,7 @@ int main(int argc, char** argv) { CDClientManager::Instance()->Initialize(); } catch (CppSQLite3Exception& e) { Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database"); - Game::logger->Log("WorldServer", "May be caused by corrupted file: %s", cdclient_path.c_str()); + Game::logger->Log("WorldServer", "May be caused by corrupted file: %s", (Game::assetManager->GetResPath() / "CDServer.sqlite").string().c_str()); Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); return EXIT_FAILURE; diff --git a/dNavigation/dNavMesh.cpp b/dNavigation/dNavMesh.cpp index b3c8a229..e5ba0129 100644 --- a/dNavigation/dNavMesh.cpp +++ b/dNavigation/dNavMesh.cpp @@ -43,7 +43,7 @@ dNavMesh::~dNavMesh() { void dNavMesh::LoadNavmesh() { - std::string path = "./res/maps/navmeshes/" + std::to_string(m_ZoneId) + ".bin"; + std::string path = "./navmeshes/" + std::to_string(m_ZoneId) + ".bin"; if (!BinaryIO::DoesFileExist(path)) { return; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 89243d59..23761b2b 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -55,6 +55,7 @@ #include "MasterPackets.h" #include "Player.h" #include "PropertyManagementComponent.h" +#include "AssetManager.h" #include "ZCompression.h" @@ -68,6 +69,8 @@ namespace Game { dLocale* locale; std::mt19937 randomEngine; + AssetManager* assetManager; + RakPeerInterface* chatServer; SystemAddress chatSysAddr; } @@ -142,9 +145,19 @@ int main(int argc, char** argv) { Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); if (config.GetValue("disable_chat") == "1") chatDisabled = true; + try { + std::string client_path = config.GetValue("client_location"); + if (client_path.empty()) client_path = "./res"; + Game::assetManager = new AssetManager(config.GetValue("client_location")); + } catch (std::runtime_error& ex) { + Game::logger->Log("WorldServer", "Got an error while setting up assets: %s", ex.what()); + + return EXIT_FAILURE; + } + // Connect to CDClient try { - CDClientDatabase::Connect("./res/CDServer.sqlite"); + CDClientDatabase::Connect((Game::assetManager->GetResPath() / "CDServer.sqlite").string()); } catch (CppSQLite3Exception& e) { Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); @@ -189,7 +202,7 @@ int main(int argc, char** argv) { ObjectIDManager::Instance()->Initialize(); UserManager::Instance()->Initialize(); LootGenerator::Instance(); - Game::chatFilter = new dChatFilter("./res/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); + Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, zoneID); @@ -243,14 +256,14 @@ int main(int argc, char** argv) { std::ifstream fileStream; static const std::vector<std::string> aliases = { - "res/CDServers.fdb", - "res/cdserver.fdb", - "res/CDClient.fdb", - "res/cdclient.fdb", + "CDServers.fdb", + "cdserver.fdb", + "CDClient.fdb", + "cdclient.fdb", }; for (const auto& file : aliases) { - fileStream.open(file, std::ios::binary | std::ios::in); + fileStream.open(Game::assetManager->GetResPath() / file, std::ios::binary | std::ios::in); if (fileStream.is_open()) { break; } diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index f12adc56..dd38d208 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -13,17 +13,22 @@ #include "EntityManager.h" #include "CDFeatureGatingTable.h" #include "CDClientManager.h" +#include "AssetManager.h" Level::Level(Zone* parentZone, const std::string& filepath) { m_ParentZone = parentZone; - std::ifstream file(filepath, std::ios_base::in | std::ios_base::binary); - if (file) { - ReadChunks(file); - } else { + + auto buffer = Game::assetManager->GetFileAsBuffer(filepath.c_str()); + + if (!buffer.m_Success) { Game::logger->Log("Level", "Failed to load %s", filepath.c_str()); + return; } - file.close(); + std::istream file(&buffer); + ReadChunks(file); + + buffer.close(); } Level::~Level() { @@ -41,7 +46,7 @@ const void Level::PrintAllObjects() { } } -void Level::ReadChunks(std::ifstream& file) { +void Level::ReadChunks(std::istream& file) { const uint32_t CHNK_HEADER = ('C' + ('H' << 8) + ('N' << 16) + ('K' << 24)); while (!file.eof()) { @@ -139,7 +144,7 @@ void Level::ReadChunks(std::ifstream& file) { } } -void Level::ReadFileInfoChunk(std::ifstream& file, Header& header) { +void Level::ReadFileInfoChunk(std::istream& file, Header& header) { FileInfoChunk* fi = new FileInfoChunk; BinaryIO::BinaryRead(file, fi->version); BinaryIO::BinaryRead(file, fi->revision); @@ -152,7 +157,7 @@ void Level::ReadFileInfoChunk(std::ifstream& file, Header& header) { if (header.fileInfo->revision == 3452816845 && m_ParentZone->GetZoneID().GetMapID() == 1100) header.fileInfo->revision = 26; } -void Level::ReadSceneObjectDataChunk(std::ifstream& file, Header& header) { +void Level::ReadSceneObjectDataChunk(std::istream& file, Header& header) { SceneObjectDataChunk* chunk = new SceneObjectDataChunk; uint32_t objectsCount = 0; BinaryIO::BinaryRead(file, objectsCount); diff --git a/dZoneManager/Level.h b/dZoneManager/Level.h index e724363f..83daeedb 100644 --- a/dZoneManager/Level.h +++ b/dZoneManager/Level.h @@ -67,7 +67,7 @@ private: Zone* m_ParentZone; //private functions: - void ReadChunks(std::ifstream& file); - void ReadFileInfoChunk(std::ifstream& file, Header& header); - void ReadSceneObjectDataChunk(std::ifstream& file, Header& header); + void ReadChunks(std::istream& file); + void ReadFileInfoChunk(std::istream& file, Header& header); + void ReadSceneObjectDataChunk(std::istream& file, Header& header); }; diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index b670849b..1fe47454 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -7,6 +7,7 @@ #include "GeneralUtils.h" #include "BinaryIO.h" +#include "AssetManager.h" #include "CDClientManager.h" #include "CDZoneTableTable.h" #include "Spawner.h" @@ -40,7 +41,8 @@ void Zone::LoadZoneIntoMemory() { m_ZonePath = m_ZoneFilePath.substr(0, m_ZoneFilePath.rfind('/') + 1); if (m_ZoneFilePath == "ERR") return; - std::ifstream file(m_ZoneFilePath, std::ios::binary); + AssetMemoryBuffer buffer = Game::assetManager->GetFileAsBuffer(m_ZoneFilePath.c_str()); + std::istream file(&buffer); if (file) { BinaryIO::BinaryRead(file, m_ZoneFileFormatVersion); @@ -144,17 +146,13 @@ void Zone::LoadZoneIntoMemory() { } } - - - //m_PathData.resize(m_PathDataLength); - //file.read((char*)&m_PathData[0], m_PathDataLength); } } else { Game::logger->Log("Zone", "Failed to open: %s", m_ZoneFilePath.c_str()); } m_ZonePath = m_ZoneFilePath.substr(0, m_ZoneFilePath.rfind('/') + 1); - file.close(); + buffer.close(); } std::string Zone::GetFilePathForZoneID() { @@ -162,7 +160,7 @@ std::string Zone::GetFilePathForZoneID() { CDZoneTableTable* zoneTable = CDClientManager::Instance()->GetTable<CDZoneTableTable>("ZoneTable"); const CDZoneTable* zone = zoneTable->Query(this->GetZoneID().GetMapID()); if (zone != nullptr) { - std::string toReturn = "./res/maps/" + zone->zoneName; + std::string toReturn = "maps/" + zone->zoneName; std::transform(toReturn.begin(), toReturn.end(), toReturn.begin(), ::tolower); return toReturn; } @@ -222,7 +220,7 @@ const void Zone::PrintAllGameObjects() { } } -void Zone::LoadScene(std::ifstream& file) { +void Zone::LoadScene(std::istream& file) { SceneRef scene; scene.level = nullptr; LWOSCENEID lwoSceneID(LWOZONEID_INVALID, 0); @@ -264,10 +262,17 @@ void Zone::LoadScene(std::ifstream& file) { std::vector<LUTriggers::Trigger*> Zone::LoadLUTriggers(std::string triggerFile, LWOSCENEID sceneID) { std::vector<LUTriggers::Trigger*> lvlTriggers; - std::ifstream file(m_ZonePath + triggerFile); + + auto buffer = Game::assetManager->GetFileAsBuffer((m_ZonePath + triggerFile).c_str()); + + if (!buffer.m_Success) return lvlTriggers; + + std::istream file(&buffer); std::stringstream data; data << file.rdbuf(); + buffer.close(); + if (data.str().size() == 0) return lvlTriggers; tinyxml2::XMLDocument* doc = new tinyxml2::XMLDocument(); @@ -336,7 +341,7 @@ const Path* Zone::GetPath(std::string name) const { return nullptr; } -void Zone::LoadSceneTransition(std::ifstream& file) { +void Zone::LoadSceneTransition(std::istream& file) { SceneTransition sceneTrans; if (m_ZoneFileFormatVersion < Zone::ZoneFileFormatVersion::Auramar) { uint8_t length; @@ -355,14 +360,14 @@ void Zone::LoadSceneTransition(std::ifstream& file) { m_SceneTransitions.push_back(sceneTrans); } -SceneTransitionInfo Zone::LoadSceneTransitionInfo(std::ifstream& file) { +SceneTransitionInfo Zone::LoadSceneTransitionInfo(std::istream& file) { SceneTransitionInfo info; BinaryIO::BinaryRead(file, info.sceneID); BinaryIO::BinaryRead(file, info.position); return info; } -void Zone::LoadPath(std::ifstream& file) { +void Zone::LoadPath(std::istream& file) { // Currently only spawner (type 4) paths are supported Path path = Path(); diff --git a/dZoneManager/Zone.h b/dZoneManager/Zone.h index 50530273..f041b616 100644 --- a/dZoneManager/Zone.h +++ b/dZoneManager/Zone.h @@ -225,9 +225,9 @@ private: std::map<LWOSCENEID, uint32_t, mapCompareLwoSceneIDs> m_MapRevisions; //rhs is the revision! //private ("helper") functions: - void LoadScene(std::ifstream& file); + void LoadScene(std::istream& file); std::vector<LUTriggers::Trigger*> LoadLUTriggers(std::string triggerFile, LWOSCENEID sceneID); - void LoadSceneTransition(std::ifstream& file); - SceneTransitionInfo LoadSceneTransitionInfo(std::ifstream& file); - void LoadPath(std::ifstream& file); + void LoadSceneTransition(std::istream& file); + SceneTransitionInfo LoadSceneTransitionInfo(std::istream& file); + void LoadPath(std::istream& file); }; diff --git a/resources/sharedconfig.ini b/resources/sharedconfig.ini index 1a377d28..847a6b7c 100644 --- a/resources/sharedconfig.ini +++ b/resources/sharedconfig.ini @@ -21,3 +21,7 @@ max_clients=999 # Where to put crashlogs dump_folder= + +# The location of the client +# Either the folder with /res or with /client and /versions +client_location= From 353c328485979bbf29d1b5760943afdaa6981a2d Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Wed, 2 Nov 2022 22:05:52 -0500 Subject: [PATCH 115/322] compile fixes and default client_location (#809) * support for gcc9 on ubuntu 18.04 This is needed to make filesystem work * fix default for client location --- CMakeLists.txt | 2 +- dChatServer/ChatServer.cpp | 2 +- dMasterServer/MasterServer.cpp | 2 +- dWorldServer/WorldServer.cpp | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 9437bc63..005466cf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -58,7 +58,7 @@ if(UNIX) if(APPLE) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++17 -O2 -Wuninitialized -D_GLIBCXX_USE_CXX11_ABI=0 -D_GLIBCXX_USE_CXX17_ABI=0 -fPIC") else() - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++17 -O2 -Wuninitialized -D_GLIBCXX_USE_CXX11_ABI=0 -D_GLIBCXX_USE_CXX17_ABI=0 -static-libgcc -fPIC") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++17 -O2 -Wuninitialized -D_GLIBCXX_USE_CXX11_ABI=0 -D_GLIBCXX_USE_CXX17_ABI=0 -static-libgcc -fPIC -lstdc++fs") endif() if (__dynamic AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -rdynamic") diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index 5a60e494..fc8bdd5b 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -55,7 +55,7 @@ int main(int argc, char** argv) { try { std::string client_path = config.GetValue("client_location"); if (client_path.empty()) client_path = "./res"; - Game::assetManager = new AssetManager(config.GetValue("client_location")); + Game::assetManager = new AssetManager(client_path); } catch (std::runtime_error& ex) { Game::logger->Log("ChatServer", "Got an error while setting up assets: %s", ex.what()); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 5aac3743..12d8e04f 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -104,7 +104,7 @@ int main(int argc, char** argv) { try { std::string client_path = config.GetValue("client_location"); if (client_path.empty()) client_path = "./res"; - Game::assetManager = new AssetManager(config.GetValue("client_location")); + Game::assetManager = new AssetManager(client_path); } catch (std::runtime_error& ex) { Game::logger->Log("MasterServer", "Got an error while setting up assets: %s", ex.what()); diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 23761b2b..d4e55cb5 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -148,7 +148,7 @@ int main(int argc, char** argv) { try { std::string client_path = config.GetValue("client_location"); if (client_path.empty()) client_path = "./res"; - Game::assetManager = new AssetManager(config.GetValue("client_location")); + Game::assetManager = new AssetManager(client_path); } catch (std::runtime_error& ex) { Game::logger->Log("WorldServer", "Got an error while setting up assets: %s", ex.what()); From 8edade5f989257315f8c18ef20abb1f03e591aef Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 2 Nov 2022 20:30:35 -0700 Subject: [PATCH 116/322] Fix client paths (#811) --- CMakeLists.txt | 2 +- dCommon/dClient/AssetManager.cpp | 14 ++++++++------ dCommon/dClient/Pack.cpp | 3 ++- dCommon/dClient/PackIndex.cpp | 8 ++++++-- 4 files changed, 17 insertions(+), 10 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 005466cf..25575b0c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.14) +cmake_minimum_required(VERSION 3.18) project(Darkflame) include(CTest) diff --git a/dCommon/dClient/AssetManager.cpp b/dCommon/dClient/AssetManager.cpp index 3319bad7..ba928340 100644 --- a/dCommon/dClient/AssetManager.cpp +++ b/dCommon/dClient/AssetManager.cpp @@ -1,4 +1,6 @@ #include "AssetManager.h" +#include "Game.h" +#include "dLogger.h" #include <zlib.h> @@ -91,14 +93,9 @@ bool AssetManager::HasFile(const char* name) { bool AssetManager::GetFile(const char* name, char** data, uint32_t* len) { auto fixedName = std::string(name); std::transform(fixedName.begin(), fixedName.end(), fixedName.begin(), [](uint8_t c) { return std::tolower(c); }); - std::replace(fixedName.begin(), fixedName.end(), '/', '\\'); - + std::replace(fixedName.begin(), fixedName.end(), '\\', '/'); // On the off chance someone has the wrong slashes, force forward slashes auto realPathName = fixedName; - if (fixedName.rfind("client\\res\\", 0) != 0) { - fixedName = "client\\res\\" + fixedName; - } - if (std::filesystem::exists(m_ResPath / realPathName)) { FILE* file; #ifdef _WIN32 @@ -121,6 +118,11 @@ bool AssetManager::GetFile(const char* name, char** data, uint32_t* len) { if (this->m_AssetBundleType == eAssetBundleType::Unpacked) return false; + // The crc in side of the pack always uses backslashes, so we need to convert them again... + std::replace(fixedName.begin(), fixedName.end(), '/', '\\'); + if (fixedName.rfind("client\\res\\", 0) != 0) { + fixedName = "client\\res\\" + fixedName; + } int32_t packIndex = -1; uint32_t crc = crc32b(0xFFFFFFFF, (uint8_t*)fixedName.c_str(), fixedName.size()); crc = crc32b(crc, (Bytef*)"\0\0\0\0", 4); diff --git a/dCommon/dClient/Pack.cpp b/dCommon/dClient/Pack.cpp index d7716bc9..1c1a643a 100644 --- a/dCommon/dClient/Pack.cpp +++ b/dCommon/dClient/Pack.cpp @@ -1,5 +1,6 @@ #include "Pack.h" +#include "BinaryIO.h" #include "ZCompression.h" Pack::Pack(const std::filesystem::path& filePath) { @@ -11,7 +12,7 @@ Pack::Pack(const std::filesystem::path& filePath) { m_FileStream = std::ifstream(filePath, std::ios::in | std::ios::binary); - m_FileStream.read(m_Version, 7); + m_FileStream.read(m_Version, 7); m_FileStream.seekg(-8, std::ios::end); // move file pointer to 8 bytes before the end (location of the address of the record count) diff --git a/dCommon/dClient/PackIndex.cpp b/dCommon/dClient/PackIndex.cpp index 49ce61d1..5d96abeb 100644 --- a/dCommon/dClient/PackIndex.cpp +++ b/dCommon/dClient/PackIndex.cpp @@ -1,5 +1,7 @@ #include "PackIndex.h" - +#include "BinaryIO.h" +#include "Game.h" +#include "dLogger.h" PackIndex::PackIndex(const std::filesystem::path& filePath) { m_FileStream = std::ifstream(filePath / "versions" / "primary.pki", std::ios::in | std::ios::binary); @@ -34,7 +36,9 @@ PackIndex::PackIndex(const std::filesystem::path& filePath) { Game::logger->Log("PackIndex", "Loaded pack catalog with %i pack files and %i files", m_PackPaths.size(), m_PackFileIndices.size()); - for (const auto& item : m_PackPaths) { + for (auto& item : m_PackPaths) { + std::replace(item.begin(), item.end(), '\\', '/'); + auto* pack = new Pack(filePath / item); m_Packs.push_back(pack); From b974eed8f5312a4ddcdf5b95c792b84d4ad11c4e Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Thu, 3 Nov 2022 03:53:45 +0000 Subject: [PATCH 117/322] Make changes to certain database functions and a debug assert (#804) - Replace all interaction of std::string and sqlString. - Add a return before a debug assertion can be triggered by lvl chunks being loaded on server start. --- dDatabase/Database.cpp | 4 ++-- dDatabase/MigrationRunner.cpp | 10 +++++----- dMasterServer/MasterServer.cpp | 4 ++-- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/dDatabase/Database.cpp b/dDatabase/Database.cpp index c301cbd9..91589377 100644 --- a/dDatabase/Database.cpp +++ b/dDatabase/Database.cpp @@ -35,8 +35,8 @@ void Database::Connect(const string& host, const string& database, const string& } void Database::Connect() { - con = driver->connect(Database::props); - con->setSchema(Database::database); + con = driver->connect(Database::props["hostName"].c_str(), Database::props["user"].c_str(), Database::props["password"].c_str()); + con->setSchema(Database::database.c_str()); } void Database::Destroy(std::string source, bool log) { diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index 017ebe32..25312608 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -45,7 +45,7 @@ void MigrationRunner::RunMigrations() { } stmt = Database::CreatePreppedStmt("SELECT name FROM migration_history WHERE name = ?;"); - stmt->setString(1, migration.name); + stmt->setString(1, migration.name.c_str()); auto* res = stmt->executeQuery(); bool doExit = res->next(); delete res; @@ -56,11 +56,11 @@ void MigrationRunner::RunMigrations() { if (migration.name == "5_brick_model_sd0.sql") { runSd0Migrations = true; } else { - finalSQL.append(migration.data); + finalSQL.append(migration.data.c_str()); } stmt = Database::CreatePreppedStmt("INSERT INTO migration_history (name) VALUES (?);"); - stmt->setString(1, migration.name); + stmt->setString(1, migration.name.c_str()); stmt->execute(); delete stmt; } @@ -76,7 +76,7 @@ void MigrationRunner::RunMigrations() { for (auto& query : migration) { try { if (query.empty()) continue; - simpleStatement->execute(query); + simpleStatement->execute(query.c_str()); } catch (sql::SQLException& e) { Game::logger->Log("MigrationRunner", "Encountered error running migration: %s", e.what()); } @@ -103,7 +103,7 @@ void MigrationRunner::RunSQLiteMigrations() { if (migration.data.empty()) continue; stmt = Database::CreatePreppedStmt("SELECT name FROM migration_history WHERE name = ?;"); - stmt->setString(1, migration.name); + stmt->setString(1, migration.name.c_str()); auto* res = stmt->executeQuery(); bool doExit = res->next(); delete res; diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 12d8e04f..061a91c7 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -237,7 +237,7 @@ int main(int argc, char** argv) { //If we found a server, update it's IP and port to the current one. if (result->next()) { auto* updateStatement = Database::CreatePreppedStmt("UPDATE `servers` SET `ip` = ?, `port` = ? WHERE `id` = ?"); - updateStatement->setString(1, master_server_ip); + updateStatement->setString(1, master_server_ip.c_str()); updateStatement->setInt(2, Game::server->GetPort()); updateStatement->setInt(3, result->getInt("id")); updateStatement->execute(); @@ -245,7 +245,7 @@ int main(int argc, char** argv) { } else { //If we didn't find a server, create one. auto* insertStatement = Database::CreatePreppedStmt("INSERT INTO `servers` (`name`, `ip`, `port`, `state`, `version`) VALUES ('master', ?, ?, 0, 171023)"); - insertStatement->setString(1, master_server_ip); + insertStatement->setString(1, master_server_ip.c_str()); insertStatement->setInt(2, Game::server->GetPort()); insertStatement->execute(); delete insertStatement; From 8d37d9b6811c551be752788444cadeb923a39073 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 3 Nov 2022 10:57:54 -0700 Subject: [PATCH 118/322] Organize dScripts (#814) * Organize dScripts whitespace Remove parent scope Remove parent scope from initial setter Remove debug Remove helper programs * Fix NtImagimeterVisibility script Co-authored-by: aronwk-aaron <aronwk.aaron@gmail.com> --- CMakeLists.txt | 68 +++++ dGame/CMakeLists.txt | 3 +- dScripts/02_server/CMakeLists.txt | 45 +++ dScripts/02_server/DLU/CMakeLists.txt | 3 + dScripts/{ => 02_server/DLU}/DLUVanityNPC.cpp | 0 dScripts/{ => 02_server/DLU}/DLUVanityNPC.h | 0 .../Enemy/AG}/BossSpiderQueenEnemyServer.cpp | 0 .../Enemy/AG}/BossSpiderQueenEnemyServer.h | 0 dScripts/02_server/Enemy/AG/CMakeLists.txt | 3 + .../Enemy/AM}/AmDarklingDragon.cpp | 0 .../Enemy/AM}/AmDarklingDragon.h | 0 .../Enemy/AM}/AmDarklingMech.cpp | 0 .../{ => 02_server/Enemy/AM}/AmDarklingMech.h | 0 .../Enemy/AM}/AmSkeletonEngineer.cpp | 0 .../Enemy/AM}/AmSkeletonEngineer.h | 0 dScripts/02_server/Enemy/AM/CMakeLists.txt | 5 + dScripts/02_server/Enemy/CMakeLists.txt | 45 +++ dScripts/02_server/Enemy/FV/CMakeLists.txt | 4 + .../Enemy/FV}/FvMaelstromCavalry.cpp | 0 .../Enemy/FV}/FvMaelstromCavalry.h | 0 .../Enemy/FV}/FvMaelstromDragon.cpp | 0 .../Enemy/FV}/FvMaelstromDragon.h | 0 .../Enemy/General}/BaseEnemyApe.cpp | 0 .../Enemy/General}/BaseEnemyApe.h | 0 .../Enemy/General}/BaseEnemyMech.cpp | 0 .../Enemy/General}/BaseEnemyMech.h | 0 .../02_server/Enemy/General/CMakeLists.txt | 7 + .../Enemy/General}/EnemyNjBuff.cpp | 0 .../Enemy/General}/EnemyNjBuff.h | 0 .../Enemy/General}/GfApeSmashingQB.cpp | 0 .../Enemy/General}/GfApeSmashingQB.h | 0 .../General}/TreasureChestDragonServer.cpp | 0 .../General}/TreasureChestDragonServer.h | 0 .../Enemy/Survival}/AgSurvivalMech.cpp | 0 .../Enemy/Survival}/AgSurvivalMech.h | 0 .../Enemy/Survival}/AgSurvivalSpiderling.cpp | 0 .../Enemy/Survival}/AgSurvivalSpiderling.h | 0 .../Enemy/Survival}/AgSurvivalStromling.cpp | 0 .../Enemy/Survival}/AgSurvivalStromling.h | 0 .../02_server/Enemy/Survival/CMakeLists.txt | 5 + dScripts/02_server/Enemy/VE/CMakeLists.txt | 3 + dScripts/{ => 02_server/Enemy/VE}/VeMech.cpp | 0 dScripts/{ => 02_server/Enemy/VE}/VeMech.h | 0 dScripts/02_server/Enemy/Waves/CMakeLists.txt | 6 + .../Enemy/Waves}/WaveBossApe.cpp | 0 .../{ => 02_server/Enemy/Waves}/WaveBossApe.h | 0 .../Enemy/Waves}/WaveBossHammerling.cpp | 0 .../Enemy/Waves}/WaveBossHammerling.h | 0 .../Enemy/Waves}/WaveBossHorsemen.cpp | 0 .../Enemy/Waves}/WaveBossHorsemen.h | 0 .../Enemy/Waves}/WaveBossSpiderling.cpp | 0 .../Enemy/Waves}/WaveBossSpiderling.h | 0 .../Equipment}/BootyDigServer.cpp | 0 .../Equipment}/BootyDigServer.h | 0 dScripts/02_server/Equipment/CMakeLists.txt | 4 + .../MaestromExtracticatorServer.cpp | 0 .../Equipment}/MaestromExtracticatorServer.h | 0 .../{ => 02_server/Map/AG}/AgBugsprayer.cpp | 0 .../{ => 02_server/Map/AG}/AgBugsprayer.h | 0 .../Map/AG}/AgCagedBricksServer.cpp | 0 .../Map/AG}/AgCagedBricksServer.h | 0 .../Map/AG}/AgLaserSensorServer.cpp | 0 .../Map/AG}/AgLaserSensorServer.h | 0 .../Map/AG}/AgMonumentBirds.cpp | 0 .../{ => 02_server/Map/AG}/AgMonumentBirds.h | 0 .../Map/AG}/AgMonumentLaserServer.cpp | 0 .../Map/AG}/AgMonumentLaserServer.h | 0 .../Map/AG}/AgMonumentRaceCancel.cpp | 0 .../Map/AG}/AgMonumentRaceCancel.h | 0 .../Map/AG}/AgMonumentRaceGoal.cpp | 0 .../Map/AG}/AgMonumentRaceGoal.h | 0 dScripts/02_server/Map/AG/CMakeLists.txt | 16 + .../Map/AG}/NpcAgCourseStarter.cpp | 0 .../Map/AG}/NpcAgCourseStarter.h | 0 .../Map/AG}/NpcCowboyServer.cpp | 0 .../{ => 02_server/Map/AG}/NpcCowboyServer.h | 0 .../Map/AG}/NpcEpsilonServer.cpp | 0 .../{ => 02_server/Map/AG}/NpcEpsilonServer.h | 0 .../Map/AG}/NpcNjAssistantServer.cpp | 0 .../Map/AG}/NpcNjAssistantServer.h | 0 .../Map/AG}/NpcPirateServer.cpp | 0 .../{ => 02_server/Map/AG}/NpcPirateServer.h | 0 .../{ => 02_server/Map/AG}/NpcWispServer.cpp | 0 .../{ => 02_server/Map/AG}/NpcWispServer.h | 0 .../Map/AG}/RemoveRentalGear.cpp | 0 .../{ => 02_server/Map/AG}/RemoveRentalGear.h | 0 .../Map/AG_Spider_Queen/CMakeLists.txt | 4 + .../SpiderBossTreasureChestServer.cpp | 0 .../SpiderBossTreasureChestServer.h | 0 .../AG_Spider_Queen}/ZoneAgSpiderQueen.cpp | 0 .../Map/AG_Spider_Queen}/ZoneAgSpiderQueen.h | 0 dScripts/{ => 02_server/Map/AM}/AmBlueX.cpp | 0 dScripts/{ => 02_server/Map/AM}/AmBlueX.h | 0 dScripts/{ => 02_server/Map/AM}/AmBridge.cpp | 0 dScripts/{ => 02_server/Map/AM}/AmBridge.h | 0 .../Map/AM}/AmConsoleTeleportServer.cpp | 0 .../Map/AM}/AmConsoleTeleportServer.h | 0 .../{ => 02_server/Map/AM}/AmDrawBridge.cpp | 0 .../{ => 02_server/Map/AM}/AmDrawBridge.h | 0 .../Map/AM}/AmDropshipComputer.cpp | 0 .../Map/AM}/AmDropshipComputer.h | 0 .../Map/AM}/AmScrollReaderServer.cpp | 0 .../Map/AM}/AmScrollReaderServer.h | 0 .../Map/AM}/AmShieldGenerator.cpp | 0 .../Map/AM}/AmShieldGenerator.h | 0 .../Map/AM}/AmShieldGeneratorQuickbuild.cpp | 0 .../Map/AM}/AmShieldGeneratorQuickbuild.h | 0 .../Map/AM}/AmSkullkinDrill.cpp | 0 .../{ => 02_server/Map/AM}/AmSkullkinDrill.h | 0 .../Map/AM}/AmSkullkinDrillStand.cpp | 0 .../Map/AM}/AmSkullkinDrillStand.h | 0 .../Map/AM}/AmSkullkinTower.cpp | 0 .../{ => 02_server/Map/AM}/AmSkullkinTower.h | 0 .../{ => 02_server/Map/AM}/AmTeapotServer.cpp | 0 .../{ => 02_server/Map/AM}/AmTeapotServer.h | 0 .../Map/AM}/AmTemplateSkillVolume.cpp | 0 .../Map/AM}/AmTemplateSkillVolume.h | 0 dScripts/02_server/Map/AM/CMakeLists.txt | 19 ++ .../Map/AM}/RandomSpawnerFin.cpp | 0 .../{ => 02_server/Map/AM}/RandomSpawnerFin.h | 0 .../Map/AM}/RandomSpawnerPit.cpp | 0 .../{ => 02_server/Map/AM}/RandomSpawnerPit.h | 0 .../Map/AM}/RandomSpawnerStr.cpp | 0 .../{ => 02_server/Map/AM}/RandomSpawnerStr.h | 0 .../Map/AM}/RandomSpawnerZip.cpp | 0 .../{ => 02_server/Map/AM}/RandomSpawnerZip.h | 0 dScripts/02_server/Map/CMakeLists.txt | 81 +++++ dScripts/02_server/Map/FV/CMakeLists.txt | 14 + .../Map/FV}/EnemyRoninSpawner.cpp | 0 .../Map/FV}/EnemyRoninSpawner.h | 0 dScripts/{ => 02_server/Map/FV}/FvCandle.cpp | 0 dScripts/{ => 02_server/Map/FV}/FvCandle.h | 0 dScripts/{ => 02_server/Map/FV}/FvFong.cpp | 0 dScripts/{ => 02_server/Map/FV}/FvFong.h | 0 .../Map/FV}/FvHorsemenTrigger.cpp | 0 .../Map/FV}/FvHorsemenTrigger.h | 0 .../Map/FV}/ImgBrickConsoleQB.cpp | 0 .../Map/FV}/ImgBrickConsoleQB.h | 0 .../02_server/Map/FV/Racing/CMakeLists.txt | 3 + .../Map/FV/Racing}/RaceMaelstromGeiser.cpp | 0 .../Map/FV/Racing}/RaceMaelstromGeiser.h | 0 dScripts/02_server/Map/GF/CMakeLists.txt | 6 + .../Map/GF}/GfCaptainsCannon.cpp | 0 .../{ => 02_server/Map/GF}/GfCaptainsCannon.h | 0 .../{ => 02_server/Map/GF}/GfTikiTorch.cpp | 0 dScripts/{ => 02_server/Map/GF}/GfTikiTorch.h | 0 .../{ => 02_server/Map/GF}/MastTeleport.cpp | 0 .../{ => 02_server/Map/GF}/MastTeleport.h | 0 .../Map/GF}/SpawnLionServer.cpp | 0 .../{ => 02_server/Map/GF}/SpawnLionServer.h | 0 .../Map/General}/BankInteractServer.cpp | 0 .../Map/General}/BankInteractServer.h | 0 .../General}/BaseInteractDropLootServer.cpp | 0 .../Map/General}/BaseInteractDropLootServer.h | 0 .../Map/General}/Binoculars.cpp | 0 .../{ => 02_server/Map/General}/Binoculars.h | 0 dScripts/02_server/Map/General/CMakeLists.txt | 28 ++ .../Map/General}/ExplodingAsset.cpp | 0 .../Map/General}/ExplodingAsset.h | 0 .../Map/General}/ForceVolumeServer.cpp | 0 .../Map/General}/ForceVolumeServer.h | 0 .../Map/General}/GrowingFlower.cpp | 0 .../Map/General}/GrowingFlower.h | 0 .../ImaginationBackpackHealServer.cpp | 0 .../General}/ImaginationBackpackHealServer.h | 0 .../Map/General}/InvalidScript.cpp | 0 .../Map/General}/InvalidScript.h | 0 .../Map/General}/MailBoxServer.cpp | 0 .../Map/General}/MailBoxServer.h | 0 .../Map/General/Ninjago/CMakeLists.txt | 6 + .../General/Ninjago}/NjIceRailActivator.cpp | 0 .../Map/General/Ninjago}/NjIceRailActivator.h | 0 .../Ninjago}/NjRailActivatorsServer.cpp | 0 .../General/Ninjago}/NjRailActivatorsServer.h | 0 .../Map/General/Ninjago}/NjRailPostServer.cpp | 0 .../Map/General/Ninjago}/NjRailPostServer.h | 0 .../Ninjago}/NjhubLavaPlayerDeathTrigger.cpp | 0 .../Ninjago}/NjhubLavaPlayerDeathTrigger.h | 0 .../Map/General}/NjRailSwitch.cpp | 0 .../Map/General}/NjRailSwitch.h | 0 .../Map/General}/PetDigServer.cpp | 0 .../Map/General}/PetDigServer.h | 0 .../Map/General}/PropertyDevice.cpp | 0 .../Map/General}/PropertyDevice.h | 0 .../Map/General}/PropertyPlatform.cpp | 0 .../Map/General}/PropertyPlatform.h | 0 .../Map/General}/QbEnemyStunner.cpp | 0 .../Map/General}/QbEnemyStunner.h | 0 .../{ => 02_server/Map/General}/QbSpawner.cpp | 0 .../{ => 02_server/Map/General}/QbSpawner.h | 0 .../Map/General}/StoryBoxInteractServer.cpp | 0 .../Map/General}/StoryBoxInteractServer.h | 0 .../Map/General}/TokenConsoleServer.cpp | 0 .../Map/General}/TokenConsoleServer.h | 0 .../Map/General}/TouchMissionUpdateServer.cpp | 0 .../Map/General}/TouchMissionUpdateServer.h | 0 .../Map/General}/WishingWellServer.cpp | 0 .../Map/General}/WishingWellServer.h | 0 dScripts/02_server/Map/NS/CMakeLists.txt | 13 + .../Map/NS}/NsConcertChoiceBuildManager.cpp | 0 .../Map/NS}/NsConcertChoiceBuildManager.h | 0 .../{ => 02_server/Map/NS}/NsLegoClubDoor.cpp | 0 .../{ => 02_server/Map/NS}/NsLegoClubDoor.h | 0 .../{ => 02_server/Map/NS}/NsLupTeleport.cpp | 0 .../{ => 02_server/Map/NS}/NsLupTeleport.h | 0 .../Map/NS}/NsTokenConsoleServer.cpp | 0 .../Map/NS}/NsTokenConsoleServer.h | 0 .../02_server/Map/NS/Waves/CMakeLists.txt | 3 + .../Map/NS/Waves}/ZoneNsWaves.cpp | 0 .../Map/NS/Waves}/ZoneNsWaves.h | 0 dScripts/02_server/Map/NT/CMakeLists.txt | 26 ++ .../Map/NT}/NtAssemblyTubeServer.cpp | 0 .../Map/NT}/NtAssemblyTubeServer.h | 0 .../Map/NT}/NtBeamImaginationCollectors.cpp | 0 .../Map/NT}/NtBeamImaginationCollectors.h | 0 .../Map/NT}/NtCombatChallengeDummy.cpp | 0 .../Map/NT}/NtCombatChallengeDummy.h | 0 .../NT}/NtCombatChallengeExplodingDummy.cpp | 0 .../Map/NT}/NtCombatChallengeExplodingDummy.h | 0 .../Map/NT}/NtCombatChallengeServer.cpp | 0 .../Map/NT}/NtCombatChallengeServer.h | 0 .../Map/NT}/NtConsoleTeleportServer.cpp | 0 .../Map/NT}/NtConsoleTeleportServer.h | 0 .../Map/NT}/NtDarkitectRevealServer.cpp | 0 .../Map/NT}/NtDarkitectRevealServer.h | 0 .../Map/NT}/NtDirtCloudServer.cpp | 0 .../Map/NT}/NtDirtCloudServer.h | 0 .../{ => 02_server/Map/NT}/NtDukeServer.cpp | 0 .../{ => 02_server/Map/NT}/NtDukeServer.h | 0 .../{ => 02_server/Map/NT}/NtHaelServer.cpp | 0 .../{ => 02_server/Map/NT}/NtHaelServer.h | 0 .../Map/NT}/NtImagBeamBuffer.cpp | 0 .../{ => 02_server/Map/NT}/NtImagBeamBuffer.h | 0 .../Map/NT}/NtImagimeterVisibility.cpp | 0 .../Map/NT}/NtImagimeterVisibility.h | 0 .../Map/NT}/NtOverbuildServer.cpp | 0 .../Map/NT}/NtOverbuildServer.h | 0 .../Map/NT}/NtParadoxPanelServer.cpp | 0 .../Map/NT}/NtParadoxPanelServer.h | 0 .../Map/NT}/NtParadoxTeleServer.cpp | 0 .../Map/NT}/NtParadoxTeleServer.h | 0 .../Map/NT}/NtSentinelWalkwayServer.cpp | 0 .../Map/NT}/NtSentinelWalkwayServer.h | 0 .../Map/NT}/NtSleepingGuard.cpp | 0 .../{ => 02_server/Map/NT}/NtSleepingGuard.h | 0 .../{ => 02_server/Map/NT}/NtVandaServer.cpp | 0 .../{ => 02_server/Map/NT}/NtVandaServer.h | 0 .../Map/NT}/NtVentureCannonServer.cpp | 0 .../Map/NT}/NtVentureCannonServer.h | 0 .../Map/NT}/NtVentureSpeedPadServer.cpp | 0 .../Map/NT}/NtVentureSpeedPadServer.h | 0 .../{ => 02_server/Map/NT}/NtXRayServer.cpp | 0 .../{ => 02_server/Map/NT}/NtXRayServer.h | 0 .../Map/NT}/SpawnSaberCatServer.cpp | 0 .../Map/NT}/SpawnSaberCatServer.h | 0 .../Map/NT}/SpawnShrakeServer.cpp | 0 .../Map/NT}/SpawnShrakeServer.h | 0 .../Map/NT}/SpawnStegoServer.cpp | 0 .../{ => 02_server/Map/NT}/SpawnStegoServer.h | 0 dScripts/02_server/Map/PR/CMakeLists.txt | 5 + .../{ => 02_server/Map/PR}/HydrantBroken.cpp | 0 .../{ => 02_server/Map/PR}/HydrantBroken.h | 0 .../{ => 02_server/Map/PR}/PrSeagullFly.cpp | 0 .../{ => 02_server/Map/PR}/PrSeagullFly.h | 0 .../Map/PR}/SpawnGryphonServer.cpp | 0 .../Map/PR}/SpawnGryphonServer.h | 0 .../Map/Property/AG_Med/CMakeLists.txt | 3 + .../Property/AG_Med}/ZoneAgMedProperty.cpp | 0 .../Map/Property/AG_Med}/ZoneAgMedProperty.h | 0 .../Map/Property/AG_Small/CMakeLists.txt | 4 + .../Property/AG_Small}/EnemySpiderSpawner.cpp | 0 .../Property/AG_Small}/EnemySpiderSpawner.h | 0 .../Map/Property/AG_Small}/ZoneAgProperty.cpp | 0 .../Map/Property/AG_Small}/ZoneAgProperty.h | 0 .../02_server/Map/Property/CMakeLists.txt | 22 ++ .../Map/Property/NS_Med/CMakeLists.txt | 3 + .../Property/NS_Med}/ZoneNsMedProperty.cpp | 0 .../Map/Property/NS_Med}/ZoneNsMedProperty.h | 0 .../Map/Property}/PropertyBankInteract.cpp | 0 .../Map/Property}/PropertyBankInteract.h | 0 dScripts/02_server/Map/SS/CMakeLists.txt | 3 + .../Map/SS}/SsModularBuildServer.cpp | 0 .../Map/SS}/SsModularBuildServer.h | 0 dScripts/02_server/Map/VE/CMakeLists.txt | 5 + .../Map/VE}/VeBricksampleServer.cpp | 0 .../Map/VE}/VeBricksampleServer.h | 0 .../Map/VE}/VeEpsilonServer.cpp | 0 .../{ => 02_server/Map/VE}/VeEpsilonServer.h | 0 .../Map/VE}/VeMissionConsole.cpp | 0 .../{ => 02_server/Map/VE}/VeMissionConsole.h | 0 .../{ => 02_server/Map/njhub}/BurningTile.cpp | 0 .../{ => 02_server/Map/njhub}/BurningTile.h | 0 dScripts/02_server/Map/njhub/CMakeLists.txt | 31 ++ .../Map/njhub}/CatapultBaseServer.cpp | 0 .../Map/njhub}/CatapultBaseServer.h | 0 .../Map/njhub}/CatapultBouncerServer.cpp | 0 .../Map/njhub}/CatapultBouncerServer.h | 0 .../Map/njhub}/CavePrisonCage.cpp | 0 .../Map/njhub}/CavePrisonCage.h | 0 .../Map/njhub}/EnemySkeletonSpawner.cpp | 0 .../Map/njhub}/EnemySkeletonSpawner.h | 0 .../{ => 02_server/Map/njhub}/FallingTile.cpp | 0 .../{ => 02_server/Map/njhub}/FallingTile.h | 0 .../Map/njhub}/FlameJetServer.cpp | 0 .../Map/njhub}/FlameJetServer.h | 0 .../Map/njhub}/ImaginationShrineServer.cpp | 0 .../Map/njhub}/ImaginationShrineServer.h | 0 .../{ => 02_server/Map/njhub}/Lieutenant.cpp | 0 .../{ => 02_server/Map/njhub}/Lieutenant.h | 0 .../Map/njhub}/MonCoreNookDoors.cpp | 0 .../Map/njhub}/MonCoreNookDoors.h | 0 .../Map/njhub}/MonCoreSmashableDoors.cpp | 0 .../Map/njhub}/MonCoreSmashableDoors.h | 0 .../{ => 02_server/Map/njhub}/NjColeNPC.cpp | 0 .../{ => 02_server/Map/njhub}/NjColeNPC.h | 0 .../Map/njhub}/NjDragonEmblemChestServer.cpp | 0 .../Map/njhub}/NjDragonEmblemChestServer.h | 0 .../Map/njhub}/NjEarthDragonPetServer.cpp | 0 .../Map/njhub}/NjEarthDragonPetServer.h | 0 .../Map/njhub}/NjEarthPetServer.cpp | 0 .../Map/njhub}/NjEarthPetServer.h | 0 .../Map/njhub}/NjGarmadonCelebration.cpp | 0 .../Map/njhub}/NjGarmadonCelebration.h | 0 .../Map/njhub}/NjJayMissionItems.cpp | 0 .../Map/njhub}/NjJayMissionItems.h | 0 .../njhub}/NjNPCMissionSpinjitzuServer.cpp | 0 .../Map/njhub}/NjNPCMissionSpinjitzuServer.h | 0 .../Map/njhub}/NjNyaMissionitems.cpp | 0 .../Map/njhub}/NjNyaMissionitems.h | 0 .../Map/njhub}/NjScrollChestServer.cpp | 0 .../Map/njhub}/NjScrollChestServer.h | 0 .../{ => 02_server/Map/njhub}/NjWuNPC.cpp | 0 dScripts/{ => 02_server/Map/njhub}/NjWuNPC.h | 0 .../Map/njhub}/RainOfArrows.cpp | 0 .../{ => 02_server/Map/njhub}/RainOfArrows.h | 0 .../Map/njhub/boss_instance/CMakeLists.txt | 3 + .../boss_instance}/NjMonastryBossInstance.cpp | 0 .../boss_instance}/NjMonastryBossInstance.h | 0 dScripts/02_server/Minigame/CMakeLists.txt | 9 + .../02_server/Minigame/General/CMakeLists.txt | 3 + .../General}/MinigameTreasureChestServer.cpp | 0 .../General}/MinigameTreasureChestServer.h | 0 .../Objects}/AgSurvivalBuffStation.cpp | 0 .../Objects}/AgSurvivalBuffStation.h | 0 dScripts/02_server/Objects/CMakeLists.txt | 4 + .../Objects}/StinkyFishTarget.cpp | 0 .../Objects}/StinkyFishTarget.h | 0 dScripts/02_server/Pets/CMakeLists.txt | 5 + .../{ => 02_server/Pets}/DamagingPets.cpp | 0 dScripts/{ => 02_server/Pets}/DamagingPets.h | 0 .../{ => 02_server/Pets}/PetFromDigServer.cpp | 0 .../{ => 02_server/Pets}/PetFromDigServer.h | 0 .../Pets}/PetFromObjectServer.cpp | 0 .../Pets}/PetFromObjectServer.h | 0 dScripts/CMakeLists.txt | 285 +++--------------- .../{ => EquipmentScripts}/AnvilOfArmor.cpp | 0 .../{ => EquipmentScripts}/AnvilOfArmor.h | 0 .../BuccaneerValiantShip.cpp | 0 .../BuccaneerValiantShip.h | 0 dScripts/EquipmentScripts/CMakeLists.txt | 9 + .../{ => EquipmentScripts}/CauldronOfLife.cpp | 0 .../{ => EquipmentScripts}/CauldronOfLife.h | 0 .../FireFirstSkillonStartup.cpp | 0 .../FireFirstSkillonStartup.h | 0 .../FountainOfImagination.cpp | 0 .../FountainOfImagination.h | 0 .../PersonalFortress.cpp | 0 .../{ => EquipmentScripts}/PersonalFortress.h | 0 dScripts/{ => EquipmentScripts}/Sunflower.cpp | 0 dScripts/{ => EquipmentScripts}/Sunflower.h | 0 dScripts/{ => ai/ACT}/ActMine.cpp | 0 dScripts/{ => ai/ACT}/ActMine.h | 0 .../{ => ai/ACT}/ActPlayerDeathTrigger.cpp | 0 dScripts/{ => ai/ACT}/ActPlayerDeathTrigger.h | 0 .../{ => ai/ACT}/ActVehicleDeathTrigger.cpp | 0 .../{ => ai/ACT}/ActVehicleDeathTrigger.h | 0 dScripts/ai/ACT/CMakeLists.txt | 12 + .../ACT/FootRace}/BaseFootRaceManager.cpp | 0 .../ACT/FootRace}/BaseFootRaceManager.h | 0 dScripts/ai/ACT/FootRace/CMakeLists.txt | 3 + .../AG}/ActSharkPlayerDeathTrigger.cpp | 0 .../{ => ai/AG}/ActSharkPlayerDeathTrigger.h | 0 dScripts/{ => ai/AG}/AgBusDoor.cpp | 0 dScripts/{ => ai/AG}/AgBusDoor.h | 0 dScripts/{ => ai/AG}/AgDarkSpiderling.cpp | 0 dScripts/{ => ai/AG}/AgDarkSpiderling.h | 0 dScripts/{ => ai/AG}/AgFans.cpp | 0 dScripts/{ => ai/AG}/AgFans.h | 0 dScripts/{ => ai/AG}/AgImagSmashable.cpp | 0 dScripts/{ => ai/AG}/AgImagSmashable.h | 0 dScripts/{ => ai/AG}/AgJetEffectServer.cpp | 0 dScripts/{ => ai/AG}/AgJetEffectServer.h | 0 dScripts/{ => ai/AG}/AgPicnicBlanket.cpp | 0 dScripts/{ => ai/AG}/AgPicnicBlanket.h | 0 dScripts/{ => ai/AG}/AgQbElevator.cpp | 0 dScripts/{ => ai/AG}/AgQbElevator.h | 0 dScripts/{ => ai/AG}/AgQbWall.cpp | 0 dScripts/{ => ai/AG}/AgQbWall.h | 0 dScripts/{ => ai/AG}/AgSalutingNpcs.cpp | 0 dScripts/{ => ai/AG}/AgSalutingNpcs.h | 0 .../{ => ai/AG}/AgShipPlayerDeathTrigger.cpp | 0 .../{ => ai/AG}/AgShipPlayerDeathTrigger.h | 0 .../{ => ai/AG}/AgShipPlayerShockServer.cpp | 0 .../{ => ai/AG}/AgShipPlayerShockServer.h | 0 dScripts/{ => ai/AG}/AgSpaceStuff.cpp | 0 dScripts/{ => ai/AG}/AgSpaceStuff.h | 0 dScripts/{ => ai/AG}/AgStagePlatforms.cpp | 0 dScripts/{ => ai/AG}/AgStagePlatforms.h | 0 dScripts/{ => ai/AG}/AgStromlingProperty.cpp | 0 dScripts/{ => ai/AG}/AgStromlingProperty.h | 0 dScripts/{ => ai/AG}/AgTurret.cpp | 0 dScripts/{ => ai/AG}/AgTurret.h | 0 dScripts/ai/AG/CMakeLists.txt | 18 ++ dScripts/ai/CMakeLists.txt | 81 +++++ dScripts/{ => ai/FV}/ActNinjaTurret.cpp | 0 dScripts/{ => ai/FV}/ActNinjaTurret.h | 0 dScripts/{ => ai/FV}/ActParadoxPipeFix.cpp | 0 dScripts/{ => ai/FV}/ActParadoxPipeFix.h | 0 dScripts/ai/FV/CMakeLists.txt | 18 ++ dScripts/{ => ai/FV}/FvBounceOverWall.cpp | 0 dScripts/{ => ai/FV}/FvBounceOverWall.h | 0 dScripts/{ => ai/FV}/FvBrickPuzzleServer.cpp | 0 dScripts/{ => ai/FV}/FvBrickPuzzleServer.h | 0 .../{ => ai/FV}/FvConsoleLeftQuickbuild.cpp | 0 .../{ => ai/FV}/FvConsoleLeftQuickbuild.h | 0 .../{ => ai/FV}/FvConsoleRightQuickbuild.cpp | 0 .../{ => ai/FV}/FvConsoleRightQuickbuild.h | 0 .../{ => ai/FV}/FvDragonSmashingGolemQb.cpp | 0 .../{ => ai/FV}/FvDragonSmashingGolemQb.h | 0 dScripts/{ => ai/FV}/FvFacilityBrick.cpp | 0 dScripts/{ => ai/FV}/FvFacilityBrick.h | 0 dScripts/{ => ai/FV}/FvFacilityPipes.cpp | 0 dScripts/{ => ai/FV}/FvFacilityPipes.h | 0 .../{ => ai/FV}/FvFlyingCreviceDragon.cpp | 0 dScripts/{ => ai/FV}/FvFlyingCreviceDragon.h | 0 dScripts/{ => ai/FV}/FvFreeGfNinjas.cpp | 0 dScripts/{ => ai/FV}/FvFreeGfNinjas.h | 0 dScripts/{ => ai/FV}/FvMaelstromGeyser.cpp | 0 dScripts/{ => ai/FV}/FvMaelstromGeyser.h | 0 dScripts/{ => ai/FV}/FvNinjaGuard.cpp | 0 dScripts/{ => ai/FV}/FvNinjaGuard.h | 0 dScripts/{ => ai/FV}/FvPandaServer.cpp | 0 dScripts/{ => ai/FV}/FvPandaServer.h | 0 dScripts/{ => ai/FV}/FvPandaSpawnerServer.cpp | 0 dScripts/{ => ai/FV}/FvPandaSpawnerServer.h | 0 dScripts/{ => ai/FV}/FvPassThroughWall.cpp | 0 dScripts/{ => ai/FV}/FvPassThroughWall.h | 0 dScripts/ai/GENERAL/CMakeLists.txt | 4 + ...nceExitTransferPlayerToLastNonInstance.cpp | 0 ...tanceExitTransferPlayerToLastNonInstance.h | 0 dScripts/{ => ai/GENERAL}/LegoDieRoll.cpp | 0 dScripts/{ => ai/GENERAL}/LegoDieRoll.h | 0 dScripts/ai/GF/CMakeLists.txt | 14 + dScripts/{ => ai/GF}/GfArchway.cpp | 0 dScripts/{ => ai/GF}/GfArchway.h | 0 dScripts/{ => ai/GF}/GfBanana.cpp | 0 dScripts/{ => ai/GF}/GfBanana.h | 0 dScripts/{ => ai/GF}/GfBananaCluster.cpp | 0 dScripts/{ => ai/GF}/GfBananaCluster.h | 0 dScripts/{ => ai/GF}/GfCampfire.cpp | 0 dScripts/{ => ai/GF}/GfCampfire.h | 0 dScripts/{ => ai/GF}/GfJailWalls.cpp | 0 dScripts/{ => ai/GF}/GfJailWalls.h | 0 dScripts/{ => ai/GF}/GfJailkeepMission.cpp | 0 dScripts/{ => ai/GF}/GfJailkeepMission.h | 0 dScripts/{ => ai/GF}/GfMaelstromGeyser.cpp | 0 dScripts/{ => ai/GF}/GfMaelstromGeyser.h | 0 dScripts/{ => ai/GF}/GfOrgan.cpp | 0 dScripts/{ => ai/GF}/GfOrgan.h | 0 dScripts/{ => ai/GF}/GfParrotCrash.cpp | 0 dScripts/{ => ai/GF}/GfParrotCrash.h | 0 dScripts/{ => ai/GF}/PetDigBuild.cpp | 0 dScripts/{ => ai/GF}/PetDigBuild.h | 0 dScripts/{ => ai/GF}/PirateRep.cpp | 0 dScripts/{ => ai/GF}/PirateRep.h | 0 dScripts/{ => ai/GF}/TriggerAmbush.cpp | 0 dScripts/{ => ai/GF}/TriggerAmbush.h | 0 dScripts/ai/MINIGAME/CMakeLists.txt | 9 + dScripts/ai/MINIGAME/SG_GF/CMakeLists.txt | 10 + .../ai/MINIGAME/SG_GF/SERVER/CMakeLists.txt | 3 + .../MINIGAME/SG_GF/SERVER}/SGCannon.cpp | 0 .../{ => ai/MINIGAME/SG_GF/SERVER}/SGCannon.h | 0 .../{ => ai/MINIGAME/SG_GF}/ZoneSGServer.cpp | 0 .../{ => ai/MINIGAME/SG_GF}/ZoneSGServer.h | 0 dScripts/ai/NP/CMakeLists.txt | 3 + dScripts/{ => ai/NP}/NpcNpSpacemanBob.cpp | 0 dScripts/{ => ai/NP}/NpcNpSpacemanBob.h | 0 dScripts/ai/NS/CMakeLists.txt | 24 ++ dScripts/{ => ai/NS}/ClRing.cpp | 0 dScripts/{ => ai/NS}/ClRing.h | 0 dScripts/ai/NS/NS_PP_01/CMakeLists.txt | 3 + .../NS/NS_PP_01}/PropertyDeathPlane.cpp | 0 .../{ => ai/NS/NS_PP_01}/PropertyDeathPlane.h | 0 dScripts/{ => ai/NS}/NsConcertChoiceBuild.cpp | 0 dScripts/{ => ai/NS}/NsConcertChoiceBuild.h | 0 dScripts/{ => ai/NS}/NsConcertInstrument.cpp | 0 dScripts/{ => ai/NS}/NsConcertInstrument.h | 0 dScripts/{ => ai/NS}/NsConcertQuickBuild.cpp | 0 dScripts/{ => ai/NS}/NsConcertQuickBuild.h | 0 .../{ => ai/NS}/NsGetFactionMissionServer.cpp | 0 .../{ => ai/NS}/NsGetFactionMissionServer.h | 0 .../{ => ai/NS}/NsJohnnyMissionServer.cpp | 0 dScripts/{ => ai/NS}/NsJohnnyMissionServer.h | 0 dScripts/{ => ai/NS}/NsModularBuild.cpp | 0 dScripts/{ => ai/NS}/NsModularBuild.h | 0 .../{ => ai/NS}/NsQbImaginationStatue.cpp | 0 dScripts/{ => ai/NS}/NsQbImaginationStatue.h | 0 dScripts/ai/NS/WH/CMakeLists.txt | 4 + dScripts/{ => ai/NS/WH}/RockHydrantBroken.cpp | 0 dScripts/{ => ai/NS/WH}/RockHydrantBroken.h | 0 .../{ => ai/NS/WH}/RockHydrantSmashable.cpp | 0 .../{ => ai/NS/WH}/RockHydrantSmashable.h | 0 dScripts/{ => ai/NS}/WhFans.cpp | 0 dScripts/{ => ai/NS}/WhFans.h | 0 dScripts/ai/PETS/CMakeLists.txt | 3 + dScripts/{ => ai/PETS}/HydrantSmashable.cpp | 0 dScripts/{ => ai/PETS}/HydrantSmashable.h | 0 dScripts/{ => ai/PROPERTY/AG}/AgPropGuard.cpp | 0 dScripts/{ => ai/PROPERTY/AG}/AgPropGuard.h | 0 dScripts/ai/PROPERTY/AG/CMakeLists.txt | 3 + dScripts/{ => ai/PROPERTY}/AgPropguards.cpp | 0 dScripts/{ => ai/PROPERTY}/AgPropguards.h | 0 dScripts/ai/PROPERTY/CMakeLists.txt | 11 + .../{ => ai/PROPERTY}/PropertyFXDamage.cpp | 0 dScripts/{ => ai/PROPERTY}/PropertyFXDamage.h | 0 dScripts/ai/RACING/CMakeLists.txt | 9 + dScripts/ai/RACING/OBJECTS/CMakeLists.txt | 6 + .../OBJECTS}/FvRaceSmashEggImagineServer.cpp | 0 .../OBJECTS}/FvRaceSmashEggImagineServer.h | 0 .../OBJECTS}/RaceImagineCrateServer.cpp | 0 .../RACING/OBJECTS}/RaceImagineCrateServer.h | 0 .../RACING/OBJECTS}/RaceImaginePowerup.cpp | 0 .../RACING/OBJECTS}/RaceImaginePowerup.h | 0 .../RACING/OBJECTS}/RaceSmashServer.cpp | 0 .../{ => ai/RACING/OBJECTS}/RaceSmashServer.h | 0 dScripts/ai/SPEC/CMakeLists.txt | 3 + .../SPEC}/SpecialImaginePowerupSpawner.cpp | 0 .../SPEC}/SpecialImaginePowerupSpawner.h | 0 dScripts/{ => ai/WILD}/AllCrateChicken.cpp | 0 dScripts/{ => ai/WILD}/AllCrateChicken.h | 0 dScripts/ai/WILD/CMakeLists.txt | 4 + dScripts/{ => ai/WILD}/WildAmbients.cpp | 0 dScripts/{ => ai/WILD}/WildAmbients.h | 0 dScripts/client/CMakeLists.txt | 9 + dScripts/client/ai/CMakeLists.txt | 9 + dScripts/client/ai/PR/CMakeLists.txt | 4 + dScripts/{ => client/ai/PR}/CrabServer.cpp | 0 dScripts/{ => client/ai/PR}/CrabServer.h | 0 dScripts/{ => client/ai/PR}/PrWhistle.cpp | 0 dScripts/{ => client/ai/PR}/PrWhistle.h | 0 dScripts/zone/AG/CMakeLists.txt | 3 + dScripts/{ => zone/AG}/ZoneAgSurvival.cpp | 0 dScripts/{ => zone/AG}/ZoneAgSurvival.h | 0 dScripts/zone/CMakeLists.txt | 21 ++ dScripts/zone/LUPs/CMakeLists.txt | 3 + dScripts/{ => zone/LUPs}/WblGenericZone.cpp | 0 dScripts/{ => zone/LUPs}/WblGenericZone.h | 0 dScripts/zone/PROPERTY/CMakeLists.txt | 21 ++ dScripts/zone/PROPERTY/FV/CMakeLists.txt | 3 + .../{ => zone/PROPERTY/FV}/ZoneFvProperty.cpp | 0 .../{ => zone/PROPERTY/FV}/ZoneFvProperty.h | 0 dScripts/zone/PROPERTY/GF/CMakeLists.txt | 3 + .../{ => zone/PROPERTY/GF}/ZoneGfProperty.cpp | 0 .../{ => zone/PROPERTY/GF}/ZoneGfProperty.h | 0 dScripts/zone/PROPERTY/NS/CMakeLists.txt | 3 + .../{ => zone/PROPERTY/NS}/ZoneNsProperty.cpp | 0 .../{ => zone/PROPERTY/NS}/ZoneNsProperty.h | 0 567 files changed, 886 insertions(+), 252 deletions(-) create mode 100644 dScripts/02_server/CMakeLists.txt create mode 100644 dScripts/02_server/DLU/CMakeLists.txt rename dScripts/{ => 02_server/DLU}/DLUVanityNPC.cpp (100%) rename dScripts/{ => 02_server/DLU}/DLUVanityNPC.h (100%) rename dScripts/{ => 02_server/Enemy/AG}/BossSpiderQueenEnemyServer.cpp (100%) rename dScripts/{ => 02_server/Enemy/AG}/BossSpiderQueenEnemyServer.h (100%) create mode 100644 dScripts/02_server/Enemy/AG/CMakeLists.txt rename dScripts/{ => 02_server/Enemy/AM}/AmDarklingDragon.cpp (100%) rename dScripts/{ => 02_server/Enemy/AM}/AmDarklingDragon.h (100%) rename dScripts/{ => 02_server/Enemy/AM}/AmDarklingMech.cpp (100%) rename dScripts/{ => 02_server/Enemy/AM}/AmDarklingMech.h (100%) rename dScripts/{ => 02_server/Enemy/AM}/AmSkeletonEngineer.cpp (100%) rename dScripts/{ => 02_server/Enemy/AM}/AmSkeletonEngineer.h (100%) create mode 100644 dScripts/02_server/Enemy/AM/CMakeLists.txt create mode 100644 dScripts/02_server/Enemy/CMakeLists.txt create mode 100644 dScripts/02_server/Enemy/FV/CMakeLists.txt rename dScripts/{ => 02_server/Enemy/FV}/FvMaelstromCavalry.cpp (100%) rename dScripts/{ => 02_server/Enemy/FV}/FvMaelstromCavalry.h (100%) rename dScripts/{ => 02_server/Enemy/FV}/FvMaelstromDragon.cpp (100%) rename dScripts/{ => 02_server/Enemy/FV}/FvMaelstromDragon.h (100%) rename dScripts/{ => 02_server/Enemy/General}/BaseEnemyApe.cpp (100%) rename dScripts/{ => 02_server/Enemy/General}/BaseEnemyApe.h (100%) rename dScripts/{ => 02_server/Enemy/General}/BaseEnemyMech.cpp (100%) rename dScripts/{ => 02_server/Enemy/General}/BaseEnemyMech.h (100%) create mode 100644 dScripts/02_server/Enemy/General/CMakeLists.txt rename dScripts/{ => 02_server/Enemy/General}/EnemyNjBuff.cpp (100%) rename dScripts/{ => 02_server/Enemy/General}/EnemyNjBuff.h (100%) rename dScripts/{ => 02_server/Enemy/General}/GfApeSmashingQB.cpp (100%) rename dScripts/{ => 02_server/Enemy/General}/GfApeSmashingQB.h (100%) rename dScripts/{ => 02_server/Enemy/General}/TreasureChestDragonServer.cpp (100%) rename dScripts/{ => 02_server/Enemy/General}/TreasureChestDragonServer.h (100%) rename dScripts/{ => 02_server/Enemy/Survival}/AgSurvivalMech.cpp (100%) rename dScripts/{ => 02_server/Enemy/Survival}/AgSurvivalMech.h (100%) rename dScripts/{ => 02_server/Enemy/Survival}/AgSurvivalSpiderling.cpp (100%) rename dScripts/{ => 02_server/Enemy/Survival}/AgSurvivalSpiderling.h (100%) rename dScripts/{ => 02_server/Enemy/Survival}/AgSurvivalStromling.cpp (100%) rename dScripts/{ => 02_server/Enemy/Survival}/AgSurvivalStromling.h (100%) create mode 100644 dScripts/02_server/Enemy/Survival/CMakeLists.txt create mode 100644 dScripts/02_server/Enemy/VE/CMakeLists.txt rename dScripts/{ => 02_server/Enemy/VE}/VeMech.cpp (100%) rename dScripts/{ => 02_server/Enemy/VE}/VeMech.h (100%) create mode 100644 dScripts/02_server/Enemy/Waves/CMakeLists.txt rename dScripts/{ => 02_server/Enemy/Waves}/WaveBossApe.cpp (100%) rename dScripts/{ => 02_server/Enemy/Waves}/WaveBossApe.h (100%) rename dScripts/{ => 02_server/Enemy/Waves}/WaveBossHammerling.cpp (100%) rename dScripts/{ => 02_server/Enemy/Waves}/WaveBossHammerling.h (100%) rename dScripts/{ => 02_server/Enemy/Waves}/WaveBossHorsemen.cpp (100%) rename dScripts/{ => 02_server/Enemy/Waves}/WaveBossHorsemen.h (100%) rename dScripts/{ => 02_server/Enemy/Waves}/WaveBossSpiderling.cpp (100%) rename dScripts/{ => 02_server/Enemy/Waves}/WaveBossSpiderling.h (100%) rename dScripts/{ => 02_server/Equipment}/BootyDigServer.cpp (100%) rename dScripts/{ => 02_server/Equipment}/BootyDigServer.h (100%) create mode 100644 dScripts/02_server/Equipment/CMakeLists.txt rename dScripts/{ => 02_server/Equipment}/MaestromExtracticatorServer.cpp (100%) rename dScripts/{ => 02_server/Equipment}/MaestromExtracticatorServer.h (100%) rename dScripts/{ => 02_server/Map/AG}/AgBugsprayer.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/AgBugsprayer.h (100%) rename dScripts/{ => 02_server/Map/AG}/AgCagedBricksServer.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/AgCagedBricksServer.h (100%) rename dScripts/{ => 02_server/Map/AG}/AgLaserSensorServer.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/AgLaserSensorServer.h (100%) rename dScripts/{ => 02_server/Map/AG}/AgMonumentBirds.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/AgMonumentBirds.h (100%) rename dScripts/{ => 02_server/Map/AG}/AgMonumentLaserServer.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/AgMonumentLaserServer.h (100%) rename dScripts/{ => 02_server/Map/AG}/AgMonumentRaceCancel.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/AgMonumentRaceCancel.h (100%) rename dScripts/{ => 02_server/Map/AG}/AgMonumentRaceGoal.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/AgMonumentRaceGoal.h (100%) create mode 100644 dScripts/02_server/Map/AG/CMakeLists.txt rename dScripts/{ => 02_server/Map/AG}/NpcAgCourseStarter.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/NpcAgCourseStarter.h (100%) rename dScripts/{ => 02_server/Map/AG}/NpcCowboyServer.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/NpcCowboyServer.h (100%) rename dScripts/{ => 02_server/Map/AG}/NpcEpsilonServer.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/NpcEpsilonServer.h (100%) rename dScripts/{ => 02_server/Map/AG}/NpcNjAssistantServer.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/NpcNjAssistantServer.h (100%) rename dScripts/{ => 02_server/Map/AG}/NpcPirateServer.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/NpcPirateServer.h (100%) rename dScripts/{ => 02_server/Map/AG}/NpcWispServer.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/NpcWispServer.h (100%) rename dScripts/{ => 02_server/Map/AG}/RemoveRentalGear.cpp (100%) rename dScripts/{ => 02_server/Map/AG}/RemoveRentalGear.h (100%) create mode 100644 dScripts/02_server/Map/AG_Spider_Queen/CMakeLists.txt rename dScripts/{ => 02_server/Map/AG_Spider_Queen}/SpiderBossTreasureChestServer.cpp (100%) rename dScripts/{ => 02_server/Map/AG_Spider_Queen}/SpiderBossTreasureChestServer.h (100%) rename dScripts/{ => 02_server/Map/AG_Spider_Queen}/ZoneAgSpiderQueen.cpp (100%) rename dScripts/{ => 02_server/Map/AG_Spider_Queen}/ZoneAgSpiderQueen.h (100%) rename dScripts/{ => 02_server/Map/AM}/AmBlueX.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/AmBlueX.h (100%) rename dScripts/{ => 02_server/Map/AM}/AmBridge.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/AmBridge.h (100%) rename dScripts/{ => 02_server/Map/AM}/AmConsoleTeleportServer.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/AmConsoleTeleportServer.h (100%) rename dScripts/{ => 02_server/Map/AM}/AmDrawBridge.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/AmDrawBridge.h (100%) rename dScripts/{ => 02_server/Map/AM}/AmDropshipComputer.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/AmDropshipComputer.h (100%) rename dScripts/{ => 02_server/Map/AM}/AmScrollReaderServer.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/AmScrollReaderServer.h (100%) rename dScripts/{ => 02_server/Map/AM}/AmShieldGenerator.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/AmShieldGenerator.h (100%) rename dScripts/{ => 02_server/Map/AM}/AmShieldGeneratorQuickbuild.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/AmShieldGeneratorQuickbuild.h (100%) rename dScripts/{ => 02_server/Map/AM}/AmSkullkinDrill.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/AmSkullkinDrill.h (100%) rename dScripts/{ => 02_server/Map/AM}/AmSkullkinDrillStand.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/AmSkullkinDrillStand.h (100%) rename dScripts/{ => 02_server/Map/AM}/AmSkullkinTower.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/AmSkullkinTower.h (100%) rename dScripts/{ => 02_server/Map/AM}/AmTeapotServer.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/AmTeapotServer.h (100%) rename dScripts/{ => 02_server/Map/AM}/AmTemplateSkillVolume.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/AmTemplateSkillVolume.h (100%) create mode 100644 dScripts/02_server/Map/AM/CMakeLists.txt rename dScripts/{ => 02_server/Map/AM}/RandomSpawnerFin.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/RandomSpawnerFin.h (100%) rename dScripts/{ => 02_server/Map/AM}/RandomSpawnerPit.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/RandomSpawnerPit.h (100%) rename dScripts/{ => 02_server/Map/AM}/RandomSpawnerStr.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/RandomSpawnerStr.h (100%) rename dScripts/{ => 02_server/Map/AM}/RandomSpawnerZip.cpp (100%) rename dScripts/{ => 02_server/Map/AM}/RandomSpawnerZip.h (100%) create mode 100644 dScripts/02_server/Map/CMakeLists.txt create mode 100644 dScripts/02_server/Map/FV/CMakeLists.txt rename dScripts/{ => 02_server/Map/FV}/EnemyRoninSpawner.cpp (100%) rename dScripts/{ => 02_server/Map/FV}/EnemyRoninSpawner.h (100%) rename dScripts/{ => 02_server/Map/FV}/FvCandle.cpp (100%) rename dScripts/{ => 02_server/Map/FV}/FvCandle.h (100%) rename dScripts/{ => 02_server/Map/FV}/FvFong.cpp (100%) rename dScripts/{ => 02_server/Map/FV}/FvFong.h (100%) rename dScripts/{ => 02_server/Map/FV}/FvHorsemenTrigger.cpp (100%) rename dScripts/{ => 02_server/Map/FV}/FvHorsemenTrigger.h (100%) rename dScripts/{ => 02_server/Map/FV}/ImgBrickConsoleQB.cpp (100%) rename dScripts/{ => 02_server/Map/FV}/ImgBrickConsoleQB.h (100%) create mode 100644 dScripts/02_server/Map/FV/Racing/CMakeLists.txt rename dScripts/{ => 02_server/Map/FV/Racing}/RaceMaelstromGeiser.cpp (100%) rename dScripts/{ => 02_server/Map/FV/Racing}/RaceMaelstromGeiser.h (100%) create mode 100644 dScripts/02_server/Map/GF/CMakeLists.txt rename dScripts/{ => 02_server/Map/GF}/GfCaptainsCannon.cpp (100%) rename dScripts/{ => 02_server/Map/GF}/GfCaptainsCannon.h (100%) rename dScripts/{ => 02_server/Map/GF}/GfTikiTorch.cpp (100%) rename dScripts/{ => 02_server/Map/GF}/GfTikiTorch.h (100%) rename dScripts/{ => 02_server/Map/GF}/MastTeleport.cpp (100%) rename dScripts/{ => 02_server/Map/GF}/MastTeleport.h (100%) rename dScripts/{ => 02_server/Map/GF}/SpawnLionServer.cpp (100%) rename dScripts/{ => 02_server/Map/GF}/SpawnLionServer.h (100%) rename dScripts/{ => 02_server/Map/General}/BankInteractServer.cpp (100%) rename dScripts/{ => 02_server/Map/General}/BankInteractServer.h (100%) rename dScripts/{ => 02_server/Map/General}/BaseInteractDropLootServer.cpp (100%) rename dScripts/{ => 02_server/Map/General}/BaseInteractDropLootServer.h (100%) rename dScripts/{ => 02_server/Map/General}/Binoculars.cpp (100%) rename dScripts/{ => 02_server/Map/General}/Binoculars.h (100%) create mode 100644 dScripts/02_server/Map/General/CMakeLists.txt rename dScripts/{ => 02_server/Map/General}/ExplodingAsset.cpp (100%) rename dScripts/{ => 02_server/Map/General}/ExplodingAsset.h (100%) rename dScripts/{ => 02_server/Map/General}/ForceVolumeServer.cpp (100%) rename dScripts/{ => 02_server/Map/General}/ForceVolumeServer.h (100%) rename dScripts/{ => 02_server/Map/General}/GrowingFlower.cpp (100%) rename dScripts/{ => 02_server/Map/General}/GrowingFlower.h (100%) rename dScripts/{ => 02_server/Map/General}/ImaginationBackpackHealServer.cpp (100%) rename dScripts/{ => 02_server/Map/General}/ImaginationBackpackHealServer.h (100%) rename dScripts/{ => 02_server/Map/General}/InvalidScript.cpp (100%) rename dScripts/{ => 02_server/Map/General}/InvalidScript.h (100%) rename dScripts/{ => 02_server/Map/General}/MailBoxServer.cpp (100%) rename dScripts/{ => 02_server/Map/General}/MailBoxServer.h (100%) create mode 100644 dScripts/02_server/Map/General/Ninjago/CMakeLists.txt rename dScripts/{ => 02_server/Map/General/Ninjago}/NjIceRailActivator.cpp (100%) rename dScripts/{ => 02_server/Map/General/Ninjago}/NjIceRailActivator.h (100%) rename dScripts/{ => 02_server/Map/General/Ninjago}/NjRailActivatorsServer.cpp (100%) rename dScripts/{ => 02_server/Map/General/Ninjago}/NjRailActivatorsServer.h (100%) rename dScripts/{ => 02_server/Map/General/Ninjago}/NjRailPostServer.cpp (100%) rename dScripts/{ => 02_server/Map/General/Ninjago}/NjRailPostServer.h (100%) rename dScripts/{ => 02_server/Map/General/Ninjago}/NjhubLavaPlayerDeathTrigger.cpp (100%) rename dScripts/{ => 02_server/Map/General/Ninjago}/NjhubLavaPlayerDeathTrigger.h (100%) rename dScripts/{ => 02_server/Map/General}/NjRailSwitch.cpp (100%) rename dScripts/{ => 02_server/Map/General}/NjRailSwitch.h (100%) rename dScripts/{ => 02_server/Map/General}/PetDigServer.cpp (100%) rename dScripts/{ => 02_server/Map/General}/PetDigServer.h (100%) rename dScripts/{ => 02_server/Map/General}/PropertyDevice.cpp (100%) rename dScripts/{ => 02_server/Map/General}/PropertyDevice.h (100%) rename dScripts/{ => 02_server/Map/General}/PropertyPlatform.cpp (100%) rename dScripts/{ => 02_server/Map/General}/PropertyPlatform.h (100%) rename dScripts/{ => 02_server/Map/General}/QbEnemyStunner.cpp (100%) rename dScripts/{ => 02_server/Map/General}/QbEnemyStunner.h (100%) rename dScripts/{ => 02_server/Map/General}/QbSpawner.cpp (100%) rename dScripts/{ => 02_server/Map/General}/QbSpawner.h (100%) rename dScripts/{ => 02_server/Map/General}/StoryBoxInteractServer.cpp (100%) rename dScripts/{ => 02_server/Map/General}/StoryBoxInteractServer.h (100%) rename dScripts/{ => 02_server/Map/General}/TokenConsoleServer.cpp (100%) rename dScripts/{ => 02_server/Map/General}/TokenConsoleServer.h (100%) rename dScripts/{ => 02_server/Map/General}/TouchMissionUpdateServer.cpp (100%) rename dScripts/{ => 02_server/Map/General}/TouchMissionUpdateServer.h (100%) rename dScripts/{ => 02_server/Map/General}/WishingWellServer.cpp (100%) rename dScripts/{ => 02_server/Map/General}/WishingWellServer.h (100%) create mode 100644 dScripts/02_server/Map/NS/CMakeLists.txt rename dScripts/{ => 02_server/Map/NS}/NsConcertChoiceBuildManager.cpp (100%) rename dScripts/{ => 02_server/Map/NS}/NsConcertChoiceBuildManager.h (100%) rename dScripts/{ => 02_server/Map/NS}/NsLegoClubDoor.cpp (100%) rename dScripts/{ => 02_server/Map/NS}/NsLegoClubDoor.h (100%) rename dScripts/{ => 02_server/Map/NS}/NsLupTeleport.cpp (100%) rename dScripts/{ => 02_server/Map/NS}/NsLupTeleport.h (100%) rename dScripts/{ => 02_server/Map/NS}/NsTokenConsoleServer.cpp (100%) rename dScripts/{ => 02_server/Map/NS}/NsTokenConsoleServer.h (100%) create mode 100644 dScripts/02_server/Map/NS/Waves/CMakeLists.txt rename dScripts/{ => 02_server/Map/NS/Waves}/ZoneNsWaves.cpp (100%) rename dScripts/{ => 02_server/Map/NS/Waves}/ZoneNsWaves.h (100%) create mode 100644 dScripts/02_server/Map/NT/CMakeLists.txt rename dScripts/{ => 02_server/Map/NT}/NtAssemblyTubeServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtAssemblyTubeServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtBeamImaginationCollectors.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtBeamImaginationCollectors.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtCombatChallengeDummy.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtCombatChallengeDummy.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtCombatChallengeExplodingDummy.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtCombatChallengeExplodingDummy.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtCombatChallengeServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtCombatChallengeServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtConsoleTeleportServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtConsoleTeleportServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtDarkitectRevealServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtDarkitectRevealServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtDirtCloudServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtDirtCloudServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtDukeServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtDukeServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtHaelServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtHaelServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtImagBeamBuffer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtImagBeamBuffer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtImagimeterVisibility.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtImagimeterVisibility.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtOverbuildServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtOverbuildServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtParadoxPanelServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtParadoxPanelServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtParadoxTeleServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtParadoxTeleServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtSentinelWalkwayServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtSentinelWalkwayServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtSleepingGuard.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtSleepingGuard.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtVandaServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtVandaServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtVentureCannonServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtVentureCannonServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtVentureSpeedPadServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtVentureSpeedPadServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/NtXRayServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/NtXRayServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/SpawnSaberCatServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/SpawnSaberCatServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/SpawnShrakeServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/SpawnShrakeServer.h (100%) rename dScripts/{ => 02_server/Map/NT}/SpawnStegoServer.cpp (100%) rename dScripts/{ => 02_server/Map/NT}/SpawnStegoServer.h (100%) create mode 100644 dScripts/02_server/Map/PR/CMakeLists.txt rename dScripts/{ => 02_server/Map/PR}/HydrantBroken.cpp (100%) rename dScripts/{ => 02_server/Map/PR}/HydrantBroken.h (100%) rename dScripts/{ => 02_server/Map/PR}/PrSeagullFly.cpp (100%) rename dScripts/{ => 02_server/Map/PR}/PrSeagullFly.h (100%) rename dScripts/{ => 02_server/Map/PR}/SpawnGryphonServer.cpp (100%) rename dScripts/{ => 02_server/Map/PR}/SpawnGryphonServer.h (100%) create mode 100644 dScripts/02_server/Map/Property/AG_Med/CMakeLists.txt rename dScripts/{ => 02_server/Map/Property/AG_Med}/ZoneAgMedProperty.cpp (100%) rename dScripts/{ => 02_server/Map/Property/AG_Med}/ZoneAgMedProperty.h (100%) create mode 100644 dScripts/02_server/Map/Property/AG_Small/CMakeLists.txt rename dScripts/{ => 02_server/Map/Property/AG_Small}/EnemySpiderSpawner.cpp (100%) rename dScripts/{ => 02_server/Map/Property/AG_Small}/EnemySpiderSpawner.h (100%) rename dScripts/{ => 02_server/Map/Property/AG_Small}/ZoneAgProperty.cpp (100%) rename dScripts/{ => 02_server/Map/Property/AG_Small}/ZoneAgProperty.h (100%) create mode 100644 dScripts/02_server/Map/Property/CMakeLists.txt create mode 100644 dScripts/02_server/Map/Property/NS_Med/CMakeLists.txt rename dScripts/{ => 02_server/Map/Property/NS_Med}/ZoneNsMedProperty.cpp (100%) rename dScripts/{ => 02_server/Map/Property/NS_Med}/ZoneNsMedProperty.h (100%) rename dScripts/{ => 02_server/Map/Property}/PropertyBankInteract.cpp (100%) rename dScripts/{ => 02_server/Map/Property}/PropertyBankInteract.h (100%) create mode 100644 dScripts/02_server/Map/SS/CMakeLists.txt rename dScripts/{ => 02_server/Map/SS}/SsModularBuildServer.cpp (100%) rename dScripts/{ => 02_server/Map/SS}/SsModularBuildServer.h (100%) create mode 100644 dScripts/02_server/Map/VE/CMakeLists.txt rename dScripts/{ => 02_server/Map/VE}/VeBricksampleServer.cpp (100%) rename dScripts/{ => 02_server/Map/VE}/VeBricksampleServer.h (100%) rename dScripts/{ => 02_server/Map/VE}/VeEpsilonServer.cpp (100%) rename dScripts/{ => 02_server/Map/VE}/VeEpsilonServer.h (100%) rename dScripts/{ => 02_server/Map/VE}/VeMissionConsole.cpp (100%) rename dScripts/{ => 02_server/Map/VE}/VeMissionConsole.h (100%) rename dScripts/{ => 02_server/Map/njhub}/BurningTile.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/BurningTile.h (100%) create mode 100644 dScripts/02_server/Map/njhub/CMakeLists.txt rename dScripts/{ => 02_server/Map/njhub}/CatapultBaseServer.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/CatapultBaseServer.h (100%) rename dScripts/{ => 02_server/Map/njhub}/CatapultBouncerServer.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/CatapultBouncerServer.h (100%) rename dScripts/{ => 02_server/Map/njhub}/CavePrisonCage.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/CavePrisonCage.h (100%) rename dScripts/{ => 02_server/Map/njhub}/EnemySkeletonSpawner.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/EnemySkeletonSpawner.h (100%) rename dScripts/{ => 02_server/Map/njhub}/FallingTile.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/FallingTile.h (100%) rename dScripts/{ => 02_server/Map/njhub}/FlameJetServer.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/FlameJetServer.h (100%) rename dScripts/{ => 02_server/Map/njhub}/ImaginationShrineServer.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/ImaginationShrineServer.h (100%) rename dScripts/{ => 02_server/Map/njhub}/Lieutenant.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/Lieutenant.h (100%) rename dScripts/{ => 02_server/Map/njhub}/MonCoreNookDoors.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/MonCoreNookDoors.h (100%) rename dScripts/{ => 02_server/Map/njhub}/MonCoreSmashableDoors.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/MonCoreSmashableDoors.h (100%) rename dScripts/{ => 02_server/Map/njhub}/NjColeNPC.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/NjColeNPC.h (100%) rename dScripts/{ => 02_server/Map/njhub}/NjDragonEmblemChestServer.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/NjDragonEmblemChestServer.h (100%) rename dScripts/{ => 02_server/Map/njhub}/NjEarthDragonPetServer.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/NjEarthDragonPetServer.h (100%) rename dScripts/{ => 02_server/Map/njhub}/NjEarthPetServer.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/NjEarthPetServer.h (100%) rename dScripts/{ => 02_server/Map/njhub}/NjGarmadonCelebration.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/NjGarmadonCelebration.h (100%) rename dScripts/{ => 02_server/Map/njhub}/NjJayMissionItems.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/NjJayMissionItems.h (100%) rename dScripts/{ => 02_server/Map/njhub}/NjNPCMissionSpinjitzuServer.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/NjNPCMissionSpinjitzuServer.h (100%) rename dScripts/{ => 02_server/Map/njhub}/NjNyaMissionitems.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/NjNyaMissionitems.h (100%) rename dScripts/{ => 02_server/Map/njhub}/NjScrollChestServer.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/NjScrollChestServer.h (100%) rename dScripts/{ => 02_server/Map/njhub}/NjWuNPC.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/NjWuNPC.h (100%) rename dScripts/{ => 02_server/Map/njhub}/RainOfArrows.cpp (100%) rename dScripts/{ => 02_server/Map/njhub}/RainOfArrows.h (100%) create mode 100644 dScripts/02_server/Map/njhub/boss_instance/CMakeLists.txt rename dScripts/{ => 02_server/Map/njhub/boss_instance}/NjMonastryBossInstance.cpp (100%) rename dScripts/{ => 02_server/Map/njhub/boss_instance}/NjMonastryBossInstance.h (100%) create mode 100644 dScripts/02_server/Minigame/CMakeLists.txt create mode 100644 dScripts/02_server/Minigame/General/CMakeLists.txt rename dScripts/{ => 02_server/Minigame/General}/MinigameTreasureChestServer.cpp (100%) rename dScripts/{ => 02_server/Minigame/General}/MinigameTreasureChestServer.h (100%) rename dScripts/{ => 02_server/Objects}/AgSurvivalBuffStation.cpp (100%) rename dScripts/{ => 02_server/Objects}/AgSurvivalBuffStation.h (100%) create mode 100644 dScripts/02_server/Objects/CMakeLists.txt rename dScripts/{ => 02_server/Objects}/StinkyFishTarget.cpp (100%) rename dScripts/{ => 02_server/Objects}/StinkyFishTarget.h (100%) create mode 100644 dScripts/02_server/Pets/CMakeLists.txt rename dScripts/{ => 02_server/Pets}/DamagingPets.cpp (100%) rename dScripts/{ => 02_server/Pets}/DamagingPets.h (100%) rename dScripts/{ => 02_server/Pets}/PetFromDigServer.cpp (100%) rename dScripts/{ => 02_server/Pets}/PetFromDigServer.h (100%) rename dScripts/{ => 02_server/Pets}/PetFromObjectServer.cpp (100%) rename dScripts/{ => 02_server/Pets}/PetFromObjectServer.h (100%) rename dScripts/{ => EquipmentScripts}/AnvilOfArmor.cpp (100%) rename dScripts/{ => EquipmentScripts}/AnvilOfArmor.h (100%) rename dScripts/{ => EquipmentScripts}/BuccaneerValiantShip.cpp (100%) rename dScripts/{ => EquipmentScripts}/BuccaneerValiantShip.h (100%) create mode 100644 dScripts/EquipmentScripts/CMakeLists.txt rename dScripts/{ => EquipmentScripts}/CauldronOfLife.cpp (100%) rename dScripts/{ => EquipmentScripts}/CauldronOfLife.h (100%) rename dScripts/{ => EquipmentScripts}/FireFirstSkillonStartup.cpp (100%) rename dScripts/{ => EquipmentScripts}/FireFirstSkillonStartup.h (100%) rename dScripts/{ => EquipmentScripts}/FountainOfImagination.cpp (100%) rename dScripts/{ => EquipmentScripts}/FountainOfImagination.h (100%) rename dScripts/{ => EquipmentScripts}/PersonalFortress.cpp (100%) rename dScripts/{ => EquipmentScripts}/PersonalFortress.h (100%) rename dScripts/{ => EquipmentScripts}/Sunflower.cpp (100%) rename dScripts/{ => EquipmentScripts}/Sunflower.h (100%) rename dScripts/{ => ai/ACT}/ActMine.cpp (100%) rename dScripts/{ => ai/ACT}/ActMine.h (100%) rename dScripts/{ => ai/ACT}/ActPlayerDeathTrigger.cpp (100%) rename dScripts/{ => ai/ACT}/ActPlayerDeathTrigger.h (100%) rename dScripts/{ => ai/ACT}/ActVehicleDeathTrigger.cpp (100%) rename dScripts/{ => ai/ACT}/ActVehicleDeathTrigger.h (100%) create mode 100644 dScripts/ai/ACT/CMakeLists.txt rename dScripts/{ => ai/ACT/FootRace}/BaseFootRaceManager.cpp (100%) rename dScripts/{ => ai/ACT/FootRace}/BaseFootRaceManager.h (100%) create mode 100644 dScripts/ai/ACT/FootRace/CMakeLists.txt rename dScripts/{ => ai/AG}/ActSharkPlayerDeathTrigger.cpp (100%) rename dScripts/{ => ai/AG}/ActSharkPlayerDeathTrigger.h (100%) rename dScripts/{ => ai/AG}/AgBusDoor.cpp (100%) rename dScripts/{ => ai/AG}/AgBusDoor.h (100%) rename dScripts/{ => ai/AG}/AgDarkSpiderling.cpp (100%) rename dScripts/{ => ai/AG}/AgDarkSpiderling.h (100%) rename dScripts/{ => ai/AG}/AgFans.cpp (100%) rename dScripts/{ => ai/AG}/AgFans.h (100%) rename dScripts/{ => ai/AG}/AgImagSmashable.cpp (100%) rename dScripts/{ => ai/AG}/AgImagSmashable.h (100%) rename dScripts/{ => ai/AG}/AgJetEffectServer.cpp (100%) rename dScripts/{ => ai/AG}/AgJetEffectServer.h (100%) rename dScripts/{ => ai/AG}/AgPicnicBlanket.cpp (100%) rename dScripts/{ => ai/AG}/AgPicnicBlanket.h (100%) rename dScripts/{ => ai/AG}/AgQbElevator.cpp (100%) rename dScripts/{ => ai/AG}/AgQbElevator.h (100%) rename dScripts/{ => ai/AG}/AgQbWall.cpp (100%) rename dScripts/{ => ai/AG}/AgQbWall.h (100%) rename dScripts/{ => ai/AG}/AgSalutingNpcs.cpp (100%) rename dScripts/{ => ai/AG}/AgSalutingNpcs.h (100%) rename dScripts/{ => ai/AG}/AgShipPlayerDeathTrigger.cpp (100%) rename dScripts/{ => ai/AG}/AgShipPlayerDeathTrigger.h (100%) rename dScripts/{ => ai/AG}/AgShipPlayerShockServer.cpp (100%) rename dScripts/{ => ai/AG}/AgShipPlayerShockServer.h (100%) rename dScripts/{ => ai/AG}/AgSpaceStuff.cpp (100%) rename dScripts/{ => ai/AG}/AgSpaceStuff.h (100%) rename dScripts/{ => ai/AG}/AgStagePlatforms.cpp (100%) rename dScripts/{ => ai/AG}/AgStagePlatforms.h (100%) rename dScripts/{ => ai/AG}/AgStromlingProperty.cpp (100%) rename dScripts/{ => ai/AG}/AgStromlingProperty.h (100%) rename dScripts/{ => ai/AG}/AgTurret.cpp (100%) rename dScripts/{ => ai/AG}/AgTurret.h (100%) create mode 100644 dScripts/ai/AG/CMakeLists.txt create mode 100644 dScripts/ai/CMakeLists.txt rename dScripts/{ => ai/FV}/ActNinjaTurret.cpp (100%) rename dScripts/{ => ai/FV}/ActNinjaTurret.h (100%) rename dScripts/{ => ai/FV}/ActParadoxPipeFix.cpp (100%) rename dScripts/{ => ai/FV}/ActParadoxPipeFix.h (100%) create mode 100644 dScripts/ai/FV/CMakeLists.txt rename dScripts/{ => ai/FV}/FvBounceOverWall.cpp (100%) rename dScripts/{ => ai/FV}/FvBounceOverWall.h (100%) rename dScripts/{ => ai/FV}/FvBrickPuzzleServer.cpp (100%) rename dScripts/{ => ai/FV}/FvBrickPuzzleServer.h (100%) rename dScripts/{ => ai/FV}/FvConsoleLeftQuickbuild.cpp (100%) rename dScripts/{ => ai/FV}/FvConsoleLeftQuickbuild.h (100%) rename dScripts/{ => ai/FV}/FvConsoleRightQuickbuild.cpp (100%) rename dScripts/{ => ai/FV}/FvConsoleRightQuickbuild.h (100%) rename dScripts/{ => ai/FV}/FvDragonSmashingGolemQb.cpp (100%) rename dScripts/{ => ai/FV}/FvDragonSmashingGolemQb.h (100%) rename dScripts/{ => ai/FV}/FvFacilityBrick.cpp (100%) rename dScripts/{ => ai/FV}/FvFacilityBrick.h (100%) rename dScripts/{ => ai/FV}/FvFacilityPipes.cpp (100%) rename dScripts/{ => ai/FV}/FvFacilityPipes.h (100%) rename dScripts/{ => ai/FV}/FvFlyingCreviceDragon.cpp (100%) rename dScripts/{ => ai/FV}/FvFlyingCreviceDragon.h (100%) rename dScripts/{ => ai/FV}/FvFreeGfNinjas.cpp (100%) rename dScripts/{ => ai/FV}/FvFreeGfNinjas.h (100%) rename dScripts/{ => ai/FV}/FvMaelstromGeyser.cpp (100%) rename dScripts/{ => ai/FV}/FvMaelstromGeyser.h (100%) rename dScripts/{ => ai/FV}/FvNinjaGuard.cpp (100%) rename dScripts/{ => ai/FV}/FvNinjaGuard.h (100%) rename dScripts/{ => ai/FV}/FvPandaServer.cpp (100%) rename dScripts/{ => ai/FV}/FvPandaServer.h (100%) rename dScripts/{ => ai/FV}/FvPandaSpawnerServer.cpp (100%) rename dScripts/{ => ai/FV}/FvPandaSpawnerServer.h (100%) rename dScripts/{ => ai/FV}/FvPassThroughWall.cpp (100%) rename dScripts/{ => ai/FV}/FvPassThroughWall.h (100%) create mode 100644 dScripts/ai/GENERAL/CMakeLists.txt rename dScripts/{ => ai/GENERAL}/InstanceExitTransferPlayerToLastNonInstance.cpp (100%) rename dScripts/{ => ai/GENERAL}/InstanceExitTransferPlayerToLastNonInstance.h (100%) rename dScripts/{ => ai/GENERAL}/LegoDieRoll.cpp (100%) rename dScripts/{ => ai/GENERAL}/LegoDieRoll.h (100%) create mode 100644 dScripts/ai/GF/CMakeLists.txt rename dScripts/{ => ai/GF}/GfArchway.cpp (100%) rename dScripts/{ => ai/GF}/GfArchway.h (100%) rename dScripts/{ => ai/GF}/GfBanana.cpp (100%) rename dScripts/{ => ai/GF}/GfBanana.h (100%) rename dScripts/{ => ai/GF}/GfBananaCluster.cpp (100%) rename dScripts/{ => ai/GF}/GfBananaCluster.h (100%) rename dScripts/{ => ai/GF}/GfCampfire.cpp (100%) rename dScripts/{ => ai/GF}/GfCampfire.h (100%) rename dScripts/{ => ai/GF}/GfJailWalls.cpp (100%) rename dScripts/{ => ai/GF}/GfJailWalls.h (100%) rename dScripts/{ => ai/GF}/GfJailkeepMission.cpp (100%) rename dScripts/{ => ai/GF}/GfJailkeepMission.h (100%) rename dScripts/{ => ai/GF}/GfMaelstromGeyser.cpp (100%) rename dScripts/{ => ai/GF}/GfMaelstromGeyser.h (100%) rename dScripts/{ => ai/GF}/GfOrgan.cpp (100%) rename dScripts/{ => ai/GF}/GfOrgan.h (100%) rename dScripts/{ => ai/GF}/GfParrotCrash.cpp (100%) rename dScripts/{ => ai/GF}/GfParrotCrash.h (100%) rename dScripts/{ => ai/GF}/PetDigBuild.cpp (100%) rename dScripts/{ => ai/GF}/PetDigBuild.h (100%) rename dScripts/{ => ai/GF}/PirateRep.cpp (100%) rename dScripts/{ => ai/GF}/PirateRep.h (100%) rename dScripts/{ => ai/GF}/TriggerAmbush.cpp (100%) rename dScripts/{ => ai/GF}/TriggerAmbush.h (100%) create mode 100644 dScripts/ai/MINIGAME/CMakeLists.txt create mode 100644 dScripts/ai/MINIGAME/SG_GF/CMakeLists.txt create mode 100644 dScripts/ai/MINIGAME/SG_GF/SERVER/CMakeLists.txt rename dScripts/{ => ai/MINIGAME/SG_GF/SERVER}/SGCannon.cpp (100%) rename dScripts/{ => ai/MINIGAME/SG_GF/SERVER}/SGCannon.h (100%) rename dScripts/{ => ai/MINIGAME/SG_GF}/ZoneSGServer.cpp (100%) rename dScripts/{ => ai/MINIGAME/SG_GF}/ZoneSGServer.h (100%) create mode 100644 dScripts/ai/NP/CMakeLists.txt rename dScripts/{ => ai/NP}/NpcNpSpacemanBob.cpp (100%) rename dScripts/{ => ai/NP}/NpcNpSpacemanBob.h (100%) create mode 100644 dScripts/ai/NS/CMakeLists.txt rename dScripts/{ => ai/NS}/ClRing.cpp (100%) rename dScripts/{ => ai/NS}/ClRing.h (100%) create mode 100644 dScripts/ai/NS/NS_PP_01/CMakeLists.txt rename dScripts/{ => ai/NS/NS_PP_01}/PropertyDeathPlane.cpp (100%) rename dScripts/{ => ai/NS/NS_PP_01}/PropertyDeathPlane.h (100%) rename dScripts/{ => ai/NS}/NsConcertChoiceBuild.cpp (100%) rename dScripts/{ => ai/NS}/NsConcertChoiceBuild.h (100%) rename dScripts/{ => ai/NS}/NsConcertInstrument.cpp (100%) rename dScripts/{ => ai/NS}/NsConcertInstrument.h (100%) rename dScripts/{ => ai/NS}/NsConcertQuickBuild.cpp (100%) rename dScripts/{ => ai/NS}/NsConcertQuickBuild.h (100%) rename dScripts/{ => ai/NS}/NsGetFactionMissionServer.cpp (100%) rename dScripts/{ => ai/NS}/NsGetFactionMissionServer.h (100%) rename dScripts/{ => ai/NS}/NsJohnnyMissionServer.cpp (100%) rename dScripts/{ => ai/NS}/NsJohnnyMissionServer.h (100%) rename dScripts/{ => ai/NS}/NsModularBuild.cpp (100%) rename dScripts/{ => ai/NS}/NsModularBuild.h (100%) rename dScripts/{ => ai/NS}/NsQbImaginationStatue.cpp (100%) rename dScripts/{ => ai/NS}/NsQbImaginationStatue.h (100%) create mode 100644 dScripts/ai/NS/WH/CMakeLists.txt rename dScripts/{ => ai/NS/WH}/RockHydrantBroken.cpp (100%) rename dScripts/{ => ai/NS/WH}/RockHydrantBroken.h (100%) rename dScripts/{ => ai/NS/WH}/RockHydrantSmashable.cpp (100%) rename dScripts/{ => ai/NS/WH}/RockHydrantSmashable.h (100%) rename dScripts/{ => ai/NS}/WhFans.cpp (100%) rename dScripts/{ => ai/NS}/WhFans.h (100%) create mode 100644 dScripts/ai/PETS/CMakeLists.txt rename dScripts/{ => ai/PETS}/HydrantSmashable.cpp (100%) rename dScripts/{ => ai/PETS}/HydrantSmashable.h (100%) rename dScripts/{ => ai/PROPERTY/AG}/AgPropGuard.cpp (100%) rename dScripts/{ => ai/PROPERTY/AG}/AgPropGuard.h (100%) create mode 100644 dScripts/ai/PROPERTY/AG/CMakeLists.txt rename dScripts/{ => ai/PROPERTY}/AgPropguards.cpp (100%) rename dScripts/{ => ai/PROPERTY}/AgPropguards.h (100%) create mode 100644 dScripts/ai/PROPERTY/CMakeLists.txt rename dScripts/{ => ai/PROPERTY}/PropertyFXDamage.cpp (100%) rename dScripts/{ => ai/PROPERTY}/PropertyFXDamage.h (100%) create mode 100644 dScripts/ai/RACING/CMakeLists.txt create mode 100644 dScripts/ai/RACING/OBJECTS/CMakeLists.txt rename dScripts/{ => ai/RACING/OBJECTS}/FvRaceSmashEggImagineServer.cpp (100%) rename dScripts/{ => ai/RACING/OBJECTS}/FvRaceSmashEggImagineServer.h (100%) rename dScripts/{ => ai/RACING/OBJECTS}/RaceImagineCrateServer.cpp (100%) rename dScripts/{ => ai/RACING/OBJECTS}/RaceImagineCrateServer.h (100%) rename dScripts/{ => ai/RACING/OBJECTS}/RaceImaginePowerup.cpp (100%) rename dScripts/{ => ai/RACING/OBJECTS}/RaceImaginePowerup.h (100%) rename dScripts/{ => ai/RACING/OBJECTS}/RaceSmashServer.cpp (100%) rename dScripts/{ => ai/RACING/OBJECTS}/RaceSmashServer.h (100%) create mode 100644 dScripts/ai/SPEC/CMakeLists.txt rename dScripts/{ => ai/SPEC}/SpecialImaginePowerupSpawner.cpp (100%) rename dScripts/{ => ai/SPEC}/SpecialImaginePowerupSpawner.h (100%) rename dScripts/{ => ai/WILD}/AllCrateChicken.cpp (100%) rename dScripts/{ => ai/WILD}/AllCrateChicken.h (100%) create mode 100644 dScripts/ai/WILD/CMakeLists.txt rename dScripts/{ => ai/WILD}/WildAmbients.cpp (100%) rename dScripts/{ => ai/WILD}/WildAmbients.h (100%) create mode 100644 dScripts/client/CMakeLists.txt create mode 100644 dScripts/client/ai/CMakeLists.txt create mode 100644 dScripts/client/ai/PR/CMakeLists.txt rename dScripts/{ => client/ai/PR}/CrabServer.cpp (100%) rename dScripts/{ => client/ai/PR}/CrabServer.h (100%) rename dScripts/{ => client/ai/PR}/PrWhistle.cpp (100%) rename dScripts/{ => client/ai/PR}/PrWhistle.h (100%) create mode 100644 dScripts/zone/AG/CMakeLists.txt rename dScripts/{ => zone/AG}/ZoneAgSurvival.cpp (100%) rename dScripts/{ => zone/AG}/ZoneAgSurvival.h (100%) create mode 100644 dScripts/zone/CMakeLists.txt create mode 100644 dScripts/zone/LUPs/CMakeLists.txt rename dScripts/{ => zone/LUPs}/WblGenericZone.cpp (100%) rename dScripts/{ => zone/LUPs}/WblGenericZone.h (100%) create mode 100644 dScripts/zone/PROPERTY/CMakeLists.txt create mode 100644 dScripts/zone/PROPERTY/FV/CMakeLists.txt rename dScripts/{ => zone/PROPERTY/FV}/ZoneFvProperty.cpp (100%) rename dScripts/{ => zone/PROPERTY/FV}/ZoneFvProperty.h (100%) create mode 100644 dScripts/zone/PROPERTY/GF/CMakeLists.txt rename dScripts/{ => zone/PROPERTY/GF}/ZoneGfProperty.cpp (100%) rename dScripts/{ => zone/PROPERTY/GF}/ZoneGfProperty.h (100%) create mode 100644 dScripts/zone/PROPERTY/NS/CMakeLists.txt rename dScripts/{ => zone/PROPERTY/NS}/ZoneNsProperty.cpp (100%) rename dScripts/{ => zone/PROPERTY/NS}/ZoneNsProperty.h (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 25575b0c..34a6cd27 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -165,6 +165,74 @@ set(INCLUDED_DIRECTORIES "dDatabase/Tables" "dNet" "dScripts" + "dScripts/02_server" + "dScripts/ai" + "dScripts/client" + "dScripts/EquipmentScripts" + "dScripts/zone" + "dScripts/02_server/DLU" + "dScripts/02_server/Enemy" + "dScripts/02_server/Equipment" + "dScripts/02_server/Map" + "dScripts/02_server/Minigame" + "dScripts/02_server/Objects" + "dScripts/02_server/Pets" + "dScripts/02_server/Enemy/AG" + "dScripts/02_server/Enemy/AM" + "dScripts/02_server/Enemy/FV" + "dScripts/02_server/Enemy/General" + "dScripts/02_server/Enemy/Survival" + "dScripts/02_server/Enemy/VE" + "dScripts/02_server/Enemy/Waves" + "dScripts/02_server/Map/AG" + "dScripts/02_server/Map/AG_Spider_Queen" + "dScripts/02_server/Map/AM" + "dScripts/02_server/Map/FV" + "dScripts/02_server/Map/General" + "dScripts/02_server/Map/GF" + "dScripts/02_server/Map/njhub" + "dScripts/02_server/Map/NS" + "dScripts/02_server/Map/NT" + "dScripts/02_server/Map/PR" + "dScripts/02_server/Map/Property" + "dScripts/02_server/Map/SS" + "dScripts/02_server/Map/VE" + "dScripts/02_server/Map/FV/Racing" + "dScripts/02_server/Map/General/Ninjago" + "dScripts/02_server/Map/njhub/boss_instance" + "dScripts/02_server/Map/NS/Waves" + "dScripts/02_server/Map/Property/AG_Med" + "dScripts/02_server/Map/Property/AG_Small" + "dScripts/02_server/Map/Property/NS_Med" + "dScripts/02_server/Minigame/General" + "dScripts/ai/ACT" + "dScripts/ai/AG" + "dScripts/ai/FV" + "dScripts/ai/GENERAL" + "dScripts/ai/GF" + "dScripts/ai/MINIGAME" + "dScripts/ai/NP" + "dScripts/ai/NS" + "dScripts/ai/PETS" + "dScripts/ai/PROPERTY" + "dScripts/ai/RACING" + "dScripts/ai/SPEC" + "dScripts/ai/WILD" + "dScripts/ai/ACT/FootRace" + "dScripts/ai/MINIGAME/SG_GF" + "dScripts/ai/MINIGAME/SG_GF/SERVER" + "dScripts/ai/NS/NS_PP_01" + "dScripts/ai/NS/WH" + "dScripts/ai/PROPERTY/AG" + "dScripts/ai/RACING/OBJECTS" + "dScripts/client/ai" + "dScripts/client/ai/PR" + "dScripts/zone/AG" + "dScripts/zone/LUPs" + "dScripts/zone/PROPERTY" + "dScripts/zone/PROPERTY/FV" + "dScripts/zone/PROPERTY/GF" + "dScripts/zone/PROPERTY/NS" "thirdparty/raknet/Source" "thirdparty/tinyxml2" diff --git a/dGame/CMakeLists.txt b/dGame/CMakeLists.txt index eb02eef2..80f16042 100644 --- a/dGame/CMakeLists.txt +++ b/dGame/CMakeLists.txt @@ -50,14 +50,13 @@ foreach(file ${DGAME_DPROPERTYBEHAVIORS_SOURCES}) set(DGAME_SOURCES ${DGAME_SOURCES} "dPropertyBehaviors/${file}") endforeach() - add_subdirectory(dUtilities) foreach(file ${DGAME_DUTILITIES_SOURCES}) set(DGAME_SOURCES ${DGAME_SOURCES} "dUtilities/${file}") endforeach() -foreach(file ${DSCRIPT_SOURCES}) +foreach(file ${DSCRIPTS_SOURCES}) set(DGAME_SOURCES ${DGAME_SOURCES} "${PROJECT_SOURCE_DIR}/dScripts/${file}") endforeach() diff --git a/dScripts/02_server/CMakeLists.txt b/dScripts/02_server/CMakeLists.txt new file mode 100644 index 00000000..1e38386f --- /dev/null +++ b/dScripts/02_server/CMakeLists.txt @@ -0,0 +1,45 @@ +set(DSCRIPTS_SOURCES_02_SERVER) + +add_subdirectory(DLU) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_DLU}) + set(DSCRIPTS_SOURCES_02_SERVER ${DSCRIPTS_SOURCES_02_SERVER} "DLU/${file}") +endforeach() + +add_subdirectory(Enemy) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_ENEMY}) + set(DSCRIPTS_SOURCES_02_SERVER ${DSCRIPTS_SOURCES_02_SERVER} "Enemy/${file}") +endforeach() + +add_subdirectory(Equipment) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_EQUIPMENT}) + set(DSCRIPTS_SOURCES_02_SERVER ${DSCRIPTS_SOURCES_02_SERVER} "Equipment/${file}") +endforeach() + +add_subdirectory(Map) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP}) + set(DSCRIPTS_SOURCES_02_SERVER ${DSCRIPTS_SOURCES_02_SERVER} "Map/${file}") +endforeach() + +add_subdirectory(Minigame) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MINIGAME}) + set(DSCRIPTS_SOURCES_02_SERVER ${DSCRIPTS_SOURCES_02_SERVER} "Minigame/${file}") +endforeach() + +add_subdirectory(Objects) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_OBJECTS}) + set(DSCRIPTS_SOURCES_02_SERVER ${DSCRIPTS_SOURCES_02_SERVER} "Objects/${file}") +endforeach() + +add_subdirectory(Pets) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_PETS}) + set(DSCRIPTS_SOURCES_02_SERVER ${DSCRIPTS_SOURCES_02_SERVER} "Pets/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_02_SERVER ${DSCRIPTS_SOURCES_02_SERVER} PARENT_SCOPE) diff --git a/dScripts/02_server/DLU/CMakeLists.txt b/dScripts/02_server/DLU/CMakeLists.txt new file mode 100644 index 00000000..64d4cbbd --- /dev/null +++ b/dScripts/02_server/DLU/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_02_SERVER_DLU + "DLUVanityNPC.cpp" + PARENT_SCOPE) diff --git a/dScripts/DLUVanityNPC.cpp b/dScripts/02_server/DLU/DLUVanityNPC.cpp similarity index 100% rename from dScripts/DLUVanityNPC.cpp rename to dScripts/02_server/DLU/DLUVanityNPC.cpp diff --git a/dScripts/DLUVanityNPC.h b/dScripts/02_server/DLU/DLUVanityNPC.h similarity index 100% rename from dScripts/DLUVanityNPC.h rename to dScripts/02_server/DLU/DLUVanityNPC.h diff --git a/dScripts/BossSpiderQueenEnemyServer.cpp b/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp similarity index 100% rename from dScripts/BossSpiderQueenEnemyServer.cpp rename to dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp diff --git a/dScripts/BossSpiderQueenEnemyServer.h b/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.h similarity index 100% rename from dScripts/BossSpiderQueenEnemyServer.h rename to dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.h diff --git a/dScripts/02_server/Enemy/AG/CMakeLists.txt b/dScripts/02_server/Enemy/AG/CMakeLists.txt new file mode 100644 index 00000000..865d4c3c --- /dev/null +++ b/dScripts/02_server/Enemy/AG/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_02_SERVER_ENEMY_AG + "BossSpiderQueenEnemyServer.cpp" + PARENT_SCOPE) diff --git a/dScripts/AmDarklingDragon.cpp b/dScripts/02_server/Enemy/AM/AmDarklingDragon.cpp similarity index 100% rename from dScripts/AmDarklingDragon.cpp rename to dScripts/02_server/Enemy/AM/AmDarklingDragon.cpp diff --git a/dScripts/AmDarklingDragon.h b/dScripts/02_server/Enemy/AM/AmDarklingDragon.h similarity index 100% rename from dScripts/AmDarklingDragon.h rename to dScripts/02_server/Enemy/AM/AmDarklingDragon.h diff --git a/dScripts/AmDarklingMech.cpp b/dScripts/02_server/Enemy/AM/AmDarklingMech.cpp similarity index 100% rename from dScripts/AmDarklingMech.cpp rename to dScripts/02_server/Enemy/AM/AmDarklingMech.cpp diff --git a/dScripts/AmDarklingMech.h b/dScripts/02_server/Enemy/AM/AmDarklingMech.h similarity index 100% rename from dScripts/AmDarklingMech.h rename to dScripts/02_server/Enemy/AM/AmDarklingMech.h diff --git a/dScripts/AmSkeletonEngineer.cpp b/dScripts/02_server/Enemy/AM/AmSkeletonEngineer.cpp similarity index 100% rename from dScripts/AmSkeletonEngineer.cpp rename to dScripts/02_server/Enemy/AM/AmSkeletonEngineer.cpp diff --git a/dScripts/AmSkeletonEngineer.h b/dScripts/02_server/Enemy/AM/AmSkeletonEngineer.h similarity index 100% rename from dScripts/AmSkeletonEngineer.h rename to dScripts/02_server/Enemy/AM/AmSkeletonEngineer.h diff --git a/dScripts/02_server/Enemy/AM/CMakeLists.txt b/dScripts/02_server/Enemy/AM/CMakeLists.txt new file mode 100644 index 00000000..dd20edb0 --- /dev/null +++ b/dScripts/02_server/Enemy/AM/CMakeLists.txt @@ -0,0 +1,5 @@ +set(DSCRIPTS_SOURCES_02_SERVER_ENEMY_AM + "AmDarklingMech.cpp" + "AmSkeletonEngineer.cpp" + "AmDarklingDragon.cpp" + PARENT_SCOPE) diff --git a/dScripts/02_server/Enemy/CMakeLists.txt b/dScripts/02_server/Enemy/CMakeLists.txt new file mode 100644 index 00000000..408ff733 --- /dev/null +++ b/dScripts/02_server/Enemy/CMakeLists.txt @@ -0,0 +1,45 @@ +set(DSCRIPTS_SOURCES_02_SERVER_ENEMY) + +add_subdirectory(AG) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_ENEMY_AG}) + set(DSCRIPTS_SOURCES_02_SERVER_ENEMY ${DSCRIPTS_SOURCES_02_SERVER_ENEMY} "AG/${file}") +endforeach() + +add_subdirectory(AM) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_ENEMY_AM}) + set(DSCRIPTS_SOURCES_02_SERVER_ENEMY ${DSCRIPTS_SOURCES_02_SERVER_ENEMY} "AM/${file}") +endforeach() + +add_subdirectory(FV) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_ENEMY_FV}) + set(DSCRIPTS_SOURCES_02_SERVER_ENEMY ${DSCRIPTS_SOURCES_02_SERVER_ENEMY} "FV/${file}") +endforeach() + +add_subdirectory(General) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_ENEMY_GENERAL}) + set(DSCRIPTS_SOURCES_02_SERVER_ENEMY ${DSCRIPTS_SOURCES_02_SERVER_ENEMY} "General/${file}") +endforeach() + +add_subdirectory(Survival) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_ENEMY_SURVIVAL}) + set(DSCRIPTS_SOURCES_02_SERVER_ENEMY ${DSCRIPTS_SOURCES_02_SERVER_ENEMY} "Survival/${file}") +endforeach() + +add_subdirectory(VE) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_ENEMY_VE}) + set(DSCRIPTS_SOURCES_02_SERVER_ENEMY ${DSCRIPTS_SOURCES_02_SERVER_ENEMY} "VE/${file}") +endforeach() + +add_subdirectory(Waves) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_ENEMY_WAVES}) + set(DSCRIPTS_SOURCES_02_SERVER_ENEMY ${DSCRIPTS_SOURCES_02_SERVER_ENEMY} "Waves/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_02_SERVER_ENEMY ${DSCRIPTS_SOURCES_02_SERVER_ENEMY} PARENT_SCOPE) diff --git a/dScripts/02_server/Enemy/FV/CMakeLists.txt b/dScripts/02_server/Enemy/FV/CMakeLists.txt new file mode 100644 index 00000000..5146d8d8 --- /dev/null +++ b/dScripts/02_server/Enemy/FV/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DSCRIPTS_SOURCES_02_SERVER_ENEMY_FV + "FvMaelstromCavalry.cpp" + "FvMaelstromDragon.cpp" + PARENT_SCOPE) diff --git a/dScripts/FvMaelstromCavalry.cpp b/dScripts/02_server/Enemy/FV/FvMaelstromCavalry.cpp similarity index 100% rename from dScripts/FvMaelstromCavalry.cpp rename to dScripts/02_server/Enemy/FV/FvMaelstromCavalry.cpp diff --git a/dScripts/FvMaelstromCavalry.h b/dScripts/02_server/Enemy/FV/FvMaelstromCavalry.h similarity index 100% rename from dScripts/FvMaelstromCavalry.h rename to dScripts/02_server/Enemy/FV/FvMaelstromCavalry.h diff --git a/dScripts/FvMaelstromDragon.cpp b/dScripts/02_server/Enemy/FV/FvMaelstromDragon.cpp similarity index 100% rename from dScripts/FvMaelstromDragon.cpp rename to dScripts/02_server/Enemy/FV/FvMaelstromDragon.cpp diff --git a/dScripts/FvMaelstromDragon.h b/dScripts/02_server/Enemy/FV/FvMaelstromDragon.h similarity index 100% rename from dScripts/FvMaelstromDragon.h rename to dScripts/02_server/Enemy/FV/FvMaelstromDragon.h diff --git a/dScripts/BaseEnemyApe.cpp b/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp similarity index 100% rename from dScripts/BaseEnemyApe.cpp rename to dScripts/02_server/Enemy/General/BaseEnemyApe.cpp diff --git a/dScripts/BaseEnemyApe.h b/dScripts/02_server/Enemy/General/BaseEnemyApe.h similarity index 100% rename from dScripts/BaseEnemyApe.h rename to dScripts/02_server/Enemy/General/BaseEnemyApe.h diff --git a/dScripts/BaseEnemyMech.cpp b/dScripts/02_server/Enemy/General/BaseEnemyMech.cpp similarity index 100% rename from dScripts/BaseEnemyMech.cpp rename to dScripts/02_server/Enemy/General/BaseEnemyMech.cpp diff --git a/dScripts/BaseEnemyMech.h b/dScripts/02_server/Enemy/General/BaseEnemyMech.h similarity index 100% rename from dScripts/BaseEnemyMech.h rename to dScripts/02_server/Enemy/General/BaseEnemyMech.h diff --git a/dScripts/02_server/Enemy/General/CMakeLists.txt b/dScripts/02_server/Enemy/General/CMakeLists.txt new file mode 100644 index 00000000..5486d2b0 --- /dev/null +++ b/dScripts/02_server/Enemy/General/CMakeLists.txt @@ -0,0 +1,7 @@ +set(DSCRIPTS_SOURCES_02_SERVER_ENEMY_GENERAL + "BaseEnemyMech.cpp" + "BaseEnemyApe.cpp" + "GfApeSmashingQB.cpp" + "TreasureChestDragonServer.cpp" + "EnemyNjBuff.cpp" + PARENT_SCOPE) diff --git a/dScripts/EnemyNjBuff.cpp b/dScripts/02_server/Enemy/General/EnemyNjBuff.cpp similarity index 100% rename from dScripts/EnemyNjBuff.cpp rename to dScripts/02_server/Enemy/General/EnemyNjBuff.cpp diff --git a/dScripts/EnemyNjBuff.h b/dScripts/02_server/Enemy/General/EnemyNjBuff.h similarity index 100% rename from dScripts/EnemyNjBuff.h rename to dScripts/02_server/Enemy/General/EnemyNjBuff.h diff --git a/dScripts/GfApeSmashingQB.cpp b/dScripts/02_server/Enemy/General/GfApeSmashingQB.cpp similarity index 100% rename from dScripts/GfApeSmashingQB.cpp rename to dScripts/02_server/Enemy/General/GfApeSmashingQB.cpp diff --git a/dScripts/GfApeSmashingQB.h b/dScripts/02_server/Enemy/General/GfApeSmashingQB.h similarity index 100% rename from dScripts/GfApeSmashingQB.h rename to dScripts/02_server/Enemy/General/GfApeSmashingQB.h diff --git a/dScripts/TreasureChestDragonServer.cpp b/dScripts/02_server/Enemy/General/TreasureChestDragonServer.cpp similarity index 100% rename from dScripts/TreasureChestDragonServer.cpp rename to dScripts/02_server/Enemy/General/TreasureChestDragonServer.cpp diff --git a/dScripts/TreasureChestDragonServer.h b/dScripts/02_server/Enemy/General/TreasureChestDragonServer.h similarity index 100% rename from dScripts/TreasureChestDragonServer.h rename to dScripts/02_server/Enemy/General/TreasureChestDragonServer.h diff --git a/dScripts/AgSurvivalMech.cpp b/dScripts/02_server/Enemy/Survival/AgSurvivalMech.cpp similarity index 100% rename from dScripts/AgSurvivalMech.cpp rename to dScripts/02_server/Enemy/Survival/AgSurvivalMech.cpp diff --git a/dScripts/AgSurvivalMech.h b/dScripts/02_server/Enemy/Survival/AgSurvivalMech.h similarity index 100% rename from dScripts/AgSurvivalMech.h rename to dScripts/02_server/Enemy/Survival/AgSurvivalMech.h diff --git a/dScripts/AgSurvivalSpiderling.cpp b/dScripts/02_server/Enemy/Survival/AgSurvivalSpiderling.cpp similarity index 100% rename from dScripts/AgSurvivalSpiderling.cpp rename to dScripts/02_server/Enemy/Survival/AgSurvivalSpiderling.cpp diff --git a/dScripts/AgSurvivalSpiderling.h b/dScripts/02_server/Enemy/Survival/AgSurvivalSpiderling.h similarity index 100% rename from dScripts/AgSurvivalSpiderling.h rename to dScripts/02_server/Enemy/Survival/AgSurvivalSpiderling.h diff --git a/dScripts/AgSurvivalStromling.cpp b/dScripts/02_server/Enemy/Survival/AgSurvivalStromling.cpp similarity index 100% rename from dScripts/AgSurvivalStromling.cpp rename to dScripts/02_server/Enemy/Survival/AgSurvivalStromling.cpp diff --git a/dScripts/AgSurvivalStromling.h b/dScripts/02_server/Enemy/Survival/AgSurvivalStromling.h similarity index 100% rename from dScripts/AgSurvivalStromling.h rename to dScripts/02_server/Enemy/Survival/AgSurvivalStromling.h diff --git a/dScripts/02_server/Enemy/Survival/CMakeLists.txt b/dScripts/02_server/Enemy/Survival/CMakeLists.txt new file mode 100644 index 00000000..55236240 --- /dev/null +++ b/dScripts/02_server/Enemy/Survival/CMakeLists.txt @@ -0,0 +1,5 @@ +set(DSCRIPTS_SOURCES_02_SERVER_ENEMY_SURVIVAL + "AgSurvivalStromling.cpp" + "AgSurvivalMech.cpp" + "AgSurvivalSpiderling.cpp" + PARENT_SCOPE) diff --git a/dScripts/02_server/Enemy/VE/CMakeLists.txt b/dScripts/02_server/Enemy/VE/CMakeLists.txt new file mode 100644 index 00000000..a1cc39ad --- /dev/null +++ b/dScripts/02_server/Enemy/VE/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_02_SERVER_ENEMY_VE + "VeMech.cpp" + PARENT_SCOPE) diff --git a/dScripts/VeMech.cpp b/dScripts/02_server/Enemy/VE/VeMech.cpp similarity index 100% rename from dScripts/VeMech.cpp rename to dScripts/02_server/Enemy/VE/VeMech.cpp diff --git a/dScripts/VeMech.h b/dScripts/02_server/Enemy/VE/VeMech.h similarity index 100% rename from dScripts/VeMech.h rename to dScripts/02_server/Enemy/VE/VeMech.h diff --git a/dScripts/02_server/Enemy/Waves/CMakeLists.txt b/dScripts/02_server/Enemy/Waves/CMakeLists.txt new file mode 100644 index 00000000..a25aca38 --- /dev/null +++ b/dScripts/02_server/Enemy/Waves/CMakeLists.txt @@ -0,0 +1,6 @@ +set(DSCRIPTS_SOURCES_02_SERVER_ENEMY_WAVES + "WaveBossHammerling.cpp" + "WaveBossApe.cpp" + "WaveBossSpiderling.cpp" + "WaveBossHorsemen.cpp" + PARENT_SCOPE) diff --git a/dScripts/WaveBossApe.cpp b/dScripts/02_server/Enemy/Waves/WaveBossApe.cpp similarity index 100% rename from dScripts/WaveBossApe.cpp rename to dScripts/02_server/Enemy/Waves/WaveBossApe.cpp diff --git a/dScripts/WaveBossApe.h b/dScripts/02_server/Enemy/Waves/WaveBossApe.h similarity index 100% rename from dScripts/WaveBossApe.h rename to dScripts/02_server/Enemy/Waves/WaveBossApe.h diff --git a/dScripts/WaveBossHammerling.cpp b/dScripts/02_server/Enemy/Waves/WaveBossHammerling.cpp similarity index 100% rename from dScripts/WaveBossHammerling.cpp rename to dScripts/02_server/Enemy/Waves/WaveBossHammerling.cpp diff --git a/dScripts/WaveBossHammerling.h b/dScripts/02_server/Enemy/Waves/WaveBossHammerling.h similarity index 100% rename from dScripts/WaveBossHammerling.h rename to dScripts/02_server/Enemy/Waves/WaveBossHammerling.h diff --git a/dScripts/WaveBossHorsemen.cpp b/dScripts/02_server/Enemy/Waves/WaveBossHorsemen.cpp similarity index 100% rename from dScripts/WaveBossHorsemen.cpp rename to dScripts/02_server/Enemy/Waves/WaveBossHorsemen.cpp diff --git a/dScripts/WaveBossHorsemen.h b/dScripts/02_server/Enemy/Waves/WaveBossHorsemen.h similarity index 100% rename from dScripts/WaveBossHorsemen.h rename to dScripts/02_server/Enemy/Waves/WaveBossHorsemen.h diff --git a/dScripts/WaveBossSpiderling.cpp b/dScripts/02_server/Enemy/Waves/WaveBossSpiderling.cpp similarity index 100% rename from dScripts/WaveBossSpiderling.cpp rename to dScripts/02_server/Enemy/Waves/WaveBossSpiderling.cpp diff --git a/dScripts/WaveBossSpiderling.h b/dScripts/02_server/Enemy/Waves/WaveBossSpiderling.h similarity index 100% rename from dScripts/WaveBossSpiderling.h rename to dScripts/02_server/Enemy/Waves/WaveBossSpiderling.h diff --git a/dScripts/BootyDigServer.cpp b/dScripts/02_server/Equipment/BootyDigServer.cpp similarity index 100% rename from dScripts/BootyDigServer.cpp rename to dScripts/02_server/Equipment/BootyDigServer.cpp diff --git a/dScripts/BootyDigServer.h b/dScripts/02_server/Equipment/BootyDigServer.h similarity index 100% rename from dScripts/BootyDigServer.h rename to dScripts/02_server/Equipment/BootyDigServer.h diff --git a/dScripts/02_server/Equipment/CMakeLists.txt b/dScripts/02_server/Equipment/CMakeLists.txt new file mode 100644 index 00000000..d29e7ca7 --- /dev/null +++ b/dScripts/02_server/Equipment/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DSCRIPTS_SOURCES_02_SERVER_EQUIPMENT + "MaestromExtracticatorServer.cpp" + "BootyDigServer.cpp" + PARENT_SCOPE) diff --git a/dScripts/MaestromExtracticatorServer.cpp b/dScripts/02_server/Equipment/MaestromExtracticatorServer.cpp similarity index 100% rename from dScripts/MaestromExtracticatorServer.cpp rename to dScripts/02_server/Equipment/MaestromExtracticatorServer.cpp diff --git a/dScripts/MaestromExtracticatorServer.h b/dScripts/02_server/Equipment/MaestromExtracticatorServer.h similarity index 100% rename from dScripts/MaestromExtracticatorServer.h rename to dScripts/02_server/Equipment/MaestromExtracticatorServer.h diff --git a/dScripts/AgBugsprayer.cpp b/dScripts/02_server/Map/AG/AgBugsprayer.cpp similarity index 100% rename from dScripts/AgBugsprayer.cpp rename to dScripts/02_server/Map/AG/AgBugsprayer.cpp diff --git a/dScripts/AgBugsprayer.h b/dScripts/02_server/Map/AG/AgBugsprayer.h similarity index 100% rename from dScripts/AgBugsprayer.h rename to dScripts/02_server/Map/AG/AgBugsprayer.h diff --git a/dScripts/AgCagedBricksServer.cpp b/dScripts/02_server/Map/AG/AgCagedBricksServer.cpp similarity index 100% rename from dScripts/AgCagedBricksServer.cpp rename to dScripts/02_server/Map/AG/AgCagedBricksServer.cpp diff --git a/dScripts/AgCagedBricksServer.h b/dScripts/02_server/Map/AG/AgCagedBricksServer.h similarity index 100% rename from dScripts/AgCagedBricksServer.h rename to dScripts/02_server/Map/AG/AgCagedBricksServer.h diff --git a/dScripts/AgLaserSensorServer.cpp b/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp similarity index 100% rename from dScripts/AgLaserSensorServer.cpp rename to dScripts/02_server/Map/AG/AgLaserSensorServer.cpp diff --git a/dScripts/AgLaserSensorServer.h b/dScripts/02_server/Map/AG/AgLaserSensorServer.h similarity index 100% rename from dScripts/AgLaserSensorServer.h rename to dScripts/02_server/Map/AG/AgLaserSensorServer.h diff --git a/dScripts/AgMonumentBirds.cpp b/dScripts/02_server/Map/AG/AgMonumentBirds.cpp similarity index 100% rename from dScripts/AgMonumentBirds.cpp rename to dScripts/02_server/Map/AG/AgMonumentBirds.cpp diff --git a/dScripts/AgMonumentBirds.h b/dScripts/02_server/Map/AG/AgMonumentBirds.h similarity index 100% rename from dScripts/AgMonumentBirds.h rename to dScripts/02_server/Map/AG/AgMonumentBirds.h diff --git a/dScripts/AgMonumentLaserServer.cpp b/dScripts/02_server/Map/AG/AgMonumentLaserServer.cpp similarity index 100% rename from dScripts/AgMonumentLaserServer.cpp rename to dScripts/02_server/Map/AG/AgMonumentLaserServer.cpp diff --git a/dScripts/AgMonumentLaserServer.h b/dScripts/02_server/Map/AG/AgMonumentLaserServer.h similarity index 100% rename from dScripts/AgMonumentLaserServer.h rename to dScripts/02_server/Map/AG/AgMonumentLaserServer.h diff --git a/dScripts/AgMonumentRaceCancel.cpp b/dScripts/02_server/Map/AG/AgMonumentRaceCancel.cpp similarity index 100% rename from dScripts/AgMonumentRaceCancel.cpp rename to dScripts/02_server/Map/AG/AgMonumentRaceCancel.cpp diff --git a/dScripts/AgMonumentRaceCancel.h b/dScripts/02_server/Map/AG/AgMonumentRaceCancel.h similarity index 100% rename from dScripts/AgMonumentRaceCancel.h rename to dScripts/02_server/Map/AG/AgMonumentRaceCancel.h diff --git a/dScripts/AgMonumentRaceGoal.cpp b/dScripts/02_server/Map/AG/AgMonumentRaceGoal.cpp similarity index 100% rename from dScripts/AgMonumentRaceGoal.cpp rename to dScripts/02_server/Map/AG/AgMonumentRaceGoal.cpp diff --git a/dScripts/AgMonumentRaceGoal.h b/dScripts/02_server/Map/AG/AgMonumentRaceGoal.h similarity index 100% rename from dScripts/AgMonumentRaceGoal.h rename to dScripts/02_server/Map/AG/AgMonumentRaceGoal.h diff --git a/dScripts/02_server/Map/AG/CMakeLists.txt b/dScripts/02_server/Map/AG/CMakeLists.txt new file mode 100644 index 00000000..df26dee4 --- /dev/null +++ b/dScripts/02_server/Map/AG/CMakeLists.txt @@ -0,0 +1,16 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_AG + "AgCagedBricksServer.cpp" + "NpcWispServer.cpp" + "NpcEpsilonServer.cpp" + "AgLaserSensorServer.cpp" + "AgMonumentLaserServer.cpp" + "AgMonumentBirds.cpp" + "RemoveRentalGear.cpp" + "NpcNjAssistantServer.cpp" + "AgBugsprayer.cpp" + "NpcAgCourseStarter.cpp" + "AgMonumentRaceGoal.cpp" + "AgMonumentRaceCancel.cpp" + "NpcCowboyServer.cpp" + "NpcPirateServer.cpp" + PARENT_SCOPE) diff --git a/dScripts/NpcAgCourseStarter.cpp b/dScripts/02_server/Map/AG/NpcAgCourseStarter.cpp similarity index 100% rename from dScripts/NpcAgCourseStarter.cpp rename to dScripts/02_server/Map/AG/NpcAgCourseStarter.cpp diff --git a/dScripts/NpcAgCourseStarter.h b/dScripts/02_server/Map/AG/NpcAgCourseStarter.h similarity index 100% rename from dScripts/NpcAgCourseStarter.h rename to dScripts/02_server/Map/AG/NpcAgCourseStarter.h diff --git a/dScripts/NpcCowboyServer.cpp b/dScripts/02_server/Map/AG/NpcCowboyServer.cpp similarity index 100% rename from dScripts/NpcCowboyServer.cpp rename to dScripts/02_server/Map/AG/NpcCowboyServer.cpp diff --git a/dScripts/NpcCowboyServer.h b/dScripts/02_server/Map/AG/NpcCowboyServer.h similarity index 100% rename from dScripts/NpcCowboyServer.h rename to dScripts/02_server/Map/AG/NpcCowboyServer.h diff --git a/dScripts/NpcEpsilonServer.cpp b/dScripts/02_server/Map/AG/NpcEpsilonServer.cpp similarity index 100% rename from dScripts/NpcEpsilonServer.cpp rename to dScripts/02_server/Map/AG/NpcEpsilonServer.cpp diff --git a/dScripts/NpcEpsilonServer.h b/dScripts/02_server/Map/AG/NpcEpsilonServer.h similarity index 100% rename from dScripts/NpcEpsilonServer.h rename to dScripts/02_server/Map/AG/NpcEpsilonServer.h diff --git a/dScripts/NpcNjAssistantServer.cpp b/dScripts/02_server/Map/AG/NpcNjAssistantServer.cpp similarity index 100% rename from dScripts/NpcNjAssistantServer.cpp rename to dScripts/02_server/Map/AG/NpcNjAssistantServer.cpp diff --git a/dScripts/NpcNjAssistantServer.h b/dScripts/02_server/Map/AG/NpcNjAssistantServer.h similarity index 100% rename from dScripts/NpcNjAssistantServer.h rename to dScripts/02_server/Map/AG/NpcNjAssistantServer.h diff --git a/dScripts/NpcPirateServer.cpp b/dScripts/02_server/Map/AG/NpcPirateServer.cpp similarity index 100% rename from dScripts/NpcPirateServer.cpp rename to dScripts/02_server/Map/AG/NpcPirateServer.cpp diff --git a/dScripts/NpcPirateServer.h b/dScripts/02_server/Map/AG/NpcPirateServer.h similarity index 100% rename from dScripts/NpcPirateServer.h rename to dScripts/02_server/Map/AG/NpcPirateServer.h diff --git a/dScripts/NpcWispServer.cpp b/dScripts/02_server/Map/AG/NpcWispServer.cpp similarity index 100% rename from dScripts/NpcWispServer.cpp rename to dScripts/02_server/Map/AG/NpcWispServer.cpp diff --git a/dScripts/NpcWispServer.h b/dScripts/02_server/Map/AG/NpcWispServer.h similarity index 100% rename from dScripts/NpcWispServer.h rename to dScripts/02_server/Map/AG/NpcWispServer.h diff --git a/dScripts/RemoveRentalGear.cpp b/dScripts/02_server/Map/AG/RemoveRentalGear.cpp similarity index 100% rename from dScripts/RemoveRentalGear.cpp rename to dScripts/02_server/Map/AG/RemoveRentalGear.cpp diff --git a/dScripts/RemoveRentalGear.h b/dScripts/02_server/Map/AG/RemoveRentalGear.h similarity index 100% rename from dScripts/RemoveRentalGear.h rename to dScripts/02_server/Map/AG/RemoveRentalGear.h diff --git a/dScripts/02_server/Map/AG_Spider_Queen/CMakeLists.txt b/dScripts/02_server/Map/AG_Spider_Queen/CMakeLists.txt new file mode 100644 index 00000000..f4204c13 --- /dev/null +++ b/dScripts/02_server/Map/AG_Spider_Queen/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_AG_SPIDER_QUEEN + "ZoneAgSpiderQueen.cpp" + "SpiderBossTreasureChestServer.cpp" + PARENT_SCOPE) diff --git a/dScripts/SpiderBossTreasureChestServer.cpp b/dScripts/02_server/Map/AG_Spider_Queen/SpiderBossTreasureChestServer.cpp similarity index 100% rename from dScripts/SpiderBossTreasureChestServer.cpp rename to dScripts/02_server/Map/AG_Spider_Queen/SpiderBossTreasureChestServer.cpp diff --git a/dScripts/SpiderBossTreasureChestServer.h b/dScripts/02_server/Map/AG_Spider_Queen/SpiderBossTreasureChestServer.h similarity index 100% rename from dScripts/SpiderBossTreasureChestServer.h rename to dScripts/02_server/Map/AG_Spider_Queen/SpiderBossTreasureChestServer.h diff --git a/dScripts/ZoneAgSpiderQueen.cpp b/dScripts/02_server/Map/AG_Spider_Queen/ZoneAgSpiderQueen.cpp similarity index 100% rename from dScripts/ZoneAgSpiderQueen.cpp rename to dScripts/02_server/Map/AG_Spider_Queen/ZoneAgSpiderQueen.cpp diff --git a/dScripts/ZoneAgSpiderQueen.h b/dScripts/02_server/Map/AG_Spider_Queen/ZoneAgSpiderQueen.h similarity index 100% rename from dScripts/ZoneAgSpiderQueen.h rename to dScripts/02_server/Map/AG_Spider_Queen/ZoneAgSpiderQueen.h diff --git a/dScripts/AmBlueX.cpp b/dScripts/02_server/Map/AM/AmBlueX.cpp similarity index 100% rename from dScripts/AmBlueX.cpp rename to dScripts/02_server/Map/AM/AmBlueX.cpp diff --git a/dScripts/AmBlueX.h b/dScripts/02_server/Map/AM/AmBlueX.h similarity index 100% rename from dScripts/AmBlueX.h rename to dScripts/02_server/Map/AM/AmBlueX.h diff --git a/dScripts/AmBridge.cpp b/dScripts/02_server/Map/AM/AmBridge.cpp similarity index 100% rename from dScripts/AmBridge.cpp rename to dScripts/02_server/Map/AM/AmBridge.cpp diff --git a/dScripts/AmBridge.h b/dScripts/02_server/Map/AM/AmBridge.h similarity index 100% rename from dScripts/AmBridge.h rename to dScripts/02_server/Map/AM/AmBridge.h diff --git a/dScripts/AmConsoleTeleportServer.cpp b/dScripts/02_server/Map/AM/AmConsoleTeleportServer.cpp similarity index 100% rename from dScripts/AmConsoleTeleportServer.cpp rename to dScripts/02_server/Map/AM/AmConsoleTeleportServer.cpp diff --git a/dScripts/AmConsoleTeleportServer.h b/dScripts/02_server/Map/AM/AmConsoleTeleportServer.h similarity index 100% rename from dScripts/AmConsoleTeleportServer.h rename to dScripts/02_server/Map/AM/AmConsoleTeleportServer.h diff --git a/dScripts/AmDrawBridge.cpp b/dScripts/02_server/Map/AM/AmDrawBridge.cpp similarity index 100% rename from dScripts/AmDrawBridge.cpp rename to dScripts/02_server/Map/AM/AmDrawBridge.cpp diff --git a/dScripts/AmDrawBridge.h b/dScripts/02_server/Map/AM/AmDrawBridge.h similarity index 100% rename from dScripts/AmDrawBridge.h rename to dScripts/02_server/Map/AM/AmDrawBridge.h diff --git a/dScripts/AmDropshipComputer.cpp b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp similarity index 100% rename from dScripts/AmDropshipComputer.cpp rename to dScripts/02_server/Map/AM/AmDropshipComputer.cpp diff --git a/dScripts/AmDropshipComputer.h b/dScripts/02_server/Map/AM/AmDropshipComputer.h similarity index 100% rename from dScripts/AmDropshipComputer.h rename to dScripts/02_server/Map/AM/AmDropshipComputer.h diff --git a/dScripts/AmScrollReaderServer.cpp b/dScripts/02_server/Map/AM/AmScrollReaderServer.cpp similarity index 100% rename from dScripts/AmScrollReaderServer.cpp rename to dScripts/02_server/Map/AM/AmScrollReaderServer.cpp diff --git a/dScripts/AmScrollReaderServer.h b/dScripts/02_server/Map/AM/AmScrollReaderServer.h similarity index 100% rename from dScripts/AmScrollReaderServer.h rename to dScripts/02_server/Map/AM/AmScrollReaderServer.h diff --git a/dScripts/AmShieldGenerator.cpp b/dScripts/02_server/Map/AM/AmShieldGenerator.cpp similarity index 100% rename from dScripts/AmShieldGenerator.cpp rename to dScripts/02_server/Map/AM/AmShieldGenerator.cpp diff --git a/dScripts/AmShieldGenerator.h b/dScripts/02_server/Map/AM/AmShieldGenerator.h similarity index 100% rename from dScripts/AmShieldGenerator.h rename to dScripts/02_server/Map/AM/AmShieldGenerator.h diff --git a/dScripts/AmShieldGeneratorQuickbuild.cpp b/dScripts/02_server/Map/AM/AmShieldGeneratorQuickbuild.cpp similarity index 100% rename from dScripts/AmShieldGeneratorQuickbuild.cpp rename to dScripts/02_server/Map/AM/AmShieldGeneratorQuickbuild.cpp diff --git a/dScripts/AmShieldGeneratorQuickbuild.h b/dScripts/02_server/Map/AM/AmShieldGeneratorQuickbuild.h similarity index 100% rename from dScripts/AmShieldGeneratorQuickbuild.h rename to dScripts/02_server/Map/AM/AmShieldGeneratorQuickbuild.h diff --git a/dScripts/AmSkullkinDrill.cpp b/dScripts/02_server/Map/AM/AmSkullkinDrill.cpp similarity index 100% rename from dScripts/AmSkullkinDrill.cpp rename to dScripts/02_server/Map/AM/AmSkullkinDrill.cpp diff --git a/dScripts/AmSkullkinDrill.h b/dScripts/02_server/Map/AM/AmSkullkinDrill.h similarity index 100% rename from dScripts/AmSkullkinDrill.h rename to dScripts/02_server/Map/AM/AmSkullkinDrill.h diff --git a/dScripts/AmSkullkinDrillStand.cpp b/dScripts/02_server/Map/AM/AmSkullkinDrillStand.cpp similarity index 100% rename from dScripts/AmSkullkinDrillStand.cpp rename to dScripts/02_server/Map/AM/AmSkullkinDrillStand.cpp diff --git a/dScripts/AmSkullkinDrillStand.h b/dScripts/02_server/Map/AM/AmSkullkinDrillStand.h similarity index 100% rename from dScripts/AmSkullkinDrillStand.h rename to dScripts/02_server/Map/AM/AmSkullkinDrillStand.h diff --git a/dScripts/AmSkullkinTower.cpp b/dScripts/02_server/Map/AM/AmSkullkinTower.cpp similarity index 100% rename from dScripts/AmSkullkinTower.cpp rename to dScripts/02_server/Map/AM/AmSkullkinTower.cpp diff --git a/dScripts/AmSkullkinTower.h b/dScripts/02_server/Map/AM/AmSkullkinTower.h similarity index 100% rename from dScripts/AmSkullkinTower.h rename to dScripts/02_server/Map/AM/AmSkullkinTower.h diff --git a/dScripts/AmTeapotServer.cpp b/dScripts/02_server/Map/AM/AmTeapotServer.cpp similarity index 100% rename from dScripts/AmTeapotServer.cpp rename to dScripts/02_server/Map/AM/AmTeapotServer.cpp diff --git a/dScripts/AmTeapotServer.h b/dScripts/02_server/Map/AM/AmTeapotServer.h similarity index 100% rename from dScripts/AmTeapotServer.h rename to dScripts/02_server/Map/AM/AmTeapotServer.h diff --git a/dScripts/AmTemplateSkillVolume.cpp b/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp similarity index 100% rename from dScripts/AmTemplateSkillVolume.cpp rename to dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp diff --git a/dScripts/AmTemplateSkillVolume.h b/dScripts/02_server/Map/AM/AmTemplateSkillVolume.h similarity index 100% rename from dScripts/AmTemplateSkillVolume.h rename to dScripts/02_server/Map/AM/AmTemplateSkillVolume.h diff --git a/dScripts/02_server/Map/AM/CMakeLists.txt b/dScripts/02_server/Map/AM/CMakeLists.txt new file mode 100644 index 00000000..d3d13b73 --- /dev/null +++ b/dScripts/02_server/Map/AM/CMakeLists.txt @@ -0,0 +1,19 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_AM + "AmConsoleTeleportServer.cpp" + "RandomSpawnerFin.cpp" + "RandomSpawnerPit.cpp" + "RandomSpawnerStr.cpp" + "RandomSpawnerZip.cpp" + "AmBridge.cpp" + "AmDrawBridge.cpp" + "AmShieldGenerator.cpp" + "AmShieldGeneratorQuickbuild.cpp" + "AmDropshipComputer.cpp" + "AmScrollReaderServer.cpp" + "AmTemplateSkillVolume.cpp" + "AmSkullkinDrill.cpp" + "AmSkullkinDrillStand.cpp" + "AmSkullkinTower.cpp" + "AmBlueX.cpp" + "AmTeapotServer.cpp" + PARENT_SCOPE) diff --git a/dScripts/RandomSpawnerFin.cpp b/dScripts/02_server/Map/AM/RandomSpawnerFin.cpp similarity index 100% rename from dScripts/RandomSpawnerFin.cpp rename to dScripts/02_server/Map/AM/RandomSpawnerFin.cpp diff --git a/dScripts/RandomSpawnerFin.h b/dScripts/02_server/Map/AM/RandomSpawnerFin.h similarity index 100% rename from dScripts/RandomSpawnerFin.h rename to dScripts/02_server/Map/AM/RandomSpawnerFin.h diff --git a/dScripts/RandomSpawnerPit.cpp b/dScripts/02_server/Map/AM/RandomSpawnerPit.cpp similarity index 100% rename from dScripts/RandomSpawnerPit.cpp rename to dScripts/02_server/Map/AM/RandomSpawnerPit.cpp diff --git a/dScripts/RandomSpawnerPit.h b/dScripts/02_server/Map/AM/RandomSpawnerPit.h similarity index 100% rename from dScripts/RandomSpawnerPit.h rename to dScripts/02_server/Map/AM/RandomSpawnerPit.h diff --git a/dScripts/RandomSpawnerStr.cpp b/dScripts/02_server/Map/AM/RandomSpawnerStr.cpp similarity index 100% rename from dScripts/RandomSpawnerStr.cpp rename to dScripts/02_server/Map/AM/RandomSpawnerStr.cpp diff --git a/dScripts/RandomSpawnerStr.h b/dScripts/02_server/Map/AM/RandomSpawnerStr.h similarity index 100% rename from dScripts/RandomSpawnerStr.h rename to dScripts/02_server/Map/AM/RandomSpawnerStr.h diff --git a/dScripts/RandomSpawnerZip.cpp b/dScripts/02_server/Map/AM/RandomSpawnerZip.cpp similarity index 100% rename from dScripts/RandomSpawnerZip.cpp rename to dScripts/02_server/Map/AM/RandomSpawnerZip.cpp diff --git a/dScripts/RandomSpawnerZip.h b/dScripts/02_server/Map/AM/RandomSpawnerZip.h similarity index 100% rename from dScripts/RandomSpawnerZip.h rename to dScripts/02_server/Map/AM/RandomSpawnerZip.h diff --git a/dScripts/02_server/Map/CMakeLists.txt b/dScripts/02_server/Map/CMakeLists.txt new file mode 100644 index 00000000..feed8a97 --- /dev/null +++ b/dScripts/02_server/Map/CMakeLists.txt @@ -0,0 +1,81 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP) + +add_subdirectory(AG) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_AG}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} "AG/${file}") +endforeach() + +add_subdirectory(AG_Spider_Queen) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_AG_SPIDER_QUEEN}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} "AG_Spider_Queen/${file}") +endforeach() + +add_subdirectory(AM) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_AM}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} "AM/${file}") +endforeach() + +add_subdirectory(FV) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_FV}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} "FV/${file}") +endforeach() + +add_subdirectory(General) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_GENERAL}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} "General/${file}") +endforeach() + +add_subdirectory(GF) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_GF}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} "GF/${file}") +endforeach() + +add_subdirectory(njhub) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_NJHUB}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} "njhub/${file}") +endforeach() + +add_subdirectory(NS) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_NS}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} "NS/${file}") +endforeach() + +add_subdirectory(NT) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_NT}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} "NT/${file}") +endforeach() + +add_subdirectory(PR) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_PR}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} "PR/${file}") +endforeach() + +add_subdirectory(Property) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} "Property/${file}") +endforeach() + +add_subdirectory(SS) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_SS}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} "SS/${file}") +endforeach() + +add_subdirectory(VE) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_VE}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} "VE/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_02_SERVER_MAP ${DSCRIPTS_SOURCES_02_SERVER_MAP} PARENT_SCOPE) diff --git a/dScripts/02_server/Map/FV/CMakeLists.txt b/dScripts/02_server/Map/FV/CMakeLists.txt new file mode 100644 index 00000000..505d97c4 --- /dev/null +++ b/dScripts/02_server/Map/FV/CMakeLists.txt @@ -0,0 +1,14 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_FV + "EnemyRoninSpawner.cpp" + "FvCandle.cpp" + "FvFong.cpp" + "FvHorsemenTrigger.cpp" + "ImgBrickConsoleQB.cpp") + +add_subdirectory(Racing) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_FV_RACING}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP_FV ${DSCRIPTS_SOURCES_02_SERVER_MAP_FV} "Racing/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_02_SERVER_MAP_FV ${DSCRIPTS_SOURCES_02_SERVER_MAP_FV} PARENT_SCOPE) diff --git a/dScripts/EnemyRoninSpawner.cpp b/dScripts/02_server/Map/FV/EnemyRoninSpawner.cpp similarity index 100% rename from dScripts/EnemyRoninSpawner.cpp rename to dScripts/02_server/Map/FV/EnemyRoninSpawner.cpp diff --git a/dScripts/EnemyRoninSpawner.h b/dScripts/02_server/Map/FV/EnemyRoninSpawner.h similarity index 100% rename from dScripts/EnemyRoninSpawner.h rename to dScripts/02_server/Map/FV/EnemyRoninSpawner.h diff --git a/dScripts/FvCandle.cpp b/dScripts/02_server/Map/FV/FvCandle.cpp similarity index 100% rename from dScripts/FvCandle.cpp rename to dScripts/02_server/Map/FV/FvCandle.cpp diff --git a/dScripts/FvCandle.h b/dScripts/02_server/Map/FV/FvCandle.h similarity index 100% rename from dScripts/FvCandle.h rename to dScripts/02_server/Map/FV/FvCandle.h diff --git a/dScripts/FvFong.cpp b/dScripts/02_server/Map/FV/FvFong.cpp similarity index 100% rename from dScripts/FvFong.cpp rename to dScripts/02_server/Map/FV/FvFong.cpp diff --git a/dScripts/FvFong.h b/dScripts/02_server/Map/FV/FvFong.h similarity index 100% rename from dScripts/FvFong.h rename to dScripts/02_server/Map/FV/FvFong.h diff --git a/dScripts/FvHorsemenTrigger.cpp b/dScripts/02_server/Map/FV/FvHorsemenTrigger.cpp similarity index 100% rename from dScripts/FvHorsemenTrigger.cpp rename to dScripts/02_server/Map/FV/FvHorsemenTrigger.cpp diff --git a/dScripts/FvHorsemenTrigger.h b/dScripts/02_server/Map/FV/FvHorsemenTrigger.h similarity index 100% rename from dScripts/FvHorsemenTrigger.h rename to dScripts/02_server/Map/FV/FvHorsemenTrigger.h diff --git a/dScripts/ImgBrickConsoleQB.cpp b/dScripts/02_server/Map/FV/ImgBrickConsoleQB.cpp similarity index 100% rename from dScripts/ImgBrickConsoleQB.cpp rename to dScripts/02_server/Map/FV/ImgBrickConsoleQB.cpp diff --git a/dScripts/ImgBrickConsoleQB.h b/dScripts/02_server/Map/FV/ImgBrickConsoleQB.h similarity index 100% rename from dScripts/ImgBrickConsoleQB.h rename to dScripts/02_server/Map/FV/ImgBrickConsoleQB.h diff --git a/dScripts/02_server/Map/FV/Racing/CMakeLists.txt b/dScripts/02_server/Map/FV/Racing/CMakeLists.txt new file mode 100644 index 00000000..89536b67 --- /dev/null +++ b/dScripts/02_server/Map/FV/Racing/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_FV_RACING + "RaceMaelstromGeiser.cpp" + PARENT_SCOPE) diff --git a/dScripts/RaceMaelstromGeiser.cpp b/dScripts/02_server/Map/FV/Racing/RaceMaelstromGeiser.cpp similarity index 100% rename from dScripts/RaceMaelstromGeiser.cpp rename to dScripts/02_server/Map/FV/Racing/RaceMaelstromGeiser.cpp diff --git a/dScripts/RaceMaelstromGeiser.h b/dScripts/02_server/Map/FV/Racing/RaceMaelstromGeiser.h similarity index 100% rename from dScripts/RaceMaelstromGeiser.h rename to dScripts/02_server/Map/FV/Racing/RaceMaelstromGeiser.h diff --git a/dScripts/02_server/Map/GF/CMakeLists.txt b/dScripts/02_server/Map/GF/CMakeLists.txt new file mode 100644 index 00000000..90cc38a5 --- /dev/null +++ b/dScripts/02_server/Map/GF/CMakeLists.txt @@ -0,0 +1,6 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_GF + "GfTikiTorch.cpp" + "GfCaptainsCannon.cpp" + "MastTeleport.cpp" + "SpawnLionServer.cpp" + PARENT_SCOPE) diff --git a/dScripts/GfCaptainsCannon.cpp b/dScripts/02_server/Map/GF/GfCaptainsCannon.cpp similarity index 100% rename from dScripts/GfCaptainsCannon.cpp rename to dScripts/02_server/Map/GF/GfCaptainsCannon.cpp diff --git a/dScripts/GfCaptainsCannon.h b/dScripts/02_server/Map/GF/GfCaptainsCannon.h similarity index 100% rename from dScripts/GfCaptainsCannon.h rename to dScripts/02_server/Map/GF/GfCaptainsCannon.h diff --git a/dScripts/GfTikiTorch.cpp b/dScripts/02_server/Map/GF/GfTikiTorch.cpp similarity index 100% rename from dScripts/GfTikiTorch.cpp rename to dScripts/02_server/Map/GF/GfTikiTorch.cpp diff --git a/dScripts/GfTikiTorch.h b/dScripts/02_server/Map/GF/GfTikiTorch.h similarity index 100% rename from dScripts/GfTikiTorch.h rename to dScripts/02_server/Map/GF/GfTikiTorch.h diff --git a/dScripts/MastTeleport.cpp b/dScripts/02_server/Map/GF/MastTeleport.cpp similarity index 100% rename from dScripts/MastTeleport.cpp rename to dScripts/02_server/Map/GF/MastTeleport.cpp diff --git a/dScripts/MastTeleport.h b/dScripts/02_server/Map/GF/MastTeleport.h similarity index 100% rename from dScripts/MastTeleport.h rename to dScripts/02_server/Map/GF/MastTeleport.h diff --git a/dScripts/SpawnLionServer.cpp b/dScripts/02_server/Map/GF/SpawnLionServer.cpp similarity index 100% rename from dScripts/SpawnLionServer.cpp rename to dScripts/02_server/Map/GF/SpawnLionServer.cpp diff --git a/dScripts/SpawnLionServer.h b/dScripts/02_server/Map/GF/SpawnLionServer.h similarity index 100% rename from dScripts/SpawnLionServer.h rename to dScripts/02_server/Map/GF/SpawnLionServer.h diff --git a/dScripts/BankInteractServer.cpp b/dScripts/02_server/Map/General/BankInteractServer.cpp similarity index 100% rename from dScripts/BankInteractServer.cpp rename to dScripts/02_server/Map/General/BankInteractServer.cpp diff --git a/dScripts/BankInteractServer.h b/dScripts/02_server/Map/General/BankInteractServer.h similarity index 100% rename from dScripts/BankInteractServer.h rename to dScripts/02_server/Map/General/BankInteractServer.h diff --git a/dScripts/BaseInteractDropLootServer.cpp b/dScripts/02_server/Map/General/BaseInteractDropLootServer.cpp similarity index 100% rename from dScripts/BaseInteractDropLootServer.cpp rename to dScripts/02_server/Map/General/BaseInteractDropLootServer.cpp diff --git a/dScripts/BaseInteractDropLootServer.h b/dScripts/02_server/Map/General/BaseInteractDropLootServer.h similarity index 100% rename from dScripts/BaseInteractDropLootServer.h rename to dScripts/02_server/Map/General/BaseInteractDropLootServer.h diff --git a/dScripts/Binoculars.cpp b/dScripts/02_server/Map/General/Binoculars.cpp similarity index 100% rename from dScripts/Binoculars.cpp rename to dScripts/02_server/Map/General/Binoculars.cpp diff --git a/dScripts/Binoculars.h b/dScripts/02_server/Map/General/Binoculars.h similarity index 100% rename from dScripts/Binoculars.h rename to dScripts/02_server/Map/General/Binoculars.h diff --git a/dScripts/02_server/Map/General/CMakeLists.txt b/dScripts/02_server/Map/General/CMakeLists.txt new file mode 100644 index 00000000..1fe3d785 --- /dev/null +++ b/dScripts/02_server/Map/General/CMakeLists.txt @@ -0,0 +1,28 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_GENERAL + "BankInteractServer.cpp" + "BaseInteractDropLootServer.cpp" + "Binoculars.cpp" + "ExplodingAsset.cpp" + "ForceVolumeServer.cpp" + "GrowingFlower.cpp" + "ImaginationBackpackHealServer.cpp" + "InvalidScript.cpp" + "MailBoxServer.cpp" + "NjRailSwitch.cpp" + "PetDigServer.cpp" + "PropertyDevice.cpp" + "PropertyPlatform.cpp" + "QbEnemyStunner.cpp" + "QbSpawner.cpp" + "StoryBoxInteractServer.cpp" + "TokenConsoleServer.cpp" + "TouchMissionUpdateServer.cpp" + "WishingWellServer.cpp") + +add_subdirectory(Ninjago) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_GENERAL_NINJAGO}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP_GENERAL ${DSCRIPTS_SOURCES_02_SERVER_MAP_GENERAL} "Ninjago/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_02_SERVER_MAP_GENERAL ${DSCRIPTS_SOURCES_02_SERVER_MAP_GENERAL} PARENT_SCOPE) diff --git a/dScripts/ExplodingAsset.cpp b/dScripts/02_server/Map/General/ExplodingAsset.cpp similarity index 100% rename from dScripts/ExplodingAsset.cpp rename to dScripts/02_server/Map/General/ExplodingAsset.cpp diff --git a/dScripts/ExplodingAsset.h b/dScripts/02_server/Map/General/ExplodingAsset.h similarity index 100% rename from dScripts/ExplodingAsset.h rename to dScripts/02_server/Map/General/ExplodingAsset.h diff --git a/dScripts/ForceVolumeServer.cpp b/dScripts/02_server/Map/General/ForceVolumeServer.cpp similarity index 100% rename from dScripts/ForceVolumeServer.cpp rename to dScripts/02_server/Map/General/ForceVolumeServer.cpp diff --git a/dScripts/ForceVolumeServer.h b/dScripts/02_server/Map/General/ForceVolumeServer.h similarity index 100% rename from dScripts/ForceVolumeServer.h rename to dScripts/02_server/Map/General/ForceVolumeServer.h diff --git a/dScripts/GrowingFlower.cpp b/dScripts/02_server/Map/General/GrowingFlower.cpp similarity index 100% rename from dScripts/GrowingFlower.cpp rename to dScripts/02_server/Map/General/GrowingFlower.cpp diff --git a/dScripts/GrowingFlower.h b/dScripts/02_server/Map/General/GrowingFlower.h similarity index 100% rename from dScripts/GrowingFlower.h rename to dScripts/02_server/Map/General/GrowingFlower.h diff --git a/dScripts/ImaginationBackpackHealServer.cpp b/dScripts/02_server/Map/General/ImaginationBackpackHealServer.cpp similarity index 100% rename from dScripts/ImaginationBackpackHealServer.cpp rename to dScripts/02_server/Map/General/ImaginationBackpackHealServer.cpp diff --git a/dScripts/ImaginationBackpackHealServer.h b/dScripts/02_server/Map/General/ImaginationBackpackHealServer.h similarity index 100% rename from dScripts/ImaginationBackpackHealServer.h rename to dScripts/02_server/Map/General/ImaginationBackpackHealServer.h diff --git a/dScripts/InvalidScript.cpp b/dScripts/02_server/Map/General/InvalidScript.cpp similarity index 100% rename from dScripts/InvalidScript.cpp rename to dScripts/02_server/Map/General/InvalidScript.cpp diff --git a/dScripts/InvalidScript.h b/dScripts/02_server/Map/General/InvalidScript.h similarity index 100% rename from dScripts/InvalidScript.h rename to dScripts/02_server/Map/General/InvalidScript.h diff --git a/dScripts/MailBoxServer.cpp b/dScripts/02_server/Map/General/MailBoxServer.cpp similarity index 100% rename from dScripts/MailBoxServer.cpp rename to dScripts/02_server/Map/General/MailBoxServer.cpp diff --git a/dScripts/MailBoxServer.h b/dScripts/02_server/Map/General/MailBoxServer.h similarity index 100% rename from dScripts/MailBoxServer.h rename to dScripts/02_server/Map/General/MailBoxServer.h diff --git a/dScripts/02_server/Map/General/Ninjago/CMakeLists.txt b/dScripts/02_server/Map/General/Ninjago/CMakeLists.txt new file mode 100644 index 00000000..2b74e921 --- /dev/null +++ b/dScripts/02_server/Map/General/Ninjago/CMakeLists.txt @@ -0,0 +1,6 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_GENERAL_NINJAGO + "NjRailActivatorsServer.cpp" + "NjRailPostServer.cpp" + "NjIceRailActivator.cpp" + "NjhubLavaPlayerDeathTrigger.cpp" + PARENT_SCOPE) diff --git a/dScripts/NjIceRailActivator.cpp b/dScripts/02_server/Map/General/Ninjago/NjIceRailActivator.cpp similarity index 100% rename from dScripts/NjIceRailActivator.cpp rename to dScripts/02_server/Map/General/Ninjago/NjIceRailActivator.cpp diff --git a/dScripts/NjIceRailActivator.h b/dScripts/02_server/Map/General/Ninjago/NjIceRailActivator.h similarity index 100% rename from dScripts/NjIceRailActivator.h rename to dScripts/02_server/Map/General/Ninjago/NjIceRailActivator.h diff --git a/dScripts/NjRailActivatorsServer.cpp b/dScripts/02_server/Map/General/Ninjago/NjRailActivatorsServer.cpp similarity index 100% rename from dScripts/NjRailActivatorsServer.cpp rename to dScripts/02_server/Map/General/Ninjago/NjRailActivatorsServer.cpp diff --git a/dScripts/NjRailActivatorsServer.h b/dScripts/02_server/Map/General/Ninjago/NjRailActivatorsServer.h similarity index 100% rename from dScripts/NjRailActivatorsServer.h rename to dScripts/02_server/Map/General/Ninjago/NjRailActivatorsServer.h diff --git a/dScripts/NjRailPostServer.cpp b/dScripts/02_server/Map/General/Ninjago/NjRailPostServer.cpp similarity index 100% rename from dScripts/NjRailPostServer.cpp rename to dScripts/02_server/Map/General/Ninjago/NjRailPostServer.cpp diff --git a/dScripts/NjRailPostServer.h b/dScripts/02_server/Map/General/Ninjago/NjRailPostServer.h similarity index 100% rename from dScripts/NjRailPostServer.h rename to dScripts/02_server/Map/General/Ninjago/NjRailPostServer.h diff --git a/dScripts/NjhubLavaPlayerDeathTrigger.cpp b/dScripts/02_server/Map/General/Ninjago/NjhubLavaPlayerDeathTrigger.cpp similarity index 100% rename from dScripts/NjhubLavaPlayerDeathTrigger.cpp rename to dScripts/02_server/Map/General/Ninjago/NjhubLavaPlayerDeathTrigger.cpp diff --git a/dScripts/NjhubLavaPlayerDeathTrigger.h b/dScripts/02_server/Map/General/Ninjago/NjhubLavaPlayerDeathTrigger.h similarity index 100% rename from dScripts/NjhubLavaPlayerDeathTrigger.h rename to dScripts/02_server/Map/General/Ninjago/NjhubLavaPlayerDeathTrigger.h diff --git a/dScripts/NjRailSwitch.cpp b/dScripts/02_server/Map/General/NjRailSwitch.cpp similarity index 100% rename from dScripts/NjRailSwitch.cpp rename to dScripts/02_server/Map/General/NjRailSwitch.cpp diff --git a/dScripts/NjRailSwitch.h b/dScripts/02_server/Map/General/NjRailSwitch.h similarity index 100% rename from dScripts/NjRailSwitch.h rename to dScripts/02_server/Map/General/NjRailSwitch.h diff --git a/dScripts/PetDigServer.cpp b/dScripts/02_server/Map/General/PetDigServer.cpp similarity index 100% rename from dScripts/PetDigServer.cpp rename to dScripts/02_server/Map/General/PetDigServer.cpp diff --git a/dScripts/PetDigServer.h b/dScripts/02_server/Map/General/PetDigServer.h similarity index 100% rename from dScripts/PetDigServer.h rename to dScripts/02_server/Map/General/PetDigServer.h diff --git a/dScripts/PropertyDevice.cpp b/dScripts/02_server/Map/General/PropertyDevice.cpp similarity index 100% rename from dScripts/PropertyDevice.cpp rename to dScripts/02_server/Map/General/PropertyDevice.cpp diff --git a/dScripts/PropertyDevice.h b/dScripts/02_server/Map/General/PropertyDevice.h similarity index 100% rename from dScripts/PropertyDevice.h rename to dScripts/02_server/Map/General/PropertyDevice.h diff --git a/dScripts/PropertyPlatform.cpp b/dScripts/02_server/Map/General/PropertyPlatform.cpp similarity index 100% rename from dScripts/PropertyPlatform.cpp rename to dScripts/02_server/Map/General/PropertyPlatform.cpp diff --git a/dScripts/PropertyPlatform.h b/dScripts/02_server/Map/General/PropertyPlatform.h similarity index 100% rename from dScripts/PropertyPlatform.h rename to dScripts/02_server/Map/General/PropertyPlatform.h diff --git a/dScripts/QbEnemyStunner.cpp b/dScripts/02_server/Map/General/QbEnemyStunner.cpp similarity index 100% rename from dScripts/QbEnemyStunner.cpp rename to dScripts/02_server/Map/General/QbEnemyStunner.cpp diff --git a/dScripts/QbEnemyStunner.h b/dScripts/02_server/Map/General/QbEnemyStunner.h similarity index 100% rename from dScripts/QbEnemyStunner.h rename to dScripts/02_server/Map/General/QbEnemyStunner.h diff --git a/dScripts/QbSpawner.cpp b/dScripts/02_server/Map/General/QbSpawner.cpp similarity index 100% rename from dScripts/QbSpawner.cpp rename to dScripts/02_server/Map/General/QbSpawner.cpp diff --git a/dScripts/QbSpawner.h b/dScripts/02_server/Map/General/QbSpawner.h similarity index 100% rename from dScripts/QbSpawner.h rename to dScripts/02_server/Map/General/QbSpawner.h diff --git a/dScripts/StoryBoxInteractServer.cpp b/dScripts/02_server/Map/General/StoryBoxInteractServer.cpp similarity index 100% rename from dScripts/StoryBoxInteractServer.cpp rename to dScripts/02_server/Map/General/StoryBoxInteractServer.cpp diff --git a/dScripts/StoryBoxInteractServer.h b/dScripts/02_server/Map/General/StoryBoxInteractServer.h similarity index 100% rename from dScripts/StoryBoxInteractServer.h rename to dScripts/02_server/Map/General/StoryBoxInteractServer.h diff --git a/dScripts/TokenConsoleServer.cpp b/dScripts/02_server/Map/General/TokenConsoleServer.cpp similarity index 100% rename from dScripts/TokenConsoleServer.cpp rename to dScripts/02_server/Map/General/TokenConsoleServer.cpp diff --git a/dScripts/TokenConsoleServer.h b/dScripts/02_server/Map/General/TokenConsoleServer.h similarity index 100% rename from dScripts/TokenConsoleServer.h rename to dScripts/02_server/Map/General/TokenConsoleServer.h diff --git a/dScripts/TouchMissionUpdateServer.cpp b/dScripts/02_server/Map/General/TouchMissionUpdateServer.cpp similarity index 100% rename from dScripts/TouchMissionUpdateServer.cpp rename to dScripts/02_server/Map/General/TouchMissionUpdateServer.cpp diff --git a/dScripts/TouchMissionUpdateServer.h b/dScripts/02_server/Map/General/TouchMissionUpdateServer.h similarity index 100% rename from dScripts/TouchMissionUpdateServer.h rename to dScripts/02_server/Map/General/TouchMissionUpdateServer.h diff --git a/dScripts/WishingWellServer.cpp b/dScripts/02_server/Map/General/WishingWellServer.cpp similarity index 100% rename from dScripts/WishingWellServer.cpp rename to dScripts/02_server/Map/General/WishingWellServer.cpp diff --git a/dScripts/WishingWellServer.h b/dScripts/02_server/Map/General/WishingWellServer.h similarity index 100% rename from dScripts/WishingWellServer.h rename to dScripts/02_server/Map/General/WishingWellServer.h diff --git a/dScripts/02_server/Map/NS/CMakeLists.txt b/dScripts/02_server/Map/NS/CMakeLists.txt new file mode 100644 index 00000000..c815a8c5 --- /dev/null +++ b/dScripts/02_server/Map/NS/CMakeLists.txt @@ -0,0 +1,13 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_NS + "NsConcertChoiceBuildManager.cpp" + "NsLegoClubDoor.cpp" + "NsLupTeleport.cpp" + "NsTokenConsoleServer.cpp") + +add_subdirectory(Waves) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_NS_WAVES}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP_NS ${DSCRIPTS_SOURCES_02_SERVER_MAP_NS} "Waves/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_02_SERVER_MAP_NS ${DSCRIPTS_SOURCES_02_SERVER_MAP_NS} PARENT_SCOPE) diff --git a/dScripts/NsConcertChoiceBuildManager.cpp b/dScripts/02_server/Map/NS/NsConcertChoiceBuildManager.cpp similarity index 100% rename from dScripts/NsConcertChoiceBuildManager.cpp rename to dScripts/02_server/Map/NS/NsConcertChoiceBuildManager.cpp diff --git a/dScripts/NsConcertChoiceBuildManager.h b/dScripts/02_server/Map/NS/NsConcertChoiceBuildManager.h similarity index 100% rename from dScripts/NsConcertChoiceBuildManager.h rename to dScripts/02_server/Map/NS/NsConcertChoiceBuildManager.h diff --git a/dScripts/NsLegoClubDoor.cpp b/dScripts/02_server/Map/NS/NsLegoClubDoor.cpp similarity index 100% rename from dScripts/NsLegoClubDoor.cpp rename to dScripts/02_server/Map/NS/NsLegoClubDoor.cpp diff --git a/dScripts/NsLegoClubDoor.h b/dScripts/02_server/Map/NS/NsLegoClubDoor.h similarity index 100% rename from dScripts/NsLegoClubDoor.h rename to dScripts/02_server/Map/NS/NsLegoClubDoor.h diff --git a/dScripts/NsLupTeleport.cpp b/dScripts/02_server/Map/NS/NsLupTeleport.cpp similarity index 100% rename from dScripts/NsLupTeleport.cpp rename to dScripts/02_server/Map/NS/NsLupTeleport.cpp diff --git a/dScripts/NsLupTeleport.h b/dScripts/02_server/Map/NS/NsLupTeleport.h similarity index 100% rename from dScripts/NsLupTeleport.h rename to dScripts/02_server/Map/NS/NsLupTeleport.h diff --git a/dScripts/NsTokenConsoleServer.cpp b/dScripts/02_server/Map/NS/NsTokenConsoleServer.cpp similarity index 100% rename from dScripts/NsTokenConsoleServer.cpp rename to dScripts/02_server/Map/NS/NsTokenConsoleServer.cpp diff --git a/dScripts/NsTokenConsoleServer.h b/dScripts/02_server/Map/NS/NsTokenConsoleServer.h similarity index 100% rename from dScripts/NsTokenConsoleServer.h rename to dScripts/02_server/Map/NS/NsTokenConsoleServer.h diff --git a/dScripts/02_server/Map/NS/Waves/CMakeLists.txt b/dScripts/02_server/Map/NS/Waves/CMakeLists.txt new file mode 100644 index 00000000..bb216ee9 --- /dev/null +++ b/dScripts/02_server/Map/NS/Waves/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_NS_WAVES + "ZoneNsWaves.cpp" + PARENT_SCOPE) diff --git a/dScripts/ZoneNsWaves.cpp b/dScripts/02_server/Map/NS/Waves/ZoneNsWaves.cpp similarity index 100% rename from dScripts/ZoneNsWaves.cpp rename to dScripts/02_server/Map/NS/Waves/ZoneNsWaves.cpp diff --git a/dScripts/ZoneNsWaves.h b/dScripts/02_server/Map/NS/Waves/ZoneNsWaves.h similarity index 100% rename from dScripts/ZoneNsWaves.h rename to dScripts/02_server/Map/NS/Waves/ZoneNsWaves.h diff --git a/dScripts/02_server/Map/NT/CMakeLists.txt b/dScripts/02_server/Map/NT/CMakeLists.txt new file mode 100644 index 00000000..ede9b003 --- /dev/null +++ b/dScripts/02_server/Map/NT/CMakeLists.txt @@ -0,0 +1,26 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_NT + "NtCombatChallengeDummy.cpp" + "NtCombatChallengeExplodingDummy.cpp" + "NtCombatChallengeServer.cpp" + "NtAssemblyTubeServer.cpp" + "NtParadoxPanelServer.cpp" + "NtImagBeamBuffer.cpp" + "NtBeamImaginationCollectors.cpp" + "NtDirtCloudServer.cpp" + "NtConsoleTeleportServer.cpp" + "SpawnStegoServer.cpp" + "SpawnSaberCatServer.cpp" + "SpawnShrakeServer.cpp" + "NtDukeServer.cpp" + "NtHaelServer.cpp" + "NtOverbuildServer.cpp" + "NtVandaServer.cpp" + "NtXRayServer.cpp" + "NtSleepingGuard.cpp" + "NtImagimeterVisibility.cpp" + "NtSentinelWalkwayServer.cpp" + "NtDarkitectRevealServer.cpp" + "NtParadoxTeleServer.cpp" + "NtVentureSpeedPadServer.cpp" + "NtVentureCannonServer.cpp" + PARENT_SCOPE) diff --git a/dScripts/NtAssemblyTubeServer.cpp b/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp similarity index 100% rename from dScripts/NtAssemblyTubeServer.cpp rename to dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp diff --git a/dScripts/NtAssemblyTubeServer.h b/dScripts/02_server/Map/NT/NtAssemblyTubeServer.h similarity index 100% rename from dScripts/NtAssemblyTubeServer.h rename to dScripts/02_server/Map/NT/NtAssemblyTubeServer.h diff --git a/dScripts/NtBeamImaginationCollectors.cpp b/dScripts/02_server/Map/NT/NtBeamImaginationCollectors.cpp similarity index 100% rename from dScripts/NtBeamImaginationCollectors.cpp rename to dScripts/02_server/Map/NT/NtBeamImaginationCollectors.cpp diff --git a/dScripts/NtBeamImaginationCollectors.h b/dScripts/02_server/Map/NT/NtBeamImaginationCollectors.h similarity index 100% rename from dScripts/NtBeamImaginationCollectors.h rename to dScripts/02_server/Map/NT/NtBeamImaginationCollectors.h diff --git a/dScripts/NtCombatChallengeDummy.cpp b/dScripts/02_server/Map/NT/NtCombatChallengeDummy.cpp similarity index 100% rename from dScripts/NtCombatChallengeDummy.cpp rename to dScripts/02_server/Map/NT/NtCombatChallengeDummy.cpp diff --git a/dScripts/NtCombatChallengeDummy.h b/dScripts/02_server/Map/NT/NtCombatChallengeDummy.h similarity index 100% rename from dScripts/NtCombatChallengeDummy.h rename to dScripts/02_server/Map/NT/NtCombatChallengeDummy.h diff --git a/dScripts/NtCombatChallengeExplodingDummy.cpp b/dScripts/02_server/Map/NT/NtCombatChallengeExplodingDummy.cpp similarity index 100% rename from dScripts/NtCombatChallengeExplodingDummy.cpp rename to dScripts/02_server/Map/NT/NtCombatChallengeExplodingDummy.cpp diff --git a/dScripts/NtCombatChallengeExplodingDummy.h b/dScripts/02_server/Map/NT/NtCombatChallengeExplodingDummy.h similarity index 100% rename from dScripts/NtCombatChallengeExplodingDummy.h rename to dScripts/02_server/Map/NT/NtCombatChallengeExplodingDummy.h diff --git a/dScripts/NtCombatChallengeServer.cpp b/dScripts/02_server/Map/NT/NtCombatChallengeServer.cpp similarity index 100% rename from dScripts/NtCombatChallengeServer.cpp rename to dScripts/02_server/Map/NT/NtCombatChallengeServer.cpp diff --git a/dScripts/NtCombatChallengeServer.h b/dScripts/02_server/Map/NT/NtCombatChallengeServer.h similarity index 100% rename from dScripts/NtCombatChallengeServer.h rename to dScripts/02_server/Map/NT/NtCombatChallengeServer.h diff --git a/dScripts/NtConsoleTeleportServer.cpp b/dScripts/02_server/Map/NT/NtConsoleTeleportServer.cpp similarity index 100% rename from dScripts/NtConsoleTeleportServer.cpp rename to dScripts/02_server/Map/NT/NtConsoleTeleportServer.cpp diff --git a/dScripts/NtConsoleTeleportServer.h b/dScripts/02_server/Map/NT/NtConsoleTeleportServer.h similarity index 100% rename from dScripts/NtConsoleTeleportServer.h rename to dScripts/02_server/Map/NT/NtConsoleTeleportServer.h diff --git a/dScripts/NtDarkitectRevealServer.cpp b/dScripts/02_server/Map/NT/NtDarkitectRevealServer.cpp similarity index 100% rename from dScripts/NtDarkitectRevealServer.cpp rename to dScripts/02_server/Map/NT/NtDarkitectRevealServer.cpp diff --git a/dScripts/NtDarkitectRevealServer.h b/dScripts/02_server/Map/NT/NtDarkitectRevealServer.h similarity index 100% rename from dScripts/NtDarkitectRevealServer.h rename to dScripts/02_server/Map/NT/NtDarkitectRevealServer.h diff --git a/dScripts/NtDirtCloudServer.cpp b/dScripts/02_server/Map/NT/NtDirtCloudServer.cpp similarity index 100% rename from dScripts/NtDirtCloudServer.cpp rename to dScripts/02_server/Map/NT/NtDirtCloudServer.cpp diff --git a/dScripts/NtDirtCloudServer.h b/dScripts/02_server/Map/NT/NtDirtCloudServer.h similarity index 100% rename from dScripts/NtDirtCloudServer.h rename to dScripts/02_server/Map/NT/NtDirtCloudServer.h diff --git a/dScripts/NtDukeServer.cpp b/dScripts/02_server/Map/NT/NtDukeServer.cpp similarity index 100% rename from dScripts/NtDukeServer.cpp rename to dScripts/02_server/Map/NT/NtDukeServer.cpp diff --git a/dScripts/NtDukeServer.h b/dScripts/02_server/Map/NT/NtDukeServer.h similarity index 100% rename from dScripts/NtDukeServer.h rename to dScripts/02_server/Map/NT/NtDukeServer.h diff --git a/dScripts/NtHaelServer.cpp b/dScripts/02_server/Map/NT/NtHaelServer.cpp similarity index 100% rename from dScripts/NtHaelServer.cpp rename to dScripts/02_server/Map/NT/NtHaelServer.cpp diff --git a/dScripts/NtHaelServer.h b/dScripts/02_server/Map/NT/NtHaelServer.h similarity index 100% rename from dScripts/NtHaelServer.h rename to dScripts/02_server/Map/NT/NtHaelServer.h diff --git a/dScripts/NtImagBeamBuffer.cpp b/dScripts/02_server/Map/NT/NtImagBeamBuffer.cpp similarity index 100% rename from dScripts/NtImagBeamBuffer.cpp rename to dScripts/02_server/Map/NT/NtImagBeamBuffer.cpp diff --git a/dScripts/NtImagBeamBuffer.h b/dScripts/02_server/Map/NT/NtImagBeamBuffer.h similarity index 100% rename from dScripts/NtImagBeamBuffer.h rename to dScripts/02_server/Map/NT/NtImagBeamBuffer.h diff --git a/dScripts/NtImagimeterVisibility.cpp b/dScripts/02_server/Map/NT/NtImagimeterVisibility.cpp similarity index 100% rename from dScripts/NtImagimeterVisibility.cpp rename to dScripts/02_server/Map/NT/NtImagimeterVisibility.cpp diff --git a/dScripts/NtImagimeterVisibility.h b/dScripts/02_server/Map/NT/NtImagimeterVisibility.h similarity index 100% rename from dScripts/NtImagimeterVisibility.h rename to dScripts/02_server/Map/NT/NtImagimeterVisibility.h diff --git a/dScripts/NtOverbuildServer.cpp b/dScripts/02_server/Map/NT/NtOverbuildServer.cpp similarity index 100% rename from dScripts/NtOverbuildServer.cpp rename to dScripts/02_server/Map/NT/NtOverbuildServer.cpp diff --git a/dScripts/NtOverbuildServer.h b/dScripts/02_server/Map/NT/NtOverbuildServer.h similarity index 100% rename from dScripts/NtOverbuildServer.h rename to dScripts/02_server/Map/NT/NtOverbuildServer.h diff --git a/dScripts/NtParadoxPanelServer.cpp b/dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp similarity index 100% rename from dScripts/NtParadoxPanelServer.cpp rename to dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp diff --git a/dScripts/NtParadoxPanelServer.h b/dScripts/02_server/Map/NT/NtParadoxPanelServer.h similarity index 100% rename from dScripts/NtParadoxPanelServer.h rename to dScripts/02_server/Map/NT/NtParadoxPanelServer.h diff --git a/dScripts/NtParadoxTeleServer.cpp b/dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp similarity index 100% rename from dScripts/NtParadoxTeleServer.cpp rename to dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp diff --git a/dScripts/NtParadoxTeleServer.h b/dScripts/02_server/Map/NT/NtParadoxTeleServer.h similarity index 100% rename from dScripts/NtParadoxTeleServer.h rename to dScripts/02_server/Map/NT/NtParadoxTeleServer.h diff --git a/dScripts/NtSentinelWalkwayServer.cpp b/dScripts/02_server/Map/NT/NtSentinelWalkwayServer.cpp similarity index 100% rename from dScripts/NtSentinelWalkwayServer.cpp rename to dScripts/02_server/Map/NT/NtSentinelWalkwayServer.cpp diff --git a/dScripts/NtSentinelWalkwayServer.h b/dScripts/02_server/Map/NT/NtSentinelWalkwayServer.h similarity index 100% rename from dScripts/NtSentinelWalkwayServer.h rename to dScripts/02_server/Map/NT/NtSentinelWalkwayServer.h diff --git a/dScripts/NtSleepingGuard.cpp b/dScripts/02_server/Map/NT/NtSleepingGuard.cpp similarity index 100% rename from dScripts/NtSleepingGuard.cpp rename to dScripts/02_server/Map/NT/NtSleepingGuard.cpp diff --git a/dScripts/NtSleepingGuard.h b/dScripts/02_server/Map/NT/NtSleepingGuard.h similarity index 100% rename from dScripts/NtSleepingGuard.h rename to dScripts/02_server/Map/NT/NtSleepingGuard.h diff --git a/dScripts/NtVandaServer.cpp b/dScripts/02_server/Map/NT/NtVandaServer.cpp similarity index 100% rename from dScripts/NtVandaServer.cpp rename to dScripts/02_server/Map/NT/NtVandaServer.cpp diff --git a/dScripts/NtVandaServer.h b/dScripts/02_server/Map/NT/NtVandaServer.h similarity index 100% rename from dScripts/NtVandaServer.h rename to dScripts/02_server/Map/NT/NtVandaServer.h diff --git a/dScripts/NtVentureCannonServer.cpp b/dScripts/02_server/Map/NT/NtVentureCannonServer.cpp similarity index 100% rename from dScripts/NtVentureCannonServer.cpp rename to dScripts/02_server/Map/NT/NtVentureCannonServer.cpp diff --git a/dScripts/NtVentureCannonServer.h b/dScripts/02_server/Map/NT/NtVentureCannonServer.h similarity index 100% rename from dScripts/NtVentureCannonServer.h rename to dScripts/02_server/Map/NT/NtVentureCannonServer.h diff --git a/dScripts/NtVentureSpeedPadServer.cpp b/dScripts/02_server/Map/NT/NtVentureSpeedPadServer.cpp similarity index 100% rename from dScripts/NtVentureSpeedPadServer.cpp rename to dScripts/02_server/Map/NT/NtVentureSpeedPadServer.cpp diff --git a/dScripts/NtVentureSpeedPadServer.h b/dScripts/02_server/Map/NT/NtVentureSpeedPadServer.h similarity index 100% rename from dScripts/NtVentureSpeedPadServer.h rename to dScripts/02_server/Map/NT/NtVentureSpeedPadServer.h diff --git a/dScripts/NtXRayServer.cpp b/dScripts/02_server/Map/NT/NtXRayServer.cpp similarity index 100% rename from dScripts/NtXRayServer.cpp rename to dScripts/02_server/Map/NT/NtXRayServer.cpp diff --git a/dScripts/NtXRayServer.h b/dScripts/02_server/Map/NT/NtXRayServer.h similarity index 100% rename from dScripts/NtXRayServer.h rename to dScripts/02_server/Map/NT/NtXRayServer.h diff --git a/dScripts/SpawnSaberCatServer.cpp b/dScripts/02_server/Map/NT/SpawnSaberCatServer.cpp similarity index 100% rename from dScripts/SpawnSaberCatServer.cpp rename to dScripts/02_server/Map/NT/SpawnSaberCatServer.cpp diff --git a/dScripts/SpawnSaberCatServer.h b/dScripts/02_server/Map/NT/SpawnSaberCatServer.h similarity index 100% rename from dScripts/SpawnSaberCatServer.h rename to dScripts/02_server/Map/NT/SpawnSaberCatServer.h diff --git a/dScripts/SpawnShrakeServer.cpp b/dScripts/02_server/Map/NT/SpawnShrakeServer.cpp similarity index 100% rename from dScripts/SpawnShrakeServer.cpp rename to dScripts/02_server/Map/NT/SpawnShrakeServer.cpp diff --git a/dScripts/SpawnShrakeServer.h b/dScripts/02_server/Map/NT/SpawnShrakeServer.h similarity index 100% rename from dScripts/SpawnShrakeServer.h rename to dScripts/02_server/Map/NT/SpawnShrakeServer.h diff --git a/dScripts/SpawnStegoServer.cpp b/dScripts/02_server/Map/NT/SpawnStegoServer.cpp similarity index 100% rename from dScripts/SpawnStegoServer.cpp rename to dScripts/02_server/Map/NT/SpawnStegoServer.cpp diff --git a/dScripts/SpawnStegoServer.h b/dScripts/02_server/Map/NT/SpawnStegoServer.h similarity index 100% rename from dScripts/SpawnStegoServer.h rename to dScripts/02_server/Map/NT/SpawnStegoServer.h diff --git a/dScripts/02_server/Map/PR/CMakeLists.txt b/dScripts/02_server/Map/PR/CMakeLists.txt new file mode 100644 index 00000000..3a32e9f3 --- /dev/null +++ b/dScripts/02_server/Map/PR/CMakeLists.txt @@ -0,0 +1,5 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_PR + "HydrantBroken.cpp" + "PrSeagullFly.cpp" + "SpawnGryphonServer.cpp" + PARENT_SCOPE) diff --git a/dScripts/HydrantBroken.cpp b/dScripts/02_server/Map/PR/HydrantBroken.cpp similarity index 100% rename from dScripts/HydrantBroken.cpp rename to dScripts/02_server/Map/PR/HydrantBroken.cpp diff --git a/dScripts/HydrantBroken.h b/dScripts/02_server/Map/PR/HydrantBroken.h similarity index 100% rename from dScripts/HydrantBroken.h rename to dScripts/02_server/Map/PR/HydrantBroken.h diff --git a/dScripts/PrSeagullFly.cpp b/dScripts/02_server/Map/PR/PrSeagullFly.cpp similarity index 100% rename from dScripts/PrSeagullFly.cpp rename to dScripts/02_server/Map/PR/PrSeagullFly.cpp diff --git a/dScripts/PrSeagullFly.h b/dScripts/02_server/Map/PR/PrSeagullFly.h similarity index 100% rename from dScripts/PrSeagullFly.h rename to dScripts/02_server/Map/PR/PrSeagullFly.h diff --git a/dScripts/SpawnGryphonServer.cpp b/dScripts/02_server/Map/PR/SpawnGryphonServer.cpp similarity index 100% rename from dScripts/SpawnGryphonServer.cpp rename to dScripts/02_server/Map/PR/SpawnGryphonServer.cpp diff --git a/dScripts/SpawnGryphonServer.h b/dScripts/02_server/Map/PR/SpawnGryphonServer.h similarity index 100% rename from dScripts/SpawnGryphonServer.h rename to dScripts/02_server/Map/PR/SpawnGryphonServer.h diff --git a/dScripts/02_server/Map/Property/AG_Med/CMakeLists.txt b/dScripts/02_server/Map/Property/AG_Med/CMakeLists.txt new file mode 100644 index 00000000..90985f9f --- /dev/null +++ b/dScripts/02_server/Map/Property/AG_Med/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY_AG_MED + "ZoneAgMedProperty.cpp" + PARENT_SCOPE) diff --git a/dScripts/ZoneAgMedProperty.cpp b/dScripts/02_server/Map/Property/AG_Med/ZoneAgMedProperty.cpp similarity index 100% rename from dScripts/ZoneAgMedProperty.cpp rename to dScripts/02_server/Map/Property/AG_Med/ZoneAgMedProperty.cpp diff --git a/dScripts/ZoneAgMedProperty.h b/dScripts/02_server/Map/Property/AG_Med/ZoneAgMedProperty.h similarity index 100% rename from dScripts/ZoneAgMedProperty.h rename to dScripts/02_server/Map/Property/AG_Med/ZoneAgMedProperty.h diff --git a/dScripts/02_server/Map/Property/AG_Small/CMakeLists.txt b/dScripts/02_server/Map/Property/AG_Small/CMakeLists.txt new file mode 100644 index 00000000..3d71dc1a --- /dev/null +++ b/dScripts/02_server/Map/Property/AG_Small/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY_AG_SMALL + "ZoneAgProperty.cpp" + "EnemySpiderSpawner.cpp" + PARENT_SCOPE) diff --git a/dScripts/EnemySpiderSpawner.cpp b/dScripts/02_server/Map/Property/AG_Small/EnemySpiderSpawner.cpp similarity index 100% rename from dScripts/EnemySpiderSpawner.cpp rename to dScripts/02_server/Map/Property/AG_Small/EnemySpiderSpawner.cpp diff --git a/dScripts/EnemySpiderSpawner.h b/dScripts/02_server/Map/Property/AG_Small/EnemySpiderSpawner.h similarity index 100% rename from dScripts/EnemySpiderSpawner.h rename to dScripts/02_server/Map/Property/AG_Small/EnemySpiderSpawner.h diff --git a/dScripts/ZoneAgProperty.cpp b/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp similarity index 100% rename from dScripts/ZoneAgProperty.cpp rename to dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp diff --git a/dScripts/ZoneAgProperty.h b/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.h similarity index 100% rename from dScripts/ZoneAgProperty.h rename to dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.h diff --git a/dScripts/02_server/Map/Property/CMakeLists.txt b/dScripts/02_server/Map/Property/CMakeLists.txt new file mode 100644 index 00000000..74badb32 --- /dev/null +++ b/dScripts/02_server/Map/Property/CMakeLists.txt @@ -0,0 +1,22 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY + "PropertyBankInteract.cpp") + +add_subdirectory(AG_Med) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY_AG_MED}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY ${DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY} "AG_Med/${file}") +endforeach() + +add_subdirectory(AG_Small) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY_AG_SMALL}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY ${DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY} "AG_Small/${file}") +endforeach() + +add_subdirectory(NS_Med) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY_NS_MED}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY ${DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY} "NS_Med/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY ${DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY} PARENT_SCOPE) diff --git a/dScripts/02_server/Map/Property/NS_Med/CMakeLists.txt b/dScripts/02_server/Map/Property/NS_Med/CMakeLists.txt new file mode 100644 index 00000000..230bc2cf --- /dev/null +++ b/dScripts/02_server/Map/Property/NS_Med/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY_NS_MED + "ZoneNsMedProperty.cpp" + PARENT_SCOPE) diff --git a/dScripts/ZoneNsMedProperty.cpp b/dScripts/02_server/Map/Property/NS_Med/ZoneNsMedProperty.cpp similarity index 100% rename from dScripts/ZoneNsMedProperty.cpp rename to dScripts/02_server/Map/Property/NS_Med/ZoneNsMedProperty.cpp diff --git a/dScripts/ZoneNsMedProperty.h b/dScripts/02_server/Map/Property/NS_Med/ZoneNsMedProperty.h similarity index 100% rename from dScripts/ZoneNsMedProperty.h rename to dScripts/02_server/Map/Property/NS_Med/ZoneNsMedProperty.h diff --git a/dScripts/PropertyBankInteract.cpp b/dScripts/02_server/Map/Property/PropertyBankInteract.cpp similarity index 100% rename from dScripts/PropertyBankInteract.cpp rename to dScripts/02_server/Map/Property/PropertyBankInteract.cpp diff --git a/dScripts/PropertyBankInteract.h b/dScripts/02_server/Map/Property/PropertyBankInteract.h similarity index 100% rename from dScripts/PropertyBankInteract.h rename to dScripts/02_server/Map/Property/PropertyBankInteract.h diff --git a/dScripts/02_server/Map/SS/CMakeLists.txt b/dScripts/02_server/Map/SS/CMakeLists.txt new file mode 100644 index 00000000..49db031f --- /dev/null +++ b/dScripts/02_server/Map/SS/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_SS + "SsModularBuildServer.cpp" + PARENT_SCOPE) diff --git a/dScripts/SsModularBuildServer.cpp b/dScripts/02_server/Map/SS/SsModularBuildServer.cpp similarity index 100% rename from dScripts/SsModularBuildServer.cpp rename to dScripts/02_server/Map/SS/SsModularBuildServer.cpp diff --git a/dScripts/SsModularBuildServer.h b/dScripts/02_server/Map/SS/SsModularBuildServer.h similarity index 100% rename from dScripts/SsModularBuildServer.h rename to dScripts/02_server/Map/SS/SsModularBuildServer.h diff --git a/dScripts/02_server/Map/VE/CMakeLists.txt b/dScripts/02_server/Map/VE/CMakeLists.txt new file mode 100644 index 00000000..ac3a6461 --- /dev/null +++ b/dScripts/02_server/Map/VE/CMakeLists.txt @@ -0,0 +1,5 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_VE + "VeMissionConsole.cpp" + "VeEpsilonServer.cpp" + "VeBricksampleServer.cpp" + PARENT_SCOPE) diff --git a/dScripts/VeBricksampleServer.cpp b/dScripts/02_server/Map/VE/VeBricksampleServer.cpp similarity index 100% rename from dScripts/VeBricksampleServer.cpp rename to dScripts/02_server/Map/VE/VeBricksampleServer.cpp diff --git a/dScripts/VeBricksampleServer.h b/dScripts/02_server/Map/VE/VeBricksampleServer.h similarity index 100% rename from dScripts/VeBricksampleServer.h rename to dScripts/02_server/Map/VE/VeBricksampleServer.h diff --git a/dScripts/VeEpsilonServer.cpp b/dScripts/02_server/Map/VE/VeEpsilonServer.cpp similarity index 100% rename from dScripts/VeEpsilonServer.cpp rename to dScripts/02_server/Map/VE/VeEpsilonServer.cpp diff --git a/dScripts/VeEpsilonServer.h b/dScripts/02_server/Map/VE/VeEpsilonServer.h similarity index 100% rename from dScripts/VeEpsilonServer.h rename to dScripts/02_server/Map/VE/VeEpsilonServer.h diff --git a/dScripts/VeMissionConsole.cpp b/dScripts/02_server/Map/VE/VeMissionConsole.cpp similarity index 100% rename from dScripts/VeMissionConsole.cpp rename to dScripts/02_server/Map/VE/VeMissionConsole.cpp diff --git a/dScripts/VeMissionConsole.h b/dScripts/02_server/Map/VE/VeMissionConsole.h similarity index 100% rename from dScripts/VeMissionConsole.h rename to dScripts/02_server/Map/VE/VeMissionConsole.h diff --git a/dScripts/BurningTile.cpp b/dScripts/02_server/Map/njhub/BurningTile.cpp similarity index 100% rename from dScripts/BurningTile.cpp rename to dScripts/02_server/Map/njhub/BurningTile.cpp diff --git a/dScripts/BurningTile.h b/dScripts/02_server/Map/njhub/BurningTile.h similarity index 100% rename from dScripts/BurningTile.h rename to dScripts/02_server/Map/njhub/BurningTile.h diff --git a/dScripts/02_server/Map/njhub/CMakeLists.txt b/dScripts/02_server/Map/njhub/CMakeLists.txt new file mode 100644 index 00000000..2527d1ad --- /dev/null +++ b/dScripts/02_server/Map/njhub/CMakeLists.txt @@ -0,0 +1,31 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_NJHUB + "BurningTile.cpp" + "CatapultBaseServer.cpp" + "CatapultBouncerServer.cpp" + "CavePrisonCage.cpp" + "EnemySkeletonSpawner.cpp" + "FallingTile.cpp" + "FlameJetServer.cpp" + "ImaginationShrineServer.cpp" + "Lieutenant.cpp" + "MonCoreNookDoors.cpp" + "MonCoreSmashableDoors.cpp" + "NjColeNPC.cpp" + "NjDragonEmblemChestServer.cpp" + "NjEarthDragonPetServer.cpp" + "NjEarthPetServer.cpp" + "NjGarmadonCelebration.cpp" + "NjJayMissionItems.cpp" + "NjNPCMissionSpinjitzuServer.cpp" + "NjNyaMissionitems.cpp" + "NjScrollChestServer.cpp" + "NjWuNPC.cpp" + "RainOfArrows.cpp") + +add_subdirectory(boss_instance) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_NJHUB_BOSS_INSTANCE}) + set(DSCRIPTS_SOURCES_02_SERVER_MAP_NJHUB ${DSCRIPTS_SOURCES_02_SERVER_MAP_NJHUB} "boss_instance/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_02_SERVER_MAP_NJHUB ${DSCRIPTS_SOURCES_02_SERVER_MAP_NJHUB} PARENT_SCOPE) diff --git a/dScripts/CatapultBaseServer.cpp b/dScripts/02_server/Map/njhub/CatapultBaseServer.cpp similarity index 100% rename from dScripts/CatapultBaseServer.cpp rename to dScripts/02_server/Map/njhub/CatapultBaseServer.cpp diff --git a/dScripts/CatapultBaseServer.h b/dScripts/02_server/Map/njhub/CatapultBaseServer.h similarity index 100% rename from dScripts/CatapultBaseServer.h rename to dScripts/02_server/Map/njhub/CatapultBaseServer.h diff --git a/dScripts/CatapultBouncerServer.cpp b/dScripts/02_server/Map/njhub/CatapultBouncerServer.cpp similarity index 100% rename from dScripts/CatapultBouncerServer.cpp rename to dScripts/02_server/Map/njhub/CatapultBouncerServer.cpp diff --git a/dScripts/CatapultBouncerServer.h b/dScripts/02_server/Map/njhub/CatapultBouncerServer.h similarity index 100% rename from dScripts/CatapultBouncerServer.h rename to dScripts/02_server/Map/njhub/CatapultBouncerServer.h diff --git a/dScripts/CavePrisonCage.cpp b/dScripts/02_server/Map/njhub/CavePrisonCage.cpp similarity index 100% rename from dScripts/CavePrisonCage.cpp rename to dScripts/02_server/Map/njhub/CavePrisonCage.cpp diff --git a/dScripts/CavePrisonCage.h b/dScripts/02_server/Map/njhub/CavePrisonCage.h similarity index 100% rename from dScripts/CavePrisonCage.h rename to dScripts/02_server/Map/njhub/CavePrisonCage.h diff --git a/dScripts/EnemySkeletonSpawner.cpp b/dScripts/02_server/Map/njhub/EnemySkeletonSpawner.cpp similarity index 100% rename from dScripts/EnemySkeletonSpawner.cpp rename to dScripts/02_server/Map/njhub/EnemySkeletonSpawner.cpp diff --git a/dScripts/EnemySkeletonSpawner.h b/dScripts/02_server/Map/njhub/EnemySkeletonSpawner.h similarity index 100% rename from dScripts/EnemySkeletonSpawner.h rename to dScripts/02_server/Map/njhub/EnemySkeletonSpawner.h diff --git a/dScripts/FallingTile.cpp b/dScripts/02_server/Map/njhub/FallingTile.cpp similarity index 100% rename from dScripts/FallingTile.cpp rename to dScripts/02_server/Map/njhub/FallingTile.cpp diff --git a/dScripts/FallingTile.h b/dScripts/02_server/Map/njhub/FallingTile.h similarity index 100% rename from dScripts/FallingTile.h rename to dScripts/02_server/Map/njhub/FallingTile.h diff --git a/dScripts/FlameJetServer.cpp b/dScripts/02_server/Map/njhub/FlameJetServer.cpp similarity index 100% rename from dScripts/FlameJetServer.cpp rename to dScripts/02_server/Map/njhub/FlameJetServer.cpp diff --git a/dScripts/FlameJetServer.h b/dScripts/02_server/Map/njhub/FlameJetServer.h similarity index 100% rename from dScripts/FlameJetServer.h rename to dScripts/02_server/Map/njhub/FlameJetServer.h diff --git a/dScripts/ImaginationShrineServer.cpp b/dScripts/02_server/Map/njhub/ImaginationShrineServer.cpp similarity index 100% rename from dScripts/ImaginationShrineServer.cpp rename to dScripts/02_server/Map/njhub/ImaginationShrineServer.cpp diff --git a/dScripts/ImaginationShrineServer.h b/dScripts/02_server/Map/njhub/ImaginationShrineServer.h similarity index 100% rename from dScripts/ImaginationShrineServer.h rename to dScripts/02_server/Map/njhub/ImaginationShrineServer.h diff --git a/dScripts/Lieutenant.cpp b/dScripts/02_server/Map/njhub/Lieutenant.cpp similarity index 100% rename from dScripts/Lieutenant.cpp rename to dScripts/02_server/Map/njhub/Lieutenant.cpp diff --git a/dScripts/Lieutenant.h b/dScripts/02_server/Map/njhub/Lieutenant.h similarity index 100% rename from dScripts/Lieutenant.h rename to dScripts/02_server/Map/njhub/Lieutenant.h diff --git a/dScripts/MonCoreNookDoors.cpp b/dScripts/02_server/Map/njhub/MonCoreNookDoors.cpp similarity index 100% rename from dScripts/MonCoreNookDoors.cpp rename to dScripts/02_server/Map/njhub/MonCoreNookDoors.cpp diff --git a/dScripts/MonCoreNookDoors.h b/dScripts/02_server/Map/njhub/MonCoreNookDoors.h similarity index 100% rename from dScripts/MonCoreNookDoors.h rename to dScripts/02_server/Map/njhub/MonCoreNookDoors.h diff --git a/dScripts/MonCoreSmashableDoors.cpp b/dScripts/02_server/Map/njhub/MonCoreSmashableDoors.cpp similarity index 100% rename from dScripts/MonCoreSmashableDoors.cpp rename to dScripts/02_server/Map/njhub/MonCoreSmashableDoors.cpp diff --git a/dScripts/MonCoreSmashableDoors.h b/dScripts/02_server/Map/njhub/MonCoreSmashableDoors.h similarity index 100% rename from dScripts/MonCoreSmashableDoors.h rename to dScripts/02_server/Map/njhub/MonCoreSmashableDoors.h diff --git a/dScripts/NjColeNPC.cpp b/dScripts/02_server/Map/njhub/NjColeNPC.cpp similarity index 100% rename from dScripts/NjColeNPC.cpp rename to dScripts/02_server/Map/njhub/NjColeNPC.cpp diff --git a/dScripts/NjColeNPC.h b/dScripts/02_server/Map/njhub/NjColeNPC.h similarity index 100% rename from dScripts/NjColeNPC.h rename to dScripts/02_server/Map/njhub/NjColeNPC.h diff --git a/dScripts/NjDragonEmblemChestServer.cpp b/dScripts/02_server/Map/njhub/NjDragonEmblemChestServer.cpp similarity index 100% rename from dScripts/NjDragonEmblemChestServer.cpp rename to dScripts/02_server/Map/njhub/NjDragonEmblemChestServer.cpp diff --git a/dScripts/NjDragonEmblemChestServer.h b/dScripts/02_server/Map/njhub/NjDragonEmblemChestServer.h similarity index 100% rename from dScripts/NjDragonEmblemChestServer.h rename to dScripts/02_server/Map/njhub/NjDragonEmblemChestServer.h diff --git a/dScripts/NjEarthDragonPetServer.cpp b/dScripts/02_server/Map/njhub/NjEarthDragonPetServer.cpp similarity index 100% rename from dScripts/NjEarthDragonPetServer.cpp rename to dScripts/02_server/Map/njhub/NjEarthDragonPetServer.cpp diff --git a/dScripts/NjEarthDragonPetServer.h b/dScripts/02_server/Map/njhub/NjEarthDragonPetServer.h similarity index 100% rename from dScripts/NjEarthDragonPetServer.h rename to dScripts/02_server/Map/njhub/NjEarthDragonPetServer.h diff --git a/dScripts/NjEarthPetServer.cpp b/dScripts/02_server/Map/njhub/NjEarthPetServer.cpp similarity index 100% rename from dScripts/NjEarthPetServer.cpp rename to dScripts/02_server/Map/njhub/NjEarthPetServer.cpp diff --git a/dScripts/NjEarthPetServer.h b/dScripts/02_server/Map/njhub/NjEarthPetServer.h similarity index 100% rename from dScripts/NjEarthPetServer.h rename to dScripts/02_server/Map/njhub/NjEarthPetServer.h diff --git a/dScripts/NjGarmadonCelebration.cpp b/dScripts/02_server/Map/njhub/NjGarmadonCelebration.cpp similarity index 100% rename from dScripts/NjGarmadonCelebration.cpp rename to dScripts/02_server/Map/njhub/NjGarmadonCelebration.cpp diff --git a/dScripts/NjGarmadonCelebration.h b/dScripts/02_server/Map/njhub/NjGarmadonCelebration.h similarity index 100% rename from dScripts/NjGarmadonCelebration.h rename to dScripts/02_server/Map/njhub/NjGarmadonCelebration.h diff --git a/dScripts/NjJayMissionItems.cpp b/dScripts/02_server/Map/njhub/NjJayMissionItems.cpp similarity index 100% rename from dScripts/NjJayMissionItems.cpp rename to dScripts/02_server/Map/njhub/NjJayMissionItems.cpp diff --git a/dScripts/NjJayMissionItems.h b/dScripts/02_server/Map/njhub/NjJayMissionItems.h similarity index 100% rename from dScripts/NjJayMissionItems.h rename to dScripts/02_server/Map/njhub/NjJayMissionItems.h diff --git a/dScripts/NjNPCMissionSpinjitzuServer.cpp b/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.cpp similarity index 100% rename from dScripts/NjNPCMissionSpinjitzuServer.cpp rename to dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.cpp diff --git a/dScripts/NjNPCMissionSpinjitzuServer.h b/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.h similarity index 100% rename from dScripts/NjNPCMissionSpinjitzuServer.h rename to dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.h diff --git a/dScripts/NjNyaMissionitems.cpp b/dScripts/02_server/Map/njhub/NjNyaMissionitems.cpp similarity index 100% rename from dScripts/NjNyaMissionitems.cpp rename to dScripts/02_server/Map/njhub/NjNyaMissionitems.cpp diff --git a/dScripts/NjNyaMissionitems.h b/dScripts/02_server/Map/njhub/NjNyaMissionitems.h similarity index 100% rename from dScripts/NjNyaMissionitems.h rename to dScripts/02_server/Map/njhub/NjNyaMissionitems.h diff --git a/dScripts/NjScrollChestServer.cpp b/dScripts/02_server/Map/njhub/NjScrollChestServer.cpp similarity index 100% rename from dScripts/NjScrollChestServer.cpp rename to dScripts/02_server/Map/njhub/NjScrollChestServer.cpp diff --git a/dScripts/NjScrollChestServer.h b/dScripts/02_server/Map/njhub/NjScrollChestServer.h similarity index 100% rename from dScripts/NjScrollChestServer.h rename to dScripts/02_server/Map/njhub/NjScrollChestServer.h diff --git a/dScripts/NjWuNPC.cpp b/dScripts/02_server/Map/njhub/NjWuNPC.cpp similarity index 100% rename from dScripts/NjWuNPC.cpp rename to dScripts/02_server/Map/njhub/NjWuNPC.cpp diff --git a/dScripts/NjWuNPC.h b/dScripts/02_server/Map/njhub/NjWuNPC.h similarity index 100% rename from dScripts/NjWuNPC.h rename to dScripts/02_server/Map/njhub/NjWuNPC.h diff --git a/dScripts/RainOfArrows.cpp b/dScripts/02_server/Map/njhub/RainOfArrows.cpp similarity index 100% rename from dScripts/RainOfArrows.cpp rename to dScripts/02_server/Map/njhub/RainOfArrows.cpp diff --git a/dScripts/RainOfArrows.h b/dScripts/02_server/Map/njhub/RainOfArrows.h similarity index 100% rename from dScripts/RainOfArrows.h rename to dScripts/02_server/Map/njhub/RainOfArrows.h diff --git a/dScripts/02_server/Map/njhub/boss_instance/CMakeLists.txt b/dScripts/02_server/Map/njhub/boss_instance/CMakeLists.txt new file mode 100644 index 00000000..22bb541d --- /dev/null +++ b/dScripts/02_server/Map/njhub/boss_instance/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MAP_NJHUB_BOSS_INSTANCE + "NjMonastryBossInstance.cpp" + PARENT_SCOPE) diff --git a/dScripts/NjMonastryBossInstance.cpp b/dScripts/02_server/Map/njhub/boss_instance/NjMonastryBossInstance.cpp similarity index 100% rename from dScripts/NjMonastryBossInstance.cpp rename to dScripts/02_server/Map/njhub/boss_instance/NjMonastryBossInstance.cpp diff --git a/dScripts/NjMonastryBossInstance.h b/dScripts/02_server/Map/njhub/boss_instance/NjMonastryBossInstance.h similarity index 100% rename from dScripts/NjMonastryBossInstance.h rename to dScripts/02_server/Map/njhub/boss_instance/NjMonastryBossInstance.h diff --git a/dScripts/02_server/Minigame/CMakeLists.txt b/dScripts/02_server/Minigame/CMakeLists.txt new file mode 100644 index 00000000..e8cb4402 --- /dev/null +++ b/dScripts/02_server/Minigame/CMakeLists.txt @@ -0,0 +1,9 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MINIGAME) + +add_subdirectory(General) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MINIGAME_GENERAL}) + set(DSCRIPTS_SOURCES_02_SERVER_MINIGAME ${DSCRIPTS_SOURCES_02_SERVER_MINIGAME} "General/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_02_SERVER_MINIGAME ${DSCRIPTS_SOURCES_02_SERVER_MINIGAME} PARENT_SCOPE) diff --git a/dScripts/02_server/Minigame/General/CMakeLists.txt b/dScripts/02_server/Minigame/General/CMakeLists.txt new file mode 100644 index 00000000..55d2e595 --- /dev/null +++ b/dScripts/02_server/Minigame/General/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_02_SERVER_MINIGAME_GENERAL + "MinigameTreasureChestServer.cpp" + PARENT_SCOPE) diff --git a/dScripts/MinigameTreasureChestServer.cpp b/dScripts/02_server/Minigame/General/MinigameTreasureChestServer.cpp similarity index 100% rename from dScripts/MinigameTreasureChestServer.cpp rename to dScripts/02_server/Minigame/General/MinigameTreasureChestServer.cpp diff --git a/dScripts/MinigameTreasureChestServer.h b/dScripts/02_server/Minigame/General/MinigameTreasureChestServer.h similarity index 100% rename from dScripts/MinigameTreasureChestServer.h rename to dScripts/02_server/Minigame/General/MinigameTreasureChestServer.h diff --git a/dScripts/AgSurvivalBuffStation.cpp b/dScripts/02_server/Objects/AgSurvivalBuffStation.cpp similarity index 100% rename from dScripts/AgSurvivalBuffStation.cpp rename to dScripts/02_server/Objects/AgSurvivalBuffStation.cpp diff --git a/dScripts/AgSurvivalBuffStation.h b/dScripts/02_server/Objects/AgSurvivalBuffStation.h similarity index 100% rename from dScripts/AgSurvivalBuffStation.h rename to dScripts/02_server/Objects/AgSurvivalBuffStation.h diff --git a/dScripts/02_server/Objects/CMakeLists.txt b/dScripts/02_server/Objects/CMakeLists.txt new file mode 100644 index 00000000..1b96d79f --- /dev/null +++ b/dScripts/02_server/Objects/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DSCRIPTS_SOURCES_02_SERVER_OBJECTS + "AgSurvivalBuffStation.cpp" + "StinkyFishTarget.cpp" + PARENT_SCOPE) diff --git a/dScripts/StinkyFishTarget.cpp b/dScripts/02_server/Objects/StinkyFishTarget.cpp similarity index 100% rename from dScripts/StinkyFishTarget.cpp rename to dScripts/02_server/Objects/StinkyFishTarget.cpp diff --git a/dScripts/StinkyFishTarget.h b/dScripts/02_server/Objects/StinkyFishTarget.h similarity index 100% rename from dScripts/StinkyFishTarget.h rename to dScripts/02_server/Objects/StinkyFishTarget.h diff --git a/dScripts/02_server/Pets/CMakeLists.txt b/dScripts/02_server/Pets/CMakeLists.txt new file mode 100644 index 00000000..8820a82e --- /dev/null +++ b/dScripts/02_server/Pets/CMakeLists.txt @@ -0,0 +1,5 @@ +set(DSCRIPTS_SOURCES_02_SERVER_PETS + "PetFromDigServer.cpp" + "PetFromObjectServer.cpp" + "DamagingPets.cpp" + PARENT_SCOPE) diff --git a/dScripts/DamagingPets.cpp b/dScripts/02_server/Pets/DamagingPets.cpp similarity index 100% rename from dScripts/DamagingPets.cpp rename to dScripts/02_server/Pets/DamagingPets.cpp diff --git a/dScripts/DamagingPets.h b/dScripts/02_server/Pets/DamagingPets.h similarity index 100% rename from dScripts/DamagingPets.h rename to dScripts/02_server/Pets/DamagingPets.h diff --git a/dScripts/PetFromDigServer.cpp b/dScripts/02_server/Pets/PetFromDigServer.cpp similarity index 100% rename from dScripts/PetFromDigServer.cpp rename to dScripts/02_server/Pets/PetFromDigServer.cpp diff --git a/dScripts/PetFromDigServer.h b/dScripts/02_server/Pets/PetFromDigServer.h similarity index 100% rename from dScripts/PetFromDigServer.h rename to dScripts/02_server/Pets/PetFromDigServer.h diff --git a/dScripts/PetFromObjectServer.cpp b/dScripts/02_server/Pets/PetFromObjectServer.cpp similarity index 100% rename from dScripts/PetFromObjectServer.cpp rename to dScripts/02_server/Pets/PetFromObjectServer.cpp diff --git a/dScripts/PetFromObjectServer.h b/dScripts/02_server/Pets/PetFromObjectServer.h similarity index 100% rename from dScripts/PetFromObjectServer.h rename to dScripts/02_server/Pets/PetFromObjectServer.h diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index 0a907a05..fce3b721 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -1,263 +1,48 @@ -set(DSCRIPT_SOURCES "ActivityManager.cpp" - "ActMine.cpp" - "ActNinjaTurret.cpp" - "ActParadoxPipeFix.cpp" - "ActPlayerDeathTrigger.cpp" - "ActSharkPlayerDeathTrigger.cpp" - "ActVehicleDeathTrigger.cpp" - "AgBugsprayer.cpp" - "AgBusDoor.cpp" - "AgCagedBricksServer.cpp" - "AgDarkSpiderling.cpp" - "AgFans.cpp" - "AgImagSmashable.cpp" - "AgJetEffectServer.cpp" - "AgLaserSensorServer.cpp" - "AgMonumentBirds.cpp" - "AgMonumentLaserServer.cpp" - "AgMonumentRaceCancel.cpp" - "AgMonumentRaceGoal.cpp" - "AgPicnicBlanket.cpp" - "AgPropGuard.cpp" - "AgPropguards.cpp" - "AgQbElevator.cpp" - "AgQbWall.cpp" - "AgSalutingNpcs.cpp" - "AgShipPlayerDeathTrigger.cpp" - "AgShipPlayerShockServer.cpp" - "AgSpaceStuff.cpp" - "AgStagePlatforms.cpp" - "AgStromlingProperty.cpp" - "AgSurvivalBuffStation.cpp" - "AgSurvivalMech.cpp" - "AgSurvivalSpiderling.cpp" - "AgSurvivalStromling.cpp" - "AgTurret.cpp" - "AllCrateChicken.cpp" - "AmBlueX.cpp" - "AmBridge.cpp" - "AmConsoleTeleportServer.cpp" - "AmDarklingDragon.cpp" - "AmDarklingMech.cpp" - "AmDrawBridge.cpp" - "AmDropshipComputer.cpp" - "AmScrollReaderServer.cpp" - "AmShieldGenerator.cpp" - "AmShieldGeneratorQuickbuild.cpp" - "AmSkeletonEngineer.cpp" - "AmSkullkinDrill.cpp" - "AmSkullkinDrillStand.cpp" - "AmSkullkinTower.cpp" - "AmTeapotServer.cpp" - "AmTemplateSkillVolume.cpp" - "AnvilOfArmor.cpp" - "BankInteractServer.cpp" +set(DSCRIPTS_SOURCES + "ActivityManager.cpp" "BaseConsoleTeleportServer.cpp" - "BaseEnemyApe.cpp" - "BaseEnemyMech.cpp" - "BaseFootRaceManager.cpp" - "BaseInteractDropLootServer.cpp" "BasePropertyServer.cpp" "BaseRandomServer.cpp" "BaseSurvivalServer.cpp" "BaseWavesGenericEnemy.cpp" "BaseWavesServer.cpp" - "Binoculars.cpp" - "BootyDigServer.cpp" - "BossSpiderQueenEnemyServer.cpp" - "BuccaneerValiantShip.cpp" - "BurningTile.cpp" - "CatapultBaseServer.cpp" - "CatapultBouncerServer.cpp" - "CauldronOfLife.cpp" - "CavePrisonCage.cpp" "ChooseYourDestinationNsToNt.cpp" - "ClRing.cpp" "CppScripts.cpp" - "CrabServer.cpp" - "DamagingPets.cpp" "Darkitect.cpp" - "DLUVanityNPC.cpp" - "EnemyNjBuff.cpp" - "EnemyRoninSpawner.cpp" - "EnemySkeletonSpawner.cpp" - "EnemySpiderSpawner.cpp" - "ExplodingAsset.cpp" - "FallingTile.cpp" - "FireFirstSkillonStartup.cpp" - "FlameJetServer.cpp" - "ForceVolumeServer.cpp" - "FountainOfImagination.cpp" - "FvBounceOverWall.cpp" - "FvBrickPuzzleServer.cpp" - "FvCandle.cpp" - "FvConsoleLeftQuickbuild.cpp" - "FvConsoleRightQuickbuild.cpp" - "FvDragonSmashingGolemQb.cpp" - "FvFacilityBrick.cpp" - "FvFacilityPipes.cpp" - "FvFlyingCreviceDragon.cpp" - "FvFong.cpp" - "FvFreeGfNinjas.cpp" - "FvHorsemenTrigger.cpp" - "FvMaelstromCavalry.cpp" - "FvMaelstromGeyser.cpp" - "FvMaelstromDragon.cpp" - "FvNinjaGuard.cpp" - "FvPandaServer.cpp" - "FvPandaSpawnerServer.cpp" - "FvPassThroughWall.cpp" - "FvRaceSmashEggImagineServer.cpp" - "GfApeSmashingQB.cpp" - "GfArchway.cpp" - "GfBanana.cpp" - "GfBananaCluster.cpp" - "GfCampfire.cpp" - "GfCaptainsCannon.cpp" - "GfJailkeepMission.cpp" - "GfJailWalls.cpp" - "GfMaelstromGeyser.cpp" - "GfOrgan.cpp" - "GfParrotCrash.cpp" - "GfTikiTorch.cpp" - "GrowingFlower.cpp" - "HydrantBroken.cpp" - "HydrantSmashable.cpp" - "ImaginationBackpackHealServer.cpp" - "ImaginationShrineServer.cpp" - "ImgBrickConsoleQB.cpp" - "InstanceExitTransferPlayerToLastNonInstance.cpp" - "InvalidScript.cpp" - "LegoDieRoll.cpp" - "Lieutenant.cpp" - "MaestromExtracticatorServer.cpp" - "MailBoxServer.cpp" - "MastTeleport.cpp" - "MinigameTreasureChestServer.cpp" - "MonCoreNookDoors.cpp" - "MonCoreSmashableDoors.cpp" - "NjColeNPC.cpp" - "NjDragonEmblemChestServer.cpp" - "NjEarthDragonPetServer.cpp" - "NjEarthPetServer.cpp" - "NjGarmadonCelebration.cpp" - "NjhubLavaPlayerDeathTrigger.cpp" - "NjIceRailActivator.cpp" - "NjJayMissionItems.cpp" - "NjMonastryBossInstance.cpp" - "NjNPCMissionSpinjitzuServer.cpp" - "NjNyaMissionitems.cpp" - "NjRailActivatorsServer.cpp" - "NjRailPostServer.cpp" - "NjRailSwitch.cpp" - "NjScrollChestServer.cpp" - "NjWuNPC.cpp" "NPCAddRemoveItem.cpp" - "NpcAgCourseStarter.cpp" - "NpcCowboyServer.cpp" - "NpcEpsilonServer.cpp" - "NpcNjAssistantServer.cpp" - "NpcNpSpacemanBob.cpp" - "NpcPirateServer.cpp" - "NpcWispServer.cpp" - "NsConcertChoiceBuild.cpp" - "NsConcertChoiceBuildManager.cpp" - "NsConcertInstrument.cpp" - "NsConcertQuickBuild.cpp" - "NsGetFactionMissionServer.cpp" - "NsJohnnyMissionServer.cpp" - "NsLegoClubDoor.cpp" - "NsLupTeleport.cpp" - "NsModularBuild.cpp" - "NsQbImaginationStatue.cpp" - "NsTokenConsoleServer.cpp" - "NtAssemblyTubeServer.cpp" - "NtBeamImaginationCollectors.cpp" - "NtCombatChallengeDummy.cpp" - "NtCombatChallengeExplodingDummy.cpp" - "NtCombatChallengeServer.cpp" - "NtConsoleTeleportServer.cpp" - "NtDarkitectRevealServer.cpp" - "NtDirtCloudServer.cpp" - "NtDukeServer.cpp" "NtFactionSpyServer.cpp" - "NtHaelServer.cpp" - "NtImagBeamBuffer.cpp" - "NtImagimeterVisibility.cpp" - "NtOverbuildServer.cpp" - "NtParadoxPanelServer.cpp" - "NtParadoxTeleServer.cpp" - "NtSentinelWalkwayServer.cpp" - "NtSleepingGuard.cpp" - "NtVandaServer.cpp" - "NtVentureCannonServer.cpp" - "NtVentureSpeedPadServer.cpp" - "NtXRayServer.cpp" - "PersonalFortress.cpp" - "PetDigBuild.cpp" - "PetDigServer.cpp" - "PetFromDigServer.cpp" - "PetFromObjectServer.cpp" - "PirateRep.cpp" - "PropertyBankInteract.cpp" - "PropertyDeathPlane.cpp" - "PropertyDevice.cpp" - "PropertyFXDamage.cpp" - "PropertyPlatform.cpp" - "PrSeagullFly.cpp" - "PrWhistle.cpp" - "QbEnemyStunner.cpp" - "QbSpawner.cpp" - "RaceImagineCrateServer.cpp" - "RaceImaginePowerup.cpp" - "RaceMaelstromGeiser.cpp" - "RaceSmashServer.cpp" - "RainOfArrows.cpp" - "RandomSpawnerFin.cpp" - "RandomSpawnerPit.cpp" - "RandomSpawnerStr.cpp" - "RandomSpawnerZip.cpp" - "RemoveRentalGear.cpp" - "RockHydrantBroken.cpp" - "RockHydrantSmashable.cpp" "ScriptComponent.cpp" "ScriptedPowerupSpawner.cpp" - "SGCannon.cpp" - "SpawnGryphonServer.cpp" - "SpawnLionServer.cpp" - "SpawnPetBaseServer.cpp" - "SpawnSaberCatServer.cpp" - "SpawnShrakeServer.cpp" - "SpawnStegoServer.cpp" - "SpecialImaginePowerupSpawner.cpp" - "SpiderBossTreasureChestServer.cpp" - "SsModularBuildServer.cpp" - "StinkyFishTarget.cpp" - "StoryBoxInteractServer.cpp" - "Sunflower.cpp" - "TokenConsoleServer.cpp" - "TouchMissionUpdateServer.cpp" - "TreasureChestDragonServer.cpp" - "TriggerAmbush.cpp" - "VeBricksampleServer.cpp" - "VeEpsilonServer.cpp" - "VeMech.cpp" - "VeMissionConsole.cpp" - "WaveBossApe.cpp" - "WaveBossHammerling.cpp" - "WaveBossHorsemen.cpp" - "WaveBossSpiderling.cpp" - "WblGenericZone.cpp" - "WhFans.cpp" - "WildAmbients.cpp" - "WishingWellServer.cpp" - "ZoneAgMedProperty.cpp" - "ZoneAgProperty.cpp" - "ZoneAgSpiderQueen.cpp" - "ZoneAgSurvival.cpp" - "ZoneFvProperty.cpp" - "ZoneGfProperty.cpp" - "ZoneNsMedProperty.cpp" - "ZoneNsProperty.cpp" - "ZoneNsWaves.cpp" - "ZoneSGServer.cpp" PARENT_SCOPE) + "SpawnPetBaseServer.cpp") + +add_subdirectory(02_server) + +foreach(file ${DSCRIPTS_SOURCES_02_SERVER}) + set(DSCRIPTS_SOURCES ${DSCRIPTS_SOURCES} "02_server/${file}") +endforeach() + +add_subdirectory(ai) + +foreach(file ${DSCRIPTS_SOURCES_AI}) + set(DSCRIPTS_SOURCES ${DSCRIPTS_SOURCES} "ai/${file}") +endforeach() + +add_subdirectory(client) + +foreach(file ${DSCRIPTS_SOURCES_CLIENT}) + set(DSCRIPTS_SOURCES ${DSCRIPTS_SOURCES} "client/${file}") +endforeach() + +add_subdirectory(EquipmentScripts) + +foreach(file ${DSCRIPTS_SOURCES_EQUIPMENTSCRIPTS}) + set(DSCRIPTS_SOURCES ${DSCRIPTS_SOURCES} "EquipmentScripts/${file}") +endforeach() + +add_subdirectory(zone) + +foreach(file ${DSCRIPTS_SOURCES_ZONE}) + set(DSCRIPTS_SOURCES ${DSCRIPTS_SOURCES} "zone/${file}") +endforeach() + +set(DSCRIPTS_SOURCES ${DSCRIPTS_SOURCES} PARENT_SCOPE) diff --git a/dScripts/AnvilOfArmor.cpp b/dScripts/EquipmentScripts/AnvilOfArmor.cpp similarity index 100% rename from dScripts/AnvilOfArmor.cpp rename to dScripts/EquipmentScripts/AnvilOfArmor.cpp diff --git a/dScripts/AnvilOfArmor.h b/dScripts/EquipmentScripts/AnvilOfArmor.h similarity index 100% rename from dScripts/AnvilOfArmor.h rename to dScripts/EquipmentScripts/AnvilOfArmor.h diff --git a/dScripts/BuccaneerValiantShip.cpp b/dScripts/EquipmentScripts/BuccaneerValiantShip.cpp similarity index 100% rename from dScripts/BuccaneerValiantShip.cpp rename to dScripts/EquipmentScripts/BuccaneerValiantShip.cpp diff --git a/dScripts/BuccaneerValiantShip.h b/dScripts/EquipmentScripts/BuccaneerValiantShip.h similarity index 100% rename from dScripts/BuccaneerValiantShip.h rename to dScripts/EquipmentScripts/BuccaneerValiantShip.h diff --git a/dScripts/EquipmentScripts/CMakeLists.txt b/dScripts/EquipmentScripts/CMakeLists.txt new file mode 100644 index 00000000..c870ae31 --- /dev/null +++ b/dScripts/EquipmentScripts/CMakeLists.txt @@ -0,0 +1,9 @@ +set(DSCRIPTS_SOURCES_EQUIPMENTSCRIPTS + "Sunflower.cpp" + "AnvilOfArmor.cpp" + "FountainOfImagination.cpp" + "CauldronOfLife.cpp" + "PersonalFortress.cpp" + "BuccaneerValiantShip.cpp" + "FireFirstSkillonStartup.cpp" + PARENT_SCOPE) diff --git a/dScripts/CauldronOfLife.cpp b/dScripts/EquipmentScripts/CauldronOfLife.cpp similarity index 100% rename from dScripts/CauldronOfLife.cpp rename to dScripts/EquipmentScripts/CauldronOfLife.cpp diff --git a/dScripts/CauldronOfLife.h b/dScripts/EquipmentScripts/CauldronOfLife.h similarity index 100% rename from dScripts/CauldronOfLife.h rename to dScripts/EquipmentScripts/CauldronOfLife.h diff --git a/dScripts/FireFirstSkillonStartup.cpp b/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp similarity index 100% rename from dScripts/FireFirstSkillonStartup.cpp rename to dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp diff --git a/dScripts/FireFirstSkillonStartup.h b/dScripts/EquipmentScripts/FireFirstSkillonStartup.h similarity index 100% rename from dScripts/FireFirstSkillonStartup.h rename to dScripts/EquipmentScripts/FireFirstSkillonStartup.h diff --git a/dScripts/FountainOfImagination.cpp b/dScripts/EquipmentScripts/FountainOfImagination.cpp similarity index 100% rename from dScripts/FountainOfImagination.cpp rename to dScripts/EquipmentScripts/FountainOfImagination.cpp diff --git a/dScripts/FountainOfImagination.h b/dScripts/EquipmentScripts/FountainOfImagination.h similarity index 100% rename from dScripts/FountainOfImagination.h rename to dScripts/EquipmentScripts/FountainOfImagination.h diff --git a/dScripts/PersonalFortress.cpp b/dScripts/EquipmentScripts/PersonalFortress.cpp similarity index 100% rename from dScripts/PersonalFortress.cpp rename to dScripts/EquipmentScripts/PersonalFortress.cpp diff --git a/dScripts/PersonalFortress.h b/dScripts/EquipmentScripts/PersonalFortress.h similarity index 100% rename from dScripts/PersonalFortress.h rename to dScripts/EquipmentScripts/PersonalFortress.h diff --git a/dScripts/Sunflower.cpp b/dScripts/EquipmentScripts/Sunflower.cpp similarity index 100% rename from dScripts/Sunflower.cpp rename to dScripts/EquipmentScripts/Sunflower.cpp diff --git a/dScripts/Sunflower.h b/dScripts/EquipmentScripts/Sunflower.h similarity index 100% rename from dScripts/Sunflower.h rename to dScripts/EquipmentScripts/Sunflower.h diff --git a/dScripts/ActMine.cpp b/dScripts/ai/ACT/ActMine.cpp similarity index 100% rename from dScripts/ActMine.cpp rename to dScripts/ai/ACT/ActMine.cpp diff --git a/dScripts/ActMine.h b/dScripts/ai/ACT/ActMine.h similarity index 100% rename from dScripts/ActMine.h rename to dScripts/ai/ACT/ActMine.h diff --git a/dScripts/ActPlayerDeathTrigger.cpp b/dScripts/ai/ACT/ActPlayerDeathTrigger.cpp similarity index 100% rename from dScripts/ActPlayerDeathTrigger.cpp rename to dScripts/ai/ACT/ActPlayerDeathTrigger.cpp diff --git a/dScripts/ActPlayerDeathTrigger.h b/dScripts/ai/ACT/ActPlayerDeathTrigger.h similarity index 100% rename from dScripts/ActPlayerDeathTrigger.h rename to dScripts/ai/ACT/ActPlayerDeathTrigger.h diff --git a/dScripts/ActVehicleDeathTrigger.cpp b/dScripts/ai/ACT/ActVehicleDeathTrigger.cpp similarity index 100% rename from dScripts/ActVehicleDeathTrigger.cpp rename to dScripts/ai/ACT/ActVehicleDeathTrigger.cpp diff --git a/dScripts/ActVehicleDeathTrigger.h b/dScripts/ai/ACT/ActVehicleDeathTrigger.h similarity index 100% rename from dScripts/ActVehicleDeathTrigger.h rename to dScripts/ai/ACT/ActVehicleDeathTrigger.h diff --git a/dScripts/ai/ACT/CMakeLists.txt b/dScripts/ai/ACT/CMakeLists.txt new file mode 100644 index 00000000..79deeded --- /dev/null +++ b/dScripts/ai/ACT/CMakeLists.txt @@ -0,0 +1,12 @@ +set(DSCRIPTS_SOURCES_AI_ACT + "ActMine.cpp" + "ActPlayerDeathTrigger.cpp" + "ActVehicleDeathTrigger.cpp") + +add_subdirectory(FootRace) + +foreach(file ${DSCRIPTS_SOURCES_AI_ACT_FOOTRACE}) + set(DSCRIPTS_SOURCES_AI_ACT ${DSCRIPTS_SOURCES_AI_ACT} "FootRace/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_AI_ACT ${DSCRIPTS_SOURCES_AI_ACT} PARENT_SCOPE) diff --git a/dScripts/BaseFootRaceManager.cpp b/dScripts/ai/ACT/FootRace/BaseFootRaceManager.cpp similarity index 100% rename from dScripts/BaseFootRaceManager.cpp rename to dScripts/ai/ACT/FootRace/BaseFootRaceManager.cpp diff --git a/dScripts/BaseFootRaceManager.h b/dScripts/ai/ACT/FootRace/BaseFootRaceManager.h similarity index 100% rename from dScripts/BaseFootRaceManager.h rename to dScripts/ai/ACT/FootRace/BaseFootRaceManager.h diff --git a/dScripts/ai/ACT/FootRace/CMakeLists.txt b/dScripts/ai/ACT/FootRace/CMakeLists.txt new file mode 100644 index 00000000..c56986ff --- /dev/null +++ b/dScripts/ai/ACT/FootRace/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_AI_ACT_FOOTRACE + "BaseFootRaceManager.cpp" + PARENT_SCOPE) diff --git a/dScripts/ActSharkPlayerDeathTrigger.cpp b/dScripts/ai/AG/ActSharkPlayerDeathTrigger.cpp similarity index 100% rename from dScripts/ActSharkPlayerDeathTrigger.cpp rename to dScripts/ai/AG/ActSharkPlayerDeathTrigger.cpp diff --git a/dScripts/ActSharkPlayerDeathTrigger.h b/dScripts/ai/AG/ActSharkPlayerDeathTrigger.h similarity index 100% rename from dScripts/ActSharkPlayerDeathTrigger.h rename to dScripts/ai/AG/ActSharkPlayerDeathTrigger.h diff --git a/dScripts/AgBusDoor.cpp b/dScripts/ai/AG/AgBusDoor.cpp similarity index 100% rename from dScripts/AgBusDoor.cpp rename to dScripts/ai/AG/AgBusDoor.cpp diff --git a/dScripts/AgBusDoor.h b/dScripts/ai/AG/AgBusDoor.h similarity index 100% rename from dScripts/AgBusDoor.h rename to dScripts/ai/AG/AgBusDoor.h diff --git a/dScripts/AgDarkSpiderling.cpp b/dScripts/ai/AG/AgDarkSpiderling.cpp similarity index 100% rename from dScripts/AgDarkSpiderling.cpp rename to dScripts/ai/AG/AgDarkSpiderling.cpp diff --git a/dScripts/AgDarkSpiderling.h b/dScripts/ai/AG/AgDarkSpiderling.h similarity index 100% rename from dScripts/AgDarkSpiderling.h rename to dScripts/ai/AG/AgDarkSpiderling.h diff --git a/dScripts/AgFans.cpp b/dScripts/ai/AG/AgFans.cpp similarity index 100% rename from dScripts/AgFans.cpp rename to dScripts/ai/AG/AgFans.cpp diff --git a/dScripts/AgFans.h b/dScripts/ai/AG/AgFans.h similarity index 100% rename from dScripts/AgFans.h rename to dScripts/ai/AG/AgFans.h diff --git a/dScripts/AgImagSmashable.cpp b/dScripts/ai/AG/AgImagSmashable.cpp similarity index 100% rename from dScripts/AgImagSmashable.cpp rename to dScripts/ai/AG/AgImagSmashable.cpp diff --git a/dScripts/AgImagSmashable.h b/dScripts/ai/AG/AgImagSmashable.h similarity index 100% rename from dScripts/AgImagSmashable.h rename to dScripts/ai/AG/AgImagSmashable.h diff --git a/dScripts/AgJetEffectServer.cpp b/dScripts/ai/AG/AgJetEffectServer.cpp similarity index 100% rename from dScripts/AgJetEffectServer.cpp rename to dScripts/ai/AG/AgJetEffectServer.cpp diff --git a/dScripts/AgJetEffectServer.h b/dScripts/ai/AG/AgJetEffectServer.h similarity index 100% rename from dScripts/AgJetEffectServer.h rename to dScripts/ai/AG/AgJetEffectServer.h diff --git a/dScripts/AgPicnicBlanket.cpp b/dScripts/ai/AG/AgPicnicBlanket.cpp similarity index 100% rename from dScripts/AgPicnicBlanket.cpp rename to dScripts/ai/AG/AgPicnicBlanket.cpp diff --git a/dScripts/AgPicnicBlanket.h b/dScripts/ai/AG/AgPicnicBlanket.h similarity index 100% rename from dScripts/AgPicnicBlanket.h rename to dScripts/ai/AG/AgPicnicBlanket.h diff --git a/dScripts/AgQbElevator.cpp b/dScripts/ai/AG/AgQbElevator.cpp similarity index 100% rename from dScripts/AgQbElevator.cpp rename to dScripts/ai/AG/AgQbElevator.cpp diff --git a/dScripts/AgQbElevator.h b/dScripts/ai/AG/AgQbElevator.h similarity index 100% rename from dScripts/AgQbElevator.h rename to dScripts/ai/AG/AgQbElevator.h diff --git a/dScripts/AgQbWall.cpp b/dScripts/ai/AG/AgQbWall.cpp similarity index 100% rename from dScripts/AgQbWall.cpp rename to dScripts/ai/AG/AgQbWall.cpp diff --git a/dScripts/AgQbWall.h b/dScripts/ai/AG/AgQbWall.h similarity index 100% rename from dScripts/AgQbWall.h rename to dScripts/ai/AG/AgQbWall.h diff --git a/dScripts/AgSalutingNpcs.cpp b/dScripts/ai/AG/AgSalutingNpcs.cpp similarity index 100% rename from dScripts/AgSalutingNpcs.cpp rename to dScripts/ai/AG/AgSalutingNpcs.cpp diff --git a/dScripts/AgSalutingNpcs.h b/dScripts/ai/AG/AgSalutingNpcs.h similarity index 100% rename from dScripts/AgSalutingNpcs.h rename to dScripts/ai/AG/AgSalutingNpcs.h diff --git a/dScripts/AgShipPlayerDeathTrigger.cpp b/dScripts/ai/AG/AgShipPlayerDeathTrigger.cpp similarity index 100% rename from dScripts/AgShipPlayerDeathTrigger.cpp rename to dScripts/ai/AG/AgShipPlayerDeathTrigger.cpp diff --git a/dScripts/AgShipPlayerDeathTrigger.h b/dScripts/ai/AG/AgShipPlayerDeathTrigger.h similarity index 100% rename from dScripts/AgShipPlayerDeathTrigger.h rename to dScripts/ai/AG/AgShipPlayerDeathTrigger.h diff --git a/dScripts/AgShipPlayerShockServer.cpp b/dScripts/ai/AG/AgShipPlayerShockServer.cpp similarity index 100% rename from dScripts/AgShipPlayerShockServer.cpp rename to dScripts/ai/AG/AgShipPlayerShockServer.cpp diff --git a/dScripts/AgShipPlayerShockServer.h b/dScripts/ai/AG/AgShipPlayerShockServer.h similarity index 100% rename from dScripts/AgShipPlayerShockServer.h rename to dScripts/ai/AG/AgShipPlayerShockServer.h diff --git a/dScripts/AgSpaceStuff.cpp b/dScripts/ai/AG/AgSpaceStuff.cpp similarity index 100% rename from dScripts/AgSpaceStuff.cpp rename to dScripts/ai/AG/AgSpaceStuff.cpp diff --git a/dScripts/AgSpaceStuff.h b/dScripts/ai/AG/AgSpaceStuff.h similarity index 100% rename from dScripts/AgSpaceStuff.h rename to dScripts/ai/AG/AgSpaceStuff.h diff --git a/dScripts/AgStagePlatforms.cpp b/dScripts/ai/AG/AgStagePlatforms.cpp similarity index 100% rename from dScripts/AgStagePlatforms.cpp rename to dScripts/ai/AG/AgStagePlatforms.cpp diff --git a/dScripts/AgStagePlatforms.h b/dScripts/ai/AG/AgStagePlatforms.h similarity index 100% rename from dScripts/AgStagePlatforms.h rename to dScripts/ai/AG/AgStagePlatforms.h diff --git a/dScripts/AgStromlingProperty.cpp b/dScripts/ai/AG/AgStromlingProperty.cpp similarity index 100% rename from dScripts/AgStromlingProperty.cpp rename to dScripts/ai/AG/AgStromlingProperty.cpp diff --git a/dScripts/AgStromlingProperty.h b/dScripts/ai/AG/AgStromlingProperty.h similarity index 100% rename from dScripts/AgStromlingProperty.h rename to dScripts/ai/AG/AgStromlingProperty.h diff --git a/dScripts/AgTurret.cpp b/dScripts/ai/AG/AgTurret.cpp similarity index 100% rename from dScripts/AgTurret.cpp rename to dScripts/ai/AG/AgTurret.cpp diff --git a/dScripts/AgTurret.h b/dScripts/ai/AG/AgTurret.h similarity index 100% rename from dScripts/AgTurret.h rename to dScripts/ai/AG/AgTurret.h diff --git a/dScripts/ai/AG/CMakeLists.txt b/dScripts/ai/AG/CMakeLists.txt new file mode 100644 index 00000000..092b8de7 --- /dev/null +++ b/dScripts/ai/AG/CMakeLists.txt @@ -0,0 +1,18 @@ +set(DSCRIPTS_SOURCES_AI_AG + "AgShipPlayerDeathTrigger.cpp" + "AgSpaceStuff.cpp" + "AgShipPlayerShockServer.cpp" + "AgImagSmashable.cpp" + "ActSharkPlayerDeathTrigger.cpp" + "AgBusDoor.cpp" + "AgTurret.cpp" + "AgFans.cpp" + "AgSalutingNpcs.cpp" + "AgJetEffectServer.cpp" + "AgQbElevator.cpp" + "AgStromlingProperty.cpp" + "AgDarkSpiderling.cpp" + "AgPicnicBlanket.cpp" + "AgStagePlatforms.cpp" + "AgQbWall.cpp" + PARENT_SCOPE) diff --git a/dScripts/ai/CMakeLists.txt b/dScripts/ai/CMakeLists.txt new file mode 100644 index 00000000..44944b90 --- /dev/null +++ b/dScripts/ai/CMakeLists.txt @@ -0,0 +1,81 @@ +set(DSCRIPTS_SOURCES_AI) + +add_subdirectory(ACT) + +foreach(file ${DSCRIPTS_SOURCES_AI_ACT}) + set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} "ACT/${file}") +endforeach() + +add_subdirectory(AG) + +foreach(file ${DSCRIPTS_SOURCES_AI_AG}) + set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} "AG/${file}") +endforeach() + +add_subdirectory(FV) + +foreach(file ${DSCRIPTS_SOURCES_AI_FV}) + set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} "FV/${file}") +endforeach() + +add_subdirectory(GENERAL) + +foreach(file ${DSCRIPTS_SOURCES_AI_GENERAL}) + set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} "GENERAL/${file}") +endforeach() + +add_subdirectory(GF) + +foreach(file ${DSCRIPTS_SOURCES_AI_GF}) + set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} "GF/${file}") +endforeach() + +add_subdirectory(MINIGAME) + +foreach(file ${DSCRIPTS_SOURCES_AI_MINIGAME}) + set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} "MINIGAME/${file}") +endforeach() + +add_subdirectory(NP) + +foreach(file ${DSCRIPTS_SOURCES_AI_NP}) + set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} "NP/${file}") +endforeach() + +add_subdirectory(NS) + +foreach(file ${DSCRIPTS_SOURCES_AI_NS}) + set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} "NS/${file}") +endforeach() + +add_subdirectory(PETS) + +foreach(file ${DSCRIPTS_SOURCES_AI_PETS}) + set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} "PETS/${file}") +endforeach() + +add_subdirectory(PROPERTY) + +foreach(file ${DSCRIPTS_SOURCES_AI_PROPERTY}) + set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} "PROPERTY/${file}") +endforeach() + +add_subdirectory(RACING) + +foreach(file ${DSCRIPTS_SOURCES_AI_RACING}) + set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} "RACING/${file}") +endforeach() + +add_subdirectory(SPEC) + +foreach(file ${DSCRIPTS_SOURCES_AI_SPEC}) + set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} "SPEC/${file}") +endforeach() + +add_subdirectory(WILD) + +foreach(file ${DSCRIPTS_SOURCES_AI_WILD}) + set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} "WILD/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_AI ${DSCRIPTS_SOURCES_AI} PARENT_SCOPE) diff --git a/dScripts/ActNinjaTurret.cpp b/dScripts/ai/FV/ActNinjaTurret.cpp similarity index 100% rename from dScripts/ActNinjaTurret.cpp rename to dScripts/ai/FV/ActNinjaTurret.cpp diff --git a/dScripts/ActNinjaTurret.h b/dScripts/ai/FV/ActNinjaTurret.h similarity index 100% rename from dScripts/ActNinjaTurret.h rename to dScripts/ai/FV/ActNinjaTurret.h diff --git a/dScripts/ActParadoxPipeFix.cpp b/dScripts/ai/FV/ActParadoxPipeFix.cpp similarity index 100% rename from dScripts/ActParadoxPipeFix.cpp rename to dScripts/ai/FV/ActParadoxPipeFix.cpp diff --git a/dScripts/ActParadoxPipeFix.h b/dScripts/ai/FV/ActParadoxPipeFix.h similarity index 100% rename from dScripts/ActParadoxPipeFix.h rename to dScripts/ai/FV/ActParadoxPipeFix.h diff --git a/dScripts/ai/FV/CMakeLists.txt b/dScripts/ai/FV/CMakeLists.txt new file mode 100644 index 00000000..2a8a3367 --- /dev/null +++ b/dScripts/ai/FV/CMakeLists.txt @@ -0,0 +1,18 @@ +set(DSCRIPTS_SOURCES_AI_FV + "ActNinjaTurret.cpp" + "FvFlyingCreviceDragon.cpp" + "FvDragonSmashingGolemQb.cpp" + "FvFreeGfNinjas.cpp" + "FvPandaSpawnerServer.cpp" + "FvPandaServer.cpp" + "FvBrickPuzzleServer.cpp" + "FvConsoleLeftQuickbuild.cpp" + "FvConsoleRightQuickbuild.cpp" + "FvFacilityBrick.cpp" + "FvFacilityPipes.cpp" + "ActParadoxPipeFix.cpp" + "FvNinjaGuard.cpp" + "FvPassThroughWall.cpp" + "FvBounceOverWall.cpp" + "FvMaelstromGeyser.cpp" + PARENT_SCOPE) diff --git a/dScripts/FvBounceOverWall.cpp b/dScripts/ai/FV/FvBounceOverWall.cpp similarity index 100% rename from dScripts/FvBounceOverWall.cpp rename to dScripts/ai/FV/FvBounceOverWall.cpp diff --git a/dScripts/FvBounceOverWall.h b/dScripts/ai/FV/FvBounceOverWall.h similarity index 100% rename from dScripts/FvBounceOverWall.h rename to dScripts/ai/FV/FvBounceOverWall.h diff --git a/dScripts/FvBrickPuzzleServer.cpp b/dScripts/ai/FV/FvBrickPuzzleServer.cpp similarity index 100% rename from dScripts/FvBrickPuzzleServer.cpp rename to dScripts/ai/FV/FvBrickPuzzleServer.cpp diff --git a/dScripts/FvBrickPuzzleServer.h b/dScripts/ai/FV/FvBrickPuzzleServer.h similarity index 100% rename from dScripts/FvBrickPuzzleServer.h rename to dScripts/ai/FV/FvBrickPuzzleServer.h diff --git a/dScripts/FvConsoleLeftQuickbuild.cpp b/dScripts/ai/FV/FvConsoleLeftQuickbuild.cpp similarity index 100% rename from dScripts/FvConsoleLeftQuickbuild.cpp rename to dScripts/ai/FV/FvConsoleLeftQuickbuild.cpp diff --git a/dScripts/FvConsoleLeftQuickbuild.h b/dScripts/ai/FV/FvConsoleLeftQuickbuild.h similarity index 100% rename from dScripts/FvConsoleLeftQuickbuild.h rename to dScripts/ai/FV/FvConsoleLeftQuickbuild.h diff --git a/dScripts/FvConsoleRightQuickbuild.cpp b/dScripts/ai/FV/FvConsoleRightQuickbuild.cpp similarity index 100% rename from dScripts/FvConsoleRightQuickbuild.cpp rename to dScripts/ai/FV/FvConsoleRightQuickbuild.cpp diff --git a/dScripts/FvConsoleRightQuickbuild.h b/dScripts/ai/FV/FvConsoleRightQuickbuild.h similarity index 100% rename from dScripts/FvConsoleRightQuickbuild.h rename to dScripts/ai/FV/FvConsoleRightQuickbuild.h diff --git a/dScripts/FvDragonSmashingGolemQb.cpp b/dScripts/ai/FV/FvDragonSmashingGolemQb.cpp similarity index 100% rename from dScripts/FvDragonSmashingGolemQb.cpp rename to dScripts/ai/FV/FvDragonSmashingGolemQb.cpp diff --git a/dScripts/FvDragonSmashingGolemQb.h b/dScripts/ai/FV/FvDragonSmashingGolemQb.h similarity index 100% rename from dScripts/FvDragonSmashingGolemQb.h rename to dScripts/ai/FV/FvDragonSmashingGolemQb.h diff --git a/dScripts/FvFacilityBrick.cpp b/dScripts/ai/FV/FvFacilityBrick.cpp similarity index 100% rename from dScripts/FvFacilityBrick.cpp rename to dScripts/ai/FV/FvFacilityBrick.cpp diff --git a/dScripts/FvFacilityBrick.h b/dScripts/ai/FV/FvFacilityBrick.h similarity index 100% rename from dScripts/FvFacilityBrick.h rename to dScripts/ai/FV/FvFacilityBrick.h diff --git a/dScripts/FvFacilityPipes.cpp b/dScripts/ai/FV/FvFacilityPipes.cpp similarity index 100% rename from dScripts/FvFacilityPipes.cpp rename to dScripts/ai/FV/FvFacilityPipes.cpp diff --git a/dScripts/FvFacilityPipes.h b/dScripts/ai/FV/FvFacilityPipes.h similarity index 100% rename from dScripts/FvFacilityPipes.h rename to dScripts/ai/FV/FvFacilityPipes.h diff --git a/dScripts/FvFlyingCreviceDragon.cpp b/dScripts/ai/FV/FvFlyingCreviceDragon.cpp similarity index 100% rename from dScripts/FvFlyingCreviceDragon.cpp rename to dScripts/ai/FV/FvFlyingCreviceDragon.cpp diff --git a/dScripts/FvFlyingCreviceDragon.h b/dScripts/ai/FV/FvFlyingCreviceDragon.h similarity index 100% rename from dScripts/FvFlyingCreviceDragon.h rename to dScripts/ai/FV/FvFlyingCreviceDragon.h diff --git a/dScripts/FvFreeGfNinjas.cpp b/dScripts/ai/FV/FvFreeGfNinjas.cpp similarity index 100% rename from dScripts/FvFreeGfNinjas.cpp rename to dScripts/ai/FV/FvFreeGfNinjas.cpp diff --git a/dScripts/FvFreeGfNinjas.h b/dScripts/ai/FV/FvFreeGfNinjas.h similarity index 100% rename from dScripts/FvFreeGfNinjas.h rename to dScripts/ai/FV/FvFreeGfNinjas.h diff --git a/dScripts/FvMaelstromGeyser.cpp b/dScripts/ai/FV/FvMaelstromGeyser.cpp similarity index 100% rename from dScripts/FvMaelstromGeyser.cpp rename to dScripts/ai/FV/FvMaelstromGeyser.cpp diff --git a/dScripts/FvMaelstromGeyser.h b/dScripts/ai/FV/FvMaelstromGeyser.h similarity index 100% rename from dScripts/FvMaelstromGeyser.h rename to dScripts/ai/FV/FvMaelstromGeyser.h diff --git a/dScripts/FvNinjaGuard.cpp b/dScripts/ai/FV/FvNinjaGuard.cpp similarity index 100% rename from dScripts/FvNinjaGuard.cpp rename to dScripts/ai/FV/FvNinjaGuard.cpp diff --git a/dScripts/FvNinjaGuard.h b/dScripts/ai/FV/FvNinjaGuard.h similarity index 100% rename from dScripts/FvNinjaGuard.h rename to dScripts/ai/FV/FvNinjaGuard.h diff --git a/dScripts/FvPandaServer.cpp b/dScripts/ai/FV/FvPandaServer.cpp similarity index 100% rename from dScripts/FvPandaServer.cpp rename to dScripts/ai/FV/FvPandaServer.cpp diff --git a/dScripts/FvPandaServer.h b/dScripts/ai/FV/FvPandaServer.h similarity index 100% rename from dScripts/FvPandaServer.h rename to dScripts/ai/FV/FvPandaServer.h diff --git a/dScripts/FvPandaSpawnerServer.cpp b/dScripts/ai/FV/FvPandaSpawnerServer.cpp similarity index 100% rename from dScripts/FvPandaSpawnerServer.cpp rename to dScripts/ai/FV/FvPandaSpawnerServer.cpp diff --git a/dScripts/FvPandaSpawnerServer.h b/dScripts/ai/FV/FvPandaSpawnerServer.h similarity index 100% rename from dScripts/FvPandaSpawnerServer.h rename to dScripts/ai/FV/FvPandaSpawnerServer.h diff --git a/dScripts/FvPassThroughWall.cpp b/dScripts/ai/FV/FvPassThroughWall.cpp similarity index 100% rename from dScripts/FvPassThroughWall.cpp rename to dScripts/ai/FV/FvPassThroughWall.cpp diff --git a/dScripts/FvPassThroughWall.h b/dScripts/ai/FV/FvPassThroughWall.h similarity index 100% rename from dScripts/FvPassThroughWall.h rename to dScripts/ai/FV/FvPassThroughWall.h diff --git a/dScripts/ai/GENERAL/CMakeLists.txt b/dScripts/ai/GENERAL/CMakeLists.txt new file mode 100644 index 00000000..da973658 --- /dev/null +++ b/dScripts/ai/GENERAL/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DSCRIPTS_SOURCES_AI_GENERAL + "InstanceExitTransferPlayerToLastNonInstance.cpp" + "LegoDieRoll.cpp" + PARENT_SCOPE) diff --git a/dScripts/InstanceExitTransferPlayerToLastNonInstance.cpp b/dScripts/ai/GENERAL/InstanceExitTransferPlayerToLastNonInstance.cpp similarity index 100% rename from dScripts/InstanceExitTransferPlayerToLastNonInstance.cpp rename to dScripts/ai/GENERAL/InstanceExitTransferPlayerToLastNonInstance.cpp diff --git a/dScripts/InstanceExitTransferPlayerToLastNonInstance.h b/dScripts/ai/GENERAL/InstanceExitTransferPlayerToLastNonInstance.h similarity index 100% rename from dScripts/InstanceExitTransferPlayerToLastNonInstance.h rename to dScripts/ai/GENERAL/InstanceExitTransferPlayerToLastNonInstance.h diff --git a/dScripts/LegoDieRoll.cpp b/dScripts/ai/GENERAL/LegoDieRoll.cpp similarity index 100% rename from dScripts/LegoDieRoll.cpp rename to dScripts/ai/GENERAL/LegoDieRoll.cpp diff --git a/dScripts/LegoDieRoll.h b/dScripts/ai/GENERAL/LegoDieRoll.h similarity index 100% rename from dScripts/LegoDieRoll.h rename to dScripts/ai/GENERAL/LegoDieRoll.h diff --git a/dScripts/ai/GF/CMakeLists.txt b/dScripts/ai/GF/CMakeLists.txt new file mode 100644 index 00000000..9937618c --- /dev/null +++ b/dScripts/ai/GF/CMakeLists.txt @@ -0,0 +1,14 @@ +set(DSCRIPTS_SOURCES_AI_GF + "GfCampfire.cpp" + "GfOrgan.cpp" + "GfBanana.cpp" + "GfBananaCluster.cpp" + "GfJailkeepMission.cpp" + "TriggerAmbush.cpp" + "GfJailWalls.cpp" + "PetDigBuild.cpp" + "GfArchway.cpp" + "GfMaelstromGeyser.cpp" + "PirateRep.cpp" + "GfParrotCrash.cpp" + PARENT_SCOPE) diff --git a/dScripts/GfArchway.cpp b/dScripts/ai/GF/GfArchway.cpp similarity index 100% rename from dScripts/GfArchway.cpp rename to dScripts/ai/GF/GfArchway.cpp diff --git a/dScripts/GfArchway.h b/dScripts/ai/GF/GfArchway.h similarity index 100% rename from dScripts/GfArchway.h rename to dScripts/ai/GF/GfArchway.h diff --git a/dScripts/GfBanana.cpp b/dScripts/ai/GF/GfBanana.cpp similarity index 100% rename from dScripts/GfBanana.cpp rename to dScripts/ai/GF/GfBanana.cpp diff --git a/dScripts/GfBanana.h b/dScripts/ai/GF/GfBanana.h similarity index 100% rename from dScripts/GfBanana.h rename to dScripts/ai/GF/GfBanana.h diff --git a/dScripts/GfBananaCluster.cpp b/dScripts/ai/GF/GfBananaCluster.cpp similarity index 100% rename from dScripts/GfBananaCluster.cpp rename to dScripts/ai/GF/GfBananaCluster.cpp diff --git a/dScripts/GfBananaCluster.h b/dScripts/ai/GF/GfBananaCluster.h similarity index 100% rename from dScripts/GfBananaCluster.h rename to dScripts/ai/GF/GfBananaCluster.h diff --git a/dScripts/GfCampfire.cpp b/dScripts/ai/GF/GfCampfire.cpp similarity index 100% rename from dScripts/GfCampfire.cpp rename to dScripts/ai/GF/GfCampfire.cpp diff --git a/dScripts/GfCampfire.h b/dScripts/ai/GF/GfCampfire.h similarity index 100% rename from dScripts/GfCampfire.h rename to dScripts/ai/GF/GfCampfire.h diff --git a/dScripts/GfJailWalls.cpp b/dScripts/ai/GF/GfJailWalls.cpp similarity index 100% rename from dScripts/GfJailWalls.cpp rename to dScripts/ai/GF/GfJailWalls.cpp diff --git a/dScripts/GfJailWalls.h b/dScripts/ai/GF/GfJailWalls.h similarity index 100% rename from dScripts/GfJailWalls.h rename to dScripts/ai/GF/GfJailWalls.h diff --git a/dScripts/GfJailkeepMission.cpp b/dScripts/ai/GF/GfJailkeepMission.cpp similarity index 100% rename from dScripts/GfJailkeepMission.cpp rename to dScripts/ai/GF/GfJailkeepMission.cpp diff --git a/dScripts/GfJailkeepMission.h b/dScripts/ai/GF/GfJailkeepMission.h similarity index 100% rename from dScripts/GfJailkeepMission.h rename to dScripts/ai/GF/GfJailkeepMission.h diff --git a/dScripts/GfMaelstromGeyser.cpp b/dScripts/ai/GF/GfMaelstromGeyser.cpp similarity index 100% rename from dScripts/GfMaelstromGeyser.cpp rename to dScripts/ai/GF/GfMaelstromGeyser.cpp diff --git a/dScripts/GfMaelstromGeyser.h b/dScripts/ai/GF/GfMaelstromGeyser.h similarity index 100% rename from dScripts/GfMaelstromGeyser.h rename to dScripts/ai/GF/GfMaelstromGeyser.h diff --git a/dScripts/GfOrgan.cpp b/dScripts/ai/GF/GfOrgan.cpp similarity index 100% rename from dScripts/GfOrgan.cpp rename to dScripts/ai/GF/GfOrgan.cpp diff --git a/dScripts/GfOrgan.h b/dScripts/ai/GF/GfOrgan.h similarity index 100% rename from dScripts/GfOrgan.h rename to dScripts/ai/GF/GfOrgan.h diff --git a/dScripts/GfParrotCrash.cpp b/dScripts/ai/GF/GfParrotCrash.cpp similarity index 100% rename from dScripts/GfParrotCrash.cpp rename to dScripts/ai/GF/GfParrotCrash.cpp diff --git a/dScripts/GfParrotCrash.h b/dScripts/ai/GF/GfParrotCrash.h similarity index 100% rename from dScripts/GfParrotCrash.h rename to dScripts/ai/GF/GfParrotCrash.h diff --git a/dScripts/PetDigBuild.cpp b/dScripts/ai/GF/PetDigBuild.cpp similarity index 100% rename from dScripts/PetDigBuild.cpp rename to dScripts/ai/GF/PetDigBuild.cpp diff --git a/dScripts/PetDigBuild.h b/dScripts/ai/GF/PetDigBuild.h similarity index 100% rename from dScripts/PetDigBuild.h rename to dScripts/ai/GF/PetDigBuild.h diff --git a/dScripts/PirateRep.cpp b/dScripts/ai/GF/PirateRep.cpp similarity index 100% rename from dScripts/PirateRep.cpp rename to dScripts/ai/GF/PirateRep.cpp diff --git a/dScripts/PirateRep.h b/dScripts/ai/GF/PirateRep.h similarity index 100% rename from dScripts/PirateRep.h rename to dScripts/ai/GF/PirateRep.h diff --git a/dScripts/TriggerAmbush.cpp b/dScripts/ai/GF/TriggerAmbush.cpp similarity index 100% rename from dScripts/TriggerAmbush.cpp rename to dScripts/ai/GF/TriggerAmbush.cpp diff --git a/dScripts/TriggerAmbush.h b/dScripts/ai/GF/TriggerAmbush.h similarity index 100% rename from dScripts/TriggerAmbush.h rename to dScripts/ai/GF/TriggerAmbush.h diff --git a/dScripts/ai/MINIGAME/CMakeLists.txt b/dScripts/ai/MINIGAME/CMakeLists.txt new file mode 100644 index 00000000..d4517519 --- /dev/null +++ b/dScripts/ai/MINIGAME/CMakeLists.txt @@ -0,0 +1,9 @@ +set(DSCRIPTS_SOURCES_AI_MINIGAME) + +add_subdirectory(SG_GF) + +foreach(file ${DSCRIPTS_SOURCES_AI_MINIGAME_SG_GF}) + set(DSCRIPTS_SOURCES_AI_MINIGAME ${DSCRIPTS_SOURCES_AI_MINIGAME} "SG_GF/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_AI_MINIGAME ${DSCRIPTS_SOURCES_AI_MINIGAME} PARENT_SCOPE) diff --git a/dScripts/ai/MINIGAME/SG_GF/CMakeLists.txt b/dScripts/ai/MINIGAME/SG_GF/CMakeLists.txt new file mode 100644 index 00000000..87bd879a --- /dev/null +++ b/dScripts/ai/MINIGAME/SG_GF/CMakeLists.txt @@ -0,0 +1,10 @@ +set(DSCRIPTS_SOURCES_AI_MINIGAME_SG_GF + "ZoneSGServer.cpp") + +add_subdirectory(SERVER) + +foreach(file ${DSCRIPTS_SOURCES_AI_MINIGAME_SG_GF_SERVER}) + set(DSCRIPTS_SOURCES_AI_MINIGAME_SG_GF ${DSCRIPTS_SOURCES_AI_MINIGAME_SG_GF} "SERVER/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_AI_MINIGAME_SG_GF ${DSCRIPTS_SOURCES_AI_MINIGAME_SG_GF} PARENT_SCOPE) diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/CMakeLists.txt b/dScripts/ai/MINIGAME/SG_GF/SERVER/CMakeLists.txt new file mode 100644 index 00000000..fb79c0e9 --- /dev/null +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_AI_MINIGAME_SG_GF_SERVER + "SGCannon.cpp" + PARENT_SCOPE) diff --git a/dScripts/SGCannon.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp similarity index 100% rename from dScripts/SGCannon.cpp rename to dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp diff --git a/dScripts/SGCannon.h b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.h similarity index 100% rename from dScripts/SGCannon.h rename to dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.h diff --git a/dScripts/ZoneSGServer.cpp b/dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.cpp similarity index 100% rename from dScripts/ZoneSGServer.cpp rename to dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.cpp diff --git a/dScripts/ZoneSGServer.h b/dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.h similarity index 100% rename from dScripts/ZoneSGServer.h rename to dScripts/ai/MINIGAME/SG_GF/ZoneSGServer.h diff --git a/dScripts/ai/NP/CMakeLists.txt b/dScripts/ai/NP/CMakeLists.txt new file mode 100644 index 00000000..39a7301a --- /dev/null +++ b/dScripts/ai/NP/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_AI_NP + "NpcNpSpacemanBob.cpp" + PARENT_SCOPE) diff --git a/dScripts/NpcNpSpacemanBob.cpp b/dScripts/ai/NP/NpcNpSpacemanBob.cpp similarity index 100% rename from dScripts/NpcNpSpacemanBob.cpp rename to dScripts/ai/NP/NpcNpSpacemanBob.cpp diff --git a/dScripts/NpcNpSpacemanBob.h b/dScripts/ai/NP/NpcNpSpacemanBob.h similarity index 100% rename from dScripts/NpcNpSpacemanBob.h rename to dScripts/ai/NP/NpcNpSpacemanBob.h diff --git a/dScripts/ai/NS/CMakeLists.txt b/dScripts/ai/NS/CMakeLists.txt new file mode 100644 index 00000000..e8ec84b1 --- /dev/null +++ b/dScripts/ai/NS/CMakeLists.txt @@ -0,0 +1,24 @@ +set(DSCRIPTS_SOURCES_AI_NS + "ClRing.cpp" + "NsConcertChoiceBuild.cpp" + "NsConcertInstrument.cpp" + "NsConcertQuickBuild.cpp" + "NsGetFactionMissionServer.cpp" + "NsJohnnyMissionServer.cpp" + "NsModularBuild.cpp" + "NsQbImaginationStatue.cpp" + "WhFans.cpp") + +add_subdirectory(NS_PP_01) + +foreach(file ${DSCRIPTS_SOURCES_AI_NS_NS_PP_01}) + set(DSCRIPTS_SOURCES_AI_NS ${DSCRIPTS_SOURCES_AI_NS} "NS_PP_01/${file}") +endforeach() + +add_subdirectory(WH) + +foreach(file ${DSCRIPTS_SOURCES_AI_NS_WH}) + set(DSCRIPTS_SOURCES_AI_NS ${DSCRIPTS_SOURCES_AI_NS} "WH/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_AI_NS ${DSCRIPTS_SOURCES_AI_NS} PARENT_SCOPE) diff --git a/dScripts/ClRing.cpp b/dScripts/ai/NS/ClRing.cpp similarity index 100% rename from dScripts/ClRing.cpp rename to dScripts/ai/NS/ClRing.cpp diff --git a/dScripts/ClRing.h b/dScripts/ai/NS/ClRing.h similarity index 100% rename from dScripts/ClRing.h rename to dScripts/ai/NS/ClRing.h diff --git a/dScripts/ai/NS/NS_PP_01/CMakeLists.txt b/dScripts/ai/NS/NS_PP_01/CMakeLists.txt new file mode 100644 index 00000000..3f26c135 --- /dev/null +++ b/dScripts/ai/NS/NS_PP_01/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_AI_NS_NS_PP_01 + "PropertyDeathPlane.cpp" + PARENT_SCOPE) diff --git a/dScripts/PropertyDeathPlane.cpp b/dScripts/ai/NS/NS_PP_01/PropertyDeathPlane.cpp similarity index 100% rename from dScripts/PropertyDeathPlane.cpp rename to dScripts/ai/NS/NS_PP_01/PropertyDeathPlane.cpp diff --git a/dScripts/PropertyDeathPlane.h b/dScripts/ai/NS/NS_PP_01/PropertyDeathPlane.h similarity index 100% rename from dScripts/PropertyDeathPlane.h rename to dScripts/ai/NS/NS_PP_01/PropertyDeathPlane.h diff --git a/dScripts/NsConcertChoiceBuild.cpp b/dScripts/ai/NS/NsConcertChoiceBuild.cpp similarity index 100% rename from dScripts/NsConcertChoiceBuild.cpp rename to dScripts/ai/NS/NsConcertChoiceBuild.cpp diff --git a/dScripts/NsConcertChoiceBuild.h b/dScripts/ai/NS/NsConcertChoiceBuild.h similarity index 100% rename from dScripts/NsConcertChoiceBuild.h rename to dScripts/ai/NS/NsConcertChoiceBuild.h diff --git a/dScripts/NsConcertInstrument.cpp b/dScripts/ai/NS/NsConcertInstrument.cpp similarity index 100% rename from dScripts/NsConcertInstrument.cpp rename to dScripts/ai/NS/NsConcertInstrument.cpp diff --git a/dScripts/NsConcertInstrument.h b/dScripts/ai/NS/NsConcertInstrument.h similarity index 100% rename from dScripts/NsConcertInstrument.h rename to dScripts/ai/NS/NsConcertInstrument.h diff --git a/dScripts/NsConcertQuickBuild.cpp b/dScripts/ai/NS/NsConcertQuickBuild.cpp similarity index 100% rename from dScripts/NsConcertQuickBuild.cpp rename to dScripts/ai/NS/NsConcertQuickBuild.cpp diff --git a/dScripts/NsConcertQuickBuild.h b/dScripts/ai/NS/NsConcertQuickBuild.h similarity index 100% rename from dScripts/NsConcertQuickBuild.h rename to dScripts/ai/NS/NsConcertQuickBuild.h diff --git a/dScripts/NsGetFactionMissionServer.cpp b/dScripts/ai/NS/NsGetFactionMissionServer.cpp similarity index 100% rename from dScripts/NsGetFactionMissionServer.cpp rename to dScripts/ai/NS/NsGetFactionMissionServer.cpp diff --git a/dScripts/NsGetFactionMissionServer.h b/dScripts/ai/NS/NsGetFactionMissionServer.h similarity index 100% rename from dScripts/NsGetFactionMissionServer.h rename to dScripts/ai/NS/NsGetFactionMissionServer.h diff --git a/dScripts/NsJohnnyMissionServer.cpp b/dScripts/ai/NS/NsJohnnyMissionServer.cpp similarity index 100% rename from dScripts/NsJohnnyMissionServer.cpp rename to dScripts/ai/NS/NsJohnnyMissionServer.cpp diff --git a/dScripts/NsJohnnyMissionServer.h b/dScripts/ai/NS/NsJohnnyMissionServer.h similarity index 100% rename from dScripts/NsJohnnyMissionServer.h rename to dScripts/ai/NS/NsJohnnyMissionServer.h diff --git a/dScripts/NsModularBuild.cpp b/dScripts/ai/NS/NsModularBuild.cpp similarity index 100% rename from dScripts/NsModularBuild.cpp rename to dScripts/ai/NS/NsModularBuild.cpp diff --git a/dScripts/NsModularBuild.h b/dScripts/ai/NS/NsModularBuild.h similarity index 100% rename from dScripts/NsModularBuild.h rename to dScripts/ai/NS/NsModularBuild.h diff --git a/dScripts/NsQbImaginationStatue.cpp b/dScripts/ai/NS/NsQbImaginationStatue.cpp similarity index 100% rename from dScripts/NsQbImaginationStatue.cpp rename to dScripts/ai/NS/NsQbImaginationStatue.cpp diff --git a/dScripts/NsQbImaginationStatue.h b/dScripts/ai/NS/NsQbImaginationStatue.h similarity index 100% rename from dScripts/NsQbImaginationStatue.h rename to dScripts/ai/NS/NsQbImaginationStatue.h diff --git a/dScripts/ai/NS/WH/CMakeLists.txt b/dScripts/ai/NS/WH/CMakeLists.txt new file mode 100644 index 00000000..179a417f --- /dev/null +++ b/dScripts/ai/NS/WH/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DSCRIPTS_SOURCES_AI_NS_WH + "RockHydrantSmashable.cpp" + "RockHydrantBroken.cpp" + PARENT_SCOPE) diff --git a/dScripts/RockHydrantBroken.cpp b/dScripts/ai/NS/WH/RockHydrantBroken.cpp similarity index 100% rename from dScripts/RockHydrantBroken.cpp rename to dScripts/ai/NS/WH/RockHydrantBroken.cpp diff --git a/dScripts/RockHydrantBroken.h b/dScripts/ai/NS/WH/RockHydrantBroken.h similarity index 100% rename from dScripts/RockHydrantBroken.h rename to dScripts/ai/NS/WH/RockHydrantBroken.h diff --git a/dScripts/RockHydrantSmashable.cpp b/dScripts/ai/NS/WH/RockHydrantSmashable.cpp similarity index 100% rename from dScripts/RockHydrantSmashable.cpp rename to dScripts/ai/NS/WH/RockHydrantSmashable.cpp diff --git a/dScripts/RockHydrantSmashable.h b/dScripts/ai/NS/WH/RockHydrantSmashable.h similarity index 100% rename from dScripts/RockHydrantSmashable.h rename to dScripts/ai/NS/WH/RockHydrantSmashable.h diff --git a/dScripts/WhFans.cpp b/dScripts/ai/NS/WhFans.cpp similarity index 100% rename from dScripts/WhFans.cpp rename to dScripts/ai/NS/WhFans.cpp diff --git a/dScripts/WhFans.h b/dScripts/ai/NS/WhFans.h similarity index 100% rename from dScripts/WhFans.h rename to dScripts/ai/NS/WhFans.h diff --git a/dScripts/ai/PETS/CMakeLists.txt b/dScripts/ai/PETS/CMakeLists.txt new file mode 100644 index 00000000..93a9012d --- /dev/null +++ b/dScripts/ai/PETS/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_AI_PETS + "HydrantSmashable.cpp" + PARENT_SCOPE) diff --git a/dScripts/HydrantSmashable.cpp b/dScripts/ai/PETS/HydrantSmashable.cpp similarity index 100% rename from dScripts/HydrantSmashable.cpp rename to dScripts/ai/PETS/HydrantSmashable.cpp diff --git a/dScripts/HydrantSmashable.h b/dScripts/ai/PETS/HydrantSmashable.h similarity index 100% rename from dScripts/HydrantSmashable.h rename to dScripts/ai/PETS/HydrantSmashable.h diff --git a/dScripts/AgPropGuard.cpp b/dScripts/ai/PROPERTY/AG/AgPropGuard.cpp similarity index 100% rename from dScripts/AgPropGuard.cpp rename to dScripts/ai/PROPERTY/AG/AgPropGuard.cpp diff --git a/dScripts/AgPropGuard.h b/dScripts/ai/PROPERTY/AG/AgPropGuard.h similarity index 100% rename from dScripts/AgPropGuard.h rename to dScripts/ai/PROPERTY/AG/AgPropGuard.h diff --git a/dScripts/ai/PROPERTY/AG/CMakeLists.txt b/dScripts/ai/PROPERTY/AG/CMakeLists.txt new file mode 100644 index 00000000..f2139463 --- /dev/null +++ b/dScripts/ai/PROPERTY/AG/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_AI_PROPERTY_AG + "AgPropGuard.cpp" + PARENT_SCOPE) diff --git a/dScripts/AgPropguards.cpp b/dScripts/ai/PROPERTY/AgPropguards.cpp similarity index 100% rename from dScripts/AgPropguards.cpp rename to dScripts/ai/PROPERTY/AgPropguards.cpp diff --git a/dScripts/AgPropguards.h b/dScripts/ai/PROPERTY/AgPropguards.h similarity index 100% rename from dScripts/AgPropguards.h rename to dScripts/ai/PROPERTY/AgPropguards.h diff --git a/dScripts/ai/PROPERTY/CMakeLists.txt b/dScripts/ai/PROPERTY/CMakeLists.txt new file mode 100644 index 00000000..295137b4 --- /dev/null +++ b/dScripts/ai/PROPERTY/CMakeLists.txt @@ -0,0 +1,11 @@ +set(DSCRIPTS_SOURCES_AI_PROPERTY + "AgPropguards.cpp" + "PropertyFXDamage.cpp") + +add_subdirectory(AG) + +foreach(file ${DSCRIPTS_SOURCES_AI_PROPERTY_AG}) + set(DSCRIPTS_SOURCES_AI_PROPERTY ${DSCRIPTS_SOURCES_AI_PROPERTY} "AG/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_AI_PROPERTY ${DSCRIPTS_SOURCES_AI_PROPERTY} PARENT_SCOPE) diff --git a/dScripts/PropertyFXDamage.cpp b/dScripts/ai/PROPERTY/PropertyFXDamage.cpp similarity index 100% rename from dScripts/PropertyFXDamage.cpp rename to dScripts/ai/PROPERTY/PropertyFXDamage.cpp diff --git a/dScripts/PropertyFXDamage.h b/dScripts/ai/PROPERTY/PropertyFXDamage.h similarity index 100% rename from dScripts/PropertyFXDamage.h rename to dScripts/ai/PROPERTY/PropertyFXDamage.h diff --git a/dScripts/ai/RACING/CMakeLists.txt b/dScripts/ai/RACING/CMakeLists.txt new file mode 100644 index 00000000..0c1918de --- /dev/null +++ b/dScripts/ai/RACING/CMakeLists.txt @@ -0,0 +1,9 @@ +set(DSCRIPTS_SOURCES_AI_RACING) + +add_subdirectory(OBJECTS) + +foreach(file ${DSCRIPTS_SOURCES_AI_RACING_OBJECTS}) + set(DSCRIPTS_SOURCES_AI_RACING ${DSCRIPTS_SOURCES_AI_RACING} "OBJECTS/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_AI_RACING ${DSCRIPTS_SOURCES_AI_RACING} PARENT_SCOPE) diff --git a/dScripts/ai/RACING/OBJECTS/CMakeLists.txt b/dScripts/ai/RACING/OBJECTS/CMakeLists.txt new file mode 100644 index 00000000..4ef427d5 --- /dev/null +++ b/dScripts/ai/RACING/OBJECTS/CMakeLists.txt @@ -0,0 +1,6 @@ +set(DSCRIPTS_SOURCES_AI_RACING_OBJECTS + "RaceImagineCrateServer.cpp" + "RaceImaginePowerup.cpp" + "FvRaceSmashEggImagineServer.cpp" + "RaceSmashServer.cpp" + PARENT_SCOPE) diff --git a/dScripts/FvRaceSmashEggImagineServer.cpp b/dScripts/ai/RACING/OBJECTS/FvRaceSmashEggImagineServer.cpp similarity index 100% rename from dScripts/FvRaceSmashEggImagineServer.cpp rename to dScripts/ai/RACING/OBJECTS/FvRaceSmashEggImagineServer.cpp diff --git a/dScripts/FvRaceSmashEggImagineServer.h b/dScripts/ai/RACING/OBJECTS/FvRaceSmashEggImagineServer.h similarity index 100% rename from dScripts/FvRaceSmashEggImagineServer.h rename to dScripts/ai/RACING/OBJECTS/FvRaceSmashEggImagineServer.h diff --git a/dScripts/RaceImagineCrateServer.cpp b/dScripts/ai/RACING/OBJECTS/RaceImagineCrateServer.cpp similarity index 100% rename from dScripts/RaceImagineCrateServer.cpp rename to dScripts/ai/RACING/OBJECTS/RaceImagineCrateServer.cpp diff --git a/dScripts/RaceImagineCrateServer.h b/dScripts/ai/RACING/OBJECTS/RaceImagineCrateServer.h similarity index 100% rename from dScripts/RaceImagineCrateServer.h rename to dScripts/ai/RACING/OBJECTS/RaceImagineCrateServer.h diff --git a/dScripts/RaceImaginePowerup.cpp b/dScripts/ai/RACING/OBJECTS/RaceImaginePowerup.cpp similarity index 100% rename from dScripts/RaceImaginePowerup.cpp rename to dScripts/ai/RACING/OBJECTS/RaceImaginePowerup.cpp diff --git a/dScripts/RaceImaginePowerup.h b/dScripts/ai/RACING/OBJECTS/RaceImaginePowerup.h similarity index 100% rename from dScripts/RaceImaginePowerup.h rename to dScripts/ai/RACING/OBJECTS/RaceImaginePowerup.h diff --git a/dScripts/RaceSmashServer.cpp b/dScripts/ai/RACING/OBJECTS/RaceSmashServer.cpp similarity index 100% rename from dScripts/RaceSmashServer.cpp rename to dScripts/ai/RACING/OBJECTS/RaceSmashServer.cpp diff --git a/dScripts/RaceSmashServer.h b/dScripts/ai/RACING/OBJECTS/RaceSmashServer.h similarity index 100% rename from dScripts/RaceSmashServer.h rename to dScripts/ai/RACING/OBJECTS/RaceSmashServer.h diff --git a/dScripts/ai/SPEC/CMakeLists.txt b/dScripts/ai/SPEC/CMakeLists.txt new file mode 100644 index 00000000..c4c5b809 --- /dev/null +++ b/dScripts/ai/SPEC/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_AI_SPEC + "SpecialImaginePowerupSpawner.cpp" + PARENT_SCOPE) diff --git a/dScripts/SpecialImaginePowerupSpawner.cpp b/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.cpp similarity index 100% rename from dScripts/SpecialImaginePowerupSpawner.cpp rename to dScripts/ai/SPEC/SpecialImaginePowerupSpawner.cpp diff --git a/dScripts/SpecialImaginePowerupSpawner.h b/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.h similarity index 100% rename from dScripts/SpecialImaginePowerupSpawner.h rename to dScripts/ai/SPEC/SpecialImaginePowerupSpawner.h diff --git a/dScripts/AllCrateChicken.cpp b/dScripts/ai/WILD/AllCrateChicken.cpp similarity index 100% rename from dScripts/AllCrateChicken.cpp rename to dScripts/ai/WILD/AllCrateChicken.cpp diff --git a/dScripts/AllCrateChicken.h b/dScripts/ai/WILD/AllCrateChicken.h similarity index 100% rename from dScripts/AllCrateChicken.h rename to dScripts/ai/WILD/AllCrateChicken.h diff --git a/dScripts/ai/WILD/CMakeLists.txt b/dScripts/ai/WILD/CMakeLists.txt new file mode 100644 index 00000000..57470f72 --- /dev/null +++ b/dScripts/ai/WILD/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DSCRIPTS_SOURCES_AI_WILD + "AllCrateChicken.cpp" + "WildAmbients.cpp" + PARENT_SCOPE) diff --git a/dScripts/WildAmbients.cpp b/dScripts/ai/WILD/WildAmbients.cpp similarity index 100% rename from dScripts/WildAmbients.cpp rename to dScripts/ai/WILD/WildAmbients.cpp diff --git a/dScripts/WildAmbients.h b/dScripts/ai/WILD/WildAmbients.h similarity index 100% rename from dScripts/WildAmbients.h rename to dScripts/ai/WILD/WildAmbients.h diff --git a/dScripts/client/CMakeLists.txt b/dScripts/client/CMakeLists.txt new file mode 100644 index 00000000..c2777508 --- /dev/null +++ b/dScripts/client/CMakeLists.txt @@ -0,0 +1,9 @@ +set(DSCRIPTS_SOURCES_CLIENT) + +add_subdirectory(ai) + +foreach(file ${DSCRIPTS_SOURCES_CLIENT_AI}) + set(DSCRIPTS_SOURCES_CLIENT ${DSCRIPTS_SOURCES_CLIENT} "ai/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_CLIENT ${DSCRIPTS_SOURCES_CLIENT} PARENT_SCOPE) diff --git a/dScripts/client/ai/CMakeLists.txt b/dScripts/client/ai/CMakeLists.txt new file mode 100644 index 00000000..c1358c57 --- /dev/null +++ b/dScripts/client/ai/CMakeLists.txt @@ -0,0 +1,9 @@ +set(DSCRIPTS_SOURCES_CLIENT_AI) + +add_subdirectory(PR) + +foreach(file ${DSCRIPTS_SOURCES_CLIENT_AI_PR}) + set(DSCRIPTS_SOURCES_CLIENT_AI ${DSCRIPTS_SOURCES_CLIENT_AI} "PR/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_CLIENT_AI ${DSCRIPTS_SOURCES_CLIENT_AI} PARENT_SCOPE) diff --git a/dScripts/client/ai/PR/CMakeLists.txt b/dScripts/client/ai/PR/CMakeLists.txt new file mode 100644 index 00000000..ef7d5d6a --- /dev/null +++ b/dScripts/client/ai/PR/CMakeLists.txt @@ -0,0 +1,4 @@ +set(DSCRIPTS_SOURCES_CLIENT_AI_PR + "PrWhistle.cpp" + "CrabServer.cpp" + PARENT_SCOPE) diff --git a/dScripts/CrabServer.cpp b/dScripts/client/ai/PR/CrabServer.cpp similarity index 100% rename from dScripts/CrabServer.cpp rename to dScripts/client/ai/PR/CrabServer.cpp diff --git a/dScripts/CrabServer.h b/dScripts/client/ai/PR/CrabServer.h similarity index 100% rename from dScripts/CrabServer.h rename to dScripts/client/ai/PR/CrabServer.h diff --git a/dScripts/PrWhistle.cpp b/dScripts/client/ai/PR/PrWhistle.cpp similarity index 100% rename from dScripts/PrWhistle.cpp rename to dScripts/client/ai/PR/PrWhistle.cpp diff --git a/dScripts/PrWhistle.h b/dScripts/client/ai/PR/PrWhistle.h similarity index 100% rename from dScripts/PrWhistle.h rename to dScripts/client/ai/PR/PrWhistle.h diff --git a/dScripts/zone/AG/CMakeLists.txt b/dScripts/zone/AG/CMakeLists.txt new file mode 100644 index 00000000..14426a46 --- /dev/null +++ b/dScripts/zone/AG/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_ZONE_AG + "ZoneAgSurvival.cpp" + PARENT_SCOPE) diff --git a/dScripts/ZoneAgSurvival.cpp b/dScripts/zone/AG/ZoneAgSurvival.cpp similarity index 100% rename from dScripts/ZoneAgSurvival.cpp rename to dScripts/zone/AG/ZoneAgSurvival.cpp diff --git a/dScripts/ZoneAgSurvival.h b/dScripts/zone/AG/ZoneAgSurvival.h similarity index 100% rename from dScripts/ZoneAgSurvival.h rename to dScripts/zone/AG/ZoneAgSurvival.h diff --git a/dScripts/zone/CMakeLists.txt b/dScripts/zone/CMakeLists.txt new file mode 100644 index 00000000..5d800031 --- /dev/null +++ b/dScripts/zone/CMakeLists.txt @@ -0,0 +1,21 @@ +set(DSCRIPTS_SOURCES_ZONE) + +add_subdirectory(AG) + +foreach(file ${DSCRIPTS_SOURCES_ZONE_AG}) + set(DSCRIPTS_SOURCES_ZONE ${DSCRIPTS_SOURCES_ZONE} "AG/${file}") +endforeach() + +add_subdirectory(LUPs) + +foreach(file ${DSCRIPTS_SOURCES_ZONE_LUPS}) + set(DSCRIPTS_SOURCES_ZONE ${DSCRIPTS_SOURCES_ZONE} "LUPs/${file}") +endforeach() + +add_subdirectory(PROPERTY) + +foreach(file ${DSCRIPTS_SOURCES_ZONE_PROPERTY}) + set(DSCRIPTS_SOURCES_ZONE ${DSCRIPTS_SOURCES_ZONE} "PROPERTY/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_ZONE ${DSCRIPTS_SOURCES_ZONE} PARENT_SCOPE) diff --git a/dScripts/zone/LUPs/CMakeLists.txt b/dScripts/zone/LUPs/CMakeLists.txt new file mode 100644 index 00000000..b3b55ad6 --- /dev/null +++ b/dScripts/zone/LUPs/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_ZONE_LUPS + "WblGenericZone.cpp" + PARENT_SCOPE) diff --git a/dScripts/WblGenericZone.cpp b/dScripts/zone/LUPs/WblGenericZone.cpp similarity index 100% rename from dScripts/WblGenericZone.cpp rename to dScripts/zone/LUPs/WblGenericZone.cpp diff --git a/dScripts/WblGenericZone.h b/dScripts/zone/LUPs/WblGenericZone.h similarity index 100% rename from dScripts/WblGenericZone.h rename to dScripts/zone/LUPs/WblGenericZone.h diff --git a/dScripts/zone/PROPERTY/CMakeLists.txt b/dScripts/zone/PROPERTY/CMakeLists.txt new file mode 100644 index 00000000..b0588181 --- /dev/null +++ b/dScripts/zone/PROPERTY/CMakeLists.txt @@ -0,0 +1,21 @@ +set(DSCRIPTS_SOURCES_ZONE_PROPERTY) + +add_subdirectory(FV) + +foreach(file ${DSCRIPTS_SOURCES_ZONE_PROPERTY_FV}) + set(DSCRIPTS_SOURCES_ZONE_PROPERTY ${DSCRIPTS_SOURCES_ZONE_PROPERTY} "FV/${file}") +endforeach() + +add_subdirectory(GF) + +foreach(file ${DSCRIPTS_SOURCES_ZONE_PROPERTY_GF}) + set(DSCRIPTS_SOURCES_ZONE_PROPERTY ${DSCRIPTS_SOURCES_ZONE_PROPERTY} "GF/${file}") +endforeach() + +add_subdirectory(NS) + +foreach(file ${DSCRIPTS_SOURCES_ZONE_PROPERTY_NS}) + set(DSCRIPTS_SOURCES_ZONE_PROPERTY ${DSCRIPTS_SOURCES_ZONE_PROPERTY} "NS/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_ZONE_PROPERTY ${DSCRIPTS_SOURCES_ZONE_PROPERTY} PARENT_SCOPE) diff --git a/dScripts/zone/PROPERTY/FV/CMakeLists.txt b/dScripts/zone/PROPERTY/FV/CMakeLists.txt new file mode 100644 index 00000000..60da048d --- /dev/null +++ b/dScripts/zone/PROPERTY/FV/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_ZONE_PROPERTY_FV + "ZoneFvProperty.cpp" + PARENT_SCOPE) diff --git a/dScripts/ZoneFvProperty.cpp b/dScripts/zone/PROPERTY/FV/ZoneFvProperty.cpp similarity index 100% rename from dScripts/ZoneFvProperty.cpp rename to dScripts/zone/PROPERTY/FV/ZoneFvProperty.cpp diff --git a/dScripts/ZoneFvProperty.h b/dScripts/zone/PROPERTY/FV/ZoneFvProperty.h similarity index 100% rename from dScripts/ZoneFvProperty.h rename to dScripts/zone/PROPERTY/FV/ZoneFvProperty.h diff --git a/dScripts/zone/PROPERTY/GF/CMakeLists.txt b/dScripts/zone/PROPERTY/GF/CMakeLists.txt new file mode 100644 index 00000000..fed6033b --- /dev/null +++ b/dScripts/zone/PROPERTY/GF/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_ZONE_PROPERTY_GF + "ZoneGfProperty.cpp" + PARENT_SCOPE) diff --git a/dScripts/ZoneGfProperty.cpp b/dScripts/zone/PROPERTY/GF/ZoneGfProperty.cpp similarity index 100% rename from dScripts/ZoneGfProperty.cpp rename to dScripts/zone/PROPERTY/GF/ZoneGfProperty.cpp diff --git a/dScripts/ZoneGfProperty.h b/dScripts/zone/PROPERTY/GF/ZoneGfProperty.h similarity index 100% rename from dScripts/ZoneGfProperty.h rename to dScripts/zone/PROPERTY/GF/ZoneGfProperty.h diff --git a/dScripts/zone/PROPERTY/NS/CMakeLists.txt b/dScripts/zone/PROPERTY/NS/CMakeLists.txt new file mode 100644 index 00000000..0e1f392c --- /dev/null +++ b/dScripts/zone/PROPERTY/NS/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_ZONE_PROPERTY_NS + "ZoneNsProperty.cpp" + PARENT_SCOPE) diff --git a/dScripts/ZoneNsProperty.cpp b/dScripts/zone/PROPERTY/NS/ZoneNsProperty.cpp similarity index 100% rename from dScripts/ZoneNsProperty.cpp rename to dScripts/zone/PROPERTY/NS/ZoneNsProperty.cpp diff --git a/dScripts/ZoneNsProperty.h b/dScripts/zone/PROPERTY/NS/ZoneNsProperty.h similarity index 100% rename from dScripts/ZoneNsProperty.h rename to dScripts/zone/PROPERTY/NS/ZoneNsProperty.h From 8880486c8bb34a65d2fab6a343827b44c64cc730 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 4 Nov 2022 12:28:19 -0700 Subject: [PATCH 119/322] Fix chat message reads (#817) * Fix chat message reads * Fix teams --- dChatServer/ChatPacketHandler.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index 0f7f6919..119083ee 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -394,7 +394,7 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) { uint8_t channel = 0; inStream.Read(channel); - std::string message = PacketUtils::ReadString(0x66, packet, true); + std::string message = PacketUtils::ReadString(0x66, packet, true, 512); Game::logger->Log("ChatPacketHandler", "Got a message from (%s) [%d]: %s", senderName.c_str(), channel, message.c_str()); @@ -436,7 +436,7 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) { void ChatPacketHandler::HandlePrivateChatMessage(Packet* packet) { LWOOBJID senderID = PacketUtils::ReadPacketS64(0x08, packet); std::string receiverName = PacketUtils::ReadString(0x66, packet, true); - std::string message = PacketUtils::ReadString(0xAA, packet, true); + std::string message = PacketUtils::ReadString(0xAA, packet, true, 512); //Get the bois: auto goonA = playerContainer.GetPlayerData(senderID); From 162f84e2857c1fa6b490dde8b5e3acd96d89a985 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 4 Nov 2022 19:45:04 -0500 Subject: [PATCH 120/322] simplify path fixing for packed vs unpacked (#816) fix slashes for hasfile for unpacked client checking --- dCommon/dClient/AssetManager.cpp | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/dCommon/dClient/AssetManager.cpp b/dCommon/dClient/AssetManager.cpp index ba928340..2b6f84e3 100644 --- a/dCommon/dClient/AssetManager.cpp +++ b/dCommon/dClient/AssetManager.cpp @@ -66,17 +66,15 @@ eAssetBundleType AssetManager::GetAssetBundleType() { bool AssetManager::HasFile(const char* name) { auto fixedName = std::string(name); std::transform(fixedName.begin(), fixedName.end(), fixedName.begin(), [](uint8_t c) { return std::tolower(c); }); + + + std::replace(fixedName.begin(), fixedName.end(), '\\', '/'); + if (std::filesystem::exists(m_ResPath / fixedName)) return true; + + if (this->m_AssetBundleType == eAssetBundleType::Unpacked) return false; + std::replace(fixedName.begin(), fixedName.end(), '/', '\\'); - - auto realPathName = fixedName; - - if (fixedName.rfind("client\\res\\", 0) != 0) { - fixedName = "client\\res\\" + fixedName; - } - - if (std::filesystem::exists(m_ResPath / realPathName)) { - return true; - } + if (fixedName.rfind("client\\res\\", 0) != 0) fixedName = "client\\res\\" + fixedName; uint32_t crc = crc32b(0xFFFFFFFF, (uint8_t*)fixedName.c_str(), fixedName.size()); crc = crc32b(crc, (Bytef*)"\0\0\0\0", 4); From 1d5c71eb9b839048be0380d265eb2e045c879166 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 5 Nov 2022 17:09:26 -0700 Subject: [PATCH 121/322] Fix Pet Taming causing seg fault (#818) * Fix Pet Taming * Fix Pet Taming * fix pet taming path loading just make it go to build file since the asset managet handles intermediate steps there is never res in the path in the live db, so no need to check * special case BrickModels to uppercase if unpacked remove redundent variable Co-authored-by: Aaron Kimbrell <aronwk.aaron@gmail.com> --- dCommon/dClient/AssetManager.cpp | 14 +++++++++----- dGame/dComponents/PetComponent.cpp | 16 +--------------- dGame/dUtilities/BrickDatabase.cpp | 2 +- 3 files changed, 11 insertions(+), 21 deletions(-) diff --git a/dCommon/dClient/AssetManager.cpp b/dCommon/dClient/AssetManager.cpp index 2b6f84e3..0cb2db31 100644 --- a/dCommon/dClient/AssetManager.cpp +++ b/dCommon/dClient/AssetManager.cpp @@ -67,6 +67,8 @@ bool AssetManager::HasFile(const char* name) { auto fixedName = std::string(name); std::transform(fixedName.begin(), fixedName.end(), fixedName.begin(), [](uint8_t c) { return std::tolower(c); }); + // Special case for unpacked client have BrickModels in upper case + if (this->m_AssetBundleType == eAssetBundleType::Unpacked) GeneralUtils::ReplaceInString(fixedName, "brickmodels", "BrickModels"); std::replace(fixedName.begin(), fixedName.end(), '\\', '/'); if (std::filesystem::exists(m_ResPath / fixedName)) return true; @@ -92,17 +94,19 @@ bool AssetManager::GetFile(const char* name, char** data, uint32_t* len) { auto fixedName = std::string(name); std::transform(fixedName.begin(), fixedName.end(), fixedName.begin(), [](uint8_t c) { return std::tolower(c); }); std::replace(fixedName.begin(), fixedName.end(), '\\', '/'); // On the off chance someone has the wrong slashes, force forward slashes - auto realPathName = fixedName; - if (std::filesystem::exists(m_ResPath / realPathName)) { + // Special case for unpacked client have BrickModels in upper case + if (this->m_AssetBundleType == eAssetBundleType::Unpacked) GeneralUtils::ReplaceInString(fixedName, "brickmodels", "BrickModels"); + + if (std::filesystem::exists(m_ResPath / fixedName)) { FILE* file; #ifdef _WIN32 - fopen_s(&file, (m_ResPath / realPathName).string().c_str(), "rb"); + fopen_s(&file, (m_ResPath / fixedName).string().c_str(), "rb"); #elif __APPLE__ // macOS has 64bit file IO by default - file = fopen((m_ResPath / realPathName).string().c_str(), "rb"); + file = fopen((m_ResPath / fixedName).string().c_str(), "rb"); #else - file = fopen64((m_ResPath / realPathName).string().c_str(), "rb"); + file = fopen64((m_ResPath / fixedName).string().c_str(), "rb"); #endif fseek(file, 0, SEEK_END); *len = ftell(file); diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 8863f9be..0b136a5c 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -194,21 +194,7 @@ void PetComponent::OnUse(Entity* originator) { return; } - auto lxfAsset = std::string(result.getStringField(0)); - - std::vector<std::string> lxfAssetSplit = GeneralUtils::SplitString(lxfAsset, '\\'); - - lxfAssetSplit.erase(lxfAssetSplit.begin()); - - buildFile = "res/BrickModels"; - - for (auto part : lxfAssetSplit) { - std::transform(part.begin(), part.end(), part.begin(), [](unsigned char c) { - return std::tolower(c); - }); - - buildFile += "/" + part; - } + buildFile = std::string(result.getStringField(0)); PetPuzzleData data; data.buildFile = buildFile; diff --git a/dGame/dUtilities/BrickDatabase.cpp b/dGame/dUtilities/BrickDatabase.cpp index 4e873278..c36a1097 100644 --- a/dGame/dUtilities/BrickDatabase.cpp +++ b/dGame/dUtilities/BrickDatabase.cpp @@ -18,7 +18,7 @@ std::vector<Brick>& BrickDatabase::GetBricks(const std::string& lxfmlPath) { return cached->second; } - AssetMemoryBuffer buffer = Game::assetManager->GetFileAsBuffer(("client/" + lxfmlPath).c_str()); + AssetMemoryBuffer buffer = Game::assetManager->GetFileAsBuffer((lxfmlPath).c_str()); std::istream file(&buffer); if (!file.good()) { return emptyCache; From 9c58ea5c415bf64d7972fc5408d8ef4e554185e9 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 5 Nov 2022 19:09:39 -0500 Subject: [PATCH 122/322] add 1261 to the disable landing animation switch case (#819) --- dGame/dComponents/CharacterComponent.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index d425c066..424be0ac 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -47,6 +47,7 @@ bool CharacterComponent::LandingAnimDisabled(int zoneID) { case 1202: case 1203: case 1204: + case 1261: case 1301: case 1302: case 1303: From 1464762bcd4dcfe8437872d4d0381813700fe29f Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 7 Nov 2022 00:12:35 -0800 Subject: [PATCH 123/322] Implement GTest and change windows output path Implement GTest as a testing infrastructure. Make windows output binaries to the build folder instead of the release type folder (potentially issue further down the line) Add a simple unit test for DestroyableComponent --- .gitignore | 2 +- CMakeLists.txt | 20 +- CMakePresets.json | 228 ++++++------- CMakeVariables.txt | 2 + README.md | 4 + dAuthServer/CMakeLists.txt | 4 +- dChatServer/CMakeLists.txt | 16 +- dGame/dComponents/DestroyableComponent.cpp | 15 +- dGame/dComponents/DestroyableComponent.h | 10 +- dMasterServer/CMakeLists.txt | 16 +- dNet/dServer.cpp | 11 +- dNet/dServer.h | 14 +- dWorldServer/CMakeLists.txt | 15 +- tests/CMakeLists.txt | 45 +-- tests/CommonCxxTests.cpp | 0 tests/CommonCxxTests.h | 4 - tests/TestEncoding.cpp | 52 --- .../AMFDeserializeTests.cpp | 129 ++++---- tests/dCommonTests/CMakeLists.txt | 19 ++ .../TestBitStreams/AMFBitStreamTest.bin | Bin .../AMFBitStreamUnimplementedTest.bin | 0 .../TestBitStreams/CMakeLists.txt | 11 + tests/dCommonTests/TestEncoding.cpp | 68 ++++ tests/{ => dCommonTests}/TestLDFFormat.cpp | 10 +- tests/{ => dCommonTests}/TestNiPoint3.cpp | 11 +- tests/dGameTests/CMakeLists.txt | 14 + tests/dGameTests/GameDependencies.cpp | 15 + tests/dGameTests/GameDependencies.h | 43 +++ .../dComponentsTests/CMakeLists.txt | 10 + .../DestroyableComponentTests.cpp | 300 ++++++++++++++++++ 30 files changed, 763 insertions(+), 325 deletions(-) delete mode 100644 tests/CommonCxxTests.cpp delete mode 100644 tests/CommonCxxTests.h delete mode 100644 tests/TestEncoding.cpp rename tests/{ => dCommonTests}/AMFDeserializeTests.cpp (83%) create mode 100644 tests/dCommonTests/CMakeLists.txt rename tests/{ => dCommonTests}/TestBitStreams/AMFBitStreamTest.bin (100%) rename tests/{ => dCommonTests}/TestBitStreams/AMFBitStreamUnimplementedTest.bin (100%) create mode 100644 tests/dCommonTests/TestBitStreams/CMakeLists.txt create mode 100644 tests/dCommonTests/TestEncoding.cpp rename tests/{ => dCommonTests}/TestLDFFormat.cpp (69%) rename tests/{ => dCommonTests}/TestNiPoint3.cpp (59%) create mode 100644 tests/dGameTests/CMakeLists.txt create mode 100644 tests/dGameTests/GameDependencies.cpp create mode 100644 tests/dGameTests/GameDependencies.h create mode 100644 tests/dGameTests/dComponentsTests/CMakeLists.txt create mode 100644 tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp diff --git a/.gitignore b/.gitignore index 3777608d..e093ba4b 100644 --- a/.gitignore +++ b/.gitignore @@ -121,4 +121,4 @@ docker/__pycache__ docker-compose.override.yml -!/tests/TestBitStreams/*.bin +!*Test.bin diff --git a/CMakeLists.txt b/CMakeLists.txt index 34a6cd27..7dfef867 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -76,6 +76,15 @@ endif() # Our output dir set(CMAKE_BINARY_DIR ${PROJECT_BINARY_DIR}) + +# TODO make this not have to override the build type directories +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR}) +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR}) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR}) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}) +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) @@ -239,6 +248,11 @@ set(INCLUDED_DIRECTORIES "thirdparty/recastnavigation" "thirdparty/SQLite" "thirdparty/cpplinq" + + "tests" + "tests/dCommonTests" + "tests/dGameTests" + "tests/dGameTests/dComponentsTests" ) # Add system specfic includes for Apple, Windows and Other Unix OS' (including Linux) @@ -320,8 +334,6 @@ if (UNIX) endif() endif() -add_subdirectory(tests) - # Include all of our binary directories add_subdirectory(dWorldServer) add_subdirectory(dAuthServer) @@ -354,3 +366,7 @@ target_precompile_headers( tinyxml2 PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:${PROJECT_SOURCE_DIR}/thirdparty/tinyxml2/tinyxml2.h>" ) + +if (${__enable_testing__} MATCHES "1") + add_subdirectory(tests) +endif() diff --git a/CMakePresets.json b/CMakePresets.json index badb161d..15eb729e 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -1,131 +1,131 @@ { - "version": 3, - "cmakeMinimumRequired": { - "major": 3, - "minor": 14, - "patch": 0 - }, - "configurePresets": [ - { - "name": "default", - "displayName": "Default configure step", - "description": "Use 'build' dir and Unix makefiles", - "binaryDir": "${sourceDir}/build", - "generator": "Unix Makefiles" + "version": 3, + "cmakeMinimumRequired": { + "major": 3, + "minor": 14, + "patch": 0 }, - { - "name": "ci-ubuntu-20.04", - "displayName": "CI configure step for Ubuntu", - "description": "Same as default, Used in GitHub actions workflow", - "inherits": "default" - }, - { - "name": "ci-macos-11", - "displayName": "CI configure step for MacOS", - "description": "Same as default, Used in GitHub actions workflow", - "inherits": "default", - "cacheVariables": { - "OPENSSL_ROOT_DIR": "/usr/local/Cellar/openssl@3/3.0.5/" - } - }, - { - "name": "ci-windows-2022", - "displayName": "CI configure step for Windows", - "description": "Set architecture to 64-bit (b/c RakNet)", - "inherits": "default", - "generator": "Visual Studio 17 2022", - "architecture": { - "value": "x64" + "configurePresets": [ + { + "name": "default", + "displayName": "Default configure step", + "description": "Use 'build' dir and Unix makefiles", + "binaryDir": "${sourceDir}/build", + "generator": "Unix Makefiles" }, - "cacheVariables": { - "CMAKE_BUILD_TYPE": "RelWithDebInfo" + { + "name": "ci-ubuntu-20.04", + "displayName": "CI configure step for Ubuntu", + "description": "Same as default, Used in GitHub actions workflow", + "inherits": "default" + }, + { + "name": "ci-macos-11", + "displayName": "CI configure step for MacOS", + "description": "Same as default, Used in GitHub actions workflow", + "inherits": "default", + "cacheVariables": { + "OPENSSL_ROOT_DIR": "/usr/local/Cellar/openssl@3/3.0.5/" + } + }, + { + "name": "ci-windows-2022", + "displayName": "CI configure step for Windows", + "description": "Set architecture to 64-bit (b/c RakNet)", + "inherits": "default", + "generator": "Visual Studio 17 2022", + "architecture": { + "value": "x64" + }, + "cacheVariables": { + "CMAKE_BUILD_TYPE": "RelWithDebInfo" + } + }, + { + "name": "windows-default", + "inherits": "ci-windows-2022", + "displayName": "Windows only Configure Settings", + "description": "Sets build and install directories", + "generator": "Ninja", + "architecture": { + "value": "x64", + "strategy": "external" + } } - }, - { - "name": "windows-default", - "inherits": "ci-windows-2022", - "displayName": "Windows only Configure Settings", - "description": "Sets build and install directories", - "generator": "Ninja", - "architecture": { - "value": "x64", - "strategy": "external" - } - } - ], - "buildPresets": [ - { - "name": "default", - "configurePreset": "default", - "displayName": "Default Build", - "description": "Default Build", - "jobs": 2 - }, - { - "name": "ci-windows-2022", - "configurePreset": "ci-windows-2022", - "displayName": "Windows CI Build", - "description": "This preset is used by the CI build on windows", - "configuration": "RelWithDebInfo", - "jobs": 2 - }, - { - "name": "ci-ubuntu-20.04", - "configurePreset": "ci-ubuntu-20.04", - "displayName": "Linux CI Build", - "description": "This preset is used by the CI build on linux", - "jobs": 2 - }, - { - "name": "ci-macos-11", - "configurePreset": "ci-macos-11", - "displayName": "MacOS CI Build", - "description": "This preset is used by the CI build on MacOS", - "jobs": 2 - } - ], - "testPresets": [ - { - "name": "ci-ubuntu-20.04", - "configurePreset": "ci-ubuntu-20.04", - "displayName": "CI Tests on Linux", - "description": "Runs all tests on a linux configuration", - "execution": { + ], + "buildPresets": [ + { + "name": "default", + "configurePreset": "default", + "displayName": "Default Build", + "description": "Default Build", "jobs": 2 }, - "output": { - "outputOnFailure": true - } - }, - { - "name": "ci-macos-11", - "configurePreset": "ci-macos-11", - "displayName": "CI Tests on MacOS", - "description": "Runs all tests on a Mac configuration", - "execution": { + { + "name": "ci-windows-2022", + "configurePreset": "ci-windows-2022", + "displayName": "Windows CI Build", + "description": "This preset is used by the CI build on windows", + "configuration": "RelWithDebInfo", "jobs": 2 }, - "output": { - "outputOnFailure": true + { + "name": "ci-ubuntu-20.04", + "configurePreset": "ci-ubuntu-20.04", + "displayName": "Linux CI Build", + "description": "This preset is used by the CI build on linux", + "jobs": 2 + }, + { + "name": "ci-macos-11", + "configurePreset": "ci-macos-11", + "displayName": "MacOS CI Build", + "description": "This preset is used by the CI build on MacOS", + "jobs": 2 } - }, - { - "name": "ci-windows-2022", - "configurePreset": "ci-windows-2022", - "displayName": "CI Tests on windows", - "description": "Runs all tests on a windows configuration", - "configuration": "RelWithDebInfo", + ], + "testPresets": [ + { + "name": "ci-ubuntu-20.04", + "configurePreset": "ci-ubuntu-20.04", + "displayName": "CI Tests on Linux", + "description": "Runs all tests on a linux configuration", "execution": { "jobs": 2 }, + "output": { + "outputOnFailure": true + } + }, + { + "name": "ci-macos-11", + "configurePreset": "ci-macos-11", + "displayName": "CI Tests on MacOS", + "description": "Runs all tests on a Mac configuration", + "execution": { + "jobs": 2 + }, + "output": { + "outputOnFailure": true + } + }, + { + "name": "ci-windows-2022", + "configurePreset": "ci-windows-2022", + "displayName": "CI Tests on windows", + "description": "Runs all tests on a windows configuration", + "configuration": "RelWithDebInfo", + "execution": { + "jobs": 2 + }, + "output": { + "outputOnFailure": true + }, "filter": { "exclude": { "name": "((example)|(minigzip))+" } - }, - "output": { - "outputOnFailure": true + } } - } - ] -} + ] + } diff --git a/CMakeVariables.txt b/CMakeVariables.txt index e68e826e..94e9cd20 100644 --- a/CMakeVariables.txt +++ b/CMakeVariables.txt @@ -18,3 +18,5 @@ __dynamic=1 # Set __compile_backtrace__ to 1 to compile the backtrace library instead of using system libraries. __maria_db_connector_compile_jobs__=1 # Set to the number of jobs (make -j equivalent) to compile the mariadbconn files with. +__enable_testing__=1 +# When set to 1 and uncommented, compiling and linking testing folders and libraries will be done. diff --git a/README.md b/README.md index 8f9eaf8d..e588d341 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,10 @@ This was done make sure that older and incomplete clients wouldn't produce false If you're using a DLU client you'll have to go into the "CMakeVariables.txt" file and change the NET_VERSION variable to 171023 to match the modified client's version number. +### Enabling testing +While it is highly recommended to enable testing, if you would like to save compilation time, you'll want to comment out the enable_testing variable in CMakeVariables.txt. +It is recommended that after building and if testing is enabled, to run `ctest` and make sure all the tests pass. + ### Using Docker Refer to [Docker.md](/Docker.md). diff --git a/dAuthServer/CMakeLists.txt b/dAuthServer/CMakeLists.txt index 353f2a54..00fa6e7a 100644 --- a/dAuthServer/CMakeLists.txt +++ b/dAuthServer/CMakeLists.txt @@ -1,4 +1,2 @@ -set(DAUTHSERVER_SOURCES "AuthServer.cpp") - -add_executable(AuthServer ${DAUTHSERVER_SOURCES}) +add_executable(AuthServer "AuthServer.cpp") target_link_libraries(AuthServer ${COMMON_LIBRARIES}) diff --git a/dChatServer/CMakeLists.txt b/dChatServer/CMakeLists.txt index 948593fb..9a47803d 100644 --- a/dChatServer/CMakeLists.txt +++ b/dChatServer/CMakeLists.txt @@ -1,6 +1,10 @@ -set(DCHATSERVER_SOURCES "ChatPacketHandler.cpp" - "ChatServer.cpp" - "PlayerContainer.cpp") - -add_executable(ChatServer ${DCHATSERVER_SOURCES}) -target_link_libraries(ChatServer ${COMMON_LIBRARIES} dChatFilter) +set(DCHATSERVER_SOURCES + "ChatPacketHandler.cpp" + "PlayerContainer.cpp" +) + +add_executable(ChatServer "ChatServer.cpp") +add_library(dChatServer ${DCHATSERVER_SOURCES}) + +target_link_libraries(dChatServer ${COMMON_LIBRARIES} dChatFilter) +target_link_libraries(ChatServer ${COMMON_LIBRARIES} dChatFilter dChatServer) diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 8b9ae42d..3cf206da 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -138,25 +138,17 @@ void DestroyableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIn if (m_IsSmashable) { outBitStream->Write(m_HasBricks); - - if (m_ExplodeFactor != 1.0f) { - outBitStream->Write1(); - outBitStream->Write(m_ExplodeFactor); - } else { - outBitStream->Write0(); - } + outBitStream->Write(m_ExplodeFactor != 1.0f); + if (m_ExplodeFactor != 1.0f) outBitStream->Write(m_ExplodeFactor); } } - m_DirtyHealth = false; } + outBitStream->Write(m_DirtyThreatList || bIsInitialUpdate); if (m_DirtyThreatList || bIsInitialUpdate) { - outBitStream->Write1(); outBitStream->Write(m_HasThreats); m_DirtyThreatList = false; - } else { - outBitStream->Write0(); } } @@ -438,7 +430,6 @@ void DestroyableComponent::AddEnemyFaction(int32_t factionID) { void DestroyableComponent::SetIsSmashable(bool value) { m_DirtyHealth = true; m_IsSmashable = value; - //m_HasBricks = value; } void DestroyableComponent::SetAttacksToBlock(const uint32_t value) { diff --git a/dGame/dComponents/DestroyableComponent.h b/dGame/dComponents/DestroyableComponent.h index a403717b..b8e81b33 100644 --- a/dGame/dComponents/DestroyableComponent.h +++ b/dGame/dComponents/DestroyableComponent.h @@ -239,7 +239,7 @@ public: * Sets the multiplier for the explosion that's visible when the bricks fly out when this entity is smashed * @param value the multiplier for the explosion that's visible when the bricks fly out when this entity is smashed */ - void SetExplodeFactor(float value); + void SetExplodeFactor(float value) { m_ExplodeFactor = value; }; /** * Returns the current multiplier for explosions @@ -414,6 +414,14 @@ public: */ void AddOnHitCallback(const std::function<void(Entity*)>& callback); + /** + * Pushes a faction back to the list of factions. + * @param value Faction to add to list. + * + * This method should only be used for testing. Use AddFaction(int32_t, bool) for adding a faction properly. + */ + void AddFactionNoLookup(int32_t faction) { m_FactionIDs.push_back(faction); }; + private: /** * Whether or not the health should be serialized diff --git a/dMasterServer/CMakeLists.txt b/dMasterServer/CMakeLists.txt index 08fc63db..2161681f 100644 --- a/dMasterServer/CMakeLists.txt +++ b/dMasterServer/CMakeLists.txt @@ -1,9 +1,13 @@ -set(DMASTERSERVER_SOURCES "InstanceManager.cpp" - "MasterServer.cpp" - "ObjectIDManager.cpp") - -add_executable(MasterServer ${DMASTERSERVER_SOURCES}) -target_link_libraries(MasterServer ${COMMON_LIBRARIES}) +set(DMASTERSERVER_SOURCES + "InstanceManager.cpp" + "ObjectIDManager.cpp" +) + +add_library(dMasterServer ${DMASTERSERVER_SOURCES}) +add_executable(MasterServer "MasterServer.cpp") + +target_link_libraries(dMasterServer ${COMMON_LIBRARIES}) +target_link_libraries(MasterServer ${COMMON_LIBRARIES} dMasterServer) if(WIN32) add_dependencies(MasterServer WorldServer AuthServer ChatServer) diff --git a/dNet/dServer.cpp b/dNet/dServer.cpp index 4c032f33..c46b156c 100644 --- a/dNet/dServer.cpp +++ b/dNet/dServer.cpp @@ -50,7 +50,6 @@ dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnect mNetIDManager = nullptr; mReplicaManager = nullptr; mServerType = serverType; - //Attempt to start our server here: mIsOkay = Startup(); @@ -193,7 +192,10 @@ bool dServer::Startup() { } void dServer::Shutdown() { - mPeer->Shutdown(1000); + if (mPeer) { + mPeer->Shutdown(1000); + RakNetworkFactory::DestroyRakPeerInterface(mPeer); + } if (mNetIDManager) { delete mNetIDManager; @@ -205,10 +207,9 @@ void dServer::Shutdown() { mReplicaManager = nullptr; } - //RakNetworkFactory::DestroyRakPeerInterface(mPeer); //Not needed, we already called Shutdown ourselves. - if (mServerType != ServerType::Master) { + if (mServerType != ServerType::Master && mMasterPeer) { mMasterPeer->Shutdown(1000); - //RakNetworkFactory::DestroyRakPeerInterface(mMasterPeer); + RakNetworkFactory::DestroyRakPeerInterface(mMasterPeer); } } diff --git a/dNet/dServer.h b/dNet/dServer.h index bd052f86..264932ee 100644 --- a/dNet/dServer.h +++ b/dNet/dServer.h @@ -15,6 +15,8 @@ enum class ServerType : uint32_t { class dServer { public: + // Default constructor should only used for testing! + dServer() {}; dServer(const std::string& ip, int port, int instanceID, int maxConnections, bool isInternal, bool useEncryption, dLogger* logger, const std::string masterIP, int masterPort, ServerType serverType, unsigned int zoneID = 0); ~dServer(); @@ -22,7 +24,7 @@ public: Packet* Receive(); void DeallocatePacket(Packet* packet); void DeallocateMasterPacket(Packet* packet); - void Send(RakNet::BitStream* bitStream, const SystemAddress& sysAddr, bool broadcast); + virtual void Send(RakNet::BitStream* bitStream, const SystemAddress& sysAddr, bool broadcast); void SendToMaster(RakNet::BitStream* bitStream); void Disconnect(const SystemAddress& sysAddr, uint32_t disconNotifyID); @@ -55,10 +57,10 @@ private: bool ConnectToMaster(); private: - dLogger* mLogger; - RakPeerInterface* mPeer; - ReplicaManager* mReplicaManager; - NetworkIDManager* mNetIDManager; + dLogger* mLogger = nullptr; + RakPeerInterface* mPeer = nullptr; + ReplicaManager* mReplicaManager = nullptr; + NetworkIDManager* mNetIDManager = nullptr; SocketDescriptor mSocketDescriptor; std::string mIP; int mPort; @@ -71,7 +73,7 @@ private: bool mMasterConnectionActive; ServerType mServerType; - RakPeerInterface* mMasterPeer; + RakPeerInterface* mMasterPeer = nullptr; SocketDescriptor mMasterSocketDescriptor; SystemAddress mMasterSystemAddress; std::string mMasterIP; diff --git a/dWorldServer/CMakeLists.txt b/dWorldServer/CMakeLists.txt index fcf29838..c616da87 100644 --- a/dWorldServer/CMakeLists.txt +++ b/dWorldServer/CMakeLists.txt @@ -1,6 +1,11 @@ -set(DWORLDSERVER_SOURCES "ObjectIDManager.cpp" - "PerformanceManager.cpp" - "WorldServer.cpp") +set(DWORLDSERVER_SOURCES + "ObjectIDManager.cpp" + "PerformanceManager.cpp" +) + +add_library(dWorldServer ${DWORLDSERVER_SOURCES}) +add_executable(WorldServer "WorldServer.cpp") + +target_link_libraries(dWorldServer ${COMMON_LIBRARIES}) +target_link_libraries(WorldServer ${COMMON_LIBRARIES} dChatFilter dGame dZoneManager dPhysics Detour Recast tinyxml2 dWorldServer dNavigation) -add_executable(WorldServer ${DWORLDSERVER_SOURCES}) -target_link_libraries(WorldServer ${COMMON_LIBRARIES} dChatFilter dGame dZoneManager Detour Recast dPhysics tinyxml2 dNavigation) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index fb1ed5ac..9ba75a2f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,34 +1,21 @@ -# create the testing file and list of tests -create_test_sourcelist (Tests - CommonCxxTests.cpp - AMFDeserializeTests.cpp - TestNiPoint3.cpp - TestLDFFormat.cpp - TestEncoding.cpp +message (STATUS "Testing is enabled. Fetching gtest...") +enable_testing() + +include(FetchContent) +FetchContent_Declare( + googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG release-1.12.1 ) -# add the executable -add_executable (CommonCxxTests ${Tests}) -target_link_libraries(CommonCxxTests ${COMMON_LIBRARIES}) +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) -# remove the test driver source file -set (TestsToRun ${Tests}) -remove (TestsToRun CommonCxxTests.cpp) +FetchContent_MakeAvailable(GoogleTest) +include(GoogleTest) -# Copy test files to testing directory -configure_file( - ${CMAKE_SOURCE_DIR}/tests/TestBitStreams/AMFBitStreamTest.bin ${PROJECT_BINARY_DIR}/tests/AMFBitStreamTest.bin - COPYONLY -) +message(STATUS "gtest fetched and is now ready.") -configure_file( - ${CMAKE_SOURCE_DIR}/tests/TestBitStreams/AMFBitStreamUnimplementedTest.bin ${PROJECT_BINARY_DIR}/tests/AMFBitStreamUnimplementedTest.bin - COPYONLY -) - -# Add all the ADD_TEST for each test -foreach (test ${TestsToRun}) - get_filename_component (TName ${test} NAME_WE) - add_test (NAME ${TName} COMMAND CommonCxxTests ${TName}) - set_property(TEST ${TName} PROPERTY ENVIRONMENT CTEST_OUTPUT_ON_FAILURE=1) -endforeach () +# Add the subdirectories +add_subdirectory(dCommonTests) +add_subdirectory(dGameTests) diff --git a/tests/CommonCxxTests.cpp b/tests/CommonCxxTests.cpp deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/CommonCxxTests.h b/tests/CommonCxxTests.h deleted file mode 100644 index f1894927..00000000 --- a/tests/CommonCxxTests.h +++ /dev/null @@ -1,4 +0,0 @@ -#include <cstdio> - -#define ASSERT_EQ(a,b) { if (!(a == b)) { printf("Failed assertion: " #a " == " #b " \n in %s:%d\n", __FILE__, __LINE__); return 1; }} -#define ASSERT_NE(a,b) { if (!(a != b)) { printf("Failed assertion: " #a " != " #b " \n in %s:%d\n", __FILE__, __LINE__); return 1; }} diff --git a/tests/TestEncoding.cpp b/tests/TestEncoding.cpp deleted file mode 100644 index c23e2db6..00000000 --- a/tests/TestEncoding.cpp +++ /dev/null @@ -1,52 +0,0 @@ -#include <stdexcept> -#include <string> - -#include "GeneralUtils.h" -#include "CommonCxxTests.h" - -int TestEncoding(int argc, char** const argv) { - std::string x = "Hello World!"; - std::string_view v(x); - - uint32_t out; - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'H'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'e'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'l'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 'o'); - ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), true); - - x = u8"Frühling"; - v = x; - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'F'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'r'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'ü'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'h'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'l'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'i'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'n'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'g'); - ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); - - x = "中文字"; - v = x; - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'中'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'文'); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, U'字'); - ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); - - x = "👨‍⚖️"; - v = x; - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x1F468); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x200D); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0x2696); - GeneralUtils::_NextUTF8Char(v, out); ASSERT_EQ(out, 0xFE0F); - ASSERT_EQ(GeneralUtils::_NextUTF8Char(v, out), false); - - ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Hello World!"), u"Hello World!"); - ASSERT_EQ(GeneralUtils::UTF8ToUTF16("Frühling"), u"Frühling"); - ASSERT_EQ(GeneralUtils::UTF8ToUTF16("中文字"), u"中文字"); - ASSERT_EQ(GeneralUtils::UTF8ToUTF16("👨‍⚖️"), u"👨‍⚖️"); - - return 0; -} diff --git a/tests/AMFDeserializeTests.cpp b/tests/dCommonTests/AMFDeserializeTests.cpp similarity index 83% rename from tests/AMFDeserializeTests.cpp rename to tests/dCommonTests/AMFDeserializeTests.cpp index 8d4974a3..a823b0dc 100644 --- a/tests/AMFDeserializeTests.cpp +++ b/tests/dCommonTests/AMFDeserializeTests.cpp @@ -1,52 +1,65 @@ -#include <chrono> #include <fstream> -#include <iostream> #include <memory> +#include <gtest/gtest.h> #include "AMFDeserialize.h" #include "AMFFormat.h" -#include "CommonCxxTests.h" +/** + * Helper method that all tests use to get their respective AMF. + */ std::unique_ptr<AMFValue> ReadFromBitStream(RakNet::BitStream* bitStream) { AMFDeserialize deserializer; std::unique_ptr<AMFValue> returnValue(deserializer.Read(bitStream)); return returnValue; } -int ReadAMFUndefinedFromBitStream() { - CBITSTREAM; +/** + * @brief Test reading an AMFUndefined value from a BitStream. + */ +TEST(dCommonTests, AMFDeserializeAMFUndefinedTest) { + CBITSTREAM bitStream.Write<uint8_t>(0x00); std::unique_ptr<AMFValue> res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFUndefined); - return 0; } -int ReadAMFNullFromBitStream() { - CBITSTREAM; +/** + * @brief Test reading an AMFNull value from a BitStream. + * + */ +TEST(dCommonTests, AMFDeserializeAMFNullTest) { + CBITSTREAM bitStream.Write<uint8_t>(0x01); std::unique_ptr<AMFValue> res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFNull); - return 0; } -int ReadAMFFalseFromBitStream() { - CBITSTREAM; +/** + * @brief Test reading an AMFFalse value from a BitStream. + */ +TEST(dCommonTests, AMFDeserializeAMFFalseTest) { + CBITSTREAM bitStream.Write<uint8_t>(0x02); std::unique_ptr<AMFValue> res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFFalse); - return 0; } -int ReadAMFTrueFromBitStream() { - CBITSTREAM; +/** + * @brief Test reading an AMFTrue value from a BitStream. + */ +TEST(dCommonTests, AMFDeserializeAMFTrueTest) { + CBITSTREAM bitStream.Write<uint8_t>(0x03); std::unique_ptr<AMFValue> res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFTrue); - return 0; } -int ReadAMFIntegerFromBitStream() { - CBITSTREAM; +/** + * @brief Test reading an AMFInteger value from a BitStream. + */ +TEST(dCommonTests, AMFDeserializeAMFIntegerTest) { + CBITSTREAM { bitStream.Write<uint8_t>(0x04); // 127 == 01111111 @@ -91,21 +104,25 @@ int ReadAMFIntegerFromBitStream() { // Check that 2 byte max can be read correctly ASSERT_EQ(static_cast<AMFIntegerValue*>(res.get())->GetIntegerValue(), 16383); } - return 0; } -int ReadAMFDoubleFromBitStream() { - CBITSTREAM; +/** + * @brief Test reading an AMFDouble value from a BitStream. + */ +TEST(dCommonTests, AMFDeserializeAMFDoubleTest) { + CBITSTREAM bitStream.Write<uint8_t>(0x05); bitStream.Write<double>(25346.4f); std::unique_ptr<AMFValue> res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFDouble); ASSERT_EQ(static_cast<AMFDoubleValue*>(res.get())->GetDoubleValue(), 25346.4f); - return 0; } -int ReadAMFStringFromBitStream() { - CBITSTREAM; +/** + * @brief Test reading an AMFString value from a BitStream. + */ +TEST(dCommonTests, AMFDeserializeAMFStringTest) { + CBITSTREAM bitStream.Write<uint8_t>(0x06); bitStream.Write<uint8_t>(0x0F); std::string toWrite = "stateID"; @@ -113,11 +130,13 @@ int ReadAMFStringFromBitStream() { std::unique_ptr<AMFValue> res(ReadFromBitStream(&bitStream)); ASSERT_EQ(res->GetValueType(), AMFValueType::AMFString); ASSERT_EQ(static_cast<AMFStringValue*>(res.get())->GetStringValue(), "stateID"); - return 0; } -int ReadAMFArrayFromBitStream() { - CBITSTREAM; +/** + * @brief Test reading an AMFArray value from a BitStream. + */ +TEST(dCommonTests, AMFDeserializeAMFArrayTest) { + CBITSTREAM // Test empty AMFArray bitStream.Write<uint8_t>(0x09); bitStream.Write<uint8_t>(0x01); @@ -149,15 +168,15 @@ int ReadAMFArrayFromBitStream() { ASSERT_EQ(static_cast<AMFArrayValue*>(res.get())->FindValue<AMFStringValue>("BehaviorID")->GetStringValue(), "10447"); ASSERT_EQ(static_cast<AMFArrayValue*>(res.get())->GetValueAt<AMFStringValue>(0)->GetStringValue(), "10447"); } - // Test a dense array - return 0; } /** - * This test checks that if we recieve an unimplemented AMFValueType + * @brief This test checks that if we recieve an unimplemented AMFValueType * we correctly throw an error and can actch it. + * */ -int TestUnimplementedAMFValues() { +#pragma message("-- The AMFDeserializeUnimplementedValuesTest causes a known memory leak of 880 bytes since it throws errors! --") +TEST(dCommonTests, AMFDeserializeUnimplementedValuesTest) { std::vector<AMFValueType> unimplementedValues = { AMFValueType::AMFXMLDoc, AMFValueType::AMFDate, @@ -196,13 +215,15 @@ int TestUnimplementedAMFValues() { } catch (AMFValueType unimplementedValueType) { caughtException = true; } - std::cout << "Testing unimplemented value " << amfValueType << " Did we catch an exception: " << (caughtException ? "YES" : "NO") << std::endl; + ASSERT_EQ(caughtException, true); } - return 0; } -int TestLiveCapture() { +/** + * @brief Test reading a packet capture from live from a BitStream + */ +TEST(dCommonTests, AMFDeserializeLivePacketTest) { std::ifstream testFileStream; testFileStream.open("AMFBitStreamTest.bin", std::ios::binary); @@ -267,9 +288,9 @@ int TestLiveCapture() { auto actionID = firstStrip->FindValue<AMFDoubleValue>("id"); - ASSERT_EQ(actionID->GetDoubleValue(), 0.0f) + ASSERT_EQ(actionID->GetDoubleValue(), 0.0f); - auto uiArray = firstStrip->FindValue<AMFArrayValue>("ui"); + auto uiArray = firstStrip->FindValue<AMFArrayValue>("ui"); auto xPos = uiArray->FindValue<AMFDoubleValue>("x"); auto yPos = uiArray->FindValue<AMFDoubleValue>("y"); @@ -279,9 +300,9 @@ int TestLiveCapture() { auto stripID = firstStrip->FindValue<AMFDoubleValue>("id"); - ASSERT_EQ(stripID->GetDoubleValue(), 0.0f) + ASSERT_EQ(stripID->GetDoubleValue(), 0.0f); - auto firstAction = dynamic_cast<AMFArrayValue*>(actionsInFirstStrip[0]); + auto firstAction = dynamic_cast<AMFArrayValue*>(actionsInFirstStrip[0]); auto firstType = firstAction->FindValue<AMFStringValue>("Type"); @@ -318,17 +339,17 @@ int TestLiveCapture() { auto thirdDistance = thirdAction->FindValue<AMFDoubleValue>("Distance"); ASSERT_EQ(thirdDistance->GetDoubleValue(), 25.0f); - - return 0; } -int TestNullStream() { +/** + * @brief Tests that having no BitStream returns a nullptr. + */ +TEST(dCommonTests, AMFDeserializeNullTest) { auto result = ReadFromBitStream(nullptr); ASSERT_EQ(result.get(), nullptr); - return 0; } -int TestBadConversion() { +TEST(dCommonTests, AMFBadConversionTest) { std::ifstream testFileStream; testFileStream.open("AMFBitStreamTest.bin", std::ios::binary); @@ -360,30 +381,6 @@ int TestBadConversion() { // Value is out of bounds ASSERT_EQ(result->GetValueAt<AMFTrueValue>(1), nullptr); - - return 0; -} - -int AMFDeserializeTests(int argc, char** const argv) { - std::cout << "Checking that using a null bitstream doesnt cause exception" << std::endl; - if (TestNullStream()) return 1; - std::cout << "passed nullptr test, checking basic tests" << std::endl; - if (ReadAMFUndefinedFromBitStream() != 0) return 1; - if (ReadAMFNullFromBitStream() != 0) return 1; - if (ReadAMFFalseFromBitStream() != 0) return 1; - if (ReadAMFTrueFromBitStream() != 0) return 1; - if (ReadAMFIntegerFromBitStream() != 0) return 1; - if (ReadAMFDoubleFromBitStream() != 0) return 1; - if (ReadAMFStringFromBitStream() != 0) return 1; - if (ReadAMFArrayFromBitStream() != 0) return 1; - std::cout << "Passed basic test, checking live capture" << std::endl; - if (TestLiveCapture() != 0) return 1; - std::cout << "Passed live capture, checking unimplemented amf values" << std::endl; - if (TestUnimplementedAMFValues() != 0) return 1; - std::cout << "Passed unimplemented values, checking poor casting" << std::endl; - if (TestBadConversion() != 0) return 1; - std::cout << "Passed all tests." << std::endl; - return 0; } /** diff --git a/tests/dCommonTests/CMakeLists.txt b/tests/dCommonTests/CMakeLists.txt new file mode 100644 index 00000000..86c00c58 --- /dev/null +++ b/tests/dCommonTests/CMakeLists.txt @@ -0,0 +1,19 @@ +set(DCOMMONTEST_SOURCES + "AMFDeserializeTests.cpp" + "TestLDFFormat.cpp" + "TestNiPoint3.cpp" + "TestEncoding.cpp" +) + +# Set our executable +add_executable(dCommonTests ${DCOMMONTEST_SOURCES}) + +# Link needed libraries +target_link_libraries(dCommonTests ${COMMON_LIBRARIES} GTest::gtest_main) + +# Copy test files to testing directory +add_subdirectory(TestBitStreams) +file(COPY ${TESTBITSTREAMS} DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) + +# Discover the tests +gtest_discover_tests(dCommonTests) diff --git a/tests/TestBitStreams/AMFBitStreamTest.bin b/tests/dCommonTests/TestBitStreams/AMFBitStreamTest.bin similarity index 100% rename from tests/TestBitStreams/AMFBitStreamTest.bin rename to tests/dCommonTests/TestBitStreams/AMFBitStreamTest.bin diff --git a/tests/TestBitStreams/AMFBitStreamUnimplementedTest.bin b/tests/dCommonTests/TestBitStreams/AMFBitStreamUnimplementedTest.bin similarity index 100% rename from tests/TestBitStreams/AMFBitStreamUnimplementedTest.bin rename to tests/dCommonTests/TestBitStreams/AMFBitStreamUnimplementedTest.bin diff --git a/tests/dCommonTests/TestBitStreams/CMakeLists.txt b/tests/dCommonTests/TestBitStreams/CMakeLists.txt new file mode 100644 index 00000000..93606df6 --- /dev/null +++ b/tests/dCommonTests/TestBitStreams/CMakeLists.txt @@ -0,0 +1,11 @@ +set(TESTBITSTREAMS + "AMFBitStreamTest.bin" + "AMFBitStreamUnimplementedTest.bin" +) + +# Get the folder name and prepend it to the files above +get_filename_component(thisFolderName ${CMAKE_CURRENT_SOURCE_DIR} NAME) +list(TRANSFORM TESTBITSTREAMS PREPEND "${thisFolderName}/") + +# Export our list of files +set(TESTBITSTREAMS ${TESTBITSTREAMS} PARENT_SCOPE) diff --git a/tests/dCommonTests/TestEncoding.cpp b/tests/dCommonTests/TestEncoding.cpp new file mode 100644 index 00000000..c103ccbf --- /dev/null +++ b/tests/dCommonTests/TestEncoding.cpp @@ -0,0 +1,68 @@ +#include <string> +#include <gtest/gtest.h> +#include <string_view> + +#include "GeneralUtils.h" + +class EncodingTest : public ::testing::Test { +protected: + std::string originalWord; + std::string_view originalWordSv; + uint32_t out; +}; + +TEST_F(EncodingTest, TestEncodingHello) { + originalWord = "Hello World!"; + originalWordSv = originalWord; + + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, 'H'); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, 'e'); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, 'l'); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, 'l'); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, 'o'); + EXPECT_EQ(GeneralUtils::_NextUTF8Char(originalWordSv, out), true); + + EXPECT_EQ(GeneralUtils::UTF8ToUTF16("Hello World!"), u"Hello World!"); +}; + +TEST_F(EncodingTest, TestEncodingUmlaut) { + originalWord = u8"Frühling"; + originalWordSv = originalWord; + + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, U'F'); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, U'r'); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, U'ü'); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, U'h'); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, U'l'); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, U'i'); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, U'n'); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, U'g'); + EXPECT_EQ(GeneralUtils::_NextUTF8Char(originalWordSv, out), false); + + EXPECT_EQ(GeneralUtils::UTF8ToUTF16("Frühling"), u"Frühling"); +}; + +TEST_F(EncodingTest, TestEncodingChinese) { + originalWord = "中文字"; + originalWordSv = originalWord; + + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, U'中'); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, U'文'); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, U'字'); + EXPECT_EQ(GeneralUtils::_NextUTF8Char(originalWordSv, out), false); + + EXPECT_EQ(GeneralUtils::UTF8ToUTF16("中文字"), u"中文字"); +}; + +TEST_F(EncodingTest, TestEncodingEmoji) { + originalWord = "👨‍⚖️"; + originalWordSv = originalWord; + + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, 0x1F468); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, 0x200D); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, 0x2696); + GeneralUtils::_NextUTF8Char(originalWordSv, out); EXPECT_EQ(out, 0xFE0F); + EXPECT_EQ(GeneralUtils::_NextUTF8Char(originalWordSv, out), false); + + EXPECT_EQ(GeneralUtils::UTF8ToUTF16("👨‍⚖️"), u"👨‍⚖️"); +}; diff --git a/tests/TestLDFFormat.cpp b/tests/dCommonTests/TestLDFFormat.cpp similarity index 69% rename from tests/TestLDFFormat.cpp rename to tests/dCommonTests/TestLDFFormat.cpp index a7433e96..647c3cbf 100644 --- a/tests/TestLDFFormat.cpp +++ b/tests/dCommonTests/TestLDFFormat.cpp @@ -1,14 +1,10 @@ #include "LDFFormat.h" -#include "CommonCxxTests.h" +#include <gtest/gtest.h> /** * @brief Test parsing an LDF value - * - * @param argc Number of command line arguments for this test - * @param argv Command line arguments - * @return 0 on success, non-zero on failure */ -int TestLDFFormat(int argc, char** const argv) { +TEST(dCommonTests, LDFTest) { // Create auto* data = LDFBaseData::DataFromString("KEY=0:VALUE"); @@ -26,6 +22,4 @@ int TestLDFFormat(int argc, char** const argv) { // Cleanup the object delete data; - - return 0; } diff --git a/tests/TestNiPoint3.cpp b/tests/dCommonTests/TestNiPoint3.cpp similarity index 59% rename from tests/TestNiPoint3.cpp rename to tests/dCommonTests/TestNiPoint3.cpp index d1588b8b..33cd51d2 100644 --- a/tests/TestNiPoint3.cpp +++ b/tests/dCommonTests/TestNiPoint3.cpp @@ -1,13 +1,14 @@ -#include <stdexcept> +#include <gtest/gtest.h> #include "NiPoint3.h" -#include "CommonCxxTests.h" -int TestNiPoint3(int argc, char** const argv) { +/** + * @brief Basic test for NiPoint3 functionality + * + */ +TEST(dCommonTests, NiPoint3Test) { // Check that Unitize works ASSERT_EQ(NiPoint3(3, 0, 0).Unitize(), NiPoint3::UNIT_X); // Check what unitize does to a vector of length 0 ASSERT_EQ(NiPoint3::ZERO.Unitize(), NiPoint3::ZERO); - // If we get here, all was successful - return 0; } diff --git a/tests/dGameTests/CMakeLists.txt b/tests/dGameTests/CMakeLists.txt new file mode 100644 index 00000000..68192b3f --- /dev/null +++ b/tests/dGameTests/CMakeLists.txt @@ -0,0 +1,14 @@ +set(DGAMETEST_SOURCES + "GameDependencies.cpp" +) + +add_subdirectory(dComponentsTests) +list(APPEND DGAMETEST_SOURCES ${DCOMPONENTS_TESTS}) + +# Add the executable. Remember to add all tests above this! +add_executable(dGameTests ${DGAMETEST_SOURCES}) + +target_link_libraries(dGameTests ${COMMON_LIBRARIES} GTest::gtest_main dGame dZoneManager dPhysics Detour Recast tinyxml2 dWorldServer dChatFilter dNavigation) + +# Discover the tests +gtest_discover_tests(dGameTests) diff --git a/tests/dGameTests/GameDependencies.cpp b/tests/dGameTests/GameDependencies.cpp new file mode 100644 index 00000000..8a572668 --- /dev/null +++ b/tests/dGameTests/GameDependencies.cpp @@ -0,0 +1,15 @@ +#include "GameDependencies.h" + +namespace Game { + dLogger* logger; + dServer* server; + dZoneManager* zoneManager; + dpWorld* physicsWorld; + dChatFilter* chatFilter; + dConfig* config; + dLocale* locale; + std::mt19937 randomEngine; + RakPeerInterface* chatServer; + AssetManager* assetManager; + SystemAddress chatSysAddr; +} diff --git a/tests/dGameTests/GameDependencies.h b/tests/dGameTests/GameDependencies.h new file mode 100644 index 00000000..593ec0fc --- /dev/null +++ b/tests/dGameTests/GameDependencies.h @@ -0,0 +1,43 @@ +#ifndef __GAMEDEPENDENCIES__H__ +#define __GAMEDEPENDENCIES__H__ + +#include "Game.h" +#include "dLogger.h" +#include "dServer.h" +#include "EntityManager.h" +class dZoneManager; +class AssetManager; +#include <gtest/gtest.h> + +class dServerMock : public dServer { +public: + dServerMock() {}; + ~dServerMock() {}; + void Send(RakNet::BitStream* bitStream, const SystemAddress& sysAddr, bool broadcast) override {}; +}; + +class GameDependenciesTest : public ::testing::Test { +protected: + void SetUpDependencies() { + info.pos = NiPoint3::ZERO; + info.rot = NiQuaternion::IDENTITY; + info.scale = 1.0f; + info.spawner = nullptr; + info.lot = 999; + Game::logger = new dLogger("./testing.log", true, true); + Game::server = new dServerMock(); + } + + void TearDownDependencies() { + if (Game::server) delete Game::server; + delete EntityManager::Instance(); + if (Game::logger) { + Game::logger->Flush(); + delete Game::logger; + } + } + + EntityInfo info; +}; + +#endif //!__GAMEDEPENDENCIES__H__ diff --git a/tests/dGameTests/dComponentsTests/CMakeLists.txt b/tests/dGameTests/dComponentsTests/CMakeLists.txt new file mode 100644 index 00000000..17e69a2f --- /dev/null +++ b/tests/dGameTests/dComponentsTests/CMakeLists.txt @@ -0,0 +1,10 @@ +set(DCOMPONENTS_TESTS + "DestroyableComponentTests.cpp" +) + +# Get the folder name and prepend it to the files above +get_filename_component(thisFolderName ${CMAKE_CURRENT_SOURCE_DIR} NAME) +list(TRANSFORM DCOMPONENTS_TESTS PREPEND "${thisFolderName}/") + +# Export to parent scope +set(DCOMPONENTS_TESTS ${DCOMPONENTS_TESTS} PARENT_SCOPE) diff --git a/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp new file mode 100644 index 00000000..97288909 --- /dev/null +++ b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp @@ -0,0 +1,300 @@ +#include "GameDependencies.h" +#include <gtest/gtest.h> + +#include "BitStream.h" +#include "DestroyableComponent.h" +#include "Entity.h" + +class DestroyableTest : public GameDependenciesTest { +protected: + Entity* baseEntity; + DestroyableComponent* destroyableComponent; + CBITSTREAM + uint32_t flags = 0; + void SetUp() override { + SetUpDependencies(); + baseEntity = new Entity(15, GameDependenciesTest::info); + destroyableComponent = new DestroyableComponent(baseEntity); + baseEntity->AddComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent); + // Initialize some values to be not default + destroyableComponent->SetMaxHealth(12345.0f); + destroyableComponent->SetHealth(23); + destroyableComponent->SetMaxArmor(14.0f); + destroyableComponent->SetArmor(7); + destroyableComponent->SetMaxImagination(14000.0f); + destroyableComponent->SetImagination(6000); + destroyableComponent->SetIsSmashable(true); + destroyableComponent->SetExplodeFactor(1.1f); + destroyableComponent->AddFactionNoLookup(-1); + destroyableComponent->AddFactionNoLookup(6); + } + + void TearDown() override { + delete baseEntity; + TearDownDependencies(); + } +}; + +/** + * Test Construction of a DestroyableComponent + */ +TEST_F(DestroyableTest, DestroyableComponentSerializeConstructionTest) { + destroyableComponent->Serialize(&bitStream, true, flags); + // Assert that the full number of bits are present + ASSERT_EQ(bitStream.GetNumberOfUnreadBits(), 460); + { + // Now read in the full serialized construction BitStream + bool optionStatusImmunityInfo{}; // Values under this option are unused. + bool optionStatsInfo{}; + uint32_t currentHealth{}; + float maxHealth{}; + uint32_t currentArmor{}; + float maxArmor{}; + uint32_t currentImagination{}; + float maxImagination{}; + uint32_t damageAbsorptionPoints{}; + bool hasImmunity{}; + bool isGmImmune{}; + bool isShielded{}; + float actualMaxHealth{}; + float actualMaxArmor{}; + float actualMaxImagination{}; + uint32_t factionsSize{}; + std::vector<int32_t> factions{}; + bool isSmashable{}; + bool isDead{}; + bool isSmashed{}; + bool isModuleAssembly{}; + bool optionExplodeFactor{}; + float explodeFactor{}; + bool optionIsOnThreatList{}; + bool isThreatened{}; + bitStream.Read(optionStatusImmunityInfo); + + bitStream.Read(optionStatsInfo); + bitStream.Read(currentHealth); + bitStream.Read(maxHealth); + bitStream.Read(currentArmor); + bitStream.Read(maxArmor); + bitStream.Read(currentImagination); + bitStream.Read(maxImagination); + bitStream.Read(damageAbsorptionPoints); + bitStream.Read(hasImmunity); + bitStream.Read(isGmImmune); + bitStream.Read(isShielded); + bitStream.Read(actualMaxHealth); + bitStream.Read(actualMaxArmor); + bitStream.Read(actualMaxImagination); + bitStream.Read(factionsSize); + for (uint32_t i = 0; i < factionsSize; i++) { + int32_t factionID{}; + bitStream.Read(factionID); + factions.push_back(factionID); + } + bitStream.Read(isSmashable); // This is an option later and also a flag at this spot + bitStream.Read(isDead); + bitStream.Read(isSmashed); + // if IsSmashable is true, read the next bits. + bitStream.Read(isModuleAssembly); + bitStream.Read(optionExplodeFactor); + bitStream.Read(explodeFactor); + + bitStream.Read(optionIsOnThreatList); + bitStream.Read(isThreatened); + EXPECT_EQ(optionStatusImmunityInfo, false); + + EXPECT_EQ(optionStatsInfo, true); + EXPECT_EQ(currentHealth, 23); + EXPECT_EQ(maxHealth, 12345.0f); + EXPECT_EQ(currentArmor, 7); + EXPECT_EQ(maxArmor, 14.0f); + EXPECT_EQ(currentImagination, 6000); + EXPECT_EQ(maxImagination, 14000.0f); + EXPECT_EQ(damageAbsorptionPoints, 0.0f); + EXPECT_EQ(hasImmunity, false); + EXPECT_EQ(isGmImmune, false); + EXPECT_EQ(isShielded, false); + EXPECT_EQ(actualMaxHealth, 12345.0f); + EXPECT_EQ(actualMaxArmor, 14.0f); + EXPECT_EQ(actualMaxImagination, 14000.0f); + EXPECT_EQ(factionsSize, 2); + EXPECT_NE(std::find(factions.begin(), factions.end(), -1), factions.end()); + EXPECT_NE(std::find(factions.begin(), factions.end(), 6), factions.end()); + EXPECT_EQ(isSmashable, true); + EXPECT_EQ(isDead, false); + EXPECT_EQ(isSmashed, false); + EXPECT_EQ(isSmashable, true); // For the sake of readability with the struct viewers, we will test this twice since its used as an option here, but as a bool above. + EXPECT_EQ(isModuleAssembly, false); + EXPECT_EQ(optionExplodeFactor, true); + EXPECT_EQ(explodeFactor, 1.1f); + + EXPECT_EQ(optionIsOnThreatList, true); + EXPECT_EQ(isThreatened, false); + } + bitStream.Reset(); +} + +/** + * Test serialization of a DestroyableComponent + */ +TEST_F(DestroyableTest, DestroyableComponentSerializeTest) { + bitStream.Reset(); + // Initialize some values to be not default so we can test a full serialization + destroyableComponent->SetMaxHealth(1233.0f); + + // Now we test a serialization for correctness. + destroyableComponent->Serialize(&bitStream, false, flags); + ASSERT_EQ(bitStream.GetNumberOfUnreadBits(), 422); + { + // Now read in the full serialized BitStream + bool optionStatsInfo{}; + uint32_t currentHealth{}; + float maxHealth{}; + uint32_t currentArmor{}; + float maxArmor{}; + uint32_t currentImagination{}; + float maxImagination{}; + uint32_t damageAbsorptionPoints{}; + bool hasImmunity{}; + bool isGmImmune{}; + bool isShielded{}; + float actualMaxHealth{}; + float actualMaxArmor{}; + float actualMaxImagination{}; + uint32_t factionsSize{}; + std::vector<int32_t> factions{}; + bool isSmashable{}; + bool optionIsOnThreatList{}; + bitStream.Read(optionStatsInfo); + bitStream.Read(currentHealth); + bitStream.Read(maxHealth); + bitStream.Read(currentArmor); + bitStream.Read(maxArmor); + bitStream.Read(currentImagination); + bitStream.Read(maxImagination); + bitStream.Read(damageAbsorptionPoints); + bitStream.Read(hasImmunity); + bitStream.Read(isGmImmune); + bitStream.Read(isShielded); + bitStream.Read(actualMaxHealth); + bitStream.Read(actualMaxArmor); + bitStream.Read(actualMaxImagination); + bitStream.Read(factionsSize); + for (uint32_t i = 0; i < factionsSize; i++) { + int32_t factionID{}; + bitStream.Read(factionID); + factions.push_back(factionID); + } + bitStream.Read(isSmashable); + + bitStream.Read(optionIsOnThreatList); + + EXPECT_EQ(optionStatsInfo, true); + EXPECT_EQ(currentHealth, 23); + EXPECT_EQ(maxHealth, 1233.0f); + EXPECT_EQ(currentArmor, 7); + EXPECT_EQ(maxArmor, 14.0f); + EXPECT_EQ(currentImagination, 6000); + EXPECT_EQ(maxImagination, 14000.0f); + EXPECT_EQ(damageAbsorptionPoints, 0.0f); + EXPECT_EQ(hasImmunity, false); + EXPECT_EQ(isGmImmune, false); + EXPECT_EQ(isShielded, false); + EXPECT_EQ(actualMaxHealth, 1233.0f); + EXPECT_EQ(actualMaxArmor, 14.0f); + EXPECT_EQ(actualMaxImagination, 14000.0f); + EXPECT_EQ(factionsSize, 2); + EXPECT_NE(std::find(factions.begin(), factions.end(), -1), factions.end()); + EXPECT_NE(std::find(factions.begin(), factions.end(), 6), factions.end()); + EXPECT_EQ(isSmashable, true); + + EXPECT_EQ(optionIsOnThreatList, false); // Always zero for now on serialization + } +} + +/** + * Test the Damage method of DestroyableComponent + */ +TEST_F(DestroyableTest, DestroyableComponentDamageTest) { + // Do some actions + destroyableComponent->SetMaxHealth(100.0f); + destroyableComponent->SetHealth(100); + destroyableComponent->SetMaxArmor(0.0f); + destroyableComponent->Damage(10, LWOOBJID_EMPTY); + // Check that we take damage + ASSERT_EQ(destroyableComponent->GetHealth(), 90); + // Check that if we have armor, we take the correct amount of damage + destroyableComponent->SetMaxArmor(10.0f); + destroyableComponent->SetArmor(5); + destroyableComponent->Damage(10, LWOOBJID_EMPTY); + ASSERT_EQ(destroyableComponent->GetHealth(), 85); + // Check that if we have damage absorption we take the correct damage + destroyableComponent->SetDamageToAbsorb(10); + destroyableComponent->Damage(9, LWOOBJID_EMPTY); + ASSERT_EQ(destroyableComponent->GetHealth(), 85); + ASSERT_EQ(destroyableComponent->GetDamageToAbsorb(), 1); + destroyableComponent->Damage(6, LWOOBJID_EMPTY); + ASSERT_EQ(destroyableComponent->GetHealth(), 80); + // Check that we take the correct reduced damage if we take reduced damage + destroyableComponent->SetDamageReduction(2); + destroyableComponent->Damage(7, LWOOBJID_EMPTY); + ASSERT_EQ(destroyableComponent->GetHealth(), 75); + destroyableComponent->Damage(2, LWOOBJID_EMPTY); + ASSERT_EQ(destroyableComponent->GetHealth(), 74); + ASSERT_EQ(destroyableComponent->GetDamageReduction(), 2); + destroyableComponent->SetDamageReduction(0); + // Check that blocking works + destroyableComponent->SetAttacksToBlock(1); + destroyableComponent->Damage(UINT32_MAX, LWOOBJID_EMPTY); + ASSERT_EQ(destroyableComponent->GetHealth(), 74); + destroyableComponent->Damage(4, LWOOBJID_EMPTY); + ASSERT_EQ(destroyableComponent->GetHealth(), 70); + // Check that immunity works + destroyableComponent->SetIsImmune(true); + destroyableComponent->Damage(UINT32_MAX, LWOOBJID_EMPTY); + ASSERT_EQ(destroyableComponent->GetHealth(), 70); + ASSERT_TRUE(destroyableComponent->IsImmune()); + destroyableComponent->SetIsImmune(false); + destroyableComponent->SetIsGMImmune(true); + destroyableComponent->Damage(UINT32_MAX, LWOOBJID_EMPTY); + ASSERT_EQ(destroyableComponent->GetHealth(), 70); + ASSERT_TRUE(destroyableComponent->IsImmune()); + destroyableComponent->SetIsGMImmune(false); + // Check knockback immunity + destroyableComponent->SetIsShielded(true); + ASSERT_TRUE(destroyableComponent->IsKnockbackImmune()); + // Finally deal enough damage to kill the Entity + destroyableComponent->Damage(71, LWOOBJID_EMPTY); + ASSERT_EQ(destroyableComponent->GetHealth(), 0); + // Now lets heal some stats + destroyableComponent->Heal(15); + ASSERT_EQ(destroyableComponent->GetHealth(), 15); + destroyableComponent->Heal(15000); + ASSERT_EQ(destroyableComponent->GetHealth(), 100); + destroyableComponent->Repair(10); + ASSERT_EQ(destroyableComponent->GetArmor(), 10); + destroyableComponent->Repair(15000); + ASSERT_EQ(destroyableComponent->GetArmor(), 10); + destroyableComponent->SetMaxImagination(100.0f); + destroyableComponent->SetImagination(0); + destroyableComponent->Imagine(99); + ASSERT_EQ(destroyableComponent->GetImagination(), 99); + destroyableComponent->Imagine(4); + ASSERT_EQ(destroyableComponent->GetImagination(), 100); +} + +TEST_F(DestroyableTest, DestroyableComponentFactionTest) { + ASSERT_TRUE(destroyableComponent->HasFaction(-1)); + ASSERT_TRUE(destroyableComponent->HasFaction(6)); +} + +TEST_F(DestroyableTest, DestroyableComponentValiditiyTest) { + auto* enemyEntity = new Entity(19, info); + auto* enemyDestroyableComponent = new DestroyableComponent(enemyEntity); + enemyEntity->AddComponent(COMPONENT_TYPE_DESTROYABLE, enemyDestroyableComponent); + enemyDestroyableComponent->AddFactionNoLookup(16); + destroyableComponent->AddEnemyFaction(16); + EXPECT_TRUE(destroyableComponent->IsEnemy(enemyEntity)); + EXPECT_FALSE(destroyableComponent->IsFriend(enemyEntity)); + delete enemyEntity; +} From 2f48981801e57eff625033929d560f1baf5069fa Mon Sep 17 00:00:00 2001 From: Jonathan Romano <jonathan@luxaritas.com> Date: Mon, 7 Nov 2022 04:26:15 -0500 Subject: [PATCH 124/322] Address socket issues with MariaDB Use a new method of determining how to send the connection information to the database --- dDatabase/Database.cpp | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/dDatabase/Database.cpp b/dDatabase/Database.cpp index 91589377..1ce6966f 100644 --- a/dDatabase/Database.cpp +++ b/dDatabase/Database.cpp @@ -14,8 +14,6 @@ std::string Database::database; void Database::Connect(const string& host, const string& database, const string& username, const string& password) { //To bypass debug issues: - std::string newHost = "tcp://" + host; - const char* szHost = newHost.c_str(); const char* szDatabase = database.c_str(); const char* szUsername = username.c_str(); const char* szPassword = password.c_str(); @@ -23,7 +21,24 @@ void Database::Connect(const string& host, const string& database, const string& driver = sql::mariadb::get_driver_instance(); sql::Properties properties; - properties["hostName"] = szHost; + // The mariadb connector is *supposed* to handle unix:// and pipe:// prefixes to hostName, but there are bugs where + // 1) it tries to parse a database from the connection string (like in tcp://localhost:3001/darkflame) based on the + // presence of a / + // 2) even avoiding that, the connector still assumes you're connecting with a tcp socket + // So, what we do in the presence of a unix socket or pipe is to set the hostname to the protocol and localhost, + // which avoids parsing errors while still ensuring the correct connection type is used, and then setting the appropriate + // property manually (which the URL parsing fails to do) + const std::string UNIX_PROTO = "unix://"; + const std::string PIPE_PROTO = "pipe://"; + if (host.find(UNIX_PROTO) == 0) { + properties["hostName"] = "unix://localhost"; + properties["localSocket"] = host.substr(UNIX_PROTO.length()).c_str(); + } else if (host.find(PIPE_PROTO) == 0) { + properties["hostName"] = "pipe://localhost"; + properties["pipe"] = host.substr(PIPE_PROTO.length()).c_str(); + } else { + properties["hostName"] = host.c_str(); + } properties["user"] = szUsername; properties["password"] = szPassword; properties["autoReconnect"] = "true"; @@ -35,7 +50,13 @@ void Database::Connect(const string& host, const string& database, const string& } void Database::Connect() { - con = driver->connect(Database::props["hostName"].c_str(), Database::props["user"].c_str(), Database::props["password"].c_str()); + // `connect(const Properties& props)` segfaults in windows debug, but + // `connect(const SQLString& host, const SQLString& user, const SQLString& pwd)` doesn't handle pipes/unix sockets correctly + if (Database::props.find("localSocket") != Database::props.end() || Database::props.find("pipe") != Database::props.end()) { + con = driver->connect(Database::props); + } else { + con = driver->connect(Database::props["hostName"].c_str(), Database::props["user"].c_str(), Database::props["password"].c_str()); + } con->setSchema(Database::database.c_str()); } From 2570c74b713200a632332b7d61a5740f58343b5d Mon Sep 17 00:00:00 2001 From: Jonathan Romano <jonathan@luxaritas.com> Date: Mon, 7 Nov 2022 04:27:48 -0500 Subject: [PATCH 125/322] Remove hardcoded port number in AuthPackets Removes the hard coded port numbers in AuthPackets --- dNet/AuthPackets.cpp | 6 +++--- dNet/AuthPackets.h | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index 60fe13c5..636f3fcf 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -29,16 +29,16 @@ void AuthPackets::HandleHandshake(dServer* server, Packet* packet) { inStream.Read(clientVersion); server->GetLogger()->Log("AuthPackets", "Received client version: %i", clientVersion); - SendHandshake(server, packet->systemAddress, server->GetIP(), server->GetPort()); + SendHandshake(server, packet->systemAddress, server->GetIP(), server->GetPort(), server->GetServerType()); } -void AuthPackets::SendHandshake(dServer* server, const SystemAddress& sysAddr, const std::string& nextServerIP, uint16_t nextServerPort) { +void AuthPackets::SendHandshake(dServer* server, const SystemAddress& sysAddr, const std::string& nextServerIP, uint16_t nextServerPort, const ServerType serverType) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, SERVER, MSG_SERVER_VERSION_CONFIRM); bitStream.Write<unsigned int>(NET_VERSION); bitStream.Write(uint32_t(0x93)); - if (nextServerPort == 1001) bitStream.Write(uint32_t(1)); //Conn: auth + if (serverType == ServerType::Auth) bitStream.Write(uint32_t(1)); //Conn: auth else bitStream.Write(uint32_t(4)); //Conn: world bitStream.Write(uint32_t(0)); //Server process ID diff --git a/dNet/AuthPackets.h b/dNet/AuthPackets.h index e972d2f7..378a5862 100644 --- a/dNet/AuthPackets.h +++ b/dNet/AuthPackets.h @@ -5,11 +5,12 @@ #include "dCommonVars.h" #include "dNetCommon.h" +enum class ServerType : uint32_t; class dServer; namespace AuthPackets { void HandleHandshake(dServer* server, Packet* packet); - void SendHandshake(dServer* server, const SystemAddress& sysAddr, const std::string& nextServerIP, uint16_t nextServerPort); + void SendHandshake(dServer* server, const SystemAddress& sysAddr, const std::string& nextServerIP, uint16_t nextServerPort, const ServerType serverType); void HandleLoginRequest(dServer* server, Packet* packet); void SendLoginResponse(dServer* server, const SystemAddress& sysAddr, eLoginResponse responseCode, const std::string& errorMsg, const std::string& wServerIP, uint16_t wServerPort, std::string username); From 7c2437173bdb5d5a0c01efc4092e88310924ad61 Mon Sep 17 00:00:00 2001 From: Jack Kawell <jgkawell@outlook.com> Date: Mon, 7 Nov 2022 16:04:20 -0700 Subject: [PATCH 126/322] Fixed docker installation (#823) --- docker/setup.sh | 6 ++---- docker/start_server.sh | 3 +++ 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docker/setup.sh b/docker/setup.sh index 1a95f4de..0f5c0d2e 100755 --- a/docker/setup.sh +++ b/docker/setup.sh @@ -30,6 +30,7 @@ function update_ini_values() { cp resources/authconfig.ini /docker/configs/ cp resources/chatconfig.ini /docker/configs/ cp resources/worldconfig.ini /docker/configs/ + cp resources/sharedconfig.ini /docker/configs/ update_ini worldconfig.ini chat_server_port $CHAT_SERVER_PORT update_ini worldconfig.ini max_clients $MAX_CLIENTS @@ -37,10 +38,7 @@ function update_ini_values() { # always use the internal docker hostname update_ini masterconfig.ini master_ip "darkflame" - update_database_ini_values_for masterconfig.ini - update_database_ini_values_for authconfig.ini - update_database_ini_values_for chatconfig.ini - update_database_ini_values_for worldconfig.ini + update_database_ini_values_for sharedconfig.ini } function fdb_to_sqlite() { diff --git a/docker/start_server.sh b/docker/start_server.sh index feb61361..ca1a49a0 100755 --- a/docker/start_server.sh +++ b/docker/start_server.sh @@ -8,6 +8,8 @@ function symlink_client_files() { ln -s /client/client/res/names/ /app/res/names ln -s /client/client/res/CDServer.sqlite /app/res/CDServer.sqlite ln -s /client/client/locale/locale.xml /app/locale/locale.xml + # need to create this file so the server knows the client is unpacked (see `dCommon/dClient/AssetManager.cpp`) + touch /app/res/cdclient.fdb # need to iterate over entries in maps due to maps already being a directory with navmeshes/ in it ( cd /client/client/res/maps @@ -25,6 +27,7 @@ function symlink_config_files() { ln -s /shared_configs/configs/chatconfig.ini /app/chatconfig.ini ln -s /shared_configs/configs/masterconfig.ini /app/masterconfig.ini ln -s /shared_configs/configs/worldconfig.ini /app/worldconfig.ini + ln -s /shared_configs/configs/sharedconfig.ini /app/sharedconfig.ini } # check to make sure the setup has completed From 1eff3ae454cc42b9b07db1902c73d1e58b23dc1a Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 10 Nov 2022 12:59:31 -0600 Subject: [PATCH 127/322] Add checks to AssetBuffers before they are used (#820) * add checks to buffers before they are used to avoid crashing * address feedback --- dGame/dInventory/Item.cpp | 5 +++++ dGame/dUtilities/BrickDatabase.cpp | 5 +++++ dGame/dUtilities/SlashCommandHandler.cpp | 6 ++++++ dZoneManager/Zone.cpp | 11 ++++++++++- 4 files changed, 26 insertions(+), 1 deletion(-) diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 655af84e..c05c0672 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -344,6 +344,11 @@ void Item::DisassembleModel() { std::string lxfmlPath = "BrickModels/" + GeneralUtils::SplitString(renderAssetSplit.back(), '.').at(0) + ".lxfml"; auto buffer = Game::assetManager->GetFileAsBuffer(lxfmlPath.c_str()); + if (!buffer.m_Success) { + Game::logger->Log("Item", "Failed to load %s to disassemble model into bricks, check that this file exists", lxfmlPath.c_str()); + return; + } + std::istream file(&buffer); result.finalize(); diff --git a/dGame/dUtilities/BrickDatabase.cpp b/dGame/dUtilities/BrickDatabase.cpp index c36a1097..6d1e380c 100644 --- a/dGame/dUtilities/BrickDatabase.cpp +++ b/dGame/dUtilities/BrickDatabase.cpp @@ -19,6 +19,11 @@ std::vector<Brick>& BrickDatabase::GetBricks(const std::string& lxfmlPath) { } AssetMemoryBuffer buffer = Game::assetManager->GetFileAsBuffer((lxfmlPath).c_str()); + + if (!buffer.m_Success) { + return emptyCache; + } + std::istream file(&buffer); if (!file.good()) { return emptyCache; diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index e8f1659e..8f4ac1a8 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -584,6 +584,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (args[0].find("\\") != std::string::npos) return; auto buf = Game::assetManager->GetFileAsBuffer(("macros/" + args[0] + ".scm").c_str()); + + if (!buf.m_Success){ + ChatPackets::SendSystemMessage(sysAddr, u"Unknown macro! Is the filename right?"); + return; + } + std::istream infile(&buf); if (infile.good()) { diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 1fe47454..e507f859 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -42,6 +42,12 @@ void Zone::LoadZoneIntoMemory() { if (m_ZoneFilePath == "ERR") return; AssetMemoryBuffer buffer = Game::assetManager->GetFileAsBuffer(m_ZoneFilePath.c_str()); + + if (!buffer.m_Success) { + Game::logger->Log("Zone", "Failed to load %s", m_ZoneFilePath.c_str()); + throw std::runtime_error("Aborting Zone loading due to no Zone File."); + } + std::istream file(&buffer); if (file) { BinaryIO::BinaryRead(file, m_ZoneFileFormatVersion); @@ -265,7 +271,10 @@ std::vector<LUTriggers::Trigger*> Zone::LoadLUTriggers(std::string triggerFile, auto buffer = Game::assetManager->GetFileAsBuffer((m_ZonePath + triggerFile).c_str()); - if (!buffer.m_Success) return lvlTriggers; + if (!buffer.m_Success) { + Game::logger->Log("Zone", "Failed to load %s from disk. Skipping loading triggers", (m_ZonePath + triggerFile).c_str()); + return lvlTriggers; + } std::istream file(&buffer); std::stringstream data; From cf7fa8e52d750e158c464fbed3ff8987cc483fa3 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 12 Nov 2022 08:44:03 -0600 Subject: [PATCH 128/322] cleanup and define all unknowns in zone reading (#826) * cleanup and define all unknowns in zone reading fix for movement path config reading * simplify reading and don't use intermediates * fix spelling * remove dup variable in struct read to the proper name that relates to the enum --- dZoneManager/Zone.cpp | 91 ++++++++++++++----------------------------- dZoneManager/Zone.h | 43 ++++++++++++++++++-- 2 files changed, 68 insertions(+), 66 deletions(-) diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index e507f859..eb1d789a 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -98,15 +98,12 @@ void Zone::LoadZoneIntoMemory() { if (m_ZoneFileFormatVersion >= Zone::ZoneFileFormatVersion::EarlyAlpha) { BinaryIO::BinaryRead(file, m_PathDataLength); - uint32_t unknown; - uint32_t pathCount; + BinaryIO::BinaryRead(file, m_PathChunkVersion); // always should be 1 - BinaryIO::BinaryRead(file, unknown); + uint32_t pathCount; BinaryIO::BinaryRead(file, pathCount); - for (uint32_t i = 0; i < pathCount; ++i) { - LoadPath(file); - } + for (uint32_t i = 0; i < pathCount; ++i) LoadPath(file); for (Path path : m_Paths) { if (path.pathType == PathType::Spawner) { @@ -251,15 +248,6 @@ void Zone::LoadScene(std::istream& file) { scene.name = BinaryIO::ReadString(file, sceneNameLength); file.ignore(3); - /* - if (m_Scenes.find(scene.id) != m_Scenes.end()) { - //Extract the layer id from the filename (bad I know, but it's reliable at least): - std::string layer = scene.filename.substr(scene.filename.rfind('x') + 1); - layer = layer.substr(0, layer.find('_')); - lwoSceneID.SetLayerID(std::atoi(layer.c_str())); - } - */ - lwoSceneID.SetLayerID(scene.sceneType); m_Scenes.insert(std::make_pair(lwoSceneID, scene)); @@ -377,14 +365,10 @@ SceneTransitionInfo Zone::LoadSceneTransitionInfo(std::istream& file) { } void Zone::LoadPath(std::istream& file) { - // Currently only spawner (type 4) paths are supported Path path = Path(); - uint32_t unknown1; - uint32_t pathType; - uint32_t pathBehavior; - BinaryIO::BinaryRead(file, path.pathVersion); + uint8_t stringLength; BinaryIO::BinaryRead(file, stringLength); for (uint8_t i = 0; i < stringLength; ++i) { @@ -392,16 +376,14 @@ void Zone::LoadPath(std::istream& file) { BinaryIO::BinaryRead(file, character); path.pathName.push_back(character); } - BinaryIO::BinaryRead(file, pathType); - path.pathType = PathType(pathType); - BinaryIO::BinaryRead(file, unknown1); - BinaryIO::BinaryRead(file, pathBehavior); - path.pathType = PathType(pathType); + + BinaryIO::BinaryRead(file, path.pathType); + BinaryIO::BinaryRead(file, path.flags); + BinaryIO::BinaryRead(file, path.pathBehavior); if (path.pathType == PathType::MovingPlatform) { if (path.pathVersion >= 18) { - uint8_t unknown; - BinaryIO::BinaryRead(file, unknown); + BinaryIO::BinaryRead(file, path.movingPlatform.timeBasedMovement); } else if (path.pathVersion >= 13) { uint8_t count; BinaryIO::BinaryRead(file, count); @@ -412,10 +394,9 @@ void Zone::LoadPath(std::istream& file) { } } } else if (path.pathType == PathType::Property) { - int32_t unknown; - BinaryIO::BinaryRead(file, unknown); + BinaryIO::BinaryRead(file, path.property.pathType); BinaryIO::BinaryRead(file, path.property.price); - BinaryIO::BinaryRead(file, path.property.rentalTime); + BinaryIO::BinaryRead(file, path.property.rentalTimeUnit); BinaryIO::BinaryRead(file, path.property.associatedZone); if (path.pathVersion >= 5) { @@ -435,10 +416,7 @@ void Zone::LoadPath(std::istream& file) { } } - if (path.pathVersion >= 6) { - int32_t unknown1; - BinaryIO::BinaryRead(file, unknown1); - } + if (path.pathVersion >= 6) BinaryIO::BinaryRead(file, path.property.type); if (path.pathVersion >= 7) { BinaryIO::BinaryRead(file, path.property.cloneLimit); @@ -462,11 +440,10 @@ void Zone::LoadPath(std::istream& file) { path.camera.nextPath.push_back(character); } if (path.pathVersion >= 14) { - uint8_t unknown; - BinaryIO::BinaryRead(file, unknown); + BinaryIO::BinaryRead(file, path.camera.rotatePlayer); + } } else if (path.pathType == PathType::Spawner) { - //SpawnerPath* path = static_cast<SpawnerPath*>(path); // Convert to a spawner path BinaryIO::BinaryRead(file, path.spawner.spawnedLOT); BinaryIO::BinaryRead(file, path.spawner.respawnTime); BinaryIO::BinaryRead(file, path.spawner.maxToSpawn); @@ -487,7 +464,7 @@ void Zone::LoadPath(std::istream& file) { BinaryIO::BinaryRead(file, waypoint.position.z); - if (path.pathType == PathType::Spawner || path.pathType == PathType::MovingPlatform || path.pathType == PathType::Race) { + if (path.pathType == PathType::Spawner || path.pathType == PathType::MovingPlatform || path.pathType == PathType::Race || path.pathType == PathType::Camera || path.pathType == PathType::Rail) { BinaryIO::BinaryRead(file, waypoint.rotation.w); BinaryIO::BinaryRead(file, waypoint.rotation.x); BinaryIO::BinaryRead(file, waypoint.rotation.y); @@ -515,33 +492,17 @@ void Zone::LoadPath(std::istream& file) { } } } else if (path.pathType == PathType::Camera) { - float unknown; - BinaryIO::BinaryRead(file, unknown); - BinaryIO::BinaryRead(file, unknown); - BinaryIO::BinaryRead(file, unknown); - BinaryIO::BinaryRead(file, unknown); BinaryIO::BinaryRead(file, waypoint.camera.time); - BinaryIO::BinaryRead(file, unknown); + BinaryIO::BinaryRead(file, waypoint.camera.fov); BinaryIO::BinaryRead(file, waypoint.camera.tension); BinaryIO::BinaryRead(file, waypoint.camera.continuity); BinaryIO::BinaryRead(file, waypoint.camera.bias); } else if (path.pathType == PathType::Race) { - uint8_t unknown; - BinaryIO::BinaryRead(file, unknown); - BinaryIO::BinaryRead(file, unknown); - float unknown1; - BinaryIO::BinaryRead(file, unknown1); - BinaryIO::BinaryRead(file, unknown1); - BinaryIO::BinaryRead(file, unknown1); - } else if (path.pathType == PathType::Rail) { - float unknown; - BinaryIO::BinaryRead(file, unknown); - BinaryIO::BinaryRead(file, unknown); - BinaryIO::BinaryRead(file, unknown); - BinaryIO::BinaryRead(file, unknown); - if (path.pathVersion >= 17) { - BinaryIO::BinaryRead(file, unknown); - } + BinaryIO::BinaryRead(file, waypoint.racing.isResetNode); + BinaryIO::BinaryRead(file, waypoint.racing.isNonHorizontalCamera); + BinaryIO::BinaryRead(file, waypoint.racing.planeWidth); + BinaryIO::BinaryRead(file, waypoint.racing.planeHeight); + BinaryIO::BinaryRead(file, waypoint.racing.shortestDistanceToEnd); } // object LDF configs @@ -565,8 +526,14 @@ void Zone::LoadPath(std::istream& file) { BinaryIO::BinaryRead(file, character); value.push_back(character); } - LDFBaseData* ldfConfig = LDFBaseData::DataFromString(parameter + "=" + value); - waypoint.config.push_back(ldfConfig); + + LDFBaseData* ldfConfig = nullptr; + if (path.pathType == PathType::Movement) { + ldfConfig = LDFBaseData::DataFromString(parameter + "=0:" + value); + } else { + ldfConfig = LDFBaseData::DataFromString(parameter + "=" + value); + } + if (ldfConfig) waypoint.config.push_back(ldfConfig); } } diff --git a/dZoneManager/Zone.h b/dZoneManager/Zone.h index f041b616..0e7ae5eb 100644 --- a/dZoneManager/Zone.h +++ b/dZoneManager/Zone.h @@ -59,16 +59,32 @@ struct MovingPlatformPathWaypoint { struct CameraPathWaypoint { float time; + float fov; float tension; float continuity; float bias; }; +struct RacingPathWaypoint { + uint8_t isResetNode; + uint8_t isNonHorizontalCamera; + float planeWidth; + float planeHeight; + float shortestDistanceToEnd; +}; + +struct RailPathWaypoint { + float speed; + std::vector<LDFBaseData*> config; +}; + struct PathWaypoint { NiPoint3 position; NiQuaternion rotation; // not included in all, but it's more convenient here MovingPlatformPathWaypoint movingPlatform; CameraPathWaypoint camera; + RacingPathWaypoint racing; + RailPathWaypoint rail; std::vector<LDFBaseData*> config; }; @@ -89,6 +105,19 @@ enum class PathBehavior : uint32_t { Once = 2 }; +enum class PropertyPathType : int32_t { + Path = 0, + EntireZone = 1, + GenetatedRectangle = 2 +}; + +enum class PropertyType : int32_t{ + Premiere = 0, + Prize = 1, + LUP = 2, + Headspace = 3 +}; + enum class PropertyRentalTimeUnit : int32_t { Forever = 0, Seconds = 1, @@ -116,17 +145,19 @@ enum class PropertyAchievmentRequired : int32_t { struct MovingPlatformPath { std::string platformTravelSound; + uint8_t timeBasedMovement; }; struct PropertyPath { + PropertyPathType pathType; int32_t price; - int32_t rentalTime; + PropertyRentalTimeUnit rentalTimeUnit; uint64_t associatedZone; std::string displayName; std::string displayDesc; + PropertyType type; int32_t cloneLimit; float repMultiplier; - PropertyRentalTimeUnit rentalTimeUnit; PropertyAchievmentRequired achievementRequired; NiPoint3 playerZoneCoords; float maxBuildHeight; @@ -134,6 +165,7 @@ struct PropertyPath { struct CameraPath { std::string nextPath; + uint8_t rotatePlayer; }; struct SpawnerPath { @@ -150,6 +182,7 @@ struct Path { uint32_t pathVersion; PathType pathType; std::string pathName; + uint32_t flags; PathBehavior pathBehavior; uint32_t waypointCount; std::vector<PathWaypoint> pathWaypoints; @@ -219,9 +252,11 @@ private: std::map<LWOSCENEID, SceneRef, mapCompareLwoSceneIDs> m_Scenes; std::vector<SceneTransition> m_SceneTransitions; + uint32_t m_PathDataLength; - //std::vector<char> m_PathData; //Binary path data - std::vector<Path> m_Paths; + uint32_t m_PathChunkVersion; + std::vector<Path> m_Paths; + std::map<LWOSCENEID, uint32_t, mapCompareLwoSceneIDs> m_MapRevisions; //rhs is the revision! //private ("helper") functions: From 22e5d024009663723f98ca992af5b08f7acf4af1 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 12 Nov 2022 08:44:13 -0600 Subject: [PATCH 129/322] Use Property path name and desc when claiming (#827) --- .../dComponents/PropertyManagementComponent.cpp | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index 1e90e8db..d196e935 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -200,6 +200,16 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) { // If we are not on our clone do not allow us to claim the property if (propertyCloneId != playerCloneId) return false; + std::string name = zone->GetZoneName(); + std::string description = ""; + + auto prop_path = zone->GetPath(m_Parent->GetVarAsString(u"propertyName")); + + if (prop_path){ + if (!prop_path->property.displayName.empty()) name = prop_path->property.displayName; + description = prop_path->property.displayDesc; + } + SetOwnerId(playerId); propertyId = ObjectIDManager::GenerateRandomObjectID(); @@ -207,14 +217,15 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) { auto* insertion = Database::CreatePreppedStmt( "INSERT INTO properties" "(id, owner_id, template_id, clone_id, name, description, rent_amount, rent_due, privacy_option, last_updated, time_claimed, rejection_reason, reputation, zone_id, performance_cost)" - "VALUES (?, ?, ?, ?, ?, '', 0, 0, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), '', 0, ?, 0.0)" + "VALUES (?, ?, ?, ?, ?, ?, 0, 0, 0, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), '', 0, ?, 0.0)" ); insertion->setUInt64(1, propertyId); insertion->setUInt64(2, (uint32_t)playerId); insertion->setUInt(3, templateId); insertion->setUInt64(4, playerCloneId); - insertion->setString(5, zone->GetZoneName().c_str()); - insertion->setInt(6, propertyZoneId); + insertion->setString(5, name.c_str()); + insertion->setString(6, description.c_str()); + insertion->setInt(7, propertyZoneId); // Try and execute the query, print an error if it fails. try { From 7429902a646699013d94954556c00b015e71ccf8 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 12 Nov 2022 08:44:27 -0600 Subject: [PATCH 130/322] Prevent adding movingplatform components to all entites with an attached_path (#829) * Stop adding movingpla comps where they aren't needed * move stuff around to make it more congruent * invert if else block logic patter Since setting up the comp will be longer han just adding the path will make the readability flow better * address feedback --- dGame/Entity.cpp | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 52eddd06..62ac8bc2 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -317,15 +317,6 @@ void Entity::Initialize() { m_Components.insert(std::make_pair(COMPONENT_TYPE_SOUND_TRIGGER, comp)); } - //Check to see if we have a moving platform component: - //Which, for some reason didn't get added to the ComponentsRegistry so we have to check for a path manually here. - std::string attachedPath = GetVarAsString(u"attached_path"); - - if (!attachedPath.empty() || compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MOVING_PLATFORM, -1) != -1) { - MovingPlatformComponent* plat = new MovingPlatformComponent(this, attachedPath); - m_Components.insert(std::make_pair(COMPONENT_TYPE_MOVING_PLATFORM, plat)); - } - //Also check for the collectible id: m_CollectibleID = GetVarAs<int32_t>(u"collectible_id"); @@ -696,6 +687,26 @@ void Entity::Initialize() { m_Components.insert(std::make_pair(COMPONENT_TYPE_MOVEMENT_AI, new MovementAIComponent(this, moveInfo))); } + std::string pathName = GetVarAsString(u"attached_path"); + const Path* path = dZoneManager::Instance()->GetZone()->GetPath(pathName); + + //Check to see if we have an attached path and add the appropiate component to handle it: + if (path){ + // if we have a moving platform path, then we need a moving platform component + if (path->pathType == PathType::MovingPlatform) { + MovingPlatformComponent* plat = new MovingPlatformComponent(this, pathName); + m_Components.insert(std::make_pair(COMPONENT_TYPE_MOVING_PLATFORM, plat)); + // else if we are a movement path + } /*else if (path->pathType == PathType::Movement) { + auto movementAIcomp = GetComponent<MovementAIComponent>(); + if (movementAIcomp){ + // TODO: set path in existing movementAIComp + } else { + // TODO: create movementAIcomp and set path + } + }*/ + } + int proximityMonitorID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROXIMITY_MONITOR); if (proximityMonitorID > 0) { CDProximityMonitorComponentTable* proxCompTable = CDClientManager::Instance()->GetTable<CDProximityMonitorComponentTable>("ProximityMonitorComponent"); From 848c0669248c506e5b916f52b9fec436ac655548 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 12 Nov 2022 08:44:37 -0600 Subject: [PATCH 131/322] Not every scene has triggers, that is normal (#831) Quell the onslaught of meaningless logs --- dZoneManager/Zone.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index eb1d789a..3a1127a4 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -233,7 +233,8 @@ void Zone::LoadScene(std::istream& file) { scene.filename = BinaryIO::ReadString(file, sceneFilenameLength); std::string luTriggersPath = scene.filename.substr(0, scene.filename.size() - 4) + ".lutriggers"; - std::vector<LUTriggers::Trigger*> triggers = LoadLUTriggers(luTriggersPath, scene.id); + std::vector<LUTriggers::Trigger*> triggers; + if(Game::assetManager->HasFile(luTriggersPath.c_str())) triggers = LoadLUTriggers(luTriggersPath, scene.id); for (LUTriggers::Trigger* trigger : triggers) { scene.triggers.insert({ trigger->id, trigger }); From 53b559bef3407f6376bb61bfa4bf8c8cb70e5b73 Mon Sep 17 00:00:00 2001 From: Jonathan Romano <jonathan@luxaritas.com> Date: Mon, 14 Nov 2022 09:08:49 -0500 Subject: [PATCH 132/322] Make build script fail if any command fails (#832) --- build.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/build.sh b/build.sh index 4a476cc1..a736a4ee 100755 --- a/build.sh +++ b/build.sh @@ -1,3 +1,6 @@ +# Error if any command fails +set -e + # Create the build directory, preserving it if it already exists mkdir -p build cd build From 37524af549de353d89552ab7dd1f29576deb55de Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Mon, 14 Nov 2022 12:55:40 -0600 Subject: [PATCH 133/322] fix trigger loading (#838) Fixes #836 --- dZoneManager/Zone.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 3a1127a4..adf66dc9 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -234,7 +234,7 @@ void Zone::LoadScene(std::istream& file) { std::string luTriggersPath = scene.filename.substr(0, scene.filename.size() - 4) + ".lutriggers"; std::vector<LUTriggers::Trigger*> triggers; - if(Game::assetManager->HasFile(luTriggersPath.c_str())) triggers = LoadLUTriggers(luTriggersPath, scene.id); + if(Game::assetManager->HasFile((m_ZonePath + luTriggersPath).c_str())) triggers = LoadLUTriggers(luTriggersPath, scene.id); for (LUTriggers::Trigger* trigger : triggers) { scene.triggers.insert({ trigger->id, trigger }); From 3fa6ea4cea758e15f4590fbee38be0024b7fbe4a Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Mon, 14 Nov 2022 13:57:49 -0600 Subject: [PATCH 134/322] Fix ninjago crashes (#837) Fixed reading speed from rail paths Made the config of rail paths be read in sanely due to not having a type Fixes #835 --- dZoneManager/Zone.cpp | 4 +++- dZoneManager/Zone.h | 1 - 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index adf66dc9..ec73237e 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -504,6 +504,8 @@ void Zone::LoadPath(std::istream& file) { BinaryIO::BinaryRead(file, waypoint.racing.planeWidth); BinaryIO::BinaryRead(file, waypoint.racing.planeHeight); BinaryIO::BinaryRead(file, waypoint.racing.shortestDistanceToEnd); + } else if (path.pathType == PathType::Rail) { + if (path.pathVersion > 16) BinaryIO::BinaryRead(file, waypoint.rail.speed); } // object LDF configs @@ -529,7 +531,7 @@ void Zone::LoadPath(std::istream& file) { } LDFBaseData* ldfConfig = nullptr; - if (path.pathType == PathType::Movement) { + if (path.pathType == PathType::Movement || path.pathType == PathType::Rail) { ldfConfig = LDFBaseData::DataFromString(parameter + "=0:" + value); } else { ldfConfig = LDFBaseData::DataFromString(parameter + "=" + value); diff --git a/dZoneManager/Zone.h b/dZoneManager/Zone.h index 0e7ae5eb..978438aa 100644 --- a/dZoneManager/Zone.h +++ b/dZoneManager/Zone.h @@ -75,7 +75,6 @@ struct RacingPathWaypoint { struct RailPathWaypoint { float speed; - std::vector<LDFBaseData*> config; }; struct PathWaypoint { From 416021c2081e924fed3faca7202882a7d5aa8cf7 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 21 Nov 2022 14:18:01 -0800 Subject: [PATCH 135/322] Remove need for Avant Gardens Survival Client Fix This addresses the Avant Gardens Survival bug Does not conflict with clients that have the fix. --- README.md | 16 +++------------- dGame/dGameMessages/GameMessageHandler.cpp | 2 +- 2 files changed, 4 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index e588d341..87319c10 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ Some tools utilized to streamline the setup process require Python 3, make sure ### Choosing the right version for your client DLU clients identify themselves using a higher version number than the regular live clients out there. -This was done make sure that older and incomplete clients wouldn't produce false positive bug reports for us, and because we made bug fixes and new content for the client. +This was done make sure that older and incomplete clients wouldn't produce false positive bug reports for us, and because we made bug fixes and new content for the client. If you're using a DLU client you'll have to go into the "CMakeVariables.txt" file and change the NET_VERSION variable to 171023 to match the modified client's version number. @@ -173,7 +173,7 @@ Known good SHA256 checksums of the client: - `0d862f71eedcadc4494c4358261669721b40b2131101cbd6ef476c5a6ec6775b` (unpacked client, includes extra locales, rar compressed) Known good *SHA1* checksum of the DLU client: -- `91498e09b83ce69f46baf9e521d48f23fe502985` (packed client, zip compressed) +- `91498e09b83ce69f46baf9e521d48f23fe502985` (packed client, zip compressed) How to generate a SHA256 checksum: ```bash @@ -273,16 +273,6 @@ To connect to a server follow these steps: * Launch `legouniverse.exe`, through `wine` if on a Unix-like operating system * Note that if you are on WSL2, you will need to configure the public IP in the server and client to be the IP of the WSL2 instance and not localhost, which can be found by running `ifconfig` in the terminal. Windows defaults to WSL1, so this will not apply to most users. -### Survival - -The client script for the survival minigame has a bug in it which can cause the minigame to not load. To fix this, follow these instructions: -* Open `res/scripts/ai/minigame/survival/l_zone_survival_client.lua` -* Navigate to line `617` -* Change `PlayerReady(self)` to `onPlayerReady(self)` -* Save the file, overriding readonly mode if required - -If you still experience the bug, try deleting/renaming `res/pack/scripts.pk`. - ### Brick-By-Brick building Brick-By-Brick building requires `PATCHSERVERIP=0:` in the `boot.cfg` to point to a HTTP server which always returns `HTTP 404 - Not Found` for all requests. This can be achieved by pointing it to `localhost` while having `sudo python -m http.server 80` running in the background. @@ -340,7 +330,7 @@ Here is a summary of the commands available in-game. All commands are prefixed b /instanceinfo </td> <td> - Displays in the chat the current zone, clone, and instance id. + Displays in the chat the current zone, clone, and instance id. </td> <td> </td> diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 9cf09bbc..2ce79966 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -157,8 +157,8 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System Game::logger->Log("GameMessageHandler", "Player %s (%llu) loaded.", entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); // After we've done our thing, tell the client they're ready - GameMessages::SendPlayerReady(dZoneManager::Instance()->GetZoneControlObject(), sysAddr); GameMessages::SendPlayerReady(entity, sysAddr); + GameMessages::SendPlayerReady(dZoneManager::Instance()->GetZoneControlObject(), sysAddr); break; } From 9d62a8cd0bec17febc132c3b84f78b9e122687fd Mon Sep 17 00:00:00 2001 From: Demetri Van Sickle <demetriv.s.7@gmail.com> Date: Mon, 21 Nov 2022 14:19:37 -0800 Subject: [PATCH 136/322] Add backwards compatibility with servers using previous setup method * MasterServer will nolonger require cdclient.fdb * Added support for packed/unpacked clients not requiring .fdb file if .sqlite exsits --- dCommon/dClient/AssetManager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dCommon/dClient/AssetManager.cpp b/dCommon/dClient/AssetManager.cpp index 0cb2db31..349b5271 100644 --- a/dCommon/dClient/AssetManager.cpp +++ b/dCommon/dClient/AssetManager.cpp @@ -26,11 +26,11 @@ AssetManager::AssetManager(const std::string& path) { m_RootPath = (m_Path / ".." / ".."); m_ResPath = m_Path; - } else if (std::filesystem::exists(m_Path / "res" / "cdclient.fdb") && !std::filesystem::exists(m_Path / "res" / "pack")) { + } else if ((std::filesystem::exists(m_Path / "res" / "cdclient.fdb") || std::filesystem::exists(m_Path / "res" / "CDServer.sqlite")) && !std::filesystem::exists(m_Path / "res" / "pack")) { m_AssetBundleType = eAssetBundleType::Unpacked; m_ResPath = (m_Path / "res"); - } else if (std::filesystem::exists(m_Path / "cdclient.fdb") && !std::filesystem::exists(m_Path / "pack")) { + } else if ((std::filesystem::exists(m_Path / "cdclient.fdb") || std::filesystem::exists(m_Path / "CDServer.sqlite")) && !std::filesystem::exists(m_Path / "pack")) { m_AssetBundleType = eAssetBundleType::Unpacked; m_ResPath = m_Path; From b17ba56af17f42f47dafdfbe56913caabf49c450 Mon Sep 17 00:00:00 2001 From: Nico Mexis <nico.mexis@kabelmail.de> Date: Wed, 23 Nov 2022 19:50:45 +0100 Subject: [PATCH 137/322] Update workflow actions (#844) --- .github/workflows/build-and-test.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 8f65fd8e..ab3917c1 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -16,7 +16,7 @@ jobs: os: [ windows-2022, ubuntu-20.04, macos-11 ] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 with: submodules: true - name: Add msbuild to PATH (Windows only) @@ -35,7 +35,7 @@ jobs: buildPreset: "ci-${{matrix.os}}" testPreset: "ci-${{matrix.os}}" - name: artifacts - uses: actions/upload-artifact@v2 + uses: actions/upload-artifact@v3 if: ${{ github.ref == 'ref/head/main' }} with: name: build-${{matrix.os}} From afb97a81b5001272a2b9510c993bf79a63e81a86 Mon Sep 17 00:00:00 2001 From: Jonathan Romano <jonathan@luxaritas.com> Date: Fri, 25 Nov 2022 20:28:20 -0500 Subject: [PATCH 138/322] Address Mac CI using specific versions of OpenSSL Corrected CI to use the version brew links in opt rather than the specific version in Cellar --- CMakePresets.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakePresets.json b/CMakePresets.json index 15eb729e..3968b3ce 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -25,7 +25,7 @@ "description": "Same as default, Used in GitHub actions workflow", "inherits": "default", "cacheVariables": { - "OPENSSL_ROOT_DIR": "/usr/local/Cellar/openssl@3/3.0.5/" + "OPENSSL_ROOT_DIR": "/usr/local/opt/openssl@3/" } }, { From 4569f621007cdd70e1b45c6141e8fba173cd0fb4 Mon Sep 17 00:00:00 2001 From: Jonathan Romano <jonathan@luxaritas.com> Date: Sat, 26 Nov 2022 05:29:53 -0500 Subject: [PATCH 139/322] Fix three-part names coming across as INVALID with custom client path --- dGame/UserManager.cpp | 49 +++++++++++++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 16 deletions(-) diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index 7da26b9a..f3fd78c4 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -20,6 +20,7 @@ #include "Entity.h" #include "EntityManager.h" #include "SkillComponent.h" +#include "AssetManager.h" UserManager* UserManager::m_Address = nullptr; @@ -32,43 +33,59 @@ inline void StripCR(std::string& str) { } void UserManager::Initialize() { - std::string firstNamePath = "./res/names/minifigname_first.txt"; - std::string middleNamePath = "./res/names/minifigname_middle.txt"; - std::string lastNamePath = "./res/names/minifigname_last.txt"; std::string line; - std::fstream fnFile(firstNamePath, std::ios::in); - std::fstream mnFile(middleNamePath, std::ios::in); - std::fstream lnFile(lastNamePath, std::ios::in); - - while (std::getline(fnFile, line, '\n')) { + AssetMemoryBuffer fnBuff = Game::assetManager->GetFileAsBuffer("names/minifigname_first.txt"); + if (!fnBuff.m_Success) { + Game::logger->Log("UserManager", "Failed to load %s", (Game::assetManager->GetResPath() / "names/minifigname_first.txt").string().c_str()); + throw std::runtime_error("Aborting initialization due to missing minifigure name file."); + } + std::istream fnStream = std::istream(&fnBuff); + while (std::getline(fnStream, line, '\n')) { std::string name = line; StripCR(name); m_FirstNames.push_back(name); } + fnBuff.close(); - while (std::getline(mnFile, line, '\n')) { + AssetMemoryBuffer mnBuff = Game::assetManager->GetFileAsBuffer("names/minifigname_middle.txt"); + if (!mnBuff.m_Success) { + Game::logger->Log("UserManager", "Failed to load %s", (Game::assetManager->GetResPath() / "names/minifigname_middle.txt").string().c_str()); + throw std::runtime_error("Aborting initialization due to missing minifigure name file."); + } + std::istream mnStream = std::istream(&mnBuff); + while (std::getline(mnStream, line, '\n')) { std::string name = line; StripCR(name); m_MiddleNames.push_back(name); } + mnBuff.close(); - while (std::getline(lnFile, line, '\n')) { + AssetMemoryBuffer lnBuff = Game::assetManager->GetFileAsBuffer("names/minifigname_last.txt"); + if (!lnBuff.m_Success) { + Game::logger->Log("UserManager", "Failed to load %s", (Game::assetManager->GetResPath() / "names/minifigname_last.txt").string().c_str()); + throw std::runtime_error("Aborting initialization due to missing minifigure name file."); + } + std::istream lnStream = std::istream(&lnBuff); + while (std::getline(lnStream, line, '\n')) { std::string name = line; StripCR(name); m_LastNames.push_back(name); } - - fnFile.close(); - mnFile.close(); - lnFile.close(); + lnBuff.close(); //Load our pre-approved names: - std::fstream chatList("./res/chatplus_en_us.txt", std::ios::in); - while (std::getline(chatList, line, '\n')) { + AssetMemoryBuffer chatListBuff = Game::assetManager->GetFileAsBuffer("chatplus_en_us.txt"); + if (!chatListBuff.m_Success) { + Game::logger->Log("UserManager", "Failed to load %s", (Game::assetManager->GetResPath() / "names/chatplus_en_us.txt").string().c_str()); + throw std::runtime_error("Aborting initialization due to missing chat whitelist file."); + } + std::istream chatListStream = std::istream(&chatListBuff); + while (std::getline(chatListStream, line, '\n')) { StripCR(line); m_PreapprovedNames.push_back(line); } + chatListBuff.close(); } UserManager::~UserManager() { From 36eecd693dde89979d4ab2ddb785ba82b4d87b4e Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 26 Nov 2022 03:30:53 -0700 Subject: [PATCH 140/322] Brick stack sizes are now unlimited Make brick stacks unlimited as they were in live. If you have more than uint32_max bricks, the extra bricks are trashed. --- dGame/dComponents/InventoryComponent.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 930ace8d..12b6792e 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -211,7 +211,7 @@ void InventoryComponent::AddItem( // info.itemType of 1 is item type brick if (inventoryType == eInventoryType::BRICKS || (stack == 0 && info.itemType == 1)) { - stack = 999; + stack = UINT32_MAX; } else if (stack == 0) { stack = 1; } @@ -232,7 +232,8 @@ void InventoryComponent::AddItem( } } - while (left > 0) { + // If we have some leftover and we aren't bricks, make a new stack + while (left > 0 && !(inventoryType == eInventoryType::BRICKS || (stack == 0 && info.itemType == 1))) { const auto size = std::min(left, stack); left -= size; From e2616c5f11ca6057ded4e5740b036e0c32a76e2e Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 26 Nov 2022 14:22:00 -0800 Subject: [PATCH 141/322] Move enums to a single directory A technical change to move all emum files to a single directory --- CMakeLists.txt | 3 ++- dCommon/{ => dEnums}/AddFriendResponseCode.h | 0 dCommon/{ => dEnums}/AddFriendResponseType.h | 0 .../dInventory => dCommon/dEnums}/ItemSetPassiveAbilityID.h | 0 {dGame/dMission => dCommon/dEnums}/MissionLockState.h | 0 {dGame/dMission => dCommon/dEnums}/MissionState.h | 0 {dGame/dMission => dCommon/dEnums}/MissionTaskType.h | 0 {dGame/dMission => dCommon/dEnums}/RacingTaskParam.h | 0 dCommon/{ => dEnums}/dCommonVars.h | 5 +++++ {dNet => dCommon/dEnums}/dMessageIdentifiers.h | 0 dCommon/{ => dEnums}/dPlatforms.h | 0 {dPhysics => dCommon/dEnums}/dpCollisionGroups.h | 0 {dPhysics => dCommon/dEnums}/dpCommon.h | 0 dCommon/{ => dEnums}/eAninmationFlags.h | 0 dCommon/{ => dEnums}/eItemType.h | 0 dCommon/{ => dEnums}/eUnequippableActiveType.h | 0 16 files changed, 7 insertions(+), 1 deletion(-) rename dCommon/{ => dEnums}/AddFriendResponseCode.h (100%) rename dCommon/{ => dEnums}/AddFriendResponseType.h (100%) rename {dGame/dInventory => dCommon/dEnums}/ItemSetPassiveAbilityID.h (100%) rename {dGame/dMission => dCommon/dEnums}/MissionLockState.h (100%) rename {dGame/dMission => dCommon/dEnums}/MissionState.h (100%) rename {dGame/dMission => dCommon/dEnums}/MissionTaskType.h (100%) rename {dGame/dMission => dCommon/dEnums}/RacingTaskParam.h (100%) rename dCommon/{ => dEnums}/dCommonVars.h (99%) rename {dNet => dCommon/dEnums}/dMessageIdentifiers.h (100%) rename dCommon/{ => dEnums}/dPlatforms.h (100%) rename {dPhysics => dCommon/dEnums}/dpCollisionGroups.h (100%) rename {dPhysics => dCommon/dEnums}/dpCommon.h (100%) rename dCommon/{ => dEnums}/eAninmationFlags.h (100%) rename dCommon/{ => dEnums}/eItemType.h (100%) rename dCommon/{ => dEnums}/eUnequippableActiveType.h (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7dfef867..644fc383 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -155,6 +155,8 @@ endforeach() # Create our list of include directories set(INCLUDED_DIRECTORIES "dCommon" + "dCommon/dClient" + "dCommon/dEnums" "dChatFilter" "dGame" "dGame/dBehaviors" @@ -165,7 +167,6 @@ set(INCLUDED_DIRECTORIES "dGame/dEntity" "dGame/dPropertyBehaviors" "dGame/dUtilities" - "dCommon/dClient" "dPhysics" "dNavigation" "dNavigation/dTerrain" diff --git a/dCommon/AddFriendResponseCode.h b/dCommon/dEnums/AddFriendResponseCode.h similarity index 100% rename from dCommon/AddFriendResponseCode.h rename to dCommon/dEnums/AddFriendResponseCode.h diff --git a/dCommon/AddFriendResponseType.h b/dCommon/dEnums/AddFriendResponseType.h similarity index 100% rename from dCommon/AddFriendResponseType.h rename to dCommon/dEnums/AddFriendResponseType.h diff --git a/dGame/dInventory/ItemSetPassiveAbilityID.h b/dCommon/dEnums/ItemSetPassiveAbilityID.h similarity index 100% rename from dGame/dInventory/ItemSetPassiveAbilityID.h rename to dCommon/dEnums/ItemSetPassiveAbilityID.h diff --git a/dGame/dMission/MissionLockState.h b/dCommon/dEnums/MissionLockState.h similarity index 100% rename from dGame/dMission/MissionLockState.h rename to dCommon/dEnums/MissionLockState.h diff --git a/dGame/dMission/MissionState.h b/dCommon/dEnums/MissionState.h similarity index 100% rename from dGame/dMission/MissionState.h rename to dCommon/dEnums/MissionState.h diff --git a/dGame/dMission/MissionTaskType.h b/dCommon/dEnums/MissionTaskType.h similarity index 100% rename from dGame/dMission/MissionTaskType.h rename to dCommon/dEnums/MissionTaskType.h diff --git a/dGame/dMission/RacingTaskParam.h b/dCommon/dEnums/RacingTaskParam.h similarity index 100% rename from dGame/dMission/RacingTaskParam.h rename to dCommon/dEnums/RacingTaskParam.h diff --git a/dCommon/dCommonVars.h b/dCommon/dEnums/dCommonVars.h similarity index 99% rename from dCommon/dCommonVars.h rename to dCommon/dEnums/dCommonVars.h index 4c0e15fa..41d6cb67 100644 --- a/dCommon/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -1,5 +1,8 @@ #pragma once +#ifndef __DCOMMONVARS__H__ +#define __DCOMMONVARS__H__ + #include <cstdint> #include <string> #include <set> @@ -648,3 +651,5 @@ inline T const& clamp(const T& val, const T& low, const T& high) { return val; } + +#endif //!__DCOMMONVARS__H__ diff --git a/dNet/dMessageIdentifiers.h b/dCommon/dEnums/dMessageIdentifiers.h similarity index 100% rename from dNet/dMessageIdentifiers.h rename to dCommon/dEnums/dMessageIdentifiers.h diff --git a/dCommon/dPlatforms.h b/dCommon/dEnums/dPlatforms.h similarity index 100% rename from dCommon/dPlatforms.h rename to dCommon/dEnums/dPlatforms.h diff --git a/dPhysics/dpCollisionGroups.h b/dCommon/dEnums/dpCollisionGroups.h similarity index 100% rename from dPhysics/dpCollisionGroups.h rename to dCommon/dEnums/dpCollisionGroups.h diff --git a/dPhysics/dpCommon.h b/dCommon/dEnums/dpCommon.h similarity index 100% rename from dPhysics/dpCommon.h rename to dCommon/dEnums/dpCommon.h diff --git a/dCommon/eAninmationFlags.h b/dCommon/dEnums/eAninmationFlags.h similarity index 100% rename from dCommon/eAninmationFlags.h rename to dCommon/dEnums/eAninmationFlags.h diff --git a/dCommon/eItemType.h b/dCommon/dEnums/eItemType.h similarity index 100% rename from dCommon/eItemType.h rename to dCommon/dEnums/eItemType.h diff --git a/dCommon/eUnequippableActiveType.h b/dCommon/dEnums/eUnequippableActiveType.h similarity index 100% rename from dCommon/eUnequippableActiveType.h rename to dCommon/dEnums/eUnequippableActiveType.h From af28d170fbd394f560c077365d161566402e797c Mon Sep 17 00:00:00 2001 From: Jonathan Romano <jonathan@luxaritas.com> Date: Sun, 27 Nov 2022 04:06:17 -0500 Subject: [PATCH 142/322] Fix chat whitelist path in UserManager error log (#853) --- dGame/UserManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index f3fd78c4..ddbad03a 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -77,7 +77,7 @@ void UserManager::Initialize() { //Load our pre-approved names: AssetMemoryBuffer chatListBuff = Game::assetManager->GetFileAsBuffer("chatplus_en_us.txt"); if (!chatListBuff.m_Success) { - Game::logger->Log("UserManager", "Failed to load %s", (Game::assetManager->GetResPath() / "names/chatplus_en_us.txt").string().c_str()); + Game::logger->Log("UserManager", "Failed to load %s", (Game::assetManager->GetResPath() / "chatplus_en_us.txt").string().c_str()); throw std::runtime_error("Aborting initialization due to missing chat whitelist file."); } std::istream chatListStream = std::istream(&chatListBuff); From e40a597f1854bd315953a90c572d74c6d42fc880 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 27 Nov 2022 01:24:35 -0800 Subject: [PATCH 143/322] Property Behavior deserialize definitions (#812) * Implement basic functionality Implements the basic functionality and parsing of property behaviors. Unhandled messages and logged and discarded for the time being. The only implemented message is a basic one that sends the needed info the the client side User Interface to pop up. --- dCommon/dEnums/dCommonVars.h | 2 + dGame/dPropertyBehaviors/BehaviorStates.h | 20 + dGame/dPropertyBehaviors/ControlBehaviors.cpp | 600 ++++++++++++++++-- dGame/dPropertyBehaviors/ControlBehaviors.h | 10 +- 4 files changed, 583 insertions(+), 49 deletions(-) create mode 100644 dGame/dPropertyBehaviors/BehaviorStates.h diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index 41d6cb67..005d7205 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -33,6 +33,8 @@ 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; +typedef uint32_t BEHAVIORSTATE; typedef int32_t PetTamingPiece; //!< Pet Taming Pieces diff --git a/dGame/dPropertyBehaviors/BehaviorStates.h b/dGame/dPropertyBehaviors/BehaviorStates.h new file mode 100644 index 00000000..e09e45ba --- /dev/null +++ b/dGame/dPropertyBehaviors/BehaviorStates.h @@ -0,0 +1,20 @@ +#pragma once + +#ifndef __BEHAVIORSTATES__H__ +#define __BEHAVIORSTATES__H__ + +#include <string> +#include <cstdint> + +#include "dCommonVars.h" + +enum States : BEHAVIORSTATE { + HOME_STATE = 0, //!< The HOME behavior state + CIRCLE_STATE, //!< The CIRCLE behavior state + SQUARE_STATE, //!< The SQUARE behavior state + DIAMOND_STATE, //!< The DIAMOND behavior state + TRIANGLE_STATE, //!< The TRIANGLE behavior state + STAR_STATE //!< The STAR behavior state +}; + +#endif //!__BEHAVIORSTATES__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.cpp b/dGame/dPropertyBehaviors/ControlBehaviors.cpp index 4e922ee0..d5b71a3a 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviors.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviors.cpp @@ -5,50 +5,67 @@ #include "Game.h" #include "GameMessages.h" #include "ModelComponent.h" +#include "../../dWorldServer/ObjectIDManager.h" #include "dLogger.h" -void ControlBehaviors::ProcessCommand(Entity* modelEntity, const SystemAddress& sysAddr, AMFArrayValue* arguments, std::string command, Entity* modelOwner) { - if (!modelEntity || !modelOwner || !arguments) return; +uint32_t GetBehaviorIDFromArgument(AMFArrayValue* arguments, const std::string& key = "BehaviorID") { + auto* behaviorIDValue = arguments->FindValue<AMFStringValue>(key); + uint32_t behaviorID = -1; - if (command == "sendBehaviorListToClient") - SendBehaviorListToClient(modelEntity, sysAddr, modelOwner); - else if (command == "modelTypeChanged") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "toggleExecutionUpdates") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "addStrip") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "removeStrip") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "mergeStrips") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "splitStrip") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "updateStripUI") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "addAction") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "migrateActions") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "rearrangeStrip") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "add") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "removeActions") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "rename") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "sendBehaviorBlocksToClient") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "moveToInventory") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else if (command == "updateAction") - Game::logger->Log("ControlBehaviors", "Got command %s but is not implemented!", command.c_str()); - else - Game::logger->Log("ControlBehaviors", "Unknown behavior command (%s)\n", command.c_str()); + if (behaviorIDValue) { + behaviorID = std::stoul(behaviorIDValue->GetStringValue()); + } else if (arguments->FindValue<AMFUndefinedValue>(key) == nullptr){ + throw std::invalid_argument("Unable to find behavior ID from argument \"" + key + "\""); + } + + return behaviorID; } -void ControlBehaviors::SendBehaviorListToClient( +BEHAVIORSTATE GetBehaviorStateFromArgument(AMFArrayValue* arguments, const std::string& key = "stateID") { + auto* stateIDValue = arguments->FindValue<AMFDoubleValue>(key); + if (!stateIDValue) throw std::invalid_argument("Unable to find behavior state from argument \"" + key + "\""); + + BEHAVIORSTATE stateID = static_cast<BEHAVIORSTATE>(stateIDValue->GetDoubleValue()); + + return stateID; +} + +STRIPID GetStripIDFromArgument(AMFArrayValue* arguments, const std::string& key = "stripID") { + auto* stripIDValue = arguments->FindValue<AMFDoubleValue>(key); + if (!stripIDValue) throw std::invalid_argument("Unable to find strip ID from argument \"" + key + "\""); + + STRIPID stripID = static_cast<STRIPID>(stripIDValue->GetDoubleValue()); + + return stripID; +} + +void RequestUpdatedID(int32_t behaviorID, ModelComponent* modelComponent, Entity* modelOwner, const SystemAddress& sysAddr) { + // auto behavior = modelComponent->FindBehavior(behaviorID); + // if (behavior->GetBehaviorID() == -1 || behavior->GetShouldSetNewID()) { + // ObjectIDManager::Instance()->RequestPersistentID( + // [behaviorID, behavior, modelComponent, modelOwner, sysAddr](uint32_t persistentId) { + // behavior->SetShouldGetNewID(false); + // behavior->SetIsTemplated(false); + // behavior->SetBehaviorID(persistentId); + + // // This updates the behavior ID of the behavior should this be a new behavior + // AMFArrayValue args; + + // AMFStringValue* behaviorIDString = new AMFStringValue(); + // behaviorIDString->SetStringValue(std::to_string(persistentId)); + // args.InsertValue("behaviorID", behaviorIDString); + + // AMFStringValue* objectIDAsString = new AMFStringValue(); + // objectIDAsString->SetStringValue(std::to_string(modelComponent->GetParent()->GetObjectID())); + // args.InsertValue("objectID", objectIDAsString); + + // GameMessages::SendUIMessageServerToSingleClient(modelOwner, sysAddr, "UpdateBehaviorID", &args); + // ControlBehaviors::SendBehaviorListToClient(modelComponent->GetParent(), sysAddr, modelOwner); + // }); + // } +} + +void SendBehaviorListToClient( Entity* modelEntity, const SystemAddress& sysAddr, Entity* modelOwner @@ -57,7 +74,7 @@ void ControlBehaviors::SendBehaviorListToClient( if (!modelComponent) return; - AMFArrayValue behaviorsToSerialize; + AMFArrayValue behaviorsToSerialize; AMFArrayValue* behaviors = new AMFArrayValue(); // Empty for now @@ -79,3 +96,506 @@ void ControlBehaviors::SendBehaviorListToClient( behaviorsToSerialize.InsertValue("objectID", amfStringValueForObjectID); GameMessages::SendUIMessageServerToSingleClient(modelOwner, sysAddr, "UpdateBehaviorList", &behaviorsToSerialize); } + +void ModelTypeChanged(AMFArrayValue* arguments, ModelComponent* ModelComponent) { + auto* modelTypeAmf = arguments->FindValue<AMFDoubleValue>("ModelType"); + if (!modelTypeAmf) return; + + uint32_t modelType = static_cast<uint32_t>(modelTypeAmf->GetDoubleValue()); + + //TODO Update the model type here +} + +void ToggleExecutionUpdates() { + //TODO do something with this info +} + +void AddStrip(AMFArrayValue* arguments) { + auto* strip = arguments->FindValue<AMFArrayValue>("strip"); + if (!strip) return; + + auto* actions = strip->FindValue<AMFArrayValue>("actions"); + if (!actions) return; + + auto* uiArray = arguments->FindValue<AMFArrayValue>("ui"); + if (!uiArray) return; + + auto* xPositionValue = uiArray->FindValue<AMFDoubleValue>("x"); + if (!xPositionValue) return; + + double xPosition = xPositionValue->GetDoubleValue(); + + auto* yPositionValue = uiArray->FindValue<AMFDoubleValue>("y"); + if (!yPositionValue) return; + + double yPosition = yPositionValue->GetDoubleValue(); + + STRIPID stripID = GetStripIDFromArgument(arguments); + + BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); + + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + std::string type = ""; + std::string valueParameterName = ""; + std::string valueParameterString = ""; + double valueParameterDouble = 0.0; + for (uint32_t position = 0; position < actions->GetDenseValueSize(); position++) { + auto* actionAsArray = actions->GetValueAt<AMFArrayValue>(position); + if (!actionAsArray) continue; + + for (auto& typeValueMap : actionAsArray->GetAssociativeMap()) { + if (typeValueMap.first == "Type") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + + type = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + valueParameterName = typeValueMap.first; + // Message is the only known string parameter + if (valueParameterName == "Message") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + valueParameterString = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFDouble) continue; + valueParameterDouble = static_cast<AMFDoubleValue*>(typeValueMap.second)->GetDoubleValue(); + } + } + } + // modelComponent->AddStrip(stateID, stripID, type, behaviorID, valueParameterName, valueParameterString, valueParameterDouble, "", xPosition, yPosition); + type.clear(); + valueParameterName.clear(); + valueParameterString.clear(); + valueParameterDouble = 0.0; + } + // RequestUpdatedID(behaviorID); +} + +void RemoveStrip(AMFArrayValue* arguments) { + STRIPID stripID = GetStripIDFromArgument(arguments); + + BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); + + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + // modelComponent->RemoveStrip(stateID, stripID, behaviorID); + + // RequestUpdatedID(behaviorID); +} + +void MergeStrips(AMFArrayValue* arguments) { + STRIPID srcStripID = GetStripIDFromArgument(arguments, "srcStripID"); + + BEHAVIORSTATE dstStateID = GetBehaviorStateFromArgument(arguments, "dstStateID"); + + BEHAVIORSTATE srcStateID = GetBehaviorStateFromArgument(arguments, "srcStateID"); + + auto* dstActionIndexValue = arguments->FindValue<AMFDoubleValue>("dstActionIndex"); + if (!dstActionIndexValue) return; + + uint32_t dstActionIndex = static_cast<uint32_t>(dstActionIndexValue->GetDoubleValue()); + + STRIPID dstStripID = GetStripIDFromArgument(arguments, "dstStripID"); + + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + // modelComponent->MergeStrips(srcStripID, dstStripID, srcStateID, dstStateID, behaviorID, dstActionIndex); + + // RequestUpdatedID(behaviorID); +} + +void SplitStrip(AMFArrayValue* arguments) { + auto* srcActionIndexValue = arguments->FindValue<AMFDoubleValue>("srcActionIndex"); + if (!srcActionIndexValue) return; + + uint32_t srcActionIndex = static_cast<uint32_t>(srcActionIndexValue->GetDoubleValue()); + + STRIPID srcStripID = GetStripIDFromArgument(arguments, "srcStripID"); + + BEHAVIORSTATE srcStateID = GetBehaviorStateFromArgument(arguments, "srcStateID"); + + STRIPID dstStripID = GetStripIDFromArgument(arguments, "dstStripID"); + + BEHAVIORSTATE dstStateID = GetBehaviorStateFromArgument(arguments, "dstStateID"); + + auto* dstStripUIArray = arguments->FindValue<AMFArrayValue>("dstStripUI"); + if (!dstStripUIArray) return; + + auto* xPositionValue = dstStripUIArray->FindValue<AMFDoubleValue>("x"); + auto* yPositionValue = dstStripUIArray->FindValue<AMFDoubleValue>("y"); + if (!xPositionValue || !yPositionValue) return; + + // x and y position 15 are just where the game puts the strip by default if none is given. + double yPosition = yPositionValue->GetDoubleValue(); + double xPosition = xPositionValue->GetDoubleValue(); + + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + // modelComponent->SplitStrip(srcActionIndex, srcStripID, srcStateID, dstStripID, dstStateID, behaviorID, yPosition, xPosition); + + // RequestUpdatedID(behaviorID); +} + +void UpdateStripUI(AMFArrayValue* arguments) { + auto* uiArray = arguments->FindValue<AMFArrayValue>("ui"); + if (!uiArray) return; + + auto* xPositionValue = uiArray->FindValue<AMFDoubleValue>("x"); + auto* yPositionValue = uiArray->FindValue<AMFDoubleValue>("y"); + if (!xPositionValue || !yPositionValue) return; + + double yPosition = yPositionValue->GetDoubleValue(); + double xPosition = xPositionValue->GetDoubleValue(); + + STRIPID stripID = GetStripIDFromArgument(arguments); + + BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); + + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + // modelComponent->UpdateUIOfStrip(stateID, stripID, xPosition, yPosition, behaviorID); + + // RequestUpdatedID(behaviorID); +} + +void AddAction(AMFArrayValue* arguments) { + auto* actionIndexAmf = arguments->FindValue<AMFDoubleValue>("actionIndex"); + if (!actionIndexAmf) return; + + uint32_t actionIndex = static_cast<uint32_t>(actionIndexAmf->GetDoubleValue()); + + STRIPID stripID = GetStripIDFromArgument(arguments); + + BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); + + std::string type = ""; + std::string valueParameterName = ""; + std::string valueParameterString = ""; + double valueParameterDouble = 0.0; + auto* action = arguments->FindValue<AMFArrayValue>("action"); + if (!action) return; + + for (auto& typeValueMap : action->GetAssociativeMap()) { + if (typeValueMap.first == "Type") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + type = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + valueParameterName = typeValueMap.first; + // Message is the only known string parameter + if (valueParameterName == "Message") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + valueParameterString = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFDouble) continue; + valueParameterDouble = static_cast<AMFDoubleValue*>(typeValueMap.second)->GetDoubleValue(); + } + } + } + + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + // modelComponent->AddAction(stateID, stripID, type, valueParameterName, valueParameterString, valueParameterDouble, "", actionIndex, behaviorID); + + // RequestUpdatedID(behaviorID); +} + +void MigrateActions(AMFArrayValue* arguments) { + auto* srcActionIndexAmf = arguments->FindValue<AMFDoubleValue>("srcActionIndex"); + if (!srcActionIndexAmf) return; + + uint32_t srcActionIndex = static_cast<uint32_t>(srcActionIndexAmf->GetDoubleValue()); + + STRIPID srcStripID = GetStripIDFromArgument(arguments, "srcStripID"); + + BEHAVIORSTATE srcStateID = GetBehaviorStateFromArgument(arguments, "srcStateID"); + + auto* dstActionIndexAmf = arguments->FindValue<AMFDoubleValue>("dstActionIndex"); + if (!dstActionIndexAmf) return; + + uint32_t dstActionIndex = static_cast<uint32_t>(dstActionIndexAmf->GetDoubleValue()); + + STRIPID dstStripID = GetStripIDFromArgument(arguments, "dstStripID"); + + BEHAVIORSTATE dstStateID = GetBehaviorStateFromArgument(arguments, "dstStateID"); + + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + // modelComponent->MigrateActions(srcActionIndex, srcStripID, srcStateID, dstActionIndex, dstStripID, dstStateID, behaviorID); + + // RequestUpdatedID(behaviorID); +} + +void RearrangeStrip(AMFArrayValue* arguments) { + auto* srcActionIndexValue = arguments->FindValue<AMFDoubleValue>("srcActionIndex"); + uint32_t srcActionIndex = static_cast<uint32_t>(srcActionIndexValue->GetDoubleValue()); + + uint32_t stripID = GetStripIDFromArgument(arguments); + + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + auto* dstActionIndexValue = arguments->FindValue<AMFDoubleValue>("dstActionIndex"); + uint32_t dstActionIndex = static_cast<uint32_t>(dstActionIndexValue->GetDoubleValue()); + + BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); + + // modelComponent->RearrangeStrip(stateID, stripID, srcActionIndex, dstActionIndex, behaviorID); + + // RequestUpdatedID(behaviorID); +} + +void Add(AMFArrayValue* arguments) { + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + uint32_t behaviorIndex = 0; + auto* behaviorIndexAmf = arguments->FindValue<AMFDoubleValue>("BehaviorIndex"); + + if (!behaviorIndexAmf) return; + + behaviorIndex = static_cast<uint32_t>(behaviorIndexAmf->GetDoubleValue()); + + // modelComponent->AddBehavior(behaviorID, behaviorIndex, modelOwner); + + // SendBehaviorListToClient(); +} + +void RemoveActions(AMFArrayValue* arguments) { + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + auto* actionIndexAmf = arguments->FindValue<AMFDoubleValue>("actionIndex"); + if (!actionIndexAmf) return; + + uint32_t actionIndex = static_cast<uint32_t>(actionIndexAmf->GetDoubleValue()); + + STRIPID stripID = GetStripIDFromArgument(arguments); + + BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); + + // modelComponent->RemoveAction(stateID, stripID, actionIndex, behaviorID); + + // RequestUpdatedID(behaviorID); +} + +void Rename(Entity* modelEntity, const SystemAddress& sysAddr, Entity* modelOwner, AMFArrayValue* arguments) { + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + auto* nameAmf = arguments->FindValue<AMFStringValue>("Name"); + if (!nameAmf) return; + + auto name = nameAmf->GetStringValue(); + + // modelComponent->Rename(behaviorID, name); + + SendBehaviorListToClient(modelEntity, sysAddr, modelOwner); + + // RequestUpdatedID(behaviorID); +} + +// TODO This is also supposed to serialize the state of the behaviors in progress but those aren't implemented yet +void SendBehaviorBlocksToClient(ModelComponent* modelComponent, const SystemAddress& sysAddr, Entity* modelOwner, AMFArrayValue* arguments) { + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + // auto modelBehavior = modelComponent->FindBehavior(behaviorID); + + // if (!modelBehavior) return; + + // modelBehavior->VerifyStates(); + + // auto states = modelBehavior->GetBehaviorStates(); + + // // Begin serialization. + + // /** + // * for each state + // * strip id + // * ui info + // * x + // * y + // * actions + // * action1 + // * action2 + // * ... + // * behaviorID of strip + // * objectID of strip + // */ + // LWOOBJID targetObjectID = LWOOBJID_EMPTY; + // behaviorID = 0; + // AMFArrayValue behaviorInfo; + + // AMFArrayValue* stateSerialize = new AMFArrayValue(); + + // for (auto it = states.begin(); it != states.end(); it++) { + // Game::logger->Log("PropertyBehaviors", "Begin serialization of state %i!\n", it->first); + // AMFArrayValue* state = new AMFArrayValue(); + + // AMFDoubleValue* stateAsDouble = new AMFDoubleValue(); + // stateAsDouble->SetDoubleValue(it->first); + // state->InsertValue("id", stateAsDouble); + + // AMFArrayValue* strips = new AMFArrayValue(); + // auto stripsInState = it->second->GetStrips(); + // for (auto strip = stripsInState.begin(); strip != stripsInState.end(); strip++) { + // Game::logger->Log("PropertyBehaviors", "Begin serialization of strip %i!\n", strip->first); + // AMFArrayValue* thisStrip = new AMFArrayValue(); + + // AMFDoubleValue* stripID = new AMFDoubleValue(); + // stripID->SetDoubleValue(strip->first); + // thisStrip->InsertValue("id", stripID); + + // AMFArrayValue* uiArray = new AMFArrayValue(); + // AMFDoubleValue* yPosition = new AMFDoubleValue(); + // yPosition->SetDoubleValue(strip->second->GetYPosition()); + // uiArray->InsertValue("y", yPosition); + + // AMFDoubleValue* xPosition = new AMFDoubleValue(); + // xPosition->SetDoubleValue(strip->second->GetXPosition()); + // uiArray->InsertValue("x", xPosition); + + // thisStrip->InsertValue("ui", uiArray); + // targetObjectID = modelComponent->GetParent()->GetObjectID(); + // behaviorID = modelBehavior->GetBehaviorID(); + + // AMFArrayValue* stripSerialize = new AMFArrayValue(); + // for (auto behaviorAction : strip->second->GetActions()) { + // Game::logger->Log("PropertyBehaviors", "Begin serialization of action %s!\n", behaviorAction->actionName.c_str()); + // AMFArrayValue* thisAction = new AMFArrayValue(); + + // AMFStringValue* actionName = new AMFStringValue(); + // actionName->SetStringValue(behaviorAction->actionName); + // thisAction->InsertValue("Type", actionName); + + // if (behaviorAction->parameterValueString != "") + // { + // AMFStringValue* valueAsString = new AMFStringValue(); + // valueAsString->SetStringValue(behaviorAction->parameterValueString); + // thisAction->InsertValue(behaviorAction->parameterName, valueAsString); + // } + // else if (behaviorAction->parameterValueDouble != 0.0) + // { + // AMFDoubleValue* valueAsDouble = new AMFDoubleValue(); + // valueAsDouble->SetDoubleValue(behaviorAction->parameterValueDouble); + // thisAction->InsertValue(behaviorAction->parameterName, valueAsDouble); + // } + // stripSerialize->PushBackValue(thisAction); + // } + // thisStrip->InsertValue("actions", stripSerialize); + // strips->PushBackValue(thisStrip); + // } + // state->InsertValue("strips", strips); + // stateSerialize->PushBackValue(state); + // } + // behaviorInfo.InsertValue("states", stateSerialize); + + // AMFStringValue* objectidAsString = new AMFStringValue(); + // objectidAsString->SetStringValue(std::to_string(targetObjectID)); + // behaviorInfo.InsertValue("objectID", objectidAsString); + + // AMFStringValue* behaviorIDAsString = new AMFStringValue(); + // behaviorIDAsString->SetStringValue(std::to_string(behaviorID)); + // behaviorInfo.InsertValue("BehaviorID", behaviorIDAsString); + + // GameMessages::SendUIMessageServerToSingleClient(modelOwner, sysAddr, "UpdateBehaviorBlocks", &behaviorInfo); +} + +void UpdateAction(AMFArrayValue* arguments) { + std::string type = ""; + std::string valueParameterName = ""; + std::string valueParameterString = ""; + double valueParameterDouble = 0.0; + auto* actionAsArray = arguments->FindValue<AMFArrayValue>("action"); + if (!actionAsArray) return; + for (auto& typeValueMap : actionAsArray->GetAssociativeMap()) { + if (typeValueMap.first == "Type") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + type = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + valueParameterName = typeValueMap.first; + // Message is the only known string parameter + if (valueParameterName == "Message") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + valueParameterString = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFDouble) continue; + valueParameterDouble = static_cast<AMFDoubleValue*>(typeValueMap.second)->GetDoubleValue(); + } + } + } + + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + auto* actionIndexValue = arguments->FindValue<AMFDoubleValue>("actionIndex"); + if (!actionIndexValue) return; + + uint32_t actionIndex = static_cast<uint32_t>(actionIndexValue->GetDoubleValue()); + + STRIPID stripID = GetStripIDFromArgument(arguments); + + BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); + + // modelComponent->UpdateAction(stateID, stripID, type, valueParameterName, valueParameterString, valueParameterDouble, "", actionIndex, behaviorID); + + // RequestUpdatedID(behaviorID); +} + +void MoveToInventory(ModelComponent* modelComponent, const SystemAddress& sysAddr, Entity* modelOwner, AMFArrayValue* arguments) { + // This closes the UI menu should it be open while the player is removing behaviors + AMFArrayValue args; + + AMFFalseValue* stateToPop = new AMFFalseValue(); + args.InsertValue("visible", stateToPop); + + GameMessages::SendUIMessageServerToSingleClient(modelOwner, modelOwner->GetParentUser()->GetSystemAddress(), "ToggleBehaviorEditor", &args); + + uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); + + auto* behaviorIndexValue = arguments->FindValue<AMFDoubleValue>("BehaviorIndex"); + if (!behaviorIndexValue) return; + + uint32_t behaviorIndex = static_cast<uint32_t>(behaviorIndexValue->GetDoubleValue()); + + // modelComponent->MoveBehaviorToInventory(behaviorID, behaviorIndex, modelOwner); + + SendBehaviorListToClient(modelComponent->GetParent(), sysAddr, modelOwner); +} + +void ControlBehaviors::ProcessCommand(Entity* modelEntity, const SystemAddress& sysAddr, AMFArrayValue* arguments, std::string command, Entity* modelOwner) { + if (!modelEntity || !modelOwner || !arguments) return; + auto* modelComponent = modelEntity->GetComponent<ModelComponent>(); + + if (!modelComponent) return; + + if (command == "sendBehaviorListToClient") + SendBehaviorListToClient(modelEntity, sysAddr, modelOwner); + else if (command == "modelTypeChanged") + ModelTypeChanged(arguments, modelComponent); + else if (command == "toggleExecutionUpdates") + ToggleExecutionUpdates(); + else if (command == "addStrip") + AddStrip(arguments); + else if (command == "removeStrip") + RemoveStrip(arguments); + else if (command == "mergeStrips") + MergeStrips(arguments); + else if (command == "splitStrip") + SplitStrip(arguments); + else if (command == "updateStripUI") + UpdateStripUI(arguments); + else if (command == "addAction") + AddAction(arguments); + else if (command == "migrateActions") + MigrateActions(arguments); + else if (command == "rearrangeStrip") + RearrangeStrip(arguments); + else if (command == "add") + Add(arguments); + else if (command == "removeActions") + RemoveActions(arguments); + else if (command == "rename") + Rename(modelEntity, sysAddr, modelOwner, arguments); + else if (command == "sendBehaviorBlocksToClient") + SendBehaviorBlocksToClient(modelComponent, sysAddr, modelOwner, arguments); + else if (command == "moveToInventory") + MoveToInventory(modelComponent, sysAddr, modelOwner, arguments); + else if (command == "updateAction") + UpdateAction(arguments); + else + Game::logger->Log("ControlBehaviors", "Unknown behavior command (%s)\n", command.c_str()); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.h b/dGame/dPropertyBehaviors/ControlBehaviors.h index 7c24da68..d487f929 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviors.h +++ b/dGame/dPropertyBehaviors/ControlBehaviors.h @@ -9,6 +9,7 @@ class Entity; class AMFArrayValue; +class ModelComponent; namespace ControlBehaviors { /** @@ -21,15 +22,6 @@ namespace ControlBehaviors { * @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); - - /** - * @brief Helper function to send the behavior list to the client - * - * @param modelEntity The model that sent this command - * @param sysAddr The SystemAddress to respond to - * @param modelOwner The owner of the model which sent this command - */ - void SendBehaviorListToClient(Entity* modelEntity, const SystemAddress& sysAddr, Entity* modelOwner); }; #endif //!__CONTROLBEHAVIORS__H__ From f8f5b731f189a1a31ceecbb5256bfc4a3da08ed7 Mon Sep 17 00:00:00 2001 From: Jonathan Romano <jonathan@luxaritas.com> Date: Sun, 27 Nov 2022 06:59:59 -0500 Subject: [PATCH 144/322] Allow servers to be run from directories other than `build`. Read/write files relative to binary instead of cwd (#834) Allows the server to be run from a non-build directory. Also only read or write files relative to the build directory, regardless of where the server is run from --- dAuthServer/AuthServer.cpp | 3 +- dChatServer/ChatServer.cpp | 14 +++-- dCommon/BinaryPathFinder.cpp | 71 ++++++++++++++++++++++++ dCommon/BinaryPathFinder.h | 15 +++++ dCommon/CMakeLists.txt | 1 + dCommon/dClient/AssetManager.cpp | 8 ++- dCommon/dClient/AssetManager.h | 2 +- dCommon/dConfig.cpp | 5 +- dDatabase/MigrationRunner.cpp | 7 ++- dGame/dUtilities/SlashCommandHandler.cpp | 3 +- dGame/dUtilities/VanityUtilities.cpp | 5 +- dGame/dUtilities/dLocale.cpp | 3 +- dMasterServer/InstanceManager.cpp | 11 ++-- dMasterServer/MasterServer.cpp | 40 +++++++------ dNavigation/dNavMesh.cpp | 3 +- dWorldServer/WorldServer.cpp | 13 +++-- 16 files changed, 158 insertions(+), 46 deletions(-) create mode 100644 dCommon/BinaryPathFinder.cpp create mode 100644 dCommon/BinaryPathFinder.h diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index 73cb4212..9621f683 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -11,6 +11,7 @@ #include "Database.h" #include "dConfig.h" #include "Diagnostics.h" +#include "BinaryPathFinder.h" //RakNet includes: #include "RakNetDefines.h" @@ -150,7 +151,7 @@ int main(int argc, char** argv) { } dLogger* SetupLogger() { - std::string logPath = "./logs/AuthServer_" + std::to_string(time(nullptr)) + ".log"; + std::string logPath = (BinaryPathFinder::GetBinaryDir() / ("logs/AuthServer_" + std::to_string(time(nullptr)) + ".log")).string(); bool logToConsole = false; bool logDebugStatements = false; #ifdef _DEBUG diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index fc8bdd5b..e0073747 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -13,6 +13,7 @@ #include "dChatFilter.h" #include "Diagnostics.h" #include "AssetManager.h" +#include "BinaryPathFinder.h" #include "PlayerContainer.h" #include "ChatPacketHandler.h" @@ -53,9 +54,14 @@ int main(int argc, char** argv) { Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); try { - std::string client_path = config.GetValue("client_location"); - if (client_path.empty()) client_path = "./res"; - Game::assetManager = new AssetManager(client_path); + std::string clientPathStr = config.GetValue("client_location"); + if (clientPathStr.empty()) clientPathStr = "./res"; + std::filesystem::path clientPath = std::filesystem::path(clientPathStr); + if (clientPath.is_relative()) { + clientPath = BinaryPathFinder::GetBinaryDir() / clientPath; + } + + Game::assetManager = new AssetManager(clientPath); } catch (std::runtime_error& ex) { Game::logger->Log("ChatServer", "Got an error while setting up assets: %s", ex.what()); @@ -167,7 +173,7 @@ int main(int argc, char** argv) { } dLogger* SetupLogger() { - std::string logPath = "./logs/ChatServer_" + std::to_string(time(nullptr)) + ".log"; + std::string logPath = (BinaryPathFinder::GetBinaryDir() / ("logs/ChatServer_" + std::to_string(time(nullptr)) + ".log")).string(); bool logToConsole = false; bool logDebugStatements = false; #ifdef _DEBUG diff --git a/dCommon/BinaryPathFinder.cpp b/dCommon/BinaryPathFinder.cpp new file mode 100644 index 00000000..b1c2afef --- /dev/null +++ b/dCommon/BinaryPathFinder.cpp @@ -0,0 +1,71 @@ +#include <filesystem> +#include <string> +#include "BinaryPathFinder.h" +#include "dPlatforms.h" + +#if defined(DARKFLAME_PLATFORM_WIN32) +#include <Windows.h> +#elif defined(DARKFLAME_PLATFORM_MACOS) || defined(DARKFLAME_PLATFORM_IOS) +#include <mach-o/dyld.h> +#elif defined(DARKFLAME_PLATFORM_FREEBSD) +#include <sys/types.h> +#include <sys/sysctl.h> +#include <stdlib.h> +#endif + +std::filesystem::path BinaryPathFinder::binaryDir; + +std::filesystem::path BinaryPathFinder::GetBinaryDir() { + if (!binaryDir.empty()) { + return binaryDir; + } + + std::string pathStr; + + // Derived from boost::dll::program_location, licensed under the Boost Software License: http://www.boost.org/LICENSE_1_0.txt +#if defined(DARKFLAME_PLATFORM_WIN32) + char path[MAX_PATH]; + GetModuleFileName(NULL, path, MAX_PATH); + pathStr = std::string(path); +#elif defined(DARKFLAME_PLATFORM_MACOS) || defined(DARKFLAME_PLATFORM_IOS) + char path[1024]; + uint32_t size = sizeof(path); + if (_NSGetExecutablePath(path, &size) == 0) { + pathStr = std::string(path); + } else { + // The filepath size is greater than our initial buffer size, so try again with the size + // that _NSGetExecutablePath told us it actually is + char *p = new char[size]; + if (_NSGetExecutablePath(p, &size) != 0) { + throw std::runtime_error("Failed to get binary path from _NSGetExecutablePath"); + } + + pathStr = std::string(p); + delete[] p; + } +#elif defined(DARKFLAME_PLATFORM_FREEBSD) + int mib[4]; + mib[0] = CTL_KERN; + mib[1] = KERN_PROC; + mib[2] = KERN_PROC_PATHNAME; + mib[3] = -1; + char buf[10240]; + size_t cb = sizeof(buf); + sysctl(mib, 4, buf, &cb, NULL, 0); + pathStr = std::string(buf); +#else // DARKFLAME_PLATFORM_LINUX || DARKFLAME_PLATFORM_UNIX || DARKFLAME_PLATFORM_ANDROID + pathStr = std::filesystem::read_symlink("/proc/self/exe"); +#endif + + // Some methods like _NSGetExecutablePath could return a symlink + // Either way, we need to get the parent path because we want the directory, not the binary itself + // We also ensure that it is an absolute path so that it is valid if we need to construct a path + // to exucute on unix systems (eg sudo BinaryPathFinder::GetBinaryDir() / WorldServer) + if (std::filesystem::is_symlink(pathStr)) { + binaryDir = std::filesystem::absolute(std::filesystem::read_symlink(pathStr).parent_path()); + } else { + binaryDir = std::filesystem::absolute(std::filesystem::path(pathStr).parent_path()); + } + + return binaryDir; +} diff --git a/dCommon/BinaryPathFinder.h b/dCommon/BinaryPathFinder.h new file mode 100644 index 00000000..c4ca6da2 --- /dev/null +++ b/dCommon/BinaryPathFinder.h @@ -0,0 +1,15 @@ +#pragma once + +#ifndef __BINARYPATHFINDER__H__ +#define __BINARYPATHFINDER__H__ + +#include <filesystem> + +class BinaryPathFinder { +private: + static std::filesystem::path binaryDir; +public: + static std::filesystem::path GetBinaryDir(); +}; + +#endif //!__BINARYPATHFINDER__H__ diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 46102b74..8d02186b 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -15,6 +15,7 @@ set(DCOMMON_SOURCES "AMFFormat.cpp" "Type.cpp" "ZCompression.cpp" "BrickByBrickFix.cpp" + "BinaryPathFinder.cpp" ) add_subdirectory(dClient) diff --git a/dCommon/dClient/AssetManager.cpp b/dCommon/dClient/AssetManager.cpp index 349b5271..dc3db0a1 100644 --- a/dCommon/dClient/AssetManager.cpp +++ b/dCommon/dClient/AssetManager.cpp @@ -1,15 +1,17 @@ +#include <filesystem> + #include "AssetManager.h" #include "Game.h" #include "dLogger.h" #include <zlib.h> -AssetManager::AssetManager(const std::string& path) { +AssetManager::AssetManager(const std::filesystem::path& path) { if (!std::filesystem::is_directory(path)) { - throw std::runtime_error("Attempted to load asset bundle (" + path + ") however it is not a valid directory."); + throw std::runtime_error("Attempted to load asset bundle (" + path.string() + ") however it is not a valid directory."); } - m_Path = std::filesystem::path(path); + m_Path = path; if (std::filesystem::exists(m_Path / "client") && std::filesystem::exists(m_Path / "versions")) { m_AssetBundleType = eAssetBundleType::Packed; diff --git a/dCommon/dClient/AssetManager.h b/dCommon/dClient/AssetManager.h index 87653845..73b24f18 100644 --- a/dCommon/dClient/AssetManager.h +++ b/dCommon/dClient/AssetManager.h @@ -48,7 +48,7 @@ struct AssetMemoryBuffer : std::streambuf { class AssetManager { public: - AssetManager(const std::string& path); + AssetManager(const std::filesystem::path& path); ~AssetManager(); std::filesystem::path GetResPath(); diff --git a/dCommon/dConfig.cpp b/dCommon/dConfig.cpp index c22c91cc..1bc940e8 100644 --- a/dCommon/dConfig.cpp +++ b/dCommon/dConfig.cpp @@ -1,9 +1,10 @@ #include "dConfig.h" #include <sstream> +#include "BinaryPathFinder.h" dConfig::dConfig(const std::string& filepath) { m_EmptyString = ""; - std::ifstream in(filepath); + std::ifstream in(BinaryPathFinder::GetBinaryDir() / filepath); if (!in.good()) return; std::string line; @@ -13,7 +14,7 @@ dConfig::dConfig(const std::string& filepath) { } } - std::ifstream sharedConfig("sharedconfig.ini", std::ios::in); + std::ifstream sharedConfig(BinaryPathFinder::GetBinaryDir() / "sharedconfig.ini", std::ios::in); if (!sharedConfig.good()) return; while (std::getline(sharedConfig, line)) { diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index 25312608..fe0f933a 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -6,12 +6,13 @@ #include "Game.h" #include "GeneralUtils.h" #include "dLogger.h" +#include "BinaryPathFinder.h" #include <istream> Migration LoadMigration(std::string path) { Migration migration{}; - std::ifstream file("./migrations/" + path); + std::ifstream file(BinaryPathFinder::GetBinaryDir() / "migrations/" / path); if (file.is_open()) { std::string line; @@ -37,7 +38,7 @@ void MigrationRunner::RunMigrations() { sql::SQLString finalSQL = ""; bool runSd0Migrations = false; - for (const auto& entry : GeneralUtils::GetFileNamesFromFolder("./migrations/dlu/")) { + for (const auto& entry : GeneralUtils::GetFileNamesFromFolder((BinaryPathFinder::GetBinaryDir() / "./migrations/dlu/").string())) { auto migration = LoadMigration("dlu/" + entry); if (migration.data.empty()) { @@ -97,7 +98,7 @@ void MigrationRunner::RunSQLiteMigrations() { stmt->execute(); delete stmt; - for (const auto& entry : GeneralUtils::GetFileNamesFromFolder("./migrations/cdserver/")) { + for (const auto& entry : GeneralUtils::GetFileNamesFromFolder((BinaryPathFinder::GetBinaryDir() / "migrations/cdserver/").string())) { auto migration = LoadMigration("cdserver/" + entry); if (migration.data.empty()) continue; diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 8f4ac1a8..2f4d9211 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -64,6 +64,7 @@ #include "ScriptedActivityComponent.h" #include "LevelProgressionComponent.h" #include "AssetManager.h" +#include "BinaryPathFinder.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { std::string chatCommand; @@ -248,7 +249,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "credits" || chatCommand == "info") { - const auto& customText = chatCommand == "credits" ? VanityUtilities::ParseMarkdown("./vanity/CREDITS.md") : VanityUtilities::ParseMarkdown("./vanity/INFO.md"); + const auto& customText = chatCommand == "credits" ? VanityUtilities::ParseMarkdown((BinaryPathFinder::GetBinaryDir() / "vanity/CREDITS.md").string()) : VanityUtilities::ParseMarkdown((BinaryPathFinder::GetBinaryDir() / "vanity/INFO.md").string()); { AMFArrayValue args; diff --git a/dGame/dUtilities/VanityUtilities.cpp b/dGame/dUtilities/VanityUtilities.cpp index 733d94c4..3a1259a2 100644 --- a/dGame/dUtilities/VanityUtilities.cpp +++ b/dGame/dUtilities/VanityUtilities.cpp @@ -13,6 +13,7 @@ #include "tinyxml2.h" #include "Game.h" #include "dLogger.h" +#include "BinaryPathFinder.h" #include <fstream> @@ -27,7 +28,7 @@ void VanityUtilities::SpawnVanity() { const uint32_t zoneID = Game::server->GetZoneID(); - ParseXML("./vanity/NPC.xml"); + ParseXML((BinaryPathFinder::GetBinaryDir() / "vanity/NPC.xml").string()); // Loop through all parties for (const auto& party : m_Parties) { @@ -131,7 +132,7 @@ void VanityUtilities::SpawnVanity() { info.spawnerID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); info.settings = { new LDFData<bool>(u"hasCustomText", true), - new LDFData<std::string>(u"customText", ParseMarkdown("./vanity/TESTAMENT.md")) }; + new LDFData<std::string>(u"customText", ParseMarkdown((BinaryPathFinder::GetBinaryDir() / "vanity/TESTAMENT.md").string())) }; auto* entity = EntityManager::Instance()->CreateEntity(info); diff --git a/dGame/dUtilities/dLocale.cpp b/dGame/dUtilities/dLocale.cpp index 65ef3a58..de65511b 100644 --- a/dGame/dUtilities/dLocale.cpp +++ b/dGame/dUtilities/dLocale.cpp @@ -9,13 +9,14 @@ #include "tinyxml2.h" #include "Game.h" #include "dConfig.h" +#include "BinaryPathFinder.h" dLocale::dLocale() { if (Game::config->GetValue("locale_enabled") != "1") { return; } - std::ifstream file(m_LocalePath); + std::ifstream file(BinaryPathFinder::GetBinaryDir() / m_LocalePath); if (!file.good()) { return; diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index 0c605ed6..83378dbb 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -10,6 +10,7 @@ #include "dMessageIdentifiers.h" #include "MasterPackets.h" #include "PacketUtils.h" +#include "BinaryPathFinder.h" InstanceManager::InstanceManager(dLogger* logger, const std::string& externalIP) { mLogger = logger; @@ -48,13 +49,13 @@ Instance* InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, LW //Start the actual process: #ifdef _WIN32 - std::string cmd = "start ./WorldServer.exe -zone "; + std::string cmd = "start " + (BinaryPathFinder::GetBinaryDir() / "WorldServer.exe").string() + " -zone "; #else std::string cmd; if (std::atoi(Game::config->GetValue("use_sudo_world").c_str())) { - cmd = "sudo ./WorldServer -zone "; + cmd = "sudo " + (BinaryPathFinder::GetBinaryDir() / "WorldServer").string() + " -zone "; } else { - cmd = "./WorldServer -zone "; + cmd = (BinaryPathFinder::GetBinaryDir() / "WorldServer").string() + " -zone "; } #endif @@ -300,10 +301,10 @@ Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID clon instance = new Instance(mExternalIP, port, mapID, ++m_LastInstanceID, cloneID, maxPlayers, maxPlayers, true, password); //Start the actual process: - std::string cmd = "start ./WorldServer.exe -zone "; + std::string cmd = "start " + (BinaryPathFinder::GetBinaryDir() / "WorldServer").string() + " -zone "; #ifndef _WIN32 - cmd = "./WorldServer -zone "; + cmd = (BinaryPathFinder::GetBinaryDir() / "WorldServer").string() + " -zone "; #endif cmd.append(std::to_string(mapID)); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 061a91c7..34e2f71a 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -26,6 +26,7 @@ #include "dLogger.h" #include "dServer.h" #include "AssetManager.h" +#include "BinaryPathFinder.h" //RakNet includes: #include "RakNetDefines.h" @@ -102,9 +103,14 @@ int main(int argc, char** argv) { } try { - std::string client_path = config.GetValue("client_location"); - if (client_path.empty()) client_path = "./res"; - Game::assetManager = new AssetManager(client_path); + std::string clientPathStr = config.GetValue("client_location"); + if (clientPathStr.empty()) clientPathStr = "./res"; + std::filesystem::path clientPath = std::filesystem::path(clientPathStr); + if (clientPath.is_relative()) { + clientPath = BinaryPathFinder::GetBinaryDir() / clientPath; + } + + Game::assetManager = new AssetManager(clientPath); } catch (std::runtime_error& ex) { Game::logger->Log("MasterServer", "Got an error while setting up assets: %s", ex.what()); @@ -127,18 +133,16 @@ int main(int argc, char** argv) { stmt->executeUpdate(); delete stmt; - std::string res = "python3 ../thirdparty/docker-utils/utils/fdb_to_sqlite.py " + (Game::assetManager->GetResPath() / "cdclient.fdb").string(); + std::string res = "python3 " + + (BinaryPathFinder::GetBinaryDir() / "../thirdparty/docker-utils/utils/fdb_to_sqlite.py").string() + + " --sqlite_path " + (Game::assetManager->GetResPath() / "CDServer.sqlite").string() + + " " + (Game::assetManager->GetResPath() / "cdclient.fdb").string(); int result = system(res.c_str()); if (result != 0) { Game::logger->Log("MasterServer", "Failed to convert fdb to sqlite"); return EXIT_FAILURE; } - - if (std::rename("./cdclient.sqlite", (Game::assetManager->GetResPath() / "CDServer.sqlite").string().c_str()) != 0) { - Game::logger->Log("MasterServer", "Failed to move cdclient file."); - return EXIT_FAILURE; - } } //Connect to CDClient @@ -363,7 +367,7 @@ int main(int argc, char** argv) { dLogger* SetupLogger() { std::string logPath = - "./logs/MasterServer_" + std::to_string(time(nullptr)) + ".log"; + (BinaryPathFinder::GetBinaryDir() / ("logs/MasterServer_" + std::to_string(time(nullptr)) + ".log")).string(); bool logToConsole = false; bool logDebugStatements = false; #ifdef _DEBUG @@ -738,28 +742,28 @@ void HandlePacket(Packet* packet) { void StartChatServer() { #ifdef __APPLE__ //macOS doesn't need sudo to run on ports < 1024 - system("./ChatServer&"); + system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); #elif _WIN32 - system("start ./ChatServer.exe"); + system(("start " + (BinaryPathFinder::GetBinaryDir() / "ChatServer.exe").string()).c_str()); #else if (std::atoi(Game::config->GetValue("use_sudo_chat").c_str())) { - system("sudo ./ChatServer&"); + system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); } else { - system("./ChatServer&"); + system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); } #endif } void StartAuthServer() { #ifdef __APPLE__ - system("./AuthServer&"); + system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); #elif _WIN32 - system("start ./AuthServer.exe"); + system(("start " + (BinaryPathFinder::GetBinaryDir() / "AuthServer.exe").string()).c_str()); #else if (std::atoi(Game::config->GetValue("use_sudo_auth").c_str())) { - system("sudo ./AuthServer&"); + system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); } else { - system("./AuthServer&"); + system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); } #endif } diff --git a/dNavigation/dNavMesh.cpp b/dNavigation/dNavMesh.cpp index e5ba0129..fdba4a2d 100644 --- a/dNavigation/dNavMesh.cpp +++ b/dNavigation/dNavMesh.cpp @@ -7,6 +7,7 @@ #include "dPlatforms.h" #include "NiPoint3.h" #include "BinaryIO.h" +#include "BinaryPathFinder.h" #include "dZoneManager.h" @@ -43,7 +44,7 @@ dNavMesh::~dNavMesh() { void dNavMesh::LoadNavmesh() { - std::string path = "./navmeshes/" + std::to_string(m_ZoneId) + ".bin"; + std::string path = (BinaryPathFinder::GetBinaryDir() / "navmeshes/" / (std::to_string(m_ZoneId) + ".bin")).string(); if (!BinaryIO::DoesFileExist(path)) { return; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index d4e55cb5..b7d7cc14 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -17,6 +17,7 @@ #include "Metrics.hpp" #include "PerformanceManager.h" #include "Diagnostics.h" +#include "BinaryPathFinder.h" //RakNet includes: #include "RakNetDefines.h" @@ -146,9 +147,13 @@ int main(int argc, char** argv) { if (config.GetValue("disable_chat") == "1") chatDisabled = true; try { - std::string client_path = config.GetValue("client_location"); - if (client_path.empty()) client_path = "./res"; - Game::assetManager = new AssetManager(client_path); + std::string clientPathStr = config.GetValue("client_location"); + if (clientPathStr.empty()) clientPathStr = "./res"; + std::filesystem::path clientPath = std::filesystem::path(clientPathStr); + if (clientPath.is_relative()) { + clientPath = BinaryPathFinder::GetBinaryDir() / clientPath; + } + Game::assetManager = new AssetManager(clientPath); } catch (std::runtime_error& ex) { Game::logger->Log("WorldServer", "Got an error while setting up assets: %s", ex.what()); @@ -489,7 +494,7 @@ int main(int argc, char** argv) { } dLogger* SetupLogger(int zoneID, int instanceID) { - std::string logPath = "./logs/WorldServer_" + std::to_string(zoneID) + "_" + std::to_string(instanceID) + "_" + std::to_string(time(nullptr)) + ".log"; + std::string logPath = (BinaryPathFinder::GetBinaryDir() / ("logs/WorldServer_" + std::to_string(zoneID) + "_" + std::to_string(instanceID) + "_" + std::to_string(time(nullptr)) + ".log")).string(); bool logToConsole = false; bool logDebugStatements = false; #ifdef _DEBUG From d382eb3bc2d97e73d56995c532fb6795b31922a7 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 27 Nov 2022 04:03:30 -0800 Subject: [PATCH 145/322] Fix Boogie Down (#854) - Give entities that have a script component ID of zero a script component still - Progress scripted entity missions within the for loop as we do for script calls Tested that Boogie Down is (finally) completable. Tested that Mission 737 is still completable Checked that missions progressed inside OnEmoteReceived scripts to not double trigger progression --- dGame/Entity.cpp | 4 ++-- dGame/dGameMessages/GameMessages.cpp | 13 +++++++------ dScripts/ai/FV/FvNinjaGuard.cpp | 7 ------- 3 files changed, 9 insertions(+), 15 deletions(-) diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 62ac8bc2..1f094291 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -454,7 +454,7 @@ void Entity::Initialize() { */ CDScriptComponentTable* scriptCompTable = CDClientManager::Instance()->GetTable<CDScriptComponentTable>("ScriptComponent"); - int scriptComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SCRIPT); + int32_t scriptComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SCRIPT, -1); std::string scriptName = ""; bool client = false; @@ -496,7 +496,7 @@ void Entity::Initialize() { scriptName = customScriptServer; } - if (!scriptName.empty() || client || m_Character) { + if (!scriptName.empty() || client || m_Character || scriptComponentID >= 0) { m_Components.insert(std::make_pair(COMPONENT_TYPE_SCRIPT, new ScriptComponent(this, scriptName, true, client && scriptName.empty()))); } diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 18d7e0f6..025c26b3 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -4894,27 +4894,27 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) inStream->Read(emoteID); inStream->Read(targetID); - Game::logger->Log("GameMessages", "Emote (%i) (%llu)", emoteID, targetID); + Game::logger->LogDebug("GameMessages", "Emote (%i) (%llu)", emoteID, targetID); //TODO: If targetID != 0, and we have one of the "perform emote" missions, complete them. if (emoteID == 0) return; std::string sAnimationName = "deaded"; //Default name in case we fail to get the emote - MissionComponent* mission = static_cast<MissionComponent*>(entity->GetComponent(COMPONENT_TYPE_MISSION)); - if (mission) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_EMOTE, emoteID, targetID); - } + MissionComponent* missionComponent = entity->GetComponent<MissionComponent>(); + if (!missionComponent) return; if (targetID != LWOOBJID_EMPTY) { auto* targetEntity = EntityManager::Instance()->GetEntity(targetID); - Game::logger->Log("GameMessages", "Emote target found (%d)", targetEntity != nullptr); + Game::logger->LogDebug("GameMessages", "Emote target found (%d)", targetEntity != nullptr); if (targetEntity != nullptr) { targetEntity->OnEmoteReceived(emoteID, entity); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_EMOTE, emoteID, targetID); } } else { + Game::logger->LogDebug("GameMessages", "Target ID is empty, using backup"); const auto scriptedEntities = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); const auto& referencePoint = entity->GetPosition(); @@ -4923,6 +4923,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) if (Vector3::DistanceSquared(scripted->GetPosition(), referencePoint) > 5.0f * 5.0f) continue; scripted->OnEmoteReceived(emoteID, entity); + missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_EMOTE, emoteID, scripted->GetObjectID()); } } diff --git a/dScripts/ai/FV/FvNinjaGuard.cpp b/dScripts/ai/FV/FvNinjaGuard.cpp index 6a841ccf..58267999 100644 --- a/dScripts/ai/FV/FvNinjaGuard.cpp +++ b/dScripts/ai/FV/FvNinjaGuard.cpp @@ -19,12 +19,6 @@ void FvNinjaGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* ta GameMessages::SendPlayAnimation(self, u"scared"); - auto* missionComponent = target->GetComponent<MissionComponent>(); - - if (missionComponent != nullptr && missionComponent->HasMission(737)) { - missionComponent->ForceProgressTaskType(737, 5, 1, false); - } - if (self->GetLOT() == 7412) { auto* rightGuard = EntityManager::Instance()->GetEntity(m_RightGuard); @@ -39,4 +33,3 @@ void FvNinjaGuard::OnEmoteReceived(Entity* self, const int32_t emote, Entity* ta } } } - From 1556f580d6ce37f2845a39481066d6bea73b01f5 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 27 Nov 2022 13:47:14 -0800 Subject: [PATCH 146/322] Improve Diagnostics logging (#841) Improve diagnostics to write the file name and signal to the log file should there be a crash. --- dCommon/Diagnostics.cpp | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/dCommon/Diagnostics.cpp b/dCommon/Diagnostics.cpp index 4c2c8beb..3025f083 100644 --- a/dCommon/Diagnostics.cpp +++ b/dCommon/Diagnostics.cpp @@ -1,4 +1,6 @@ #include "Diagnostics.h" +#include "Game.h" +#include "dLogger.h" // If we're on Win32, we'll include our minidump writer #ifdef _WIN32 @@ -26,7 +28,7 @@ void make_minidump(EXCEPTION_POINTERS* e) { "_%4d%02d%02d_%02d%02d%02d.dmp", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond); } - + Game::logger->Log("Diagnostics", "Creating crash dump %s", name); auto hFile = CreateFileA(name, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (hFile == INVALID_HANDLE_VALUE) return; @@ -81,6 +83,7 @@ struct bt_ctx { static inline void Bt(struct backtrace_state* state) { std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; + Game::logger->Log("Diagnostics", "backtrace is enabled, crash dump located at %s", fileName.c_str()); FILE* file = fopen(fileName.c_str(), "w+"); if (file != nullptr) { backtrace_print(state, 2, file); @@ -114,6 +117,8 @@ void GenerateDump() { void CatchUnhandled(int sig) { #ifndef __include_backtrace__ + std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; + Game::logger->Log("Diagnostics", "Encountered signal %i, creating crash dump %s", sig, fileName.c_str()); if (Diagnostics::GetProduceMemoryDump()) { GenerateDump(); } @@ -124,7 +129,6 @@ void CatchUnhandled(int sig) { // get void*'s for all entries on the stack size = backtrace(array, 10); - printf("Fatal error %i\nStacktrace:\n", sig); #if defined(__GNUG__) and defined(__dynamic) // Loop through the returned addresses, and get the symbols to be demangled @@ -142,19 +146,18 @@ void CatchUnhandled(int sig) { demangled = demangle(functionName.c_str()); if (demangled.empty()) { - printf("[%02zu] %s\n", i, demangled.c_str()); + Game::logger->Log("Diagnostics", "[%02zu] %s", i, demangled.c_str()); } else { - printf("[%02zu] %s\n", i, functionName.c_str()); + Game::logger->Log("Diagnostics", "[%02zu] %s", i, functionName.c_str()); } } else { - printf("[%02zu] %s\n", i, functionName.c_str()); + Game::logger->Log("Diagnostics", "[%02zu] %s", i, functionName.c_str()); } } #else backtrace_symbols_fd(array, size, STDOUT_FILENO); #endif - std::string fileName = Diagnostics::GetOutDirectory() + "crash_" + Diagnostics::GetProcessName() + "_" + std::to_string(getpid()) + ".log"; FILE* file = fopen(fileName.c_str(), "w+"); if (file != NULL) { // print out all the frames to stderr From 3939f19b08f8c1dc642933e016a56ac373d68244 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 27 Nov 2022 16:40:14 -0800 Subject: [PATCH 147/322] Add Remove Buff Behavior and patch infinite use Imagination Backpack(#845) Testing does not reveal any issues with existing buff removals sending this GM as well and may fix more bugs that were unknown, or cause more. --- dCommon/dEnums/dMessageIdentifiers.h | 1 + dGame/dBehaviors/Behavior.cpp | 5 ++++- dGame/dBehaviors/CMakeLists.txt | 1 + dGame/dBehaviors/RemoveBuffBehavior.cpp | 21 +++++++++++++++++++++ dGame/dBehaviors/RemoveBuffBehavior.h | 22 ++++++++++++++++++++++ dGame/dComponents/BuffComponent.cpp | 4 +++- dGame/dComponents/BuffComponent.h | 3 ++- dGame/dComponents/InventoryComponent.cpp | 1 + dGame/dGameMessages/GameMessages.cpp | 14 ++++++++++++++ dGame/dGameMessages/GameMessages.h | 2 ++ 10 files changed, 71 insertions(+), 3 deletions(-) create mode 100644 dGame/dBehaviors/RemoveBuffBehavior.cpp create mode 100644 dGame/dBehaviors/RemoveBuffBehavior.h diff --git a/dCommon/dEnums/dMessageIdentifiers.h b/dCommon/dEnums/dMessageIdentifiers.h index 7dc08711..5f7e9128 100644 --- a/dCommon/dEnums/dMessageIdentifiers.h +++ b/dCommon/dEnums/dMessageIdentifiers.h @@ -537,6 +537,7 @@ enum GAME_MSG : unsigned short { GAME_MSG_REMOVE_RUN_SPEED_MODIFIER = 1506, GAME_MSG_UPDATE_PROPERTY_PERFORMANCE_COST = 1547, GAME_MSG_PROPERTY_ENTRANCE_BEGIN = 1553, + GAME_MSG_REMOVE_BUFF = 1648, GAME_MSG_REQUEST_MOVE_ITEM_BETWEEN_INVENTORY_TYPES = 1666, GAME_MSG_RESPONSE_MOVE_ITEM_BETWEEN_INVENTORY_TYPES = 1667, GAME_MSG_PLAYER_SET_CAMERA_CYCLING_MODE = 1676, diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index 046df117..d0d6192b 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -42,6 +42,7 @@ #include "SkillCastFailedBehavior.h" #include "SpawnBehavior.h" #include "ForceMovementBehavior.h" +#include "RemoveBuffBehavior.h" #include "ImmunityBehavior.h" #include "InterruptBehavior.h" #include "PlayEffectBehavior.h" @@ -226,7 +227,9 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) { break; case BehaviorTemplates::BEHAVIOR_ALTER_CHAIN_DELAY: break; case BehaviorTemplates::BEHAVIOR_CAMERA: break; - case BehaviorTemplates::BEHAVIOR_REMOVE_BUFF: break; + case BehaviorTemplates::BEHAVIOR_REMOVE_BUFF: + behavior = new RemoveBuffBehavior(behaviorId); + break; case BehaviorTemplates::BEHAVIOR_GRAB: break; case BehaviorTemplates::BEHAVIOR_MODULAR_BUILD: break; case BehaviorTemplates::BEHAVIOR_NPC_COMBAT_SKILL: diff --git a/dGame/dBehaviors/CMakeLists.txt b/dGame/dBehaviors/CMakeLists.txt index fe8e89b8..297c389b 100644 --- a/dGame/dBehaviors/CMakeLists.txt +++ b/dGame/dBehaviors/CMakeLists.txt @@ -34,6 +34,7 @@ set(DGAME_DBEHAVIORS_SOURCES "AirMovementBehavior.cpp" "PlayEffectBehavior.cpp" "ProjectileAttackBehavior.cpp" "PullToPointBehavior.cpp" + "RemoveBuffBehavior.cpp" "RepairBehavior.cpp" "SkillCastFailedBehavior.cpp" "SkillEventBehavior.cpp" diff --git a/dGame/dBehaviors/RemoveBuffBehavior.cpp b/dGame/dBehaviors/RemoveBuffBehavior.cpp new file mode 100644 index 00000000..be3066ac --- /dev/null +++ b/dGame/dBehaviors/RemoveBuffBehavior.cpp @@ -0,0 +1,21 @@ +#include "RemoveBuffBehavior.h" + +#include "BehaviorBranchContext.h" +#include "BehaviorContext.h" +#include "EntityManager.h" +#include "BuffComponent.h" + +void RemoveBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto* entity = EntityManager::Instance()->GetEntity(context->caster); + if (!entity) return; + + auto* buffComponent = entity->GetComponent<BuffComponent>(); + if (!buffComponent) return; + + buffComponent->RemoveBuff(m_BuffId, false, m_RemoveImmunity); +} + +void RemoveBuffBehavior::Load() { + this->m_RemoveImmunity = GetBoolean("remove_immunity"); + this->m_BuffId = GetInt("buff_id"); +} diff --git a/dGame/dBehaviors/RemoveBuffBehavior.h b/dGame/dBehaviors/RemoveBuffBehavior.h new file mode 100644 index 00000000..f2d8547b --- /dev/null +++ b/dGame/dBehaviors/RemoveBuffBehavior.h @@ -0,0 +1,22 @@ +#pragma once +#include "Behavior.h" + +class RemoveBuffBehavior final : public Behavior +{ +public: + + /* + * Inherited + */ + + explicit RemoveBuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { + } + + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + + void Load() override; + +private: + bool m_RemoveImmunity; + uint32_t m_BuffId; +}; diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index ecb10017..af20fc00 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -123,13 +123,15 @@ void BuffComponent::ApplyBuff(const int32_t id, const float duration, const LWOO m_Buffs.emplace(id, buff); } -void BuffComponent::RemoveBuff(int32_t id) { +void BuffComponent::RemoveBuff(int32_t id, bool fromUnEquip, bool removeImmunity) { const auto& iter = m_Buffs.find(id); if (iter == m_Buffs.end()) { return; } + GameMessages::SendRemoveBuff(m_Parent, fromUnEquip, removeImmunity, id); + m_Buffs.erase(iter); RemoveBuffEffect(id); diff --git a/dGame/dComponents/BuffComponent.h b/dGame/dComponents/BuffComponent.h index aa669b13..7f7c6b0f 100644 --- a/dGame/dComponents/BuffComponent.h +++ b/dGame/dComponents/BuffComponent.h @@ -78,8 +78,9 @@ public: /** * Removes a buff from the parent entity, reversing its effects * @param id the id of the buff to remove + * @param removeImmunity whether or not to remove immunity on removing the buff */ - void RemoveBuff(int32_t id); + void RemoveBuff(int32_t id, bool fromUnEquip = false, bool removeImmunity = false); /** * Returns whether or not the entity has a buff identified by `id` diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 12b6792e..9f53cfa3 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -986,6 +986,7 @@ void InventoryComponent::ApplyBuff(Item* item) const { } } +// TODO Something needs to send the remove buff GameMessage as well when it is unequipping items that would remove buffs. void InventoryComponent::RemoveBuff(Item* item) const { const auto buffs = FindBuffs(item, false); diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 025c26b3..896dfa0c 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -3476,6 +3476,20 @@ void GameMessages::SendPlayEmote(LWOOBJID objectId, int32_t emoteID, LWOOBJID ta SEND_PACKET; } +void GameMessages::SendRemoveBuff(Entity* entity, bool fromUnEquip, bool removeImmunity, uint32_t buffId) { + CBITSTREAM; + CMSGHEADER; + + bitStream.Write(entity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_REMOVE_BUFF); + + bitStream.Write(false); // bFromRemoveBehavior but setting this to true makes the GM not do anything on the client? + bitStream.Write(fromUnEquip); + bitStream.Write(removeImmunity); + bitStream.Write(buffId); + + SEND_PACKET_BROADCAST; +} void GameMessages::SendBouncerActiveStatus(LWOOBJID objectId, bool bActive, const SystemAddress& sysAddr) { CBITSTREAM; diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 31bdebb3..3594a86a 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -566,6 +566,8 @@ namespace GameMessages { void HandleReportBug(RakNet::BitStream* inStream, Entity* entity); + void SendRemoveBuff(Entity* entity, bool fromUnEquip, bool removeImmunity, uint32_t buffId); + /* Message to synchronize a skill cast */ class EchoSyncSkill { static const GAME_MSG MsgID = GAME_MSG_ECHO_SYNC_SKILL; From 3222e788155e17931e3b0af82f35239722f6c847 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 27 Nov 2022 16:48:46 -0800 Subject: [PATCH 148/322] Implement undo action for pre-built models (#830) Brick building as of right now does not implement the undo action properly. This commit addresses the issue with undoing button being non-functional server side and implements the GM needed for addressing further issues. Implement GameMessage UnUseModel which is called when a model in BrickBuilding is UnUsed. Important for UGC content down the line. Final code has been tested as follows: 1. Placed a model in brick build 2. saved placed a brick 3. repeat 2 and 3 twice more for 6 total models 4. Place a new model in brick mode and then edit all 7 models into one brick model instance 5. Pressing undo returns the converted model to the inventory and properly discards the other 6 without crashing. Intended live behavior is to store this in the inventory instead however behind the scenes work is needed to implement UGC models properly. Implement enum Implement the BlueprintSaveResponseType enum so there are less magic numbers sent via packets. Correct int sizes from unsigned int to uint32_t Add deserialize test Add a test for de-serializing a GM that is sent to the client. Assertions verify the data is in the correct order and has no extra information. --- dCommon/dEnums/dCommonVars.h | 1 + dCommon/dEnums/dMessageIdentifiers.h | 1 + dCommon/eBlueprintSaveResponseType.h | 26 +++++++ dGame/dComponents/InventoryComponent.cpp | 13 ++-- .../PropertyManagementComponent.cpp | 2 +- dGame/dGameMessages/GameMessageHandler.cpp | 4 ++ dGame/dGameMessages/GameMessages.cpp | 70 ++++++++++++++++--- dGame/dGameMessages/GameMessages.h | 11 +++ dGame/dInventory/Inventory.h | 2 +- dMasterServer/ObjectIDManager.cpp | 4 +- dWorldServer/WorldServer.cpp | 7 +- tests/dGameTests/CMakeLists.txt | 3 + tests/dGameTests/GameDependencies.h | 9 ++- .../dGameMessagesTests/CMakeLists.txt | 9 +++ .../dGameMessagesTests/GameMessageTests.cpp | 52 ++++++++++++++ 15 files changed, 188 insertions(+), 26 deletions(-) create mode 100644 dCommon/eBlueprintSaveResponseType.h create mode 100644 tests/dGameTests/dGameMessagesTests/CMakeLists.txt create mode 100644 tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index 005d7205..74d83b11 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -434,6 +434,7 @@ enum eInventoryType : uint32_t { ITEMS = 0, VAULT_ITEMS, BRICKS, + MODELS_IN_BBB, TEMP_ITEMS = 4, MODELS, TEMP_MODELS, diff --git a/dCommon/dEnums/dMessageIdentifiers.h b/dCommon/dEnums/dMessageIdentifiers.h index 5f7e9128..5a5c9088 100644 --- a/dCommon/dEnums/dMessageIdentifiers.h +++ b/dCommon/dEnums/dMessageIdentifiers.h @@ -433,6 +433,7 @@ enum GAME_MSG : unsigned short { GAME_MSG_ORIENT_TO_POSITION = 906, GAME_MSG_ORIENT_TO_ANGLE = 907, GAME_MSG_BOUNCER_ACTIVE_STATUS = 942, + GAME_MSG_UN_USE_BBB_MODEL = 999, GAME_MSG_BBB_LOAD_ITEM_REQUEST = 1000, GAME_MSG_BBB_SAVE_REQUEST = 1001, GAME_MSG_BBB_SAVE_RESPONSE = 1006, diff --git a/dCommon/eBlueprintSaveResponseType.h b/dCommon/eBlueprintSaveResponseType.h new file mode 100644 index 00000000..29d15695 --- /dev/null +++ b/dCommon/eBlueprintSaveResponseType.h @@ -0,0 +1,26 @@ +#pragma once + +#ifndef __EBLUEPRINTSAVERESPONSETYPE__H__ +#define __EBLUEPRINTSAVERESPONSETYPE__H__ + +#include <cstdint> + +enum class eBlueprintSaveResponseType : uint32_t { + EverythingWorked = 0, + SaveCancelled, + CantBeginTransaction, + SaveBlueprintFailed, + SaveUgobjectFailed, + CantEndTransaction, + SaveFilesFailed, + BadInput, + NotEnoughBricks, + InventoryFull, + ModelGenerationFailed, + PlacementFailed, + GmLevelInsufficient, + WaitForPreviousSave, + FindMatchesFailed +}; + +#endif //!__EBLUEPRINTSAVERESPONSETYPE__H__ diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 9f53cfa3..77f3f035 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -606,16 +606,17 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) { return; } - std::vector<Inventory*> inventories; + std::vector<Inventory*> inventoriesToSave; + // Need to prevent some transfer inventories from being saved for (const auto& pair : this->m_Inventories) { auto* inventory = pair.second; - if (inventory->GetType() == VENDOR_BUYBACK) { + if (inventory->GetType() == VENDOR_BUYBACK || inventory->GetType() == eInventoryType::MODELS_IN_BBB) { continue; } - inventories.push_back(inventory); + inventoriesToSave.push_back(inventory); } inventoryElement->SetAttribute("csl", m_Consumable); @@ -630,7 +631,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) { bags->DeleteChildren(); - for (const auto* inventory : inventories) { + for (const auto* inventory : inventoriesToSave) { auto* bag = document->NewElement("b"); bag->SetAttribute("t", inventory->GetType()); @@ -649,7 +650,7 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) { items->DeleteChildren(); - for (auto* inventory : inventories) { + for (auto* inventory : inventoriesToSave) { if (inventory->GetSize() == 0) { continue; } @@ -1260,7 +1261,7 @@ BehaviorSlot InventoryComponent::FindBehaviorSlot(const eItemType type) { } bool InventoryComponent::IsTransferInventory(eInventoryType type) { - return type == VENDOR_BUYBACK || type == VAULT_ITEMS || type == VAULT_MODELS || type == TEMP_ITEMS || type == TEMP_MODELS; + return type == VENDOR_BUYBACK || type == VAULT_ITEMS || type == VAULT_MODELS || type == TEMP_ITEMS || type == TEMP_MODELS || type == MODELS_IN_BBB; } uint32_t InventoryComponent::FindSkill(const LOT lot) { diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index d196e935..eaade8be 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -474,7 +474,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet settings.push_back(propertyObjectID); settings.push_back(modelType); - inventoryComponent->AddItem(6662, 1, eLootSourceType::LOOT_SOURCE_DELETION, eInventoryType::HIDDEN, settings, LWOOBJID_EMPTY, false, false, spawnerId); + inventoryComponent->AddItem(6662, 1, eLootSourceType::LOOT_SOURCE_DELETION, eInventoryType::MODELS_IN_BBB, settings, LWOOBJID_EMPTY, false, false, spawnerId); auto* item = inventoryComponent->FindItemBySubKey(spawnerId); if (item == nullptr) { diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 2ce79966..b7687c19 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -46,6 +46,10 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System switch (messageID) { + case GAME_MSG_UN_USE_BBB_MODEL: { + GameMessages::HandleUnUseModel(inStream, entity, sysAddr); + break; + } case GAME_MSG_PLAY_EMOTE: { GameMessages::HandlePlayEmote(inStream, entity); break; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 896dfa0c..6639197c 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -70,6 +70,7 @@ #include "TradingManager.h" #include "ControlBehaviors.h" #include "AMFDeserialize.h" +#include "eBlueprintSaveResponseType.h" void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender) { CBITSTREAM; @@ -2139,6 +2140,32 @@ void GameMessages::HandleSetPropertyAccess(RakNet::BitStream* inStream, Entity* PropertyManagementComponent::Instance()->SetPrivacyOption(static_cast<PropertyPrivacyOption>(accessType)); } +void GameMessages::HandleUnUseModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { + bool unknown{}; + LWOOBJID objIdToAddToInventory{}; + inStream->Read(unknown); + inStream->Read(objIdToAddToInventory); + auto* inventoryComponent = entity->GetComponent<InventoryComponent>(); + if (inventoryComponent) { + auto* inventory = inventoryComponent->GetInventory(eInventoryType::MODELS_IN_BBB); + auto* item = inventory->FindItemById(objIdToAddToInventory); + if (item) { + inventoryComponent->MoveItemToInventory(item, eInventoryType::MODELS, 1); + } else { + Game::logger->Log("GameMessages", "item id %llu not found in MODELS_IN_BBB inventory, likely because it does not exist", objIdToAddToInventory); + } + } + + if (unknown) { + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); + bitStream.Write<LWOOBJID>(LWOOBJID_EMPTY); //always zero so that a check on the client passes + bitStream.Write(eBlueprintSaveResponseType::PlacementFailed); // Sending a non-zero error code here prevents the client from deleting its in progress build for some reason? + bitStream.Write<uint32_t>(0); + SEND_PACKET; + } +} + void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { bool isProperty{}; LWOOBJID objectId{}; @@ -2353,16 +2380,40 @@ void GameMessages::HandleDeletePropertyModel(RakNet::BitStream* inStream, Entity } void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - LWOOBJID itemID = LWOOBJID_EMPTY; - inStream->Read(itemID); + LWOOBJID previousItemID = LWOOBJID_EMPTY; + inStream->Read(previousItemID); - Game::logger->Log("BBB", "Load item request for: %lld", itemID); + Game::logger->Log("BBB", "Load item request for: %lld", previousItemID); + LWOOBJID newId = previousItemID; + auto* inventoryComponent = entity->GetComponent<InventoryComponent>(); + if (inventoryComponent) { + auto* inventory = inventoryComponent->GetInventory(eInventoryType::MODELS); + auto* itemToMove = inventory->FindItemById(previousItemID); + if (itemToMove) { + LOT previousLot = itemToMove->GetLot(); + inventoryComponent->MoveItemToInventory(itemToMove, eInventoryType::MODELS_IN_BBB, 1, false); + + auto* destinationInventory = inventoryComponent->GetInventory(eInventoryType::MODELS_IN_BBB); + if (destinationInventory) { + auto* movedItem = destinationInventory->FindItemByLot(previousLot); + if (movedItem) newId = movedItem->GetId(); + } + } else { + Game::logger->Log("GameMessages", "item id %llu not found in MODELS inventory, likely because it does not exist", previousItemID); + } + } + + // Second argument always true (successful) for now + SendBlueprintLoadItemResponse(sysAddr, true, previousItemID, newId); +} + +void GameMessages::SendBlueprintLoadItemResponse(const SystemAddress& sysAddr, bool success, LWOOBJID oldItemId, LWOOBJID newItemId) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_LOAD_RESPONSE_ITEMID); - bitStream.Write(static_cast<uint8_t>(1)); - bitStream.Write<LWOOBJID>(itemID); - bitStream.Write<LWOOBJID>(itemID); + bitStream.Write(static_cast<uint8_t>(success)); + bitStream.Write<LWOOBJID>(oldItemId); + bitStream.Write<LWOOBJID>(newItemId); SEND_PACKET; } @@ -2413,7 +2464,7 @@ void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* e } auto owner = PropertyManagementComponent::Instance()->GetOwner(); - if (!owner) return; + if (!owner) return; ControlBehaviors::ProcessCommand(entity, sysAddr, static_cast<AMFArrayValue*>(amfArguments.get()), command, owner); } @@ -2609,8 +2660,8 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent CBITSTREAM; PacketUtils::WriteHeader(bitStream, CLIENT, CLIENT::MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); bitStream.Write(localId); - bitStream.Write<unsigned int>(0); - bitStream.Write<unsigned int>(1); + bitStream.Write(eBlueprintSaveResponseType::EverythingWorked); + bitStream.Write<uint32_t>(1); bitStream.Write(blueprintID); bitStream.Write<uint32_t>(sd0Size); @@ -2620,7 +2671,6 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent } SEND_PACKET; - // PacketUtils::SavePacket("MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE.bin", (char*)bitStream.GetData(), bitStream.GetNumberOfBytesUsed()); //Now we have to construct this object: diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 3594a86a..f9968d14 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -121,6 +121,7 @@ namespace GameMessages { void SendMatchResponse(Entity* entity, const SystemAddress& sysAddr, int response); void SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, std::string data, int type); + void HandleUnUseModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void SendStartCelebrationEffect(Entity* entity, const SystemAddress& sysAddr, int celebrationID); /** @@ -197,6 +198,16 @@ namespace GameMessages { void SendDownloadPropertyData(LWOOBJID objectId, const PropertyDataMessage& data, const SystemAddress& sysAddr); + /** + * @brief Send an updated item id to the client when they load a blueprint in brick build mode + * + * @param sysAddr SystemAddress to respond to + * @param oldItemId The item ID that was requested to be loaded + * @param newItemId The new item ID of the loaded item + * + */ + void SendBlueprintLoadItemResponse(const SystemAddress& sysAddr, bool success, LWOOBJID oldItemId, LWOOBJID newItemId); + void SendPropertyRentalResponse(LWOOBJID objectId, LWOCLONEID cloneId, uint32_t code, LWOOBJID propertyId, int64_t rentDue, const SystemAddress& sysAddr); void SendLockNodeRotation(Entity* entity, std::string nodeName); diff --git a/dGame/dInventory/Inventory.h b/dGame/dInventory/Inventory.h index 30f753da..6c6a4306 100644 --- a/dGame/dInventory/Inventory.h +++ b/dGame/dInventory/Inventory.h @@ -95,7 +95,7 @@ public: * @param lot the lot to find items for * @param ignoreEquipped ignores equipped items * @param ignoreBound ignores bound items - * @return item in the inventory for the provided LOT + * @return item with the lowest stack count in the inventory for the provided LOT */ Item* FindItemByLot(LOT lot, bool ignoreEquipped = false, bool ignoreBound = false) const; diff --git a/dMasterServer/ObjectIDManager.cpp b/dMasterServer/ObjectIDManager.cpp index 0f3b98c9..83dde8dd 100644 --- a/dMasterServer/ObjectIDManager.cpp +++ b/dMasterServer/ObjectIDManager.cpp @@ -51,13 +51,13 @@ uint32_t ObjectIDManager::GeneratePersistentID(void) { uint32_t toReturn = ++this->currentPersistentID; // So we peroidically save our ObjID to the database: - if (toReturn % 25 == 0) { // TEMP: DISABLED FOR DEBUG / DEVELOPMENT! + // if (toReturn % 25 == 0) { // TEMP: DISABLED FOR DEBUG / DEVELOPMENT! sql::PreparedStatement* stmt = Database::CreatePreppedStmt( "UPDATE object_id_tracker SET last_object_id=?"); stmt->setUInt(1, toReturn); stmt->execute(); delete stmt; - } + // } return toReturn; } diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index b7d7cc14..16e0b1c1 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -57,6 +57,7 @@ #include "Player.h" #include "PropertyManagementComponent.h" #include "AssetManager.h" +#include "eBlueprintSaveResponseType.h" #include "ZCompression.h" @@ -1082,9 +1083,9 @@ void HandlePacket(Packet* packet) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); - bitStream.Write<LWOOBJID>(0); //always zero so that a check on the client passes - bitStream.Write<unsigned int>(0); - bitStream.Write<unsigned int>(1); + bitStream.Write<LWOOBJID>(LWOOBJID_EMPTY); //always zero so that a check on the client passes + bitStream.Write(eBlueprintSaveResponseType::EverythingWorked); + bitStream.Write<uint32_t>(1); bitStream.Write(blueprintID); bitStream.Write<uint32_t>(lxfmlSize); diff --git a/tests/dGameTests/CMakeLists.txt b/tests/dGameTests/CMakeLists.txt index 68192b3f..ba7d4d1c 100644 --- a/tests/dGameTests/CMakeLists.txt +++ b/tests/dGameTests/CMakeLists.txt @@ -5,6 +5,9 @@ set(DGAMETEST_SOURCES add_subdirectory(dComponentsTests) list(APPEND DGAMETEST_SOURCES ${DCOMPONENTS_TESTS}) +add_subdirectory(dGameMessagesTests) +list(APPEND DGAMETEST_SOURCES ${DGAMEMESSAGES_TESTS}) + # Add the executable. Remember to add all tests above this! add_executable(dGameTests ${DGAMETEST_SOURCES}) diff --git a/tests/dGameTests/GameDependencies.h b/tests/dGameTests/GameDependencies.h index 593ec0fc..ee52dec6 100644 --- a/tests/dGameTests/GameDependencies.h +++ b/tests/dGameTests/GameDependencies.h @@ -5,15 +5,18 @@ #include "dLogger.h" #include "dServer.h" #include "EntityManager.h" -class dZoneManager; -class AssetManager; #include <gtest/gtest.h> +class dZoneManager; +class AssetManager; + class dServerMock : public dServer { + RakNet::BitStream* sentBitStream = nullptr; public: dServerMock() {}; ~dServerMock() {}; - void Send(RakNet::BitStream* bitStream, const SystemAddress& sysAddr, bool broadcast) override {}; + RakNet::BitStream* GetMostRecentBitStream() { return sentBitStream; }; + void Send(RakNet::BitStream* bitStream, const SystemAddress& sysAddr, bool broadcast) override { sentBitStream = bitStream; }; }; class GameDependenciesTest : public ::testing::Test { diff --git a/tests/dGameTests/dGameMessagesTests/CMakeLists.txt b/tests/dGameTests/dGameMessagesTests/CMakeLists.txt new file mode 100644 index 00000000..2417d29c --- /dev/null +++ b/tests/dGameTests/dGameMessagesTests/CMakeLists.txt @@ -0,0 +1,9 @@ +SET(DGAMEMESSAGES_TESTS + "GameMessageTests.cpp") + +# Get the folder name and prepend it to the files above +get_filename_component(thisFolderName ${CMAKE_CURRENT_SOURCE_DIR} NAME) +list(TRANSFORM DGAMEMESSAGES_TESTS PREPEND "${thisFolderName}/") + +# Export to parent scope +set(DGAMEMESSAGES_TESTS ${DGAMEMESSAGES_TESTS} PARENT_SCOPE) diff --git a/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp b/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp new file mode 100644 index 00000000..3d8b2d04 --- /dev/null +++ b/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp @@ -0,0 +1,52 @@ +#include "GameMessages.h" +#include "GameDependencies.h" +#include <gtest/gtest.h> + +class GameMessageTests : public GameDependenciesTest { + protected: + void SetUp() override { + SetUpDependencies(); + } + void TearDown() override { + TearDownDependencies(); + } +}; + +/** + * @brief Tests that the serialization struct BlueprintLoadItemResponse is serialized correctly + * + */ +TEST_F(GameMessageTests, SendBlueprintLoadItemResponse) { + GameMessages::SendBlueprintLoadItemResponse(UNASSIGNED_SYSTEM_ADDRESS, true, 515, 990); + auto* bitStream = static_cast<dServerMock*>(Game::server)->GetMostRecentBitStream(); + ASSERT_NE(bitStream, nullptr); + ASSERT_EQ(bitStream->GetNumberOfUnreadBits(), 200); + // First read in the packets' header + uint8_t rakNetPacketId{}; + uint16_t remoteConnectionType{}; + uint32_t packetId{}; + uint8_t always0{}; + + bitStream->Read(rakNetPacketId); + bitStream->Read(remoteConnectionType); + bitStream->Read(packetId); + bitStream->Read(always0); + ASSERT_EQ(rakNetPacketId, 0x53); + ASSERT_EQ(remoteConnectionType, 0x05); + ASSERT_EQ(packetId, 0x17); + ASSERT_EQ(always0, 0x00); + + // Next read in packet data + + uint8_t bSuccess{}; // unsigned bool + LWOOBJID previousId{}; + LWOOBJID newId{}; + bitStream->Read(bSuccess); + bitStream->Read(previousId); + bitStream->Read(newId); + ASSERT_EQ(bSuccess, static_cast<uint8_t>(true)); + ASSERT_EQ(previousId, 515); + ASSERT_EQ(newId, 990); + + ASSERT_EQ(bitStream->GetNumberOfUnreadBits(), 0); +} From 56da3f8543bdb1b9eb754332dca32b570b07d6c0 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 27 Nov 2022 16:56:55 -0800 Subject: [PATCH 149/322] Remove Locale (#808) * Remove Locale (finally) --- CMakeLists.txt | 3 - dCommon/Game.h | 2 - dGame/dMission/Mission.cpp | 12 ++-- dGame/dUtilities/CMakeLists.txt | 1 - dGame/dUtilities/dLocale.cpp | 82 --------------------------- dGame/dUtilities/dLocale.h | 19 ------- dWorldServer/WorldServer.cpp | 3 - docker/start_server.sh | 2 +- tests/dGameTests/GameDependencies.cpp | 1 - 9 files changed, 5 insertions(+), 120 deletions(-) delete mode 100644 dGame/dUtilities/dLocale.cpp delete mode 100644 dGame/dUtilities/dLocale.h mode change 100755 => 100644 docker/start_server.sh diff --git a/CMakeLists.txt b/CMakeLists.txt index 644fc383..163196fb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -92,9 +92,6 @@ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) # Create a /res directory make_directory(${CMAKE_BINARY_DIR}/res) -# Create a /locale directory -make_directory(${CMAKE_BINARY_DIR}/locale) - # Create a /logs directory make_directory(${CMAKE_BINARY_DIR}/logs) diff --git a/dCommon/Game.h b/dCommon/Game.h index 616c7fbf..1c4bbc85 100644 --- a/dCommon/Game.h +++ b/dCommon/Game.h @@ -8,7 +8,6 @@ class InstanceManager; class dpWorld; class dChatFilter; class dConfig; -class dLocale; class RakPeerInterface; class AssetManager; struct SystemAddress; @@ -20,7 +19,6 @@ namespace Game { extern dpWorld* physicsWorld; extern dChatFilter* chatFilter; extern dConfig* config; - extern dLocale* locale; extern std::mt19937 randomEngine; extern RakPeerInterface* chatServer; extern AssetManager* assetManager; diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index 6020e51c..0a8a57fe 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -13,7 +13,6 @@ #include "Mail.h" #include "MissionComponent.h" #include "RacingTaskParam.h" -#include "dLocale.h" #include "dLogger.h" #include "dServer.h" #include "dZoneManager.h" @@ -335,13 +334,10 @@ void Mission::Complete(const bool yieldRewards) { for (const auto& email : missionEmails) { const auto missionEmailBase = "MissionEmail_" + std::to_string(email.ID) + "_"; - const auto senderLocale = missionEmailBase + "senderName"; - const auto announceLocale = missionEmailBase + "announceText"; - - if (email.messageType == 1 && Game::locale->HasPhrase(senderLocale)) { - const auto subject = dLocale::GetTemplate(missionEmailBase + "subjectText"); - const auto body = dLocale::GetTemplate(missionEmailBase + "bodyText"); - const auto sender = dLocale::GetTemplate(senderLocale); + if (email.messageType == 1) { + const auto subject = "%[" + missionEmailBase + "subjectText]"; + const auto body = "%[" + missionEmailBase + "bodyText]"; + const auto sender = "%[" + missionEmailBase + "senderName]"; Mail::SendMail(LWOOBJID_EMPTY, sender, GetAssociate(), subject, body, email.attachmentLOT, 1); } diff --git a/dGame/dUtilities/CMakeLists.txt b/dGame/dUtilities/CMakeLists.txt index 0c848bf4..2c453a2e 100644 --- a/dGame/dUtilities/CMakeLists.txt +++ b/dGame/dUtilities/CMakeLists.txt @@ -1,5 +1,4 @@ set(DGAME_DUTILITIES_SOURCES "BrickDatabase.cpp" - "dLocale.cpp" "GameConfig.cpp" "GUID.cpp" "Loot.cpp" diff --git a/dGame/dUtilities/dLocale.cpp b/dGame/dUtilities/dLocale.cpp deleted file mode 100644 index de65511b..00000000 --- a/dGame/dUtilities/dLocale.cpp +++ /dev/null @@ -1,82 +0,0 @@ -#include "dLocale.h" - -#include <clocale> -#include <fstream> -#include <sstream> -#include <vector> -#include <algorithm> - -#include "tinyxml2.h" -#include "Game.h" -#include "dConfig.h" -#include "BinaryPathFinder.h" - -dLocale::dLocale() { - if (Game::config->GetValue("locale_enabled") != "1") { - return; - } - - std::ifstream file(BinaryPathFinder::GetBinaryDir() / m_LocalePath); - - if (!file.good()) { - return; - } - - std::stringstream data; - data << file.rdbuf(); - - if (data.str().empty()) { - return; - } - - auto* doc = new tinyxml2::XMLDocument(); - - if (doc == nullptr) { - return; - } - - if (doc->Parse(data.str().c_str(), data.str().size()) != 0) { - return; - } - - std::hash<std::string> hash; - - auto* localization = doc->FirstChildElement("localization"); - auto* phrases = localization->FirstChildElement("phrases"); - - auto* phrase = phrases->FirstChildElement("phrase"); - - while (phrase != nullptr) { - // Add the phrase hash to the vector - m_Phrases.push_back(hash(phrase->Attribute("id"))); - phrase = phrase->NextSiblingElement("phrase"); - } - - file.close(); - - delete doc; -} - -dLocale::~dLocale() = default; - -std::string dLocale::GetTemplate(const std::string& phraseID) { - return "%[" + phraseID + "]"; -} - -bool dLocale::HasPhrase(const std::string& phraseID) { - if (Game::config->GetValue("locale_enabled") != "1") { - return true; - } - - // Compute the hash and see if it's in the vector - std::hash<std::string> hash; - std::size_t hashValue = hash(phraseID); - return std::find(m_Phrases.begin(), m_Phrases.end(), hashValue) != m_Phrases.end(); -} - -/*std::string dLocale::GetPhrase(const std::string& phraseID) { - if (m_Phrases.find(phraseID) == m_Phrases.end()) { - return ""; - } - return m_Phrases[phraseID]; -}*/ diff --git a/dGame/dUtilities/dLocale.h b/dGame/dUtilities/dLocale.h deleted file mode 100644 index db5d2a4f..00000000 --- a/dGame/dUtilities/dLocale.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -#include <map> -#include <string> -#include <vector> -#include <cstdint> - -class dLocale { -public: - dLocale(); - ~dLocale(); - static std::string GetTemplate(const std::string& phraseID); - bool HasPhrase(const std::string& phraseID); - //std::string GetPhrase(const std::string& phraseID); - -private: - std::string m_LocalePath = "./locale/locale.xml"; - std::string m_Locale = "en_US"; // TODO: add to config - std::vector<std::size_t> m_Phrases; -}; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 16e0b1c1..bbba1166 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -48,7 +48,6 @@ #include "GameMessageHandler.h" #include "GameMessages.h" #include "Mail.h" -#include "dLocale.h" #include "TeamManager.h" #include "SkillComponent.h" #include "DestroyableComponent.h" @@ -68,7 +67,6 @@ namespace Game { dpWorld* physicsWorld; dChatFilter* chatFilter; dConfig* config; - dLocale* locale; std::mt19937 randomEngine; AssetManager* assetManager; @@ -223,7 +221,6 @@ int main(int argc, char** argv) { //Set up other things: Game::randomEngine = std::mt19937(time(0)); - Game::locale = new dLocale(); //Run it until server gets a kill message from Master: auto lastTime = std::chrono::high_resolution_clock::now(); diff --git a/docker/start_server.sh b/docker/start_server.sh old mode 100755 new mode 100644 index ca1a49a0..4fd6e2be --- a/docker/start_server.sh +++ b/docker/start_server.sh @@ -7,7 +7,7 @@ function symlink_client_files() { ln -s /client/client/res/chatplus_en_us.txt /app/res/chatplus_en_us.txt ln -s /client/client/res/names/ /app/res/names ln -s /client/client/res/CDServer.sqlite /app/res/CDServer.sqlite - ln -s /client/client/locale/locale.xml /app/locale/locale.xml + # need to create this file so the server knows the client is unpacked (see `dCommon/dClient/AssetManager.cpp`) touch /app/res/cdclient.fdb # need to iterate over entries in maps due to maps already being a directory with navmeshes/ in it diff --git a/tests/dGameTests/GameDependencies.cpp b/tests/dGameTests/GameDependencies.cpp index 8a572668..5ac3339a 100644 --- a/tests/dGameTests/GameDependencies.cpp +++ b/tests/dGameTests/GameDependencies.cpp @@ -7,7 +7,6 @@ namespace Game { dpWorld* physicsWorld; dChatFilter* chatFilter; dConfig* config; - dLocale* locale; std::mt19937 randomEngine; RakPeerInterface* chatServer; AssetManager* assetManager; From 09dfb6df3a53ce3fd3870351e8b3e6633e5a349b Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 27 Nov 2022 22:19:15 -0800 Subject: [PATCH 150/322] Address news feed showing up on every world transfer (#855) Addresses the news feed showing up on every world transfer --- dCommon/dEnums/dCommonVars.h | 1 + dGame/Character.cpp | 51 ++++++++++++++++++++++++++++-------- dGame/Character.h | 15 ++++++++++- dGame/UserManager.cpp | 1 + 4 files changed, 56 insertions(+), 12 deletions(-) diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index 74d83b11..f64d496f 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -560,6 +560,7 @@ enum ePlayerFlags { ENTER_BBB_FROM_PROPERTY_EDIT_CONFIRMATION_DIALOG = 64, AG_FIRST_COMBAT_COMPLETE = 65, AG_COMPLETE_BOB_MISSION = 66, + IS_NEWS_SCREEN_VISIBLE = 114, NJ_GARMADON_CINEMATIC_SEEN = 125, ELEPHANT_PET_3050 = 801, CAT_PET_3054 = 802, diff --git a/dGame/Character.cpp b/dGame/Character.cpp index 440c30c1..a9cffc65 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -264,14 +264,17 @@ void Character::DoQuickXMLDataParse() { if (flags) { auto* currentChild = flags->FirstChildElement(); while (currentChild) { - uint32_t index = 0; - uint64_t value = 0; const auto* temp = currentChild->Attribute("v"); + const auto* id = currentChild->Attribute("id"); + if (temp && id) { + uint32_t index = 0; + uint64_t value = 0; - index = std::stoul(currentChild->Attribute("id")); - value = std::stoull(temp); + index = std::stoul(id); + value = std::stoull(temp); - m_PlayerFlags.insert(std::make_pair(index, value)); + m_PlayerFlags.insert(std::make_pair(index, value)); + } currentChild = currentChild->NextSiblingElement(); } } @@ -351,6 +354,13 @@ void Character::SaveXMLToDatabase() { flags->LinkEndChild(f); } + // Prevents the news feed from showing up on world transfers + if (GetPlayerFlag(ePlayerFlags::IS_NEWS_SCREEN_VISIBLE)) { + auto* s = m_Doc->NewElement("s"); + s->SetAttribute("si", ePlayerFlags::IS_NEWS_SCREEN_VISIBLE); + flags->LinkEndChild(s); + } + SaveXmlRespawnCheckpoints(); //Call upon the entity to update our xmlDoc: @@ -361,6 +371,31 @@ void Character::SaveXMLToDatabase() { m_OurEntity->UpdateXMLDoc(m_Doc); + WriteToDatabase(); + + //For metrics, log the time it took to save: + auto end = std::chrono::system_clock::now(); + std::chrono::duration<double> elapsed = end - start; + Game::logger->Log("Character", "Saved character to Database in: %fs", elapsed.count()); +} + +void Character::SetIsNewLogin() { + // If we dont have a flag element, then we cannot have a s element as a child of flag. + auto* flags = m_Doc->FirstChildElement("obj")->FirstChildElement("flag"); + if (!flags) return; + + auto* currentChild = flags->FirstChildElement(); + while (currentChild) { + if (currentChild->Attribute("si")) { + flags->DeleteChild(currentChild); + Game::logger->Log("Character", "Removed isLoggedIn flag from character %i, saving character to database", GetID()); + WriteToDatabase(); + } + currentChild = currentChild->NextSiblingElement(); + } +} + +void Character::WriteToDatabase() { //Dump our xml into m_XMLData: auto* printer = new tinyxml2::XMLPrinter(0, true, 0); m_Doc->Print(printer); @@ -372,12 +407,6 @@ void Character::SaveXMLToDatabase() { stmt->setUInt(2, m_ID); stmt->execute(); delete stmt; - - //For metrics, log the time it took to save: - auto end = std::chrono::system_clock::now(); - std::chrono::duration<double> elapsed = end - start; - Game::logger->Log("Character", "Saved character to Database in: %fs", elapsed.count()); - delete printer; } diff --git a/dGame/Character.h b/dGame/Character.h index 52bff83d..07bde36c 100644 --- a/dGame/Character.h +++ b/dGame/Character.h @@ -23,6 +23,10 @@ public: Character(uint32_t id, User* parentUser); ~Character(); + /** + * Write the current m_Doc to the database for saving. + */ + void WriteToDatabase(); void SaveXMLToDatabase(); void UpdateFromDatabase(); @@ -32,6 +36,15 @@ public: const std::string& GetXMLData() const { return m_XMLData; } tinyxml2::XMLDocument* GetXMLDoc() const { return m_Doc; } + /** + * Out of abundance of safety and clarity of what this saves, this is its own function. + * + * Clears the s element from the flag element and saves the xml to the database. Used to prevent the news + * feed from showing up on world transfers. + * + */ + void SetIsNewLogin(); + /** * Gets the database ID of the character * @return the database ID of the character @@ -427,7 +440,7 @@ public: /** * @brief Get the flying state - * @return value of the flying state + * @return value of the flying state */ bool GetIsFlying() { return m_IsFlying; } diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index ddbad03a..6779a42c 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -227,6 +227,7 @@ void UserManager::RequestCharacterList(const SystemAddress& sysAddr) { while (res->next()) { LWOOBJID objID = res->getUInt64(1); Character* character = new Character(uint32_t(objID), u); + character->SetIsNewLogin(); chars.push_back(character); } } From 63460ea00d944ccb0c1ab7735010c90c028d1e84 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 30 Nov 2022 01:04:46 -0800 Subject: [PATCH 151/322] Fix bricks not creating new stacks (#860) Unintentionally, bricks were not creating new stacks if you tried to get another stack. This prevents some missions from being completed. This issue is now fixed --- dGame/dComponents/InventoryComponent.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 77f3f035..acf1ae6a 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -209,8 +209,10 @@ void InventoryComponent::AddItem( auto stack = static_cast<uint32_t>(info.stackSize); + bool isBrick = inventoryType == eInventoryType::BRICKS || (stack == 0 && info.itemType == 1); + // info.itemType of 1 is item type brick - if (inventoryType == eInventoryType::BRICKS || (stack == 0 && info.itemType == 1)) { + if (isBrick) { stack = UINT32_MAX; } else if (stack == 0) { stack = 1; @@ -233,7 +235,7 @@ void InventoryComponent::AddItem( } // If we have some leftover and we aren't bricks, make a new stack - while (left > 0 && !(inventoryType == eInventoryType::BRICKS || (stack == 0 && info.itemType == 1))) { + while (left > 0 && (!isBrick || (isBrick && !existing))) { const auto size = std::min(left, stack); left -= size; From 2b9c014b86e8c5f8cd8a50577b8a2877563d4b42 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 2 Dec 2022 01:44:20 -0700 Subject: [PATCH 152/322] Quiet activity manager timer logs (#861) --- dScripts/ActivityManager.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dScripts/ActivityManager.cpp b/dScripts/ActivityManager.cpp index 18d72311..36e85b11 100644 --- a/dScripts/ActivityManager.cpp +++ b/dScripts/ActivityManager.cpp @@ -124,7 +124,7 @@ void ActivityManager::ActivityTimerStart(Entity* self, const std::string& timerN auto* timer = new ActivityTimer{ timerName, updateInterval, stopTime }; activeTimers.push_back(timer); - Game::logger->Log("ActivityManager", "Starting timer '%s', %f, %f", timerName.c_str(), updateInterval, stopTime); + Game::logger->LogDebug("ActivityManager", "Starting timer '%s', %f, %f", timerName.c_str(), updateInterval, stopTime); self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); } @@ -205,10 +205,10 @@ void ActivityManager::OnTimerDone(Entity* self, std::string timerName) { activeTimers.erase(std::remove(activeTimers.begin(), activeTimers.end(), timer), activeTimers.end()); delete timer; - Game::logger->Log("ActivityManager", "Executing timer '%s'", activityTimerName.c_str()); + Game::logger->LogDebug("ActivityManager", "Executing timer '%s'", activityTimerName.c_str()); OnActivityTimerDone(self, activityTimerName); } else { - Game::logger->Log("ActivityManager", "Updating timer '%s'", activityTimerName.c_str()); + Game::logger->LogDebug("ActivityManager", "Updating timer '%s'", activityTimerName.c_str()); OnActivityTimerUpdate(self, timer->name, timer->stopTime - timer->runTime, timer->runTime); self->AddTimer(GetPrefixedName(timer->name), timer->updateInterval); } From d8945e9067fe56175259f943fa432d57c4da471c Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 2 Dec 2022 04:46:54 -0700 Subject: [PATCH 153/322] Add migration to make play_key_id nullable (#857) since there is an option not to use play_keys --- migrations/dlu/7_make_play_key_id_nullable.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 migrations/dlu/7_make_play_key_id_nullable.sql diff --git a/migrations/dlu/7_make_play_key_id_nullable.sql b/migrations/dlu/7_make_play_key_id_nullable.sql new file mode 100644 index 00000000..7491874f --- /dev/null +++ b/migrations/dlu/7_make_play_key_id_nullable.sql @@ -0,0 +1 @@ +ALTER TABLE account MODIFY play_key_id INT DEFAULT 0; From e1af528d9b7fa849d99264dcae2971bac305419a Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 2 Dec 2022 03:47:27 -0800 Subject: [PATCH 154/322] Add SlashCommand for spawngroup (#858) --- dGame/dUtilities/SlashCommandHandler.cpp | 51 ++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 2f4d9211..79e61bae 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -1264,6 +1264,57 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit EntityManager::Instance()->ConstructEntity(newEntity); } + if (chatCommand == "spawngroup" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 3) { + auto controllablePhysicsComponent = entity->GetComponent<ControllablePhysicsComponent>(); + if (!controllablePhysicsComponent) return; + + LOT lot{}; + uint32_t numberToSpawn{}; + float radiusToSpawnWithin{}; + + if (!GeneralUtils::TryParse(args[0], lot)) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid lot."); + return; + } + + if (!GeneralUtils::TryParse(args[1], numberToSpawn) && numberToSpawn > 0) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid number of enemies to spawn."); + return; + } + + // Must spawn within a radius of at least 0.0f + if (!GeneralUtils::TryParse(args[2], radiusToSpawnWithin) && radiusToSpawnWithin < 0.0f) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid radius to spawn within."); + return; + } + + EntityInfo info; + info.lot = lot; + info.spawner = nullptr; + info.spawnerID = entity->GetObjectID(); + info.spawnerNodeID = 0; + + auto playerPosition = controllablePhysicsComponent->GetPosition(); + while (numberToSpawn > 0) { + auto randomAngle = GeneralUtils::GenerateRandomNumber<float>(0.0f, 2 * PI); + auto randomRadius = GeneralUtils::GenerateRandomNumber<float>(0.0f, radiusToSpawnWithin); + + // Set the position to the generated random position plus the player position. This will + // spawn the entity in a circle around the player. As you get further from the player, the angle chosen will get less accurate. + info.pos = playerPosition + NiPoint3(cos(randomAngle) * randomRadius, 0.0f, sin(randomAngle) * randomRadius); + info.rot = NiQuaternion(); + + auto newEntity = EntityManager::Instance()->CreateEntity(info); + if (newEntity == nullptr) { + ChatPackets::SendSystemMessage(sysAddr, u"Failed to spawn entity."); + return; + } + + EntityManager::Instance()->ConstructEntity(newEntity); + numberToSpawn--; + } + } + if ((chatCommand == "giveuscore") && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { int32_t uscore; From ab5adea24c7b603b58b2c57d39fc53a17dde9113 Mon Sep 17 00:00:00 2001 From: Wincent Holm <wincent.holm@gmail.com> Date: Sat, 3 Dec 2022 13:17:13 +0100 Subject: [PATCH 155/322] Move CDServer migration history table (#867) --- dDatabase/MigrationRunner.cpp | 37 +++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index fe0f933a..31fb9148 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -94,6 +94,10 @@ void MigrationRunner::RunMigrations() { } void MigrationRunner::RunSQLiteMigrations() { + auto cdstmt = CDClientDatabase::CreatePreppedStmt("CREATE TABLE IF NOT EXISTS migration_history (name TEXT NOT NULL, date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP);"); + cdstmt.execQuery().finalize(); + cdstmt.finalize(); + auto* stmt = Database::CreatePreppedStmt("CREATE TABLE IF NOT EXISTS migration_history (name TEXT NOT NULL, date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP());"); stmt->execute(); delete stmt; @@ -103,13 +107,31 @@ void MigrationRunner::RunSQLiteMigrations() { if (migration.data.empty()) continue; + // Check if there is an entry in the migration history table on the cdclient database. + cdstmt = CDClientDatabase::CreatePreppedStmt("SELECT name FROM migration_history WHERE name = ?;"); + cdstmt.bind((int32_t) 1, migration.name.c_str()); + auto cdres = cdstmt.execQuery(); + bool doExit = !cdres.eof(); + cdres.finalize(); + cdstmt.finalize(); + + if (doExit) continue; + + // Check first if there is entry in the migration history table on the main database. stmt = Database::CreatePreppedStmt("SELECT name FROM migration_history WHERE name = ?;"); stmt->setString(1, migration.name.c_str()); auto* res = stmt->executeQuery(); - bool doExit = res->next(); + doExit = res->next(); delete res; delete stmt; - if (doExit) continue; + if (doExit) { + // Insert into cdclient database if there is an entry in the main database but not the cdclient database. + cdstmt = CDClientDatabase::CreatePreppedStmt("INSERT INTO migration_history (name) VALUES (?);"); + cdstmt.bind((int32_t) 1, migration.name.c_str()); + cdstmt.execQuery().finalize(); + cdstmt.finalize(); + continue; + } // Doing these 1 migration at a time since one takes a long time and some may think it is crashing. // This will at the least guarentee that the full migration needs to be run in order to be counted as "migrated". @@ -122,10 +144,13 @@ void MigrationRunner::RunSQLiteMigrations() { Game::logger->Log("MigrationRunner", "Encountered error running DML command: (%i) : %s", e.errorCode(), e.errorMessage()); } } - stmt = Database::CreatePreppedStmt("INSERT INTO migration_history (name) VALUES (?);"); - stmt->setString(1, migration.name); - stmt->execute(); - delete stmt; + + // Insert into cdclient database. + cdstmt = CDClientDatabase::CreatePreppedStmt("INSERT INTO migration_history (name) VALUES (?);"); + cdstmt.bind((int32_t) 1, migration.name.c_str()); + cdstmt.execQuery().finalize(); + cdstmt.finalize(); } + Game::logger->Log("MigrationRunner", "CDServer database is up to date."); } From de3e53de6cbcbf599d2c6f9fedbd14883ee6b0a1 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 4 Dec 2022 14:25:25 -0800 Subject: [PATCH 156/322] Fix Model Vault (#870) Allow pets, rockets and racecars to be stored in vault --- dGame/dComponents/InventoryComponent.cpp | 6 ++++-- dGame/dGameMessages/GameMessages.cpp | 14 +++++++------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index acf1ae6a..8215664c 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -330,7 +330,9 @@ void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType in const auto lot = item->GetLot(); - if (item->GetConfig().empty() && !item->GetBound() || (item->GetBound() && item->GetInfo().isBOP)) { + const auto subkey = item->GetSubKey(); + + if (subkey == LWOOBJID_EMPTY && item->GetConfig().empty() && (!item->GetBound() || (item->GetBound() && item->GetInfo().isBOP))) { auto left = std::min<uint32_t>(count, origin->GetLotCount(lot)); while (left > 0) { @@ -361,7 +363,7 @@ void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType in const auto delta = std::min<uint32_t>(item->GetCount(), count); - AddItem(lot, delta, eLootSourceType::LOOT_SOURCE_NONE, inventory, config, LWOOBJID_EMPTY, showFlyingLot, isModMoveAndEquip, LWOOBJID_EMPTY, origin->GetType(), 0, item->GetBound(), preferredSlot); + AddItem(lot, delta, eLootSourceType::LOOT_SOURCE_NONE, inventory, config, LWOOBJID_EMPTY, showFlyingLot, isModMoveAndEquip, subkey, origin->GetType(), 0, item->GetBound(), preferredSlot); item->SetCount(item->GetCount() - delta, false, false); } diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 6639197c..fcc25fdc 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -4462,13 +4462,13 @@ void GameMessages::SendAddBuff(LWOOBJID& objectID, const LWOOBJID& casterID, uin // NT void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - bool bAllowPartial; + bool bAllowPartial{}; int32_t destSlot = -1; int32_t iStackCount = 1; eInventoryType invTypeDst = ITEMS; eInventoryType invTypeSrc = ITEMS; LWOOBJID itemID = LWOOBJID_EMPTY; - bool showFlyingLoot; + bool showFlyingLoot{}; LWOOBJID subkey = LWOOBJID_EMPTY; LOT itemLOT = 0; @@ -4492,12 +4492,12 @@ void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* if (itemID != LWOOBJID_EMPTY) { auto* item = inventoryComponent->FindItemById(itemID); - if (item == nullptr) { - return; - } + if (!item) return; - if (inventoryComponent->IsPet(item->GetSubKey()) || !item->GetConfig().empty()) { - return; + // Despawn the pet if we are moving that pet to the vault. + auto* petComponent = PetComponent::GetActivePet(entity->GetObjectID()); + if (petComponent && petComponent->GetDatabaseId() == item->GetSubKey()) { + inventoryComponent->DespawnPet(); } inventoryComponent->MoveItemToInventory(item, invTypeDst, iStackCount, showFlyingLoot, false, false, destSlot); From e8ba3357e8c28f22136babdcd6a6a9e489fc520c Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 4 Dec 2022 14:25:58 -0800 Subject: [PATCH 157/322] Add support to reload the config (#868) --- dCommon/dConfig.cpp | 56 ++++++++----------- dCommon/dConfig.h | 24 ++++++-- .../dComponents/ScriptedActivityComponent.cpp | 18 +++++- dGame/dComponents/ScriptedActivityComponent.h | 12 ++++ dGame/dUtilities/SlashCommandHandler.cpp | 15 +++++ dMasterServer/MasterServer.cpp | 29 +++++----- dPhysics/dpGrid.cpp | 2 + dPhysics/dpGrid.h | 10 ++++ dPhysics/dpWorld.cpp | 44 +++++++++++---- dPhysics/dpWorld.h | 4 +- dWorldServer/WorldServer.cpp | 2 - 11 files changed, 150 insertions(+), 66 deletions(-) diff --git a/dCommon/dConfig.cpp b/dCommon/dConfig.cpp index 1bc940e8..f09a44c1 100644 --- a/dCommon/dConfig.cpp +++ b/dCommon/dConfig.cpp @@ -1,61 +1,53 @@ #include "dConfig.h" + #include <sstream> + #include "BinaryPathFinder.h" +#include "GeneralUtils.h" dConfig::dConfig(const std::string& filepath) { - m_EmptyString = ""; - std::ifstream in(BinaryPathFinder::GetBinaryDir() / filepath); + m_ConfigFilePath = filepath; + LoadConfig(); +} + +void dConfig::LoadConfig() { + std::ifstream in(BinaryPathFinder::GetBinaryDir() / m_ConfigFilePath); if (!in.good()) return; - std::string line; + std::string line{}; while (std::getline(in, line)) { - if (line.length() > 0) { - if (line[0] != '#') ProcessLine(line); - } + if (!line.empty() && line.front() != '#') ProcessLine(line); } std::ifstream sharedConfig(BinaryPathFinder::GetBinaryDir() / "sharedconfig.ini", std::ios::in); if (!sharedConfig.good()) return; + line.clear(); while (std::getline(sharedConfig, line)) { - if (line.length() > 0) { - if (line[0] != '#') ProcessLine(line); - } + if (!line.empty() && line.front() != '#') ProcessLine(line); } } -dConfig::~dConfig(void) { +void dConfig::ReloadConfig() { + this->m_ConfigValues.clear(); + LoadConfig(); } const std::string& dConfig::GetValue(std::string key) { - for (size_t i = 0; i < m_Keys.size(); ++i) { - if (m_Keys[i] == key) return m_Values[i]; - } - - return m_EmptyString; + return this->m_ConfigValues[key]; } void dConfig::ProcessLine(const std::string& line) { - std::stringstream ss(line); - std::string segment; - std::vector<std::string> seglist; + auto splitLine = GeneralUtils::SplitString(line, '='); - while (std::getline(ss, segment, '=')) { - seglist.push_back(segment); - } - - if (seglist.size() != 2) return; + if (splitLine.size() != 2) return; //Make sure that on Linux, we remove special characters: - if (!seglist[1].empty() && seglist[1][seglist[1].size() - 1] == '\r') - seglist[1].erase(seglist[1].size() - 1); + auto& key = splitLine.at(0); + auto& value = splitLine.at(1); + if (!value.empty() && value.at(value.size() - 1) == '\r') value.erase(value.size() - 1); - for (const auto& key : m_Keys) { - if (seglist[0] == key) { - return; // first loaded key is preferred due to loading shared config secondarily - } - } + if (this->m_ConfigValues.find(key) != this->m_ConfigValues.end()) return; - m_Keys.push_back(seglist[0]); - m_Values.push_back(seglist[1]); + this->m_ConfigValues.insert(std::make_pair(key, value)); } diff --git a/dCommon/dConfig.h b/dCommon/dConfig.h index 7764fa54..a6dd5df7 100644 --- a/dCommon/dConfig.h +++ b/dCommon/dConfig.h @@ -1,20 +1,34 @@ #pragma once #include <fstream> +#include <map> #include <string> -#include <vector> class dConfig { public: dConfig(const std::string& filepath); - ~dConfig(void); + /** + * Gets the specified key from the config. Returns an empty string if the value is not found. + * + * @param key Key to find + * @return The keys value in the config + */ const std::string& GetValue(std::string key); + /** + * Loads the config from a file + */ + void LoadConfig(); + + /** + * Reloads the config file to reset values + */ + void ReloadConfig(); + private: void ProcessLine(const std::string& line); private: - std::vector<std::string> m_Keys; - std::vector<std::string> m_Values; - std::string m_EmptyString; + std::map<std::string, std::string> m_ConfigValues; + std::string m_ConfigFilePath; }; diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index 4b5ec41d..f6d50d66 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -19,8 +19,9 @@ #include "DestroyableComponent.h" ScriptedActivityComponent::ScriptedActivityComponent(Entity* parent, int activityID) : Component(parent) { + m_ActivityID = activityID; CDActivitiesTable* activitiesTable = CDClientManager::Instance()->GetTable<CDActivitiesTable>("Activities"); - std::vector<CDActivities> activities = activitiesTable->Query([=](CDActivities entry) {return (entry.ActivityID == activityID); }); + std::vector<CDActivities> activities = activitiesTable->Query([=](CDActivities entry) {return (entry.ActivityID == m_ActivityID); }); for (CDActivities activity : activities) { m_ActivityInfo = activity; @@ -88,6 +89,21 @@ void ScriptedActivityComponent::Serialize(RakNet::BitStream* outBitStream, bool } } +void ScriptedActivityComponent::ReloadConfig() { + CDActivitiesTable* activitiesTable = CDClientManager::Instance()->GetTable<CDActivitiesTable>("Activities"); + std::vector<CDActivities> activities = activitiesTable->Query([=](CDActivities entry) {return (entry.ActivityID == m_ActivityID); }); + for (auto activity : activities) { + auto mapID = m_ActivityInfo.instanceMapID; + if ((mapID == 1203 || mapID == 1261 || mapID == 1303 || mapID == 1403) && Game::config->GetValue("solo_racing") == "1") { + m_ActivityInfo.minTeamSize = 1; + m_ActivityInfo.minTeams = 1; + } else { + m_ActivityInfo.minTeamSize = activity.minTeamSize; + m_ActivityInfo.minTeams = activity.minTeams; + } + } +} + void ScriptedActivityComponent::HandleMessageBoxResponse(Entity* player, const std::string& id) { if (m_ActivityInfo.ActivityID == 103) { return; diff --git a/dGame/dComponents/ScriptedActivityComponent.h b/dGame/dComponents/ScriptedActivityComponent.h index 66ca799f..8bb17093 100644 --- a/dGame/dComponents/ScriptedActivityComponent.h +++ b/dGame/dComponents/ScriptedActivityComponent.h @@ -276,6 +276,12 @@ public: */ ActivityInstance* GetInstance(const LWOOBJID playerID); + /** + * @brief Reloads the config settings for this component + * + */ + void ReloadConfig(); + /** * Removes all the instances */ @@ -361,6 +367,12 @@ private: * LMIs for team sizes */ std::unordered_map<uint32_t, uint32_t> m_ActivityLootMatrices; + + /** + * The activity id + * + */ + int32_t m_ActivityID; }; #endif // SCRIPTEDACTIVITYCOMPONENT_H diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 79e61bae..60862c1a 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -65,6 +65,7 @@ #include "LevelProgressionComponent.h" #include "AssetManager.h" #include "BinaryPathFinder.h" +#include "dConfig.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { std::string chatCommand; @@ -1766,6 +1767,20 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } + if (chatCommand == "reloadconfig" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + Game::config->ReloadConfig(); + VanityUtilities::SpawnVanity(); + dpWorld::Instance().Reload(); + auto entities = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY); + for (auto entity : entities) { + auto* scriptedActivityComponent = entity->GetComponent<ScriptedActivityComponent>(); + if (!scriptedActivityComponent) continue; + + scriptedActivityComponent->ReloadConfig(); + } + ChatPackets::SendSystemMessage(sysAddr, u"Successfully reloaded config for world!"); + } + if (chatCommand == "rollloot" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && args.size() >= 3) { uint32_t lootMatrixIndex = 0; uint32_t targetLot = 0; diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 34e2f71a..0a387d8e 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -82,17 +82,15 @@ int main(int argc, char** argv) { Game::logger->Log("MasterServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("MasterServer", "Compiled on: %s", __TIMESTAMP__); - //Read our config: - dConfig config("masterconfig.ini"); - Game::config = &config; - Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); - Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); + Game::config = new dConfig("masterconfig.ini"); + Game::logger->SetLogToConsole(bool(std::stoi(Game::config->GetValue("log_to_console")))); + Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); //Connect to the MySQL Database - std::string mysql_host = config.GetValue("mysql_host"); - std::string mysql_database = config.GetValue("mysql_database"); - std::string mysql_username = config.GetValue("mysql_username"); - std::string mysql_password = config.GetValue("mysql_password"); + std::string mysql_host = Game::config->GetValue("mysql_host"); + std::string mysql_database = Game::config->GetValue("mysql_database"); + std::string mysql_username = Game::config->GetValue("mysql_username"); + std::string mysql_password = Game::config->GetValue("mysql_password"); try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); @@ -103,7 +101,7 @@ int main(int argc, char** argv) { } try { - std::string clientPathStr = config.GetValue("client_location"); + std::string clientPathStr = Game::config->GetValue("client_location"); if (clientPathStr.empty()) clientPathStr = "./res"; std::filesystem::path clientPath = std::filesystem::path(clientPathStr); if (clientPath.is_relative()) { @@ -223,16 +221,16 @@ int main(int argc, char** argv) { int maxClients = 999; int ourPort = 1000; - if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); - if (config.GetValue("port") != "") ourPort = std::stoi(config.GetValue("port")); + if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients")); + if (Game::config->GetValue("port") != "") ourPort = std::stoi(Game::config->GetValue("port")); - Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, true, false, Game::logger, "", 0, ServerType::Master); + Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, true, false, Game::logger, "", 0, ServerType::Master); //Query for the database for a server labeled "master" auto* masterLookupStatement = Database::CreatePreppedStmt("SELECT id FROM `servers` WHERE `name` = 'master'"); auto* result = masterLookupStatement->executeQuery(); - auto master_server_ip = config.GetValue("master_ip"); + auto master_server_ip = Game::config->GetValue("master_ip"); if (master_server_ip == "") { master_server_ip = Game::server->GetIP(); @@ -260,7 +258,7 @@ int main(int argc, char** argv) { Game::im = new InstanceManager(Game::logger, Game::server->GetIP()); //Depending on the config, start up servers: - if (config.GetValue("prestart_servers") != "" && config.GetValue("prestart_servers") == "1") { + if (Game::config->GetValue("prestart_servers") != "" && Game::config->GetValue("prestart_servers") == "1") { StartChatServer(); Game::im->GetInstance(0, false, 0)->SetIsReady(true); @@ -843,6 +841,7 @@ void ShutdownSequence() { int FinalizeShutdown() { //Delete our objects here: Database::Destroy("MasterServer"); + if (Game::config) delete Game::config; if (Game::im) delete Game::im; if (Game::server) delete Game::server; if (Game::logger) delete Game::logger; diff --git a/dPhysics/dpGrid.cpp b/dPhysics/dpGrid.cpp index 6e44ade9..b4fe385e 100644 --- a/dPhysics/dpGrid.cpp +++ b/dPhysics/dpGrid.cpp @@ -6,6 +6,7 @@ dpGrid::dpGrid(int numCells, int cellSize) { NUM_CELLS = numCells; CELL_SIZE = cellSize; + m_DeleteGrid = true; //dumb method but i can't be bothered @@ -23,6 +24,7 @@ dpGrid::dpGrid(int numCells, int cellSize) { } dpGrid::~dpGrid() { + if (!this->m_DeleteGrid) return; for (auto& x : m_Cells) { //x for (auto& y : x) { //y for (auto en : y) { diff --git a/dPhysics/dpGrid.h b/dPhysics/dpGrid.h index a10f165e..229e7449 100644 --- a/dPhysics/dpGrid.h +++ b/dPhysics/dpGrid.h @@ -23,6 +23,15 @@ public: void Update(float deltaTime); + /** + * Sets the delete grid parameter to value. When false, the grid will not clean up memory. + * + * @param value Whether or not to delete entities on deletion of the grid. + */ + void SetDeleteGrid(bool value) { this->m_DeleteGrid = value; }; + + std::vector<std::vector<std::forward_list<dpEntity*>>> GetCells() { return this->m_Cells; }; + private: void HandleEntity(dpEntity* entity, dpEntity* other); void HandleCell(int x, int z, float deltaTime); @@ -31,4 +40,5 @@ private: //cells on X, cells on Y for that X, then another vector that contains the entities within that cell. std::vector<std::vector<std::forward_list<dpEntity*>>> m_Cells; std::map<LWOOBJID, dpEntity*> m_GargantuanObjects; + bool m_DeleteGrid = true; }; diff --git a/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index 510da518..70fbfa3a 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -9,7 +9,7 @@ #include "dLogger.h" #include "dConfig.h" -void dpWorld::Initialize(unsigned int zoneID) { +void dpWorld::Initialize(unsigned int zoneID, bool generateNewNavMesh) { phys_sp_tilecount = std::atoi(Game::config->GetValue("phys_sp_tilecount").c_str()); phys_sp_tilesize = std::atoi(Game::config->GetValue("phys_sp_tilesize").c_str()); @@ -21,13 +21,37 @@ void dpWorld::Initialize(unsigned int zoneID) { m_Grid = new dpGrid(phys_sp_tilecount, phys_sp_tilesize); } - m_NavMesh = new dNavMesh(zoneID); + if (generateNewNavMesh) m_NavMesh = new dNavMesh(zoneID); Game::logger->Log("dpWorld", "Physics world initialized!"); + m_ZoneID = zoneID; +} + +void dpWorld::Reload() { + if (m_Grid) { + m_Grid->SetDeleteGrid(false); + auto oldGridCells = m_Grid->GetCells(); + delete m_Grid; + m_Grid = nullptr; + + Initialize(m_ZoneID, false); + for (auto column : oldGridCells) { + for (auto row : column) { + for (auto entity : row) { + AddEntity(entity); + } + } + } + Game::logger->Log("dpWorld", "Successfully reloaded physics world!"); + } else { + Game::logger->Log("dpWorld", "No physics world to reload!"); + } } dpWorld::~dpWorld() { if (m_Grid) { + // Triple check this is true + m_Grid->SetDeleteGrid(true); delete m_Grid; m_Grid = nullptr; } @@ -103,14 +127,14 @@ bool dpWorld::ShouldUseSP(unsigned int zoneID) { // Only large maps should be added as tiling likely makes little difference on small maps. switch (zoneID) { - case 1100: // Avant Gardens - case 1200: // Nimbus Station - case 1300: // Gnarled Forest - case 1400: // Forbidden Valley - case 1800: // Crux Prime - case 1900: // Nexus Tower - case 2000: // Ninjago - return true; + case 1100: // Avant Gardens + case 1200: // Nimbus Station + case 1300: // Gnarled Forest + case 1400: // Forbidden Valley + case 1800: // Crux Prime + case 1900: // Nexus Tower + case 2000: // Ninjago + return true; } return false; diff --git a/dPhysics/dpWorld.h b/dPhysics/dpWorld.h index 45e550cb..d48435d0 100644 --- a/dPhysics/dpWorld.h +++ b/dPhysics/dpWorld.h @@ -19,7 +19,8 @@ class dpGrid; class dpWorld : public Singleton<dpWorld> { public: - void Initialize(unsigned int zoneID); + void Initialize(unsigned int zoneID, bool generateNewNavMesh = true); + void Reload(); ~dpWorld(); @@ -43,4 +44,5 @@ private: std::vector<dpEntity*> m_DynamicEntites; dNavMesh* m_NavMesh = nullptr; + uint32_t m_ZoneID = 0; }; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index bbba1166..b4be7511 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -250,7 +250,6 @@ int main(int argc, char** argv) { //Load our level: if (zoneID != 0) { dpWorld::Instance().Initialize(zoneID); - Game::physicsWorld = &dpWorld::Instance(); //just in case some old code references it dZoneManager::Instance()->Initialize(LWOZONEID(zoneID, instanceID, cloneID)); g_CloneID = cloneID; @@ -1281,7 +1280,6 @@ void WorldShutdownSequence() { void FinalizeShutdown() { //Delete our objects here: - if (Game::physicsWorld) Game::physicsWorld = nullptr; if (Game::zoneManager) delete Game::zoneManager; Game::logger->Log("WorldServer", "Shutdown complete, zone (%i), instance (%i)", Game::server->GetZoneID(), instanceID); From 2ba3103a0c69252976f5114c67197be38753fabb Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 5 Dec 2022 00:57:58 -0800 Subject: [PATCH 158/322] Implement FDB to SQLite (#872) --- dCommon/CMakeLists.txt | 1 + dCommon/FdbToSqlite.cpp | 248 +++++++++++++++++++++++++++++++ dCommon/FdbToSqlite.h | 49 ++++++ dCommon/dEnums/eSqliteDataType.h | 16 ++ dDatabase/MigrationRunner.cpp | 2 + dMasterServer/MasterServer.cpp | 14 +- 6 files changed, 319 insertions(+), 11 deletions(-) create mode 100644 dCommon/FdbToSqlite.cpp create mode 100644 dCommon/FdbToSqlite.h create mode 100644 dCommon/dEnums/eSqliteDataType.h diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 8d02186b..549acfb2 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -16,6 +16,7 @@ set(DCOMMON_SOURCES "AMFFormat.cpp" "ZCompression.cpp" "BrickByBrickFix.cpp" "BinaryPathFinder.cpp" + "FdbToSqlite.cpp" ) add_subdirectory(dClient) diff --git a/dCommon/FdbToSqlite.cpp b/dCommon/FdbToSqlite.cpp new file mode 100644 index 00000000..d98d4962 --- /dev/null +++ b/dCommon/FdbToSqlite.cpp @@ -0,0 +1,248 @@ +#include "FdbToSqlite.h" + +#include <map> +#include <fstream> +#include <cassert> +#include <iomanip> + +#include "BinaryIO.h" +#include "CDClientDatabase.h" +#include "GeneralUtils.h" +#include "Game.h" +#include "dLogger.h" + +#include "eSqliteDataType.h" + +std::map<eSqliteDataType, std::string> FdbToSqlite::Convert::sqliteType = { + { eSqliteDataType::NONE, "none"}, + { eSqliteDataType::INT32, "int32"}, + { eSqliteDataType::REAL, "real"}, + { eSqliteDataType::TEXT_4, "text_4"}, + { eSqliteDataType::INT_BOOL, "int_bool"}, + { eSqliteDataType::INT64, "int64"}, + { eSqliteDataType::TEXT_8, "text_8"} +}; + +FdbToSqlite::Convert::Convert(std::string basePath) { + this->basePath = basePath; +} + +bool FdbToSqlite::Convert::ConvertDatabase() { + fdb.open(basePath + "/cdclient.fdb", std::ios::binary); + + try { + CDClientDatabase::Connect(basePath + "/CDServer.sqlite"); + + CDClientDatabase::ExecuteQuery("BEGIN TRANSACTION;"); + + int32_t numberOfTables = ReadInt32(); + ReadTables(numberOfTables); + + CDClientDatabase::ExecuteQuery("COMMIT;"); + } catch (CppSQLite3Exception& e) { + Game::logger->Log("FdbToSqlite", "Encountered error %s converting FDB to SQLite", e.errorMessage()); + return false; + } + + fdb.close(); + return true; +} + +int32_t FdbToSqlite::Convert::ReadInt32() { + uint32_t numberOfTables{}; + BinaryIO::BinaryRead(fdb, numberOfTables); + return numberOfTables; +} + +int64_t FdbToSqlite::Convert::ReadInt64() { + int32_t prevPosition = SeekPointer(); + + int64_t value{}; + BinaryIO::BinaryRead(fdb, value); + + fdb.seekg(prevPosition); + return value; +} + +std::string FdbToSqlite::Convert::ReadString() { + int32_t prevPosition = SeekPointer(); + + auto readString = BinaryIO::ReadString(fdb); + + fdb.seekg(prevPosition); + return readString; +} + +int32_t FdbToSqlite::Convert::SeekPointer() { + int32_t position{}; + BinaryIO::BinaryRead(fdb, position); + int32_t prevPosition = fdb.tellg(); + fdb.seekg(position); + return prevPosition; +} + +std::string FdbToSqlite::Convert::ReadColumnHeader() { + int32_t prevPosition = SeekPointer(); + + int32_t numberOfColumns = ReadInt32(); + std::string tableName = ReadString(); + + auto columns = ReadColumns(numberOfColumns); + std::string newTable = "CREATE TABLE IF NOT EXISTS '" + tableName + "' (" + columns + ");"; + CDClientDatabase::ExecuteDML(newTable); + + fdb.seekg(prevPosition); + + return tableName; +} + +void FdbToSqlite::Convert::ReadTables(int32_t& numberOfTables) { + int32_t prevPosition = SeekPointer(); + + for (int32_t i = 0; i < numberOfTables; i++) { + auto columnHeader = ReadColumnHeader(); + ReadRowHeader(columnHeader); + } + + fdb.seekg(prevPosition); +} + +std::string FdbToSqlite::Convert::ReadColumns(int32_t& numberOfColumns) { + std::stringstream columnsToCreate; + int32_t prevPosition = SeekPointer(); + + std::string name{}; + eSqliteDataType dataType{}; + for (int32_t i = 0; i < numberOfColumns; i++) { + if (i != 0) columnsToCreate << ", "; + dataType = static_cast<eSqliteDataType>(ReadInt32()); + name = ReadString(); + columnsToCreate << "'" << name << "' " << FdbToSqlite::Convert::sqliteType[dataType]; + } + + fdb.seekg(prevPosition); + return columnsToCreate.str(); +} + +void FdbToSqlite::Convert::ReadRowHeader(std::string& tableName) { + int32_t prevPosition = SeekPointer(); + + int32_t numberOfAllocatedRows = ReadInt32(); + if (numberOfAllocatedRows != 0) assert((numberOfAllocatedRows & (numberOfAllocatedRows - 1)) == 0); // assert power of 2 allocation size + ReadRows(numberOfAllocatedRows, tableName); + + fdb.seekg(prevPosition); +} + +void FdbToSqlite::Convert::ReadRows(int32_t& numberOfAllocatedRows, std::string& tableName) { + int32_t prevPosition = SeekPointer(); + + int32_t rowid = 0; + for (int32_t row = 0; row < numberOfAllocatedRows; row++) { + int32_t rowPointer = ReadInt32(); + if (rowPointer == -1) rowid++; + else ReadRow(rowid, rowPointer, tableName); + } + + fdb.seekg(prevPosition); +} + +void FdbToSqlite::Convert::ReadRow(int32_t& rowid, int32_t& position, std::string& tableName) { + int32_t prevPosition = fdb.tellg(); + fdb.seekg(position); + + while (true) { + ReadRowInfo(tableName); + int32_t linked = ReadInt32(); + + rowid += 1; + + if (linked == -1) break; + + fdb.seekg(linked); + } + + fdb.seekg(prevPosition); +} + +void FdbToSqlite::Convert::ReadRowInfo(std::string& tableName) { + int32_t prevPosition = SeekPointer(); + + int32_t numberOfColumns = ReadInt32(); + ReadRowValues(numberOfColumns, tableName); + + fdb.seekg(prevPosition); +} + +void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& tableName) { + int32_t prevPosition = SeekPointer(); + + int32_t emptyValue{}; + int32_t intValue{}; + float_t floatValue{}; + std::string stringValue{}; + int32_t boolValue{}; + int64_t int64Value{}; + bool insertedFirstEntry = false; + std::stringstream insertedRow; + insertedRow << "INSERT INTO " << tableName << " values ("; + + for (int32_t i = 0; i < numberOfColumns; i++) { + if (i != 0) insertedRow << ", "; // Only append comma and space after first entry in row. + switch (static_cast<eSqliteDataType>(ReadInt32())) { + case eSqliteDataType::NONE: + BinaryIO::BinaryRead(fdb, emptyValue); + assert(emptyValue == 0); + insertedRow << "\"\""; + break; + + case eSqliteDataType::INT32: + intValue = ReadInt32(); + insertedRow << intValue; + break; + + case eSqliteDataType::REAL: + BinaryIO::BinaryRead(fdb, floatValue); + insertedRow << std::fixed << std::setprecision(34) << floatValue; // maximum precision of floating point number + break; + + case eSqliteDataType::TEXT_4: + case eSqliteDataType::TEXT_8: { + stringValue = ReadString(); + size_t position = 0; + + // Need to escape quote with a double of ". + while (position < stringValue.size()) { + if (stringValue.at(position) == '\"') { + stringValue.insert(position, "\""); + position++; + } + position++; + } + insertedRow << "\"" << stringValue << "\""; + break; + } + + case eSqliteDataType::INT_BOOL: + BinaryIO::BinaryRead(fdb, boolValue); + insertedRow << static_cast<bool>(boolValue); + break; + + case eSqliteDataType::INT64: + int64Value = ReadInt64(); + insertedRow << std::to_string(int64Value); + break; + + default: + throw std::invalid_argument("Unsupported SQLite type encountered."); + break; + + } + } + + insertedRow << ");"; + + auto copiedString = insertedRow.str(); + CDClientDatabase::ExecuteDML(copiedString); + fdb.seekg(prevPosition); +} diff --git a/dCommon/FdbToSqlite.h b/dCommon/FdbToSqlite.h new file mode 100644 index 00000000..a9611220 --- /dev/null +++ b/dCommon/FdbToSqlite.h @@ -0,0 +1,49 @@ +#ifndef __FDBTOSQLITE__H__ +#define __FDBTOSQLITE__H__ + +#pragma once + +#include <cstdint> +#include <iosfwd> +#include <map> + +enum class eSqliteDataType : int32_t; + +namespace FdbToSqlite { + class Convert { + public: + Convert(std::string inputFile); + + bool ConvertDatabase(); + + int32_t ReadInt32(); + + int64_t ReadInt64(); + + std::string ReadString(); + + int32_t SeekPointer(); + + std::string ReadColumnHeader(); + + void ReadTables(int32_t& numberOfTables); + + std::string ReadColumns(int32_t& numberOfColumns); + + void ReadRowHeader(std::string& tableName); + + void ReadRows(int32_t& numberOfAllocatedRows, std::string& tableName); + + void ReadRow(int32_t& rowid, int32_t& position, std::string& tableName); + + void ReadRowInfo(std::string& tableName); + + void ReadRowValues(int32_t& numberOfColumns, std::string& tableName); + private: + static std::map<eSqliteDataType, std::string> sqliteType; + std::string basePath{}; + std::ifstream fdb{}; + }; // class FdbToSqlite +}; //! namespace FdbToSqlite + +#endif //!__FDBTOSQLITE__H__ diff --git a/dCommon/dEnums/eSqliteDataType.h b/dCommon/dEnums/eSqliteDataType.h new file mode 100644 index 00000000..26e1233b --- /dev/null +++ b/dCommon/dEnums/eSqliteDataType.h @@ -0,0 +1,16 @@ +#ifndef __ESQLITEDATATYPE__H__ +#define __ESQLITEDATATYPE__H__ + +#include <cstdint> + +enum class eSqliteDataType : int32_t { + NONE = 0, + INT32, + REAL = 3, + TEXT_4, + INT_BOOL, + INT64, + TEXT_8 = 8 +}; + +#endif //!__ESQLITEDATATYPE__H__ diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index 31fb9148..d39201b2 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -136,6 +136,7 @@ void MigrationRunner::RunSQLiteMigrations() { // Doing these 1 migration at a time since one takes a long time and some may think it is crashing. // This will at the least guarentee that the full migration needs to be run in order to be counted as "migrated". Game::logger->Log("MigrationRunner", "Executing migration: %s. This may take a while. Do not shut down server.", migration.name.c_str()); + CDClientDatabase::ExecuteQuery("BEGIN TRANSACTION;"); for (const auto& dml : GeneralUtils::SplitString(migration.data, ';')) { if (dml.empty()) continue; try { @@ -150,6 +151,7 @@ void MigrationRunner::RunSQLiteMigrations() { cdstmt.bind((int32_t) 1, migration.name.c_str()); cdstmt.execQuery().finalize(); cdstmt.finalize(); + CDClientDatabase::ExecuteQuery("COMMIT;"); } Game::logger->Log("MigrationRunner", "CDServer database is up to date."); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 0a387d8e..0329d9a0 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -40,6 +40,7 @@ #include "ObjectIDManager.h" #include "PacketUtils.h" #include "dMessageIdentifiers.h" +#include "FdbToSqlite.h" namespace Game { dLogger* logger; @@ -126,18 +127,9 @@ int main(int argc, char** argv) { return EXIT_FAILURE; } - Game::logger->Log("WorldServer", "Found cdclient.fdb. Clearing cdserver migration_history then copying and converting to sqlite."); - auto stmt = Database::CreatePreppedStmt(R"#(DELETE FROM migration_history WHERE name LIKE "%cdserver%";)#"); - stmt->executeUpdate(); - delete stmt; + Game::logger->Log("WorldServer", "Found cdclient.fdb. Converting to SQLite"); - std::string res = "python3 " - + (BinaryPathFinder::GetBinaryDir() / "../thirdparty/docker-utils/utils/fdb_to_sqlite.py").string() - + " --sqlite_path " + (Game::assetManager->GetResPath() / "CDServer.sqlite").string() - + " " + (Game::assetManager->GetResPath() / "cdclient.fdb").string(); - - int result = system(res.c_str()); - if (result != 0) { + if (FdbToSqlite::Convert(Game::assetManager->GetResPath().string()).ConvertDatabase() == false) { Game::logger->Log("MasterServer", "Failed to convert fdb to sqlite"); return EXIT_FAILURE; } From 0a616f891fd4e09bd52c5d68f56099cf62ea7954 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 5 Dec 2022 07:04:59 -0800 Subject: [PATCH 159/322] Change File Finder (#873) --- dCommon/GeneralUtils.cpp | 65 +++++++++++++---------------------- dCommon/GeneralUtils.h | 3 +- dDatabase/MigrationRunner.cpp | 4 +-- 3 files changed, 27 insertions(+), 45 deletions(-) diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index 24ea72a0..54ef5661 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -4,6 +4,8 @@ #include <cstdint> #include <cassert> #include <algorithm> +#include <filesystem> +#include <map> template <typename T> inline size_t MinSize(size_t size, const std::basic_string_view<T>& string) { @@ -290,51 +292,30 @@ std::u16string GeneralUtils::ReadWString(RakNet::BitStream* inStream) { return string; } -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN -#include <Windows.h> - -std::vector<std::string> GeneralUtils::GetFileNamesFromFolder(const std::string& folder) { - std::vector<std::string> names; - std::string search_path = folder + "/*.*"; - WIN32_FIND_DATA fd; - HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd); - if (hFind != INVALID_HANDLE_VALUE) { - do { - if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { - names.push_back(fd.cFileName); - } - } while (::FindNextFile(hFind, &fd)); - ::FindClose(hFind); - } - return names; -} -#else -#include <stdio.h> -#include <dirent.h> -#include <sys/types.h> -#include <iostream> -#include <vector> -#include <cstring> - -std::vector<std::string> GeneralUtils::GetFileNamesFromFolder(const std::string& folder) { - std::vector<std::string> names; - struct dirent* entry; - DIR* dir = opendir(folder.c_str()); - if (dir == NULL) { - return names; +std::vector<std::string> 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<uint32_t, std::string> 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)); } - while ((entry = readdir(dir)) != NULL) { - std::string value(entry->d_name, strlen(entry->d_name)); - if (value == "." || value == "..") { - continue; + // Now sort the map by the oldest migration. + std::vector<std::string> sortedFiles{}; + auto fileIterator = filenames.begin(); + std::map<uint32_t, std::string>::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; } - names.push_back(value); + if (oldest->first > fileIterator->first) oldest = fileIterator; + fileIterator++; } - closedir(dir); - - return names; + return sortedFiles; } -#endif diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index 898616d2..af7c7012 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -12,6 +12,7 @@ #include <BitStream.h> #include "Game.h" +#include "dLogger.h" /*! \file GeneralUtils.hpp @@ -138,7 +139,7 @@ namespace GeneralUtils { std::vector<std::string> SplitString(const std::string& str, char delimiter); - std::vector<std::string> GetFileNamesFromFolder(const std::string& folder); + std::vector<std::string> GetSqlFileNamesFromFolder(const std::string& folder); template <typename T> T Parse(const char* value); diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index d39201b2..54def9e2 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -38,7 +38,7 @@ void MigrationRunner::RunMigrations() { sql::SQLString finalSQL = ""; bool runSd0Migrations = false; - for (const auto& entry : GeneralUtils::GetFileNamesFromFolder((BinaryPathFinder::GetBinaryDir() / "./migrations/dlu/").string())) { + for (const auto& entry : GeneralUtils::GetSqlFileNamesFromFolder((BinaryPathFinder::GetBinaryDir() / "./migrations/dlu/").string())) { auto migration = LoadMigration("dlu/" + entry); if (migration.data.empty()) { @@ -102,7 +102,7 @@ void MigrationRunner::RunSQLiteMigrations() { stmt->execute(); delete stmt; - for (const auto& entry : GeneralUtils::GetFileNamesFromFolder((BinaryPathFinder::GetBinaryDir() / "migrations/cdserver/").string())) { + for (const auto& entry : GeneralUtils::GetSqlFileNamesFromFolder((BinaryPathFinder::GetBinaryDir() / "migrations/cdserver/").string())) { auto migration = LoadMigration("cdserver/" + entry); if (migration.data.empty()) continue; From 18a0ae599bcf3976b01e5550607a9d3abf04b9df Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 5 Dec 2022 16:08:47 -0800 Subject: [PATCH 160/322] Add bandwidth limit of 10kb/s(#863) --- dAuthServer/AuthServer.cpp | 2 +- dChatServer/ChatServer.cpp | 2 +- dGame/dUtilities/SlashCommandHandler.cpp | 1 + dMasterServer/MasterServer.cpp | 2 +- dNet/dServer.cpp | 11 +++++++++-- dNet/dServer.h | 5 ++++- dWorldServer/WorldServer.cpp | 2 +- resources/sharedconfig.ini | 3 +++ 8 files changed, 21 insertions(+), 7 deletions(-) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index 9621f683..a9f02f53 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -83,7 +83,7 @@ int main(int argc, char** argv) { if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); - Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth); + Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth, Game::config); //Run it until server gets a kill message from Master: auto t = std::chrono::high_resolution_clock::now(); diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index e0073747..e3c6d6e9 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -103,7 +103,7 @@ int main(int argc, char** argv) { if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); - Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat); + Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config); Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 60862c1a..9b37d4b8 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -1778,6 +1778,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit scriptedActivityComponent->ReloadConfig(); } + Game::server->UpdateBandwidthLimit(); ChatPackets::SendSystemMessage(sysAddr, u"Successfully reloaded config for world!"); } diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 0329d9a0..4acb9b26 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -216,7 +216,7 @@ int main(int argc, char** argv) { if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients")); if (Game::config->GetValue("port") != "") ourPort = std::stoi(Game::config->GetValue("port")); - Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, true, false, Game::logger, "", 0, ServerType::Master); + Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, true, false, Game::logger, "", 0, ServerType::Master, Game::config); //Query for the database for a server labeled "master" auto* masterLookupStatement = Database::CreatePreppedStmt("SELECT id FROM `servers` WHERE `name` = 'master'"); diff --git a/dNet/dServer.cpp b/dNet/dServer.cpp index c46b156c..481667b8 100644 --- a/dNet/dServer.cpp +++ b/dNet/dServer.cpp @@ -2,6 +2,7 @@ #include "dServer.h" #include "dNetCommon.h" #include "dLogger.h" +#include "dConfig.h" #include "RakNetworkFactory.h" #include "MessageIdentifiers.h" @@ -35,7 +36,7 @@ public: } } ReceiveDownloadCompleteCB; -dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnections, bool isInternal, bool useEncryption, dLogger* logger, const std::string masterIP, int masterPort, ServerType serverType, unsigned int zoneID) { +dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnections, bool isInternal, bool useEncryption, dLogger* logger, const std::string masterIP, int masterPort, ServerType serverType, dConfig* config, unsigned int zoneID) { mIP = ip; mPort = port; mZoneID = zoneID; @@ -50,6 +51,7 @@ dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnect mNetIDManager = nullptr; mReplicaManager = nullptr; mServerType = serverType; + mConfig = config; //Attempt to start our server here: mIsOkay = Startup(); @@ -181,7 +183,7 @@ bool dServer::Startup() { if (mIsInternal) { mPeer->SetIncomingPassword("3.25 DARKFLAME1", 15); } else { - //mPeer->SetPerConnectionOutgoingBandwidthLimit(800000); //100Kb/s + UpdateBandwidthLimit(); mPeer->SetIncomingPassword("3.25 ND1", 8); } @@ -191,6 +193,11 @@ bool dServer::Startup() { return true; } +void dServer::UpdateBandwidthLimit() { + auto newBandwidth = mConfig->GetValue("maximum_outgoing_bandwidth"); + mPeer->SetPerConnectionOutgoingBandwidthLimit(!newBandwidth.empty() ? std::stoi(newBandwidth) : 0); +} + void dServer::Shutdown() { if (mPeer) { mPeer->Shutdown(1000); diff --git a/dNet/dServer.h b/dNet/dServer.h index 264932ee..0fbdecce 100644 --- a/dNet/dServer.h +++ b/dNet/dServer.h @@ -5,6 +5,7 @@ #include "NetworkIDManager.h" class dLogger; +class dConfig; enum class ServerType : uint32_t { Master, @@ -17,7 +18,7 @@ class dServer { public: // Default constructor should only used for testing! dServer() {}; - dServer(const std::string& ip, int port, int instanceID, int maxConnections, bool isInternal, bool useEncryption, dLogger* logger, const std::string masterIP, int masterPort, ServerType serverType, unsigned int zoneID = 0); + dServer(const std::string& ip, int port, int instanceID, int maxConnections, bool isInternal, bool useEncryption, dLogger* logger, const std::string masterIP, int masterPort, ServerType serverType, dConfig* config, unsigned int zoneID = 0); ~dServer(); Packet* ReceiveFromMaster(); @@ -42,6 +43,7 @@ public: const int GetInstanceID() const { return mInstanceID; } ReplicaManager* GetReplicaManager() { return mReplicaManager; } void UpdateReplica(); + void UpdateBandwidthLimit(); int GetPing(const SystemAddress& sysAddr) const; int GetLatestPing(const SystemAddress& sysAddr) const; @@ -58,6 +60,7 @@ private: private: dLogger* mLogger = nullptr; + dConfig* mConfig = nullptr; RakPeerInterface* mPeer = nullptr; ReplicaManager* mReplicaManager = nullptr; NetworkIDManager* mNetIDManager = nullptr; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index b4be7511..acd38ad3 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -208,7 +208,7 @@ int main(int argc, char** argv) { LootGenerator::Instance(); Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); - Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, zoneID); + Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, Game::config, zoneID); //Connect to the chat server: int chatPort = 1501; diff --git a/resources/sharedconfig.ini b/resources/sharedconfig.ini index 847a6b7c..439ffe2f 100644 --- a/resources/sharedconfig.ini +++ b/resources/sharedconfig.ini @@ -25,3 +25,6 @@ dump_folder= # The location of the client # Either the folder with /res or with /client and /versions client_location= + +# The maximum outgoing bandwidth in bits +maximum_outgoing_bandwidth=80000 From 46f085eb4ba5a3c956eb9b0eaecb6fced5e39e3c Mon Sep 17 00:00:00 2001 From: EmosewaMC <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 6 Dec 2022 04:39:09 -0800 Subject: [PATCH 161/322] Resolve warnings and change init order Initialize dConfig first, before logger so we know whether or not to log to console Initialize namespace Game variables to nullptr so they are a known value if accessed before initialization. Removed unused Game variables Replaced config with a pointer instead of referencing something on the stack. Assign return values to system calls to silence warnings. Tested that the server still compiles, runs and allows me to load into the game. --- dAuthServer/AuthServer.cpp | 38 +++++++------- dChatServer/ChatServer.cpp | 46 ++++++++--------- dCommon/Game.h | 2 - dMasterServer/InstanceManager.cpp | 4 +- dMasterServer/MasterServer.cpp | 34 ++++++------- dWorldServer/WorldServer.cpp | 71 ++++++++++++--------------- tests/dGameTests/GameDependencies.cpp | 1 - 7 files changed, 92 insertions(+), 104 deletions(-) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index a9f02f53..4999b62e 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -22,9 +22,9 @@ #include "Game.h" namespace Game { - dLogger* logger; - dServer* server; - dConfig* config; + dLogger* logger = nullptr; + dServer* server = nullptr; + dConfig* config = nullptr; } dLogger* SetupLogger(); @@ -37,22 +37,22 @@ int main(int argc, char** argv) { //Create all the objects we need to run our service: Game::logger = SetupLogger(); - if (!Game::logger) return 0; + if (!Game::logger) return EXIT_FAILURE; + + //Read our config: + Game::config = new dConfig("authconfig.ini"); + Game::logger->SetLogToConsole(bool(std::stoi(Game::config->GetValue("log_to_console")))); + Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); + Game::logger->Log("AuthServer", "Starting Auth server..."); Game::logger->Log("AuthServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("AuthServer", "Compiled on: %s", __TIMESTAMP__); - //Read our config: - dConfig config("authconfig.ini"); - Game::config = &config; - Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); - Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); - //Connect to the MySQL Database - std::string mysql_host = config.GetValue("mysql_host"); - std::string mysql_database = config.GetValue("mysql_database"); - std::string mysql_username = config.GetValue("mysql_username"); - std::string mysql_password = config.GetValue("mysql_password"); + std::string mysql_host = Game::config->GetValue("mysql_host"); + std::string mysql_database = Game::config->GetValue("mysql_database"); + std::string mysql_username = Game::config->GetValue("mysql_username"); + std::string mysql_password = Game::config->GetValue("mysql_password"); try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); @@ -61,7 +61,7 @@ int main(int argc, char** argv) { Database::Destroy("AuthServer"); delete Game::server; delete Game::logger; - return 0; + return EXIT_FAILURE; } //Find out the master's IP: @@ -80,10 +80,10 @@ int main(int argc, char** argv) { //It's safe to pass 'localhost' here, as the IP is only used as the external IP. int maxClients = 50; int ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. - if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); - if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); + if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients")); + if (Game::config->GetValue("port") != "") ourPort = std::atoi(Game::config->GetValue("port").c_str()); - Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth, Game::config); + Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth, Game::config); //Run it until server gets a kill message from Master: auto t = std::chrono::high_resolution_clock::now(); @@ -145,8 +145,8 @@ int main(int argc, char** argv) { Database::Destroy("AuthServer"); delete Game::server; delete Game::logger; + delete Game::config; - exit(EXIT_SUCCESS); return EXIT_SUCCESS; } diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index e3c6d6e9..2c36b222 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -20,11 +20,11 @@ #include "Game.h" namespace Game { - dLogger* logger; - dServer* server; - dConfig* config; - dChatFilter* chatFilter; - AssetManager* assetManager; + dLogger* logger = nullptr; + dServer* server = nullptr; + dConfig* config = nullptr; + dChatFilter* chatFilter = nullptr; + AssetManager* assetManager = nullptr; } //RakNet includes: @@ -42,19 +42,19 @@ int main(int argc, char** argv) { //Create all the objects we need to run our service: Game::logger = SetupLogger(); - if (!Game::logger) return 0; + if (!Game::logger) return EXIT_FAILURE; + + //Read our config: + Game::config = new dConfig("chatconfig.ini"); + Game::logger->SetLogToConsole(bool(std::stoi(Game::config->GetValue("log_to_console")))); + Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); + Game::logger->Log("ChatServer", "Starting Chat server..."); Game::logger->Log("ChatServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("ChatServer", "Compiled on: %s", __TIMESTAMP__); - //Read our config: - dConfig config("chatconfig.ini"); - Game::config = &config; - Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); - Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); - try { - std::string clientPathStr = config.GetValue("client_location"); + std::string clientPathStr = Game::config->GetValue("client_location"); if (clientPathStr.empty()) clientPathStr = "./res"; std::filesystem::path clientPath = std::filesystem::path(clientPathStr); if (clientPath.is_relative()) { @@ -69,10 +69,10 @@ int main(int argc, char** argv) { } //Connect to the MySQL Database - std::string mysql_host = config.GetValue("mysql_host"); - std::string mysql_database = config.GetValue("mysql_database"); - std::string mysql_username = config.GetValue("mysql_username"); - std::string mysql_password = config.GetValue("mysql_password"); + std::string mysql_host = Game::config->GetValue("mysql_host"); + std::string mysql_database = Game::config->GetValue("mysql_database"); + std::string mysql_username = Game::config->GetValue("mysql_username"); + std::string mysql_password = Game::config->GetValue("mysql_password"); try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); @@ -81,7 +81,7 @@ int main(int argc, char** argv) { Database::Destroy("ChatServer"); delete Game::server; delete Game::logger; - return 0; + return EXIT_FAILURE; } //Find out the master's IP: @@ -100,12 +100,12 @@ int main(int argc, char** argv) { //It's safe to pass 'localhost' here, as the IP is only used as the external IP. int maxClients = 50; int ourPort = 1501; - if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); - if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); + if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients")); + if (Game::config->GetValue("port") != "") ourPort = std::atoi(Game::config->GetValue("port").c_str()); - Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config); + Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config); - Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); + Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(Game::config->GetValue("dont_generate_dcf")))); //Run it until server gets a kill message from Master: auto t = std::chrono::high_resolution_clock::now(); @@ -167,8 +167,8 @@ int main(int argc, char** argv) { Database::Destroy("ChatServer"); delete Game::server; delete Game::logger; + delete Game::config; - exit(EXIT_SUCCESS); return EXIT_SUCCESS; } diff --git a/dCommon/Game.h b/dCommon/Game.h index 1c4bbc85..38cadb70 100644 --- a/dCommon/Game.h +++ b/dCommon/Game.h @@ -5,7 +5,6 @@ class dServer; class dLogger; class InstanceManager; -class dpWorld; class dChatFilter; class dConfig; class RakPeerInterface; @@ -16,7 +15,6 @@ namespace Game { extern dLogger* logger; extern dServer* server; extern InstanceManager* im; - extern dpWorld* physicsWorld; extern dChatFilter* chatFilter; extern dConfig* config; extern std::mt19937 randomEngine; diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index 83378dbb..a1983dd4 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -74,7 +74,7 @@ Instance* InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, LW cmd.append("&"); //Sends our next process to the background on Linux #endif - system(cmd.c_str()); + auto ret = system(cmd.c_str()); m_Instances.push_back(instance); @@ -322,7 +322,7 @@ Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID clon cmd.append("&"); //Sends our next process to the background on Linux #endif - system(cmd.c_str()); + auto ret = system(cmd.c_str()); m_Instances.push_back(instance); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 4acb9b26..a4aa270a 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -43,11 +43,11 @@ #include "FdbToSqlite.h" namespace Game { - dLogger* logger; - dServer* server; - InstanceManager* im; - dConfig* config; - AssetManager* assetManager; + dLogger* logger = nullptr; + dServer* server = nullptr; + InstanceManager* im = nullptr; + dConfig* config = nullptr; + AssetManager* assetManager = nullptr; } //namespace Game bool shutdownSequenceStarted = false; @@ -79,14 +79,14 @@ int main(int argc, char** argv) { Game::logger = SetupLogger(); if (!Game::logger) return EXIT_FAILURE; - Game::logger->Log("MasterServer", "Starting Master server..."); - Game::logger->Log("MasterServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); - Game::logger->Log("MasterServer", "Compiled on: %s", __TIMESTAMP__); - Game::config = new dConfig("masterconfig.ini"); Game::logger->SetLogToConsole(bool(std::stoi(Game::config->GetValue("log_to_console")))); Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); + Game::logger->Log("MasterServer", "Starting Master server..."); + Game::logger->Log("MasterServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); + Game::logger->Log("MasterServer", "Compiled on: %s", __TIMESTAMP__); + //Connect to the MySQL Database std::string mysql_host = Game::config->GetValue("mysql_host"); std::string mysql_database = Game::config->GetValue("mysql_database"); @@ -732,28 +732,28 @@ void HandlePacket(Packet* packet) { void StartChatServer() { #ifdef __APPLE__ //macOS doesn't need sudo to run on ports < 1024 - system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); + auto result = system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); #elif _WIN32 - system(("start " + (BinaryPathFinder::GetBinaryDir() / "ChatServer.exe").string()).c_str()); + auto result = system(("start " + (BinaryPathFinder::GetBinaryDir() / "ChatServer.exe").string()).c_str()); #else if (std::atoi(Game::config->GetValue("use_sudo_chat").c_str())) { - system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); + auto result = system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); } else { - system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); + auto result = system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); } #endif } void StartAuthServer() { #ifdef __APPLE__ - system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); + auto result = system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); #elif _WIN32 - system(("start " + (BinaryPathFinder::GetBinaryDir() / "AuthServer.exe").string()).c_str()); + auto result = system(("start " + (BinaryPathFinder::GetBinaryDir() / "AuthServer.exe").string()).c_str()); #else if (std::atoi(Game::config->GetValue("use_sudo_auth").c_str())) { - system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); + auto result = system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); } else { - system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); + auto result = system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); } #endif } diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index acd38ad3..5887597d 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -61,17 +61,14 @@ #include "ZCompression.h" namespace Game { - dLogger* logger; - dServer* server; - dZoneManager* zoneManager; - dpWorld* physicsWorld; - dChatFilter* chatFilter; - dConfig* config; + dLogger* logger = nullptr; + dServer* server = nullptr; + dpWorld* physicsWorld = nullptr; + dChatFilter* chatFilter = nullptr; + dConfig* config = nullptr; + AssetManager* assetManager = nullptr; + RakPeerInterface* chatServer = nullptr; std::mt19937 randomEngine; - - AssetManager* assetManager; - - RakPeerInterface* chatServer; SystemAddress chatSysAddr; } @@ -127,26 +124,21 @@ int main(int argc, char** argv) { //Create all the objects we need to run our service: Game::logger = SetupLogger(zoneID, instanceID); - if (!Game::logger) return 0; + if (!Game::logger) return EXIT_FAILURE; + + //Read our config: + Game::config = new dConfig("worldconfig.ini"); + Game::logger->SetLogToConsole(bool(std::stoi(Game::config->GetValue("log_to_console")))); + Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); - Game::logger->SetLogToConsole(true); //We want this info to always be logged. Game::logger->Log("WorldServer", "Starting World server..."); Game::logger->Log("WorldServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("WorldServer", "Compiled on: %s", __TIMESTAMP__); -#ifndef _DEBUG - Game::logger->SetLogToConsole(false); //By default, turn it back off if not in debug. -#endif - - //Read our config: - dConfig config("worldconfig.ini"); - Game::config = &config; - Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); - Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); - if (config.GetValue("disable_chat") == "1") chatDisabled = true; + if (Game::config->GetValue("disable_chat") == "1") chatDisabled = true; try { - std::string clientPathStr = config.GetValue("client_location"); + std::string clientPathStr = Game::config->GetValue("client_location"); if (clientPathStr.empty()) clientPathStr = "./res"; std::filesystem::path clientPath = std::filesystem::path(clientPathStr); if (clientPath.is_relative()) { @@ -166,28 +158,28 @@ int main(int argc, char** argv) { Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); - return -1; + return EXIT_FAILURE; } CDClientManager::Instance()->Initialize(); //Connect to the MySQL Database - std::string mysql_host = config.GetValue("mysql_host"); - std::string mysql_database = config.GetValue("mysql_database"); - std::string mysql_username = config.GetValue("mysql_username"); - std::string mysql_password = config.GetValue("mysql_password"); + std::string mysql_host = Game::config->GetValue("mysql_host"); + std::string mysql_database = Game::config->GetValue("mysql_database"); + std::string mysql_username = Game::config->GetValue("mysql_username"); + std::string mysql_password = Game::config->GetValue("mysql_password"); - Diagnostics::SetProduceMemoryDump(config.GetValue("generate_dump") == "1"); + Diagnostics::SetProduceMemoryDump(Game::config->GetValue("generate_dump") == "1"); - if (!config.GetValue("dump_folder").empty()) { - Diagnostics::SetOutDirectory(config.GetValue("dump_folder")); + if (!Game::config->GetValue("dump_folder").empty()) { + Diagnostics::SetOutDirectory(Game::config->GetValue("dump_folder")); } try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); } catch (sql::SQLException& ex) { Game::logger->Log("WorldServer", "Got an error while connecting to the database: %s", ex.what()); - return 0; + return EXIT_FAILURE; } //Find out the master's IP: @@ -206,13 +198,13 @@ int main(int argc, char** argv) { ObjectIDManager::Instance()->Initialize(); UserManager::Instance()->Initialize(); LootGenerator::Instance(); - Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); + Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(Game::config->GetValue("dont_generate_dcf")))); Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, Game::config, zoneID); //Connect to the chat server: int chatPort = 1501; - if (config.GetValue("chat_server_port") != "") chatPort = std::atoi(config.GetValue("chat_server_port").c_str()); + if (Game::config->GetValue("chat_server_port") != "") chatPort = std::atoi(Game::config->GetValue("chat_server_port").c_str()); auto chatSock = SocketDescriptor(uint16_t(ourPort + 2), 0); Game::chatServer = RakNetworkFactory::GetRakPeerInterface(); @@ -1279,16 +1271,15 @@ void WorldShutdownSequence() { } void FinalizeShutdown() { - //Delete our objects here: - if (Game::zoneManager) delete Game::zoneManager; - Game::logger->Log("WorldServer", "Shutdown complete, zone (%i), instance (%i)", Game::server->GetZoneID(), instanceID); + //Delete our objects here: Metrics::Clear(); Database::Destroy("WorldServer"); - delete Game::chatFilter; - delete Game::server; - delete Game::logger; + if (Game::chatFilter) delete Game::chatFilter; + if (Game::server) delete Game::server; + if (Game::logger) delete Game::logger; + if (Game::config) delete Game::config; worldShutdownSequenceComplete = true; diff --git a/tests/dGameTests/GameDependencies.cpp b/tests/dGameTests/GameDependencies.cpp index 5ac3339a..7b0a8412 100644 --- a/tests/dGameTests/GameDependencies.cpp +++ b/tests/dGameTests/GameDependencies.cpp @@ -4,7 +4,6 @@ namespace Game { dLogger* logger; dServer* server; dZoneManager* zoneManager; - dpWorld* physicsWorld; dChatFilter* chatFilter; dConfig* config; std::mt19937 randomEngine; From fde62a47773f02abdb3beed76d959cd86751f050 Mon Sep 17 00:00:00 2001 From: Demetri Van Sickle <demetriv.s.7@gmail.com> Date: Tue, 6 Dec 2022 06:36:42 -0800 Subject: [PATCH 162/322] Fixed typo (#875) --- migrations/dlu/7_make_play_key_id_nullable.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/migrations/dlu/7_make_play_key_id_nullable.sql b/migrations/dlu/7_make_play_key_id_nullable.sql index 7491874f..11239967 100644 --- a/migrations/dlu/7_make_play_key_id_nullable.sql +++ b/migrations/dlu/7_make_play_key_id_nullable.sql @@ -1 +1 @@ -ALTER TABLE account MODIFY play_key_id INT DEFAULT 0; +ALTER TABLE accounts MODIFY play_key_id INT DEFAULT 0; From a14e16237b8d20a1b43fc5770169c5d3ca4b5ad1 Mon Sep 17 00:00:00 2001 From: EmosewaMC <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 6 Dec 2022 19:30:43 -0800 Subject: [PATCH 163/322] Only start Master of config files exist Also default the logging to console to on on the off chance the files exist but are wrong / corrupted. --- dAuthServer/AuthServer.cpp | 4 ++-- dChatServer/ChatServer.cpp | 4 ++-- dMasterServer/MasterServer.cpp | 29 +++++++++++++++++++++++++++-- dWorldServer/WorldServer.cpp | 4 ++-- 4 files changed, 33 insertions(+), 8 deletions(-) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index 4999b62e..aefc822b 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -40,8 +40,8 @@ int main(int argc, char** argv) { if (!Game::logger) return EXIT_FAILURE; //Read our config: - Game::config = new dConfig("authconfig.ini"); - Game::logger->SetLogToConsole(bool(std::stoi(Game::config->GetValue("log_to_console")))); + Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "authconfig.ini").string()); + Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0"); Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); Game::logger->Log("AuthServer", "Starting Auth server..."); diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index 2c36b222..043e7869 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -45,8 +45,8 @@ int main(int argc, char** argv) { if (!Game::logger) return EXIT_FAILURE; //Read our config: - Game::config = new dConfig("chatconfig.ini"); - Game::logger->SetLogToConsole(bool(std::stoi(Game::config->GetValue("log_to_console")))); + Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "chatconfig.ini").string()); + Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0"); Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); Game::logger->Log("ChatServer", "Starting Chat server..."); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index a4aa270a..4c18566e 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -79,8 +79,33 @@ int main(int argc, char** argv) { Game::logger = SetupLogger(); if (!Game::logger) return EXIT_FAILURE; - Game::config = new dConfig("masterconfig.ini"); - Game::logger->SetLogToConsole(bool(std::stoi(Game::config->GetValue("log_to_console")))); + if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "authconfig.ini")) { + Game::logger->Log("MasterServer", "Couldnt find authconfig.ini"); + return EXIT_FAILURE; + } + + if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "chatconfig.ini")) { + Game::logger->Log("MasterServer", "Couldnt find chatconfig.ini"); + return EXIT_FAILURE; + } + + if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "masterconfig.ini")) { + Game::logger->Log("MasterServer", "Couldnt find masterconfig.ini"); + return EXIT_FAILURE; + } + + if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "sharedconfig.ini")) { + Game::logger->Log("MasterServer", "Couldnt find sharedconfig.ini"); + return EXIT_FAILURE; + } + + if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "worldconfig.ini")) { + Game::logger->Log("MasterServer", "Couldnt find worldconfig.ini"); + return EXIT_FAILURE; + } + + Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "masterconfig.ini").string()); + Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0"); Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); Game::logger->Log("MasterServer", "Starting Master server..."); diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 5887597d..68ec0e57 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -127,8 +127,8 @@ int main(int argc, char** argv) { if (!Game::logger) return EXIT_FAILURE; //Read our config: - Game::config = new dConfig("worldconfig.ini"); - Game::logger->SetLogToConsole(bool(std::stoi(Game::config->GetValue("log_to_console")))); + Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "worldconfig.ini").string()); + Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0"); Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); Game::logger->Log("WorldServer", "Starting World server..."); From 8886bf65475ff3cea82d5229d900e68828975f4f Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 8 Dec 2022 00:13:25 -0700 Subject: [PATCH 164/322] Address Force movement behaviors triggering twice (#878) --- dGame/dBehaviors/ForceMovementBehavior.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/dBehaviors/ForceMovementBehavior.cpp b/dGame/dBehaviors/ForceMovementBehavior.cpp index 55cda622..e1ac6133 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.cpp +++ b/dGame/dBehaviors/ForceMovementBehavior.cpp @@ -75,5 +75,5 @@ void ForceMovementBehavior::SyncCalculation(BehaviorContext* context, RakNet::Bi this->m_hitAction->Calculate(context, bitStream, branch); this->m_hitEnemyAction->Calculate(context, bitStream, branch); - this->m_hitEnemyAction->Calculate(context, bitStream, branch); + this->m_hitFactionAction->Calculate(context, bitStream, branch); } From d5613b8034ea8594db6818606fe085a47c455611 Mon Sep 17 00:00:00 2001 From: EmosewaMC <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 8 Dec 2022 04:44:56 -0800 Subject: [PATCH 165/322] hot fix --- dCommon/FdbToSqlite.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/dCommon/FdbToSqlite.cpp b/dCommon/FdbToSqlite.cpp index d98d4962..6015fd3a 100644 --- a/dCommon/FdbToSqlite.cpp +++ b/dCommon/FdbToSqlite.cpp @@ -49,9 +49,9 @@ bool FdbToSqlite::Convert::ConvertDatabase() { } int32_t FdbToSqlite::Convert::ReadInt32() { - uint32_t numberOfTables{}; - BinaryIO::BinaryRead(fdb, numberOfTables); - return numberOfTables; + int32_t nextInt{}; + BinaryIO::BinaryRead(fdb, nextInt); + return nextInt; } int64_t FdbToSqlite::Convert::ReadInt64() { @@ -193,7 +193,7 @@ void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& case eSqliteDataType::NONE: BinaryIO::BinaryRead(fdb, emptyValue); assert(emptyValue == 0); - insertedRow << "\"\""; + insertedRow << "NULL"; break; case eSqliteDataType::INT32: From da910309a043f50821a388531ace407507cf1e95 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 8 Dec 2022 13:32:47 -0800 Subject: [PATCH 166/322] Remove unneeded commands (#880) * Remove unneeded commands * Thank you aron --- dGame/dUtilities/SlashCommandHandler.cpp | 16 ---------------- docs/Commands.md | 2 -- 2 files changed, 18 deletions(-) diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 9b37d4b8..89f11346 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -212,22 +212,6 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "skip-ags") { - auto* missionComponent = entity->GetComponent<MissionComponent>(); - - if (missionComponent != nullptr && missionComponent->HasMission(479)) { - missionComponent->CompleteMission(479); - } - } - - if (chatCommand == "skip-sg") { - auto* missionComponent = entity->GetComponent<MissionComponent>(); - - if (missionComponent != nullptr && missionComponent->HasMission(229)) { - missionComponent->CompleteMission(229); - } - } - if (chatCommand == "fix-stats") { // Reset skill component and buff component auto* skillComponent = entity->GetComponent<SkillComponent>(); diff --git a/docs/Commands.md b/docs/Commands.md index 95ec28f9..7a15bf37 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -14,8 +14,6 @@ Here is a summary of the commands available in-game. All commands are prefixed b |pvp|`/pvp`|Toggle your PVP flag.|| |resurrect|`/resurrect`|Resurrects the player.|| |requestmailcount|`/requestmailcount`|Sends notification with number of unread messages in the player's mailbox.|| -|skip-ags|`/skip-ags`|Skips the Avant Gardens Survival minigame mission, "Impress the Sentinel Faction".|| -|skip-sg|`/skip-sg`|Skips the Shooting Gallery minigame mission, "Monarch of the Sea".|| |who|`/who`|Displays in chat all players on the instance.|| ## Moderation Commands From 5292f36417e94085aa21400f31bf6ed595b12330 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 11 Dec 2022 00:27:01 -0800 Subject: [PATCH 167/322] Packages updates (#864) Update packages to not open if you dont have enough room. Update packages to no longer allow them selves to be open unless you meet the pre-reqs. --- dGame/dInventory/Item.cpp | 67 ++++++++++++++++++++++++------ dGame/dUtilities/Preconditions.cpp | 7 +--- 2 files changed, 56 insertions(+), 18 deletions(-) diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index c05c0672..02739ec2 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -253,7 +253,7 @@ bool Item::Consume() { } } - Game::logger->Log("Item", "Consumed (%i) / (%llu) with (%d)", lot, id, success); + Game::logger->LogDebug("Item", "Consumed LOT (%i) itemID (%llu). Success=(%d)", lot, id, success); GameMessages::SendUseItemResult(inventory->GetComponent()->GetParent(), lot, success); @@ -265,14 +265,34 @@ bool Item::Consume() { } void Item::UseNonEquip() { + LOT thisLot = this->GetLot(); + if (!GetInventory()) { + Game::logger->LogDebug("Item", "item %i has no inventory??", this->GetLot()); + return; + } + + auto* playerInventoryComponent = GetInventory()->GetComponent(); + if (!playerInventoryComponent) { + Game::logger->LogDebug("Item", "no inventory component attached to item id %llu lot %i", this->GetId(), this->GetLot()); + return; + } + + auto* playerEntity = playerInventoryComponent->GetParent(); + if (!playerEntity) { + Game::logger->LogDebug("Item", "no player entity attached to inventory? item id is %llu", this->GetId()); + return; + } + const auto type = static_cast<eItemType>(info->itemType); if (type == eItemType::ITEM_TYPE_MOUNT) { - GetInventory()->GetComponent()->HandlePossession(this); + playerInventoryComponent->HandlePossession(this); + // TODO Check if mounts are allowed to be spawned } else if (type == eItemType::ITEM_TYPE_PET_INVENTORY_ITEM && subKey != LWOOBJID_EMPTY) { - const auto& databasePet = GetInventory()->GetComponent()->GetDatabasePet(subKey); + const auto& databasePet = playerInventoryComponent->GetDatabasePet(subKey); if (databasePet.lot != LOT_NULL) { - GetInventory()->GetComponent()->SpawnPet(this); + playerInventoryComponent->SpawnPet(this); } + // This precondition response is taken care of in SpawnPet(). } else { auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_PACKAGE); @@ -282,18 +302,41 @@ void Item::UseNonEquip() { auto* packCompTable = CDClientManager::Instance()->GetTable<CDPackageComponentTable>("PackageComponent"); auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast<uint32_t>(packageComponentId); }); - const auto success = !packages.empty(); + auto success = !packages.empty(); if (success) { - auto* entityParent = inventory->GetComponent()->GetParent(); - for (auto& pack : packages) { - std::unordered_map<LOT, int32_t> result{}; - result = LootGenerator::Instance().RollLootMatrix(entityParent, pack.LootMatrixIndex); - if (!inventory->GetComponent()->HasSpaceForLoot(result)) { + if (this->GetPreconditionExpression()->Check(playerInventoryComponent->GetParent())) { + auto* entityParent = playerInventoryComponent->GetParent(); + // Roll the loot for all the packages then see if it all fits. If it fits, give it to the player, otherwise don't. + std::unordered_map<LOT, int32_t> rolledLoot{}; + for (auto& pack : packages) { + auto thisPackage = LootGenerator::Instance().RollLootMatrix(entityParent, pack.LootMatrixIndex); + for (auto& loot : thisPackage) { + // If we already rolled this lot, add it to the existing one, otherwise create a new entry. + auto existingLoot = rolledLoot.find(loot.first); + if (existingLoot == rolledLoot.end()) { + rolledLoot.insert(loot); + } else { + existingLoot->second += loot.second; + } + } } - LootGenerator::Instance().GiveLoot(inventory->GetComponent()->GetParent(), result, eLootSourceType::LOOT_SOURCE_CONSUMPTION); + if (playerInventoryComponent->HasSpaceForLoot(rolledLoot)) { + LootGenerator::Instance().GiveLoot(playerInventoryComponent->GetParent(), rolledLoot, eLootSourceType::LOOT_SOURCE_CONSUMPTION); + playerInventoryComponent->RemoveItem(lot, 1); + } else { + success = false; + } + } else { + GameMessages::SendUseItemRequirementsResponse( + playerInventoryComponent->GetParent()->GetObjectID(), + playerInventoryComponent->GetParent()->GetSystemAddress(), + UseItemResponse::FailedPrecondition + ); + success = false; } - inventory->GetComponent()->RemoveItem(lot, 1); } + Game::logger->LogDebug("Item", "Player %llu %s used item %i", playerEntity->GetObjectID(), success ? "successfully" : "unsuccessfully", thisLot); + GameMessages::SendUseItemResult(playerInventoryComponent->GetParent(), thisLot, success); } } diff --git a/dGame/dUtilities/Preconditions.cpp b/dGame/dUtilities/Preconditions.cpp index 1f719433..c23ac53b 100644 --- a/dGame/dUtilities/Preconditions.cpp +++ b/dGame/dUtilities/Preconditions.cpp @@ -154,7 +154,7 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluat case PreconditionType::MissionComplete: mission = missionComponent->GetMission(value); - return mission == nullptr || mission->GetMissionState() >= MissionState::MISSION_STATE_COMPLETE; + return mission == nullptr ? false : mission->GetMissionState() >= MissionState::MISSION_STATE_COMPLETE; case PreconditionType::PetDeployed: return false; // TODO case PreconditionType::HasFlag: @@ -277,11 +277,6 @@ bool PreconditionExpression::Check(Entity* player, bool evaluateCosts) const { return true; } - if (player->GetGMLevel() >= 9) // Developers can skip this for testing - { - return true; - } - const auto a = Preconditions::Check(player, condition, evaluateCosts); if (!a) { From 435761f64bdf75edf717ed6a12b966624c16447c Mon Sep 17 00:00:00 2001 From: EmosewaMC <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 15 Dec 2022 04:02:38 -0800 Subject: [PATCH 168/322] Improve shutdown --- dAuthServer/AuthServer.cpp | 41 ++++++------ dChatServer/ChatServer.cpp | 49 ++++++++------- dCommon/Game.h | 3 + dMasterServer/InstanceManager.cpp | 6 +- dMasterServer/MasterServer.cpp | 88 ++++++++++---------------- dNet/dServer.cpp | 8 ++- dNet/dServer.h | 20 +++++- dWorldServer/WorldServer.cpp | 91 +++++++++++++++------------ tests/dGameTests/GameDependencies.cpp | 1 + 9 files changed, 160 insertions(+), 147 deletions(-) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index aefc822b..4fffc5d0 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -22,9 +22,10 @@ #include "Game.h" namespace Game { - dLogger* logger = nullptr; - dServer* server = nullptr; - dConfig* config = nullptr; + dLogger* logger; + dServer* server; + dConfig* config; + bool shouldShutdown = false; } dLogger* SetupLogger(); @@ -37,22 +38,22 @@ int main(int argc, char** argv) { //Create all the objects we need to run our service: Game::logger = SetupLogger(); - if (!Game::logger) return EXIT_FAILURE; - - //Read our config: - Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "authconfig.ini").string()); - Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0"); - Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); - + if (!Game::logger) return 0; Game::logger->Log("AuthServer", "Starting Auth server..."); Game::logger->Log("AuthServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("AuthServer", "Compiled on: %s", __TIMESTAMP__); + //Read our config: + dConfig config("authconfig.ini"); + Game::config = &config; + Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); + Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); + //Connect to the MySQL Database - std::string mysql_host = Game::config->GetValue("mysql_host"); - std::string mysql_database = Game::config->GetValue("mysql_database"); - std::string mysql_username = Game::config->GetValue("mysql_username"); - std::string mysql_password = Game::config->GetValue("mysql_password"); + std::string mysql_host = config.GetValue("mysql_host"); + std::string mysql_database = config.GetValue("mysql_database"); + std::string mysql_username = config.GetValue("mysql_username"); + std::string mysql_password = config.GetValue("mysql_password"); try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); @@ -61,7 +62,7 @@ int main(int argc, char** argv) { Database::Destroy("AuthServer"); delete Game::server; delete Game::logger; - return EXIT_FAILURE; + return 0; } //Find out the master's IP: @@ -80,10 +81,10 @@ int main(int argc, char** argv) { //It's safe to pass 'localhost' here, as the IP is only used as the external IP. int maxClients = 50; int ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. - if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients")); - if (Game::config->GetValue("port") != "") ourPort = std::atoi(Game::config->GetValue("port").c_str()); + if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); + if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); - Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth, Game::config); + Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth, Game::config, Game::shouldShutdown); //Run it until server gets a kill message from Master: auto t = std::chrono::high_resolution_clock::now(); @@ -92,7 +93,7 @@ int main(int argc, char** argv) { int framesSinceMasterDisconnect = 0; int framesSinceLastSQLPing = 0; - while (true) { + while (!Game::shouldShutdown) { //Check if we're still connected to master: if (!Game::server->GetIsConnectedToMaster()) { framesSinceMasterDisconnect++; @@ -145,8 +146,8 @@ int main(int argc, char** argv) { Database::Destroy("AuthServer"); delete Game::server; delete Game::logger; - delete Game::config; + exit(EXIT_SUCCESS); return EXIT_SUCCESS; } diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index 043e7869..d2eb7fc7 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -20,11 +20,12 @@ #include "Game.h" namespace Game { - dLogger* logger = nullptr; - dServer* server = nullptr; - dConfig* config = nullptr; - dChatFilter* chatFilter = nullptr; - AssetManager* assetManager = nullptr; + dLogger* logger; + dServer* server; + dConfig* config; + dChatFilter* chatFilter; + AssetManager* assetManager; + bool shouldShutdown = false; } //RakNet includes: @@ -42,19 +43,19 @@ int main(int argc, char** argv) { //Create all the objects we need to run our service: Game::logger = SetupLogger(); - if (!Game::logger) return EXIT_FAILURE; - - //Read our config: - Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "chatconfig.ini").string()); - Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0"); - Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); - + if (!Game::logger) return 0; Game::logger->Log("ChatServer", "Starting Chat server..."); Game::logger->Log("ChatServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("ChatServer", "Compiled on: %s", __TIMESTAMP__); + //Read our config: + dConfig config("chatconfig.ini"); + Game::config = &config; + Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); + Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); + try { - std::string clientPathStr = Game::config->GetValue("client_location"); + std::string clientPathStr = config.GetValue("client_location"); if (clientPathStr.empty()) clientPathStr = "./res"; std::filesystem::path clientPath = std::filesystem::path(clientPathStr); if (clientPath.is_relative()) { @@ -69,10 +70,10 @@ int main(int argc, char** argv) { } //Connect to the MySQL Database - std::string mysql_host = Game::config->GetValue("mysql_host"); - std::string mysql_database = Game::config->GetValue("mysql_database"); - std::string mysql_username = Game::config->GetValue("mysql_username"); - std::string mysql_password = Game::config->GetValue("mysql_password"); + std::string mysql_host = config.GetValue("mysql_host"); + std::string mysql_database = config.GetValue("mysql_database"); + std::string mysql_username = config.GetValue("mysql_username"); + std::string mysql_password = config.GetValue("mysql_password"); try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); @@ -81,7 +82,7 @@ int main(int argc, char** argv) { Database::Destroy("ChatServer"); delete Game::server; delete Game::logger; - return EXIT_FAILURE; + return 0; } //Find out the master's IP: @@ -100,12 +101,12 @@ int main(int argc, char** argv) { //It's safe to pass 'localhost' here, as the IP is only used as the external IP. int maxClients = 50; int ourPort = 1501; - if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients")); - if (Game::config->GetValue("port") != "") ourPort = std::atoi(Game::config->GetValue("port").c_str()); + if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); + if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); - Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config); + Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config, Game::shouldShutdown); - Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(Game::config->GetValue("dont_generate_dcf")))); + Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); //Run it until server gets a kill message from Master: auto t = std::chrono::high_resolution_clock::now(); @@ -114,7 +115,7 @@ int main(int argc, char** argv) { int framesSinceMasterDisconnect = 0; int framesSinceLastSQLPing = 0; - while (true) { + while (!Game::shouldShutdown) { //Check if we're still connected to master: if (!Game::server->GetIsConnectedToMaster()) { framesSinceMasterDisconnect++; @@ -167,8 +168,8 @@ int main(int argc, char** argv) { Database::Destroy("ChatServer"); delete Game::server; delete Game::logger; - delete Game::config; + exit(EXIT_SUCCESS); return EXIT_SUCCESS; } diff --git a/dCommon/Game.h b/dCommon/Game.h index 38cadb70..cbddafec 100644 --- a/dCommon/Game.h +++ b/dCommon/Game.h @@ -5,6 +5,7 @@ class dServer; class dLogger; class InstanceManager; +class dpWorld; class dChatFilter; class dConfig; class RakPeerInterface; @@ -15,10 +16,12 @@ namespace Game { extern dLogger* logger; extern dServer* server; extern InstanceManager* im; + extern dpWorld* physicsWorld; extern dChatFilter* chatFilter; extern dConfig* config; extern std::mt19937 randomEngine; extern RakPeerInterface* chatServer; extern AssetManager* assetManager; extern SystemAddress chatSysAddr; + extern bool shouldShutdown; } diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index a1983dd4..327a18b9 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -74,7 +74,7 @@ Instance* InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, LW cmd.append("&"); //Sends our next process to the background on Linux #endif - auto ret = system(cmd.c_str()); + system(cmd.c_str()); m_Instances.push_back(instance); @@ -322,7 +322,7 @@ Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID clon cmd.append("&"); //Sends our next process to the background on Linux #endif - auto ret = system(cmd.c_str()); + system(cmd.c_str()); m_Instances.push_back(instance); @@ -391,5 +391,5 @@ void Instance::Shutdown() { Game::server->Send(&bitStream, this->m_SysAddr, false); - Game::logger->Log("Instance", "Triggered world shutdown"); + Game::logger->Log("Instance", "Triggered world shutdown for zone/clone/instance %i/%i/%i", GetMapID(), GetCloneID(), GetInstanceID()); } diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 4c18566e..2f54243a 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -43,11 +43,12 @@ #include "FdbToSqlite.h" namespace Game { - dLogger* logger = nullptr; - dServer* server = nullptr; - InstanceManager* im = nullptr; - dConfig* config = nullptr; - AssetManager* assetManager = nullptr; + dLogger* logger; + dServer* server; + InstanceManager* im; + dConfig* config; + AssetManager* assetManager; + bool shouldShutdown = false; } //namespace Game bool shutdownSequenceStarted = false; @@ -58,7 +59,6 @@ void StartAuthServer(); void StartChatServer(); void HandlePacket(Packet* packet); std::map<uint32_t, std::string> activeSessions; -bool shouldShutdown = false; SystemAddress chatServerMasterPeerSysAddr; int main(int argc, char** argv) { @@ -79,39 +79,14 @@ int main(int argc, char** argv) { Game::logger = SetupLogger(); if (!Game::logger) return EXIT_FAILURE; - if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "authconfig.ini")) { - Game::logger->Log("MasterServer", "Couldnt find authconfig.ini"); - return EXIT_FAILURE; - } - - if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "chatconfig.ini")) { - Game::logger->Log("MasterServer", "Couldnt find chatconfig.ini"); - return EXIT_FAILURE; - } - - if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "masterconfig.ini")) { - Game::logger->Log("MasterServer", "Couldnt find masterconfig.ini"); - return EXIT_FAILURE; - } - - if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "sharedconfig.ini")) { - Game::logger->Log("MasterServer", "Couldnt find sharedconfig.ini"); - return EXIT_FAILURE; - } - - if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "worldconfig.ini")) { - Game::logger->Log("MasterServer", "Couldnt find worldconfig.ini"); - return EXIT_FAILURE; - } - - Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "masterconfig.ini").string()); - Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0"); - Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); - Game::logger->Log("MasterServer", "Starting Master server..."); Game::logger->Log("MasterServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("MasterServer", "Compiled on: %s", __TIMESTAMP__); + Game::config = new dConfig("masterconfig.ini"); + Game::logger->SetLogToConsole(bool(std::stoi(Game::config->GetValue("log_to_console")))); + Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); + //Connect to the MySQL Database std::string mysql_host = Game::config->GetValue("mysql_host"); std::string mysql_database = Game::config->GetValue("mysql_database"); @@ -241,7 +216,7 @@ int main(int argc, char** argv) { if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients")); if (Game::config->GetValue("port") != "") ourPort = std::stoi(Game::config->GetValue("port")); - Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, true, false, Game::logger, "", 0, ServerType::Master, Game::config); + Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, true, false, Game::logger, "", 0, ServerType::Master, Game::config, Game::shouldShutdown); //Query for the database for a server labeled "master" auto* masterLookupStatement = Database::CreatePreppedStmt("SELECT id FROM `servers` WHERE `name` = 'master'"); @@ -328,7 +303,7 @@ int main(int argc, char** argv) { framesSinceLastSQLPing++; //10m shutdown for universe kill command - if (shouldShutdown) { + if (Game::shouldShutdown) { if (framesSinceKillUniverseCommand >= 40000) { //Break main loop and exit break; @@ -406,7 +381,7 @@ void HandlePacket(Packet* packet) { Game::im->RemoveInstance(instance); //Delete the old } - if (packet->systemAddress == chatServerMasterPeerSysAddr && !shouldShutdown) { + if (packet->systemAddress == chatServerMasterPeerSysAddr && !Game::shouldShutdown) { StartChatServer(); } } @@ -422,7 +397,7 @@ void HandlePacket(Packet* packet) { //Game::im->GetInstance(zoneID.GetMapID(), false, 0); //Create the new } - if (packet->systemAddress == chatServerMasterPeerSysAddr && !shouldShutdown) { + if (packet->systemAddress == chatServerMasterPeerSysAddr && !Game::shouldShutdown) { StartChatServer(); } } @@ -744,7 +719,7 @@ void HandlePacket(Packet* packet) { case MSG_MASTER_SHUTDOWN_UNIVERSE: { Game::logger->Log("MasterServer", "Received shutdown universe command, shutting down in 10 minutes."); - shouldShutdown = true; + Game::shouldShutdown = true; break; } @@ -757,28 +732,28 @@ void HandlePacket(Packet* packet) { void StartChatServer() { #ifdef __APPLE__ //macOS doesn't need sudo to run on ports < 1024 - auto result = system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); + system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); #elif _WIN32 - auto result = system(("start " + (BinaryPathFinder::GetBinaryDir() / "ChatServer.exe").string()).c_str()); + system(("start " + (BinaryPathFinder::GetBinaryDir() / "ChatServer.exe").string()).c_str()); #else if (std::atoi(Game::config->GetValue("use_sudo_chat").c_str())) { - auto result = system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); + system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); } else { - auto result = system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); + system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); } #endif } void StartAuthServer() { #ifdef __APPLE__ - auto result = system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); + system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); #elif _WIN32 - auto result = system(("start " + (BinaryPathFinder::GetBinaryDir() / "AuthServer.exe").string()).c_str()); + system(("start " + (BinaryPathFinder::GetBinaryDir() / "AuthServer.exe").string()).c_str()); #else if (std::atoi(Game::config->GetValue("use_sudo_auth").c_str())) { - auto result = system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); + system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); } else { - auto result = system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); + system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); } #endif } @@ -790,14 +765,11 @@ void ShutdownSequence() { shutdownSequenceStarted = true; - if (Game::im) { - for (auto* instance : Game::im->GetInstances()) { - if (instance == nullptr) { - continue; - } - - instance->Shutdown(); - } + { + CBITSTREAM; + PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SHUTDOWN); + Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); + Game::logger->Log("MasterServer", "Triggered master shutdown"); } auto* objIdManager = ObjectIDManager::TryInstance(); @@ -813,6 +785,10 @@ void ShutdownSequence() { exit(EXIT_SUCCESS); } + for (auto instance : Game::im->GetInstances()) { + instance->SetIsShuttingDown(true); + } + Game::logger->Log("MasterServer", "Attempting to shutdown instances, max 60 seconds..."); while (true) { diff --git a/dNet/dServer.cpp b/dNet/dServer.cpp index 481667b8..3a5ef822 100644 --- a/dNet/dServer.cpp +++ b/dNet/dServer.cpp @@ -36,7 +36,7 @@ public: } } ReceiveDownloadCompleteCB; -dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnections, bool isInternal, bool useEncryption, dLogger* logger, const std::string masterIP, int masterPort, ServerType serverType, dConfig* config, unsigned int zoneID) { +dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnections, bool isInternal, bool useEncryption, dLogger* logger, const std::string masterIP, int masterPort, ServerType serverType, dConfig* config, bool& shouldShutdown, unsigned int zoneID) { mIP = ip; mPort = port; mZoneID = zoneID; @@ -52,6 +52,7 @@ dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnect mReplicaManager = nullptr; mServerType = serverType; mConfig = config; + mShouldShutdown = &shouldShutdown; //Attempt to start our server here: mIsOkay = Startup(); @@ -124,8 +125,11 @@ Packet* dServer::ReceiveFromMaster() { ZoneInstanceManager::Instance()->HandleRequestZoneTransferResponse(requestID, packet); break; } + case MSG_MASTER_SHUTDOWN: + *mShouldShutdown = true; + break; - //When we handle these packets in World instead dServer, we just return the packet's pointer. + //When we handle these packets in World instead dServer, we just return the packet's pointer. default: return packet; diff --git a/dNet/dServer.h b/dNet/dServer.h index 0fbdecce..608b3b83 100644 --- a/dNet/dServer.h +++ b/dNet/dServer.h @@ -18,7 +18,20 @@ class dServer { public: // Default constructor should only used for testing! dServer() {}; - dServer(const std::string& ip, int port, int instanceID, int maxConnections, bool isInternal, bool useEncryption, dLogger* logger, const std::string masterIP, int masterPort, ServerType serverType, dConfig* config, unsigned int zoneID = 0); + dServer( + const std::string& ip, + int port, + int instanceID, + int maxConnections, + bool isInternal, + bool useEncryption, + dLogger* logger, + const std::string masterIP, + int masterPort, + ServerType serverType, + dConfig* config, + bool& shouldShutdown, + unsigned int zoneID = 0); ~dServer(); Packet* ReceiveFromMaster(); @@ -64,6 +77,11 @@ private: RakPeerInterface* mPeer = nullptr; ReplicaManager* mReplicaManager = nullptr; NetworkIDManager* mNetIDManager = nullptr; + + /** + * Whether or not to shut down the server. Pointer to Game::shouldShutdown. + */ + bool* mShouldShutdown = nullptr; SocketDescriptor mSocketDescriptor; std::string mIP; int mPort; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 68ec0e57..2fdb373b 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -61,20 +61,23 @@ #include "ZCompression.h" namespace Game { - dLogger* logger = nullptr; - dServer* server = nullptr; - dpWorld* physicsWorld = nullptr; - dChatFilter* chatFilter = nullptr; - dConfig* config = nullptr; - AssetManager* assetManager = nullptr; - RakPeerInterface* chatServer = nullptr; + dLogger* logger; + dServer* server; + dZoneManager* zoneManager; + dpWorld* physicsWorld; + dChatFilter* chatFilter; + dConfig* config; std::mt19937 randomEngine; + + AssetManager* assetManager; + + RakPeerInterface* chatServer; SystemAddress chatSysAddr; -} + bool shouldShutdown = false; +} // namespace Game bool chatDisabled = false; bool chatConnected = false; -bool worldShutdownSequenceStarted = false; bool worldShutdownSequenceComplete = false; void WorldShutdownSequence(); void WorldShutdownProcess(uint32_t zoneId); @@ -124,21 +127,26 @@ int main(int argc, char** argv) { //Create all the objects we need to run our service: Game::logger = SetupLogger(zoneID, instanceID); - if (!Game::logger) return EXIT_FAILURE; - - //Read our config: - Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "worldconfig.ini").string()); - Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0"); - Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); + if (!Game::logger) return 0; + Game::logger->SetLogToConsole(true); //We want this info to always be logged. Game::logger->Log("WorldServer", "Starting World server..."); Game::logger->Log("WorldServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("WorldServer", "Compiled on: %s", __TIMESTAMP__); - if (Game::config->GetValue("disable_chat") == "1") chatDisabled = true; +#ifndef _DEBUG + Game::logger->SetLogToConsole(false); //By default, turn it back off if not in debug. +#endif + + //Read our config: + dConfig config("worldconfig.ini"); + Game::config = &config; + Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); + Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); + if (config.GetValue("disable_chat") == "1") chatDisabled = true; try { - std::string clientPathStr = Game::config->GetValue("client_location"); + std::string clientPathStr = config.GetValue("client_location"); if (clientPathStr.empty()) clientPathStr = "./res"; std::filesystem::path clientPath = std::filesystem::path(clientPathStr); if (clientPath.is_relative()) { @@ -158,28 +166,28 @@ int main(int argc, char** argv) { Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); - return EXIT_FAILURE; + return -1; } CDClientManager::Instance()->Initialize(); //Connect to the MySQL Database - std::string mysql_host = Game::config->GetValue("mysql_host"); - std::string mysql_database = Game::config->GetValue("mysql_database"); - std::string mysql_username = Game::config->GetValue("mysql_username"); - std::string mysql_password = Game::config->GetValue("mysql_password"); + std::string mysql_host = config.GetValue("mysql_host"); + std::string mysql_database = config.GetValue("mysql_database"); + std::string mysql_username = config.GetValue("mysql_username"); + std::string mysql_password = config.GetValue("mysql_password"); - Diagnostics::SetProduceMemoryDump(Game::config->GetValue("generate_dump") == "1"); + Diagnostics::SetProduceMemoryDump(config.GetValue("generate_dump") == "1"); - if (!Game::config->GetValue("dump_folder").empty()) { - Diagnostics::SetOutDirectory(Game::config->GetValue("dump_folder")); + if (!config.GetValue("dump_folder").empty()) { + Diagnostics::SetOutDirectory(config.GetValue("dump_folder")); } try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); } catch (sql::SQLException& ex) { Game::logger->Log("WorldServer", "Got an error while connecting to the database: %s", ex.what()); - return EXIT_FAILURE; + return 0; } //Find out the master's IP: @@ -198,13 +206,13 @@ int main(int argc, char** argv) { ObjectIDManager::Instance()->Initialize(); UserManager::Instance()->Initialize(); LootGenerator::Instance(); - Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(Game::config->GetValue("dont_generate_dcf")))); + Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); - Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, Game::config, zoneID); + Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, Game::config, Game::shouldShutdown, zoneID); //Connect to the chat server: int chatPort = 1501; - if (Game::config->GetValue("chat_server_port") != "") chatPort = std::atoi(Game::config->GetValue("chat_server_port").c_str()); + if (config.GetValue("chat_server_port") != "") chatPort = std::atoi(config.GetValue("chat_server_port").c_str()); auto chatSock = SocketDescriptor(uint16_t(ourPort + 2), 0); Game::chatServer = RakNetworkFactory::GetRakPeerInterface(); @@ -315,9 +323,9 @@ int main(int argc, char** argv) { framesSinceMasterDisconnect++; int framesToWaitForMaster = ready ? 10 : 200; - if (framesSinceMasterDisconnect >= framesToWaitForMaster && !worldShutdownSequenceStarted) { + if (framesSinceMasterDisconnect >= framesToWaitForMaster && !Game::shouldShutdown) { Game::logger->Log("WorldServer", "Game loop running but no connection to master for %d frames, shutting down", framesToWaitForMaster); - worldShutdownSequenceStarted = true; + Game::shouldShutdown = true; } } else framesSinceMasterDisconnect = 0; @@ -413,7 +421,7 @@ int main(int argc, char** argv) { //If we haven't had any players for a while, time out and shut down: if (framesSinceLastUser == (cloneID != 0 ? 4000 : 40000)) { - worldShutdownSequenceStarted = true; + Game::shouldShutdown = true; } } else { framesSinceLastUser = 0; @@ -470,7 +478,7 @@ int main(int argc, char** argv) { } } - if (worldShutdownSequenceStarted && !worldShutdownSequenceComplete) { + if (Game::shouldShutdown && !worldShutdownSequenceComplete) { WorldShutdownProcess(zoneID); break; } @@ -789,7 +797,7 @@ void HandlePacket(Packet* packet) { } case MSG_MASTER_SHUTDOWN: { - worldShutdownSequenceStarted = true; + Game::shouldShutdown = true; Game::logger->Log("WorldServer", "Got shutdown request from master, zone (%i), instance (%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); break; } @@ -1259,11 +1267,11 @@ void WorldShutdownProcess(uint32_t zoneId) { } void WorldShutdownSequence() { - if (worldShutdownSequenceStarted || worldShutdownSequenceComplete) { + if (Game::shouldShutdown || worldShutdownSequenceComplete) { return; } - worldShutdownSequenceStarted = true; + Game::shouldShutdown = true; Game::logger->Log("WorldServer", "Zone (%i) instance (%i) shutting down outside of main loop!", Game::server->GetZoneID(), instanceID); WorldShutdownProcess(Game::server->GetZoneID()); @@ -1271,15 +1279,16 @@ void WorldShutdownSequence() { } void FinalizeShutdown() { + //Delete our objects here: + if (Game::zoneManager) delete Game::zoneManager; + Game::logger->Log("WorldServer", "Shutdown complete, zone (%i), instance (%i)", Game::server->GetZoneID(), instanceID); - //Delete our objects here: Metrics::Clear(); Database::Destroy("WorldServer"); - if (Game::chatFilter) delete Game::chatFilter; - if (Game::server) delete Game::server; - if (Game::logger) delete Game::logger; - if (Game::config) delete Game::config; + delete Game::chatFilter; + delete Game::server; + delete Game::logger; worldShutdownSequenceComplete = true; diff --git a/tests/dGameTests/GameDependencies.cpp b/tests/dGameTests/GameDependencies.cpp index 7b0a8412..5ac3339a 100644 --- a/tests/dGameTests/GameDependencies.cpp +++ b/tests/dGameTests/GameDependencies.cpp @@ -4,6 +4,7 @@ namespace Game { dLogger* logger; dServer* server; dZoneManager* zoneManager; + dpWorld* physicsWorld; dChatFilter* chatFilter; dConfig* config; std::mt19937 randomEngine; From 1afe71756332574988eea8fcc4f5979450c0faa4 Mon Sep 17 00:00:00 2001 From: EmosewaMC <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 15 Dec 2022 05:46:03 -0800 Subject: [PATCH 169/322] Properly exit Properly exit based on the path taken to shutdown master. Tested that shutting down through sigint or sigterm returns -1 Tested that a segfault exits the program properly Need to test that players who are trying to connect while master is shutting down are not able to spawn more child worlds. --- dAuthServer/AuthServer.cpp | 2 +- dChatServer/ChatServer.cpp | 2 +- dMasterServer/InstanceManager.cpp | 2 +- dMasterServer/MasterServer.cpp | 82 ++++++++++++++++++++++--------- dNet/dServer.cpp | 4 +- dNet/dServer.h | 2 +- dWorldServer/WorldServer.cpp | 2 +- 7 files changed, 65 insertions(+), 31 deletions(-) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index 4fffc5d0..092b7fa4 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -84,7 +84,7 @@ int main(int argc, char** argv) { if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); - Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth, Game::config, Game::shouldShutdown); + Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth, Game::config, &Game::shouldShutdown); //Run it until server gets a kill message from Master: auto t = std::chrono::high_resolution_clock::now(); diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index d2eb7fc7..ace5e287 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -104,7 +104,7 @@ int main(int argc, char** argv) { if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); - Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config, Game::shouldShutdown); + Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config, &Game::shouldShutdown); Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index 327a18b9..de64c4ba 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -150,7 +150,7 @@ void InstanceManager::RemoveInstance(Instance* instance) { if (m_Instances[i] == instance) { instance->SetShutdownComplete(true); - RedirectPendingRequests(instance); + if (!Game::shouldShutdown) RedirectPendingRequests(instance); delete m_Instances[i]; diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 2f54243a..388654f5 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -52,13 +52,14 @@ namespace Game { } //namespace Game bool shutdownSequenceStarted = false; -void ShutdownSequence(); -int FinalizeShutdown(); +void ShutdownSequence(int signal = -1); +int FinalizeShutdown(int signal = -1); dLogger* SetupLogger(); void StartAuthServer(); void StartChatServer(); void HandlePacket(Packet* packet); std::map<uint32_t, std::string> activeSessions; +SystemAddress authServerMasterPeerSysAddr; SystemAddress chatServerMasterPeerSysAddr; int main(int argc, char** argv) { @@ -71,9 +72,9 @@ int main(int argc, char** argv) { #endif //Triggers the shutdown sequence at application exit - std::atexit(ShutdownSequence); - signal(SIGINT, [](int) { ShutdownSequence(); }); - signal(SIGTERM, [](int) { ShutdownSequence(); }); + std::atexit([]() { ShutdownSequence(); }); + signal(SIGINT, [](int signal) { ShutdownSequence(EXIT_FAILURE); }); + signal(SIGTERM, [](int signal) { ShutdownSequence(EXIT_FAILURE); }); //Create all the objects we need to run our service: Game::logger = SetupLogger(); @@ -216,7 +217,7 @@ int main(int argc, char** argv) { if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients")); if (Game::config->GetValue("port") != "") ourPort = std::stoi(Game::config->GetValue("port")); - Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, true, false, Game::logger, "", 0, ServerType::Master, Game::config, Game::shouldShutdown); + Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, true, false, Game::logger, "", 0, ServerType::Master, Game::config, &Game::shouldShutdown); //Query for the database for a server labeled "master" auto* masterLookupStatement = Database::CreatePreppedStmt("SELECT id FROM `servers` WHERE `name` = 'master'"); @@ -253,8 +254,8 @@ int main(int argc, char** argv) { if (Game::config->GetValue("prestart_servers") != "" && Game::config->GetValue("prestart_servers") == "1") { StartChatServer(); - Game::im->GetInstance(0, false, 0)->SetIsReady(true); - Game::im->GetInstance(1000, false, 0)->SetIsReady(true); + Game::im->GetInstance(0, false, 0); + Game::im->GetInstance(1000, false, 0); StartAuthServer(); } @@ -350,9 +351,7 @@ int main(int argc, char** argv) { t += std::chrono::milliseconds(highFrameRate); std::this_thread::sleep_until(t); } - FinalizeShutdown(); - exit(EXIT_SUCCESS); - return EXIT_SUCCESS; + return FinalizeShutdown(EXIT_SUCCESS); } dLogger* SetupLogger() { @@ -381,9 +380,15 @@ void HandlePacket(Packet* packet) { Game::im->RemoveInstance(instance); //Delete the old } - if (packet->systemAddress == chatServerMasterPeerSysAddr && !Game::shouldShutdown) { + if (packet->systemAddress == chatServerMasterPeerSysAddr) { + chatServerMasterPeerSysAddr = UNASSIGNED_SYSTEM_ADDRESS; StartChatServer(); } + + if (packet->systemAddress == authServerMasterPeerSysAddr) { + authServerMasterPeerSysAddr = UNASSIGNED_SYSTEM_ADDRESS; + StartAuthServer(); + } } if (packet->data[0] == ID_CONNECTION_LOST) { @@ -397,9 +402,15 @@ void HandlePacket(Packet* packet) { //Game::im->GetInstance(zoneID.GetMapID(), false, 0); //Create the new } - if (packet->systemAddress == chatServerMasterPeerSysAddr && !Game::shouldShutdown) { + if (packet->systemAddress == chatServerMasterPeerSysAddr) { + chatServerMasterPeerSysAddr = UNASSIGNED_SYSTEM_ADDRESS; StartChatServer(); } + + if (packet->systemAddress == authServerMasterPeerSysAddr) { + authServerMasterPeerSysAddr = UNASSIGNED_SYSTEM_ADDRESS; + StartAuthServer(); + } } if (packet->data[1] == MASTER) { @@ -495,6 +506,14 @@ void HandlePacket(Packet* packet) { chatServerMasterPeerSysAddr = copy; } + if (theirServerType == ServerType::Auth) { + SystemAddress copy; + copy.binaryAddress = packet->systemAddress.binaryAddress; + copy.port = packet->systemAddress.port; + + authServerMasterPeerSysAddr = copy; + } + Game::logger->Log("MasterServer", "Received server info, instance: %i port: %i", theirInstanceID, theirPort); break; @@ -726,10 +745,14 @@ void HandlePacket(Packet* packet) { default: Game::logger->Log("MasterServer", "Unknown master packet ID from server: %i", packet->data[3]); } + } } -} void StartChatServer() { + if (Game::shouldShutdown) { + Game::logger->Log("MasterServer", "Currently shutting down. Chat will not be restarted."); + return; + } #ifdef __APPLE__ //macOS doesn't need sudo to run on ports < 1024 system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); @@ -742,9 +765,13 @@ void StartChatServer() { system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); } #endif -} + } void StartAuthServer() { + if (Game::shouldShutdown) { + Game::logger->Log("MasterServer", "Currently shutting down. Auth will not be restarted."); + return; + } #ifdef __APPLE__ system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); #elif _WIN32 @@ -758,12 +785,13 @@ void StartAuthServer() { #endif } -void ShutdownSequence() { +void ShutdownSequence(int signal) { if (shutdownSequenceStarted) { return; } shutdownSequenceStarted = true; + Game::shouldShutdown = true; { CBITSTREAM; @@ -782,7 +810,14 @@ void ShutdownSequence() { auto ticks = 0; if (!Game::im) { - exit(EXIT_SUCCESS); + FinalizeShutdown(EXIT_FAILURE); + } + + // A server might not be finished spinning up yet, remove all of those here. + for (auto instance : Game::im->GetInstances()) { + if (!instance->GetIsReady()) { + Game::im->RemoveInstance(instance); + } } for (auto instance : Game::im->GetInstances()) { @@ -792,7 +827,6 @@ void ShutdownSequence() { Game::logger->Log("MasterServer", "Attempting to shutdown instances, max 60 seconds..."); while (true) { - auto packet = Game::server->Receive(); if (packet) { HandlePacket(packet); @@ -811,8 +845,8 @@ void ShutdownSequence() { done = false; } } - - if (done) { + + if (done && authServerMasterPeerSysAddr == UNASSIGNED_SYSTEM_ADDRESS && chatServerMasterPeerSysAddr == UNASSIGNED_SYSTEM_ADDRESS) { Game::logger->Log("MasterServer", "Finished shutting down MasterServer!"); break; } @@ -828,10 +862,10 @@ void ShutdownSequence() { } } - FinalizeShutdown(); + FinalizeShutdown(signal); } -int FinalizeShutdown() { +int FinalizeShutdown(int signal) { //Delete our objects here: Database::Destroy("MasterServer"); if (Game::config) delete Game::config; @@ -839,6 +873,6 @@ int FinalizeShutdown() { if (Game::server) delete Game::server; if (Game::logger) delete Game::logger; - exit(EXIT_SUCCESS); - return EXIT_SUCCESS; + if (signal != EXIT_SUCCESS) exit(signal); + return signal; } diff --git a/dNet/dServer.cpp b/dNet/dServer.cpp index 3a5ef822..f41b9699 100644 --- a/dNet/dServer.cpp +++ b/dNet/dServer.cpp @@ -36,7 +36,7 @@ public: } } ReceiveDownloadCompleteCB; -dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnections, bool isInternal, bool useEncryption, dLogger* logger, const std::string masterIP, int masterPort, ServerType serverType, dConfig* config, bool& shouldShutdown, unsigned int zoneID) { +dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnections, bool isInternal, bool useEncryption, dLogger* logger, const std::string masterIP, int masterPort, ServerType serverType, dConfig* config, bool* shouldShutdown, unsigned int zoneID) { mIP = ip; mPort = port; mZoneID = zoneID; @@ -52,7 +52,7 @@ dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnect mReplicaManager = nullptr; mServerType = serverType; mConfig = config; - mShouldShutdown = &shouldShutdown; + mShouldShutdown = shouldShutdown; //Attempt to start our server here: mIsOkay = Startup(); diff --git a/dNet/dServer.h b/dNet/dServer.h index 608b3b83..af4c8322 100644 --- a/dNet/dServer.h +++ b/dNet/dServer.h @@ -30,7 +30,7 @@ public: int masterPort, ServerType serverType, dConfig* config, - bool& shouldShutdown, + bool* shouldShutdown, unsigned int zoneID = 0); ~dServer(); diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 2fdb373b..abb2c19f 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -208,7 +208,7 @@ int main(int argc, char** argv) { LootGenerator::Instance(); Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); - Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, Game::config, Game::shouldShutdown, zoneID); + Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, Game::config, &Game::shouldShutdown, zoneID); //Connect to the chat server: int chatPort = 1501; From b7341c8106bf030813a408ebeae74e92ef212d1e Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 15 Dec 2022 06:13:49 -0800 Subject: [PATCH 170/322] Resolve warnings, change config init order and remove unused Game variables for all servers (#877) * Resolve warnings and change init order Initialize dConfig first, before logger so we know whether or not to log to console Initialize namespace Game variables to nullptr so they are a known value if accessed before initialization. Removed unused Game variables Replaced config with a pointer instead of referencing something on the stack. Assign return values to system calls to silence warnings. Tested that the server still compiles, runs and allows me to load into the game. * Only start Master of config files exist Also default the logging to console to on on the off chance the files exist but are wrong / corrupted. --- dAuthServer/AuthServer.cpp | 38 +++++++------- dChatServer/ChatServer.cpp | 46 ++++++++--------- dCommon/Game.h | 2 - dMasterServer/InstanceManager.cpp | 4 +- dMasterServer/MasterServer.cpp | 59 +++++++++++++++------- dWorldServer/WorldServer.cpp | 71 ++++++++++++--------------- tests/dGameTests/GameDependencies.cpp | 1 - 7 files changed, 117 insertions(+), 104 deletions(-) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index a9f02f53..aefc822b 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -22,9 +22,9 @@ #include "Game.h" namespace Game { - dLogger* logger; - dServer* server; - dConfig* config; + dLogger* logger = nullptr; + dServer* server = nullptr; + dConfig* config = nullptr; } dLogger* SetupLogger(); @@ -37,22 +37,22 @@ int main(int argc, char** argv) { //Create all the objects we need to run our service: Game::logger = SetupLogger(); - if (!Game::logger) return 0; + if (!Game::logger) return EXIT_FAILURE; + + //Read our config: + Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "authconfig.ini").string()); + Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0"); + Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); + Game::logger->Log("AuthServer", "Starting Auth server..."); Game::logger->Log("AuthServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("AuthServer", "Compiled on: %s", __TIMESTAMP__); - //Read our config: - dConfig config("authconfig.ini"); - Game::config = &config; - Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); - Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); - //Connect to the MySQL Database - std::string mysql_host = config.GetValue("mysql_host"); - std::string mysql_database = config.GetValue("mysql_database"); - std::string mysql_username = config.GetValue("mysql_username"); - std::string mysql_password = config.GetValue("mysql_password"); + std::string mysql_host = Game::config->GetValue("mysql_host"); + std::string mysql_database = Game::config->GetValue("mysql_database"); + std::string mysql_username = Game::config->GetValue("mysql_username"); + std::string mysql_password = Game::config->GetValue("mysql_password"); try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); @@ -61,7 +61,7 @@ int main(int argc, char** argv) { Database::Destroy("AuthServer"); delete Game::server; delete Game::logger; - return 0; + return EXIT_FAILURE; } //Find out the master's IP: @@ -80,10 +80,10 @@ int main(int argc, char** argv) { //It's safe to pass 'localhost' here, as the IP is only used as the external IP. int maxClients = 50; int ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. - if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); - if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); + if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients")); + if (Game::config->GetValue("port") != "") ourPort = std::atoi(Game::config->GetValue("port").c_str()); - Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth, Game::config); + Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth, Game::config); //Run it until server gets a kill message from Master: auto t = std::chrono::high_resolution_clock::now(); @@ -145,8 +145,8 @@ int main(int argc, char** argv) { Database::Destroy("AuthServer"); delete Game::server; delete Game::logger; + delete Game::config; - exit(EXIT_SUCCESS); return EXIT_SUCCESS; } diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index e3c6d6e9..043e7869 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -20,11 +20,11 @@ #include "Game.h" namespace Game { - dLogger* logger; - dServer* server; - dConfig* config; - dChatFilter* chatFilter; - AssetManager* assetManager; + dLogger* logger = nullptr; + dServer* server = nullptr; + dConfig* config = nullptr; + dChatFilter* chatFilter = nullptr; + AssetManager* assetManager = nullptr; } //RakNet includes: @@ -42,19 +42,19 @@ int main(int argc, char** argv) { //Create all the objects we need to run our service: Game::logger = SetupLogger(); - if (!Game::logger) return 0; + if (!Game::logger) return EXIT_FAILURE; + + //Read our config: + Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "chatconfig.ini").string()); + Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0"); + Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); + Game::logger->Log("ChatServer", "Starting Chat server..."); Game::logger->Log("ChatServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("ChatServer", "Compiled on: %s", __TIMESTAMP__); - //Read our config: - dConfig config("chatconfig.ini"); - Game::config = &config; - Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); - Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); - try { - std::string clientPathStr = config.GetValue("client_location"); + std::string clientPathStr = Game::config->GetValue("client_location"); if (clientPathStr.empty()) clientPathStr = "./res"; std::filesystem::path clientPath = std::filesystem::path(clientPathStr); if (clientPath.is_relative()) { @@ -69,10 +69,10 @@ int main(int argc, char** argv) { } //Connect to the MySQL Database - std::string mysql_host = config.GetValue("mysql_host"); - std::string mysql_database = config.GetValue("mysql_database"); - std::string mysql_username = config.GetValue("mysql_username"); - std::string mysql_password = config.GetValue("mysql_password"); + std::string mysql_host = Game::config->GetValue("mysql_host"); + std::string mysql_database = Game::config->GetValue("mysql_database"); + std::string mysql_username = Game::config->GetValue("mysql_username"); + std::string mysql_password = Game::config->GetValue("mysql_password"); try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); @@ -81,7 +81,7 @@ int main(int argc, char** argv) { Database::Destroy("ChatServer"); delete Game::server; delete Game::logger; - return 0; + return EXIT_FAILURE; } //Find out the master's IP: @@ -100,12 +100,12 @@ int main(int argc, char** argv) { //It's safe to pass 'localhost' here, as the IP is only used as the external IP. int maxClients = 50; int ourPort = 1501; - if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); - if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); + if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients")); + if (Game::config->GetValue("port") != "") ourPort = std::atoi(Game::config->GetValue("port").c_str()); - Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config); + Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config); - Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); + Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(Game::config->GetValue("dont_generate_dcf")))); //Run it until server gets a kill message from Master: auto t = std::chrono::high_resolution_clock::now(); @@ -167,8 +167,8 @@ int main(int argc, char** argv) { Database::Destroy("ChatServer"); delete Game::server; delete Game::logger; + delete Game::config; - exit(EXIT_SUCCESS); return EXIT_SUCCESS; } diff --git a/dCommon/Game.h b/dCommon/Game.h index 1c4bbc85..38cadb70 100644 --- a/dCommon/Game.h +++ b/dCommon/Game.h @@ -5,7 +5,6 @@ class dServer; class dLogger; class InstanceManager; -class dpWorld; class dChatFilter; class dConfig; class RakPeerInterface; @@ -16,7 +15,6 @@ namespace Game { extern dLogger* logger; extern dServer* server; extern InstanceManager* im; - extern dpWorld* physicsWorld; extern dChatFilter* chatFilter; extern dConfig* config; extern std::mt19937 randomEngine; diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index 83378dbb..a1983dd4 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -74,7 +74,7 @@ Instance* InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, LW cmd.append("&"); //Sends our next process to the background on Linux #endif - system(cmd.c_str()); + auto ret = system(cmd.c_str()); m_Instances.push_back(instance); @@ -322,7 +322,7 @@ Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID clon cmd.append("&"); //Sends our next process to the background on Linux #endif - system(cmd.c_str()); + auto ret = system(cmd.c_str()); m_Instances.push_back(instance); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 4acb9b26..4c18566e 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -43,11 +43,11 @@ #include "FdbToSqlite.h" namespace Game { - dLogger* logger; - dServer* server; - InstanceManager* im; - dConfig* config; - AssetManager* assetManager; + dLogger* logger = nullptr; + dServer* server = nullptr; + InstanceManager* im = nullptr; + dConfig* config = nullptr; + AssetManager* assetManager = nullptr; } //namespace Game bool shutdownSequenceStarted = false; @@ -79,14 +79,39 @@ int main(int argc, char** argv) { Game::logger = SetupLogger(); if (!Game::logger) return EXIT_FAILURE; + if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "authconfig.ini")) { + Game::logger->Log("MasterServer", "Couldnt find authconfig.ini"); + return EXIT_FAILURE; + } + + if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "chatconfig.ini")) { + Game::logger->Log("MasterServer", "Couldnt find chatconfig.ini"); + return EXIT_FAILURE; + } + + if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "masterconfig.ini")) { + Game::logger->Log("MasterServer", "Couldnt find masterconfig.ini"); + return EXIT_FAILURE; + } + + if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "sharedconfig.ini")) { + Game::logger->Log("MasterServer", "Couldnt find sharedconfig.ini"); + return EXIT_FAILURE; + } + + if (!std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "worldconfig.ini")) { + Game::logger->Log("MasterServer", "Couldnt find worldconfig.ini"); + return EXIT_FAILURE; + } + + Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "masterconfig.ini").string()); + Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0"); + Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); + Game::logger->Log("MasterServer", "Starting Master server..."); Game::logger->Log("MasterServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("MasterServer", "Compiled on: %s", __TIMESTAMP__); - Game::config = new dConfig("masterconfig.ini"); - Game::logger->SetLogToConsole(bool(std::stoi(Game::config->GetValue("log_to_console")))); - Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); - //Connect to the MySQL Database std::string mysql_host = Game::config->GetValue("mysql_host"); std::string mysql_database = Game::config->GetValue("mysql_database"); @@ -732,28 +757,28 @@ void HandlePacket(Packet* packet) { void StartChatServer() { #ifdef __APPLE__ //macOS doesn't need sudo to run on ports < 1024 - system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); + auto result = system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); #elif _WIN32 - system(("start " + (BinaryPathFinder::GetBinaryDir() / "ChatServer.exe").string()).c_str()); + auto result = system(("start " + (BinaryPathFinder::GetBinaryDir() / "ChatServer.exe").string()).c_str()); #else if (std::atoi(Game::config->GetValue("use_sudo_chat").c_str())) { - system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); + auto result = system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); } else { - system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); + auto result = system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); } #endif } void StartAuthServer() { #ifdef __APPLE__ - system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); + auto result = system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); #elif _WIN32 - system(("start " + (BinaryPathFinder::GetBinaryDir() / "AuthServer.exe").string()).c_str()); + auto result = system(("start " + (BinaryPathFinder::GetBinaryDir() / "AuthServer.exe").string()).c_str()); #else if (std::atoi(Game::config->GetValue("use_sudo_auth").c_str())) { - system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); + auto result = system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); } else { - system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); + auto result = system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); } #endif } diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index acd38ad3..68ec0e57 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -61,17 +61,14 @@ #include "ZCompression.h" namespace Game { - dLogger* logger; - dServer* server; - dZoneManager* zoneManager; - dpWorld* physicsWorld; - dChatFilter* chatFilter; - dConfig* config; + dLogger* logger = nullptr; + dServer* server = nullptr; + dpWorld* physicsWorld = nullptr; + dChatFilter* chatFilter = nullptr; + dConfig* config = nullptr; + AssetManager* assetManager = nullptr; + RakPeerInterface* chatServer = nullptr; std::mt19937 randomEngine; - - AssetManager* assetManager; - - RakPeerInterface* chatServer; SystemAddress chatSysAddr; } @@ -127,26 +124,21 @@ int main(int argc, char** argv) { //Create all the objects we need to run our service: Game::logger = SetupLogger(zoneID, instanceID); - if (!Game::logger) return 0; + if (!Game::logger) return EXIT_FAILURE; + + //Read our config: + Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "worldconfig.ini").string()); + Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0"); + Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1"); - Game::logger->SetLogToConsole(true); //We want this info to always be logged. Game::logger->Log("WorldServer", "Starting World server..."); Game::logger->Log("WorldServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("WorldServer", "Compiled on: %s", __TIMESTAMP__); -#ifndef _DEBUG - Game::logger->SetLogToConsole(false); //By default, turn it back off if not in debug. -#endif - - //Read our config: - dConfig config("worldconfig.ini"); - Game::config = &config; - Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console")))); - Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1"); - if (config.GetValue("disable_chat") == "1") chatDisabled = true; + if (Game::config->GetValue("disable_chat") == "1") chatDisabled = true; try { - std::string clientPathStr = config.GetValue("client_location"); + std::string clientPathStr = Game::config->GetValue("client_location"); if (clientPathStr.empty()) clientPathStr = "./res"; std::filesystem::path clientPath = std::filesystem::path(clientPathStr); if (clientPath.is_relative()) { @@ -166,28 +158,28 @@ int main(int argc, char** argv) { Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); Game::logger->Log("WorldServer", "Error Code: %i", e.errorCode()); - return -1; + return EXIT_FAILURE; } CDClientManager::Instance()->Initialize(); //Connect to the MySQL Database - std::string mysql_host = config.GetValue("mysql_host"); - std::string mysql_database = config.GetValue("mysql_database"); - std::string mysql_username = config.GetValue("mysql_username"); - std::string mysql_password = config.GetValue("mysql_password"); + std::string mysql_host = Game::config->GetValue("mysql_host"); + std::string mysql_database = Game::config->GetValue("mysql_database"); + std::string mysql_username = Game::config->GetValue("mysql_username"); + std::string mysql_password = Game::config->GetValue("mysql_password"); - Diagnostics::SetProduceMemoryDump(config.GetValue("generate_dump") == "1"); + Diagnostics::SetProduceMemoryDump(Game::config->GetValue("generate_dump") == "1"); - if (!config.GetValue("dump_folder").empty()) { - Diagnostics::SetOutDirectory(config.GetValue("dump_folder")); + if (!Game::config->GetValue("dump_folder").empty()) { + Diagnostics::SetOutDirectory(Game::config->GetValue("dump_folder")); } try { Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); } catch (sql::SQLException& ex) { Game::logger->Log("WorldServer", "Got an error while connecting to the database: %s", ex.what()); - return 0; + return EXIT_FAILURE; } //Find out the master's IP: @@ -206,13 +198,13 @@ int main(int argc, char** argv) { ObjectIDManager::Instance()->Initialize(); UserManager::Instance()->Initialize(); LootGenerator::Instance(); - Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); + Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(Game::config->GetValue("dont_generate_dcf")))); Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, Game::config, zoneID); //Connect to the chat server: int chatPort = 1501; - if (config.GetValue("chat_server_port") != "") chatPort = std::atoi(config.GetValue("chat_server_port").c_str()); + if (Game::config->GetValue("chat_server_port") != "") chatPort = std::atoi(Game::config->GetValue("chat_server_port").c_str()); auto chatSock = SocketDescriptor(uint16_t(ourPort + 2), 0); Game::chatServer = RakNetworkFactory::GetRakPeerInterface(); @@ -1279,16 +1271,15 @@ void WorldShutdownSequence() { } void FinalizeShutdown() { - //Delete our objects here: - if (Game::zoneManager) delete Game::zoneManager; - Game::logger->Log("WorldServer", "Shutdown complete, zone (%i), instance (%i)", Game::server->GetZoneID(), instanceID); + //Delete our objects here: Metrics::Clear(); Database::Destroy("WorldServer"); - delete Game::chatFilter; - delete Game::server; - delete Game::logger; + if (Game::chatFilter) delete Game::chatFilter; + if (Game::server) delete Game::server; + if (Game::logger) delete Game::logger; + if (Game::config) delete Game::config; worldShutdownSequenceComplete = true; diff --git a/tests/dGameTests/GameDependencies.cpp b/tests/dGameTests/GameDependencies.cpp index 5ac3339a..7b0a8412 100644 --- a/tests/dGameTests/GameDependencies.cpp +++ b/tests/dGameTests/GameDependencies.cpp @@ -4,7 +4,6 @@ namespace Game { dLogger* logger; dServer* server; dZoneManager* zoneManager; - dpWorld* physicsWorld; dChatFilter* chatFilter; dConfig* config; std::mt19937 randomEngine; From 4775dbf27f6d82b31dbe33fa83b82ecaf8d4fce4 Mon Sep 17 00:00:00 2001 From: EmosewaMC <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 15 Dec 2022 19:55:07 -0800 Subject: [PATCH 171/322] Condense frame rates --- dAuthServer/AuthServer.cpp | 2 +- dChatServer/ChatServer.cpp | 2 +- dCommon/dEnums/dCommonVars.h | 15 +++++++++++---- dMasterServer/MasterServer.cpp | 4 ++-- dWorldServer/PerformanceManager.cpp | 26 +++++++------------------- dWorldServer/PerformanceManager.h | 5 ----- dWorldServer/WorldServer.cpp | 4 ++-- 7 files changed, 24 insertions(+), 34 deletions(-) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index 3fd4b0bf..e4d8a052 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -138,7 +138,7 @@ int main(int argc, char** argv) { } else framesSinceLastSQLPing++; //Sleep our thread since auth can afford to. - t += std::chrono::milliseconds(mediumFramerate); //Auth can run at a lower "fps" + t += std::chrono::milliseconds(mediumFrameDelta); //Auth can run at a lower "fps" std::this_thread::sleep_until(t); } diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index f3b2c123..8ae1a9bd 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -160,7 +160,7 @@ int main(int argc, char** argv) { } else framesSinceLastSQLPing++; //Sleep our thread since auth can afford to. - t += std::chrono::milliseconds(mediumFramerate); //Chat can run at a lower "fps" + t += std::chrono::milliseconds(mediumFrameDelta); //Chat can run at a lower "fps" std::this_thread::sleep_until(t); } diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index f64d496f..f3d02bf7 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -6,15 +6,22 @@ #include <cstdint> #include <string> #include <set> -#include "../thirdparty/raknet/Source/BitStream.h" +#include "BitStream.h" #pragma warning (disable:4251) //Disables SQL warnings typedef int RESTICKET; -const int highFrameRate = 16; //60fps -const int mediumFramerate = 33; //30fps -const int lowFramerate = 66; //15fps +#define FRAMES_TO_MS(x) 1000 / x + +//=========== FRAME TIMINGS =========== +constexpr uint32_t highFramerate = 60; +constexpr uint32_t mediumFramerate = 30; +constexpr uint32_t lowFramerate = 15; + +constexpr uint32_t highFrameDelta = FRAMES_TO_MS(highFramerate); +constexpr uint32_t mediumFrameDelta = FRAMES_TO_MS(mediumFramerate); +constexpr uint32_t lowFrameDelta = FRAMES_TO_MS(lowFramerate); //========== MACROS =========== diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index bfe9f323..49919568 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -373,7 +373,7 @@ int main(int argc, char** argv) { } } - t += std::chrono::milliseconds(highFrameRate); + t += std::chrono::milliseconds(highFrameDelta); std::this_thread::sleep_until(t); } return FinalizeShutdown(EXIT_SUCCESS); @@ -876,7 +876,7 @@ void ShutdownSequence(int signal) { break; } - t += std::chrono::milliseconds(highFrameRate); + t += std::chrono::milliseconds(highFrameDelta); std::this_thread::sleep_until(t); ticks++; diff --git a/dWorldServer/PerformanceManager.cpp b/dWorldServer/PerformanceManager.cpp index 85546f28..66dcb615 100644 --- a/dWorldServer/PerformanceManager.cpp +++ b/dWorldServer/PerformanceManager.cpp @@ -2,23 +2,18 @@ #include "UserManager.h" -//Times are 1 / fps, in ms -#define HIGH 16 //60 fps -#define MEDIUM 33 //30 fps -#define LOW 66 //15 fps - -#define SOCIAL { LOW } -#define SOCIAL_HUB { MEDIUM } //Added to compensate for the large playercounts in NS and NT -#define BATTLE { HIGH } -#define BATTLE_INSTANCE { MEDIUM } -#define RACE { HIGH } -#define PROPERTY { LOW } +#define SOCIAL { lowFrameDelta } +#define SOCIAL_HUB { mediumFrameDelta } //Added to compensate for the large playercounts in NS and NT +#define BATTLE { highFrameDelta } +#define BATTLE_INSTANCE { mediumFrameDelta } +#define RACE { highFrameDelta } +#define PROPERTY { lowFrameDelta } PerformanceProfile PerformanceManager::m_CurrentProfile = SOCIAL; PerformanceProfile PerformanceManager::m_DefaultProfile = SOCIAL; -PerformanceProfile PerformanceManager::m_InactiveProfile = { LOW }; +PerformanceProfile PerformanceManager::m_InactiveProfile = { lowFrameDelta }; std::map<LWOMAPID, PerformanceProfile> PerformanceManager::m_Profiles = { // VE @@ -72,13 +67,6 @@ std::map<LWOMAPID, PerformanceProfile> PerformanceManager::m_Profiles = { { 2001, BATTLE_INSTANCE }, }; - -PerformanceManager::PerformanceManager() { -} - -PerformanceManager::~PerformanceManager() { -} - void PerformanceManager::SelectProfile(LWOMAPID mapID) { const auto pair = m_Profiles.find(mapID); diff --git a/dWorldServer/PerformanceManager.h b/dWorldServer/PerformanceManager.h index b8a090e0..3d8517eb 100644 --- a/dWorldServer/PerformanceManager.h +++ b/dWorldServer/PerformanceManager.h @@ -8,18 +8,13 @@ struct PerformanceProfile { uint32_t serverFramerate; }; - class PerformanceManager { public: - ~PerformanceManager(); - static void SelectProfile(LWOMAPID mapID); static uint32_t GetServerFramerate(); private: - PerformanceManager(); - static PerformanceProfile m_CurrentProfile; static PerformanceProfile m_DefaultProfile; static PerformanceProfile m_InactiveProfile; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 594d3dc7..c531595f 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -232,7 +232,7 @@ int main(int argc, char** argv) { bool ready = false; int framesSinceMasterStatus = 0; int framesSinceShutdownSequence = 0; - int currentFramerate = highFrameRate; + int currentFramerate = highFrameDelta; int ghostingStepCount = 0; auto ghostingLastTime = std::chrono::high_resolution_clock::now(); @@ -300,7 +300,7 @@ int main(int argc, char** argv) { const auto occupied = UserManager::Instance()->GetUserCount() != 0; if (!ready) { - currentFramerate = highFrameRate; + currentFramerate = highFrameDelta; } else { currentFramerate = PerformanceManager::GetServerFramerate(); } From 3c581fffbbb67c414add2be5afccb76c24ff42b6 Mon Sep 17 00:00:00 2001 From: EmosewaMC <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 15 Dec 2022 20:39:29 -0800 Subject: [PATCH 172/322] Remove magic numbers Replace magic numbers with constexpr calculated times. Tested that trying to create a new instance while shutting down doesn't allow a new instance to be created. --- dMasterServer/InstanceManager.cpp | 20 +++++++- dMasterServer/InstanceManager.h | 6 +++ dMasterServer/MasterServer.cpp | 81 ++++++++++++++++++------------- 3 files changed, 73 insertions(+), 34 deletions(-) diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index 868bf6ee..b277adbf 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -31,6 +31,15 @@ Instance* InstanceManager::GetInstance(LWOMAPID mapID, bool isFriendTransfer, LW Instance* instance = FindInstance(mapID, isFriendTransfer, cloneID); if (instance) return instance; + // If we are shutting down, return a nullptr so a new instance is not created. + if (m_IsShuttingDown) { + Game::logger->Log("InstanceManager", + "Tried to create a new instance map/instance/clone %i/%i/%i, but Master is shutting down.", + mapID, + m_LastInstanceID + 1, + cloneID); + return nullptr; + } //TODO: Update this so that the IP is read from a configuration file instead int softCap = 8; @@ -238,7 +247,7 @@ void InstanceManager::RedirectPendingRequests(Instance* instance) { for (const auto& request : instance->GetPendingAffirmations()) { auto* in = Game::im->GetInstance(zoneId.GetMapID(), false, zoneId.GetCloneID()); - if (!in->GetIsReady()) // Instance not ready, make a pending request + if (in && !in->GetIsReady()) // Instance not ready, make a pending request { in->GetPendingRequests().push_back(request); @@ -295,6 +304,15 @@ Instance* InstanceManager::CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID clon return instance; } + if (m_IsShuttingDown) { + Game::logger->Log("InstanceManager", + "Tried to create a new private instance map/instance/clone %i/%i/%i, but Master is shutting down.", + mapID, + m_LastInstanceID + 1, + cloneID); + return nullptr; + } + int maxPlayers = 999; uint32_t port = GetFreePort(); diff --git a/dMasterServer/InstanceManager.h b/dMasterServer/InstanceManager.h index 2c5083d4..5f48f93b 100644 --- a/dMasterServer/InstanceManager.h +++ b/dMasterServer/InstanceManager.h @@ -128,6 +128,7 @@ public: Instance* CreatePrivateInstance(LWOMAPID mapID, LWOCLONEID cloneID, const std::string& password); Instance* FindPrivateInstance(const std::string& password); + void SetIsShuttingDown(bool value) { this->m_IsShuttingDown = value; }; private: dLogger* mLogger; @@ -136,6 +137,11 @@ private: unsigned short m_LastPort; LWOINSTANCEID m_LastInstanceID; + /** + * Whether or not the master server is currently shutting down. + */ + bool m_IsShuttingDown = false; + //Private functions: bool IsInstanceFull(Instance* instance, bool isFriendTransfer); int GetSoftCap(LWOMAPID mapID); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 49919568..ed94ff83 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -63,6 +63,8 @@ SystemAddress authServerMasterPeerSysAddr; SystemAddress chatServerMasterPeerSysAddr; int main(int argc, char** argv) { + constexpr uint32_t masterFramerate = mediumFramerate; + constexpr uint32_t masterFrameDelta = mediumFrameDelta; Diagnostics::SetProcessName("Master"); Diagnostics::SetProcessFileName(argv[0]); Diagnostics::Initialize(); @@ -287,6 +289,10 @@ int main(int argc, char** argv) { auto t = std::chrono::high_resolution_clock::now(); Packet* packet = nullptr; + constexpr uint32_t logFlushTime = 15 * masterFramerate; + constexpr uint32_t sqlPingTime = 10 * 60 * masterFramerate; + constexpr uint32_t shutdownUniverseTime = 10 * 60 * masterFramerate; + constexpr uint32_t instanceReadyTimeout = 30 * masterFramerate; int framesSinceLastFlush = 0; int framesSinceLastSQLPing = 0; int framesSinceKillUniverseCommand = 0; @@ -303,14 +309,14 @@ int main(int argc, char** argv) { } //Push our log every 15s: - if (framesSinceLastFlush >= 900) { + if (framesSinceLastFlush >= logFlushTime) { Game::logger->Flush(); framesSinceLastFlush = 0; } else framesSinceLastFlush++; //Every 10 min we ping our sql server to keep it alive hopefully: - if (framesSinceLastSQLPing >= 40000) { + if (framesSinceLastSQLPing >= sqlPingTime) { //Find out the master's IP for absolutely no reason: std::string masterIP; int masterPort; @@ -330,7 +336,7 @@ int main(int argc, char** argv) { //10m shutdown for universe kill command if (Game::shouldShutdown) { - if (framesSinceKillUniverseCommand >= 40000) { + if (framesSinceKillUniverseCommand >= shutdownUniverseTime) { //Break main loop and exit break; } else @@ -354,7 +360,7 @@ int main(int argc, char** argv) { instance->SetAffirmationTimeout(affirmTimeout); - if (affirmTimeout == 1000) { + if (affirmTimeout == instanceReadyTimeout) { instance->Shutdown(); instance->SetIsShuttingDown(true); @@ -373,7 +379,7 @@ int main(int argc, char** argv) { } } - t += std::chrono::milliseconds(highFrameDelta); + t += std::chrono::milliseconds(masterFrameDelta); std::this_thread::sleep_until(t); } return FinalizeShutdown(EXIT_SUCCESS); @@ -424,7 +430,6 @@ void HandlePacket(Packet* packet) { if (instance) { LWOZONEID zoneID = instance->GetZoneID(); //Get the zoneID so we can recreate a server Game::im->RemoveInstance(instance); //Delete the old - //Game::im->GetInstance(zoneID.GetMapID(), false, 0); //Create the new } if (packet->systemAddress == chatServerMasterPeerSysAddr) { @@ -465,14 +470,17 @@ void HandlePacket(Packet* packet) { inStream.Read(mythranShift); inStream.Read(zoneID); inStream.Read(zoneClone); - + if (shutdownSequenceStarted) { + Game::logger->Log("MasterServer", "Shutdown sequence has been started. Not creating a new zone."); + break; + } Instance* in = Game::im->GetInstance(zoneID, false, zoneClone); for (auto* instance : Game::im->GetInstances()) { Game::logger->Log("MasterServer", "Instance: %i/%i/%i -> %i", instance->GetMapID(), instance->GetCloneID(), instance->GetInstanceID(), instance == in); } - if (!in->GetIsReady()) //Instance not ready, make a pending request + if (in && !in->GetIsReady()) //Instance not ready, make a pending request { in->GetPendingRequests().push_back({ requestID, static_cast<bool>(mythranShift), packet->systemAddress }); Game::logger->Log("MasterServer", "Server not ready, adding pending request %llu %i %i", requestID, zoneID, zoneClone); @@ -720,9 +728,13 @@ void HandlePacket(Packet* packet) { int zoneID; inStream.Read(zoneID); - - Game::logger->Log("MasterServer", "Prepping zone %i", zoneID); - Game::im->GetInstance(zoneID, false, 0); + if (shutdownSequenceStarted) { + Game::logger->Log("MasterServer", "Shutdown sequence has been started. Not prepping a new zone."); + break; + } else { + Game::logger->Log("MasterServer", "Prepping zone %i", zoneID); + Game::im->GetInstance(zoneID, false, 0); + } break; } @@ -770,8 +782,8 @@ void HandlePacket(Packet* packet) { default: Game::logger->Log("MasterServer", "Unknown master packet ID from server: %i", packet->data[3]); } - } } +} void StartChatServer() { if (Game::shouldShutdown) { @@ -788,9 +800,9 @@ void StartChatServer() { auto result = system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); } else { auto result = system(((BinaryPathFinder::GetBinaryDir() / "ChatServer").string() + "&").c_str()); - } +} #endif - } +} void StartAuthServer() { if (Game::shouldShutdown) { @@ -806,7 +818,7 @@ void StartAuthServer() { auto result = system(("sudo " + (BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); } else { auto result = system(((BinaryPathFinder::GetBinaryDir() / "AuthServer").string() + "&").c_str()); - } +} #endif } @@ -815,6 +827,11 @@ void ShutdownSequence(int signal) { return; } + if (!Game::im) { + FinalizeShutdown(EXIT_FAILURE); + } + + Game::im->SetIsShuttingDown(true); shutdownSequenceStarted = true; Game::shouldShutdown = true; @@ -826,40 +843,38 @@ void ShutdownSequence(int signal) { } auto* objIdManager = ObjectIDManager::TryInstance(); - if (objIdManager != nullptr) { + if (objIdManager) { objIdManager->SaveToDatabase(); Game::logger->Log("MasterServer", "Saved ObjectIDTracker to DB"); } - auto t = std::chrono::high_resolution_clock::now(); - auto ticks = 0; - - if (!Game::im) { - FinalizeShutdown(EXIT_FAILURE); - } - // A server might not be finished spinning up yet, remove all of those here. - for (auto instance : Game::im->GetInstances()) { + for (auto* instance : Game::im->GetInstances()) { if (!instance->GetIsReady()) { Game::im->RemoveInstance(instance); } } - for (auto instance : Game::im->GetInstances()) { + for (auto* instance : Game::im->GetInstances()) { instance->SetIsShuttingDown(true); } Game::logger->Log("MasterServer", "Attempting to shutdown instances, max 60 seconds..."); + auto t = std::chrono::high_resolution_clock::now(); + uint32_t framesSinceShutdownStart = 0; + constexpr uint32_t maxShutdownTime = 60 * mediumFramerate; + bool allInstancesShutdown = false; + Packet* packet = nullptr; while (true) { - auto packet = Game::server->Receive(); + packet = Game::server->Receive(); if (packet) { HandlePacket(packet); Game::server->DeallocatePacket(packet); packet = nullptr; } - auto done = true; + allInstancesShutdown = true; for (auto* instance : Game::im->GetInstances()) { if (instance == nullptr) { @@ -867,21 +882,21 @@ void ShutdownSequence(int signal) { } if (!instance->GetShutdownComplete()) { - done = false; + allInstancesShutdown = false; } } - - if (done && authServerMasterPeerSysAddr == UNASSIGNED_SYSTEM_ADDRESS && chatServerMasterPeerSysAddr == UNASSIGNED_SYSTEM_ADDRESS) { + + if (allInstancesShutdown && authServerMasterPeerSysAddr == UNASSIGNED_SYSTEM_ADDRESS && chatServerMasterPeerSysAddr == UNASSIGNED_SYSTEM_ADDRESS) { Game::logger->Log("MasterServer", "Finished shutting down MasterServer!"); break; } - t += std::chrono::milliseconds(highFrameDelta); + t += std::chrono::milliseconds(mediumFrameDelta); std::this_thread::sleep_until(t); - ticks++; + framesSinceShutdownStart++; - if (ticks == 600 * 6) { + if (framesSinceShutdownStart == maxShutdownTime) { Game::logger->Log("MasterServer", "Finished shutting down by timeout!"); break; } From 213c3c37b0ac03d9ee6ffeb76e69e4f8dc5617e9 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 15 Dec 2022 22:10:58 -0800 Subject: [PATCH 173/322] Fix crash in BasicAttackBehavior (#862) * Add failArmor server side Address out of bounds reading in behavior Address the basicAttackBehavior reading out of bounds memory and reading bits that didnt exist, which occasionally caused crashes and also caused the behavior to do undefined behavior due to the bad reads. Tested that attacking a wall anywhere with a projectile now does not crash the game. Tested with logs that the behavior correctly returned when there were no allocated bits or returned when other states were met. Add back logs and add fail handle Remove comment block Revert "Add back logs and add fail handle" This reverts commit db19be0906fc8bf35bf89037e2bfba39f5ef9c0c. Split out checks * Remove case 2 * Update SkillComponent.cpp --- dGame/dBehaviors/BasicAttackBehavior.cpp | 85 ++++++++++++++++-------- dGame/dBehaviors/BasicAttackBehavior.h | 14 ++-- dGame/dComponents/SkillComponent.cpp | 29 +------- 3 files changed, 65 insertions(+), 63 deletions(-) diff --git a/dGame/dBehaviors/BasicAttackBehavior.cpp b/dGame/dBehaviors/BasicAttackBehavior.cpp index fe773f36..f166f00c 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.cpp +++ b/dGame/dBehaviors/BasicAttackBehavior.cpp @@ -14,43 +14,65 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi auto* destroyableComponent = entity->GetComponent<DestroyableComponent>(); if (destroyableComponent != nullptr) { PlayFx(u"onhit", entity->GetObjectID()); - destroyableComponent->Damage(this->m_maxDamage, context->originator, context->skillID); + destroyableComponent->Damage(this->m_MaxDamage, context->originator, context->skillID); } - this->m_onSuccess->Handle(context, bitStream, branch); + this->m_OnSuccess->Handle(context, bitStream, branch); return; } bitStream->AlignReadToByteBoundary(); - uint16_t allocatedBits; - bitStream->Read(allocatedBits); - + uint16_t allocatedBits{}; + if (!bitStream->Read(allocatedBits) || allocatedBits == 0) { + Game::logger->LogDebug("BasicAttackBehavior", "No allocated bits"); + return; + } + Game::logger->LogDebug("BasicAttackBehavior", "Number of allocated bits %i", allocatedBits); const auto baseAddress = bitStream->GetReadOffset(); - if (bitStream->ReadBit()) { // Blocked + bool isBlocked{}; + bool isImmune{}; + bool isSuccess{}; + + if (!bitStream->Read(isBlocked)) { + Game::logger->LogDebug("BasicAttackBehavior", "Unable to read isBlocked"); return; } - if (bitStream->ReadBit()) { // Immune + if (isBlocked) return; + + if (!bitStream->Read(isImmune)) { + Game::logger->LogDebug("BasicAttackBehavior", "Unable to read isImmune"); return; } - if (bitStream->ReadBit()) { // Success - uint32_t unknown; - bitStream->Read(unknown); + if (isImmune) return; - uint32_t damageDealt; - bitStream->Read(damageDealt); + if (bitStream->Read(isSuccess) && isSuccess) { // Success + uint32_t unknown{}; + if (!bitStream->Read(unknown)) { + Game::logger->LogDebug("BasicAttackBehavior", "Unable to read unknown"); + return; + } + + uint32_t damageDealt{}; + if (!bitStream->Read(damageDealt)) { + Game::logger->LogDebug("BasicAttackBehavior", "Unable to read damageDealt"); + return; + } // A value that's too large may be a cheating attempt, so we set it to MIN too - if (damageDealt > this->m_maxDamage || damageDealt < this->m_minDamage) { - damageDealt = this->m_minDamage; + if (damageDealt > this->m_MaxDamage || damageDealt < this->m_MinDamage) { + damageDealt = this->m_MinDamage; } auto* entity = EntityManager::Instance()->GetEntity(branch.target); - bool died; - bitStream->Read(died); + bool died{}; + if (!bitStream->Read(died)) { + Game::logger->LogDebug("BasicAttackBehavior", "Unable to read died"); + return; + } if (entity != nullptr) { auto* destroyableComponent = entity->GetComponent<DestroyableComponent>(); @@ -61,15 +83,18 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi } } - uint8_t successState; - bitStream->Read(successState); + uint8_t successState{}; + if (!bitStream->Read(successState)) { + Game::logger->LogDebug("BasicAttackBehavior", "Unable to read success state"); + return; + } switch (successState) { case 1: - this->m_onSuccess->Handle(context, bitStream, branch); + this->m_OnSuccess->Handle(context, bitStream, branch); break; default: - Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!", successState); + Game::logger->LogDebug("BasicAttackBehavior", "Unknown success state (%i)!", successState); break; } @@ -79,7 +104,7 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* self = EntityManager::Instance()->GetEntity(context->originator); if (self == nullptr) { - Game::logger->Log("BasicAttackBehavior", "Invalid self entity (%llu)!", context->originator); + Game::logger->LogDebug("BasicAttackBehavior", "Invalid self entity (%llu)!", context->originator); return; } @@ -99,7 +124,7 @@ void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* uint32_t unknown3 = 0; bitStream->Write(unknown3); - auto damage = this->m_minDamage; + auto damage = this->m_MinDamage; auto* entity = EntityManager::Instance()->GetEntity(branch.target); if (entity == nullptr) { @@ -124,10 +149,10 @@ void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* switch (successState) { case 1: - this->m_onSuccess->Calculate(context, bitStream, branch); + this->m_OnSuccess->Calculate(context, bitStream, branch); break; default: - Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!", successState); + Game::logger->LogDebug("BasicAttackBehavior", "Unknown success state (%i)!", successState); break; } @@ -140,11 +165,13 @@ void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* } void BasicAttackBehavior::Load() { - this->m_minDamage = GetInt("min damage"); - if (this->m_minDamage == 0) this->m_minDamage = 1; + this->m_MinDamage = GetInt("min damage"); + if (this->m_MinDamage == 0) this->m_MinDamage = 1; - this->m_maxDamage = GetInt("max damage"); - if (this->m_maxDamage == 0) this->m_maxDamage = 1; + this->m_MaxDamage = GetInt("max damage"); + if (this->m_MaxDamage == 0) this->m_MaxDamage = 1; - this->m_onSuccess = GetAction("on_success"); + this->m_OnSuccess = GetAction("on_success"); + + this->m_OnFailArmor = GetAction("on_fail_armor"); } diff --git a/dGame/dBehaviors/BasicAttackBehavior.h b/dGame/dBehaviors/BasicAttackBehavior.h index 8e23d443..9c08141c 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.h +++ b/dGame/dBehaviors/BasicAttackBehavior.h @@ -4,12 +4,6 @@ class BasicAttackBehavior final : public Behavior { public: - uint32_t m_minDamage; - - uint32_t m_maxDamage; - - Behavior* m_onSuccess; - explicit BasicAttackBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } @@ -18,4 +12,12 @@ public: void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; +private: + uint32_t m_MinDamage; + + uint32_t m_MaxDamage; + + Behavior* m_OnSuccess; + + Behavior* m_OnFailArmor; }; diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index f7e8e7d9..c749dbaf 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -319,34 +319,7 @@ void SkillComponent::CalculateUpdate(const float deltaTime) { const auto distance = Vector3::DistanceSquared(targetPosition, closestPoint); if (distance > 3 * 3) { - /* - if (entry.TrackTarget && distance <= entry.TrackRadius) - { - const auto rotation = NiQuaternion::LookAtUnlocked(position, targetPosition); - - const auto speed = entry.Velocity.Length(); - - const auto homingTarget = rotation.GetForwardVector() * speed; - - Vector3 homing; - - // Move towards - - const auto difference = homingTarget - entry.Velocity; - const auto mag = difference.Length(); - if (mag <= speed || mag == 0) - { - homing = homingTarget; - } - else - { - entry.Velocity + homingTarget / mag * speed; - } - - entry.Velocity = homing; - } - */ - + // TODO There is supposed to be an implementation for homing projectiles here continue; } From 1ed3af63b9f2be42ecd1c7966c65a6ee604f90a7 Mon Sep 17 00:00:00 2001 From: Daniel Seiler <me@xiphoseer.de> Date: Fri, 16 Dec 2022 07:32:36 +0100 Subject: [PATCH 174/322] Log some recvfrom errors on linux (#885) --- thirdparty/raknet/Source/SocketLayer.cpp | 51 +++++++++++++++++++++++- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/thirdparty/raknet/Source/SocketLayer.cpp b/thirdparty/raknet/Source/SocketLayer.cpp index b6af8751..6cb4f7c6 100644 --- a/thirdparty/raknet/Source/SocketLayer.cpp +++ b/thirdparty/raknet/Source/SocketLayer.cpp @@ -417,8 +417,14 @@ int SocketLayer::RecvFrom( const SOCKET s, RakPeer *rakPeer, int *errorCode, uns assert( 0 ); #endif - *errorCode = -1; - return -1; + //*errorCode = -1; +#ifdef __linux__ + char str[INET_ADDRSTRLEN]; + inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN); + printf("[RakNet] SocketLayer::RecvFrom: empty datagram from %s", str); +#endif + //return -1; + return 0; } if ( len > 0 ) @@ -479,6 +485,47 @@ int SocketLayer::RecvFrom( const SOCKET s, RakPeer *rakPeer, int *errorCode, uns } #endif } +#elif defined(__linux__) + if (len < -1) + { + printf("[RakNet] SocketLayer::RecvFrom: Unexpected return value."); + return -1; + } + + int local_errno = errno; + if (local_errno == EAGAIN || local_errno == EWOULDBLOCK) + { + return 0; // no data + } + + if (local_errno == EINTR) + { + printf("[RakNet] SocketLayer::RecvFrom: The receive was interrupted by delivery of a signal before any data were available."); + return 0; // log, but ignore + } + + char str[INET_ADDRSTRLEN]; + inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN); + printf("[RakNet] SocketLayer::RecvFrom: Error receiving data from %s", str); + + switch (local_errno) { + case EINVAL: + printf("[RakNet] SocketLayer::RecvFrom: Invalid argument passed."); break; + case ENOMEM: + case ENOBUFS: + printf("[RakNet] SocketLayer::RecvFrom: Could not allocate memory for recvmsg()."); break; + case EFAULT: + printf("[RakNet] SocketLayer::RecvFrom: The receive buffer pointer(s) point outside the process's address space."); break; + case EBADF: + printf("[RakNet] SocketLayer::RecvFrom: The argument sockfd is an invalid descriptor."); break; + case ENOTSOCK: + printf("[RakNet] SocketLayer::RecvFrom: The argument sockfd does not refer to a socket."); break; + case EPIPE: + printf("[RakNet] SocketLayer::RecvFrom: The connection was unexpectedly closed or shut down by the other end. "); break; + default: + printf("[RakNet] SocketLayer::RecvFrom: Unknown Error %d", local_errno); break; + } + return -1; #endif } From 3f1b4339f5df28a9b4510349f32819f184239c88 Mon Sep 17 00:00:00 2001 From: David Markowitz <EmosewaMC@gmail.com> Date: Fri, 16 Dec 2022 02:24:02 -0800 Subject: [PATCH 175/322] Improve chat and Auth Also change most uses of int to specified lengths. --- dAuthServer/AuthServer.cpp | 26 ++++++++------ dChatServer/ChatServer.cpp | 33 ++++++++++-------- dMasterServer/MasterServer.cpp | 30 ++++++++-------- dWorldServer/WorldServer.cpp | 62 +++++++++++++++++----------------- 4 files changed, 80 insertions(+), 71 deletions(-) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index e4d8a052..f5090495 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -32,6 +32,8 @@ dLogger* SetupLogger(); void HandlePacket(Packet* packet); int main(int argc, char** argv) { + constexpr uint32_t authFramerate = mediumFramerate; + constexpr uint32_t authFrameDelta = mediumFrameDelta; Diagnostics::SetProcessName("Auth"); Diagnostics::SetProcessFileName(argv[0]); Diagnostics::Initialize(); @@ -67,7 +69,7 @@ int main(int argc, char** argv) { //Find out the master's IP: std::string masterIP; - int masterPort = 1500; + uint32_t masterPort = 1500; sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';"); auto res = stmt->executeQuery(); while (res->next()) { @@ -79,8 +81,8 @@ int main(int argc, char** argv) { delete stmt; //It's safe to pass 'localhost' here, as the IP is only used as the external IP. - int maxClients = 50; - int ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. + uint32_t maxClients = 50; + uint32_t ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients")); if (Game::config->GetValue("port") != "") ourPort = std::atoi(Game::config->GetValue("port").c_str()); @@ -89,16 +91,18 @@ int main(int argc, char** argv) { //Run it until server gets a kill message from Master: auto t = std::chrono::high_resolution_clock::now(); Packet* packet = nullptr; - int framesSinceLastFlush = 0; - int framesSinceMasterDisconnect = 0; - int framesSinceLastSQLPing = 0; + constexpr uint32_t logFlushTime = 30 * authFramerate; // 30 seconds in frames + constexpr uint32_t sqlPingTime = 10 * 60 * authFramerate; // 10 minutes in frames + uint32_t framesSinceLastFlush = 0; + uint32_t framesSinceMasterDisconnect = 0; + uint32_t framesSinceLastSQLPing = 0; while (!Game::shouldShutdown) { //Check if we're still connected to master: if (!Game::server->GetIsConnectedToMaster()) { framesSinceMasterDisconnect++; - if (framesSinceMasterDisconnect >= 30) + if (framesSinceMasterDisconnect >= authFramerate) break; //Exit our loop, shut down. } else framesSinceMasterDisconnect = 0; @@ -114,16 +118,16 @@ int main(int argc, char** argv) { } //Push our log every 30s: - if (framesSinceLastFlush >= 900) { + if (framesSinceLastFlush >= logFlushTime) { Game::logger->Flush(); framesSinceLastFlush = 0; } else framesSinceLastFlush++; //Every 10 min we ping our sql server to keep it alive hopefully: - if (framesSinceLastSQLPing >= 40000) { + if (framesSinceLastSQLPing >= sqlPingTime) { //Find out the master's IP for absolutely no reason: std::string masterIP; - int masterPort; + uint32_t masterPort; sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';"); auto res = stmt->executeQuery(); while (res->next()) { @@ -138,7 +142,7 @@ int main(int argc, char** argv) { } else framesSinceLastSQLPing++; //Sleep our thread since auth can afford to. - t += std::chrono::milliseconds(mediumFrameDelta); //Auth can run at a lower "fps" + t += std::chrono::milliseconds(authFrameDelta); //Auth can run at a lower "fps" std::this_thread::sleep_until(t); } diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index 8ae1a9bd..a75c4d51 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -19,6 +19,9 @@ #include "ChatPacketHandler.h" #include "Game.h" + +//RakNet includes: +#include "RakNetDefines.h" namespace Game { dLogger* logger = nullptr; dServer* server = nullptr; @@ -28,8 +31,6 @@ namespace Game { bool shouldShutdown = false; } -//RakNet includes: -#include "RakNetDefines.h" dLogger* SetupLogger(); void HandlePacket(Packet* packet); @@ -37,6 +38,8 @@ void HandlePacket(Packet* packet); PlayerContainer playerContainer; int main(int argc, char** argv) { + constexpr uint32_t chatFramerate = mediumFramerate; + constexpr uint32_t chatFrameDelta = mediumFrameDelta; Diagnostics::SetProcessName("Chat"); Diagnostics::SetProcessFileName(argv[0]); Diagnostics::Initialize(); @@ -65,7 +68,7 @@ int main(int argc, char** argv) { Game::assetManager = new AssetManager(clientPath); } catch (std::runtime_error& ex) { Game::logger->Log("ChatServer", "Got an error while setting up assets: %s", ex.what()); - + return EXIT_FAILURE; } @@ -87,7 +90,7 @@ int main(int argc, char** argv) { //Find out the master's IP: std::string masterIP; - int masterPort = 1000; + uint32_t masterPort = 1000; sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';"); auto res = stmt->executeQuery(); while (res->next()) { @@ -99,8 +102,8 @@ int main(int argc, char** argv) { delete stmt; //It's safe to pass 'localhost' here, as the IP is only used as the external IP. - int maxClients = 50; - int ourPort = 1501; + uint32_t maxClients = 50; + uint32_t ourPort = 1501; if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients")); if (Game::config->GetValue("port") != "") ourPort = std::atoi(Game::config->GetValue("port").c_str()); @@ -111,16 +114,18 @@ int main(int argc, char** argv) { //Run it until server gets a kill message from Master: auto t = std::chrono::high_resolution_clock::now(); Packet* packet = nullptr; - int framesSinceLastFlush = 0; - int framesSinceMasterDisconnect = 0; - int framesSinceLastSQLPing = 0; + constexpr uint32_t logFlushTime = 30 * chatFramerate; // 30 seconds in frames + constexpr uint32_t sqlPingTime = 10 * 60 * chatFramerate; // 10 minutes in frames + uint32_t framesSinceLastFlush = 0; + uint32_t framesSinceMasterDisconnect = 0; + uint32_t framesSinceLastSQLPing = 0; while (!Game::shouldShutdown) { //Check if we're still connected to master: if (!Game::server->GetIsConnectedToMaster()) { framesSinceMasterDisconnect++; - if (framesSinceMasterDisconnect >= 30) + if (framesSinceMasterDisconnect >= chatFramerate) break; //Exit our loop, shut down. } else framesSinceMasterDisconnect = 0; @@ -136,16 +141,16 @@ int main(int argc, char** argv) { } //Push our log every 30s: - if (framesSinceLastFlush >= 900) { + if (framesSinceLastFlush >= logFlushTime) { Game::logger->Flush(); framesSinceLastFlush = 0; } else framesSinceLastFlush++; //Every 10 min we ping our sql server to keep it alive hopefully: - if (framesSinceLastSQLPing >= 40000) { + if (framesSinceLastSQLPing >= sqlPingTime) { //Find out the master's IP for absolutely no reason: std::string masterIP; - int masterPort; + uint32_t masterPort; sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';"); auto res = stmt->executeQuery(); while (res->next()) { @@ -160,7 +165,7 @@ int main(int argc, char** argv) { } else framesSinceLastSQLPing++; //Sleep our thread since auth can afford to. - t += std::chrono::milliseconds(mediumFrameDelta); //Chat can run at a lower "fps" + t += std::chrono::milliseconds(chatFrameDelta); //Chat can run at a lower "fps" std::this_thread::sleep_until(t); } diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index ed94ff83..5bbe7a8c 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -52,8 +52,8 @@ namespace Game { } //namespace Game bool shutdownSequenceStarted = false; -void ShutdownSequence(int signal = -1); -int FinalizeShutdown(int signal = -1); +void ShutdownSequence(int32_t signal = -1); +int32_t FinalizeShutdown(int32_t signal = -1); dLogger* SetupLogger(); void StartAuthServer(); void StartChatServer(); @@ -75,8 +75,8 @@ int main(int argc, char** argv) { //Triggers the shutdown sequence at application exit std::atexit([]() { ShutdownSequence(); }); - signal(SIGINT, [](int signal) { ShutdownSequence(EXIT_FAILURE); }); - signal(SIGTERM, [](int signal) { ShutdownSequence(EXIT_FAILURE); }); + signal(SIGINT, [](int32_t signal) { ShutdownSequence(EXIT_FAILURE); }); + signal(SIGTERM, [](int32_t signal) { ShutdownSequence(EXIT_FAILURE); }); //Create all the objects we need to run our service: Game::logger = SetupLogger(); @@ -239,8 +239,8 @@ int main(int argc, char** argv) { return EXIT_SUCCESS; } - int maxClients = 999; - int ourPort = 1000; + uint32_t maxClients = 999; + uint32_t ourPort = 1000; if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients")); if (Game::config->GetValue("port") != "") ourPort = std::stoi(Game::config->GetValue("port")); @@ -293,9 +293,9 @@ int main(int argc, char** argv) { constexpr uint32_t sqlPingTime = 10 * 60 * masterFramerate; constexpr uint32_t shutdownUniverseTime = 10 * 60 * masterFramerate; constexpr uint32_t instanceReadyTimeout = 30 * masterFramerate; - int framesSinceLastFlush = 0; - int framesSinceLastSQLPing = 0; - int framesSinceKillUniverseCommand = 0; + uint32_t framesSinceLastFlush = 0; + uint32_t framesSinceLastSQLPing = 0; + uint32_t framesSinceKillUniverseCommand = 0; while (true) { //In world we'd update our other systems here. @@ -319,7 +319,7 @@ int main(int argc, char** argv) { if (framesSinceLastSQLPing >= sqlPingTime) { //Find out the master's IP for absolutely no reason: std::string masterIP; - int masterPort; + uint32_t masterPort; sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';"); auto res = stmt->executeQuery(); while (res->next()) { @@ -652,7 +652,7 @@ void HandlePacket(Packet* packet) { uint32_t len; inStream.Read<uint32_t>(len); - for (int i = 0; len > i; i++) { + for (uint32_t i = 0; len > i; i++) { char character; inStream.Read<char>(character); password += character; @@ -678,7 +678,7 @@ void HandlePacket(Packet* packet) { uint32_t len; inStream.Read<uint32_t>(len); - for (int i = 0; i < len; i++) { + for (uint32_t i = 0; i < len; i++) { char character; inStream.Read<char>(character); password += character; } @@ -726,7 +726,7 @@ void HandlePacket(Packet* packet) { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); - int zoneID; + int32_t zoneID; inStream.Read(zoneID); if (shutdownSequenceStarted) { Game::logger->Log("MasterServer", "Shutdown sequence has been started. Not prepping a new zone."); @@ -822,7 +822,7 @@ void StartAuthServer() { #endif } -void ShutdownSequence(int signal) { +void ShutdownSequence(int32_t signal) { if (shutdownSequenceStarted) { return; } @@ -905,7 +905,7 @@ void ShutdownSequence(int signal) { FinalizeShutdown(signal); } -int FinalizeShutdown(int signal) { +int32_t FinalizeShutdown(int32_t signal) { //Delete our objects here: Database::Destroy("MasterServer"); if (Game::config) delete Game::config; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index c531595f..c8826efe 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -81,7 +81,7 @@ void WorldShutdownProcess(uint32_t zoneId); void FinalizeShutdown(); void SendShutdownMessageToMaster(); -dLogger* SetupLogger(int zoneID, int instanceID); +dLogger* SetupLogger(uint32_t zoneID, uint32_t instanceID); void HandlePacketChat(Packet* packet); void HandlePacket(Packet* packet); @@ -91,8 +91,8 @@ struct tempSessionInfo { }; std::map<std::string, tempSessionInfo> m_PendingUsers; -int instanceID = 0; -int g_CloneID = 0; +uint32_t instanceID = 0; +uint32_t g_CloneID = 0; std::string databaseChecksum = ""; int main(int argc, char** argv) { @@ -106,13 +106,13 @@ int main(int argc, char** argv) { signal(SIGINT, [](int) { WorldShutdownSequence(); }); signal(SIGTERM, [](int) { WorldShutdownSequence(); }); - int zoneID = 1000; - int cloneID = 0; - int maxClients = 8; - int ourPort = 2007; + uint32_t zoneID = 1000; + uint32_t cloneID = 0; + uint32_t maxClients = 8; + uint32_t ourPort = 2007; //Check our arguments: - for (int i = 0; i < argc; ++i) { + for (int32_t i = 0; i < argc; ++i) { std::string argument(argv[i]); if (argument == "-zone") zoneID = atoi(argv[i + 1]); @@ -184,7 +184,7 @@ int main(int argc, char** argv) { //Find out the master's IP: std::string masterIP = "localhost"; - int masterPort = 1000; + uint32_t masterPort = 1000; sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';"); auto res = stmt->executeQuery(); while (res->next()) { @@ -203,7 +203,7 @@ int main(int argc, char** argv) { Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, Game::config, &Game::shouldShutdown, zoneID); //Connect to the chat server: - int chatPort = 1501; + uint32_t chatPort = 1501; if (Game::config->GetValue("chat_server_port") != "") chatPort = std::atoi(Game::config->GetValue("chat_server_port").c_str()); auto chatSock = SocketDescriptor(uint16_t(ourPort + 2), 0); @@ -219,22 +219,22 @@ int main(int argc, char** argv) { auto t = std::chrono::high_resolution_clock::now(); Packet* packet = nullptr; - int framesSinceLastFlush = 0; - int framesSinceMasterDisconnect = 0; - int framesSinceChatDisconnect = 0; - int framesSinceLastUsersSave = 0; - int framesSinceLastSQLPing = 0; - int framesSinceLastUser = 0; + uint32_t framesSinceLastFlush = 0; + uint32_t framesSinceMasterDisconnect = 0; + uint32_t framesSinceChatDisconnect = 0; + uint32_t framesSinceLastUsersSave = 0; + uint32_t framesSinceLastSQLPing = 0; + uint32_t framesSinceLastUser = 0; const float maxPacketProcessingTime = 1.5f; //0.015f; - const int maxPacketsToProcess = 1024; + const uint32_t maxPacketsToProcess = 1024; bool ready = false; - int framesSinceMasterStatus = 0; - int framesSinceShutdownSequence = 0; - int currentFramerate = highFrameDelta; + uint32_t framesSinceMasterStatus = 0; + uint32_t framesSinceShutdownSequence = 0; + uint32_t currentFramerate = highFrameDelta; - int ghostingStepCount = 0; + uint32_t ghostingStepCount = 0; auto ghostingLastTime = std::chrono::high_resolution_clock::now(); PerformanceManager::SelectProfile(zoneID); @@ -263,7 +263,7 @@ int main(int argc, char** argv) { } } - const int bufferSize = 1024; + const int32_t bufferSize = 1024; MD5* md5 = new MD5(); char fileStreamBuffer[1024] = {}; @@ -314,7 +314,7 @@ int main(int argc, char** argv) { if (!Game::server->GetIsConnectedToMaster()) { framesSinceMasterDisconnect++; - int framesToWaitForMaster = ready ? 10 : 200; + uint32_t framesToWaitForMaster = ready ? 10 : 200; if (framesSinceMasterDisconnect >= framesToWaitForMaster && !Game::shouldShutdown) { Game::logger->Log("WorldServer", "Game loop running but no connection to master for %d frames, shutting down", framesToWaitForMaster); Game::shouldShutdown = true; @@ -378,7 +378,7 @@ int main(int argc, char** argv) { UserManager::Instance()->DeletePendingRemovals(); auto t1 = std::chrono::high_resolution_clock::now(); - for (int curPacket = 0; curPacket < maxPacketsToProcess && timeSpent < maxPacketProcessingTime; curPacket++) { + for (uint32_t curPacket = 0; curPacket < maxPacketsToProcess && timeSpent < maxPacketProcessingTime; curPacket++) { packet = Game::server->Receive(); if (packet) { auto t1 = std::chrono::high_resolution_clock::now(); @@ -433,7 +433,7 @@ int main(int argc, char** argv) { if (framesSinceLastSQLPing >= 40000) { //Find out the master's IP for absolutely no reason: std::string masterIP; - int masterPort; + uint32_t masterPort; sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';"); auto res = stmt->executeQuery(); while (res->next()) { @@ -482,7 +482,7 @@ int main(int argc, char** argv) { return EXIT_SUCCESS; } -dLogger* SetupLogger(int zoneID, int instanceID) { +dLogger* SetupLogger(uint32_t zoneID, uint32_t instanceID) { std::string logPath = (BinaryPathFinder::GetBinaryDir() / ("logs/WorldServer_" + std::to_string(zoneID) + "_" + std::to_string(instanceID) + "_" + std::to_string(time(nullptr)) + ".log")).string(); bool logToConsole = false; bool logDebugStatements = false; @@ -524,7 +524,7 @@ void HandlePacketChat(Packet* packet) { //Write our stream outwards: CBITSTREAM; - for (int i = 0; i < inStream.GetNumberOfBytesUsed(); i++) { + for (BitSize_t i = 0; i < inStream.GetNumberOfBytesUsed(); i++) { bitStream.Write(packet->data[i + 16]); //16 bytes == header + playerID to skip } @@ -543,7 +543,7 @@ void HandlePacketChat(Packet* packet) { uint32_t len; inStream.Read<uint32_t>(len); - for (int i = 0; len > i; i++) { + for (uint32_t i = 0; len > i; i++) { char character; inStream.Read<char>(character); title += character; @@ -551,7 +551,7 @@ void HandlePacketChat(Packet* packet) { len = 0; inStream.Read<uint32_t>(len); - for (int i = 0; len > i; i++) { + for (uint32_t i = 0; len > i; i++) { char character; inStream.Read<char>(character); msg += character; @@ -804,7 +804,7 @@ void HandlePacket(Packet* packet) { uint32_t len; inStream.Read(len); - for (int i = 0; i < len; i++) { + for (uint32_t i = 0; i < len; i++) { char character; inStream.Read<char>(character); username += character; } @@ -1027,7 +1027,7 @@ void HandlePacket(Packet* packet) { //Check for BBB models: auto stmt = Database::CreatePreppedStmt("SELECT ugc_id FROM properties_contents WHERE lot=14 AND property_id=?"); - int templateId = result.getIntField(0); + int32_t templateId = result.getIntField(0); result.finalize(); From 0d460c0eb30c31d7b3e2ff1c520400b9a43281ae Mon Sep 17 00:00:00 2001 From: David Markowitz <EmosewaMC@gmail.com> Date: Fri, 16 Dec 2022 03:46:38 -0800 Subject: [PATCH 176/322] Update WorldServer timings --- dCommon/dEnums/dCommonVars.h | 3 ++ dWorldServer/PerformanceManager.cpp | 6 ++-- dWorldServer/PerformanceManager.h | 4 +-- dWorldServer/WorldServer.cpp | 48 ++++++++++++++++++++--------- 4 files changed, 42 insertions(+), 19 deletions(-) diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index f3d02bf7..68339032 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -12,7 +12,10 @@ typedef int RESTICKET; +// These are the same define, but they mean two different things in different contexts +// so a different define to distinguish what calculation is happening will help clarity. #define FRAMES_TO_MS(x) 1000 / x +#define MS_TO_FRAMES(x) 1000 / x //=========== FRAME TIMINGS =========== constexpr uint32_t highFramerate = 60; diff --git a/dWorldServer/PerformanceManager.cpp b/dWorldServer/PerformanceManager.cpp index 66dcb615..19f38d00 100644 --- a/dWorldServer/PerformanceManager.cpp +++ b/dWorldServer/PerformanceManager.cpp @@ -79,10 +79,10 @@ void PerformanceManager::SelectProfile(LWOMAPID mapID) { m_CurrentProfile = pair->second; } -uint32_t PerformanceManager::GetServerFramerate() { +uint32_t PerformanceManager::GetServerFrameDelta() { if (UserManager::Instance()->GetUserCount() == 0) { - return m_InactiveProfile.serverFramerate; + return m_InactiveProfile.serverFrameDelta; } - return m_CurrentProfile.serverFramerate; + return m_CurrentProfile.serverFrameDelta; } diff --git a/dWorldServer/PerformanceManager.h b/dWorldServer/PerformanceManager.h index 3d8517eb..c584d4ac 100644 --- a/dWorldServer/PerformanceManager.h +++ b/dWorldServer/PerformanceManager.h @@ -5,14 +5,14 @@ #include "dCommonVars.h" struct PerformanceProfile { - uint32_t serverFramerate; + uint32_t serverFrameDelta; }; class PerformanceManager { public: static void SelectProfile(LWOMAPID mapID); - static uint32_t GetServerFramerate(); + static uint32_t GetServerFrameDelta(); private: static PerformanceProfile m_CurrentProfile; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index c8826efe..0ed994fe 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -232,7 +232,7 @@ int main(int argc, char** argv) { bool ready = false; uint32_t framesSinceMasterStatus = 0; uint32_t framesSinceShutdownSequence = 0; - uint32_t currentFramerate = highFrameDelta; + uint32_t currentFramerate = highFramerate; uint32_t ghostingStepCount = 0; auto ghostingLastTime = std::chrono::high_resolution_clock::now(); @@ -287,6 +287,14 @@ int main(int argc, char** argv) { } } + uint32_t currentFrameDelta = highFrameDelta; + // These values are adjust them selves to the current framerate should it update. + uint32_t logFlushTime = 15 * currentFramerate; // 15 seconds in frames + uint32_t shutdownTimeout = 10 * 60 * currentFramerate; // 10 minutes in frames + uint32_t noMasterConnectionTimeout = 5 * currentFramerate; // 5 seconds in frames + uint32_t chatReconnectionTime = 30 * currentFramerate; // 30 seconds in frames + uint32_t saveTime = 10 * 60 * currentFramerate; // 10 minutes in frames + uint32_t sqlPingTime = 10 * 60 * currentFramerate; // 10 minutes in frames while (true) { Metrics::StartMeasurement(MetricVariable::Frame); Metrics::StartMeasurement(MetricVariable::GameLoop); @@ -299,24 +307,37 @@ int main(int argc, char** argv) { const auto occupied = UserManager::Instance()->GetUserCount() != 0; + uint32_t newFrameDelta = currentFrameDelta; if (!ready) { - currentFramerate = highFrameDelta; + newFrameDelta = highFrameDelta; } else { - currentFramerate = PerformanceManager::GetServerFramerate(); + newFrameDelta = PerformanceManager::GetServerFrameDelta(); + } + + // Update to the new framerate + if (newFrameDelta != currentFrameDelta) { + currentFrameDelta = newFrameDelta; + currentFramerate = MS_TO_FRAMES(newFrameDelta); + Game::logger->LogDebug("WorldServer", "Framerate for zone/instance/clone %i/%i/%i is now %i", zoneID, instanceID, cloneID, currentFramerate); + logFlushTime = 15 * currentFramerate; // 15 seconds in frames + shutdownTimeout = 10 * 60 * currentFramerate; // 10 minutes in frames + noMasterConnectionTimeout = 5 * currentFramerate; // 5 seconds in frames + chatReconnectionTime = 30 * currentFramerate; // 30 seconds in frames + saveTime = 10 * 60 * currentFramerate; // 10 minutes in frames + sqlPingTime = 10 * 60 * currentFramerate; // 10 minutes in frames } //Warning if we ran slow - if (deltaTime > currentFramerate) { - Game::logger->Log("WorldServer", "We're running behind, dT: %f > %f (framerate)", deltaTime, currentFramerate); + if (deltaTime > currentFrameDelta) { + Game::logger->Log("WorldServer", "We're running behind, dT: %f > %f (framerate %i)", deltaTime, currentFrameDelta, currentFramerate); } //Check if we're still connected to master: if (!Game::server->GetIsConnectedToMaster()) { framesSinceMasterDisconnect++; - uint32_t framesToWaitForMaster = ready ? 10 : 200; - if (framesSinceMasterDisconnect >= framesToWaitForMaster && !Game::shouldShutdown) { - Game::logger->Log("WorldServer", "Game loop running but no connection to master for %d frames, shutting down", framesToWaitForMaster); + if (framesSinceMasterDisconnect >= noMasterConnectionTimeout && !Game::shouldShutdown) { + Game::logger->Log("WorldServer", "Game loop running but no connection to master for %d frames, shutting down", noMasterConnectionTimeout); Game::shouldShutdown = true; } } else framesSinceMasterDisconnect = 0; @@ -325,8 +346,7 @@ int main(int argc, char** argv) { if (!chatConnected) { framesSinceChatDisconnect++; - // Attempt to reconnect every 30 seconds. - if (framesSinceChatDisconnect >= 2000) { + if (framesSinceChatDisconnect >= chatReconnectionTime) { framesSinceChatDisconnect = 0; Game::chatServer->Connect(masterIP.c_str(), chatPort, "3.25 ND1", 8); @@ -403,7 +423,7 @@ int main(int argc, char** argv) { Metrics::EndMeasurement(MetricVariable::UpdateReplica); //Push our log every 15s: - if (framesSinceLastFlush >= 1000) { + if (framesSinceLastFlush >= logFlushTime) { Game::logger->Flush(); framesSinceLastFlush = 0; } else framesSinceLastFlush++; @@ -420,7 +440,7 @@ int main(int argc, char** argv) { } //Save all connected users every 10 minutes: - if (framesSinceLastUsersSave >= 40000 && zoneID != 0) { + if (framesSinceLastUsersSave >= saveTime && zoneID != 0) { UserManager::Instance()->SaveAllActiveCharacters(); framesSinceLastUsersSave = 0; @@ -430,7 +450,7 @@ int main(int argc, char** argv) { } else framesSinceLastUsersSave++; //Every 10 min we ping our sql server to keep it alive hopefully: - if (framesSinceLastSQLPing >= 40000) { + if (framesSinceLastSQLPing >= sqlPingTime) { //Find out the master's IP for absolutely no reason: std::string masterIP; uint32_t masterPort; @@ -451,7 +471,7 @@ int main(int argc, char** argv) { Metrics::StartMeasurement(MetricVariable::Sleep); - t += std::chrono::milliseconds(currentFramerate); + t += std::chrono::milliseconds(currentFrameDelta); std::this_thread::sleep_until(t); Metrics::EndMeasurement(MetricVariable::Sleep); From b33a3df012375a2ddd873f8d2f47bcbc5ba00e7e Mon Sep 17 00:00:00 2001 From: David Markowitz <EmosewaMC@gmail.com> Date: Fri, 16 Dec 2022 04:02:54 -0800 Subject: [PATCH 177/322] Scale timers --- dWorldServer/WorldServer.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 0ed994fe..37dce5cd 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -287,7 +287,7 @@ int main(int argc, char** argv) { } } - uint32_t currentFrameDelta = highFrameDelta; + uint32_t currentFrameDelta = highFrameDelta; // These values are adjust them selves to the current framerate should it update. uint32_t logFlushTime = 15 * currentFramerate; // 15 seconds in frames uint32_t shutdownTimeout = 10 * 60 * currentFramerate; // 10 minutes in frames @@ -314,17 +314,24 @@ int main(int argc, char** argv) { newFrameDelta = PerformanceManager::GetServerFrameDelta(); } - // Update to the new framerate + // Update to the new framerate and scale all timings to said new framerate if (newFrameDelta != currentFrameDelta) { + float_t ratioBeforeToAfter = (float)currentFrameDelta / (float)newFrameDelta; currentFrameDelta = newFrameDelta; currentFramerate = MS_TO_FRAMES(newFrameDelta); Game::logger->LogDebug("WorldServer", "Framerate for zone/instance/clone %i/%i/%i is now %i", zoneID, instanceID, cloneID, currentFramerate); logFlushTime = 15 * currentFramerate; // 15 seconds in frames + framesSinceLastFlush *= ratioBeforeToAfter; shutdownTimeout = 10 * 60 * currentFramerate; // 10 minutes in frames + framesSinceLastUser *= ratioBeforeToAfter; noMasterConnectionTimeout = 5 * currentFramerate; // 5 seconds in frames + framesSinceMasterDisconnect *= ratioBeforeToAfter; chatReconnectionTime = 30 * currentFramerate; // 30 seconds in frames + framesSinceChatDisconnect *= ratioBeforeToAfter; saveTime = 10 * 60 * currentFramerate; // 10 minutes in frames + framesSinceLastUsersSave *= ratioBeforeToAfter; sqlPingTime = 10 * 60 * currentFramerate; // 10 minutes in frames + framesSinceLastSQLPing *= ratioBeforeToAfter; } //Warning if we ran slow From a2ca2733702f2be1e8a0277c1f9ba64edc0c1b65 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 16 Dec 2022 13:23:02 -0800 Subject: [PATCH 178/322] Cleanup behavior bitstream reads (#888) * Add failArmor server side Address out of bounds reading in behavior Address the basicAttackBehavior reading out of bounds memory and reading bits that didnt exist, which occasionally caused crashes and also caused the behavior to do undefined behavior due to the bad reads. Tested that attacking a wall anywhere with a projectile now does not crash the game. Tested with logs that the behavior correctly returned when there were no allocated bits or returned when other states were met. Add back logs and add fail handle Remove comment block Revert "Add back logs and add fail handle" This reverts commit db19be0906fc8bf35bf89037e2bfba39f5ef9c0c. Split out checks * Cleanup Behavior streams --- dGame/dBehaviors/AirMovementBehavior.cpp | 27 +++++++++++++------ dGame/dBehaviors/AirMovementBehavior.h | 2 +- dGame/dBehaviors/AreaOfEffectBehavior.cpp | 16 ++++++++--- dGame/dBehaviors/AttackDelayBehavior.cpp | 7 +++-- dGame/dBehaviors/ChainBehavior.cpp | 15 +++++++---- dGame/dBehaviors/ChargeUpBehavior.cpp | 8 ++++-- dGame/dBehaviors/ForceMovementBehavior.cpp | 23 +++++++++++----- dGame/dBehaviors/InterruptBehavior.cpp | 15 ++++++++--- dGame/dBehaviors/KnockbackBehavior.cpp | 9 +++++-- dGame/dBehaviors/MovementSwitchBehavior.cpp | 9 ++++--- dGame/dBehaviors/ProjectileAttackBehavior.cpp | 21 ++++++++++----- dGame/dBehaviors/StunBehavior.cpp | 7 +++-- dGame/dBehaviors/SwitchBehavior.cpp | 5 +++- dGame/dBehaviors/SwitchMultipleBehavior.cpp | 12 +++++---- dGame/dBehaviors/TacArcBehavior.cpp | 18 +++++++++---- 15 files changed, 138 insertions(+), 56 deletions(-) diff --git a/dGame/dBehaviors/AirMovementBehavior.cpp b/dGame/dBehaviors/AirMovementBehavior.cpp index 469ac6e4..932297b9 100644 --- a/dGame/dBehaviors/AirMovementBehavior.cpp +++ b/dGame/dBehaviors/AirMovementBehavior.cpp @@ -2,11 +2,16 @@ #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "EntityManager.h" +#include "Game.h" +#include "dLogger.h" void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - uint32_t handle; + uint32_t handle{}; - bitStream->Read(handle); + if (!bitStream->Read(handle)) { + Game::logger->Log("AirMovementBehavior", "Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + } context->RegisterSyncBehavior(handle, this, branch); } @@ -17,14 +22,20 @@ void AirMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream->Write(handle); } -void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { - uint32_t behaviorId; +void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + uint32_t behaviorId{}; - bit_stream->Read(behaviorId); + if (!bitStream->Read(behaviorId)) { + Game::logger->Log("AirMovementBehavior", "Unable to read behaviorId from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits()); + return; + } - LWOOBJID target; + LWOOBJID target{}; - bit_stream->Read(target); + if (!bitStream->Read(target)) { + Game::logger->Log("AirMovementBehavior", "Unable to read target from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits()); + return; + } auto* behavior = CreateBehavior(behaviorId); @@ -32,7 +43,7 @@ void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bit_ branch.target = target; } - behavior->Handle(context, bit_stream, branch); + behavior->Handle(context, bitStream, branch); } void AirMovementBehavior::Load() { diff --git a/dGame/dBehaviors/AirMovementBehavior.h b/dGame/dBehaviors/AirMovementBehavior.h index 323edf37..89dc1e05 100644 --- a/dGame/dBehaviors/AirMovementBehavior.h +++ b/dGame/dBehaviors/AirMovementBehavior.h @@ -16,7 +16,7 @@ public: void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void Sync(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.cpp b/dGame/dBehaviors/AreaOfEffectBehavior.cpp index 898d1f99..ca3bdf93 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.cpp +++ b/dGame/dBehaviors/AreaOfEffectBehavior.cpp @@ -9,11 +9,16 @@ #include "BehaviorContext.h" #include "RebuildComponent.h" #include "DestroyableComponent.h" +#include "Game.h" +#include "dLogger.h" void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - uint32_t targetCount; + uint32_t targetCount{}; - bitStream->Read(targetCount); + if (!bitStream->Read(targetCount)) { + Game::logger->Log("AreaOfEffectBehavior", "Unable to read targetCount from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + } if (targetCount > this->m_maxTargets) { return; @@ -24,9 +29,12 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b targets.reserve(targetCount); for (auto i = 0u; i < targetCount; ++i) { - LWOOBJID target; + LWOOBJID target{}; - bitStream->Read(target); + if (!bitStream->Read(target)) { + Game::logger->Log("AreaOfEffectBehavior", "failed to read in target %i from bitStream, aborting target Handle!", i); + return; + }; targets.push_back(target); } diff --git a/dGame/dBehaviors/AttackDelayBehavior.cpp b/dGame/dBehaviors/AttackDelayBehavior.cpp index 450741ec..201921a3 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.cpp +++ b/dGame/dBehaviors/AttackDelayBehavior.cpp @@ -5,9 +5,12 @@ #include "dLogger.h" void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { - uint32_t handle; + uint32_t handle{}; - bitStream->Read(handle); + if (!bitStream->Read(handle)) { + Game::logger->Log("AttackDelayBehavior", "Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + }; for (auto i = 0u; i < this->m_numIntervals; ++i) { context->RegisterSyncBehavior(handle, this, branch); diff --git a/dGame/dBehaviors/ChainBehavior.cpp b/dGame/dBehaviors/ChainBehavior.cpp index 3ef8c15b..ec0f8969 100644 --- a/dGame/dBehaviors/ChainBehavior.cpp +++ b/dGame/dBehaviors/ChainBehavior.cpp @@ -4,14 +4,19 @@ #include "dLogger.h" void ChainBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { - uint32_t chain_index; + uint32_t chainIndex{}; - bitStream->Read(chain_index); + if (!bitStream->Read(chainIndex)) { + Game::logger->Log("ChainBehavior", "Unable to read chainIndex from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + } - chain_index--; + chainIndex--; - if (chain_index < this->m_behaviors.size()) { - this->m_behaviors.at(chain_index)->Handle(context, bitStream, branch); + if (chainIndex < this->m_behaviors.size()) { + this->m_behaviors.at(chainIndex)->Handle(context, bitStream, branch); + } else { + Game::logger->Log("ChainBehavior", "chainIndex out of bounds, aborting handle of chain %i bits unread %i", chainIndex, bitStream->GetNumberOfUnreadBits()); } } diff --git a/dGame/dBehaviors/ChargeUpBehavior.cpp b/dGame/dBehaviors/ChargeUpBehavior.cpp index fa9fa34b..1b9ba433 100644 --- a/dGame/dBehaviors/ChargeUpBehavior.cpp +++ b/dGame/dBehaviors/ChargeUpBehavior.cpp @@ -1,12 +1,16 @@ #include "ChargeUpBehavior.h" #include "BehaviorBranchContext.h" #include "BehaviorContext.h" +#include "Game.h" #include "dLogger.h" void ChargeUpBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { - uint32_t handle; + uint32_t handle{}; - bitStream->Read(handle); + if (!bitStream->Read(handle)) { + Game::logger->Log("ChargeUpBehavior", "Unable to read handle from bitStream, aborting Handle! variable_type"); + return; + }; context->RegisterSyncBehavior(handle, this, branch); } diff --git a/dGame/dBehaviors/ForceMovementBehavior.cpp b/dGame/dBehaviors/ForceMovementBehavior.cpp index e1ac6133..e095447c 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.cpp +++ b/dGame/dBehaviors/ForceMovementBehavior.cpp @@ -3,23 +3,34 @@ #include "BehaviorContext.h" #include "ControllablePhysicsComponent.h" #include "EntityManager.h" +#include "Game.h" +#include "dLogger.h" void ForceMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { if (this->m_hitAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitEnemyAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitFactionAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { return; } - uint32_t handle; - bitStream->Read(handle); + uint32_t handle{}; + if (!bitStream->Read(handle)) { + Game::logger->Log("ForceMovementBehavior", "Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + } context->RegisterSyncBehavior(handle, this, branch); } void ForceMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - uint32_t next; - bitStream->Read(next); + uint32_t next{}; + if (!bitStream->Read(next)) { + Game::logger->Log("ForceMovementBehavior", "Unable to read target from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits()); + return; + } - LWOOBJID target; - bitStream->Read(target); + LWOOBJID target{}; + if (!bitStream->Read(target)) { + Game::logger->Log("ForceMovementBehavior", "Unable to read target from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits()); + return; + } branch.target = target; auto* behavior = CreateBehavior(next); diff --git a/dGame/dBehaviors/InterruptBehavior.cpp b/dGame/dBehaviors/InterruptBehavior.cpp index b42eadb0..9035c092 100644 --- a/dGame/dBehaviors/InterruptBehavior.cpp +++ b/dGame/dBehaviors/InterruptBehavior.cpp @@ -11,7 +11,10 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS if (branch.target != context->originator) { bool unknown = false; - bitStream->Read(unknown); + if (!bitStream->Read(unknown)) { + Game::logger->Log("InterruptBehavior", "Unable to read unknown1 from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + }; if (unknown) return; } @@ -19,7 +22,10 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS if (!this->m_interruptBlock) { bool unknown = false; - bitStream->Read(unknown); + if (!bitStream->Read(unknown)) { + Game::logger->Log("InterruptBehavior", "Unable to read unknown2 from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + }; if (unknown) return; } @@ -28,7 +34,10 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS { bool unknown = false; - bitStream->Read(unknown); + if (!bitStream->Read(unknown)) { + Game::logger->Log("InterruptBehavior", "Unable to read unknown3 from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + }; } if (branch.target == context->originator) return; diff --git a/dGame/dBehaviors/KnockbackBehavior.cpp b/dGame/dBehaviors/KnockbackBehavior.cpp index 83c82010..1b878ed0 100644 --- a/dGame/dBehaviors/KnockbackBehavior.cpp +++ b/dGame/dBehaviors/KnockbackBehavior.cpp @@ -6,11 +6,16 @@ #include "EntityManager.h" #include "GameMessages.h" #include "DestroyableComponent.h" +#include "Game.h" +#include "dLogger.h" void KnockbackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - bool unknown; + bool unknown{}; - bitStream->Read(unknown); + if (!bitStream->Read(unknown)) { + Game::logger->Log("KnockbackBehavior", "Unable to read unknown from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + }; } void KnockbackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { diff --git a/dGame/dBehaviors/MovementSwitchBehavior.cpp b/dGame/dBehaviors/MovementSwitchBehavior.cpp index 17ed5c40..c893e6e1 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.cpp +++ b/dGame/dBehaviors/MovementSwitchBehavior.cpp @@ -13,9 +13,11 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* return; } - uint32_t movementType; - - bitStream->Read(movementType); + uint32_t movementType{}; + if (!bitStream->Read(movementType)) { + Game::logger->Log("MovementSwitchBehavior", "Unable to read movementType from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + }; switch (movementType) { case 1: @@ -55,4 +57,3 @@ void MovementSwitchBehavior::Load() { this->m_jumpAction = GetAction("jump_action"); } - diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.cpp b/dGame/dBehaviors/ProjectileAttackBehavior.cpp index 350234e2..c14f032d 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.cpp +++ b/dGame/dBehaviors/ProjectileAttackBehavior.cpp @@ -8,9 +8,12 @@ #include "../dWorldServer/ObjectIDManager.h" void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - LWOOBJID target; + LWOOBJID target{}; - bitStream->Read(target); + if (!bitStream->Read(target)) { + Game::logger->Log("ProjectileAttackBehavior", "Unable to read target from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + }; auto* entity = EntityManager::Instance()->GetEntity(context->originator); @@ -30,15 +33,21 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea if (m_useMouseposit) { NiPoint3 targetPosition = NiPoint3::ZERO; - bitStream->Read(targetPosition); + if (!bitStream->Read(targetPosition)) { + Game::logger->Log("ProjectileAttackBehavior", "Unable to read targetPosition from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + }; } auto* targetEntity = EntityManager::Instance()->GetEntity(target); for (auto i = 0u; i < this->m_projectileCount; ++i) { - LWOOBJID projectileId; + LWOOBJID projectileId{}; - bitStream->Read(projectileId); + if (!bitStream->Read(projectileId)) { + Game::logger->Log("ProjectileAttackBehavior", "Unable to read projectileId from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + }; branch.target = target; branch.isProjectile = true; @@ -98,7 +107,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt for (auto i = 0u; i < this->m_projectileCount; ++i) { auto id = static_cast<LWOOBJID>(ObjectIDManager::Instance()->GenerateObjectID()); - id = GeneralUtils::SetBit(id, OBJECT_BIT_CLIENT); + id = GeneralUtils::SetBit(id, OBJECT_BIT_SPAWNED); bitStream->Write(id); diff --git a/dGame/dBehaviors/StunBehavior.cpp b/dGame/dBehaviors/StunBehavior.cpp index 59a81440..065b7220 100644 --- a/dGame/dBehaviors/StunBehavior.cpp +++ b/dGame/dBehaviors/StunBehavior.cpp @@ -14,8 +14,11 @@ void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream return; } - bool blocked; - bitStream->Read(blocked); + bool blocked{}; + if (!bitStream->Read(blocked)) { + Game::logger->Log("StunBehavior", "Unable to read blocked from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + }; auto* target = EntityManager::Instance()->GetEntity(branch.target); diff --git a/dGame/dBehaviors/SwitchBehavior.cpp b/dGame/dBehaviors/SwitchBehavior.cpp index 78271b99..f6eb3ff5 100644 --- a/dGame/dBehaviors/SwitchBehavior.cpp +++ b/dGame/dBehaviors/SwitchBehavior.cpp @@ -10,7 +10,10 @@ void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre auto state = true; if (this->m_imagination > 0 || !this->m_isEnemyFaction) { - bitStream->Read(state); + if (!bitStream->Read(state)) { + Game::logger->Log("SwitchBehavior", "Unable to read state from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; + }; } auto* entity = EntityManager::Instance()->GetEntity(context->originator); diff --git a/dGame/dBehaviors/SwitchMultipleBehavior.cpp b/dGame/dBehaviors/SwitchMultipleBehavior.cpp index 946e5e0f..e92393fc 100644 --- a/dGame/dBehaviors/SwitchMultipleBehavior.cpp +++ b/dGame/dBehaviors/SwitchMultipleBehavior.cpp @@ -9,10 +9,12 @@ #include "EntityManager.h" -void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { - float value; +void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + float value{}; - bit_stream->Read(value); + if (!bitStream->Read(value)) { + Game::logger->Log("SwitchMultipleBehavior", "Unable to read value from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + }; uint32_t trigger = 0; @@ -30,10 +32,10 @@ void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* auto* behavior = this->m_behaviors.at(trigger).second; - behavior->Handle(context, bit_stream, branch); + behavior->Handle(context, bitStream, branch); } -void SwitchMultipleBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { +void SwitchMultipleBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { // TODO } diff --git a/dGame/dBehaviors/TacArcBehavior.cpp b/dGame/dBehaviors/TacArcBehavior.cpp index 8789f9b6..38efdea4 100644 --- a/dGame/dBehaviors/TacArcBehavior.cpp +++ b/dGame/dBehaviors/TacArcBehavior.cpp @@ -20,12 +20,16 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre bool hit = false; - bitStream->Read(hit); + if (!bitStream->Read(hit)) { + Game::logger->Log("TacArcBehavior", "Unable to read hit from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + }; if (this->m_checkEnv) { bool blocked = false; - bitStream->Read(blocked); + if (!bitStream->Read(blocked)) { + Game::logger->Log("TacArcBehavior", "Unable to read blocked from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + }; if (blocked) { this->m_blockedAction->Handle(context, bitStream, branch); @@ -37,7 +41,9 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre if (hit) { uint32_t count = 0; - bitStream->Read(count); + if (!bitStream->Read(count)) { + Game::logger->Log("TacArcBehavior", "Unable to read count from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + }; if (count > m_maxTargets && m_maxTargets > 0) { count = m_maxTargets; @@ -46,9 +52,11 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre std::vector<LWOOBJID> targets; for (auto i = 0u; i < count; ++i) { - LWOOBJID id; + LWOOBJID id{}; - bitStream->Read(id); + if (!bitStream->Read(id)) { + Game::logger->Log("TacArcBehavior", "Unable to read id from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + }; targets.push_back(id); } From cd78a3dec72ac2e4c427ef21c9fbcb452fc02fe5 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 16 Dec 2022 13:23:09 -0800 Subject: [PATCH 179/322] Fix cannon super charge speed (#883) * Fix cannon * Update SGCannon.cpp --- dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp index 049837a4..912b9f58 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp @@ -722,7 +722,7 @@ void SGCannon::ToggleSuperCharge(Entity* self, bool enable) { Game::logger->Log("SGCannon", "Player has %d equipped items", equippedItems.size()); auto skillID = constants.cannonSkill; - auto coolDown = constants.cannonRefireRate; + auto cooldown = constants.cannonRefireRate; auto* selfInventoryComponent = self->GetComponent<InventoryComponent>(); @@ -738,7 +738,7 @@ void SGCannon::ToggleSuperCharge(Entity* self, bool enable) { // TODO: Equip items skillID = constants.cannonSuperChargeSkill; - coolDown = 400; + cooldown = 400; } else { selfInventoryComponent->UpdateSlot("greeble_r", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); selfInventoryComponent->UpdateSlot("greeble_l", { ObjectIDManager::GenerateRandomObjectID(), 0, 0, 0 }); @@ -761,7 +761,7 @@ void SGCannon::ToggleSuperCharge(Entity* self, bool enable) { } } } - + cooldown = 800; self->SetVar<uint32_t>(NumberOfChargesVariable, 0); } @@ -777,7 +777,7 @@ void SGCannon::ToggleSuperCharge(Entity* self, bool enable) { properties.cannonFOV = 58.6f; properties.cannonVelocity = 129.0; - properties.cannonRefireRate = 800; + properties.cannonRefireRate = cooldown; properties.cannonMinDistance = 30; properties.cannonTimeout = -1; From 32f8bda53866996de7ece9cb591e2b82d1fb7e9c Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 16 Dec 2022 15:23:38 -0600 Subject: [PATCH 180/322] Allow the player to be interrupted (#881) --- dGame/dComponents/SkillComponent.cpp | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index c749dbaf..445a837e 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -181,17 +181,11 @@ void SkillComponent::Reset() { } void SkillComponent::Interrupt() { - if (m_Parent->IsPlayer()) return; - + // TODO: need to check immunities on the destroyable component, but they aren't implemented auto* combat = m_Parent->GetComponent<BaseCombatAIComponent>(); + if (combat != nullptr && combat->GetStunImmune()) return; - if (combat != nullptr && combat->GetStunImmune()) { - return; - } - - for (const auto& behavior : this->m_managedBehaviors) { - behavior.second->Interrupt(); - } + for (const auto& behavior : this->m_managedBehaviors) behavior.second->Interrupt(); } void SkillComponent::RegisterCalculatedProjectile(const LWOOBJID projectileId, BehaviorContext* context, const BehaviorBranchContext& branch, const LOT lot, const float maxTime, From 631365b7f70fe138fe39a390d5fac2134ffcca5e Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 16 Dec 2022 15:24:13 -0600 Subject: [PATCH 181/322] Add change idle flags behavior and GM (#871) * update naming for animation flag enum value 0 * Add change idle flags behaviors and GM * default to 0 when none is given --- dCommon/dEnums/dMessageIdentifiers.h | 1 + dCommon/dEnums/eAninmationFlags.h | 2 +- dGame/dBehaviors/Behavior.cpp | 5 ++- dGame/dBehaviors/CMakeLists.txt | 1 + dGame/dBehaviors/ChangeIdleFlagsBehavior.cpp | 37 ++++++++++++++++++++ dGame/dBehaviors/ChangeIdleFlagsBehavior.h | 23 ++++++++++++ dGame/dBehaviors/SwitchBehavior.cpp | 2 +- dGame/dComponents/PossessableComponent.cpp | 4 +-- dGame/dComponents/PossessableComponent.h | 2 +- dGame/dGameMessages/GameMessages.cpp | 12 +++++++ dGame/dGameMessages/GameMessages.h | 10 ++++++ 11 files changed, 93 insertions(+), 6 deletions(-) create mode 100644 dGame/dBehaviors/ChangeIdleFlagsBehavior.cpp create mode 100644 dGame/dBehaviors/ChangeIdleFlagsBehavior.h diff --git a/dCommon/dEnums/dMessageIdentifiers.h b/dCommon/dEnums/dMessageIdentifiers.h index 5a5c9088..129585a0 100644 --- a/dCommon/dEnums/dMessageIdentifiers.h +++ b/dCommon/dEnums/dMessageIdentifiers.h @@ -488,6 +488,7 @@ enum GAME_MSG : unsigned short { GAME_MSG_MATCH_UPDATE = 1310, GAME_MSG_MODULE_ASSEMBLY_DB_DATA_FOR_CLIENT = 1131, GAME_MSG_MODULE_ASSEMBLY_QUERY_DATA = 1132, + GAME_MSG_CHANGE_IDLE_FLAGS = 1338, GAME_MSG_VEHICLE_ADD_PASSIVE_BOOST_ACTION = 1340, GAME_MSG_VEHICLE_REMOVE_PASSIVE_BOOST_ACTION = 1341, GAME_MSG_VEHICLE_NOTIFY_SERVER_ADD_PASSIVE_BOOST_ACTION = 1342, diff --git a/dCommon/dEnums/eAninmationFlags.h b/dCommon/dEnums/eAninmationFlags.h index 9b2ea3fb..ce235ae9 100644 --- a/dCommon/dEnums/eAninmationFlags.h +++ b/dCommon/dEnums/eAninmationFlags.h @@ -6,7 +6,7 @@ #include <cstdint> enum class eAnimationFlags : uint32_t { - IDLE_INVALID = 0, // made up, for internal use!!! + IDLE_NONE = 0, IDLE_BASIC, IDLE_SWIM, IDLE_CARRY, diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index d0d6192b..cd9304d3 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -60,6 +60,7 @@ #include "SpeedBehavior.h" #include "DamageReductionBehavior.h" #include "JetPackBehavior.h" +#include "ChangeIdleFlagsBehavior.h" //CDClient includes #include "CDBehaviorParameterTable.h" @@ -196,7 +197,9 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) { behavior = new SkillCastFailedBehavior(behaviorId); break; case BehaviorTemplates::BEHAVIOR_IMITATION_SKUNK_STINK: break; - case BehaviorTemplates::BEHAVIOR_CHANGE_IDLE_FLAGS: break; + case BehaviorTemplates::BEHAVIOR_CHANGE_IDLE_FLAGS: + behavior = new ChangeIdleFlagsBehavior(behaviorId); + break; case BehaviorTemplates::BEHAVIOR_APPLY_BUFF: behavior = new ApplyBuffBehavior(behaviorId); break; diff --git a/dGame/dBehaviors/CMakeLists.txt b/dGame/dBehaviors/CMakeLists.txt index 297c389b..40ac0a9c 100644 --- a/dGame/dBehaviors/CMakeLists.txt +++ b/dGame/dBehaviors/CMakeLists.txt @@ -12,6 +12,7 @@ set(DGAME_DBEHAVIORS_SOURCES "AirMovementBehavior.cpp" "BuffBehavior.cpp" "CarBoostBehavior.cpp" "ChainBehavior.cpp" + "ChangeIdleFlagsBehavior.cpp" "ChangeOrientationBehavior.cpp" "ChargeUpBehavior.cpp" "ClearTargetBehavior.cpp" diff --git a/dGame/dBehaviors/ChangeIdleFlagsBehavior.cpp b/dGame/dBehaviors/ChangeIdleFlagsBehavior.cpp new file mode 100644 index 00000000..06a79fa7 --- /dev/null +++ b/dGame/dBehaviors/ChangeIdleFlagsBehavior.cpp @@ -0,0 +1,37 @@ + +#include "ChangeIdleFlagsBehavior.h" +#include "BehaviorContext.h" +#include "BehaviorBranchContext.h" + +void ChangeIdleFlagsBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator; + if (!target) return; + + GameMessages::SendChangeIdleFlags(target, m_FlagsOn, m_FlagsOff, UNASSIGNED_SYSTEM_ADDRESS); + + if (branch.duration > 0.0f) { + context->RegisterTimerBehavior(this, branch); + } else if (branch.start > 0) { + context->RegisterEndBehavior(this, branch); + } +} + +void ChangeIdleFlagsBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + Handle(context, bitStream, branch); +} + +void ChangeIdleFlagsBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { + const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator; + if (!target) return; + // flip on and off to end behavior + GameMessages::SendChangeIdleFlags(target, m_FlagsOff, m_FlagsOn, UNASSIGNED_SYSTEM_ADDRESS); +} + +void ChangeIdleFlagsBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { + End(context, branch, second); +} + +void ChangeIdleFlagsBehavior::Load() { + m_FlagsOff = static_cast<eAnimationFlags>(GetInt("flags_off", 0)); + m_FlagsOn = static_cast<eAnimationFlags>(GetInt("flags_on", 0)); +} diff --git a/dGame/dBehaviors/ChangeIdleFlagsBehavior.h b/dGame/dBehaviors/ChangeIdleFlagsBehavior.h new file mode 100644 index 00000000..91f802f4 --- /dev/null +++ b/dGame/dBehaviors/ChangeIdleFlagsBehavior.h @@ -0,0 +1,23 @@ + +#pragma once +#include "Behavior.h" +#include "eAninmationFlags.h" + +class ChangeIdleFlagsBehavior final : public Behavior { +public: + + /* + * Inherited + */ + explicit ChangeIdleFlagsBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} + + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; + void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; + void Load() override; + +private: + eAnimationFlags m_FlagsOff; + eAnimationFlags m_FlagsOn; +}; diff --git a/dGame/dBehaviors/SwitchBehavior.cpp b/dGame/dBehaviors/SwitchBehavior.cpp index f6eb3ff5..c010f31b 100644 --- a/dGame/dBehaviors/SwitchBehavior.cpp +++ b/dGame/dBehaviors/SwitchBehavior.cpp @@ -28,7 +28,7 @@ void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre return; } - Game::logger->Log("SwitchBehavior", "[%i] State: (%d), imagination: (%i) / (%f)", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination()); + Game::logger->LogDebug("SwitchBehavior", "[%i] State: (%d), imagination: (%i) / (%f)", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination()); if (state || (entity->GetLOT() == 8092 && destroyableComponent->GetImagination() >= m_imagination)) { this->m_actionTrue->Handle(context, bitStream, branch); diff --git a/dGame/dComponents/PossessableComponent.cpp b/dGame/dComponents/PossessableComponent.cpp index 37591532..5c45a6c1 100644 --- a/dGame/dComponents/PossessableComponent.cpp +++ b/dGame/dComponents/PossessableComponent.cpp @@ -34,8 +34,8 @@ void PossessableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIn outBitStream->Write(m_Possessor != LWOOBJID_EMPTY); if (m_Possessor != LWOOBJID_EMPTY) outBitStream->Write(m_Possessor); - outBitStream->Write(m_AnimationFlag != eAnimationFlags::IDLE_INVALID); - if (m_AnimationFlag != eAnimationFlags::IDLE_INVALID) outBitStream->Write(m_AnimationFlag); + outBitStream->Write(m_AnimationFlag != eAnimationFlags::IDLE_NONE); + if (m_AnimationFlag != eAnimationFlags::IDLE_NONE) outBitStream->Write(m_AnimationFlag); outBitStream->Write(m_ImmediatelyDepossess); m_ImmediatelyDepossess = false; // reset flag diff --git a/dGame/dComponents/PossessableComponent.h b/dGame/dComponents/PossessableComponent.h index 43ce8610..e1dc5ccd 100644 --- a/dGame/dComponents/PossessableComponent.h +++ b/dGame/dComponents/PossessableComponent.h @@ -109,7 +109,7 @@ private: * @brief What animaiton flag to use * */ - eAnimationFlags m_AnimationFlag = eAnimationFlags::IDLE_INVALID; + eAnimationFlags m_AnimationFlag = eAnimationFlags::IDLE_NONE; /** * @brief Should this be immediately depossessed diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index fcc25fdc..8c82f644 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -3922,6 +3922,18 @@ void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string SEND_PACKET; } + +void GameMessages::SendChangeIdleFlags(LWOOBJID objectId, eAnimationFlags FlagsOn, eAnimationFlags FlagsOff, const SystemAddress& sysAddr) { + CBITSTREAM; + CMSGHEADER; + + bitStream.Write(objectId); + bitStream.Write(GAME_MSG::GAME_MSG_CHANGE_IDLE_FLAGS); + bitStream.Write(FlagsOff); + bitStream.Write(FlagsOn); + + SEND_PACKET_BROADCAST; +} // Mounts void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objectID, const SystemAddress& sysAddr) { diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index f9968d14..4f92480f 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -14,6 +14,7 @@ #include "TradingManager.h" #include "LeaderboardManager.h" #include "MovingPlatformComponent.h" +#include "eAninmationFlags.h" class NiQuaternion; class User; @@ -373,6 +374,15 @@ namespace GameMessages { void SendDisplayChatBubble(LWOOBJID objectId, const std::u16string& text, const SystemAddress& sysAddr); + /** + * @brief + * + * @param objectId ID of the entity to set idle flags + * @param FlagsOn Flag to turn on + * @param FlagsOff Flag to turn off + */ + void SendChangeIdleFlags(LWOOBJID objectId, eAnimationFlags FlagsOn, eAnimationFlags FlagsOff, const SystemAddress& sysAddr); + // Mounts /** * @brief Set the Inventory LWOOBJID of the mount From 1da2db9db60379e23d36f0971cd08392bbdea542 Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Sat, 17 Dec 2022 16:03:18 +0000 Subject: [PATCH 182/322] Resolve some string related issues for Windows Debug --- dGame/dComponents/PropertyManagementComponent.cpp | 2 +- dGame/dUtilities/Mail.cpp | 6 +++--- dMasterServer/MasterServer.cpp | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index eaade8be..648edff8 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -717,7 +717,7 @@ void PropertyManagementComponent::Save() { insertion->setDouble(9, rotation.y); insertion->setDouble(10, rotation.z); insertion->setDouble(11, rotation.w); - insertion->setString(12, "Objects_" + std::to_string(entity->GetLOT()) + "_name"); // Model name. TODO make this customizable + insertion->setString(12, ("Objects_" + std::to_string(entity->GetLOT()) + "_name").c_str()); // Model name. TODO make this customizable insertion->setString(13, ""); // Model description. TODO implement this. insertion->setDouble(14, 0); // behavior 1. TODO implement this. insertion->setDouble(15, 0); // behavior 2. TODO implement this. diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index 8280b627..7047972f 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -74,12 +74,12 @@ void Mail::SendMail(const LWOOBJID sender, const std::string& senderName, LWOOBJ auto* ins = Database::CreatePreppedStmt("INSERT INTO `mail`(`sender_id`, `sender_name`, `receiver_id`, `receiver_name`, `time_sent`, `subject`, `body`, `attachment_id`, `attachment_lot`, `attachment_subkey`, `attachment_count`, `was_read`) VALUES (?,?,?,?,?,?,?,?,?,?,?,0)"); ins->setUInt(1, sender); - ins->setString(2, senderName); + ins->setString(2, senderName.c_str()); ins->setUInt(3, recipient); ins->setString(4, recipientName.c_str()); ins->setUInt64(5, time(nullptr)); - ins->setString(6, subject); - ins->setString(7, body); + ins->setString(6, subject.c_str()); + ins->setString(7, body.c_str()); ins->setUInt(8, 0); ins->setInt(9, attachment); ins->setInt(10, 0); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 4c18566e..3d55f046 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -220,7 +220,7 @@ int main(int argc, char** argv) { //Create account auto* statement = Database::CreatePreppedStmt("INSERT INTO accounts (name, password, ""gm_level) VALUES (?, ?, ?);"); - statement->setString(1, username); + statement->setString(1, username.c_str()); statement->setString(2, std::string(hash, BCRYPT_HASHSIZE).c_str()); statement->setInt(3, 9); From e1bcde628faa0944f0dab60a9aa46b0c62f3175e Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 17 Dec 2022 20:54:41 -0800 Subject: [PATCH 183/322] Implement lower cap datagram size (#890) --- dNet/dServer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dNet/dServer.cpp b/dNet/dServer.cpp index 481667b8..96bb5bc8 100644 --- a/dNet/dServer.cpp +++ b/dNet/dServer.cpp @@ -67,7 +67,7 @@ dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnect } else { mLogger->Log("dServer", "FAILED TO START SERVER ON IP/PORT: %s:%i", ip.c_str(), port); return; } mLogger->SetLogToConsole(prevLogSetting); - + mPeer->SetMTUSize(1228); // This is hard coded by lu for some reason. //Connect to master if we are not master: if (serverType != ServerType::Master) { SetupForMasterConnection(); From b972acbacc773f221094d61c28d5f2c385913d20 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 18 Dec 2022 06:49:13 -0800 Subject: [PATCH 184/322] Fix stream reads (#894) No changes expected --- dGame/dBehaviors/SwitchMultipleBehavior.cpp | 1 + dGame/dBehaviors/TacArcBehavior.cpp | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/dGame/dBehaviors/SwitchMultipleBehavior.cpp b/dGame/dBehaviors/SwitchMultipleBehavior.cpp index e92393fc..078464bb 100644 --- a/dGame/dBehaviors/SwitchMultipleBehavior.cpp +++ b/dGame/dBehaviors/SwitchMultipleBehavior.cpp @@ -14,6 +14,7 @@ void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* if (!bitStream->Read(value)) { Game::logger->Log("SwitchMultipleBehavior", "Unable to read value from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; }; uint32_t trigger = 0; diff --git a/dGame/dBehaviors/TacArcBehavior.cpp b/dGame/dBehaviors/TacArcBehavior.cpp index 38efdea4..91df3879 100644 --- a/dGame/dBehaviors/TacArcBehavior.cpp +++ b/dGame/dBehaviors/TacArcBehavior.cpp @@ -22,6 +22,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre if (!bitStream->Read(hit)) { Game::logger->Log("TacArcBehavior", "Unable to read hit from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; }; if (this->m_checkEnv) { @@ -29,6 +30,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre if (!bitStream->Read(blocked)) { Game::logger->Log("TacArcBehavior", "Unable to read blocked from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; }; if (blocked) { @@ -43,6 +45,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre if (!bitStream->Read(count)) { Game::logger->Log("TacArcBehavior", "Unable to read count from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; }; if (count > m_maxTargets && m_maxTargets > 0) { @@ -56,6 +59,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre if (!bitStream->Read(id)) { Game::logger->Log("TacArcBehavior", "Unable to read id from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + return; }; targets.push_back(id); From 84c5d74450fca63a8da9aa68de9cd1682f1b7be7 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 18 Dec 2022 07:46:04 -0800 Subject: [PATCH 185/322] Add Delete Inventory Slash Command (#865) * moving branch * Add deleteinven slash command * Change name of BRICKS_IN_BBB * Use string_view instead of strcmp * Remove GameConfig * Revert "Remove GameConfig" This reverts commit cef5cdeea2282e3fc09a118dbecb0009d851b95f. --- dCommon/GeneralUtils.h | 7 +++ dCommon/dEnums/dCommonVars.h | 20 ------- dCommon/dEnums/eInventoryType.h | 59 +++++++++++++++++++ dGame/Character.cpp | 1 + dGame/LeaderboardManager.cpp | 1 + dGame/UserManager.cpp | 1 + dGame/dBehaviors/OverTimeBehavior.cpp | 2 + dGame/dComponents/BuffComponent.cpp | 1 + dGame/dComponents/DestroyableComponent.cpp | 1 + dGame/dComponents/InventoryComponent.h | 1 + dGame/dComponents/MovementAIComponent.cpp | 1 + .../PropertyManagementComponent.cpp | 1 + .../dComponents/ScriptedActivityComponent.cpp | 1 + dGame/dGameMessages/GameMessages.cpp | 1 + dGame/dGameMessages/GameMessages.h | 3 +- dGame/dInventory/Inventory.cpp | 9 ++- dGame/dInventory/Inventory.h | 6 ++ dGame/dInventory/Item.cpp | 4 +- dGame/dInventory/Item.h | 1 + dGame/dMission/Mission.cpp | 3 +- dGame/dMission/MissionTask.cpp | 2 +- dGame/dUtilities/SlashCommandHandler.cpp | 27 +++++++++ .../02_server/Map/General/QbEnemyStunner.cpp | 1 + .../FireFirstSkillonStartup.cpp | 1 + .../ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp | 1 + dScripts/ai/NS/NsConcertInstrument.cpp | 1 + 26 files changed, 130 insertions(+), 27 deletions(-) create mode 100644 dCommon/dEnums/eInventoryType.h diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index af7c7012..d43ad9b1 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -14,6 +14,8 @@ #include "Game.h" #include "dLogger.h" +enum eInventoryType : uint32_t; + /*! \file GeneralUtils.hpp \brief A namespace containing general utility functions @@ -174,6 +176,11 @@ namespace GeneralUtils { return std::stoull(value); } + template <> + inline eInventoryType Parse(const char* value) { + return static_cast<eInventoryType>(std::stoul(value)); + } + template <typename T> bool TryParse(const char* value, T& dst) { try { diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index f64d496f..d13e8b94 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -427,26 +427,6 @@ enum class UseItemResponse : uint32_t { MountsNotAllowed }; -/** - * Represents the different types of inventories an entity may have - */ -enum eInventoryType : uint32_t { - ITEMS = 0, - VAULT_ITEMS, - BRICKS, - MODELS_IN_BBB, - TEMP_ITEMS = 4, - MODELS, - TEMP_MODELS, - BEHAVIORS, - PROPERTY_DEEDS, - VENDOR_BUYBACK = 11, - HIDDEN = 12, //Used for missional items - VAULT_MODELS = 14, - ITEM_SETS, //internal - INVALID // made up, for internal use!!! -}; - enum eRebuildState : uint32_t { REBUILD_OPEN, REBUILD_COMPLETED = 2, diff --git a/dCommon/dEnums/eInventoryType.h b/dCommon/dEnums/eInventoryType.h new file mode 100644 index 00000000..12573aa4 --- /dev/null +++ b/dCommon/dEnums/eInventoryType.h @@ -0,0 +1,59 @@ +#pragma once + +#ifndef __EINVENTORYTYPE__H__ +#define __EINVENTORYTYPE__H__ + +#include <cstdint> +static const uint8_t NUMBER_OF_INVENTORIES = 17; +/** + * Represents the different types of inventories an entity may have + */ +enum eInventoryType : uint32_t { + ITEMS = 0, + VAULT_ITEMS, + BRICKS, + MODELS_IN_BBB, + TEMP_ITEMS, + MODELS, + TEMP_MODELS, + BEHAVIORS, + PROPERTY_DEEDS, + BRICKS_IN_BBB, + VENDOR, + VENDOR_BUYBACK, + QUEST, //Used for mission items + DONATION, + VAULT_MODELS, + ITEM_SETS, //internal, technically this is BankBehaviors. + INVALID // made up, for internal use!!!, Technically this called the ALL inventory. +}; + +class InventoryType { +public: + static const char* InventoryTypeToString(eInventoryType inventory) { + const char* eInventoryTypeTable[NUMBER_OF_INVENTORIES] = { + "ITEMS", + "VAULT_ITEMS", + "BRICKS", + "MODELS_IN_BBB", + "TEMP_ITEMS", + "MODELS", + "TEMP_MODELS", + "BEHAVIORS", + "PROPERTY_DEEDS", + "BRICKS_IN_BBB", + "VENDOR", + "VENDOR_BUYBACK", + "QUEST", //Used for mission items + "DONATION", + "VAULT_MODELS", + "ITEM_SETS", //internal, technically this is BankBehaviors. + "INVALID" // made up, for internal use!!!, Technically this called the ALL inventory. + }; + + if (inventory > NUMBER_OF_INVENTORIES - 1) return nullptr; + return eInventoryTypeTable[inventory]; + }; +}; + +#endif //!__EINVENTORYTYPE__H__ diff --git a/dGame/Character.cpp b/dGame/Character.cpp index a9cffc65..67a0bf1b 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -15,6 +15,7 @@ #include "Zone.h" #include "ChatPackets.h" #include "Inventory.h" +#include "InventoryComponent.h" Character::Character(uint32_t id, User* parentUser) { //First load the name, etc: diff --git a/dGame/LeaderboardManager.cpp b/dGame/LeaderboardManager.cpp index b069e761..a0df940f 100644 --- a/dGame/LeaderboardManager.cpp +++ b/dGame/LeaderboardManager.cpp @@ -7,6 +7,7 @@ #include "GameMessages.h" #include "dLogger.h" #include "dConfig.h" +#include "CDClientManager.h" Leaderboard::Leaderboard(uint32_t gameID, uint32_t infoType, bool weekly, std::vector<LeaderboardEntry> entries, LWOOBJID relatedPlayer, LeaderboardType leaderboardType) { diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index 6779a42c..70e76016 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -21,6 +21,7 @@ #include "EntityManager.h" #include "SkillComponent.h" #include "AssetManager.h" +#include "CDClientDatabase.h" UserManager* UserManager::m_Address = nullptr; diff --git a/dGame/dBehaviors/OverTimeBehavior.cpp b/dGame/dBehaviors/OverTimeBehavior.cpp index 43ac9bc2..20dd89af 100644 --- a/dGame/dBehaviors/OverTimeBehavior.cpp +++ b/dGame/dBehaviors/OverTimeBehavior.cpp @@ -6,6 +6,8 @@ #include "EntityManager.h" #include "SkillComponent.h" #include "DestroyableComponent.h" +#include "CDClientDatabase.h" +#include "CDClientManager.h" void OverTimeBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto originator = context->originator; diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index af20fc00..d8d7428d 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -9,6 +9,7 @@ #include "SkillComponent.h" #include "ControllablePhysicsComponent.h" #include "EntityManager.h" +#include "CDClientManager.h" std::unordered_map<int32_t, std::vector<BuffParameter>> BuffComponent::m_Cache{}; diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 3cf206da..c899d9e8 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -28,6 +28,7 @@ #include "CharacterComponent.h" #include "PossessableComponent.h" #include "PossessorComponent.h" +#include "InventoryComponent.h" #include "dZoneManager.h" DestroyableComponent::DestroyableComponent(Entity* parent) : Component(parent) { diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index 394cb801..8ae35f6c 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -19,6 +19,7 @@ #include "ItemSetPassiveAbility.h" #include "ItemSetPassiveAbilityID.h" #include "PossessorComponent.h" +#include "eInventoryType.h" class Entity; class ItemSet; diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index ed6ed483..92397a55 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -9,6 +9,7 @@ #include "dpWorld.h" #include "EntityManager.h" #include "SimplePhysicsComponent.h" +#include "CDClientManager.h" std::map<LOT, float> MovementAIComponent::m_PhysicsSpeedCache = {}; diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index 648edff8..8d23c17e 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -17,6 +17,7 @@ #include "Player.h" #include "RocketLaunchpadControlComponent.h" #include "PropertyEntranceComponent.h" +#include "InventoryComponent.h" #include <vector> #include "CppScripts.h" diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index f6d50d66..da546910 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -16,6 +16,7 @@ #include "GeneralUtils.h" #include "dZoneManager.h" #include "dConfig.h" +#include "InventoryComponent.h" #include "DestroyableComponent.h" ScriptedActivityComponent::ScriptedActivityComponent(Entity* parent, int activityID) : Component(parent) { diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 8c82f644..9aa8eda2 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -49,6 +49,7 @@ #include "ScriptComponent.h" #include "RebuildComponent.h" #include "VendorComponent.h" +#include "InventoryComponent.h" #include "RocketLaunchpadControlComponent.h" #include "PropertyEntranceComponent.h" #include "MovingPlatformComponent.h" diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 4f92480f..8a1c2fe5 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -5,7 +5,6 @@ #include "dCommonVars.h" #include "RakNetTypes.h" #include <string> -#include "InventoryComponent.h" #include "dMessageIdentifiers.h" #include "AMFFormat.h" #include "AMFFormat_BitStream.h" @@ -21,6 +20,8 @@ class User; class Entity; class NiPoint3; enum class eUnequippableActiveType; +enum eInventoryType : uint32_t; +class Item; namespace GameMessages { class PropertyDataMessage; diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index 151e3164..990b08f3 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -2,6 +2,7 @@ #include "GameMessages.h" #include "Game.h" #include "Item.h" +#include "InventoryComponent.h" #include "eItemType.h" std::vector<LOT> Inventory::m_GameMasterRestrictedItems = { @@ -266,7 +267,7 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) { case eItemType::ITEM_TYPE_QUEST_OBJECT: case eItemType::ITEM_TYPE_UNKNOWN: default: - return HIDDEN; + return QUEST; } } @@ -300,6 +301,12 @@ const std::vector<LOT>& Inventory::GetAllGMItems() { return m_GameMasterRestrictedItems; } +void Inventory::DeleteAllItems() { + while (!this->items.empty()) { + if (items.begin()->second) items.begin()->second->SetCount(0); + } +} + Inventory::~Inventory() { for (auto item : items) { delete item.second; diff --git a/dGame/dInventory/Inventory.h b/dGame/dInventory/Inventory.h index 6c6a4306..cd381db3 100644 --- a/dGame/dInventory/Inventory.h +++ b/dGame/dInventory/Inventory.h @@ -10,6 +10,7 @@ #include "CDClientManager.h" #include "dCommonVars.h" +enum eInventoryType : uint32_t; class Item; class InventoryComponent; @@ -152,6 +153,11 @@ public: */ static const std::vector<LOT>& GetAllGMItems(); + /** + * Remove ALL Items from this inventory. + */ + void DeleteAllItems(); + ~Inventory(); private: diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 02739ec2..778d8237 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -14,9 +14,7 @@ #include "CharacterComponent.h" #include "eItemType.h" #include "AssetManager.h" - -class Inventory; - +#include "InventoryComponent.h" Item::Item(const LWOOBJID id, const LOT lot, Inventory* inventory, const uint32_t slot, const uint32_t count, const bool bound, const std::vector<LDFBaseData*>& config, const LWOOBJID parent, LWOOBJID subKey, eLootSourceType lootSourceType) { if (!Inventory::IsValidItem(lot)) { diff --git a/dGame/dInventory/Item.h b/dGame/dInventory/Item.h index db7e246a..bb8316d7 100644 --- a/dGame/dInventory/Item.h +++ b/dGame/dInventory/Item.h @@ -6,6 +6,7 @@ #include "CDClientManager.h" #include "dLogger.h" #include "Preconditions.h" +#include "eInventoryType.h" /** * An item that can be stored in an inventory and optionally consumed or equipped diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index 0a8a57fe..61b41992 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -16,6 +16,7 @@ #include "dLogger.h" #include "dServer.h" #include "dZoneManager.h" +#include "InventoryComponent.h" #include "Database.h" Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { @@ -424,7 +425,7 @@ void Mission::YieldRewards() { for (const auto target : task->GetAllTargets()) { // This is how live did it. ONLY remove item collection items from the items and hidden inventories and none of the others. inventoryComponent->RemoveItem(target, task->GetClientInfo().targetValue, eInventoryType::ITEMS); - inventoryComponent->RemoveItem(target, task->GetClientInfo().targetValue, eInventoryType::HIDDEN); + inventoryComponent->RemoveItem(target, task->GetClientInfo().targetValue, eInventoryType::QUEST); missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, target, LWOOBJID_EMPTY, "", -task->GetClientInfo().targetValue); } diff --git a/dGame/dMission/MissionTask.cpp b/dGame/dMission/MissionTask.cpp index dc2cb149..d52e6e95 100644 --- a/dGame/dMission/MissionTask.cpp +++ b/dGame/dMission/MissionTask.cpp @@ -11,9 +11,9 @@ #include "ScriptedActivityComponent.h" #include "GameMessages.h" #include "dZoneManager.h" +#include "InventoryComponent.h" #include "MissionComponent.h" - MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) { this->info = info; this->mission = mission; diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 89f11346..7b1bf66c 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -1803,6 +1803,33 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, message); } + if (chatCommand == "deleteinven" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { + eInventoryType inventoryType = eInventoryType::INVALID; + if (!GeneralUtils::TryParse(args[0], inventoryType)) { + // 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); + Game::logger->Log("SlashCommandHandler", "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<eInventoryType>(index)))) inventoryType = static_cast<eInventoryType>(index); + } + } + + if (inventoryType == eInventoryType::INVALID || inventoryType >= NUMBER_OF_INVENTORIES) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid inventory provided."); + return; + } + + auto* inventoryComponent = entity->GetComponent<InventoryComponent>(); + if (!inventoryComponent) return; + + auto* inventoryToDelete = inventoryComponent->GetInventory(inventoryType); + if (!inventoryToDelete) return; + + inventoryToDelete->DeleteAllItems(); + Game::logger->Log("SlashCommandHandler", "Deleted inventory %s for user %llu", args[0].c_str(), entity->GetObjectID()); + ChatPackets::SendSystemMessage(sysAddr, u"Deleted inventory " + GeneralUtils::UTF8ToUTF16(args[0])); + } + if (chatCommand == "inspect" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { Entity* closest = nullptr; diff --git a/dScripts/02_server/Map/General/QbEnemyStunner.cpp b/dScripts/02_server/Map/General/QbEnemyStunner.cpp index 5d31a788..2b15a056 100644 --- a/dScripts/02_server/Map/General/QbEnemyStunner.cpp +++ b/dScripts/02_server/Map/General/QbEnemyStunner.cpp @@ -1,5 +1,6 @@ #include "QbEnemyStunner.h" #include "SkillComponent.h" +#include "CDClientManager.h" #include "DestroyableComponent.h" void QbEnemyStunner::OnRebuildComplete(Entity* self, Entity* target) { diff --git a/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp b/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp index cd0d94f2..dcccc337 100644 --- a/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp +++ b/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp @@ -3,6 +3,7 @@ #include "SkillComponent.h" #include "CDClientDatabase.h" #include "CDObjectSkillsTable.h" +#include "CDClientManager.h" void FireFirstSkillonStartup::OnStartup(Entity* self) { auto skillComponent = self->GetComponent<SkillComponent>(); diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp index 912b9f58..47bca374 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp @@ -11,6 +11,7 @@ #include "MovementAIComponent.h" #include "../dWorldServer/ObjectIDManager.h" #include "MissionComponent.h" +#include "InventoryComponent.h" void SGCannon::OnStartup(Entity* self) { Game::logger->Log("SGCannon", "OnStartup"); diff --git a/dScripts/ai/NS/NsConcertInstrument.cpp b/dScripts/ai/NS/NsConcertInstrument.cpp index 508b7b5b..bba3986d 100644 --- a/dScripts/ai/NS/NsConcertInstrument.cpp +++ b/dScripts/ai/NS/NsConcertInstrument.cpp @@ -5,6 +5,7 @@ #include "EntityManager.h" #include "RebuildComponent.h" #include "SoundTriggerComponent.h" +#include "InventoryComponent.h" #include "MissionComponent.h" // Constants are at the bottom From f311685dda33dc2d96d6840852db709e0f1227ce Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 19 Dec 2022 00:07:43 -0800 Subject: [PATCH 186/322] Fix Some missions not progressing if they are the last item in the inventory (#899) --- dGame/dGameMessages/GameMessages.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 9aa8eda2..9753868d 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -5736,16 +5736,16 @@ void GameMessages::HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* } auto* item = inventory->FindItemById(itemConsumed); - if (item == nullptr) { return; } + LOT itemLot = item->GetLot(); item->Consume(); auto* missions = static_cast<MissionComponent*>(entity->GetComponent(COMPONENT_TYPE_MISSION)); if (missions != nullptr) { - missions->Progress(MissionTaskType::MISSION_TASK_TYPE_FOOD, item->GetLot()); + missions->Progress(MissionTaskType::MISSION_TASK_TYPE_FOOD, itemLot); } } From 157a05239ed969b9116158147e5eb69db5be42c4 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Mon, 19 Dec 2022 13:45:50 -0600 Subject: [PATCH 187/322] Add speedbase readling and writing to the level prograssion component and impli proper character versions for fixes (#856) * Add speed base readling and writing to the level prograssion component Add retroactive fix to the world transfer TODO: see about versioning charxml fixes to make them not run every time * version all current changes * cleanup speed behavior add calculate for future use in scripts make < 1 speed multiplier possible tested wormholer and it plays anims correctly * cap the lower end of the speed multiplier until the ending the behavior on hit properly works * address feedback add emun for character version make set ignore multipliers consistent in speed behavior switch case for char version upgrades * remove the ability to stack speed boosts * update value on level ups --- dCommon/dEnums/eCharacterVersion.h | 21 ++++++ dGame/Entity.cpp | 4 +- dGame/dBehaviors/SpeedBehavior.cpp | 67 ++++--------------- dGame/dBehaviors/SpeedBehavior.h | 2 + .../ControllablePhysicsComponent.cpp | 38 ++++++++--- .../ControllablePhysicsComponent.h | 17 +++++ .../dComponents/LevelProgressionComponent.cpp | 19 +++++- dGame/dComponents/LevelProgressionComponent.h | 42 ++++++++++++ dWorldServer/WorldServer.cpp | 25 ++++++- 9 files changed, 166 insertions(+), 69 deletions(-) create mode 100644 dCommon/dEnums/eCharacterVersion.h diff --git a/dCommon/dEnums/eCharacterVersion.h b/dCommon/dEnums/eCharacterVersion.h new file mode 100644 index 00000000..0fab4498 --- /dev/null +++ b/dCommon/dEnums/eCharacterVersion.h @@ -0,0 +1,21 @@ +#pragma once + +#ifndef __ECHARACTERVERSION__H__ +#define __ECHARACTERVERSION__H__ + +#include <cstdint> + +enum class eCharacterVersion : uint32_t { +// Versions from the live game + RELEASE = 0, // Initial release of the game + LIVE, // Fixes for the 1.9 release bug fixes for missions leading up to joining a faction +// New versions for DLU fixes + // Fixes the "Joined a faction" player flag not being set properly + PLAYER_FACTION_FLAGS, + // Fixes vault size value + VAULT_SIZE, + // Fixes speed base value in level component + UP_TO_DATE, // will become SPEED_BASE +}; + +#endif //!__ECHARACTERVERSION__H__ diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 1f094291..cbab87db 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -769,8 +769,8 @@ no_ghosting: auto* controllablePhysicsComponent = GetComponent<ControllablePhysicsComponent>(); auto* levelComponent = GetComponent<LevelProgressionComponent>(); - if (controllablePhysicsComponent != nullptr && levelComponent->GetLevel() >= 20) { - controllablePhysicsComponent->SetSpeedMultiplier(525.0f / 500.0f); + if (controllablePhysicsComponent && levelComponent) { + controllablePhysicsComponent->SetSpeedMultiplier(levelComponent->GetSpeedBase() / 500.0f); } } } diff --git a/dGame/dBehaviors/SpeedBehavior.cpp b/dGame/dBehaviors/SpeedBehavior.cpp index c7855557..bec2b1cb 100644 --- a/dGame/dBehaviors/SpeedBehavior.cpp +++ b/dGame/dBehaviors/SpeedBehavior.cpp @@ -7,85 +7,44 @@ void SpeedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - if (m_AffectsCaster) { - branch.target = context->caster; - } + if (m_AffectsCaster) branch.target = context->caster; auto* target = EntityManager::Instance()->GetEntity(branch.target); - - if (target == nullptr) { - return; - } + if (!target) return; auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>(); + if (!controllablePhysicsComponent) return; - if (controllablePhysicsComponent == nullptr) { - return; - } - - const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); - - controllablePhysicsComponent->SetSpeedMultiplier(current + ((m_RunSpeed - 500.0f) / 500.0f)); - + controllablePhysicsComponent->AddSpeedboost(m_RunSpeed); EntityManager::Instance()->SerializeEntity(target); if (branch.duration > 0.0f) { context->RegisterTimerBehavior(this, branch); } else if (branch.start > 0) { - controllablePhysicsComponent->SetIgnoreMultipliers(true); - context->RegisterEndBehavior(this, branch); } } -void SpeedBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { - auto* target = EntityManager::Instance()->GetEntity(branch.target); - - if (target == nullptr) { - return; - } - - auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>(); - - if (controllablePhysicsComponent == nullptr) { - return; - } - - const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); - - controllablePhysicsComponent->SetSpeedMultiplier(current - ((m_RunSpeed - 500.0f) / 500.0f)); - - EntityManager::Instance()->SerializeEntity(target); +void SpeedBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + Handle(context, bitStream, branch); } void SpeedBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - - if (target == nullptr) { - return; - } + if (!target) return; auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>(); + if (!controllablePhysicsComponent) return; - if (controllablePhysicsComponent == nullptr) { - return; - } - - const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); - - controllablePhysicsComponent->SetIgnoreMultipliers(false); - - controllablePhysicsComponent->SetSpeedMultiplier(current - ((m_RunSpeed - 500.0f) / 500.0f)); - + controllablePhysicsComponent->RemoveSpeedboost(m_RunSpeed); EntityManager::Instance()->SerializeEntity(target); } +void SpeedBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { + End(context, branch, second); +} + void SpeedBehavior::Load() { m_RunSpeed = GetFloat("run_speed"); - - if (m_RunSpeed < 500.0f) { - m_RunSpeed = 500.0f; - } - m_AffectsCaster = GetBoolean("affects_caster"); } diff --git a/dGame/dBehaviors/SpeedBehavior.h b/dGame/dBehaviors/SpeedBehavior.h index 04c0090f..57c46842 100644 --- a/dGame/dBehaviors/SpeedBehavior.h +++ b/dGame/dBehaviors/SpeedBehavior.h @@ -13,6 +13,8 @@ public: void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; diff --git a/dGame/dComponents/ControllablePhysicsComponent.cpp b/dGame/dComponents/ControllablePhysicsComponent.cpp index d7caf6a9..a5e447c8 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/ControllablePhysicsComponent.cpp @@ -12,6 +12,7 @@ #include "EntityManager.h" #include "Character.h" #include "dZoneManager.h" +#include "LevelProgressionComponent.h" ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Component(entity) { m_Position = {}; @@ -73,13 +74,7 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bo outBitStream->Write0(); //This contains info about immunities, but for now I'm leaving it out. } - if (m_SpeedMultiplier < 1.0f) { - m_DirtyCheats = false; - } - - if (m_IgnoreMultipliers) { - m_DirtyCheats = false; - } + if (m_IgnoreMultipliers) m_DirtyCheats = false; outBitStream->Write(m_DirtyCheats); if (m_DirtyCheats) { @@ -263,7 +258,7 @@ void ControllablePhysicsComponent::RemovePickupRadiusScale(float value) { if (pos != m_ActivePickupRadiusScales.end()) { m_ActivePickupRadiusScales.erase(pos); } else { - Game::logger->Log("ControllablePhysicsComponent", "Warning: Could not find pickup radius %f in list of active radii. List has %i active radii.", value, m_ActivePickupRadiusScales.size()); + Game::logger->LogDebug("ControllablePhysicsComponent", "Warning: Could not find pickup radius %f in list of active radii. List has %i active radii.", value, m_ActivePickupRadiusScales.size()); return; } @@ -276,3 +271,30 @@ void ControllablePhysicsComponent::RemovePickupRadiusScale(float value) { } EntityManager::Instance()->SerializeEntity(m_Parent); } + +void ControllablePhysicsComponent::AddSpeedboost(float value) { + m_ActiveSpeedBoosts.push_back(value); + m_SpeedBoost = value; + SetSpeedMultiplier(value / 500.0f); // 500 being the base speed +} + +void ControllablePhysicsComponent::RemoveSpeedboost(float value) { + const auto pos = std::find(m_ActiveSpeedBoosts.begin(), m_ActiveSpeedBoosts.end(), value); + if (pos != m_ActiveSpeedBoosts.end()) { + m_ActiveSpeedBoosts.erase(pos); + } else { + Game::logger->LogDebug("ControllablePhysicsComponent", "Warning: Could not find speedboost %f in list of active speedboosts. List has %i active speedboosts.", value, m_ActiveSpeedBoosts.size()); + return; + } + + // Recalculate speedboost since we removed one + m_SpeedBoost = 0.0f; + if (m_ActiveSpeedBoosts.size() == 0) { // no active speed boosts left, so return to base speed + auto* levelProgressionComponent = m_Parent->GetComponent<LevelProgressionComponent>(); + if (levelProgressionComponent) m_SpeedBoost = levelProgressionComponent->GetSpeedBase(); + } else { // Used the last applied speedboost + m_SpeedBoost = m_ActiveSpeedBoosts.back(); + } + SetSpeedMultiplier(m_SpeedBoost / 500.0f); // 500 being the base speed + EntityManager::Instance()->SerializeEntity(m_Parent); +} diff --git a/dGame/dComponents/ControllablePhysicsComponent.h b/dGame/dComponents/ControllablePhysicsComponent.h index ac481b9f..e029d607 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.h +++ b/dGame/dComponents/ControllablePhysicsComponent.h @@ -257,6 +257,13 @@ public: */ std::vector<float> GetActivePickupRadiusScales() { return m_ActivePickupRadiusScales; }; + + void AddSpeedboost(float value); + + void RemoveSpeedboost(float value); + + std::vector<float> GetActiveSpeedboosts() { return m_ActivePickupRadiusScales; }; + private: /** * The entity that owns this component @@ -372,6 +379,16 @@ private: * If the entity is teleporting */ bool m_IsTeleporting; + + /** + * The list of speed boosts for this entity + */ + std::vector<float> m_ActiveSpeedBoosts; + + /** + * The active speed boost for this entity + */ + float m_SpeedBoost; }; #endif // CONTROLLABLEPHYSICSCOMPONENT_H diff --git a/dGame/dComponents/LevelProgressionComponent.cpp b/dGame/dComponents/LevelProgressionComponent.cpp index ee3cfc6b..6e6b823e 100644 --- a/dGame/dComponents/LevelProgressionComponent.cpp +++ b/dGame/dComponents/LevelProgressionComponent.cpp @@ -7,6 +7,8 @@ LevelProgressionComponent::LevelProgressionComponent(Entity* parent) : Component(parent) { m_Parent = parent; m_Level = 1; + m_SpeedBase = 500.0f; + m_CharacterVersion = eCharacterVersion::LIVE; } void LevelProgressionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { @@ -16,7 +18,8 @@ void LevelProgressionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { return; } level->SetAttribute("l", m_Level); - + level->SetAttribute("sb", m_SpeedBase); + level->SetAttribute("cv", static_cast<uint32_t>(m_CharacterVersion)); } void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { @@ -26,7 +29,10 @@ void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { return; } level->QueryAttribute("l", &m_Level); - + level->QueryAttribute("sb", &m_SpeedBase); + uint32_t characterVersion; + level->QueryAttribute("cv", &characterVersion); + m_CharacterVersion = static_cast<eCharacterVersion>(characterVersion); } void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { @@ -60,7 +66,8 @@ void LevelProgressionComponent::HandleLevelUp() { } break; case 9: - controllablePhysicsComponent->SetSpeedMultiplier(static_cast<float>(reward->value) / 500.0f); + SetSpeedBase(static_cast<float>(reward->value) ); + controllablePhysicsComponent->SetSpeedMultiplier(GetSpeedBase() / 500.0f); break; case 11: case 12: @@ -72,3 +79,9 @@ void LevelProgressionComponent::HandleLevelUp() { // Tell the client we have finished sending level rewards. if (rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, !rewardingItem); } + +void LevelProgressionComponent::SetRetroactiveBaseSpeed(){ + if (m_Level >= 20) m_SpeedBase = 525.0f; + auto* controllablePhysicsComponent = m_Parent->GetComponent<ControllablePhysicsComponent>(); + if (controllablePhysicsComponent) controllablePhysicsComponent->SetSpeedMultiplier(m_SpeedBase / 500.0f); +} diff --git a/dGame/dComponents/LevelProgressionComponent.h b/dGame/dComponents/LevelProgressionComponent.h index 53f6693e..dd3fbfbb 100644 --- a/dGame/dComponents/LevelProgressionComponent.h +++ b/dGame/dComponents/LevelProgressionComponent.h @@ -3,11 +3,13 @@ #include "Entity.h" #include "GameMessages.h" #include "Component.h" +#include "eCharacterVersion.h" /** * Component that handles level progression and serilization. * */ + class LevelProgressionComponent : public Component { public: static const uint32_t ComponentType = eReplicaComponentType::COMPONENT_TYPE_LEVEL_PROGRESSION; @@ -44,11 +46,40 @@ public: */ void SetLevel(uint32_t level) { m_Level = level; m_DirtyLevelInfo = true; } + /** + * Gets the current Speed Base of the entity + * @return the current Speed Base of the entity + */ + const uint32_t GetSpeedBase() const { return m_SpeedBase; } + + /** + * Sets the Speed Base of the entity + * @param SpeedBase the Speed Base to set + */ + void SetSpeedBase(uint32_t SpeedBase) { m_SpeedBase = SpeedBase; } + /** * Gives the player rewards for the last level that they leveled up from */ void HandleLevelUp(); + /** + * Gets the current Character Version of the entity + * @return the current Character Version of the entity + */ + const eCharacterVersion GetCharacterVersion() const { return m_CharacterVersion; } + + /** + * Sets the Character Version of the entity + * @param CharacterVersion the Character Version to set + */ + void SetCharacterVersion(eCharacterVersion CharacterVersion) { m_CharacterVersion = CharacterVersion; } + + /** + * Set the Base Speed retroactively of the entity + */ + void SetRetroactiveBaseSpeed(); + private: /** * whether the level is dirty @@ -59,4 +90,15 @@ private: * Level of the entity */ uint32_t m_Level; + + /** + * The base speed of the entity + */ + float m_SpeedBase; + + /** + * The Character format version + */ + eCharacterVersion m_CharacterVersion; + }; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 594d3dc7..d204d5c9 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -56,6 +56,7 @@ #include "Player.h" #include "PropertyManagementComponent.h" #include "AssetManager.h" +#include "LevelProgressionComponent.h" #include "eBlueprintSaveResponseType.h" #include "ZCompression.h" @@ -993,9 +994,29 @@ void HandlePacket(Packet* packet) { player->GetComponent<CharacterComponent>()->RocketUnEquip(player); } - c->SetRetroactiveFlags(); + // Do charxml fixes here + auto* levelComponent = player->GetComponent<LevelProgressionComponent>(); + if (!levelComponent) return; - player->RetroactiveVaultSize(); + auto version = levelComponent->GetCharacterVersion(); + switch(version) { + case eCharacterVersion::RELEASE: + // TODO: Implement, super low priority + case eCharacterVersion::LIVE: + Game::logger->Log("WorldServer", "Updating Character Flags"); + c->SetRetroactiveFlags(); + levelComponent->SetCharacterVersion(eCharacterVersion::PLAYER_FACTION_FLAGS); + case eCharacterVersion::PLAYER_FACTION_FLAGS: + Game::logger->Log("WorldServer", "Updating Vault Size"); + player->RetroactiveVaultSize(); + levelComponent->SetCharacterVersion(eCharacterVersion::VAULT_SIZE); + case eCharacterVersion::VAULT_SIZE: + Game::logger->Log("WorldServer", "Updaing Speedbase"); + levelComponent->SetRetroactiveBaseSpeed(); + levelComponent->SetCharacterVersion(eCharacterVersion::UP_TO_DATE); + case eCharacterVersion::UP_TO_DATE: + break; + } player->GetCharacter()->SetTargetScene(""); From d69f733772d3bca27261aaf11b72c96754123724 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 19 Dec 2022 12:51:44 -0800 Subject: [PATCH 188/322] Fix trading taking the wrong item (#900) * Fix trading taking the wrong item * Add missing returns * Improve further Do all verification first. Then actually do the trade. Prevents possible cheating attempts --- dGame/TradingManager.cpp | 53 ++++++++++++++++++++++++++++++---------- 1 file changed, 40 insertions(+), 13 deletions(-) diff --git a/dGame/TradingManager.cpp b/dGame/TradingManager.cpp index e49cca70..ed55f217 100644 --- a/dGame/TradingManager.cpp +++ b/dGame/TradingManager.cpp @@ -103,6 +103,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) { } Complete(); + TradingManager::Instance()->CancelTrade(m_TradeId); } } @@ -121,33 +122,59 @@ void Trade::Complete() { if (inventoryA == nullptr || inventoryB == nullptr || characterA == nullptr || characterB == nullptr || missionsA == nullptr || missionsB == nullptr) return; + // First verify both players have the coins and items requested for the trade. + if (characterA->GetCoins() < m_CoinsA || characterB->GetCoins() < m_CoinsB) { + Game::logger->Log("TradingManager", "Possible coin trade cheating attempt! Aborting trade."); + return; + } + + for (const auto& tradeItem : m_ItemsA) { + auto* itemToRemove = inventoryA->FindItemById(tradeItem.itemId); + if (itemToRemove) { + if (itemToRemove->GetCount() < tradeItem.itemCount) { + Game::logger->Log("TradingManager", "Possible cheating attempt from %s in trading!!! Aborting trade", characterA->GetName().c_str()); + return; + } + } else { + Game::logger->Log("TradingManager", "Possible cheating attempt from %s in trading due to item not being available!!!", characterA->GetName().c_str()); + return; + } + } + + for (const auto& tradeItem : m_ItemsB) { + auto* itemToRemove = inventoryB->FindItemById(tradeItem.itemId); + if (itemToRemove) { + if (itemToRemove->GetCount() < tradeItem.itemCount) { + Game::logger->Log("TradingManager", "Possible cheating attempt from %s in trading!!! Aborting trade", characterB->GetName().c_str()); + return; + } + } else { + Game::logger->Log("TradingManager", "Possible cheating attempt from %s in trading due to item not being available!!! Aborting trade", characterB->GetName().c_str()); + return; + } + } + + // Now actually do the trade. characterA->SetCoins(characterA->GetCoins() - m_CoinsA + m_CoinsB, eLootSourceType::LOOT_SOURCE_TRADE); characterB->SetCoins(characterB->GetCoins() - m_CoinsB + m_CoinsA, eLootSourceType::LOOT_SOURCE_TRADE); for (const auto& tradeItem : m_ItemsA) { - inventoryA->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true); - + auto* itemToRemove = inventoryA->FindItemById(tradeItem.itemId); + if (itemToRemove) itemToRemove->SetCount(itemToRemove->GetCount() - tradeItem.itemCount); missionsA->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); - } - - for (const auto& tradeItem : m_ItemsB) { - inventoryB->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true); - - missionsB->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); - } - - for (const auto& tradeItem : m_ItemsA) { inventoryB->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); } for (const auto& tradeItem : m_ItemsB) { + auto* itemToRemove = inventoryB->FindItemById(tradeItem.itemId); + if (itemToRemove) itemToRemove->SetCount(itemToRemove->GetCount() - tradeItem.itemCount); + missionsB->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); inventoryA->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); } - TradingManager::Instance()->CancelTrade(m_TradeId); - characterA->SaveXMLToDatabase(); characterB->SaveXMLToDatabase(); + return; } void Trade::Cancel() { From 2fdcf62ec61ca551ff4bca4ca68d47891d1e7ceb Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 19 Dec 2022 12:52:00 -0800 Subject: [PATCH 189/322] Fix overread in projectile behavior and address broken stuns (#898) * Fix overread in projectile behavior * Fix stuns * Correctly read in bitStream --- dGame/dBehaviors/AttackDelayBehavior.cpp | 2 +- dGame/dBehaviors/BehaviorContext.cpp | 3 ++- dGame/dBehaviors/BehaviorContext.h | 2 +- dGame/dBehaviors/ProjectileAttackBehavior.cpp | 4 +++- dGame/dBehaviors/ProjectileAttackBehavior.h | 2 ++ 5 files changed, 9 insertions(+), 4 deletions(-) diff --git a/dGame/dBehaviors/AttackDelayBehavior.cpp b/dGame/dBehaviors/AttackDelayBehavior.cpp index 201921a3..ccea5fd9 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.cpp +++ b/dGame/dBehaviors/AttackDelayBehavior.cpp @@ -13,7 +13,7 @@ void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi }; for (auto i = 0u; i < this->m_numIntervals; ++i) { - context->RegisterSyncBehavior(handle, this, branch); + context->RegisterSyncBehavior(handle, this, branch, m_ignoreInterrupts); } } diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index 4cd9e415..c2f0c88e 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -45,12 +45,13 @@ uint32_t BehaviorContext::GetUniqueSkillId() const { } -void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext) { +void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext, bool ignoreInterrupts) { auto entry = BehaviorSyncEntry(); entry.handle = syncId; entry.behavior = behavior; entry.branchContext = branchContext; + entry.ignoreInterrupts = ignoreInterrupts; this->syncEntries.push_back(entry); } diff --git a/dGame/dBehaviors/BehaviorContext.h b/dGame/dBehaviors/BehaviorContext.h index 0462d97f..dbba4d91 100644 --- a/dGame/dBehaviors/BehaviorContext.h +++ b/dGame/dBehaviors/BehaviorContext.h @@ -80,7 +80,7 @@ struct BehaviorContext uint32_t GetUniqueSkillId() const; - void RegisterSyncBehavior(uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext); + void RegisterSyncBehavior(uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext, bool ignoreInterrupts = false); void RegisterTimerBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, LWOOBJID second = LWOOBJID_EMPTY); diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.cpp b/dGame/dBehaviors/ProjectileAttackBehavior.cpp index c14f032d..2b38db8f 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.cpp +++ b/dGame/dBehaviors/ProjectileAttackBehavior.cpp @@ -31,7 +31,7 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea return; } - if (m_useMouseposit) { + if (m_ProjectileType == 1) { NiPoint3 targetPosition = NiPoint3::ZERO; if (!bitStream->Read(targetPosition)) { Game::logger->Log("ProjectileAttackBehavior", "Unable to read targetPosition from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); @@ -157,4 +157,6 @@ void ProjectileAttackBehavior::Load() { this->m_trackRadius = GetFloat("track_radius"); this->m_useMouseposit = GetBoolean("use_mouseposit"); + + this->m_ProjectileType = GetInt("projectile_type"); } diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.h b/dGame/dBehaviors/ProjectileAttackBehavior.h index 17353a2a..b307e66c 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.h +++ b/dGame/dBehaviors/ProjectileAttackBehavior.h @@ -23,6 +23,8 @@ public: bool m_useMouseposit; + int32_t m_ProjectileType; + /* * Inherited */ From f2fa81b5c3b4be084b2664b83debc26ac5d0a8dd Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 20 Dec 2022 13:20:44 -0800 Subject: [PATCH 190/322] Fix lobbies (#901) --- dGame/dComponents/ScriptedActivityComponent.cpp | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index da546910..ee7ca22e 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -208,7 +208,7 @@ void ScriptedActivityComponent::PlayerLeave(LWOOBJID playerID) { } void ScriptedActivityComponent::Update(float deltaTime) { - + std::vector<Lobby*> lobbiesToRemove{}; // Ticks all the lobbies, not applicable for non-instance activities for (Lobby* lobby : m_Queue) { for (LobbyPlayer* player : lobby->players) { @@ -219,6 +219,11 @@ void ScriptedActivityComponent::Update(float deltaTime) { } } + if (lobby->players.empty()) { + lobbiesToRemove.push_back(lobby); + continue; + } + // Update the match time for all players if (m_ActivityInfo.maxTeamSize != 1 && lobby->players.size() >= m_ActivityInfo.minTeamSize || m_ActivityInfo.maxTeamSize == 1 && lobby->players.size() >= m_ActivityInfo.minTeams) { @@ -262,13 +267,17 @@ void ScriptedActivityComponent::Update(float deltaTime) { // The timer has elapsed, start the instance if (lobby->timer <= 0.0f) { Game::logger->Log("ScriptedActivityComponent", "Setting up instance."); - ActivityInstance* instance = NewInstance(); LoadPlayersIntoInstance(instance, lobby->players); - RemoveLobby(lobby); instance->StartZone(); + lobbiesToRemove.push_back(lobby); } } + + while (!lobbiesToRemove.empty()) { + RemoveLobby(lobbiesToRemove.front()); + lobbiesToRemove.erase(lobbiesToRemove.begin()); + } } void ScriptedActivityComponent::RemoveLobby(Lobby* lobby) { From 0a31db9d4410d2ca28b12f3fab2631a580d1ae2d Mon Sep 17 00:00:00 2001 From: Neal Spellman <nealybealy@comcast.net> Date: Tue, 20 Dec 2022 17:10:54 -0500 Subject: [PATCH 191/322] Updated README and CREDITS (#904) - README now has proper capitalization for categories in the credits. - New layout with former contributors moved to below active contributors. - LEGO Universe credits linked for the special thanks. - Aronwk properly recognized as DLU team member after mistakenly not included. - Vanity credits updated to more closely mirror categories in README's credits. --- README.md | 26 +++++++++++++------------- vanity/CREDITS.md | 13 ++++++------- 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 87319c10..bd9dd6b7 100644 --- a/README.md +++ b/README.md @@ -422,11 +422,6 @@ Here is a summary of the commands available in-game. All commands are prefixed b </table> # Credits -## Active Contributors -* [EmosewaMC](https://github.com/EmosewaMC) -* [Jettford](https://github.com/Jettford) -* [Aaron K.](https://github.com/aronwk-aaron) - ## DLU Team * [DarwinAnim8or](https://github.com/DarwinAnim8or) * [Wincent01](https://github.com/Wincent01) @@ -434,25 +429,30 @@ Here is a summary of the commands available in-game. All commands are prefixed b * [averysumner](https://github.com/codeshaunted) * [Jon002](https://github.com/jaller200) * [Jonny](https://github.com/cuzitsjonny) +* [Aaron K.](https://github.com/aronwk-aaron) -### Research and tools +### Research and Tools * [lcdr](https://github.com/lcdr) * [Xiphoseer](https://github.com/Xiphoseer) -### Community management +### Community Management * [Neal](https://github.com/NealSpellman) -### Former contributors +### Logo +* Cole Peterson (BlasterBuilder) + +## Active Contributors +* [EmosewaMC](https://github.com/EmosewaMC) +* [Jettford](https://github.com/Jettford) + +## Former Contributors * TheMachine * Matthew * [Raine](https://github.com/Rainebannister) * Bricknave -### Logo -* Cole Peterson (BlasterBuilder) - -## Special thanks +## Special Thanks * humanoid24 * pwjones1969 * [Simon](https://github.com/SimonNitzsche) -* ALL OF THE NETDEVIL AND LEGO TEAMS! +* [ALL OF THE NETDEVIL AND LEGO TEAMS!](https://www.mobygames.com/game/macintosh/lego-universe/credits) diff --git a/vanity/CREDITS.md b/vanity/CREDITS.md index e130cfb3..6780cff7 100644 --- a/vanity/CREDITS.md +++ b/vanity/CREDITS.md @@ -1,18 +1,17 @@ # CREDITS -## Developers +## DLU Team DarwinAnim8or (Max) Wincent01 Mick averysumner (codeshaunted) Jon002 Jonny -EmosewaMC -Jettford - -## Research & Tooling Xiphoseer lcdr - -## Community Management +Aaron K. Neal + +## Active Contributors +EmosewaMC +Jettford \ No newline at end of file From 38eb441ca14037b626339f17fd40bdc870f9fc84 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 21 Dec 2022 00:26:17 -0800 Subject: [PATCH 192/322] Correct Projectile behavior bitStream reads (#907) --- dGame/dBehaviors/BehaviorBranchContext.h | 2 ++ dGame/dBehaviors/BehaviorContext.cpp | 1 + dGame/dBehaviors/ProjectileAttackBehavior.cpp | 2 +- 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/dGame/dBehaviors/BehaviorBranchContext.h b/dGame/dBehaviors/BehaviorBranchContext.h index 5b2ec595..2e56cd35 100644 --- a/dGame/dBehaviors/BehaviorBranchContext.h +++ b/dGame/dBehaviors/BehaviorBranchContext.h @@ -15,6 +15,8 @@ struct BehaviorBranchContext uint32_t start = 0; + bool isSync = false; + BehaviorBranchContext(); BehaviorBranchContext(LWOOBJID target, float duration = 0, const NiPoint3& referencePosition = NiPoint3(0, 0, 0)); diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index c2f0c88e..ebed10ba 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -51,6 +51,7 @@ void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* beha entry.handle = syncId; entry.behavior = behavior; entry.branchContext = branchContext; + entry.branchContext.isSync = true; entry.ignoreInterrupts = ignoreInterrupts; this->syncEntries.push_back(entry); diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.cpp b/dGame/dBehaviors/ProjectileAttackBehavior.cpp index 2b38db8f..3ce6c415 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.cpp +++ b/dGame/dBehaviors/ProjectileAttackBehavior.cpp @@ -31,7 +31,7 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea return; } - if (m_ProjectileType == 1) { + if (m_useMouseposit && !branch.isSync) { NiPoint3 targetPosition = NiPoint3::ZERO; if (!bitStream->Read(targetPosition)) { Game::logger->Log("ProjectileAttackBehavior", "Unable to read targetPosition from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); From 51dd56f0a0479eae60da3d09279b6c2685b96a70 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 21 Dec 2022 08:51:27 -0800 Subject: [PATCH 193/322] Add MTU config option (#908) * Add config option * Add reloading --- dGame/dUtilities/SlashCommandHandler.cpp | 1 + dNet/dServer.cpp | 8 +++++++- dNet/dServer.h | 1 + resources/sharedconfig.ini | 10 +++++++++- 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 7b1bf66c..9a63f83c 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -1762,6 +1762,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit scriptedActivityComponent->ReloadConfig(); } + Game::server->UpdateMaximumMtuSize(); Game::server->UpdateBandwidthLimit(); ChatPackets::SendSystemMessage(sysAddr, u"Successfully reloaded config for world!"); } diff --git a/dNet/dServer.cpp b/dNet/dServer.cpp index 55e07da3..a3961d45 100644 --- a/dNet/dServer.cpp +++ b/dNet/dServer.cpp @@ -68,7 +68,7 @@ dServer::dServer(const std::string& ip, int port, int instanceID, int maxConnect } else { mLogger->Log("dServer", "FAILED TO START SERVER ON IP/PORT: %s:%i", ip.c_str(), port); return; } mLogger->SetLogToConsole(prevLogSetting); - mPeer->SetMTUSize(1228); // This is hard coded by lu for some reason. + //Connect to master if we are not master: if (serverType != ServerType::Master) { SetupForMasterConnection(); @@ -188,6 +188,7 @@ bool dServer::Startup() { mPeer->SetIncomingPassword("3.25 DARKFLAME1", 15); } else { UpdateBandwidthLimit(); + UpdateMaximumMtuSize(); mPeer->SetIncomingPassword("3.25 ND1", 8); } @@ -197,6 +198,11 @@ bool dServer::Startup() { return true; } +void dServer::UpdateMaximumMtuSize() { + auto maxMtuSize = mConfig->GetValue("maximum_mtu_size"); + mPeer->SetMTUSize(maxMtuSize.empty() ? 1228 : std::stoi(maxMtuSize)); +} + void dServer::UpdateBandwidthLimit() { auto newBandwidth = mConfig->GetValue("maximum_outgoing_bandwidth"); mPeer->SetPerConnectionOutgoingBandwidthLimit(!newBandwidth.empty() ? std::stoi(newBandwidth) : 0); diff --git a/dNet/dServer.h b/dNet/dServer.h index af4c8322..d9e74d2e 100644 --- a/dNet/dServer.h +++ b/dNet/dServer.h @@ -57,6 +57,7 @@ public: ReplicaManager* GetReplicaManager() { return mReplicaManager; } void UpdateReplica(); void UpdateBandwidthLimit(); + void UpdateMaximumMtuSize(); int GetPing(const SystemAddress& sysAddr) const; int GetLatestPing(const SystemAddress& sysAddr) const; diff --git a/resources/sharedconfig.ini b/resources/sharedconfig.ini index 439ffe2f..d2c43d11 100644 --- a/resources/sharedconfig.ini +++ b/resources/sharedconfig.ini @@ -26,5 +26,13 @@ dump_folder= # Either the folder with /res or with /client and /versions client_location= -# The maximum outgoing bandwidth in bits +# The maximum outgoing bandwidth in bits. If your clients are having +# issues with enemies taking a while to catch up to them, increse this value. maximum_outgoing_bandwidth=80000 + +# The Maximum Translation Unit (MTU) size for packets. If players are +# getting stuck at 55% on the loading screen, lower this number to +# reduce the chances of packet loss. This value only has an effect +# from 512 <= maximum_mtu_size <= 1492 so make sure to keep this +# value within that range. +maximum_mtu_size=1228 From bd7f532a280e959c622685b53aa325f56226087f Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 21 Dec 2022 14:33:41 -0800 Subject: [PATCH 194/322] Implement the Imaginite Backpack and Shard armor scripts (#886) * Imaginite Pack now works * Remove unused params * Address issues * Add TeslaPack script Co-authored-by: aronwk-aaron <aronwk.aaron@gmail.com> --- CMakeLists.txt | 1 + dGame/Entity.cpp | 16 ++++++++ dGame/Entity.h | 8 ++++ dGame/dComponents/DestroyableComponent.cpp | 24 ++++++++++++ dGame/dComponents/DestroyableComponent.h | 20 ++++++++++ dGame/dComponents/InventoryComponent.cpp | 38 ++++++++++++++++++- dGame/dComponents/InventoryComponent.h | 14 +++++++ dScripts/CMakeLists.txt | 6 +++ dScripts/CppScripts.cpp | 9 +++++ dScripts/CppScripts.h | 23 +++++++++++ dScripts/EquipmentTriggers/CMakeLists.txt | 3 ++ .../EquipmentTriggers/CoilBackpackBase.cpp | 25 ++++++++++++ dScripts/EquipmentTriggers/CoilBackpackBase.h | 21 ++++++++++ dScripts/EquipmentTriggers/GemPack.h | 14 +++++++ dScripts/EquipmentTriggers/ShardArmor.h | 14 +++++++ dScripts/EquipmentTriggers/TeslaPack.h | 14 +++++++ 16 files changed, 249 insertions(+), 1 deletion(-) create mode 100644 dScripts/EquipmentTriggers/CMakeLists.txt create mode 100644 dScripts/EquipmentTriggers/CoilBackpackBase.cpp create mode 100644 dScripts/EquipmentTriggers/CoilBackpackBase.h create mode 100644 dScripts/EquipmentTriggers/GemPack.h create mode 100644 dScripts/EquipmentTriggers/ShardArmor.h create mode 100644 dScripts/EquipmentTriggers/TeslaPack.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 163196fb..b9596649 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -176,6 +176,7 @@ set(INCLUDED_DIRECTORIES "dScripts/ai" "dScripts/client" "dScripts/EquipmentScripts" + "dScripts/EquipmentTriggers" "dScripts/zone" "dScripts/02_server/DLU" "dScripts/02_server/Enemy" diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index cbab87db..16b2c5a1 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -824,6 +824,22 @@ std::vector<ScriptComponent*> Entity::GetScriptComponents() { return comps; } +void Entity::Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName) { + if (notificationName == "HitOrHealResult" || notificationName == "Hit") { + auto* destroyableComponent = GetComponent<DestroyableComponent>(); + if (!destroyableComponent) return; + destroyableComponent->Subscribe(scriptObjId, scriptToAdd); + } +} + +void Entity::Unsubscribe(LWOOBJID scriptObjId, const std::string& notificationName) { + if (notificationName == "HitOrHealResult" || notificationName == "Hit") { + auto* destroyableComponent = GetComponent<DestroyableComponent>(); + if (!destroyableComponent) return; + destroyableComponent->Unsubscribe(scriptObjId); + } +} + void Entity::SetProximityRadius(float proxRadius, std::string name) { ProximityMonitorComponent* proxMon = GetComponent<ProximityMonitorComponent>(); if (!proxMon) { diff --git a/dGame/Entity.h b/dGame/Entity.h index 6c0968f8..e0d38308 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -26,8 +26,13 @@ class Spawner; class ScriptComponent; class dpEntity; class Component; +class Item; class Character; +namespace CppScripts { + class Script; +}; + /** * An entity in the world. Has multiple components. */ @@ -139,6 +144,9 @@ public: std::vector<ScriptComponent*> GetScriptComponents(); + void Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName); + void Unsubscribe(LWOOBJID scriptObjId, const std::string& notificationName); + void SetProximityRadius(float proxRadius, std::string name); void SetProximityRadius(dpEntity* entity, std::string name); diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index c899d9e8..6902917f 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -631,6 +631,7 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 auto* attacker = EntityManager::Instance()->GetEntity(source); m_Parent->OnHit(attacker); m_Parent->OnHitOrHealResult(attacker, sourceDamage); + NotifySubscribers(attacker, sourceDamage); for (const auto& cb : m_OnHitCallbacks) { cb(attacker); @@ -648,6 +649,29 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 Smash(source, eKillType::VIOLENT, u"", skillID); } +void DestroyableComponent::Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd) { + m_SubscribedScripts.insert(std::make_pair(scriptObjId, scriptToAdd)); + Game::logger->LogDebug("DestroyableComponent", "Added script %llu to entity %llu", scriptObjId, m_Parent->GetObjectID()); + Game::logger->LogDebug("DestroyableComponent", "Number of subscribed scripts %i", m_SubscribedScripts.size()); +} + +void DestroyableComponent::Unsubscribe(LWOOBJID scriptObjId) { + auto foundScript = m_SubscribedScripts.find(scriptObjId); + if (foundScript != m_SubscribedScripts.end()) { + m_SubscribedScripts.erase(foundScript); + Game::logger->LogDebug("DestroyableComponent", "Removed script %llu from entity %llu", scriptObjId, m_Parent->GetObjectID()); + } else { + Game::logger->LogDebug("DestroyableComponent", "Tried to remove a script for Entity %llu but script %llu didnt exist", m_Parent->GetObjectID(), scriptObjId); + } + Game::logger->LogDebug("DestroyableComponent", "Number of subscribed scripts %i", m_SubscribedScripts.size()); +} + +void DestroyableComponent::NotifySubscribers(Entity* attacker, uint32_t damage) { + for (auto script : m_SubscribedScripts) { + script.second->NotifyHitOrHealResult(m_Parent, attacker, damage); + } +} + void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType, uint32_t skillID) { if (m_iHealth > 0) { SetArmor(0); diff --git a/dGame/dComponents/DestroyableComponent.h b/dGame/dComponents/DestroyableComponent.h index b8e81b33..5bb990a7 100644 --- a/dGame/dComponents/DestroyableComponent.h +++ b/dGame/dComponents/DestroyableComponent.h @@ -7,6 +7,10 @@ #include "Entity.h" #include "Component.h" +namespace CppScripts { + class Script; +}; //! namespace CppScripts + /** * Represents the stats of an entity, for example its health, imagination and armor. Also handles factions, which * indicate which enemies this entity has. @@ -422,6 +426,17 @@ public: */ void AddFactionNoLookup(int32_t faction) { m_FactionIDs.push_back(faction); }; + /** + * Notify subscribed scripts of Damage actions. + * + * @param attacker The attacking Entity + * @param damage The amount of damage that was done + */ + void NotifySubscribers(Entity* attacker, uint32_t damage); + + void Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd); + void Unsubscribe(LWOOBJID scriptObjId); + private: /** * Whether or not the health should be serialized @@ -557,6 +572,11 @@ private: * The list of callbacks that will be called when this entity gets hit */ std::vector<std::function<void(Entity*)>> m_OnHitCallbacks; + + /** + * The list of scripts subscribed to this components actions + */ + std::map<LWOOBJID, CppScripts::Script*> m_SubscribedScripts; }; #endif // DESTROYABLECOMPONENT_H diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 8215664c..eeb6afa7 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -27,8 +27,9 @@ #include "dConfig.h" #include "eItemType.h" #include "eUnequippableActiveType.h" +#include "CppScripts.h" -InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document) : Component(parent) { +InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document): Component(parent) { this->m_Dirty = true; this->m_Equipped = {}; this->m_Pushed = {}; @@ -867,6 +868,8 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { AddItemSkills(item->GetLot()); + EquipScripts(item); + EntityManager::Instance()->SerializeEntity(m_Parent); } @@ -895,6 +898,8 @@ void InventoryComponent::UnEquipItem(Item* item) { PurgeProxies(item); + UnequipScripts(item); + EntityManager::Instance()->SerializeEntity(m_Parent); // Trigger property event @@ -904,6 +909,37 @@ void InventoryComponent::UnEquipItem(Item* item) { } } + +void InventoryComponent::EquipScripts(Item* equippedItem) { + CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + if (!compRegistryTable) return; + int32_t scriptComponentID = compRegistryTable->GetByIDAndType(equippedItem->GetLot(), COMPONENT_TYPE_SCRIPT, -1); + if (scriptComponentID > -1) { + CDScriptComponentTable* scriptCompTable = CDClientManager::Instance()->GetTable<CDScriptComponentTable>("ScriptComponent"); + CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); + auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name); + if (!itemScript) { + Game::logger->Log("InventoryComponent", "null script?"); + } + itemScript->OnFactionTriggerItemEquipped(m_Parent, equippedItem->GetId()); + } +} + +void InventoryComponent::UnequipScripts(Item* unequippedItem) { + CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + if (!compRegistryTable) return; + int32_t scriptComponentID = compRegistryTable->GetByIDAndType(unequippedItem->GetLot(), COMPONENT_TYPE_SCRIPT, -1); + if (scriptComponentID > -1) { + CDScriptComponentTable* scriptCompTable = CDClientManager::Instance()->GetTable<CDScriptComponentTable>("ScriptComponent"); + CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); + auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name); + if (!itemScript) { + Game::logger->Log("InventoryComponent", "null script?"); + } + itemScript->OnFactionTriggerItemUnequipped(m_Parent, unequippedItem->GetId()); + } +} + void InventoryComponent::HandlePossession(Item* item) { auto* characterComponent = m_Parent->GetComponent<CharacterComponent>(); if (!characterComponent) return; diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index 8ae35f6c..44636d95 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -352,6 +352,20 @@ public: */ static uint32_t FindSkill(LOT lot); + /** + * Call this when you equip an item. This calls OnFactionTriggerItemEquipped for any scripts found on the items. + * + * @param equippedItem The item script to lookup and call equip on + */ + void EquipScripts(Item* equippedItem); + + /** + * Call this when you unequip an item. This calls OnFactionTriggerItemUnequipped for any scripts found on the items. + * + * @param unequippedItem The item script to lookup and call unequip on + */ + void UnequipScripts(Item* unequippedItem); + ~InventoryComponent() override; private: diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index fce3b721..ac600dbc 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -39,6 +39,12 @@ foreach(file ${DSCRIPTS_SOURCES_EQUIPMENTSCRIPTS}) set(DSCRIPTS_SOURCES ${DSCRIPTS_SOURCES} "EquipmentScripts/${file}") endforeach() +add_subdirectory(EquipmentTriggers) + +foreach(file ${DSCRIPTS_SOURCES_EQUIPMENTTRIGGERSSCRIPTS}) + set(DSCRIPTS_SOURCES ${DSCRIPTS_SOURCES} "EquipmentTriggers/${file}") +endforeach() + add_subdirectory(zone) foreach(file ${DSCRIPTS_SOURCES_ZONE}) diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index dce77e4b..745a74ae 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -278,6 +278,9 @@ #include "ImaginationBackpackHealServer.h" #include "LegoDieRoll.h" #include "BuccaneerValiantShip.h" +#include "GemPack.h" +#include "ShardArmor.h" +#include "TeslaPack.h" // Survival scripts #include "AgSurvivalStromling.h" @@ -837,6 +840,12 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new BuccaneerValiantShip(); else if (scriptName == "scripts\\EquipmentScripts\\FireFirstSkillonStartup.lua") script = new FireFirstSkillonStartup(); + else if (scriptName == "scripts\\equipmenttriggers\\gempack.lua") + script = new GemPack(); + else if (scriptName == "scripts\\equipmenttriggers\\shardarmor.lua") + script = new ShardArmor(); + else if (scriptName == "scripts\\equipmenttriggers\\coilbackpack.lua") + script = new TeslaPack(); // FB else if (scriptName == "scripts\\ai\\NS\\WH\\L_ROCKHYDRANT_BROKEN.lua") diff --git a/dScripts/CppScripts.h b/dScripts/CppScripts.h index 916d2638..e4a6d655 100644 --- a/dScripts/CppScripts.h +++ b/dScripts/CppScripts.h @@ -172,6 +172,13 @@ namespace CppScripts { */ virtual void OnHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) {}; + /** + * Invoked when self has received either a hit or heal. Only used for scripts subscribed to an entity. + * + * Equivalent to 'function notifyHitOrHealResult(self, msg)' + */ + virtual void NotifyHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) {}; + /** * Invoked when a player has responsed to a mission. * @@ -316,6 +323,22 @@ namespace CppScripts { virtual void OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, float_t pathTime, float_t totalTime, int32_t waypoint) { }; + + /** + * Used by items to tell their owner that they were equipped. + * + * @param itemOwner The owner of the item + * @param itemObjId The items Object ID + */ + virtual void OnFactionTriggerItemEquipped(Entity* itemOwner, LWOOBJID itemObjId) {}; + + /** + * Used by items to tell their owner that they were unequipped. + * + * @param itemOwner The owner of the item + * @param itemObjId The items Object ID + */ + virtual void OnFactionTriggerItemUnequipped(Entity* itemOwner, LWOOBJID itemObjId) {}; }; Script* GetScript(Entity* parent, const std::string& scriptName); diff --git a/dScripts/EquipmentTriggers/CMakeLists.txt b/dScripts/EquipmentTriggers/CMakeLists.txt new file mode 100644 index 00000000..416ef553 --- /dev/null +++ b/dScripts/EquipmentTriggers/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_EQUIPMENTTRIGGERSSCRIPTS + "CoilBackpackBase.cpp" + PARENT_SCOPE) diff --git a/dScripts/EquipmentTriggers/CoilBackpackBase.cpp b/dScripts/EquipmentTriggers/CoilBackpackBase.cpp new file mode 100644 index 00000000..d3102e0e --- /dev/null +++ b/dScripts/EquipmentTriggers/CoilBackpackBase.cpp @@ -0,0 +1,25 @@ +#include "CoilBackpackBase.h" + +#include "Entity.h" +#include "SkillComponent.h" + +void CoilBackpackBase::OnFactionTriggerItemEquipped(Entity* itemOwner, LWOOBJID itemObjId) { + itemOwner->Subscribe(itemObjId, this, "HitOrHealResult"); + itemOwner->SetVar<uint8_t>(u"coilCount", 0); +} + +void CoilBackpackBase::NotifyHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) { + if (damage > 0) { + self->SetVar<uint8_t>(u"coilCount", self->GetVar<uint8_t>(u"coilCount") + 1); + if (self->GetVar<uint8_t>(u"coilCount") > 4) { + auto* skillComponent = self->GetComponent<SkillComponent>(); + if (!skillComponent) return; + skillComponent->CalculateBehavior(m_SkillId, m_BehaviorId, self->GetObjectID()); + self->SetVar<uint8_t>(u"coilCount", 0); + } + } +} + +void CoilBackpackBase::OnFactionTriggerItemUnequipped(Entity* itemOwner, LWOOBJID itemObjId) { + itemOwner->Unsubscribe(itemObjId, "HitOrHealResult"); +} diff --git a/dScripts/EquipmentTriggers/CoilBackpackBase.h b/dScripts/EquipmentTriggers/CoilBackpackBase.h new file mode 100644 index 00000000..290c6c0f --- /dev/null +++ b/dScripts/EquipmentTriggers/CoilBackpackBase.h @@ -0,0 +1,21 @@ +#ifndef __GemPackBase__H__ +#define __GemPackBase__H__ + +#include "CppScripts.h" + +class CoilBackpackBase: public CppScripts::Script { +public: + CoilBackpackBase(uint32_t skillId, uint32_t behaviorId) { + m_SkillId = skillId; + m_BehaviorId = behaviorId; + }; + + void OnFactionTriggerItemEquipped(Entity* itemOwner, LWOOBJID itemObjId) override; + void NotifyHitOrHealResult(Entity* self, Entity* attacker, int32_t damage) override; + void OnFactionTriggerItemUnequipped(Entity* itemOwner, LWOOBJID itemObjId) override; +private: + uint32_t m_SkillId = 0; + uint32_t m_BehaviorId = 0; +}; + +#endif //!__GemPackBase__H__ diff --git a/dScripts/EquipmentTriggers/GemPack.h b/dScripts/EquipmentTriggers/GemPack.h new file mode 100644 index 00000000..13bf7b0b --- /dev/null +++ b/dScripts/EquipmentTriggers/GemPack.h @@ -0,0 +1,14 @@ +#ifndef __GEMPACK__H__ +#define __GEMPACK__H__ + +#include "CoilBackpackBase.h" + +class GemPack : public CoilBackpackBase { +public: + GemPack() : CoilBackpackBase(skillId, behaviorId) {}; +private: + static const uint32_t skillId = 1488; + static const uint32_t behaviorId = 36779; +}; + +#endif //!__GEMPACK__H__ diff --git a/dScripts/EquipmentTriggers/ShardArmor.h b/dScripts/EquipmentTriggers/ShardArmor.h new file mode 100644 index 00000000..01d2fe33 --- /dev/null +++ b/dScripts/EquipmentTriggers/ShardArmor.h @@ -0,0 +1,14 @@ +#ifndef __SHARDARMOR__H__ +#define __SHARDARMOR__H__ + +#include "CoilBackpackBase.h" + +class ShardArmor : public CoilBackpackBase { +public: + ShardArmor() : CoilBackpackBase(skillId, behaviorId) {}; +private: + static const uint32_t skillId = 1249; + static const uint32_t behaviorId = 29086; +}; + +#endif //!__SHARDARMOR__H__ diff --git a/dScripts/EquipmentTriggers/TeslaPack.h b/dScripts/EquipmentTriggers/TeslaPack.h new file mode 100644 index 00000000..6e8bc9a4 --- /dev/null +++ b/dScripts/EquipmentTriggers/TeslaPack.h @@ -0,0 +1,14 @@ +#ifndef __TESLAPACK__H__ +#define __TESLAPACK__H__ + +#include "CoilBackpackBase.h" + +class TeslaPack : public CoilBackpackBase { +public: + TeslaPack() : CoilBackpackBase(skillId, behaviorId) {}; +private: + static const uint32_t skillId = 1001; + static const uint32_t behaviorId = 20917; +}; + +#endif //!__TESLAPACK__H__ From fd9757d1215dd6dafe6431aa4aeb556902f3c4b2 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 21 Dec 2022 22:34:11 -0800 Subject: [PATCH 195/322] Implement a server res directory for server required client files (#891) --- CMakeLists.txt | 4 +- dCommon/FdbToSqlite.cpp | 73 +++++++++++---------- dCommon/FdbToSqlite.h | 116 +++++++++++++++++++++++++++++++-- dMasterServer/MasterServer.cpp | 40 ++++++++---- dWorldServer/WorldServer.cpp | 2 +- 5 files changed, 176 insertions(+), 59 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b9596649..54f0d0dd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -89,8 +89,8 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) -# Create a /res directory -make_directory(${CMAKE_BINARY_DIR}/res) +# Create a /resServer directory +make_directory(${CMAKE_BINARY_DIR}/resServer) # Create a /logs directory make_directory(${CMAKE_BINARY_DIR}/logs) diff --git a/dCommon/FdbToSqlite.cpp b/dCommon/FdbToSqlite.cpp index 6015fd3a..80251e89 100644 --- a/dCommon/FdbToSqlite.cpp +++ b/dCommon/FdbToSqlite.cpp @@ -13,7 +13,7 @@ #include "eSqliteDataType.h" -std::map<eSqliteDataType, std::string> FdbToSqlite::Convert::sqliteType = { +std::map<eSqliteDataType, std::string> FdbToSqlite::Convert::m_SqliteType = { { eSqliteDataType::NONE, "none"}, { eSqliteDataType::INT32, "int32"}, { eSqliteDataType::REAL, "real"}, @@ -23,15 +23,21 @@ std::map<eSqliteDataType, std::string> FdbToSqlite::Convert::sqliteType = { { eSqliteDataType::TEXT_8, "text_8"} }; -FdbToSqlite::Convert::Convert(std::string basePath) { - this->basePath = basePath; +FdbToSqlite::Convert::Convert(std::string basePath, std::string binaryOutPath) { + this->m_BasePath = basePath; + this->m_BinaryOutPath = binaryOutPath; + m_Fdb.open(m_BasePath + "/cdclient.fdb", std::ios::binary); +} + +FdbToSqlite::Convert::~Convert() { + this->m_Fdb.close(); } bool FdbToSqlite::Convert::ConvertDatabase() { - fdb.open(basePath + "/cdclient.fdb", std::ios::binary); - + if (m_ConversionStarted) return false; + this->m_ConversionStarted = true; try { - CDClientDatabase::Connect(basePath + "/CDServer.sqlite"); + CDClientDatabase::Connect(m_BinaryOutPath + "/CDServer.sqlite"); CDClientDatabase::ExecuteQuery("BEGIN TRANSACTION;"); @@ -44,13 +50,12 @@ bool FdbToSqlite::Convert::ConvertDatabase() { return false; } - fdb.close(); return true; } int32_t FdbToSqlite::Convert::ReadInt32() { int32_t nextInt{}; - BinaryIO::BinaryRead(fdb, nextInt); + BinaryIO::BinaryRead(m_Fdb, nextInt); return nextInt; } @@ -58,26 +63,26 @@ int64_t FdbToSqlite::Convert::ReadInt64() { int32_t prevPosition = SeekPointer(); int64_t value{}; - BinaryIO::BinaryRead(fdb, value); + BinaryIO::BinaryRead(m_Fdb, value); - fdb.seekg(prevPosition); + m_Fdb.seekg(prevPosition); return value; } std::string FdbToSqlite::Convert::ReadString() { int32_t prevPosition = SeekPointer(); - auto readString = BinaryIO::ReadString(fdb); + auto readString = BinaryIO::ReadString(m_Fdb); - fdb.seekg(prevPosition); + m_Fdb.seekg(prevPosition); return readString; } int32_t FdbToSqlite::Convert::SeekPointer() { int32_t position{}; - BinaryIO::BinaryRead(fdb, position); - int32_t prevPosition = fdb.tellg(); - fdb.seekg(position); + BinaryIO::BinaryRead(m_Fdb, position); + int32_t prevPosition = m_Fdb.tellg(); + m_Fdb.seekg(position); return prevPosition; } @@ -91,7 +96,7 @@ std::string FdbToSqlite::Convert::ReadColumnHeader() { std::string newTable = "CREATE TABLE IF NOT EXISTS '" + tableName + "' (" + columns + ");"; CDClientDatabase::ExecuteDML(newTable); - fdb.seekg(prevPosition); + m_Fdb.seekg(prevPosition); return tableName; } @@ -104,7 +109,7 @@ void FdbToSqlite::Convert::ReadTables(int32_t& numberOfTables) { ReadRowHeader(columnHeader); } - fdb.seekg(prevPosition); + m_Fdb.seekg(prevPosition); } std::string FdbToSqlite::Convert::ReadColumns(int32_t& numberOfColumns) { @@ -117,10 +122,10 @@ std::string FdbToSqlite::Convert::ReadColumns(int32_t& numberOfColumns) { if (i != 0) columnsToCreate << ", "; dataType = static_cast<eSqliteDataType>(ReadInt32()); name = ReadString(); - columnsToCreate << "'" << name << "' " << FdbToSqlite::Convert::sqliteType[dataType]; + columnsToCreate << "'" << name << "' " << FdbToSqlite::Convert::m_SqliteType[dataType]; } - fdb.seekg(prevPosition); + m_Fdb.seekg(prevPosition); return columnsToCreate.str(); } @@ -131,7 +136,7 @@ void FdbToSqlite::Convert::ReadRowHeader(std::string& tableName) { if (numberOfAllocatedRows != 0) assert((numberOfAllocatedRows & (numberOfAllocatedRows - 1)) == 0); // assert power of 2 allocation size ReadRows(numberOfAllocatedRows, tableName); - fdb.seekg(prevPosition); + m_Fdb.seekg(prevPosition); } void FdbToSqlite::Convert::ReadRows(int32_t& numberOfAllocatedRows, std::string& tableName) { @@ -141,28 +146,24 @@ void FdbToSqlite::Convert::ReadRows(int32_t& numberOfAllocatedRows, std::string& for (int32_t row = 0; row < numberOfAllocatedRows; row++) { int32_t rowPointer = ReadInt32(); if (rowPointer == -1) rowid++; - else ReadRow(rowid, rowPointer, tableName); + else ReadRow(rowPointer, tableName); } - fdb.seekg(prevPosition); + m_Fdb.seekg(prevPosition); } -void FdbToSqlite::Convert::ReadRow(int32_t& rowid, int32_t& position, std::string& tableName) { - int32_t prevPosition = fdb.tellg(); - fdb.seekg(position); +void FdbToSqlite::Convert::ReadRow(int32_t& position, std::string& tableName) { + int32_t prevPosition = m_Fdb.tellg(); + m_Fdb.seekg(position); while (true) { ReadRowInfo(tableName); int32_t linked = ReadInt32(); - - rowid += 1; - if (linked == -1) break; - - fdb.seekg(linked); + m_Fdb.seekg(linked); } - fdb.seekg(prevPosition); + m_Fdb.seekg(prevPosition); } void FdbToSqlite::Convert::ReadRowInfo(std::string& tableName) { @@ -171,7 +172,7 @@ void FdbToSqlite::Convert::ReadRowInfo(std::string& tableName) { int32_t numberOfColumns = ReadInt32(); ReadRowValues(numberOfColumns, tableName); - fdb.seekg(prevPosition); + m_Fdb.seekg(prevPosition); } void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& tableName) { @@ -191,7 +192,7 @@ void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& if (i != 0) insertedRow << ", "; // Only append comma and space after first entry in row. switch (static_cast<eSqliteDataType>(ReadInt32())) { case eSqliteDataType::NONE: - BinaryIO::BinaryRead(fdb, emptyValue); + BinaryIO::BinaryRead(m_Fdb, emptyValue); assert(emptyValue == 0); insertedRow << "NULL"; break; @@ -202,7 +203,7 @@ void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& break; case eSqliteDataType::REAL: - BinaryIO::BinaryRead(fdb, floatValue); + BinaryIO::BinaryRead(m_Fdb, floatValue); insertedRow << std::fixed << std::setprecision(34) << floatValue; // maximum precision of floating point number break; @@ -224,7 +225,7 @@ void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& } case eSqliteDataType::INT_BOOL: - BinaryIO::BinaryRead(fdb, boolValue); + BinaryIO::BinaryRead(m_Fdb, boolValue); insertedRow << static_cast<bool>(boolValue); break; @@ -244,5 +245,5 @@ void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& auto copiedString = insertedRow.str(); CDClientDatabase::ExecuteDML(copiedString); - fdb.seekg(prevPosition); + m_Fdb.seekg(prevPosition); } diff --git a/dCommon/FdbToSqlite.h b/dCommon/FdbToSqlite.h index a9611220..cfa5263b 100644 --- a/dCommon/FdbToSqlite.h +++ b/dCommon/FdbToSqlite.h @@ -12,38 +12,142 @@ enum class eSqliteDataType : int32_t; namespace FdbToSqlite { class Convert { public: - Convert(std::string inputFile); + /** + * Create a new convert object with an input .fdb file and an output binary path. + * + * @param inputFile The file which ends in .fdb to be converted + * @param binaryPath The base path where the file will be saved + */ + Convert(std::string inputFile, std::string binaryOutPath); + /** + * Destroy the convert object and close the fdb file. + */ + ~Convert(); + + /** + * Converts the input file to sqlite. Calling multiple times is safe. + * + * @return true if the database was converted properly, false otherwise. + */ bool ConvertDatabase(); + /** + * @brief Reads a 32 bit int from the fdb file. + * + * @return The read value + */ int32_t ReadInt32(); + /** + * @brief Reads a 64 bit integer from the fdb file. + * + * @return The read value + */ int64_t ReadInt64(); + /** + * @brief Reads a string from the fdb file. + * + * @return The read string + * + * TODO This needs to be translated to latin-1! + */ std::string ReadString(); + /** + * @brief Seeks to a pointer position. + * + * @return The previous position before the seek + */ int32_t SeekPointer(); + /** + * @brief Reads a column header from the fdb file and creates the table in the database + * + * @return The table name + */ std::string ReadColumnHeader(); + /** + * @brief Read the tables from the fdb file. + * + * @param numberOfTables The number of tables to read + */ void ReadTables(int32_t& numberOfTables); + /** + * @brief Reads the columns from the fdb file. + * + * @param numberOfColumns The number of columns to read + * @return All columns of the table formatted for a sql query + */ std::string ReadColumns(int32_t& numberOfColumns); + /** + * @brief Reads the row header from the fdb file. + * + * @param tableName The tables name + */ void ReadRowHeader(std::string& tableName); + /** + * @brief Read the rows from the fdb file., + * + * @param numberOfAllocatedRows The number of rows that were allocated. Always a power of 2! + * @param tableName The tables name. + */ void ReadRows(int32_t& numberOfAllocatedRows, std::string& tableName); - void ReadRow(int32_t& rowid, int32_t& position, std::string& tableName); + /** + * @brief Reads a row from the fdb file. + * + * @param position The position to seek in the fdb to + * @param tableName The tables name + */ + void ReadRow(int32_t& position, std::string& tableName); + /** + * @brief Reads the row info from the fdb file. + * + * @param tableName The tables name + */ void ReadRowInfo(std::string& tableName); + /** + * @brief Reads each row and its values from the fdb file and inserts them into the database + * + * @param numberOfColumns The number of columns to read in + * @param tableName The tables name + */ void ReadRowValues(int32_t& numberOfColumns, std::string& tableName); private: - static std::map<eSqliteDataType, std::string> sqliteType; - std::string basePath{}; - std::ifstream fdb{}; - }; // class FdbToSqlite + + /** + * Maps each sqlite data type to its string equivalent. + */ + static std::map<eSqliteDataType, std::string> m_SqliteType; + + /** + * Base path of the folder containing the fdb file + */ + std::string m_BasePath{}; + + /** + * ifstream containing the fdb file + */ + std::ifstream m_Fdb{}; + + /** + * Whether or not a conversion was started. If one was started, do not attempt to convert the file again. + */ + bool m_ConversionStarted{}; + + /** + * The path where the CDServer will be stored + */ + std::string m_BinaryOutPath{}; + }; //! class FdbToSqlite }; //! namespace FdbToSqlite #endif //!__FDBTOSQLITE__H__ diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index ba36247c..34ce59c7 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -146,26 +146,38 @@ int main(int argc, char** argv) { MigrationRunner::RunMigrations(); - // Check CDClient exists - if (!std::filesystem::exists(Game::assetManager->GetResPath() / "CDServer.sqlite")) { - Game::logger->Log("WorldServer", "CDServer.sqlite could not be opened. Looking for cdclient.fdb to convert to sqlite."); + const bool cdServerExists = std::filesystem::exists(BinaryPathFinder::GetBinaryDir() / "resServer" / "CDServer.sqlite"); + const bool oldCDServerExists = std::filesystem::exists(Game::assetManager->GetResPath() / "CDServer.sqlite"); + const bool fdbExists = std::filesystem::exists(Game::assetManager->GetResPath() / "cdclient.fdb"); - if (!std::filesystem::exists(Game::assetManager->GetResPath() / "cdclient.fdb")) { - Game::logger->Log("WorldServer", "cdclient.fdb could not be opened. Please move a cdclient.fdb or an already converted database to build/res."); - return EXIT_FAILURE; - } - - Game::logger->Log("WorldServer", "Found cdclient.fdb. Converting to SQLite"); - - if (FdbToSqlite::Convert(Game::assetManager->GetResPath().string()).ConvertDatabase() == false) { - Game::logger->Log("MasterServer", "Failed to convert fdb to sqlite"); - return EXIT_FAILURE; + if (!cdServerExists) { + if (oldCDServerExists) { + // If the file doesn't exist in the new CDServer location, copy it there. We copy because we may not have write permissions from the previous directory. + Game::logger->Log("MasterServer", "CDServer.sqlite is not located at resServer, but is located at res path. Copying file..."); + std::filesystem::copy_file(Game::assetManager->GetResPath() / "CDServer.sqlite", BinaryPathFinder::GetBinaryDir() / "resServer" / "CDServer.sqlite"); + } else { + Game::logger->Log("WorldServer", + "%s could not be found in resServer or res. Looking for %s to convert to sqlite.", + (BinaryPathFinder::GetBinaryDir() / "resServer" / "CDServer.sqlite").c_str(), + (Game::assetManager->GetResPath() / "cdclient.fdb").c_str()); + if (!fdbExists) { + Game::logger->Log("WorldServer", + "%s could not be opened. Please move cdclient.fdb to %s", + (Game::assetManager->GetResPath() / "cdclient.fdb").c_str(), + (Game::assetManager->GetResPath().c_str())); + return FinalizeShutdown(); + } + Game::logger->Log("WorldServer", "Found cdclient.fdb. Converting to SQLite"); + if (FdbToSqlite::Convert(Game::assetManager->GetResPath().string(), (BinaryPathFinder::GetBinaryDir() / "resServer").string()).ConvertDatabase() == false) { + Game::logger->Log("MasterServer", "Failed to convert fdb to sqlite."); + return FinalizeShutdown(); + } } } //Connect to CDClient try { - CDClientDatabase::Connect((Game::assetManager->GetResPath() / "CDServer.sqlite").string()); + CDClientDatabase::Connect((BinaryPathFinder::GetBinaryDir() / "resServer" / "CDServer.sqlite").string()); } catch (CppSQLite3Exception& e) { Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index adb87ba0..32060a51 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -154,7 +154,7 @@ int main(int argc, char** argv) { // Connect to CDClient try { - CDClientDatabase::Connect((Game::assetManager->GetResPath() / "CDServer.sqlite").string()); + CDClientDatabase::Connect((BinaryPathFinder::GetBinaryDir() / "resServer" / "CDServer.sqlite").string()); } catch (CppSQLite3Exception& e) { Game::logger->Log("WorldServer", "Unable to connect to CDServer SQLite Database"); Game::logger->Log("WorldServer", "Error: %s", e.errorMessage()); From d052ed6a631341d89b9eb395b9936c9a25f9c13e Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 22 Dec 2022 04:06:59 -0800 Subject: [PATCH 196/322] Update MigrationRunner.cpp (#911) --- dDatabase/MigrationRunner.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp index 54def9e2..5e70c401 100644 --- a/dDatabase/MigrationRunner.cpp +++ b/dDatabase/MigrationRunner.cpp @@ -54,7 +54,7 @@ void MigrationRunner::RunMigrations() { if (doExit) continue; Game::logger->Log("MigrationRunner", "Running migration: %s", migration.name.c_str()); - if (migration.name == "5_brick_model_sd0.sql") { + if (migration.name == "dlu/5_brick_model_sd0.sql") { runSd0Migrations = true; } else { finalSQL.append(migration.data.c_str()); From dff02773a0d3904e2682ff483a5d8ae9b44f00fb Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 22 Dec 2022 05:16:08 -0800 Subject: [PATCH 197/322] Fix dragon stuns (#915) --- dScripts/02_server/Enemy/AM/AmDarklingDragon.cpp | 5 ++++- dScripts/02_server/Enemy/FV/FvMaelstromDragon.cpp | 7 ++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/dScripts/02_server/Enemy/AM/AmDarklingDragon.cpp b/dScripts/02_server/Enemy/AM/AmDarklingDragon.cpp index 8ec49d3e..9e0570ef 100644 --- a/dScripts/02_server/Enemy/AM/AmDarklingDragon.cpp +++ b/dScripts/02_server/Enemy/AM/AmDarklingDragon.cpp @@ -63,10 +63,11 @@ void AmDarklingDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t if (skillComponent != nullptr) { skillComponent->Interrupt(); + skillComponent->Reset(); } self->SetVar<int32_t>(u"weakpoint", 2); - + GameMessages::SendChangeIdleFlags(self->GetObjectID(), eAnimationFlags::IDLE_NONE, eAnimationFlags::IDLE_COMBAT, UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendPlayAnimation(self, u"stunstart", 1.7f); self->AddTimer("timeToStunLoop", 1); @@ -131,7 +132,9 @@ void AmDarklingDragon::OnTimerDone(Entity* self, std::string timerName) { } if (skillComponent != nullptr) { skillComponent->Interrupt(); + skillComponent->Reset(); } + GameMessages::SendChangeIdleFlags(self->GetObjectID(), eAnimationFlags::IDLE_COMBAT, eAnimationFlags::IDLE_NONE, UNASSIGNED_SYSTEM_ADDRESS); self->SetVar<int32_t>(u"weakspot", -1); GameMessages::SendNotifyObject(self->GetObjectID(), self->GetObjectID(), u"DragonRevive", UNASSIGNED_SYSTEM_ADDRESS); } diff --git a/dScripts/02_server/Enemy/FV/FvMaelstromDragon.cpp b/dScripts/02_server/Enemy/FV/FvMaelstromDragon.cpp index 47ddb4bf..ec513694 100644 --- a/dScripts/02_server/Enemy/FV/FvMaelstromDragon.cpp +++ b/dScripts/02_server/Enemy/FV/FvMaelstromDragon.cpp @@ -59,8 +59,6 @@ void FvMaelstromDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_ auto* destroyableComponent = self->GetComponent<DestroyableComponent>(); if (destroyableComponent != nullptr) { - Game::logger->Log("FvMaelstromDragon", "Hit %i", destroyableComponent->GetArmor()); - if (destroyableComponent->GetArmor() > 0) return; auto weakpoint = self->GetVar<int32_t>(u"weakpoint"); @@ -80,10 +78,12 @@ void FvMaelstromDragon::OnHitOrHealResult(Entity* self, Entity* attacker, int32_ if (skillComponent != nullptr) { skillComponent->Interrupt(); + skillComponent->Reset(); } self->SetVar<int32_t>(u"weakpoint", 2); + GameMessages::SendChangeIdleFlags(self->GetObjectID(), eAnimationFlags::IDLE_NONE, eAnimationFlags::IDLE_COMBAT, UNASSIGNED_SYSTEM_ADDRESS); GameMessages::SendPlayAnimation(self, u"stunstart", 1.7f); self->AddTimer("timeToStunLoop", 1); @@ -150,8 +150,9 @@ void FvMaelstromDragon::OnTimerDone(Entity* self, std::string timerName) { if (skillComponent != nullptr) { skillComponent->Interrupt(); + skillComponent->Reset(); } - + GameMessages::SendChangeIdleFlags(self->GetObjectID(), eAnimationFlags::IDLE_COMBAT, eAnimationFlags::IDLE_NONE, UNASSIGNED_SYSTEM_ADDRESS); self->SetVar<int32_t>(u"weakspot", -1); GameMessages::SendNotifyObject(self->GetObjectID(), self->GetObjectID(), u"DragonRevive", UNASSIGNED_SYSTEM_ADDRESS); From 015cbc06ea020c391bce22d1d6c56023c2daa84e Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 22 Dec 2022 05:16:18 -0800 Subject: [PATCH 198/322] Fix racing spawn positions (#913) --- dGame/dComponents/RacingControlComponent.cpp | 47 +++++++------------- dGame/dComponents/RacingControlComponent.h | 2 +- 2 files changed, 17 insertions(+), 32 deletions(-) diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 75465669..4b5743cd 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -98,7 +98,7 @@ void RacingControlComponent::OnPlayerLoaded(Entity* player) { } void RacingControlComponent::LoadPlayerVehicle(Entity* player, - bool initialLoad) { + uint32_t positionNumber, bool initialLoad) { // Load the player's vehicle. if (player == nullptr) { @@ -126,33 +126,18 @@ void RacingControlComponent::LoadPlayerVehicle(Entity* player, auto* path = dZoneManager::Instance()->GetZone()->GetPath( GeneralUtils::UTF16ToWTF8(m_PathName)); - auto startPosition = path->pathWaypoints[0].position + NiPoint3::UNIT_Y * 3; - - const auto spacing = 15; - - // This sometimes spawns the vehicle out of the map if there are lots of - // players loaded. - - const auto range = m_LoadedPlayers * spacing; - - startPosition = - startPosition + NiPoint3::UNIT_Z * ((m_LeadingPlayer / 2) + - m_RacingPlayers.size() * spacing); - - auto startRotation = - NiQuaternion::LookAt(startPosition, startPosition + NiPoint3::UNIT_X); - - auto angles = startRotation.GetEulerAngles(); - - angles.y -= M_PI; - - startRotation = NiQuaternion::FromEulerAngles(angles); - - Game::logger->Log("RacingControlComponent", - "Start position <%f, %f, %f>, <%f, %f, %f>", - startPosition.x, startPosition.y, startPosition.z, - angles.x * (180.0f / M_PI), angles.y * (180.0f / M_PI), - angles.z * (180.0f / M_PI)); + auto spawnPointEntities = EntityManager::Instance()->GetEntitiesByLOT(4843); + auto startPosition = NiPoint3::ZERO; + auto startRotation = NiQuaternion::IDENTITY; + const std::string placementAsString = std::to_string(positionNumber); + for (auto entity : spawnPointEntities) { + if (!entity) continue; + if (entity->GetVarAsString(u"placement") == placementAsString) { + startPosition = entity->GetPosition(); + startRotation = entity->GetRotation(); + break; + } + } // Make sure the player is at the correct position. @@ -567,12 +552,12 @@ void RacingControlComponent::Update(float deltaTime) { Game::logger->Log("RacingControlComponent", "Loading all players..."); - for (size_t i = 0; i < m_LobbyPlayers.size(); i++) { + for (size_t positionNumber = 0; positionNumber < m_LobbyPlayers.size(); positionNumber++) { Game::logger->Log("RacingControlComponent", "Loading player now!"); auto* player = - EntityManager::Instance()->GetEntity(m_LobbyPlayers[i]); + EntityManager::Instance()->GetEntity(m_LobbyPlayers[positionNumber]); if (player == nullptr) { return; @@ -581,7 +566,7 @@ void RacingControlComponent::Update(float deltaTime) { Game::logger->Log("RacingControlComponent", "Loading player now NOW!"); - LoadPlayerVehicle(player, true); + LoadPlayerVehicle(player, positionNumber + 1, true); m_Loaded = true; } diff --git a/dGame/dComponents/RacingControlComponent.h b/dGame/dComponents/RacingControlComponent.h index dac60962..933178cc 100644 --- a/dGame/dComponents/RacingControlComponent.h +++ b/dGame/dComponents/RacingControlComponent.h @@ -123,7 +123,7 @@ public: * @param player The player who's vehicle to initialize. * @param initialLoad Is this the first time the player is loading in this race? */ - void LoadPlayerVehicle(Entity* player, bool initialLoad = false); + void LoadPlayerVehicle(Entity* player, uint32_t positionNumber, bool initialLoad = false); /** * Invoked when the client says it has loaded in. From 96313ecd695de9ad60b4634ea90919fa4f2f4328 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 22 Dec 2022 05:16:35 -0800 Subject: [PATCH 199/322] Calculate world shutdown timer (#910) --- dWorldServer/WorldServer.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 32060a51..de6deb2a 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -296,6 +296,7 @@ int main(int argc, char** argv) { uint32_t chatReconnectionTime = 30 * currentFramerate; // 30 seconds in frames uint32_t saveTime = 10 * 60 * currentFramerate; // 10 minutes in frames uint32_t sqlPingTime = 10 * 60 * currentFramerate; // 10 minutes in frames + uint32_t emptyShutdownTime = (cloneID == 0 ? 30 : 5) * 60 * currentFramerate; // 30 minutes for main worlds, 5 for all others. while (true) { Metrics::StartMeasurement(MetricVariable::Frame); Metrics::StartMeasurement(MetricVariable::GameLoop); @@ -333,6 +334,8 @@ int main(int argc, char** argv) { framesSinceLastUsersSave *= ratioBeforeToAfter; sqlPingTime = 10 * 60 * currentFramerate; // 10 minutes in frames framesSinceLastSQLPing *= ratioBeforeToAfter; + emptyShutdownTime = (cloneID == 0 ? 30 : 5) * 60 * currentFramerate; // 30 minutes for main worlds, 5 for all others. + framesSinceLastUser *= ratioBeforeToAfter; } //Warning if we ran slow @@ -440,7 +443,7 @@ int main(int argc, char** argv) { framesSinceLastUser++; //If we haven't had any players for a while, time out and shut down: - if (framesSinceLastUser == (cloneID != 0 ? 4000 : 40000)) { + if (framesSinceLastUser >= emptyShutdownTime) { Game::shouldShutdown = true; } } else { From 9ebb06ba24d3b7e26d6270d7efbaa46ee975cfee Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 22 Dec 2022 07:24:59 -0600 Subject: [PATCH 200/322] Qb team credit (#912) * give credit to whole team for qb's * fix compiling --- dGame/dComponents/RebuildComponent.cpp | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/dGame/dComponents/RebuildComponent.cpp b/dGame/dComponents/RebuildComponent.cpp index 6ec9b964..c7c4e3a5 100644 --- a/dGame/dComponents/RebuildComponent.cpp +++ b/dGame/dComponents/RebuildComponent.cpp @@ -14,6 +14,7 @@ #include "Spawner.h" #include "MovingPlatformComponent.h" #include "Preconditions.h" +#include "TeamManager.h" #include "CppScripts.h" @@ -464,12 +465,20 @@ void RebuildComponent::CompleteRebuild(Entity* user) { auto* builder = GetBuilder(); - if (builder != nullptr) { - auto* missionComponent = builder->GetComponent<MissionComponent>(); - if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ACTIVITY, m_ActivityId); + if (builder) { + auto* team = TeamManager::Instance()->GetTeam(builder->GetObjectID()); + if (team) { + for (const auto memberId : team->members) { // progress missions for all team members + auto* member = EntityManager::Instance()->GetEntity(memberId); + if (member) { + auto* missionComponent = member->GetComponent<MissionComponent>(); + if (missionComponent) missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ACTIVITY, m_ActivityId); + } + } + } else{ + auto* missionComponent = builder->GetComponent<MissionComponent>(); + if (missionComponent) missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ACTIVITY, m_ActivityId); } - LootGenerator::Instance().DropActivityLoot(builder, m_Parent, m_ActivityId, 1); } From 675cf1d2a4f5a6955959e4884193fd733ea6185f Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 22 Dec 2022 22:14:51 -0800 Subject: [PATCH 201/322] Fix baseEnemyApe stuns and fix IdleFlags serialization (#914) * Fix baseEnemyApe stuns * Correct serialization --- dGame/dGameMessages/GameMessages.cpp | 8 +++++--- dScripts/02_server/Enemy/General/BaseEnemyApe.cpp | 8 ++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 9753868d..c3b86647 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -3924,14 +3924,16 @@ void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string } -void GameMessages::SendChangeIdleFlags(LWOOBJID objectId, eAnimationFlags FlagsOn, eAnimationFlags FlagsOff, const SystemAddress& sysAddr) { +void GameMessages::SendChangeIdleFlags(LWOOBJID objectId, eAnimationFlags flagsOn, eAnimationFlags flagsOff, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; bitStream.Write(objectId); bitStream.Write(GAME_MSG::GAME_MSG_CHANGE_IDLE_FLAGS); - bitStream.Write(FlagsOff); - bitStream.Write(FlagsOn); + bitStream.Write<bool>(flagsOff != eAnimationFlags::IDLE_NONE); + if (flagsOff != eAnimationFlags::IDLE_NONE) bitStream.Write(flagsOff); + bitStream.Write<bool>(flagsOn != eAnimationFlags::IDLE_NONE); + if (flagsOn != eAnimationFlags::IDLE_NONE) bitStream.Write(flagsOn); SEND_PACKET_BROADCAST; } diff --git a/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp b/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp index 3d0b8e25..96419c08 100644 --- a/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp +++ b/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp @@ -31,9 +31,12 @@ void BaseEnemyApe::OnHit(Entity* self, Entity* attacker) { if (destroyableComponent != nullptr && destroyableComponent->GetArmor() < 1 && !self->GetBoolean(u"knockedOut")) { StunApe(self, true); self->CancelTimer("spawnQBTime"); - + auto* skillComponent = self->GetComponent<SkillComponent>(); + if (skillComponent) { + skillComponent->Reset(); + } GameMessages::SendPlayAnimation(self, u"disable", 1.7f); - + GameMessages::SendChangeIdleFlags(self->GetObjectID(), eAnimationFlags::IDLE_NONE, eAnimationFlags::IDLE_COMBAT, UNASSIGNED_SYSTEM_ADDRESS); const auto reviveTime = self->GetVar<float_t>(u"reviveTime") != 0.0f ? self->GetVar<float_t>(u"reviveTime") : 12.0f; self->AddTimer("reviveTime", reviveTime); @@ -50,6 +53,7 @@ void BaseEnemyApe::OnTimerDone(Entity* self, std::string timerName) { destroyableComponent->SetArmor(destroyableComponent->GetMaxArmor() / timesStunned); } EntityManager::Instance()->SerializeEntity(self); + GameMessages::SendChangeIdleFlags(self->GetObjectID(), eAnimationFlags::IDLE_COMBAT, eAnimationFlags::IDLE_NONE, UNASSIGNED_SYSTEM_ADDRESS); self->SetVar<uint32_t>(u"timesStunned", timesStunned + 1); StunApe(self, false); From bbd5a49ea2c682469a1c3f48e418c93d932dec1c Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 23 Dec 2022 18:05:30 -0800 Subject: [PATCH 202/322] Update DarkInspirationBehavior.cpp (#897) --- dGame/dBehaviors/AreaOfEffectBehavior.cpp | 5 +- dGame/dBehaviors/Behavior.cpp | 5 +- dGame/dBehaviors/CMakeLists.txt | 1 + dGame/dBehaviors/DarkInspirationBehavior.cpp | 52 ++++++++++++++++++++ dGame/dBehaviors/DarkInspirationBehavior.h | 22 +++++++++ dGame/dComponents/DestroyableComponent.cpp | 2 +- dGame/dComponents/InventoryComponent.cpp | 4 +- dGame/dComponents/InventoryComponent.h | 2 +- dGame/dInventory/ItemSet.cpp | 4 +- dGame/dInventory/ItemSet.h | 2 +- dGame/dInventory/ItemSetPassiveAbility.cpp | 14 +++--- dGame/dInventory/ItemSetPassiveAbility.h | 6 +-- 12 files changed, 98 insertions(+), 21 deletions(-) create mode 100644 dGame/dBehaviors/DarkInspirationBehavior.cpp create mode 100644 dGame/dBehaviors/DarkInspirationBehavior.h diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.cpp b/dGame/dBehaviors/AreaOfEffectBehavior.cpp index ca3bdf93..dedede2a 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.cpp +++ b/dGame/dBehaviors/AreaOfEffectBehavior.cpp @@ -48,9 +48,8 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* self = EntityManager::Instance()->GetEntity(context->caster); - if (self == nullptr) { - Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!", context->originator); + Game::logger->Log("AreaOfEffectBehavior", "Invalid self for (%llu)!", context->originator); return; } @@ -79,7 +78,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream auto* entity = EntityManager::Instance()->GetEntity(validTarget); if (entity == nullptr) { - Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!", validTarget, context->originator); + Game::logger->Log("AreaOfEffectBehavior", "Invalid target (%llu) for (%llu)!", validTarget, context->originator); continue; } diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index cd9304d3..568780d0 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -61,6 +61,7 @@ #include "DamageReductionBehavior.h" #include "JetPackBehavior.h" #include "ChangeIdleFlagsBehavior.h" +#include "DarkInspirationBehavior.h" //CDClient includes #include "CDBehaviorParameterTable.h" @@ -169,7 +170,9 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) { case BehaviorTemplates::BEHAVIOR_SPEED: behavior = new SpeedBehavior(behaviorId); break; - case BehaviorTemplates::BEHAVIOR_DARK_INSPIRATION: break; + case BehaviorTemplates::BEHAVIOR_DARK_INSPIRATION: + behavior = new DarkInspirationBehavior(behaviorId); + break; case BehaviorTemplates::BEHAVIOR_LOOT_BUFF: behavior = new LootBuffBehavior(behaviorId); break; diff --git a/dGame/dBehaviors/CMakeLists.txt b/dGame/dBehaviors/CMakeLists.txt index 40ac0a9c..e274872d 100644 --- a/dGame/dBehaviors/CMakeLists.txt +++ b/dGame/dBehaviors/CMakeLists.txt @@ -18,6 +18,7 @@ set(DGAME_DBEHAVIORS_SOURCES "AirMovementBehavior.cpp" "ClearTargetBehavior.cpp" "DamageAbsorptionBehavior.cpp" "DamageReductionBehavior.cpp" + "DarkInspirationBehavior.cpp" "DurationBehavior.cpp" "EmptyBehavior.cpp" "EndBehavior.cpp" diff --git a/dGame/dBehaviors/DarkInspirationBehavior.cpp b/dGame/dBehaviors/DarkInspirationBehavior.cpp new file mode 100644 index 00000000..ea80cbba --- /dev/null +++ b/dGame/dBehaviors/DarkInspirationBehavior.cpp @@ -0,0 +1,52 @@ +#include "DarkInspirationBehavior.h" + +#include "BehaviorBranchContext.h" +#include "Entity.h" +#include "DestroyableComponent.h" +#include "EntityManager.h" +#include "BehaviorContext.h" + +void DarkInspirationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { + auto* target = EntityManager::Instance()->GetEntity(branch.target); + + if (target == nullptr) { + Game::logger->LogDebug("DarkInspirationBehavior", "Failed to find target (%llu)!", branch.target); + return; + } + + auto* destroyableComponent = target->GetComponent<DestroyableComponent>(); + + if (destroyableComponent == nullptr) { + return; + } + + if (destroyableComponent->HasFaction(m_FactionList)) { + this->m_ActionIfFactionMatches->Handle(context, bitStream, branch); + } +} + +void DarkInspirationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto* target = EntityManager::Instance()->GetEntity(branch.target); + + if (target == nullptr) { + Game::logger->LogDebug("DarkInspirationBehavior", "Failed to find target (%llu)!", branch.target); + + return; + } + + auto* destroyableComponent = target->GetComponent<DestroyableComponent>(); + + if (destroyableComponent == nullptr) { + return; + } + + if (destroyableComponent->HasFaction(m_FactionList)) { + this->m_ActionIfFactionMatches->Calculate(context, bitStream, branch); + } +} + +void DarkInspirationBehavior::Load() { + this->m_ActionIfFactionMatches = GetAction("action"); + + this->m_FactionList = GetInt("faction_list"); +} diff --git a/dGame/dBehaviors/DarkInspirationBehavior.h b/dGame/dBehaviors/DarkInspirationBehavior.h new file mode 100644 index 00000000..f8298742 --- /dev/null +++ b/dGame/dBehaviors/DarkInspirationBehavior.h @@ -0,0 +1,22 @@ +#pragma once +#include "Behavior.h" + +class DarkInspirationBehavior final : public Behavior +{ +public: + /* + * Inherited + */ + + explicit DarkInspirationBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { + } + + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + + void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + + void Load() override; +private: + Behavior* m_ActionIfFactionMatches; + uint32_t m_FactionList; +}; diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 6902917f..d832ef93 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -694,7 +694,7 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType auto* inventoryComponent = owner->GetComponent<InventoryComponent>(); if (inventoryComponent != nullptr && isEnemy) { - inventoryComponent->TriggerPassiveAbility(PassiveAbilityTrigger::EnemySmashed); + inventoryComponent->TriggerPassiveAbility(PassiveAbilityTrigger::EnemySmashed, m_Parent); } auto* missions = owner->GetComponent<MissionComponent>(); diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index eeb6afa7..6247f32d 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -1196,9 +1196,9 @@ void InventoryComponent::RemoveItemSkills(const LOT lot) { } } -void InventoryComponent::TriggerPassiveAbility(PassiveAbilityTrigger trigger) { +void InventoryComponent::TriggerPassiveAbility(PassiveAbilityTrigger trigger, Entity* target) { for (auto* set : m_Itemsets) { - set->TriggerPassiveAbility(trigger); + set->TriggerPassiveAbility(trigger, target); } } diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index 44636d95..f63a8d70 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -283,7 +283,7 @@ public: * Triggers one of the passive abilities from the equipped item set * @param trigger the trigger to fire */ - void TriggerPassiveAbility(PassiveAbilityTrigger trigger); + void TriggerPassiveAbility(PassiveAbilityTrigger trigger, Entity* target = nullptr); /** * Returns if the entity has any of the passed passive abilities equipped diff --git a/dGame/dInventory/ItemSet.cpp b/dGame/dInventory/ItemSet.cpp index 5063139e..1c67f6d6 100644 --- a/dGame/dInventory/ItemSet.cpp +++ b/dGame/dInventory/ItemSet.cpp @@ -180,9 +180,9 @@ void ItemSet::Update(float deltaTime) { } } -void ItemSet::TriggerPassiveAbility(PassiveAbilityTrigger trigger) { +void ItemSet::TriggerPassiveAbility(PassiveAbilityTrigger trigger, Entity* target) { for (auto& passiveAbility : m_PassiveAbilities) { - passiveAbility.Trigger(trigger); + passiveAbility.Trigger(trigger, target); } } diff --git a/dGame/dInventory/ItemSet.h b/dGame/dInventory/ItemSet.h index 7c713f03..d167cfaa 100644 --- a/dGame/dInventory/ItemSet.h +++ b/dGame/dInventory/ItemSet.h @@ -52,7 +52,7 @@ public: * Triggers all the passive abilities in this item set that match this trigger * @param trigger the trigger to use to trigger passive abilities */ - void TriggerPassiveAbility(PassiveAbilityTrigger trigger); + void TriggerPassiveAbility(PassiveAbilityTrigger trigger, Entity* target = nullptr); /** * Returns the skills that can be equipped for a specified amount of equipped items diff --git a/dGame/dInventory/ItemSetPassiveAbility.cpp b/dGame/dInventory/ItemSetPassiveAbility.cpp index d90f6e4e..83db4405 100644 --- a/dGame/dInventory/ItemSetPassiveAbility.cpp +++ b/dGame/dInventory/ItemSetPassiveAbility.cpp @@ -16,12 +16,12 @@ ItemSetPassiveAbility::ItemSetPassiveAbility(PassiveAbilityTrigger trigger, Enti ItemSetPassiveAbility::~ItemSetPassiveAbility() { } -void ItemSetPassiveAbility::Trigger(PassiveAbilityTrigger trigger) { +void ItemSetPassiveAbility::Trigger(PassiveAbilityTrigger trigger, Entity* target) { if (m_Trigger != trigger || m_Cooldown > 0.0f) { return; } - Activate(); + Activate(target); } void ItemSetPassiveAbility::Update(float deltaTime) { @@ -30,9 +30,9 @@ void ItemSetPassiveAbility::Update(float deltaTime) { } } -void ItemSetPassiveAbility::Activate() { +void ItemSetPassiveAbility::Activate(Entity* target) { if (m_Trigger == PassiveAbilityTrigger::EnemySmashed) { - OnEnemySmshed(); + OnEnemySmshed(target); return; } @@ -195,7 +195,7 @@ std::vector<ItemSetPassiveAbility> ItemSetPassiveAbility::FindAbilities(uint32_t return abilities; } -void ItemSetPassiveAbility::OnEnemySmshed() { +void ItemSetPassiveAbility::OnEnemySmshed(Entity* target) { auto* destroyableComponent = m_Parent->GetComponent<DestroyableComponent>(); auto* skillComponent = m_Parent->GetComponent<SkillComponent>(); @@ -293,8 +293,8 @@ void ItemSetPassiveAbility::OnEnemySmshed() { break; } case ItemSetPassiveAbilityID::ShinobiRank3: { - if (equippedCount < 4) return; - destroyableComponent->Imagine(3); + if (equippedCount < 4 || !target) return; + skillComponent->CalculateBehavior(695, 11399, target->GetObjectID()); break; } diff --git a/dGame/dInventory/ItemSetPassiveAbility.h b/dGame/dInventory/ItemSetPassiveAbility.h index ff945df2..8735e695 100644 --- a/dGame/dInventory/ItemSetPassiveAbility.h +++ b/dGame/dInventory/ItemSetPassiveAbility.h @@ -30,12 +30,12 @@ public: * Attempts to trigger a passive ability for this item set, if this is the wrong trigger this is a no-op * @param trigger the trigger to attempt to fire */ - void Trigger(PassiveAbilityTrigger trigger); + void Trigger(PassiveAbilityTrigger trigger, Entity* target = nullptr); /** * Activates the passive ability */ - void Activate(); + void Activate(Entity* target = nullptr); /** * Finds all the passive abilities associated with a certain item set @@ -47,7 +47,7 @@ public: static std::vector<ItemSetPassiveAbility> FindAbilities(uint32_t itemSetID, Entity* parent, ItemSet* itemSet); private: - void OnEnemySmshed(); + void OnEnemySmshed(Entity* target = nullptr); /** * The means of triggering this ability From 6ec921025deb43a43f2413e150b121250f635df4 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 24 Dec 2022 02:49:31 -0600 Subject: [PATCH 203/322] Use new logic for applying speed changes in ApplyBuff (#919) --- dGame/dComponents/BuffComponent.cpp | 26 ++++++-------------------- 1 file changed, 6 insertions(+), 20 deletions(-) diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index d8d7428d..974d0bd2 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -170,17 +170,10 @@ void BuffComponent::ApplyBuffEffect(int32_t id) { destroyable->SetMaxImagination(destroyable->GetMaxImagination() + maxImagination); } else if (parameter.name == "speed") { - const auto speed = parameter.value; - auto* controllablePhysicsComponent = this->GetParent()->GetComponent<ControllablePhysicsComponent>(); - - if (controllablePhysicsComponent == nullptr) return; - - const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); - - controllablePhysicsComponent->SetSpeedMultiplier(current + ((speed - 500.0f) / 500.0f)); - - EntityManager::Instance()->SerializeEntity(this->GetParent()); + if (!controllablePhysicsComponent) return; + const auto speed = parameter.value; + controllablePhysicsComponent->AddSpeedboost(speed); } } } @@ -213,17 +206,10 @@ void BuffComponent::RemoveBuffEffect(int32_t id) { destroyable->SetMaxImagination(destroyable->GetMaxImagination() - maxImagination); } else if (parameter.name == "speed") { - const auto speed = parameter.value; - auto* controllablePhysicsComponent = this->GetParent()->GetComponent<ControllablePhysicsComponent>(); - - if (controllablePhysicsComponent == nullptr) return; - - const auto current = controllablePhysicsComponent->GetSpeedMultiplier(); - - controllablePhysicsComponent->SetSpeedMultiplier(current - ((speed - 500.0f) / 500.0f)); - - EntityManager::Instance()->SerializeEntity(this->GetParent()); + if (!controllablePhysicsComponent) return; + const auto speed = parameter.value; + controllablePhysicsComponent->RemoveSpeedboost(speed); } } } From 85ab573665e8ed17ab1ef4c05b4f707253b53673 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 24 Dec 2022 00:51:59 -0800 Subject: [PATCH 204/322] Fix duping issue (#921) --- dGame/dGameMessages/GameMessages.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index c3b86647..26b1bb3c 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -4728,13 +4728,13 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit float sellScalar = vend->GetSellScalar(); if (Inventory::IsValidItem(itemComp.currencyLOT)) { - const auto altCurrency = (itemComp.altCurrencyCost * sellScalar) * count; + const auto altCurrency = static_cast<uint32_t>(itemComp.altCurrencyCost * sellScalar) * count; inv->AddItem(itemComp.currencyLOT, std::floor(altCurrency), eLootSourceType::LOOT_SOURCE_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() + ((itemComp.baseValue * sellScalar) * count)), eLootSourceType::LOOT_SOURCE_VENDOR); + character->SetCoins(std::floor(character->GetCoins() + (static_cast<uint32_t>(itemComp.baseValue * sellScalar) * count)), eLootSourceType::LOOT_SOURCE_VENDOR); //EntityManager::Instance()->SerializeEntity(player); // so inventory updates GameMessages::SendVendorTransactionResult(entity, sysAddr); } From 1470af99c3454424264f3dcb1e71a1f3332eb20d Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 24 Dec 2022 04:06:27 -0800 Subject: [PATCH 205/322] Correct Property FX incorrect skill cast (#920) --- dScripts/ai/PROPERTY/PropertyFXDamage.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dScripts/ai/PROPERTY/PropertyFXDamage.cpp b/dScripts/ai/PROPERTY/PropertyFXDamage.cpp index d12cc9e1..56079384 100644 --- a/dScripts/ai/PROPERTY/PropertyFXDamage.cpp +++ b/dScripts/ai/PROPERTY/PropertyFXDamage.cpp @@ -12,7 +12,7 @@ void PropertyFXDamage::OnCollisionPhantom(Entity* self, Entity* target) { if (skills != nullptr && targetStats != nullptr) { auto targetFactions = targetStats->GetFactionIDs(); if (std::find(targetFactions.begin(), targetFactions.end(), 1) != targetFactions.end()) { - skills->CalculateBehavior(11386, 692, target->GetObjectID()); + skills->CalculateBehavior(692, 11386, target->GetObjectID()); } } } From 5cc7d470743694e21b6960a065fc3fba202ccd2a Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 24 Dec 2022 16:41:13 -0600 Subject: [PATCH 206/322] sanity check on opening packages (#923) --- dGame/dGameMessages/GameMessages.cpp | 6 +-- dGame/dInventory/Item.cpp | 68 +++++++++++++++------------- dGame/dInventory/Item.h | 2 +- 3 files changed, 38 insertions(+), 38 deletions(-) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 26b1bb3c..37aeb093 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -5763,11 +5763,7 @@ void GameMessages::HandleUseNonEquipmentItem(RakNet::BitStream* inStream, Entity auto* item = inv->FindItemById(itemConsumed); - if (item == nullptr) { - return; - } - - item->UseNonEquip(); + if (item) item->UseNonEquip(item); } void GameMessages::HandleMatchRequest(RakNet::BitStream* inStream, Entity* entity) { diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 778d8237..a3d4cfc0 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -262,7 +262,7 @@ bool Item::Consume() { return success; } -void Item::UseNonEquip() { +void Item::UseNonEquip(Item* item) { LOT thisLot = this->GetLot(); if (!GetInventory()) { Game::logger->LogDebug("Item", "item %i has no inventory??", this->GetLot()); @@ -292,45 +292,49 @@ void Item::UseNonEquip() { } // This precondition response is taken care of in SpawnPet(). } else { - auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_PACKAGE); + bool success = false; + auto inventory = item->GetInventory(); + if (inventory && inventory->GetType() == eInventoryType::ITEMS) { + auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_PACKAGE); - if (packageComponentId == 0) return; + if (packageComponentId == 0) return; - auto* packCompTable = CDClientManager::Instance()->GetTable<CDPackageComponentTable>("PackageComponent"); - auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast<uint32_t>(packageComponentId); }); + auto* packCompTable = CDClientManager::Instance()->GetTable<CDPackageComponentTable>("PackageComponent"); + auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast<uint32_t>(packageComponentId); }); - auto success = !packages.empty(); - if (success) { - if (this->GetPreconditionExpression()->Check(playerInventoryComponent->GetParent())) { - auto* entityParent = playerInventoryComponent->GetParent(); - // Roll the loot for all the packages then see if it all fits. If it fits, give it to the player, otherwise don't. - std::unordered_map<LOT, int32_t> rolledLoot{}; - for (auto& pack : packages) { - auto thisPackage = LootGenerator::Instance().RollLootMatrix(entityParent, pack.LootMatrixIndex); - for (auto& loot : thisPackage) { - // If we already rolled this lot, add it to the existing one, otherwise create a new entry. - auto existingLoot = rolledLoot.find(loot.first); - if (existingLoot == rolledLoot.end()) { - rolledLoot.insert(loot); - } else { - existingLoot->second += loot.second; + auto success = !packages.empty(); + if (success) { + if (this->GetPreconditionExpression()->Check(playerInventoryComponent->GetParent())) { + auto* entityParent = playerInventoryComponent->GetParent(); + // Roll the loot for all the packages then see if it all fits. If it fits, give it to the player, otherwise don't. + std::unordered_map<LOT, int32_t> rolledLoot{}; + for (auto& pack : packages) { + auto thisPackage = LootGenerator::Instance().RollLootMatrix(entityParent, pack.LootMatrixIndex); + for (auto& loot : thisPackage) { + // If we already rolled this lot, add it to the existing one, otherwise create a new entry. + auto existingLoot = rolledLoot.find(loot.first); + if (existingLoot == rolledLoot.end()) { + rolledLoot.insert(loot); + } else { + existingLoot->second += loot.second; + } } } - } - if (playerInventoryComponent->HasSpaceForLoot(rolledLoot)) { - LootGenerator::Instance().GiveLoot(playerInventoryComponent->GetParent(), rolledLoot, eLootSourceType::LOOT_SOURCE_CONSUMPTION); - playerInventoryComponent->RemoveItem(lot, 1); + if (playerInventoryComponent->HasSpaceForLoot(rolledLoot)) { + LootGenerator::Instance().GiveLoot(playerInventoryComponent->GetParent(), rolledLoot, eLootSourceType::LOOT_SOURCE_CONSUMPTION); + item->SetCount(item->GetCount() - 1); + } else { + success = false; + } } else { + GameMessages::SendUseItemRequirementsResponse( + playerInventoryComponent->GetParent()->GetObjectID(), + playerInventoryComponent->GetParent()->GetSystemAddress(), + UseItemResponse::FailedPrecondition + ); success = false; } - } else { - GameMessages::SendUseItemRequirementsResponse( - playerInventoryComponent->GetParent()->GetObjectID(), - playerInventoryComponent->GetParent()->GetSystemAddress(), - UseItemResponse::FailedPrecondition - ); - success = false; } } Game::logger->LogDebug("Item", "Player %llu %s used item %i", playerEntity->GetObjectID(), success ? "successfully" : "unsuccessfully", thisLot); diff --git a/dGame/dInventory/Item.h b/dGame/dInventory/Item.h index bb8316d7..6993a0ba 100644 --- a/dGame/dInventory/Item.h +++ b/dGame/dInventory/Item.h @@ -195,7 +195,7 @@ public: /** * Uses this item if its non equip, essentially an interface for the linked GM */ - void UseNonEquip(); + void UseNonEquip(Item* item); /** * Disassembles the part LOTs of this item back into the inventory, if it has any From e41ed684475db90a59e1d70fc31ab2d7b39ac1b8 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 28 Dec 2022 13:58:53 -0800 Subject: [PATCH 207/322] Update README (#806) * Update README The README is very out of date, the following changes have been made - Update what the file tree should look like - Remove client Avant Gardens Survival script fix - Update some incorrect commands or commands that were missing packages. - Add packed client setup instructions - Add *config.ini setup instructions - Describe what configs should be modified and what you may want to change - More detail in the verify step - Change Account Manager link to Nexus Dashboard - Remove table of commands and reference Commands.md instead - Specify that UGCSERVERIP may need to be changed to localhost as well * Fix Avant Gardens Survival This addresses the Avant Gardens Survival bug. Squeezing it in with the README changes since it is a small change. * Remove Locale * Update README.md Co-authored-by: Jonathan Romano <jonathan@luxaritas.com> * Remove dLocale again? * Saving for the night * Revert "Fix Avant Gardens Survival" This reverts commit b1a1ce2d84e870c328a039673c9b77859e6e3dbd. * Update Mission.cpp * Update README.md Move comments and add pre-processor define Update README.md Update README.md Update CMakePresets.json Update CMakeVariables.txt Update README.md i love readmes Update README.md Update README.md Update README.md Update README.md Update README.md Update README.md Update README.md * Update README.md Co-authored-by: Daniel Seiler <me@xiphoseer.de> * Address feedback * Update README.md * Update Database.cpp * Update README.md * Revert tcp specification Co-authored-by: Jonathan Romano <jonathan@luxaritas.com> Co-authored-by: Aaron Kimbrell <aronwk.aaron@gmail.com> Co-authored-by: Daniel Seiler <me@xiphoseer.de> --- CMakePresets.json | 5 +- CMakeVariables.txt | 14 +- README.md | 587 +++++++++++++++++++-------------------------- docs/Commands.md | 4 +- 4 files changed, 257 insertions(+), 353 deletions(-) diff --git a/CMakePresets.json b/CMakePresets.json index 3968b3ce..f8170755 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -23,10 +23,7 @@ "name": "ci-macos-11", "displayName": "CI configure step for MacOS", "description": "Same as default, Used in GitHub actions workflow", - "inherits": "default", - "cacheVariables": { - "OPENSSL_ROOT_DIR": "/usr/local/opt/openssl@3/" - } + "inherits": "default" }, { "name": "ci-windows-2022", diff --git a/CMakeVariables.txt b/CMakeVariables.txt index 94e9cd20..d3c8b36f 100644 --- a/CMakeVariables.txt +++ b/CMakeVariables.txt @@ -8,15 +8,17 @@ LICENSE=AGPL-3.0 # 171022 - Unmodded client NET_VERSION=171022 # Debugging -__dynamic=1 # Set __dynamic to 1 to enable the -rdynamic flag for the linker, yielding some symbols in crashlogs. -# __ggdb=1 +__dynamic=1 # Set __ggdb to 1 to enable the -ggdb flag for the linker, including more debug info. -# __include_backtrace__=1 +# __ggdb=1 # Set __include_backtrace__ to 1 to includes the backtrace library for better crashlogs. -# __compile_backtrace__=1 +# __include_backtrace__=1 # Set __compile_backtrace__ to 1 to compile the backtrace library instead of using system libraries. -__maria_db_connector_compile_jobs__=1 +# __compile_backtrace__=1 # Set to the number of jobs (make -j equivalent) to compile the mariadbconn files with. -__enable_testing__=1 +__maria_db_connector_compile_jobs__=1 # When set to 1 and uncommented, compiling and linking testing folders and libraries will be done. +__enable_testing__=1 +# The path to OpenSSL. Change this if your OpenSSL install path is different than the default. +OPENSSL_ROOT_DIR=/usr/local/opt/openssl@3/ diff --git a/README.md b/README.md index bd9dd6b7..27de7d6d 100644 --- a/README.md +++ b/README.md @@ -18,210 +18,188 @@ Darkflame Universe is licensed under AGPLv3, please read [LICENSE](LICENSE). Som Throughout the entire build and setup process a level of familiarity with the command line and preferably a Unix-like development environment is greatly advantageous. ### Hosting a server -We do not recommend hosting public servers. DLU is intended for small scale deployment, for example within a group of friends. It has not been tested for large scale deployment which comes with additional security risks. +We do not recommend hosting public servers. Darkflame Universe is intended for small scale deployment, for example within a group of friends. It has not been tested for large scale deployment which comes with additional security risks. ### Supply of resource files -Darkflame Universe is a server emulator and does not distribute any LEGO® Universe files. A separate game client is required to setup this server emulator and play the game, which we cannot supply. Users are strongly suggested to refer to the safe checksums listed in the resources tab below when checking if a client will work. +Darkflame Universe is a server emulator and does not distribute any LEGO® Universe files. A separate game client is required to setup this server emulator and play the game, which we cannot supply. Users are strongly suggested to refer to the safe checksums listed [here](#verifying-your-client-files) to see if a client will work. -## Build -Development of the latest iteration of Darkflame Universe has been done primarily in a Unix-like environment and is where it has been tested and designed for deployment. It is therefore highly recommended that Darkflame Universe be built and deployed using a Unix-like environment for the most streamlined experience. +## Steps to setup server +* [Clone this repository](#clone-the-repository) +* [Install dependencies](#install-dependencies) +* [Database setup](#database-setup) +* [Build the server](#build-the-server) +* [Configuring your server](#configuring-your-server) + * [Required Configuration](#required-configuration) + * [Optional Configuration](#optional-configuration) +* [Verify your setup](#verify-your-setup) +* [Running the server](#running-the-server) +* [User Guide](#user-guide) -### Prerequisites -#### Clone the repository +## Clone the repository +If you are on Windows, you will need to download and install git from [here](https://git-scm.com/download/win) + +Then run the following command ```bash git clone --recursive https://github.com/DarkflameUniverse/DarkflameServer ``` -#### Python -Some tools utilized to streamline the setup process require Python 3, make sure you have it installed. +## Install dependencies +### Windows packages +Ensure that you have either the [MSVC C++ compiler](https://visualstudio.microsoft.com/vs/features/cplusplus/) (recommended) or the [Clang compiler](https://github.com/llvm/llvm-project/releases/) installed. +You'll also need to download and install [CMake](https://cmake.org/download/) (version <font size="4">**CMake version 3.18**</font> or later!). -### Choosing the right version for your client -DLU clients identify themselves using a higher version number than the regular live clients out there. -This was done make sure that older and incomplete clients wouldn't produce false positive bug reports for us, and because we made bug fixes and new content for the client. +### MacOS packages +Ensure you have [brew](https://brew.sh) installed. +You will need to install the following packages +```bash +brew install cmake gcc mariadb openssl zlib +``` -If you're using a DLU client you'll have to go into the "CMakeVariables.txt" file and change the NET_VERSION variable to 171023 to match the modified client's version number. +### Linux packages +Make sure packages like `gcc`, and `zlib` are installed. Depending on the distribution, these packages might already be installed. Note that on systems like Ubuntu, you will need the `zlib1g-dev` package so that the header files are available. `libssl-dev` will also be required as well as `openssl`. You will also need a MySQL database solution to use. We recommend using `mariadb-server`. -### Enabling testing -While it is highly recommended to enable testing, if you would like to save compilation time, you'll want to comment out the enable_testing variable in CMakeVariables.txt. -It is recommended that after building and if testing is enabled, to run `ctest` and make sure all the tests pass. +For Ubuntu, you would run the following commands. On other systems, the package install command will differ. -### Using Docker -Refer to [Docker.md](/Docker.md). +```bash +sudo apt update && sudo apt upgrade -For Windows, refer to [Docker_Windows.md](/Docker_Windows.md). +# Install packages +sudo apt install build-essential gcc zlib1g-dev libssl-dev openssl mariadb-server cmake +``` -### Linux builds -Make sure packages like `gcc`, `cmake`, and `zlib` are installed. Depending on the distribution, these packages might already be installed. Note that on systems like Ubuntu, you will need the `zlib1g-dev` package so that the header files are available. `libssl-dev` will also be required as well as `openssl`. +#### Required CMake version +This project uses <font size="4">**CMake version 3.18**</font> or higher and as such you will need to ensure you have this version installed. +You can check your CMake version by using the following command in a terminal. +```bash +cmake --version +``` -CMake must be version 3.14 or higher! +If you are going to be using an Ubuntu environment to run the server, you may need to get a more recent version of `cmake` than the packages available may provide. -#### Build the repository +The general approach to do so would be to obtain a copy of the signing key and then add the CMake repository to your apt. +You can do so with the following commands. +[Source of the below commands](https://askubuntu.com/questions/355565/how-do-i-install-the-latest-version-of-cmake-from-the-command-line) + +```bash +# Remove the old version of CMake +sudo apt purge --auto-remove cmake + +# Prepare for installation +sudo apt update && sudo apt install -y software-properties-common lsb-release && sudo apt clean all + +# Obtain a copy of the signing key +wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | gpg --dearmor - | sudo tee /etc/apt/trusted.gpg.d/kitware.gpg >/dev/null + +# Add the repository to your sources list. +sudo apt-add-repository "deb https://apt.kitware.com/ubuntu/ $(lsb_release -cs) main" + +# Next you'll want to ensure that Kitware's keyring stays up to date +sudo apt update +sudo apt install kitware-archive-keyring +sudo rm /etc/apt/trusted.gpg.d/kitware.gpg + +# If sudo apt update above returned an error, copy the public key at the end of the error message and run the following command +# if the error message was "The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 6AF7F09730B3F0A4" +# then the below command would be "sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 6AF7F09730B3F0A4" +sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys <TheCopiedPublicKey> + +# Finally update and install +sudo apt update +sudo apt install cmake +``` + +## Database setup +First you'll need to start MariaDB. + +For Windows the service is always running by default. + +For MacOS, run the following command +```bash +brew services start mariadb +``` + +For Linux, run the following command +```bash +sudo systemctl start mysql +# If systemctl is not a known command on your distribution, try the following instead +sudo service mysql start +``` + +<font size="4">**You will need to run this command every time you restart your environment**</font> + +If you are using Linux and `systemctl` and want the MariaDB instance to start on startup, run the following command +```bash +sudo systemctl enable --now mysql +``` + +Once MariaDB is started, you'll need to create a user and an empty database for Darkflame Universe to use. + +First, login to the MariaDB instance. + +To do this on Ubuntu/Linux, MacOS, or another Unix like operating system, run the following command in a terminal +```bash +# Logs you into the MariaDB instance as root +sudo mysql +``` + +For Windows, run the following command in the `Command Prompt (MariaDB xx.xx)` terminal +```bash +# Logs you into the mysql instance +mysql -u root -p +# You will then be prompted for the password you set for root during installation of MariaDB +``` + +Now that you are logged in, run the following commands. + +```bash +# Creates a user for this computer which uses a password and grant said user all privileges. +# Change mydarkflameuser to a custom username and password to a custom password. +GRANT ALL ON *.* TO 'mydarkflameuser'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION; +FLUSH PRIVILEGES; + +# Then create a database for Darkflame Universe to use. +CREATE DATABASE darkflame; +``` + +## Build the server You can either run `build.sh` when in the root folder of the repository: ```bash ./build.sh ``` -Or manually run the commands used in `build.sh`: +Or manually run the commands used in [build.sh](build.sh). -```bash -# Create the build directory, preserving it if it already exists -mkdir -p build -cd build +### Notes +Depending on your operating system, you may need to adjust some pre-processor defines in [CMakeVariables.txt](./CMakeVariables.txt) before building: +* If you are on MacOS, ensure OPENSSL_ROOT_DIR is pointing to the openssl root directory. +* If you are using a Darkflame Universe client, ensure NET_VERSION is changed to 171023. -# Run CMake to generate make files -cmake .. +## Configuring your server +This server has a few steps that need to be taken to configure the server for your use case. -# To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `cmake --build . --config Release -j8' -cmake --build . --config Release -``` +### Required Configuration +Darkflame Universe can run with either a packed or an unpacked client. +Navigate to `build/sharedconfig.ini` and fill in the following fields: +* `mysql_host` (This is the IP address or hostname of your MariaDB server. This is highly likely `localhost`) + * If you setup your MariaDB instance on a port other than 3306, which can be done on a Windows install, you will need to make this value `tcp://localhost:portNum` where portNum is replaced with the port you chose to run MariaDB on. +* `mysql_database` (This is the database you created for the server) +* `mysql_username` (This is the user you created for the server) +* `mysql_password` (This is the password for the user you created for the server) +* `client_location` (This is the location of the client files. This should be the folder path of a packed or unpacked client) + * Ideally the path to the client should not contain any spaces. -### MacOS builds -Ensure `cmake`, `zlib` and `open ssl` are installed as well as a compiler (e.g `clang` or `gcc`). - -In the repository root folder run the following. Ensure -DOPENSSL_ROOT_DIR=/path/to/openssl points to your openssl install location -```bash -# Create the build directory, preserving it if it already exists -mkdir -p build -cd build - -# Run CMake to generate build files -cmake .. -DOPENSSL_ROOT_DIR=/path/to/openssl - -# Get cmake to build the project. If make files are being used then using make and appending `-j` and the amount of cores to utilize may be preferable, for example `make -j8` -cmake --build . --config Release -``` - -### Windows builds (native) -Ensure that you have either the [MSVC](https://visualstudio.microsoft.com/vs/) or the [Clang](https://github.com/llvm/llvm-project/releases/) (recommended) compiler installed. You will also need to install [CMake](https://cmake.org/download/). Currently on native Windows the server will only work in Release mode. - -#### Build the repository -```batch -:: Create the build directory -mkdir build -cd build - -:: Run CMake to generate make files -cmake .. - -:: Run CMake with build flag to build -cmake --build . --config Release -``` -#### Windows for ARM has not been tested but should build by doing the following -```batch -:: Create the build directory -mkdir build -cd build - -:: Run CMake to generate make files -cmake .. -DMARIADB_BUILD_SOURCE=ON - -:: Run CMake with build flag to build -cmake --build . --config Release -``` - -### Windows builds (WSL) -This section will go through how to install [WSL](https://docs.microsoft.com/en-us/windows/wsl/install) and building in a Linux environment under Windows. WSL requires Windows 10 version 2004 and higher (Build 19041 and higher) or Windows 11. - -#### Open the Command Prompt application with Administrator permissions and run the following: -```bash -# Installing Windows Subsystem for Linux -wsl --install -``` - -#### Open the Ubuntu application and run the following: -```bash -# Make sure the install is up to date -apt update && apt upgrade - -# Make sure the gcc, cmake, and build-essentials are installed -sudo apt install gcc -sudo apt install cmake -sudo apt install build-essential -``` - -[**Follow the Linux instructions**](#linux-builds) - -### ARM builds -AArch64 builds should work on linux and MacOS using their respective build steps. Windows ARM should build but it has not been tested - -### Updating your build -To update your server to the latest version navigate to your cloned directory -```bash -cd /path/to/DarkflameServer -``` -run the following commands to update to the latest changes -```bash -git pull -git submodule update --init --recursive -``` -now follow the build section for your system - -## Setting up the environment - -### Resources - -#### LEGO® Universe 1.10.64 - -This repository does not distribute any LEGO® Universe files. A full install of LEGO® Universe version 1.10.64 (latest) is required to finish setting up Darkflame Universe. - -Known good SHA256 checksums of the client: -- `8f6c7e84eca3bab93232132a88c4ae6f8367227d7eafeaa0ef9c40e86c14edf5` (packed client, rar compressed) -- `c1531bf9401426042e8bab2de04ba1b723042dc01d9907c2635033d417de9e05` (packed client, includes extra locales, rar compressed) -- `0d862f71eedcadc4494c4358261669721b40b2131101cbd6ef476c5a6ec6775b` (unpacked client, includes extra locales, rar compressed) - -Known good *SHA1* checksum of the DLU client: -- `91498e09b83ce69f46baf9e521d48f23fe502985` (packed client, zip compressed) - -How to generate a SHA256 checksum: -```bash -# Replace <file> with the file path to the client - -# If on Linux or MacOS -shasum -a 256 <file> - -# If on Windows -certutil -hashfile <file> SHA256 -``` - -#### Unpacking the client -* Clone lcdr's utilities repository [here](https://github.com/lcdr/utils) -* Use `pkextractor.pyw` to unpack the client files if they are not already unpacked - -#### Setup resource directory -* In the `build` directory create a `res` directory if it does not already exist. -* Copy over or create symlinks from `macros`, `BrickModels`, `chatplus_en_us.txt`, `names`, and `maps` in your client `res` directory to the server `build/res` directory -* Unzip the navmeshes [here](./resources/navmeshes.zip) and place them in `build/res/maps/navmeshes` - -#### Setup locale -* In the `build` directory create a `locale` directory if it does not already exist -* Copy over or create symlinks from `locale.xml` in your client `locale` directory to the `build/locale` directory - -#### Client database -* Move the file `res/cdclient.fdb` from the unpacked client to the `build/res` folder on the server. -* The server will automatically copy and convert the file from fdb to sqlite should `CDServer.sqlite` not already exist. -* You can also convert the database manually using `fdb_to_sqlite.py` using lcdr's utilities. Just make sure to rename the file to `CDServer.sqlite` instead of `cdclient.sqlite`. -* Migrations to the database are automatically run on server start. When migrations are needed to be ran, the server may take a bit longer to start. - -### Database -Darkflame Universe utilizes a MySQL/MariaDB database for account and character information. - -Initial setup can vary drastically based on which operating system or distribution you are running; there are instructions out there for most setups, follow those and come back here when you have a database up and running. - -* All that you need to do is create a database to connect to. As long as the server can connect to the database, the schema will always be kept up to date when you start the server. - -#### Configuration - -After the server has been built there should be four `ini` files in the build director: `sharedconfig.ini`, `authconfig.ini`, `chatconfig.ini`, `masterconfig.ini`, and `worldconfig.ini`. Go through them and fill in the database credentials and configure other settings if necessary. - -#### Migrations - -The database is automatically setup and migrated to what it should look like for the latest commit whenever you start the server. - -#### Verify +### Optional Configuration +* After the server has been built there should be five `ini` files in the build directory: `sharedconfig.ini`, `authconfig.ini`, `chatconfig.ini`, `masterconfig.ini`, and `worldconfig.ini`. +* `authconfig.ini` contains an option to enable or disable play keys on your server. Do not change the default port for auth. +* `chatconfig.ini` contains a port option. +* `masterconfig.ini` contains options related to permissions you want to run your servers with. +* `sharedconfig.ini` contains several options that are shared across all servers +* `worldconfig.ini` contains several options to turn on QOL improvements should you want them. If you would like the most vanilla experience possible, you will need to turn some of these settings off. +## Verify your setup Your build directory should now look like this: * AuthServer * ChatServer @@ -230,42 +208,35 @@ Your build directory should now look like this: * authconfig.ini * chatconfig.ini * masterconfig.ini +* sharedconfig.ini * worldconfig.ini -* **locale/** - * locale.xml -* **res/** - * cdclient.fdb - * chatplus_en_us.txt - * **macros/** - * ... - * **BrickModels/** - * ... - * **maps/** - * **navmeshes/** - * ... - * ... * ... ## Running the server -If everything has been configured correctly you should now be able to run the `MasterServer` binary. Darkflame Universe utilizes port numbers under 1024, so under Linux you either have to give the binary network permissions or run it under sudo. +If everything has been configured correctly you should now be able to run the `MasterServer` binary which is located in the `build` directory. Darkflame Universe utilizes port numbers under 1024, so under Linux you either have to give the `AuthServer` binary network permissions or run it under sudo. +To give `AuthServer` network permissions and not require sudo, run the following command +```bash +sudo setcap 'cap_net_bind_service=+ep' AuthServer +``` +and then go to `build/masterconfig.ini` and change `use_sudo_auth` to 0. ### First admin user Run `MasterServer -a` to get prompted to create an admin account. This method is only intended for the system administrator as a means to get started, do NOT use this method to create accounts for other users! -### Account Manager +### Account management tool (Nexus Dashboard) +**If you are just using this server for yourself, you can skip setting up Nexus Dashboard** -Follow the instructions [here](https://github.com/DarkflameUniverse/AccountManager) to setup the DLU account management Python web application. This is the intended way for users to create accounts. +Follow the instructions [here](https://github.com/DarkflameUniverse/NexusDashboard) to setup the DLU Nexus Dashboard web application. This is the intended way for users to create accounts and the intended way for moderators to approve names/pets/properties and do other moderation actions. ### Admin levels +The admin level, or Game Master level (hereafter referred to as gmlevel), is specified in the `accounts.gm_level` column in the MySQL database. Normal players should have this set to `0`, which comes with no special privileges. The system administrator will have this set to `9`, which comes will all privileges. gmlevel `8` should be used to give a player a majority of privileges without the safety critical once. -The admin level, or game master level, is specified in the `accounts.gm_level` column in the MySQL database. Normal players should have this set to `0`, which comes with no special privileges. The system administrator will have this set to `9`, which comes will all privileges. Admin level `8` should be used to give a player a majority of privileges without the safety critical once. +While a character has a gmlevel of anything but `0`, some gameplay behavior will change. When testing gameplay, you should always use a character with a gmlevel of `0`. -While a character has a gmlevel of anything but 0, some gameplay behavior will change. When testing gameplay, you should always use a character with a gmlevel of 0. +# User guide +Some changes to the client `boot.cfg` file are needed to play on your server. -## User guide -A few modifications have to be made to the client. - -### Client configuration +## Allowing a user to connect to your server To connect to a server follow these steps: * In the client directory, locate `boot.cfg` * Open it in a text editor and locate where it says `AUTHSERVERIP=0:` @@ -273,155 +244,89 @@ To connect to a server follow these steps: * Launch `legouniverse.exe`, through `wine` if on a Unix-like operating system * Note that if you are on WSL2, you will need to configure the public IP in the server and client to be the IP of the WSL2 instance and not localhost, which can be found by running `ifconfig` in the terminal. Windows defaults to WSL1, so this will not apply to most users. -### Brick-By-Brick building +## Brick-By-Brick building +Should you choose to do any brick building, you will want to have some form of a http server that returns a 404 error since we are unable to emulate live User Generated Content at the moment. If you attempt to do any brick building without a 404 server running properly, you will be unable to load into your game. Python is the easiest way to do this, but any thing that returns a 404 should work fine. +* Note: the client hard codes this request on port 80. -Brick-By-Brick building requires `PATCHSERVERIP=0:` in the `boot.cfg` to point to a HTTP server which always returns `HTTP 404 - Not Found` for all requests. This can be achieved by pointing it to `localhost` while having `sudo python -m http.server 80` running in the background. +<font size="4">**If you do not plan on doing any Brick Building, then you can skip this step.**</font> -### In-game commands -Here is a summary of the commands available in-game. All commands are prefixed by `/` and typed in the in-game chat window. Some commands requires admin privileges. Operands within `<>` are required, operands within `()` are not. For the full list of in-game commands, please checkout [the source file](./dGame/dUtilities/SlashCommandHandler.cpp). +The easiest way to do this is to install [python](https://www.python.org/downloads/). -<table> -<thead> - <th> - Command - </th> - <th> - Usage - </th> - <th> - Description - </th> - <th> - Admin Level Requirement - </th> -</thead> -<tbody> - <tr> - <td> - info - </td> - <td> - /info - </td> - <td> - Displays server info to the user, including where to find the server's source code. - </td> - <td> - </td> - </tr> - <tr> - <td> - credits - </td> - <td> - /credits - </td> - <td> - Displays the names of the people behind Darkflame Universe. - </td> - <td> - </td> - </tr> - <tr> - <td> - instanceinfo - </td> - <td> - /instanceinfo - </td> - <td> - Displays in the chat the current zone, clone, and instance id. - </td> - <td> - </td> - </tr> - <tr> - <td> - gmlevel - </td> - <td> - /gmlevel <level> - </td> - <td> - Within the authorized range of levels for the current account, changes the character's game master level to the specified value. This is required to use certain commands. - </td> - <td> - </td> - </tr> - <tr> - <td> - testmap - </td> - <td> - /testmap <zone> (clone-id) - </td> - <td> - Transfers you to the given zone by id and clone id. - </td> - <td> - 1 - </td> - </tr> - <tr> - <td> - ban - </td> - <td> - /ban <username> - </td> - <td> - Bans a user from the server. - </td> - <td> - 4 - </td> - </tr> - <tr> - <td> - gmadditem - </td> - <td> - /gmadditem <id> (count) - </td> - <td> - Adds the given item to your inventory by id. - </td> - <td> - 8 - </td> - </tr> - <tr> - <td> - spawn - </td> - <td> - /spawn <id> - </td> - <td> - Spawns an object at your location by id. - </td> - <td> - 8 - </td> - </tr> - <tr> - <td> - metrics - </td> - <td> - /metrics - </td> - <td> - Prints some information about the server's performance. - </td> - <td> - 8 - </td> - </tr> -</tbody> -</table> +### Allowing a user to build in Brick-by-Brick mode +Brick-By-Brick building requires `PATCHSERVERIP=0:` and `UGCSERVERIP=0:` in the `boot.cfg` to point to a HTTP server which always returns `HTTP 404 - Not Found` for all requests. This can be most easily achieved by pointing both of those variables to `localhost` while having running in the background. +Each client must have their own 404 server running if they are using a locally hosted 404 server. +```bash +# If on linux run this command. Because this is run on a port below 1024, binary network permissions are needed. +sudo python3 -m http.server 80 + +# If on windows one of the following will work when run through Powershell or Command Prompt assuming python is installed +python3 -m http.server 80 +python http.server 80 +py -m http.server 80 +``` + +## Updating your server +To update your server to the latest version navigate to your cloned directory +```bash +cd path/to/DarkflameServer +``` +Run the following commands to update to the latest changes +```bash +git pull +git submodule update --init --recursive +``` +Now follow the [build](#build-the-server) section for your system and your server is up to date. + +## In-game commands +* A list of all in-game commands can be found [here](./docs/Commands.md). + +## Verifying your client files + +### LEGO® Universe 1.10.64 +To verify that you are indeed using a LEGO® Universe 1.10.64 client, make sure you have the full client compressed **in a rar file** and run the following command. +```bash +# Replace <file> with the file path to the zipped client + +# If on Linux or MacOS +shasum -a 256 <file> + +# If on Windows using the Command Prompt +certutil -hashfile <file> SHA256 +``` + +Below are known good SHA256 checksums of the client: +* `8f6c7e84eca3bab93232132a88c4ae6f8367227d7eafeaa0ef9c40e86c14edf5` (packed client, rar compressed) +* `c1531bf9401426042e8bab2de04ba1b723042dc01d9907c2635033d417de9e05` (packed client, includes extra locales, rar compressed) +* `0d862f71eedcadc4494c4358261669721b40b2131101cbd6ef476c5a6ec6775b` (unpacked client, includes extra locales, rar compressed) + +If the returned hash matches one of the lines above then you can continue with setting up the server. If you are using a fully downloaded and complete client from live, then it will work, but the hash above may not match. Otherwise you must obtain a full install of LEGO® Universe 1.10.64. + +### Darkflame Universe Client +Darkflame Universe clients identify themselves using a higher version number than the regular live clients out there. +This was done make sure that older and incomplete clients wouldn't produce false positive bug reports for us, and because we made bug fixes and new content for the client. + +To verify that you are indeed using a Darkflame Universe client, make sure you have the full client compressed **in a zip file** and run the following command. + +```bash +# Replace <file> with the file path to the zipped client + +# If on Linux or MacOS +shasum -a 1 <file> + +# If on Windows using the Command Prompt +certutil -hashfile <file> SHA1 +``` + +Known good *SHA1* checksum of the Darkflame Universe client: +- `91498e09b83ce69f46baf9e521d48f23fe502985` (packed client, zip compressed) + +# Development Documentation +This is a Work in Progress, but below are some quick links to documentaion for systems and structs in the server +[Networked message structs](https://lcdruniverse.org/lu_packets/lu_packets/index.html) +[General system documentation](https://docs.lu-dev.net/en/latest/index.html) # Credits + ## DLU Team * [DarwinAnim8or](https://github.com/DarwinAnim8or) * [Wincent01](https://github.com/Wincent01) diff --git a/docs/Commands.md b/docs/Commands.md index 7a15bf37..060c2ba0 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -1,6 +1,5 @@ # In-game commands - -Here is a summary of the commands available in-game. All commands are prefixed by `/` and typed in the in-game chat window. Some commands requires admin privileges. Operands within `<>` are required, operands within `()` are not. For the full list of in-game commands, please checkout [the source file](../dGame/dUtilities/SlashCommandHandler.cpp). +* All commands are prefixed by `/` and typed in the in-game chat window. Some commands require elevated gmlevel privileges. Operands within `<>` are required, operands within `()` are not. ## General Commands @@ -71,6 +70,7 @@ These commands are primarily for development and testing. The usage of many of t |createprivate|`/createprivate <zone id> <clone id> <password>`|Creates a private zone with password.|8| |debugui|`/debugui`|Toggle Debug UI.|8| |dismount|`/dismount`|Dismounts you from the vehicle or mount.|8| +|reloadconfig|`/reloadconfig`|Reloads the server with the new config values.|8| |force-save|`/force-save`|While saving to database usually happens on regular intervals and when you disconnect from the server, this command saves your player's data to the database.|8| |freecam|`/freecam`|Toggles freecam mode.|8| |freemoney|`/freemoney <coins>`|Gives coins.|8| From 0e9c0a8917f3afbcfda452ab9e8c66504aad15d9 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 28 Dec 2022 14:03:07 -0800 Subject: [PATCH 208/322] Fix MovementSwitch Behavior (#927) --- dGame/dBehaviors/MovementSwitchBehavior.cpp | 55 ++++++++++++--------- dGame/dBehaviors/MovementSwitchBehavior.h | 13 ++++- 2 files changed, 43 insertions(+), 25 deletions(-) diff --git a/dGame/dBehaviors/MovementSwitchBehavior.cpp b/dGame/dBehaviors/MovementSwitchBehavior.cpp index c893e6e1..0c11380f 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.cpp +++ b/dGame/dBehaviors/MovementSwitchBehavior.cpp @@ -4,17 +4,17 @@ #include "dLogger.h" void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { - if (this->m_groundAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && - this->m_jumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && - this->m_fallingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && - this->m_doubleJumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && - this->m_airAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && - this->m_jetpackAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { - return; - } - uint32_t movementType{}; if (!bitStream->Read(movementType)) { + if (this->m_groundAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && + this->m_jumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && + this->m_fallingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && + this->m_doubleJumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && + this->m_airAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && + this->m_jetpackAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && + this->m_movingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { + return; + } Game::logger->Log("MovementSwitchBehavior", "Unable to read movementType from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); return; }; @@ -27,33 +27,40 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* this->m_jumpAction->Handle(context, bitStream, branch); break; case 3: - this->m_fallingAction->Handle(context, bitStream, branch); + this->m_airAction->Handle(context, bitStream, branch); break; case 4: this->m_doubleJumpAction->Handle(context, bitStream, branch); break; case 5: - this->m_airAction->Handle(context, bitStream, branch); + this->m_fallingAction->Handle(context, bitStream, branch); break; case 6: this->m_jetpackAction->Handle(context, bitStream, branch); break; default: - Game::logger->Log("MovementSwitchBehavior", "Invalid movement behavior type (%i)!", movementType); + this->m_groundAction->Handle(context, bitStream, branch); break; } } -void MovementSwitchBehavior::Load() { - this->m_airAction = GetAction("air_action"); - - this->m_doubleJumpAction = GetAction("double_jump_action"); - - this->m_fallingAction = GetAction("falling_action"); - - this->m_groundAction = GetAction("ground_action"); - - this->m_jetpackAction = GetAction("jetpack_action"); - - this->m_jumpAction = GetAction("jump_action"); +Behavior* MovementSwitchBehavior::LoadMovementType(std::string movementType) { + float actionValue = GetFloat(movementType, -1.0f); + auto loadedBehavior = GetAction(actionValue != -1.0f ? actionValue : 0.0f); + if (actionValue == -1.0f && loadedBehavior->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { + loadedBehavior = this->m_groundAction; + } + return loadedBehavior; +} + +void MovementSwitchBehavior::Load() { + float groundActionValue = GetFloat("ground_action", -1.0f); + this->m_groundAction = GetAction(groundActionValue != -1.0f ? groundActionValue : 0.0f); + + this->m_airAction = LoadMovementType("air_action"); + this->m_doubleJumpAction = LoadMovementType("double_jump_action"); + this->m_fallingAction = LoadMovementType("falling_action"); + this->m_jetpackAction = LoadMovementType("jetpack_action"); + this->m_jumpAction = LoadMovementType("jump_action"); + this->m_movingAction = LoadMovementType("moving_action"); } diff --git a/dGame/dBehaviors/MovementSwitchBehavior.h b/dGame/dBehaviors/MovementSwitchBehavior.h index 82e1a9e9..e6ff96f6 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.h +++ b/dGame/dBehaviors/MovementSwitchBehavior.h @@ -3,7 +3,7 @@ class MovementSwitchBehavior final : public Behavior { -public: +private: /* * Members */ @@ -19,6 +19,17 @@ public: Behavior* m_jumpAction; + Behavior* m_movingAction; + + /** + * @brief Loads a movement type from the database into a behavior + * + * @param movementType The movement type to lookup in the database + * @param behaviorToLoad The Behavior where the result will be stored + */ + Behavior* LoadMovementType(std::string movementType); + +public: /* * Inherited */ From 99c0ca253cb587f3f43b440d39f9ce331748f62a Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 28 Dec 2022 14:04:37 -0800 Subject: [PATCH 209/322] Basic Attack Behavior Live Accuracy Improvements (#926) * Overhaul BasicAttack Behavior so it matches the live 1.10.64 client --- dCommon/dEnums/eBasicAttackSuccessTypes.h | 12 ++ dGame/dBehaviors/BasicAttackBehavior.cpp | 232 +++++++++++++++------- dGame/dBehaviors/BasicAttackBehavior.h | 39 ++++ 3 files changed, 206 insertions(+), 77 deletions(-) create mode 100644 dCommon/dEnums/eBasicAttackSuccessTypes.h diff --git a/dCommon/dEnums/eBasicAttackSuccessTypes.h b/dCommon/dEnums/eBasicAttackSuccessTypes.h new file mode 100644 index 00000000..8c06da8a --- /dev/null +++ b/dCommon/dEnums/eBasicAttackSuccessTypes.h @@ -0,0 +1,12 @@ +#ifndef __EBASICATTACKSUCCESSTYPES__H__ +#define __EBASICATTACKSUCCESSTYPES__H__ + +#include <cstdint> + +enum class eBasicAttackSuccessTypes : uint8_t { + SUCCESS = 1, + FAILARMOR, + FAILIMMUNE +}; + +#endif //!__EBASICATTACKSUCCESSTYPES__H__ diff --git a/dGame/dBehaviors/BasicAttackBehavior.cpp b/dGame/dBehaviors/BasicAttackBehavior.cpp index f166f00c..0378cb5e 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.cpp +++ b/dGame/dBehaviors/BasicAttackBehavior.cpp @@ -5,7 +5,7 @@ #include "EntityManager.h" #include "DestroyableComponent.h" #include "BehaviorContext.h" - +#include "eBasicAttackSuccessTypes.h" void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { if (context->unmanaged) { @@ -31,130 +31,120 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi } Game::logger->LogDebug("BasicAttackBehavior", "Number of allocated bits %i", allocatedBits); const auto baseAddress = bitStream->GetReadOffset(); + + DoHandleBehavior(context, bitStream, branch); + + bitStream->SetReadOffset(baseAddress + allocatedBits); +} + +void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto* targetEntity = EntityManager::Instance()->GetEntity(branch.target); + if (!targetEntity) { + Game::logger->Log("BasicAttackBehavior", "Target targetEntity %i not found.", branch.target); + return; + } + + auto* destroyableComponent = targetEntity->GetComponent<DestroyableComponent>(); + if (!destroyableComponent) { + Game::logger->Log("BasicAttackBehavior", "No destroyable found on the obj/lot %llu/%i", branch.target, targetEntity->GetLOT()); + return; + } + bool isBlocked{}; bool isImmune{}; bool isSuccess{}; if (!bitStream->Read(isBlocked)) { - Game::logger->LogDebug("BasicAttackBehavior", "Unable to read isBlocked"); + Game::logger->Log("BasicAttackBehavior", "Unable to read isBlocked"); return; } - if (isBlocked) return; + if (isBlocked) { + destroyableComponent->SetAttacksToBlock(std::min(destroyableComponent->GetAttacksToBlock() - 1, 0U)); + EntityManager::Instance()->SerializeEntity(targetEntity); + this->m_OnFailBlocked->Handle(context, bitStream, branch); + return; + } if (!bitStream->Read(isImmune)) { - Game::logger->LogDebug("BasicAttackBehavior", "Unable to read isImmune"); + Game::logger->Log("BasicAttackBehavior", "Unable to read isImmune"); return; } - if (isImmune) return; + if (isImmune) { + this->m_OnFailImmune->Handle(context, bitStream, branch); + return; + } - if (bitStream->Read(isSuccess) && isSuccess) { // Success - uint32_t unknown{}; - if (!bitStream->Read(unknown)) { - Game::logger->LogDebug("BasicAttackBehavior", "Unable to read unknown"); + if (!bitStream->Read(isSuccess)) { + Game::logger->Log("BasicAttackBehavior", "failed to read success from bitstream"); + return; + } + + if (isSuccess) { + uint32_t armorDamageDealt{}; + if (!bitStream->Read(armorDamageDealt)) { + Game::logger->Log("BasicAttackBehavior", "Unable to read armorDamageDealt"); return; } - uint32_t damageDealt{}; - if (!bitStream->Read(damageDealt)) { - Game::logger->LogDebug("BasicAttackBehavior", "Unable to read damageDealt"); + uint32_t healthDamageDealt{}; + if (!bitStream->Read(healthDamageDealt)) { + Game::logger->Log("BasicAttackBehavior", "Unable to read healthDamageDealt"); return; } - // A value that's too large may be a cheating attempt, so we set it to MIN too - if (damageDealt > this->m_MaxDamage || damageDealt < this->m_MinDamage) { - damageDealt = this->m_MinDamage; + uint32_t totalDamageDealt = armorDamageDealt + healthDamageDealt; + + // A value that's too large may be a cheating attempt, so we set it to MIN + if (totalDamageDealt > this->m_MaxDamage) { + totalDamageDealt = this->m_MinDamage; } - auto* entity = EntityManager::Instance()->GetEntity(branch.target); bool died{}; if (!bitStream->Read(died)) { - Game::logger->LogDebug("BasicAttackBehavior", "Unable to read died"); + Game::logger->Log("BasicAttackBehavior", "Unable to read died"); return; } - - if (entity != nullptr) { - auto* destroyableComponent = entity->GetComponent<DestroyableComponent>(); - if (destroyableComponent != nullptr) { - PlayFx(u"onhit", entity->GetObjectID()); - destroyableComponent->Damage(damageDealt, context->originator, context->skillID); - } - } + auto previousArmor = destroyableComponent->GetArmor(); + auto previousHealth = destroyableComponent->GetHealth(); + PlayFx(u"onhit", targetEntity->GetObjectID()); + destroyableComponent->Damage(totalDamageDealt, context->originator, context->skillID); } uint8_t successState{}; if (!bitStream->Read(successState)) { - Game::logger->LogDebug("BasicAttackBehavior", "Unable to read success state"); + Game::logger->Log("BasicAttackBehavior", "Unable to read success state"); return; } - switch (successState) { - case 1: + switch (static_cast<eBasicAttackSuccessTypes>(successState)) { + case eBasicAttackSuccessTypes::SUCCESS: this->m_OnSuccess->Handle(context, bitStream, branch); break; + case eBasicAttackSuccessTypes::FAILARMOR: + this->m_OnFailArmor->Handle(context, bitStream, branch); + break; default: - Game::logger->LogDebug("BasicAttackBehavior", "Unknown success state (%i)!", successState); + if (static_cast<eBasicAttackSuccessTypes>(successState) != eBasicAttackSuccessTypes::FAILIMMUNE) { + Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!", successState); + return; + } + this->m_OnFailImmune->Handle(context, bitStream, branch); break; } - - bitStream->SetReadOffset(baseAddress + allocatedBits); } void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - auto* self = EntityManager::Instance()->GetEntity(context->originator); - if (self == nullptr) { - Game::logger->LogDebug("BasicAttackBehavior", "Invalid self entity (%llu)!", context->originator); - return; - } - bitStream->AlignWriteToByteBoundary(); const auto allocatedAddress = bitStream->GetWriteOffset(); - bitStream->Write(uint16_t(0)); + bitStream->Write<uint16_t>(0); const auto startAddress = bitStream->GetWriteOffset(); - bitStream->Write0(); // Blocked - bitStream->Write0(); // Immune - bitStream->Write1(); // Success - - if (true) { - uint32_t unknown3 = 0; - bitStream->Write(unknown3); - - auto damage = this->m_MinDamage; - auto* entity = EntityManager::Instance()->GetEntity(branch.target); - - if (entity == nullptr) { - damage = 0; - bitStream->Write(damage); - bitStream->Write(false); - } else { - bitStream->Write(damage); - bitStream->Write(true); - - auto* destroyableComponent = entity->GetComponent<DestroyableComponent>(); - if (damage != 0 && destroyableComponent != nullptr) { - PlayFx(u"onhit", entity->GetObjectID(), 1); - destroyableComponent->Damage(damage, context->originator, context->skillID, false); - context->ScheduleUpdate(branch.target); - } - } - } - - uint8_t successState = 1; - bitStream->Write(successState); - - switch (successState) { - case 1: - this->m_OnSuccess->Calculate(context, bitStream, branch); - break; - default: - Game::logger->LogDebug("BasicAttackBehavior", "Unknown success state (%i)!", successState); - break; - } + DoBehaviorCalculation(context, bitStream, branch); const auto endAddress = bitStream->GetWriteOffset(); const uint16_t allocate = endAddress - startAddress + 1; @@ -164,6 +154,87 @@ void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream->SetWriteOffset(startAddress + allocate); } +void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto* targetEntity = EntityManager::Instance()->GetEntity(branch.target); + if (!targetEntity) { + Game::logger->Log("BasicAttackBehavior", "Target entity %llu is null!", branch.target); + return; + } + + auto* destroyableComponent = targetEntity->GetComponent<DestroyableComponent>(); + if (!destroyableComponent || !destroyableComponent->GetParent()) { + Game::logger->Log("BasicAttackBehavior", "No destroyable component on %llu", branch.target); + return; + } + + const bool isBlocking = destroyableComponent->GetAttacksToBlock() > 0; + + bitStream->Write(isBlocking); + + if (isBlocking) { + destroyableComponent->SetAttacksToBlock(destroyableComponent->GetAttacksToBlock() - 1); + EntityManager::Instance()->SerializeEntity(targetEntity); + this->m_OnFailBlocked->Calculate(context, bitStream, branch); + return; + } + + const bool isImmune = destroyableComponent->IsImmune(); + + bitStream->Write(isImmune); + + if (isImmune) { + this->m_OnFailImmune->Calculate(context, bitStream, branch); + return; + } + + bool isSuccess = false; + const uint32_t previousHealth = destroyableComponent->GetHealth(); + const uint32_t previousArmor = destroyableComponent->GetArmor(); + + const auto damage = this->m_MinDamage; + + PlayFx(u"onhit", targetEntity->GetObjectID(), 1); + destroyableComponent->Damage(damage, context->originator, context->skillID, false); + context->ScheduleUpdate(branch.target); + + const uint32_t armorDamageDealt = previousArmor - destroyableComponent->GetArmor(); + const uint32_t healthDamageDealt = previousHealth - destroyableComponent->GetHealth(); + isSuccess = armorDamageDealt > 0 || healthDamageDealt > 0 || (armorDamageDealt + healthDamageDealt) > 0; + + bitStream->Write(isSuccess); + + eBasicAttackSuccessTypes successState = eBasicAttackSuccessTypes::FAILIMMUNE; + if (isSuccess) { + if (healthDamageDealt >= 1) { + successState = eBasicAttackSuccessTypes::SUCCESS; + } else if (armorDamageDealt >= 1) { + successState = this->m_OnFailArmor->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY ? eBasicAttackSuccessTypes::FAILIMMUNE : eBasicAttackSuccessTypes::FAILARMOR; + } + + bitStream->Write(armorDamageDealt); + bitStream->Write(healthDamageDealt); + bitStream->Write(targetEntity->GetIsDead()); + } + + bitStream->Write(successState); + + switch (static_cast<eBasicAttackSuccessTypes>(successState)) { + case eBasicAttackSuccessTypes::SUCCESS: + this->m_OnSuccess->Calculate(context, bitStream, branch); + break; + case eBasicAttackSuccessTypes::FAILARMOR: + this->m_OnFailArmor->Calculate(context, bitStream, branch); + break; + default: + if (static_cast<eBasicAttackSuccessTypes>(successState) != eBasicAttackSuccessTypes::FAILIMMUNE) { + Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!", successState); + break; + } + this->m_OnFailImmune->Calculate(context, bitStream, branch); + break; + } +} + void BasicAttackBehavior::Load() { this->m_MinDamage = GetInt("min damage"); if (this->m_MinDamage == 0) this->m_MinDamage = 1; @@ -171,7 +242,14 @@ void BasicAttackBehavior::Load() { this->m_MaxDamage = GetInt("max damage"); if (this->m_MaxDamage == 0) this->m_MaxDamage = 1; + // The client sets the minimum damage to maximum, so we'll do the same. These are usually the same value anyways. + if (this->m_MinDamage < this->m_MaxDamage) this->m_MinDamage = this->m_MaxDamage; + this->m_OnSuccess = GetAction("on_success"); this->m_OnFailArmor = GetAction("on_fail_armor"); + + this->m_OnFailImmune = GetAction("on_fail_immune"); + + this->m_OnFailBlocked = GetAction("on_fail_blocked"); } diff --git a/dGame/dBehaviors/BasicAttackBehavior.h b/dGame/dBehaviors/BasicAttackBehavior.h index 9c08141c..f6e3fa28 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.h +++ b/dGame/dBehaviors/BasicAttackBehavior.h @@ -7,10 +7,45 @@ public: explicit BasicAttackBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } + /** + * @brief Reads a 16bit short from the bitStream and when the actual behavior handling finishes with all of its branches, the bitStream + * is then offset to after the allocated bits for this stream. + * + */ + void DoHandleBehavior(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); + + /** + * @brief Handles a client initialized Basic Attack Behavior cast to be deserialized and verified on the server. + * + * @param context The Skill's Behavior context. All behaviors in the same tree share the same context + * @param bitStream The bitStream to deserialize. BitStreams will always check their bounds before reading in a behavior + * and will fail gracefully if an overread is detected. + * @param branch The context of this specific branch of the Skill Behavior. Changes based on which branch you are going down. + */ void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + /** + * @brief Writes a 16bit short to the bitStream and when the actual behavior calculation finishes with all of its branches, the number + * of bits used is then written to where the 16bit short initially was. + * + */ void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + /** + * @brief Calculates a server initialized Basic Attack Behavior cast to be serialized to the client + * + * @param context The Skill's Behavior context. All behaviors in the same tree share the same context + * @param bitStream The bitStream to serialize to. + * @param branch The context of this specific branch of the Skill Behavior. Changes based on which branch you are going down. + */ + void DoBehaviorCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); + + /** + * @brief Loads this Behaviors parameters from the database. For this behavior specifically: + * max and min damage will always be the same. If min is less than max, they are both set to max. + * If an action is not in the database, then no action is taken for that result. + * + */ void Load() override; private: uint32_t m_MinDamage; @@ -20,4 +55,8 @@ private: Behavior* m_OnSuccess; Behavior* m_OnFailArmor; + + Behavior* m_OnFailImmune; + + Behavior* m_OnFailBlocked; }; From bd28e4051fa5eb003c4a29366dd03c75eeeeb021 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 29 Dec 2022 01:43:52 -0800 Subject: [PATCH 210/322] Fix Hash Collisions in CDBehaviorParameter table (#930) * Fix hashing * Update CDBehaviorParameterTable.cpp --- dDatabase/Tables/CDBehaviorParameterTable.cpp | 41 ++++++++----------- dDatabase/Tables/CDBehaviorParameterTable.h | 12 +++--- dGame/dBehaviors/Behavior.cpp | 2 +- 3 files changed, 25 insertions(+), 30 deletions(-) diff --git a/dDatabase/Tables/CDBehaviorParameterTable.cpp b/dDatabase/Tables/CDBehaviorParameterTable.cpp index 96015896..d09a71b2 100644 --- a/dDatabase/Tables/CDBehaviorParameterTable.cpp +++ b/dDatabase/Tables/CDBehaviorParameterTable.cpp @@ -4,9 +4,9 @@ //! Constructor CDBehaviorParameterTable::CDBehaviorParameterTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorParameter"); - size_t hash = 0; + uint32_t uniqueParameterId = 0; + uint64_t hash = 0; while (!tableData.eof()) { - hash = 0; CDBehaviorParameter entry; entry.behaviorID = tableData.getIntField(0, -1); auto candidateStringToAdd = std::string(tableData.getStringField(1, "")); @@ -14,15 +14,13 @@ CDBehaviorParameterTable::CDBehaviorParameterTable(void) { if (parameter != m_ParametersList.end()) { entry.parameterID = parameter; } else { - entry.parameterID = m_ParametersList.insert(candidateStringToAdd).first; + entry.parameterID = m_ParametersList.insert(std::make_pair(candidateStringToAdd, uniqueParameterId)).first; + uniqueParameterId++; } + hash = entry.behaviorID; + hash = (hash << 31U) | entry.parameterID->second; entry.value = tableData.getFloatField(2, -1.0f); - GeneralUtils::hash_combine(hash, entry.behaviorID); - GeneralUtils::hash_combine(hash, *entry.parameterID); - - auto it = m_Entries.find(entry.behaviorID); - m_ParametersList.insert(*entry.parameterID); m_Entries.insert(std::make_pair(hash, entry)); tableData.nextRow(); @@ -38,31 +36,28 @@ std::string CDBehaviorParameterTable::GetName(void) const { return "BehaviorParameter"; } -CDBehaviorParameter CDBehaviorParameterTable::GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue) { - CDBehaviorParameter returnValue; - returnValue.behaviorID = 0; - returnValue.parameterID = m_ParametersList.end(); - returnValue.value = defaultValue; +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; - size_t hash = 0; - GeneralUtils::hash_combine(hash, behaviorID); - GeneralUtils::hash_combine(hash, name); + uint64_t hash = behaviorID; + + hash = (hash << 31U) | parameterID->second; // Search for specific parameter const auto& it = m_Entries.find(hash); - return it != m_Entries.end() ? it->second : returnValue; + return it != m_Entries.end() ? it->second.value : defaultValue; } std::map<std::string, float> CDBehaviorParameterTable::GetParametersByBehaviorID(uint32_t behaviorID) { - size_t hash; + uint64_t hashBase = behaviorID; std::map<std::string, float> returnInfo; - for (auto parameterCandidate : m_ParametersList) { - hash = 0; - GeneralUtils::hash_combine(hash, behaviorID); - GeneralUtils::hash_combine(hash, parameterCandidate); + uint64_t hash; + for (auto& parameterCandidate : m_ParametersList) { + hash = (hashBase << 31U) | parameterCandidate.second; auto infoCandidate = m_Entries.find(hash); if (infoCandidate != m_Entries.end()) { - returnInfo.insert(std::make_pair(*(infoCandidate->second.parameterID), infoCandidate->second.value)); + returnInfo.insert(std::make_pair(infoCandidate->second.parameterID->first, infoCandidate->second.value)); } } return returnInfo; diff --git a/dDatabase/Tables/CDBehaviorParameterTable.h b/dDatabase/Tables/CDBehaviorParameterTable.h index f067e7d2..5d0d8b72 100644 --- a/dDatabase/Tables/CDBehaviorParameterTable.h +++ b/dDatabase/Tables/CDBehaviorParameterTable.h @@ -12,16 +12,16 @@ //! BehaviorParameter Entry Struct struct CDBehaviorParameter { - unsigned int behaviorID; //!< The Behavior ID - std::unordered_set<std::string>::iterator parameterID; //!< The Parameter ID - float value; //!< The value of the behavior template + unsigned int behaviorID; //!< The Behavior ID + std::unordered_map<std::string, uint32_t>::iterator parameterID; //!< The Parameter ID + float value; //!< The value of the behavior template }; //! BehaviorParameter table class CDBehaviorParameterTable : public CDTable { private: - std::unordered_map<size_t, CDBehaviorParameter> m_Entries; - std::unordered_set<std::string> m_ParametersList; + std::unordered_map<uint64_t, CDBehaviorParameter> m_Entries; + std::unordered_map<std::string, uint32_t> m_ParametersList; public: //! Constructor @@ -36,7 +36,7 @@ public: */ std::string GetName(void) const override; - CDBehaviorParameter GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue = 0); + float GetValue(const uint32_t behaviorID, const std::string& name, const float defaultValue = 0); std::map<std::string, float> GetParametersByBehaviorID(uint32_t behaviorID); }; diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index 568780d0..40c37a95 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -439,7 +439,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<CDBehaviorParameterTable>("BehaviorParameter"); - return BehaviorParameterTable->GetEntry(this->m_behaviorId, name, defaultValue).value; + return BehaviorParameterTable->GetValue(this->m_behaviorId, name, defaultValue); } From 9adbb7aa86a134707a9b5470d1bf83fb24ba5f90 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 29 Dec 2022 06:34:53 -0800 Subject: [PATCH 211/322] Address World Server Packet timing and erroneous log (#929) * Fix overread in projectile behavior * Fix stuns * Correctly read in bitStream * Fix projectile behavior * Address movement type issues * Update shutdown time to be accurate * Fix small issues --- dGame/dBehaviors/BasicAttackBehavior.cpp | 2 +- dWorldServer/WorldServer.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dGame/dBehaviors/BasicAttackBehavior.cpp b/dGame/dBehaviors/BasicAttackBehavior.cpp index 0378cb5e..97068d91 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.cpp +++ b/dGame/dBehaviors/BasicAttackBehavior.cpp @@ -40,7 +40,7 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* targetEntity = EntityManager::Instance()->GetEntity(branch.target); if (!targetEntity) { - Game::logger->Log("BasicAttackBehavior", "Target targetEntity %i not found.", branch.target); + Game::logger->Log("BasicAttackBehavior", "Target targetEntity %llu not found.", branch.target); return; } diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index de6deb2a..73157c09 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -416,7 +416,7 @@ int main(int argc, char** argv) { HandlePacket(packet); auto t2 = std::chrono::high_resolution_clock::now(); - timeSpent += std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count(); + timeSpent += std::chrono::duration_cast<std::chrono::duration<float>>(t2 - t1).count(); Game::server->DeallocatePacket(packet); packet = nullptr; } else { From 34b5f0f9d646623f6cd8ee4f3183eef865629425 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 31 Dec 2022 02:46:25 -0600 Subject: [PATCH 212/322] add uncast to speed behavior (#932) --- dGame/dBehaviors/SpeedBehavior.cpp | 12 ++++++++---- dGame/dBehaviors/SpeedBehavior.h | 2 ++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/dGame/dBehaviors/SpeedBehavior.cpp b/dGame/dBehaviors/SpeedBehavior.cpp index bec2b1cb..d326aa45 100644 --- a/dGame/dBehaviors/SpeedBehavior.cpp +++ b/dGame/dBehaviors/SpeedBehavior.cpp @@ -29,6 +29,14 @@ void SpeedBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitSt Handle(context, bitStream, branch); } +void SpeedBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { + End(context, branch, LWOOBJID_EMPTY); +} + +void SpeedBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { + End(context, branch, second); +} + void SpeedBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { auto* target = EntityManager::Instance()->GetEntity(branch.target); if (!target) return; @@ -40,10 +48,6 @@ void SpeedBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, EntityManager::Instance()->SerializeEntity(target); } -void SpeedBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { - End(context, branch, second); -} - void SpeedBehavior::Load() { m_RunSpeed = GetFloat("run_speed"); m_AffectsCaster = GetBoolean("affects_caster"); diff --git a/dGame/dBehaviors/SpeedBehavior.h b/dGame/dBehaviors/SpeedBehavior.h index 57c46842..88b85820 100644 --- a/dGame/dBehaviors/SpeedBehavior.h +++ b/dGame/dBehaviors/SpeedBehavior.h @@ -15,6 +15,8 @@ public: void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; + void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; From fab44142042789493667d4b5677c10f4663d91be Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 31 Dec 2022 03:56:12 -0800 Subject: [PATCH 213/322] Fix serratorizer chargeup time (#931) --- migrations/cdserver/5_serratorizer_chargeup_fix.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 migrations/cdserver/5_serratorizer_chargeup_fix.sql diff --git a/migrations/cdserver/5_serratorizer_chargeup_fix.sql b/migrations/cdserver/5_serratorizer_chargeup_fix.sql new file mode 100644 index 00000000..a61da2c2 --- /dev/null +++ b/migrations/cdserver/5_serratorizer_chargeup_fix.sql @@ -0,0 +1 @@ +UPDATE behaviorParameter SET value = 20 WHERE behaviorID = 21001 AND parameterID = "value 2"; From 737eaba54d3d96a2643b4f804c366c7c44883f92 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 31 Dec 2022 03:56:30 -0800 Subject: [PATCH 214/322] Serialize target with GameMessageStartSkill (#933) --- dGame/dComponents/SkillComponent.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index 445a837e..0608c63b 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -246,6 +246,7 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c start.skillID = skillId; start.uiSkillHandle = context->skillUId; start.optionalOriginatorID = context->originator; + start.optionalTargetID = target; auto* originator = EntityManager::Instance()->GetEntity(context->originator); From 09157506bf503913a0199b86678ca26f7980677d Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 31 Dec 2022 11:44:09 -0800 Subject: [PATCH 215/322] Fix Complete Overhaul (#934) Check your pointers :) --- dGame/dGameMessages/GameMessages.cpp | 15 +++++++++++++-- dGame/dInventory/Item.cpp | 9 +++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 37aeb093..2423915e 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -28,6 +28,7 @@ #include "GameConfig.h" #include "RocketLaunchLupComponent.h" #include "eUnequippableActiveType.h" +#include "RacingTaskParam.h" #include <sstream> #include <future> @@ -5482,7 +5483,8 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* auto* temp = inv->GetInventory(TEMP_MODELS); std::vector<LOT> modList; - + auto& oldPartList = character->GetVar<std::string>(u"currentModifiedBuild"); + bool everyPieceSwapped = !oldPartList.empty(); // If the player didn't put a build in initially, then they should not get this achievement. if (count >= 3) { std::u16string modules; @@ -5490,7 +5492,8 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* uint32_t mod; inStream->Read(mod); modList.push_back(mod); - modules += u"1:" + (GeneralUtils::to_u16string(mod)); + auto modToStr = GeneralUtils::to_u16string(mod); + modules += u"1:" + (modToStr); if (k + 1 != count) modules += u"+"; if (temp->GetLotCount(mod) > 0) { @@ -5498,6 +5501,13 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* } else { inv->RemoveItem(mod, 1); } + + // Doing this check for 1 singular mission that needs to know when you've swapped every part out during a car modular build. + // since all 8129's are the same, skip checking that + if (mod != 8129) { + if (oldPartList.find(GeneralUtils::UTF16ToWTF8(modToStr)) != std::string::npos) everyPieceSwapped = false; + + } } const auto moduleAssembly = new LDFData<std::u16string>(u"assemblyPartLOTs", modules); @@ -5516,6 +5526,7 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* if (entity->GetLOT() != 9980 || Game::server->GetZoneID() != 1200) { if (missionComponent != nullptr) { missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, entity->GetLOT(), entity->GetObjectID()); + if (count >= 7 && everyPieceSwapped) missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, LWOOBJID_EMPTY, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_MODULAR_BUILDING); } } } diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index a3d4cfc0..4f3626e3 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -347,6 +347,15 @@ void Item::Disassemble(const eInventoryType inventoryType) { if (data->GetKey() == u"assemblyPartLOTs") { auto modStr = data->GetValueAsString(); + // This shouldn't be null but always check your pointers. + if (GetInventory()) { + auto inventoryComponent = GetInventory()->GetComponent(); + if (inventoryComponent) { + auto entity = inventoryComponent->GetParent(); + if (entity) entity->SetVar<std::string>(u"currentModifiedBuild", modStr); + } + } + std::vector<LOT> modArray; std::stringstream ssData(modStr); From 19be0a61b2f4a9823796539e9e81a0effb7b0592 Mon Sep 17 00:00:00 2001 From: EmosewaMC <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 1 Jan 2023 04:51:22 -0800 Subject: [PATCH 216/322] Eliminate WorldConfig Magic Numbers Add comments for fields Use the name directly --- dGame/dComponents/DestroyableComponent.cpp | 19 ++--- dGame/dMission/Mission.cpp | 5 +- dGame/dUtilities/Mail.cpp | 6 +- dZoneManager/WorldConfig.h | 67 +++++++++++++++ dZoneManager/dZoneManager.cpp | 96 ++++++++++++++++++---- dZoneManager/dZoneManager.h | 31 +++---- 6 files changed, 177 insertions(+), 47 deletions(-) create mode 100644 dZoneManager/WorldConfig.h diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index d832ef93..aab4d670 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -30,6 +30,7 @@ #include "PossessorComponent.h" #include "InventoryComponent.h" #include "dZoneManager.h" +#include "WorldConfig.h" DestroyableComponent::DestroyableComponent(Entity* parent) : Component(parent) { m_iArmor = 0; @@ -765,20 +766,16 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType uint64_t coinsTotal = character->GetCoins(); if (coinsTotal > 0) { - uint64_t coinsToLoose = 1; + const uint64_t minCoinsToLose = dZoneManager::Instance()->GetWorldConfig()->coinsLostOnDeathMin; + const uint64_t maxCoinsToLose = dZoneManager::Instance()->GetWorldConfig()->coinsLostOnDeathMax; + const float coinPercentageToLose = dZoneManager::Instance()->GetWorldConfig()->coinsLostOnDeathPercent; - if (coinsTotal >= 200) { - float hundreth = (coinsTotal / 100.0f); - coinsToLoose = static_cast<int>(hundreth); - } + uint64_t coinsToLose = std::max(static_cast<uint64_t>(coinsTotal * coinPercentageToLose), minCoinsToLose); + coinsToLose = std::min(maxCoinsToLose, coinsToLose); - if (coinsToLoose > 10000) { - coinsToLoose = 10000; - } + coinsTotal -= coinsToLose; - coinsTotal -= coinsToLoose; - - LootGenerator::Instance().DropLoot(m_Parent, m_Parent, -1, coinsToLoose, coinsToLoose); + LootGenerator::Instance().DropLoot(m_Parent, m_Parent, -1, coinsToLose, coinsToLose); character->SetCoins(coinsTotal, eLootSourceType::LOOT_SOURCE_PICKUP); } } diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index 61b41992..a1ae724a 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -18,6 +18,7 @@ #include "dZoneManager.h" #include "InventoryComponent.h" #include "Database.h" +#include "WorldConfig.h" Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { m_MissionComponent = missionComponent; @@ -435,9 +436,9 @@ void Mission::YieldRewards() { int32_t coinsToSend = 0; if (info->LegoScore > 0) { eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; - if (levelComponent->GetLevel() >= dZoneManager::Instance()->GetMaxLevel()) { + if (levelComponent->GetLevel() >= dZoneManager::Instance()->GetWorldConfig()->levelCap) { // Since the character is at the level cap we reward them with coins instead of UScore. - coinsToSend += info->LegoScore * dZoneManager::Instance()->GetLevelCapCurrencyConversion(); + coinsToSend += info->LegoScore * dZoneManager::Instance()->GetWorldConfig()->levelCapCurrencyConversion; } else { characterComponent->SetUScore(characterComponent->GetUScore() + info->LegoScore); GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), info->LegoScore, lootSource); diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index 7047972f..a4ac63e1 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -22,6 +22,8 @@ #include "MissionComponent.h" #include "ChatPackets.h" #include "Character.h" +#include "dZoneManager.h" +#include "WorldConfig.h" void Mail::SendMail(const Entity* recipient, const std::string& subject, const std::string& body, const LOT attachment, const uint16_t attachmentCount) { @@ -191,7 +193,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd uint32_t itemID = static_cast<uint32_t>(attachmentID); LOT itemLOT = 0; //Inventory::InventoryType itemType; - int mailCost = 25; + int mailCost = dZoneManager::Instance()->GetWorldConfig()->mailBaseFee; int stackSize = 0; auto inv = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); Item* item = nullptr; @@ -199,7 +201,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd if (itemID > 0 && attachmentCount > 0 && inv) { item = inv->FindItemById(attachmentID); if (item) { - mailCost += (item->GetInfo().baseValue * 0.1f); + mailCost += (item->GetInfo().baseValue * dZoneManager::Instance()->GetWorldConfig()->mailPercentAttachmentFee); stackSize = item->GetCount(); itemLOT = item->GetLot(); } else { diff --git a/dZoneManager/WorldConfig.h b/dZoneManager/WorldConfig.h new file mode 100644 index 00000000..a98433a1 --- /dev/null +++ b/dZoneManager/WorldConfig.h @@ -0,0 +1,67 @@ +#ifndef __WORLDCONFIG__H__ +#define __WORLDCONFIG__H__ + +#include <cstdint> +#include <string> + +struct WorldConfig { + int32_t worldConfigID{}; //! Primary key for WorlcConfig table + float peGravityValue{}; //! Unknown + float peBroadphaseWorldSize{}; //! Unknown + float peGameObjScaleFactor{}; //! Unknown + float characterRotationSpeed{}; //! The players' rotation speed + float characterWalkForwardSpeed{}; //! The players' walk forward speed + float characterWalkBackwardSpeed{}; //! The players' walk backwards speed + float characterWalkStrafeSpeed{}; //! The players' strafe speed + float characterWalkStrafeForwardSpeed{}; //! The players' walk strafe forward speed + float characterWalkStrafeBackwardSpeed{}; //! The players' walk strage backwards speed + float characterRunBackwardSpeed{}; //! The players' run backwards speed + float characterRunStrafeSpeed{}; //! The players' run strafe speed + float characterRunStrafeForwardSpeed{}; //! The players' run strafe forward speed + float characterRunStrafeBackwardSpeed{}; //! The players' run strage backwards speed + float globalCooldown{}; //! The global ability cooldown + float characterGroundedTime{}; //! Unknown + float characterGroundedSpeed{}; //! Unknown + float globalImmunityTime{}; //! Unknown + float characterMaxSlope{}; //! Unknown + float defaultRespawnTime{}; //! Unknown + float missionTooltipTimeout{}; + float vendorBuyMultiplier{}; //! The buy scalar for buying from vendors + float petFollowRadius{}; //! The players' pet follow radius + float characterEyeHeight{}; //! The players' eye height + float flightVerticalVelocity{}; //! Unknown + float flightAirspeed{}; //! Unknown + float flightFuelRatio{}; //! Unknown + float flightMaxAirspeed{}; //! Unknown + float fReputationPerVote{}; //! Unknown + int32_t propertyCloneLimit{}; //! Unknown + int32_t defaultHomespaceTemplate{}; //! Unknown + float coinsLostOnDeathPercent{}; //! The percentage of coins to lose on a player death + int32_t coinsLostOnDeathMin{}; //! The minimum number of coins to lose on a player death + int32_t coinsLostOnDeathMax{}; //! The maximum number of coins to lose on a player death + int32_t characterVotesPerDay{}; //! Unknown + int32_t propertyModerationRequestApprovalCost{};//! Unknown + int32_t propertyModerationRequestReviewCost{}; //! Unknown + int32_t propertyModRequestsAllowedSpike{}; //! Unknown + int32_t propertyModRequestsAllowedInterval{}; //! Unknown + int32_t propertyModRequestsAllowedTotal{}; //! Unknown + int32_t propertyModRequestsSpikeDuration{}; //! Unknown + int32_t propertyModRequestsIntervalDuration{}; //! Unknown + bool modelModerateOnCreate{}; //! Unknown + float defaultPropertyMaxHeight{}; //! Unknown + float reputationPerVoteCast{}; //! Unknown + float reputationPerVoteReceived{}; //! Unknown + int32_t showcaseTopModelConsiderationBattles{}; //! Unknown + float reputationPerBattlePromotion{}; //! Unknown + float coinsLostOnDeathMinTimeout{}; //! Unknown + float coinsLostOnDeathMaxTimeout{}; //! Unknown + int32_t mailBaseFee{}; //! The base fee to take when a player sends mail + float mailPercentAttachmentFee{}; //! The scalar multiplied by an items base cost to determine how much that item costs to be mailed + int32_t propertyReputationDelay{}; //! Unknown + int32_t levelCap{}; //! The maximum player level + std::string levelUpBehaviorEffect{}; //! Unknown + int32_t characterVersion{}; //! Unknown + int32_t levelCapCurrencyConversion{}; //! The ratio of UScore (LEGO Score) to coins +}; + +#endif //! __WORLDCONFIG__H__ diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index 102fb3af..0b7844a3 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -8,6 +8,7 @@ #include "DestroyableComponent.h" #include "GameMessages.h" #include "VanityUtilities.h" +#include "WorldConfig.h" #include <chrono> #include "../dWorldServer/ObjectIDManager.h" @@ -53,6 +54,8 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { endTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count(); + LoadWorldConfig(); + Game::logger->Log("dZoneManager", "Zone prepared in: %llu ms", (endTime - startTime)); VanityUtilities::SpawnVanity(); @@ -69,6 +72,7 @@ dZoneManager::~dZoneManager() { m_Spawners.erase(p.first); } + if (m_WorldConfig) delete m_WorldConfig; } Zone* dZoneManager::GetZone() { @@ -117,24 +121,6 @@ LWOZONEID dZoneManager::GetZoneID() const { return m_ZoneID; } -uint32_t dZoneManager::GetMaxLevel() { - if (m_MaxLevel == 0) { - auto tableData = CDClientDatabase::ExecuteQuery("SELECT LevelCap FROM WorldConfig WHERE WorldConfigID = 1 LIMIT 1;"); - m_MaxLevel = tableData.getIntField(0, -1); - tableData.finalize(); - } - return m_MaxLevel; -} - -int32_t dZoneManager::GetLevelCapCurrencyConversion() { - if (m_CurrencyConversionRate == 0) { - auto tableData = CDClientDatabase::ExecuteQuery("SELECT LevelCapCurrencyConversion FROM WorldConfig WHERE WorldConfigID = 1 LIMIT 1;"); - m_CurrencyConversionRate = tableData.getIntField(0, -1); - tableData.finalize(); - } - return m_CurrencyConversionRate; -} - void dZoneManager::Update(float deltaTime) { for (auto spawner : m_Spawners) { spawner.second->Update(deltaTime); @@ -249,3 +235,77 @@ uint32_t dZoneManager::GetUniqueMissionIdStartingValue() { } return m_UniqueMissionIdStart; } + +void dZoneManager::LoadWorldConfig() { + Game::logger->Log("dZoneManager", "Loading WorldConfig into memory"); + + auto worldConfig = CDClientDatabase::ExecuteQuery("SELECT * FROM WorldConfig;"); + + if (!m_WorldConfig) m_WorldConfig = new WorldConfig(); + + if (worldConfig.eof()) { + Game::logger->Log("dZoneManager", "WorldConfig table is empty. Is this intended?"); + return; + } + + // Now read in the giant table + m_WorldConfig->worldConfigID = worldConfig.getIntField("WorldConfigID"); + m_WorldConfig->peGravityValue = worldConfig.getFloatField("pegravityvalue"); + m_WorldConfig->peBroadphaseWorldSize = worldConfig.getFloatField("pebroadphaseworldsize"); + m_WorldConfig->peGameObjScaleFactor = worldConfig.getFloatField("pegameobjscalefactor"); + m_WorldConfig->characterRotationSpeed = worldConfig.getFloatField("character_rotation_speed"); + m_WorldConfig->characterWalkForwardSpeed = worldConfig.getFloatField("character_walk_forward_speed"); + m_WorldConfig->characterWalkBackwardSpeed = worldConfig.getFloatField("character_walk_backward_speed"); + m_WorldConfig->characterWalkStrafeSpeed = worldConfig.getFloatField("character_walk_strafe_speed"); + m_WorldConfig->characterWalkStrafeForwardSpeed = worldConfig.getFloatField("character_walk_strafe_forward_speed"); + m_WorldConfig->characterWalkStrafeBackwardSpeed = worldConfig.getFloatField("character_walk_strafe_backward_speed"); + m_WorldConfig->characterRunBackwardSpeed = worldConfig.getFloatField("character_run_backward_speed"); + m_WorldConfig->characterRunStrafeSpeed = worldConfig.getFloatField("character_run_strafe_speed"); + m_WorldConfig->characterRunStrafeForwardSpeed = worldConfig.getFloatField("character_run_strafe_forward_speed"); + m_WorldConfig->characterRunStrafeBackwardSpeed = worldConfig.getFloatField("character_run_strafe_backward_speed"); + m_WorldConfig->globalCooldown = worldConfig.getFloatField("global_cooldown"); + m_WorldConfig->characterGroundedTime = worldConfig.getFloatField("characterGroundedTime"); + m_WorldConfig->characterGroundedSpeed = worldConfig.getFloatField("characterGroundedSpeed"); + m_WorldConfig->globalImmunityTime = worldConfig.getFloatField("globalImmunityTime"); + m_WorldConfig->characterMaxSlope = worldConfig.getFloatField("character_max_slope"); + m_WorldConfig->defaultRespawnTime = worldConfig.getFloatField("defaultrespawntime"); + m_WorldConfig->missionTooltipTimeout = worldConfig.getFloatField("mission_tooltip_timeout"); + m_WorldConfig->vendorBuyMultiplier = worldConfig.getFloatField("vendor_buy_multiplier"); + m_WorldConfig->petFollowRadius = worldConfig.getFloatField("pet_follow_radius"); + m_WorldConfig->characterEyeHeight = worldConfig.getFloatField("character_eye_height"); + m_WorldConfig->flightVerticalVelocity = worldConfig.getFloatField("flight_vertical_velocity"); + m_WorldConfig->flightAirspeed = worldConfig.getFloatField("flight_airspeed"); + m_WorldConfig->flightFuelRatio = worldConfig.getFloatField("flight_fuel_ratio"); + m_WorldConfig->flightMaxAirspeed = worldConfig.getFloatField("flight_max_airspeed"); + m_WorldConfig->fReputationPerVote = worldConfig.getFloatField("fReputationPerVote"); + m_WorldConfig->propertyCloneLimit = worldConfig.getIntField("nPropertyCloneLimit"); + m_WorldConfig->defaultHomespaceTemplate = worldConfig.getIntField("defaultHomespaceTemplate"); + m_WorldConfig->coinsLostOnDeathPercent = worldConfig.getFloatField("coins_lost_on_death_percent"); + m_WorldConfig->coinsLostOnDeathMin = worldConfig.getIntField("coins_lost_on_death_min"); + m_WorldConfig->coinsLostOnDeathMax = worldConfig.getIntField("coins_lost_on_death_max"); + m_WorldConfig->characterVotesPerDay = worldConfig.getIntField("character_votes_per_day"); + m_WorldConfig->propertyModerationRequestApprovalCost = worldConfig.getIntField("property_moderation_request_approval_cost"); + m_WorldConfig->propertyModerationRequestReviewCost = worldConfig.getIntField("property_moderation_request_review_cost"); + m_WorldConfig->propertyModRequestsAllowedSpike = worldConfig.getIntField("propertyModRequestsAllowedSpike"); + m_WorldConfig->propertyModRequestsAllowedInterval = worldConfig.getIntField("propertyModRequestsAllowedInterval"); + m_WorldConfig->propertyModRequestsAllowedTotal = worldConfig.getIntField("propertyModRequestsAllowedTotal"); + m_WorldConfig->propertyModRequestsSpikeDuration = worldConfig.getIntField("propertyModRequestsSpikeDuration"); + m_WorldConfig->propertyModRequestsIntervalDuration = worldConfig.getIntField("propertyModRequestsIntervalDuration"); + m_WorldConfig->modelModerateOnCreate = worldConfig.getIntField("modelModerateOnCreate") != 0; + m_WorldConfig->defaultPropertyMaxHeight = worldConfig.getFloatField("defaultPropertyMaxHeight"); + m_WorldConfig->reputationPerVoteCast = worldConfig.getFloatField("reputationPerVoteCast"); + m_WorldConfig->reputationPerVoteReceived = worldConfig.getFloatField("reputationPerVoteReceived"); + m_WorldConfig->showcaseTopModelConsiderationBattles = worldConfig.getIntField("showcaseTopModelConsiderationBattles"); + m_WorldConfig->reputationPerBattlePromotion = worldConfig.getFloatField("reputationPerBattlePromotion"); + m_WorldConfig->coinsLostOnDeathMinTimeout = worldConfig.getFloatField("coins_lost_on_death_min_timeout"); + m_WorldConfig->coinsLostOnDeathMaxTimeout = worldConfig.getFloatField("coins_lost_on_death_max_timeout"); + m_WorldConfig->mailBaseFee = worldConfig.getIntField("mail_base_fee"); + m_WorldConfig->mailPercentAttachmentFee = worldConfig.getFloatField("mail_percent_attachment_fee"); + m_WorldConfig->propertyReputationDelay = worldConfig.getIntField("propertyReputationDelay"); + m_WorldConfig->levelCap = worldConfig.getIntField("LevelCap"); + m_WorldConfig->levelUpBehaviorEffect = worldConfig.getStringField("LevelUpBehaviorEffect"); + m_WorldConfig->characterVersion = worldConfig.getIntField("CharacterVersion"); + m_WorldConfig->levelCapCurrencyConversion = worldConfig.getIntField("LevelCapCurrencyConversion"); + worldConfig.finalize(); + Game::logger->Log("dZoneManager", "Loaded WorldConfig into memory"); +} diff --git a/dZoneManager/dZoneManager.h b/dZoneManager/dZoneManager.h index b2fef1e3..c1776e79 100644 --- a/dZoneManager/dZoneManager.h +++ b/dZoneManager/dZoneManager.h @@ -4,6 +4,8 @@ #include "Spawner.h" #include <map> +class WorldConfig; + class dZoneManager { public: enum class dZoneNotifier { @@ -16,6 +18,12 @@ public: InvalidNotifier }; +private: + /** + * Reads the WorldConfig from the CDClientDatabase into memory + */ + void LoadWorldConfig(); + public: static dZoneManager* Instance() { if (!m_Address) { @@ -33,8 +41,6 @@ public: void NotifyZone(const dZoneNotifier& notifier, const LWOOBJID& objectID); //Notifies the zone of a certain event or command. void AddSpawner(LWOOBJID id, Spawner* spawner); LWOZONEID GetZoneID() const; - uint32_t GetMaxLevel(); - int32_t GetLevelCapCurrencyConversion(); LWOOBJID MakeSpawner(SpawnerInfo info); Spawner* GetSpawner(LWOOBJID id); void RemoveSpawner(LWOOBJID id); @@ -45,27 +51,24 @@ public: bool GetPlayerLoseCoinOnDeath() { return m_PlayerLoseCoinsOnDeath; } uint32_t GetUniqueMissionIdStartingValue(); + // The world config should not be modified by a caller. + const WorldConfig* GetWorldConfig() { + if (!m_WorldConfig) LoadWorldConfig(); + return m_WorldConfig; + }; + private: - /** - * The maximum level of the world. - */ - uint32_t m_MaxLevel = 0; - - /** - * The ratio of LEGO Score to currency when the character has hit the max level. - */ - int32_t m_CurrencyConversionRate = 0; - /** * The starting unique mission ID. */ uint32_t m_UniqueMissionIdStart = 0; static dZoneManager* m_Address; //Singleton - Zone* m_pZone; + Zone* m_pZone = nullptr; LWOZONEID m_ZoneID; bool m_PlayerLoseCoinsOnDeath; //Do players drop coins in this zone when smashed std::map<LWOOBJID, Spawner*> m_Spawners; + WorldConfig* m_WorldConfig = nullptr; - Entity* m_ZoneControlObject; + Entity* m_ZoneControlObject = nullptr; }; From 203a150a56688e5cbfdefa500fae80ada4fab40b Mon Sep 17 00:00:00 2001 From: David Markowitz <EmosewaMC@gmail.com> Date: Sun, 1 Jan 2023 16:36:10 -0800 Subject: [PATCH 217/322] Update DestroyableComponent.cpp --- dGame/dComponents/DestroyableComponent.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index aab4d670..8d8ed42a 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -764,9 +764,8 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType if (dZoneManager::Instance()->GetPlayerLoseCoinOnDeath()) { auto* character = m_Parent->GetCharacter(); uint64_t coinsTotal = character->GetCoins(); - - if (coinsTotal > 0) { - const uint64_t minCoinsToLose = dZoneManager::Instance()->GetWorldConfig()->coinsLostOnDeathMin; + const uint64_t minCoinsToLose = dZoneManager::Instance()->GetWorldConfig()->coinsLostOnDeathMin; + if (coinsTotal >= minCoinsToLose) { const uint64_t maxCoinsToLose = dZoneManager::Instance()->GetWorldConfig()->coinsLostOnDeathMax; const float coinPercentageToLose = dZoneManager::Instance()->GetWorldConfig()->coinsLostOnDeathPercent; From dc7d0ce142f3badfaf362846a10179b22fca1086 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 3 Jan 2023 09:21:57 -0800 Subject: [PATCH 218/322] Fix Stuns of duration zero (#938) --- dGame/dComponents/BaseCombatAIComponent.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index c035a807..478058a7 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -179,7 +179,7 @@ void BaseCombatAIComponent::Update(const float deltaTime) { if (m_Disabled || m_Parent->GetIsDead()) return; - + bool stunnedThisFrame = m_Stunned; CalculateCombat(deltaTime); // Putting this here for now if (m_StartPosition == NiPoint3::ZERO) { @@ -192,7 +192,7 @@ void BaseCombatAIComponent::Update(const float deltaTime) { return; } - if (m_Stunned) { + if (stunnedThisFrame) { m_MovementAI->Stop(); return; @@ -248,13 +248,13 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { if (m_Disabled) return; - if (m_StunTime > 0.0f) { + if (m_Stunned) { m_StunTime -= deltaTime; if (m_StunTime > 0.0f) { return; } - + m_StunTime = 0.0f; m_Stunned = false; } From 1789ec7f20380376444d93064fc7dbaeee9bbe92 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 3 Jan 2023 09:22:04 -0800 Subject: [PATCH 219/322] delta compression fixes (#937) --- dGame/dComponents/BaseCombatAIComponent.cpp | 36 ++++++++++----- dGame/dComponents/BaseCombatAIComponent.h | 12 +++++ dGame/dComponents/PetComponent.cpp | 44 ++++++++++--------- .../PlayerForcedMovementComponent.cpp | 4 +- 4 files changed, 61 insertions(+), 35 deletions(-) diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 478058a7..081496a4 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -23,9 +23,9 @@ #include "RebuildComponent.h" #include "DestroyableComponent.h" -BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id) : Component(parent) { +BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id): Component(parent) { m_Target = LWOOBJID_EMPTY; - m_State = AiState::spawn; + SetAiState(AiState::spawn); m_Timer = 1.0f; m_StartPosition = parent->GetPosition(); m_MovementAI = nullptr; @@ -206,7 +206,7 @@ void BaseCombatAIComponent::Update(const float deltaTime) { switch (m_State) { case AiState::spawn: Stun(2.0f); - m_State = AiState::idle; + SetAiState(AiState::idle); break; case AiState::idle: @@ -320,9 +320,9 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { m_Timer = 0; } - m_State = AiState::aggro; + SetAiState(AiState::aggro); } else { - m_State = AiState::idle; + SetAiState(AiState::idle); } for (auto i = 0; i < m_SkillEntries.size(); ++i) { @@ -348,7 +348,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { } if (m_Target == LWOOBJID_EMPTY) { - m_State = AiState::idle; + SetAiState(AiState::idle); return; } @@ -375,7 +375,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { m_MovementAI->Stop(); } - m_State = AiState::aggro; + SetAiState(AiState::aggro); m_Timer = 0; @@ -532,11 +532,20 @@ bool BaseCombatAIComponent::IsMech() { void BaseCombatAIComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - outBitStream->Write1(); - outBitStream->Write(uint32_t(m_State)); - outBitStream->Write(m_Target); + outBitStream->Write(m_DirtyStateOrTarget || bIsInitialUpdate); + if (m_DirtyStateOrTarget || bIsInitialUpdate) { + outBitStream->Write(uint32_t(m_State)); + outBitStream->Write(m_Target); + m_DirtyStateOrTarget = false; + } } +void BaseCombatAIComponent::SetAiState(AiState newState) { + if (newState == this->m_State) return; + this->m_State = newState; + m_DirtyStateOrTarget = true; + EntityManager::Instance()->SerializeEntity(m_Parent); +} bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const { auto* entity = EntityManager::Instance()->GetEntity(target); @@ -585,7 +594,10 @@ bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const { } void BaseCombatAIComponent::SetTarget(const LWOOBJID target) { + if (this->m_Target == target) return; m_Target = target; + m_DirtyStateOrTarget = true; + EntityManager::Instance()->SerializeEntity(m_Parent); } Entity* BaseCombatAIComponent::GetTargetEntity() const { @@ -700,7 +712,7 @@ void BaseCombatAIComponent::OnAggro() { m_MovementAI->SetDestination(targetPos); - m_State = AiState::tether; + SetAiState(AiState::tether); } m_Timer += 0.5f; @@ -726,7 +738,7 @@ void BaseCombatAIComponent::OnTether() { m_MovementAI->SetDestination(m_StartPosition); - m_State = AiState::aggro; + SetAiState(AiState::aggro); } else { if (IsMech() && Vector3::DistanceSquared(targetPos, currentPos) > m_AttackRadius * m_AttackRadius * 3 * 3) return; diff --git a/dGame/dComponents/BaseCombatAIComponent.h b/dGame/dComponents/BaseCombatAIComponent.h index 70a88a42..1f17d562 100644 --- a/dGame/dComponents/BaseCombatAIComponent.h +++ b/dGame/dComponents/BaseCombatAIComponent.h @@ -243,6 +243,12 @@ private: */ std::vector<LWOOBJID> GetTargetWithinAggroRange() const; + /** + * @brief Sets the AiState and prepares the entity for serialization next frame. + * + */ + void SetAiState(AiState newState); + /** * The current state of the AI */ @@ -374,6 +380,12 @@ private: */ bool m_DirtyThreat = false; + /** + * Whether or not the Component has dirty information and should update next frame + * + */ + bool m_DirtyStateOrTarget = false; + /** * Whether the current entity is a mech enemy, needed as mechs tether radius works differently * @return whether this entity is a mech diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 0b136a5c..d11331e7 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -59,7 +59,7 @@ std::map<LOT, uint32_t> PetComponent::petFlags = { { 13067, 838 }, // Skeleton dragon }; -PetComponent::PetComponent(Entity* parent, uint32_t componentId) : Component(parent) { +PetComponent::PetComponent(Entity* parent, uint32_t componentId): Component(parent) { m_ComponentId = componentId; m_Interaction = LWOOBJID_EMPTY; @@ -118,21 +118,23 @@ void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpd outBitStream->Write(m_Owner); } - outBitStream->Write(tamed); - if (tamed) { - outBitStream->Write(m_ModerationStatus); + if (bIsInitialUpdate) { + outBitStream->Write(tamed); + if (tamed) { + outBitStream->Write(m_ModerationStatus); - const auto nameData = GeneralUtils::UTF8ToUTF16(m_Name); - const auto ownerNameData = GeneralUtils::UTF8ToUTF16(m_OwnerName); + const auto nameData = GeneralUtils::UTF8ToUTF16(m_Name); + const auto ownerNameData = GeneralUtils::UTF8ToUTF16(m_OwnerName); - outBitStream->Write(static_cast<uint8_t>(nameData.size())); - for (const auto c : nameData) { - outBitStream->Write(c); - } + outBitStream->Write(static_cast<uint8_t>(nameData.size())); + for (const auto c : nameData) { + outBitStream->Write(c); + } - outBitStream->Write(static_cast<uint8_t>(ownerNameData.size())); - for (const auto c : ownerNameData) { - outBitStream->Write(c); + outBitStream->Write(static_cast<uint8_t>(ownerNameData.size())); + for (const auto c : ownerNameData) { + outBitStream->Write(c); + } } } } @@ -916,16 +918,16 @@ void PetComponent::AddDrainImaginationTimer(Item* item, bool fromTaming) { return; } - // If we are out of imagination despawn the pet. - if (playerDestroyableComponent->GetImagination() == 0) { - this->Deactivate(); - auto playerEntity = playerDestroyableComponent->GetParent(); - if (!playerEntity) return; + // If we are out of imagination despawn the pet. + if (playerDestroyableComponent->GetImagination() == 0) { + this->Deactivate(); + auto playerEntity = playerDestroyableComponent->GetParent(); + if (!playerEntity) return; - GameMessages::SendUseItemRequirementsResponse(playerEntity->GetObjectID(), playerEntity->GetSystemAddress(), UseItemResponse::NoImaginationForPet); - } + GameMessages::SendUseItemRequirementsResponse(playerEntity->GetObjectID(), playerEntity->GetSystemAddress(), UseItemResponse::NoImaginationForPet); + } - this->AddDrainImaginationTimer(item); + this->AddDrainImaginationTimer(item); }); } diff --git a/dGame/dComponents/PlayerForcedMovementComponent.cpp b/dGame/dComponents/PlayerForcedMovementComponent.cpp index 3bcad677..76993507 100644 --- a/dGame/dComponents/PlayerForcedMovementComponent.cpp +++ b/dGame/dComponents/PlayerForcedMovementComponent.cpp @@ -7,8 +7,8 @@ PlayerForcedMovementComponent::PlayerForcedMovementComponent(Entity* parent) : C PlayerForcedMovementComponent::~PlayerForcedMovementComponent() {} void PlayerForcedMovementComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - outBitStream->Write(m_DirtyInfo); - if (m_DirtyInfo) { + outBitStream->Write(m_DirtyInfo || bIsInitialUpdate); + if (m_DirtyInfo || bIsInitialUpdate) { outBitStream->Write(m_PlayerOnRail); outBitStream->Write(m_ShowBillboard); } From 1a34f6f74adcadcb32af136831daf33475afe629 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 4 Jan 2023 06:15:06 -0800 Subject: [PATCH 220/322] Fix debug logging newline (#940) --- dCommon/dLogger.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dCommon/dLogger.cpp b/dCommon/dLogger.cpp index d4e6a96e..7785a070 100644 --- a/dCommon/dLogger.cpp +++ b/dCommon/dLogger.cpp @@ -89,7 +89,7 @@ void dLogger::Log(const std::string& className, const std::string& message) { void dLogger::LogDebug(const char* className, const char* format, ...) { if (!m_logDebugStatements) return; va_list args; - std::string log = "[" + std::string(className) + "] " + std::string(format); + std::string log = "[" + std::string(className) + "] " + std::string(format) + "\n"; va_start(args, format); vLog(log.c_str(), args); va_end(args); From bad3845d83712eaed717b29dab819e5f396d6866 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 6 Jan 2023 21:04:20 -0800 Subject: [PATCH 221/322] Address Docker issues and remove need to extract cdclient.fdb (#895) * Implement a server res directory * Only convert if neither exist * Remove unzip, Update RegEx * readme updates Run setup after setting working dir Address several docker issues Revert "Run setup after setting working dir" This reverts commit fd2fb9228e82a350204c1ef61f7ba059479bb12f. Fix docker * Remove extra submodules * Rework logic * Switch if block * Remove need to extract fdb from client * Change log name * Update FdbToSqlite.cpp --- .gitmodules | 6 -- Docker.md | 2 +- Docker_Windows.md | 2 +- dCommon/FdbToSqlite.cpp | 142 +++++++++++++++---------------- dCommon/FdbToSqlite.h | 40 ++++----- dCommon/dClient/AssetManager.cpp | 28 ------ dCommon/dClient/AssetManager.h | 1 - dMasterServer/MasterServer.cpp | 23 ++--- docker/Dockerfile | 7 +- docker/setup.Dockerfile | 15 +--- docker/setup.sh | 55 +----------- docker/start_server.sh | 29 +------ thirdparty/LUnpack | 1 - thirdparty/docker-utils | 1 - 14 files changed, 109 insertions(+), 243 deletions(-) mode change 100644 => 100755 docker/start_server.sh delete mode 160000 thirdparty/LUnpack delete mode 160000 thirdparty/docker-utils diff --git a/.gitmodules b/.gitmodules index 6fb56bde..33193447 100644 --- a/.gitmodules +++ b/.gitmodules @@ -14,12 +14,6 @@ path = thirdparty/mariadb-connector-cpp url = https://github.com/mariadb-corporation/mariadb-connector-cpp.git ignore = dirty -[submodule "thirdparty/docker-utils"] - path = thirdparty/docker-utils - url = https://github.com/lcdr/utils.git -[submodule "thirdparty/LUnpack"] - path = thirdparty/LUnpack - url = https://github.com/Xiphoseer/LUnpack.git [submodule "thirdparty/AccountManager"] path = thirdparty/AccountManager url = https://github.com/DarkflameUniverse/AccountManager diff --git a/Docker.md b/Docker.md index 54d0ce19..b06bd0fe 100644 --- a/Docker.md +++ b/Docker.md @@ -4,7 +4,7 @@ - [Docker](https://docs.docker.com/get-docker/) (Docker Desktop or on Linux normal Docker) - [Docker Compose](https://docs.docker.com/compose/install/) (Included in Docker Desktop) -- LEGO® Universe packed Client. Check the main [README](./README.md) for details on this. +- LEGO® Universe Client. Check the main [README](./README.md) for details on this. ## Run server inside Docker diff --git a/Docker_Windows.md b/Docker_Windows.md index 1cc633cc..984bbe57 100644 --- a/Docker_Windows.md +++ b/Docker_Windows.md @@ -25,7 +25,7 @@ 11. Once the command has completed (you can see you path again and can enter commands), close the window. 12. Inside the downloaded folder, copy `.env.example` and name the copy `.env` 13. Open `.env` with Notepad by right-clicking it and selecting _Open With_ -> _More apps_ -> _Notepad_. -14. Change the text after `CLIENT_PATH=` to the location of your client. The folder you are pointing to must contain a folder called `client` which should contain the client files. +14. Change the text after `CLIENT_PATH=` to the location of your client. This folder must contain either a folder `client` or `legouniverse.exe`. > If you need the extra performance, place the client files in `\\wsl$\<your linux OS>\...` to avoid working across file systems, see [Docker Best Practices](https://docs.docker.com/desktop/windows/wsl/#best-practices) and [WSL documentation](https://docs.microsoft.com/en-us/windows/wsl/filesystems#file-storage-and-performance-across-file-systems). 15. Optionally, you can change the number after `BUILD_THREADS=` to the number of cores / threads your processor has. If your computer crashes while building, you can try to reduce this value. diff --git a/dCommon/FdbToSqlite.cpp b/dCommon/FdbToSqlite.cpp index 80251e89..e05286a9 100644 --- a/dCommon/FdbToSqlite.cpp +++ b/dCommon/FdbToSqlite.cpp @@ -10,6 +10,7 @@ #include "GeneralUtils.h" #include "Game.h" #include "dLogger.h" +#include "AssetManager.h" #include "eSqliteDataType.h" @@ -23,26 +24,23 @@ std::map<eSqliteDataType, std::string> FdbToSqlite::Convert::m_SqliteType = { { eSqliteDataType::TEXT_8, "text_8"} }; -FdbToSqlite::Convert::Convert(std::string basePath, std::string binaryOutPath) { - this->m_BasePath = basePath; +FdbToSqlite::Convert::Convert(std::string binaryOutPath) { this->m_BinaryOutPath = binaryOutPath; - m_Fdb.open(m_BasePath + "/cdclient.fdb", std::ios::binary); } -FdbToSqlite::Convert::~Convert() { - this->m_Fdb.close(); -} - -bool FdbToSqlite::Convert::ConvertDatabase() { +bool FdbToSqlite::Convert::ConvertDatabase(AssetMemoryBuffer& buffer) { if (m_ConversionStarted) return false; + + std::istream cdClientBuffer(&buffer); + this->m_ConversionStarted = true; try { CDClientDatabase::Connect(m_BinaryOutPath + "/CDServer.sqlite"); CDClientDatabase::ExecuteQuery("BEGIN TRANSACTION;"); - int32_t numberOfTables = ReadInt32(); - ReadTables(numberOfTables); + int32_t numberOfTables = ReadInt32(cdClientBuffer); + ReadTables(numberOfTables, cdClientBuffer); CDClientDatabase::ExecuteQuery("COMMIT;"); } catch (CppSQLite3Exception& e) { @@ -53,130 +51,130 @@ bool FdbToSqlite::Convert::ConvertDatabase() { return true; } -int32_t FdbToSqlite::Convert::ReadInt32() { +int32_t FdbToSqlite::Convert::ReadInt32(std::istream& cdClientBuffer) { int32_t nextInt{}; - BinaryIO::BinaryRead(m_Fdb, nextInt); + BinaryIO::BinaryRead(cdClientBuffer, nextInt); return nextInt; } -int64_t FdbToSqlite::Convert::ReadInt64() { - int32_t prevPosition = SeekPointer(); +int64_t FdbToSqlite::Convert::ReadInt64(std::istream& cdClientBuffer) { + int32_t prevPosition = SeekPointer(cdClientBuffer); int64_t value{}; - BinaryIO::BinaryRead(m_Fdb, value); + BinaryIO::BinaryRead(cdClientBuffer, value); - m_Fdb.seekg(prevPosition); + cdClientBuffer.seekg(prevPosition); return value; } -std::string FdbToSqlite::Convert::ReadString() { - int32_t prevPosition = SeekPointer(); +std::string FdbToSqlite::Convert::ReadString(std::istream& cdClientBuffer) { + int32_t prevPosition = SeekPointer(cdClientBuffer); - auto readString = BinaryIO::ReadString(m_Fdb); + auto readString = BinaryIO::ReadString(cdClientBuffer); - m_Fdb.seekg(prevPosition); + cdClientBuffer.seekg(prevPosition); return readString; } -int32_t FdbToSqlite::Convert::SeekPointer() { +int32_t FdbToSqlite::Convert::SeekPointer(std::istream& cdClientBuffer) { int32_t position{}; - BinaryIO::BinaryRead(m_Fdb, position); - int32_t prevPosition = m_Fdb.tellg(); - m_Fdb.seekg(position); + BinaryIO::BinaryRead(cdClientBuffer, position); + int32_t prevPosition = cdClientBuffer.tellg(); + cdClientBuffer.seekg(position); return prevPosition; } -std::string FdbToSqlite::Convert::ReadColumnHeader() { - int32_t prevPosition = SeekPointer(); +std::string FdbToSqlite::Convert::ReadColumnHeader(std::istream& cdClientBuffer) { + int32_t prevPosition = SeekPointer(cdClientBuffer); - int32_t numberOfColumns = ReadInt32(); - std::string tableName = ReadString(); + int32_t numberOfColumns = ReadInt32(cdClientBuffer); + std::string tableName = ReadString(cdClientBuffer); - auto columns = ReadColumns(numberOfColumns); + auto columns = ReadColumns(numberOfColumns, cdClientBuffer); std::string newTable = "CREATE TABLE IF NOT EXISTS '" + tableName + "' (" + columns + ");"; CDClientDatabase::ExecuteDML(newTable); - m_Fdb.seekg(prevPosition); + cdClientBuffer.seekg(prevPosition); return tableName; } -void FdbToSqlite::Convert::ReadTables(int32_t& numberOfTables) { - int32_t prevPosition = SeekPointer(); +void FdbToSqlite::Convert::ReadTables(int32_t& numberOfTables, std::istream& cdClientBuffer) { + int32_t prevPosition = SeekPointer(cdClientBuffer); for (int32_t i = 0; i < numberOfTables; i++) { - auto columnHeader = ReadColumnHeader(); - ReadRowHeader(columnHeader); + auto columnHeader = ReadColumnHeader(cdClientBuffer); + ReadRowHeader(columnHeader, cdClientBuffer); } - m_Fdb.seekg(prevPosition); + cdClientBuffer.seekg(prevPosition); } -std::string FdbToSqlite::Convert::ReadColumns(int32_t& numberOfColumns) { +std::string FdbToSqlite::Convert::ReadColumns(int32_t& numberOfColumns, std::istream& cdClientBuffer) { std::stringstream columnsToCreate; - int32_t prevPosition = SeekPointer(); + int32_t prevPosition = SeekPointer(cdClientBuffer); std::string name{}; eSqliteDataType dataType{}; for (int32_t i = 0; i < numberOfColumns; i++) { if (i != 0) columnsToCreate << ", "; - dataType = static_cast<eSqliteDataType>(ReadInt32()); - name = ReadString(); + dataType = static_cast<eSqliteDataType>(ReadInt32(cdClientBuffer)); + name = ReadString(cdClientBuffer); columnsToCreate << "'" << name << "' " << FdbToSqlite::Convert::m_SqliteType[dataType]; } - m_Fdb.seekg(prevPosition); + cdClientBuffer.seekg(prevPosition); return columnsToCreate.str(); } -void FdbToSqlite::Convert::ReadRowHeader(std::string& tableName) { - int32_t prevPosition = SeekPointer(); +void FdbToSqlite::Convert::ReadRowHeader(std::string& tableName, std::istream& cdClientBuffer) { + int32_t prevPosition = SeekPointer(cdClientBuffer); - int32_t numberOfAllocatedRows = ReadInt32(); + int32_t numberOfAllocatedRows = ReadInt32(cdClientBuffer); if (numberOfAllocatedRows != 0) assert((numberOfAllocatedRows & (numberOfAllocatedRows - 1)) == 0); // assert power of 2 allocation size - ReadRows(numberOfAllocatedRows, tableName); + ReadRows(numberOfAllocatedRows, tableName, cdClientBuffer); - m_Fdb.seekg(prevPosition); + cdClientBuffer.seekg(prevPosition); } -void FdbToSqlite::Convert::ReadRows(int32_t& numberOfAllocatedRows, std::string& tableName) { - int32_t prevPosition = SeekPointer(); +void FdbToSqlite::Convert::ReadRows(int32_t& numberOfAllocatedRows, std::string& tableName, std::istream& cdClientBuffer) { + int32_t prevPosition = SeekPointer(cdClientBuffer); int32_t rowid = 0; for (int32_t row = 0; row < numberOfAllocatedRows; row++) { - int32_t rowPointer = ReadInt32(); + int32_t rowPointer = ReadInt32(cdClientBuffer); if (rowPointer == -1) rowid++; - else ReadRow(rowPointer, tableName); + else ReadRow(rowPointer, tableName, cdClientBuffer); } - m_Fdb.seekg(prevPosition); + cdClientBuffer.seekg(prevPosition); } -void FdbToSqlite::Convert::ReadRow(int32_t& position, std::string& tableName) { - int32_t prevPosition = m_Fdb.tellg(); - m_Fdb.seekg(position); +void FdbToSqlite::Convert::ReadRow(int32_t& position, std::string& tableName, std::istream& cdClientBuffer) { + int32_t prevPosition = cdClientBuffer.tellg(); + cdClientBuffer.seekg(position); while (true) { - ReadRowInfo(tableName); - int32_t linked = ReadInt32(); + ReadRowInfo(tableName, cdClientBuffer); + int32_t linked = ReadInt32(cdClientBuffer); if (linked == -1) break; - m_Fdb.seekg(linked); + cdClientBuffer.seekg(linked); } - m_Fdb.seekg(prevPosition); + cdClientBuffer.seekg(prevPosition); } -void FdbToSqlite::Convert::ReadRowInfo(std::string& tableName) { - int32_t prevPosition = SeekPointer(); +void FdbToSqlite::Convert::ReadRowInfo(std::string& tableName, std::istream& cdClientBuffer) { + int32_t prevPosition = SeekPointer(cdClientBuffer); - int32_t numberOfColumns = ReadInt32(); - ReadRowValues(numberOfColumns, tableName); + int32_t numberOfColumns = ReadInt32(cdClientBuffer); + ReadRowValues(numberOfColumns, tableName, cdClientBuffer); - m_Fdb.seekg(prevPosition); + cdClientBuffer.seekg(prevPosition); } -void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& tableName) { - int32_t prevPosition = SeekPointer(); +void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& tableName, std::istream& cdClientBuffer) { + int32_t prevPosition = SeekPointer(cdClientBuffer); int32_t emptyValue{}; int32_t intValue{}; @@ -190,26 +188,26 @@ void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& for (int32_t i = 0; i < numberOfColumns; i++) { if (i != 0) insertedRow << ", "; // Only append comma and space after first entry in row. - switch (static_cast<eSqliteDataType>(ReadInt32())) { + switch (static_cast<eSqliteDataType>(ReadInt32(cdClientBuffer))) { case eSqliteDataType::NONE: - BinaryIO::BinaryRead(m_Fdb, emptyValue); + BinaryIO::BinaryRead(cdClientBuffer, emptyValue); assert(emptyValue == 0); insertedRow << "NULL"; break; case eSqliteDataType::INT32: - intValue = ReadInt32(); + intValue = ReadInt32(cdClientBuffer); insertedRow << intValue; break; case eSqliteDataType::REAL: - BinaryIO::BinaryRead(m_Fdb, floatValue); + BinaryIO::BinaryRead(cdClientBuffer, floatValue); insertedRow << std::fixed << std::setprecision(34) << floatValue; // maximum precision of floating point number break; case eSqliteDataType::TEXT_4: case eSqliteDataType::TEXT_8: { - stringValue = ReadString(); + stringValue = ReadString(cdClientBuffer); size_t position = 0; // Need to escape quote with a double of ". @@ -225,12 +223,12 @@ void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& } case eSqliteDataType::INT_BOOL: - BinaryIO::BinaryRead(m_Fdb, boolValue); + BinaryIO::BinaryRead(cdClientBuffer, boolValue); insertedRow << static_cast<bool>(boolValue); break; case eSqliteDataType::INT64: - int64Value = ReadInt64(); + int64Value = ReadInt64(cdClientBuffer); insertedRow << std::to_string(int64Value); break; @@ -245,5 +243,5 @@ void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& auto copiedString = insertedRow.str(); CDClientDatabase::ExecuteDML(copiedString); - m_Fdb.seekg(prevPosition); + cdClientBuffer.seekg(prevPosition); } diff --git a/dCommon/FdbToSqlite.h b/dCommon/FdbToSqlite.h index cfa5263b..7aad2703 100644 --- a/dCommon/FdbToSqlite.h +++ b/dCommon/FdbToSqlite.h @@ -7,6 +7,8 @@ #include <iosfwd> #include <map> +class AssetMemoryBuffer; + enum class eSqliteDataType : int32_t; namespace FdbToSqlite { @@ -18,33 +20,28 @@ namespace FdbToSqlite { * @param inputFile The file which ends in .fdb to be converted * @param binaryPath The base path where the file will be saved */ - Convert(std::string inputFile, std::string binaryOutPath); - - /** - * Destroy the convert object and close the fdb file. - */ - ~Convert(); + Convert(std::string binaryOutPath); /** * Converts the input file to sqlite. Calling multiple times is safe. * * @return true if the database was converted properly, false otherwise. */ - bool ConvertDatabase(); + bool ConvertDatabase(AssetMemoryBuffer& buffer); /** * @brief Reads a 32 bit int from the fdb file. * * @return The read value */ - int32_t ReadInt32(); + int32_t ReadInt32(std::istream& cdClientBuffer); /** * @brief Reads a 64 bit integer from the fdb file. * * @return The read value */ - int64_t ReadInt64(); + int64_t ReadInt64(std::istream& cdClientBuffer); /** * @brief Reads a string from the fdb file. @@ -53,28 +50,28 @@ namespace FdbToSqlite { * * TODO This needs to be translated to latin-1! */ - std::string ReadString(); + std::string ReadString(std::istream& cdClientBuffer); /** * @brief Seeks to a pointer position. * * @return The previous position before the seek */ - int32_t SeekPointer(); + int32_t SeekPointer(std::istream& cdClientBuffer); /** * @brief Reads a column header from the fdb file and creates the table in the database * * @return The table name */ - std::string ReadColumnHeader(); + std::string ReadColumnHeader(std::istream& cdClientBuffer); /** * @brief Read the tables from the fdb file. * * @param numberOfTables The number of tables to read */ - void ReadTables(int32_t& numberOfTables); + void ReadTables(int32_t& numberOfTables, std::istream& cdClientBuffer); /** * @brief Reads the columns from the fdb file. @@ -82,14 +79,14 @@ namespace FdbToSqlite { * @param numberOfColumns The number of columns to read * @return All columns of the table formatted for a sql query */ - std::string ReadColumns(int32_t& numberOfColumns); + std::string ReadColumns(int32_t& numberOfColumns, std::istream& cdClientBuffer); /** * @brief Reads the row header from the fdb file. * * @param tableName The tables name */ - void ReadRowHeader(std::string& tableName); + void ReadRowHeader(std::string& tableName, std::istream& cdClientBuffer); /** * @brief Read the rows from the fdb file., @@ -97,7 +94,7 @@ namespace FdbToSqlite { * @param numberOfAllocatedRows The number of rows that were allocated. Always a power of 2! * @param tableName The tables name. */ - void ReadRows(int32_t& numberOfAllocatedRows, std::string& tableName); + void ReadRows(int32_t& numberOfAllocatedRows, std::string& tableName, std::istream& cdClientBuffer); /** * @brief Reads a row from the fdb file. @@ -105,14 +102,14 @@ namespace FdbToSqlite { * @param position The position to seek in the fdb to * @param tableName The tables name */ - void ReadRow(int32_t& position, std::string& tableName); + void ReadRow(int32_t& position, std::string& tableName, std::istream& cdClientBuffer); /** * @brief Reads the row info from the fdb file. * * @param tableName The tables name */ - void ReadRowInfo(std::string& tableName); + void ReadRowInfo(std::string& tableName, std::istream& cdClientBuffer); /** * @brief Reads each row and its values from the fdb file and inserts them into the database @@ -120,7 +117,7 @@ namespace FdbToSqlite { * @param numberOfColumns The number of columns to read in * @param tableName The tables name */ - void ReadRowValues(int32_t& numberOfColumns, std::string& tableName); + void ReadRowValues(int32_t& numberOfColumns, std::string& tableName, std::istream& cdClientBuffer); private: /** @@ -132,11 +129,6 @@ namespace FdbToSqlite { * Base path of the folder containing the fdb file */ std::string m_BasePath{}; - - /** - * ifstream containing the fdb file - */ - std::ifstream m_Fdb{}; /** * Whether or not a conversion was started. If one was started, do not attempt to convert the file again. diff --git a/dCommon/dClient/AssetManager.cpp b/dCommon/dClient/AssetManager.cpp index dc3db0a1..ed86d719 100644 --- a/dCommon/dClient/AssetManager.cpp +++ b/dCommon/dClient/AssetManager.cpp @@ -45,9 +45,6 @@ AssetManager::AssetManager(const std::filesystem::path& path) { switch (m_AssetBundleType) { case eAssetBundleType::Packed: { this->LoadPackIndex(); - - this->UnpackRequiredAssets(); - break; } } @@ -160,31 +157,6 @@ AssetMemoryBuffer AssetManager::GetFileAsBuffer(const char* name) { return AssetMemoryBuffer(buf, len, success); } -void AssetManager::UnpackRequiredAssets() { - if (std::filesystem::exists(m_ResPath / "cdclient.fdb")) return; - - char* data; - uint32_t size; - - bool success = this->GetFile("cdclient.fdb", &data, &size); - - if (!success) { - Game::logger->Log("AssetManager", "Failed to extract required files from the packs."); - - delete data; - - return; - } - - std::ofstream cdclientOutput(m_ResPath / "cdclient.fdb", std::ios::out | std::ios::binary); - cdclientOutput.write(data, size); - cdclientOutput.close(); - - delete data; - - return; -} - uint32_t AssetManager::crc32b(uint32_t base, uint8_t* message, size_t l) { size_t i, j; uint32_t crc, msb; diff --git a/dCommon/dClient/AssetManager.h b/dCommon/dClient/AssetManager.h index 73b24f18..bc7e5ff7 100644 --- a/dCommon/dClient/AssetManager.h +++ b/dCommon/dClient/AssetManager.h @@ -60,7 +60,6 @@ public: private: void LoadPackIndex(); - void UnpackRequiredAssets(); // Modified crc algorithm (mpeg2) // Reference: https://stackoverflow.com/questions/54339800/how-to-modify-crc-32-to-crc-32-mpeg-2 diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 34ce59c7..82645797 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -156,22 +156,25 @@ int main(int argc, char** argv) { Game::logger->Log("MasterServer", "CDServer.sqlite is not located at resServer, but is located at res path. Copying file..."); std::filesystem::copy_file(Game::assetManager->GetResPath() / "CDServer.sqlite", BinaryPathFinder::GetBinaryDir() / "resServer" / "CDServer.sqlite"); } else { - Game::logger->Log("WorldServer", + Game::logger->Log("MasterServer", "%s could not be found in resServer or res. Looking for %s to convert to sqlite.", (BinaryPathFinder::GetBinaryDir() / "resServer" / "CDServer.sqlite").c_str(), (Game::assetManager->GetResPath() / "cdclient.fdb").c_str()); - if (!fdbExists) { - Game::logger->Log("WorldServer", - "%s could not be opened. Please move cdclient.fdb to %s", - (Game::assetManager->GetResPath() / "cdclient.fdb").c_str(), - (Game::assetManager->GetResPath().c_str())); - return FinalizeShutdown(); + + AssetMemoryBuffer cdClientBuffer = Game::assetManager->GetFileAsBuffer("cdclient.fdb"); + if (!cdClientBuffer.m_Success) { + Game::logger->Log("MasterServer", "Failed to load %s", (Game::assetManager->GetResPath() / "cdclient.fdb").c_str()); + throw std::runtime_error("Aborting initialization due to missing cdclient.fdb."); } - Game::logger->Log("WorldServer", "Found cdclient.fdb. Converting to SQLite"); - if (FdbToSqlite::Convert(Game::assetManager->GetResPath().string(), (BinaryPathFinder::GetBinaryDir() / "resServer").string()).ConvertDatabase() == false) { + + Game::logger->Log("MasterServer", "Found %s. Converting to SQLite", (Game::assetManager->GetResPath() / "cdclient.fdb").c_str()); + Game::logger->Flush(); + + if (FdbToSqlite::Convert((BinaryPathFinder::GetBinaryDir() / "resServer").string()).ConvertDatabase(cdClientBuffer) == false) { Game::logger->Log("MasterServer", "Failed to convert fdb to sqlite."); - return FinalizeShutdown(); + return EXIT_FAILURE; } + cdClientBuffer.close(); } } diff --git a/docker/Dockerfile b/docker/Dockerfile index 50f5b083..a7d91855 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -6,7 +6,7 @@ RUN --mount=type=cache,id=build-apt-cache,target=/var/cache/apt \ echo "Install build dependencies" && \ apt update && \ apt remove -y libmysqlcppconn7v5 libmysqlcppconn-dev && \ - apt install cmake zlib1g zlib1g-dev unzip -yqq --no-install-recommends && \ + apt install cmake zlib1g zlib1g-dev -yqq --no-install-recommends && \ rm -rf /var/lib/apt/lists/* COPY dAuthServer/ /build/dAuthServer @@ -35,12 +35,11 @@ ARG BUILD_VERSION=171022 RUN echo "Build server" && \ mkdir -p cmake_build && \ cd cmake_build && \ - sed -i -e "s/171022/${BUILD_VERSION}/g" ../CMakeVariables.txt && \ + sed -i -e "s/NET_VERSION=.*/NET_VERSION=${BUILD_VERSION}/g" ../CMakeVariables.txt && \ + sed -i -e "s/__maria_db_connector_compile_jobs__=.*/__maria_db_connector_compile_jobs__=${BUILD_THREADS}/g" ../CMakeVariables.txt && \ cmake .. -DCMAKE_BUILD_RPATH_USE_ORIGIN=TRUE && \ make -j $BUILD_THREADS -RUN unzip /build/resources/navmeshes.zip -d /build/cmake_build/res/maps - FROM gcc:11 as runtime RUN --mount=type=cache,id=runtime-apt-cache,target=/var/cache/apt \ diff --git a/docker/setup.Dockerfile b/docker/setup.Dockerfile index 2664e2fa..18bb2d06 100644 --- a/docker/setup.Dockerfile +++ b/docker/setup.Dockerfile @@ -1,23 +1,12 @@ -FROM rust:alpine3.14 as LUnpack - -WORKDIR /build_LUnpack - -COPY ./thirdparty/LUnpack . - -RUN apk add musl-dev --no-cache && cargo build --release - FROM python:3.10-alpine3.14 as prep -RUN apk add sqlite bash --no-cache +RUN apk add bash --no-cache WORKDIR /setup # copy needed files from repo COPY resources/ resources/ -COPY migrations/cdserver/ migrations/cdserver -COPY --from=LUnpack /build_LUnpack/target/release/lunpack /usr/local/bin/lunpack -ADD thirdparty/docker-utils/utils/*.py utils/ COPY docker/setup.sh /setup.sh -CMD [ "/setup.sh" ] \ No newline at end of file +CMD [ "/setup.sh" ] diff --git a/docker/setup.sh b/docker/setup.sh index 0f5c0d2e..ade67d2e 100755 --- a/docker/setup.sh +++ b/docker/setup.sh @@ -7,7 +7,7 @@ function update_ini() { FILE="/docker/configs/$1" KEY=$2 NEW_VALUE=$3 - sed -i "/^$KEY=/s/=.*/=$NEW_VALUE/" $FILE + sed -i "s~$2=.*~$2=$3~" $FILE } function update_database_ini_values_for() { @@ -32,62 +32,11 @@ function update_ini_values() { cp resources/worldconfig.ini /docker/configs/ cp resources/sharedconfig.ini /docker/configs/ - update_ini worldconfig.ini chat_server_port $CHAT_SERVER_PORT - update_ini worldconfig.ini max_clients $MAX_CLIENTS - # always use the internal docker hostname update_ini masterconfig.ini master_ip "darkflame" + update_ini sharedconfig.ini client_location "/client" update_database_ini_values_for sharedconfig.ini } -function fdb_to_sqlite() { - echo "Run fdb_to_sqlite" - python3 utils/fdb_to_sqlite.py /client/client/res/cdclient.fdb --sqlite_path /client/client/res/CDServer.sqlite - - ( - cd migrations/cdserver - readarray -d '' entries < <(printf '%s\0' *.sql | sort -zV) - for entry in "${entries[@]}"; do - echo "Execute $entry" - sqlite3 /client/client/res/CDServer.sqlite < $entry - done - ) -} - update_ini_values - -if [[ ! -d "/client" ]]; then - echo "Client not found." - echo "Did you forget to mount the client into the \"/client\" directory?" - exit 1 -fi - -if [[ ! -f "/client/extracted" ]]; then - echo "Start client resource extraction" - - touch globs.txt - - echo "client/res/macros/**" >> globs.txt - echo "client/res/BrickModels/**" >> globs.txt - echo "client/res/maps/**" >> globs.txt - echo "*.fdb" >> globs.txt - - lunpack -g ./globs.txt /client/ - - touch /client/extracted -else - echo "Client already extracted. Skip this step..." - echo "If you want to force a re-extract, just delete the file called \"extracted\" in the client directory" -fi - -if [[ ! -f "/client/migrated" ]]; then - echo "Start client db migration" - - fdb_to_sqlite - - touch /client/migrated -else - echo "Client db already migrated. Skip this step..." - echo "If you want to force a re-migrate, just delete the file called \"migrated\" in the client directory" -fi diff --git a/docker/start_server.sh b/docker/start_server.sh old mode 100644 new mode 100755 index 4fd6e2be..2e2e8c28 --- a/docker/start_server.sh +++ b/docker/start_server.sh @@ -1,25 +1,5 @@ #!/bin/bash -function symlink_client_files() { - echo "Creating symlinks for client files" - ln -s /client/client/res/macros/ /app/res/macros - ln -s /client/client/res/BrickModels/ /app/res/BrickModels - ln -s /client/client/res/chatplus_en_us.txt /app/res/chatplus_en_us.txt - ln -s /client/client/res/names/ /app/res/names - ln -s /client/client/res/CDServer.sqlite /app/res/CDServer.sqlite - - # need to create this file so the server knows the client is unpacked (see `dCommon/dClient/AssetManager.cpp`) - touch /app/res/cdclient.fdb - # need to iterate over entries in maps due to maps already being a directory with navmeshes/ in it - ( - cd /client/client/res/maps - readarray -d '' entries < <(printf '%s\0' * | sort -zV) - for entry in "${entries[@]}"; do - ln -s /client/client/res/maps/$entry /app/res/maps/ - done - ) -} - function symlink_config_files() { echo "Creating symlinks for config files" rm /app/*.ini @@ -30,15 +10,8 @@ function symlink_config_files() { ln -s /shared_configs/configs/sharedconfig.ini /app/sharedconfig.ini } -# check to make sure the setup has completed -while [ ! -f "/client/extracted" ] || [ ! -f "/client/migrated" ]; do - echo "Client setup not finished. Waiting for setup container to complete..." - sleep 5 -done - if [[ ! -f "/app/initialized" ]]; then # setup symlinks for volume files - symlink_client_files symlink_config_files # do not run symlinks more than once touch /app/initialized @@ -49,4 +22,4 @@ fi # start the server echo "Starting MasterServer" ./MasterServer -tail -f /dev/null \ No newline at end of file +tail -f /dev/null diff --git a/thirdparty/LUnpack b/thirdparty/LUnpack deleted file mode 160000 index f8d7e442..00000000 --- a/thirdparty/LUnpack +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f8d7e442a78910b298fe1cd5780f07c9c9285b8c diff --git a/thirdparty/docker-utils b/thirdparty/docker-utils deleted file mode 160000 index 3f0129e0..00000000 --- a/thirdparty/docker-utils +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 3f0129e0939ce5ccf41f0808dcbbe71a6243e37f From 8bcb4bd36d12282707776b3995dd946990768c81 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 6 Jan 2023 21:06:24 -0800 Subject: [PATCH 222/322] Fix smashables not counting towards whole team (#944) --- dGame/dComponents/DestroyableComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 8d8ed42a..1b127c41 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -701,7 +701,7 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType auto* missions = owner->GetComponent<MissionComponent>(); if (missions != nullptr) { - if (team != nullptr && isEnemy) { + if (team != nullptr) { for (const auto memberId : team->members) { auto* member = EntityManager::Instance()->GetEntity(memberId); From fc75d6048fbd917586c5b7a75551dbe09288c495 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 6 Jan 2023 21:17:05 -0800 Subject: [PATCH 223/322] dGame Precompiled header improvements (#876) * moving branch * Add deleteinven slash command * Change name of BRICKS_IN_BBB * Use string_view instead of strcmp * Clean up include tree * Remove unneeded headers from PCH files Removes unneeded headers from pre-compiled headers. This increases compile time, however reduces development time for most files. * Update Entity.h * Update EntityManager.h * Update GameMessages.cpp * There it compiles now Co-authored-by: Aaron Kimbrell <aronwk.aaron@gmail.com> --- dCommon/dEnums/MissionState.h | 2 +- dCommon/{ => dEnums}/PermissionMap.h | 0 .../{ => dEnums}/eBlueprintSaveResponseType.h | 0 dCommon/dEnums/eMovementPlatformState.h | 16 + dGame/Entity.cpp | 5 + dGame/Entity.h | 25 +- dGame/EntityManager.cpp | 1 + dGame/EntityManager.h | 10 +- dGame/Player.cpp | 2 + dGame/UserManager.cpp | 1 + dGame/dBehaviors/BehaviorContext.cpp | 5 +- dGame/dBehaviors/SpawnBehavior.cpp | 2 + dGame/dComponents/CharacterComponent.cpp | 1 + dGame/dComponents/MovingPlatformComponent.cpp | 15 +- dGame/dComponents/MovingPlatformComponent.h | 17 +- dGame/dComponents/PetComponent.cpp | 1 + dGame/dComponents/PhantomPhysicsComponent.cpp | 1 + .../dComponents/PropertyEntranceComponent.cpp | 1 + dGame/dComponents/RacingControlComponent.cpp | 1 + dGame/dComponents/RebuildComponent.cpp | 1 + .../dComponents/ScriptedActivityComponent.cpp | 2 + dGame/dComponents/SkillComponent.cpp | 8 +- .../dGameMessages/DoClientProjectileImpact.h | 83 +++ dGame/dGameMessages/EchoStartSkill.h | 132 ++++ dGame/dGameMessages/EchoSyncSkill.h | 70 +++ dGame/dGameMessages/GameMessageHandler.cpp | 15 +- dGame/dGameMessages/GameMessages.cpp | 13 +- dGame/dGameMessages/GameMessages.h | 577 +----------------- .../RequestServerProjectileImpact.h | 74 +++ dGame/dGameMessages/StartSkill.h | 144 +++++ dGame/dGameMessages/SyncSkill.h | 68 +++ dGame/dInventory/Item.cpp | 1 + dGame/dMission/Mission.cpp | 1 + dGame/dMission/Mission.h | 6 +- dGame/dPropertyBehaviors/ControlBehaviors.cpp | 1 + dGame/dUtilities/BrickDatabase.cpp | 1 + dGame/dUtilities/SlashCommandHandler.cpp | 6 + dGame/dUtilities/VanityUtilities.cpp | 1 + dNet/ClientPackets.cpp | 2 +- .../02_server/Enemy/AM/AmDarklingDragon.cpp | 2 + .../02_server/Enemy/FV/FvMaelstromDragon.cpp | 2 + .../02_server/Enemy/General/BaseEnemyApe.cpp | 2 + .../02_server/Enemy/General/BaseEnemyMech.cpp | 1 + .../General/TreasureChestDragonServer.cpp | 1 + .../02_server/Equipment/BootyDigServer.cpp | 1 + dScripts/02_server/Map/AG/NpcPirateServer.cpp | 1 + dScripts/02_server/Map/AG/NpcWispServer.cpp | 1 + .../02_server/Map/AG/RemoveRentalGear.cpp | 1 + .../Map/AG_Spider_Queen/ZoneAgSpiderQueen.cpp | 1 + dScripts/02_server/Map/AM/AmBlueX.cpp | 1 + .../02_server/Map/AM/AmShieldGenerator.cpp | 1 + .../Map/AM/AmShieldGeneratorQuickbuild.cpp | 1 + dScripts/02_server/Map/AM/AmSkullkinDrill.cpp | 1 + dScripts/02_server/Map/AM/AmSkullkinTower.cpp | 1 + .../02_server/Map/FV/EnemyRoninSpawner.cpp | 1 + .../Map/General/BankInteractServer.cpp | 2 + .../02_server/Map/General/GrowingFlower.cpp | 1 + .../02_server/Map/General/PetDigServer.cpp | 1 + .../Map/General/PropertyPlatform.cpp | 5 +- dScripts/02_server/Map/General/QbSpawner.cpp | 2 +- .../Map/General/WishingWellServer.cpp | 2 + .../Map/NS/NsConcertChoiceBuildManager.cpp | 1 + dScripts/02_server/Map/NS/NsLegoClubDoor.h | 1 + dScripts/02_server/Map/NS/NsLupTeleport.h | 1 + .../Map/NT/NtCombatChallengeServer.cpp | 1 + dScripts/02_server/Map/NT/NtVandaServer.cpp | 1 + .../Property/AG_Small/EnemySpiderSpawner.cpp | 1 + .../Map/Property/PropertyBankInteract.cpp | 1 + dScripts/02_server/Map/VE/VeEpsilonServer.cpp | 2 + .../02_server/Map/VE/VeMissionConsole.cpp | 1 + .../Map/njhub/EnemySkeletonSpawner.cpp | 1 + .../Map/njhub/NjDragonEmblemChestServer.cpp | 3 + .../Map/njhub/NjNPCMissionSpinjitzuServer.cpp | 1 + dScripts/02_server/Map/njhub/RainOfArrows.cpp | 1 + .../General/MinigameTreasureChestServer.cpp | 1 + .../02_server/Objects/StinkyFishTarget.cpp | 1 + dScripts/ActivityManager.cpp | 1 + dScripts/CppScripts.h | 5 +- dScripts/NPCAddRemoveItem.cpp | 1 + dScripts/ScriptedPowerupSpawner.cpp | 1 + dScripts/SpawnPetBaseServer.cpp | 1 + dScripts/ai/AG/AgImagSmashable.cpp | 1 + dScripts/ai/AG/AgPicnicBlanket.cpp | 2 + dScripts/ai/AG/AgQbElevator.cpp | 6 +- dScripts/ai/AG/AgSpaceStuff.cpp | 1 + dScripts/ai/FV/FvPandaSpawnerServer.cpp | 1 + dScripts/ai/GF/GfBanana.cpp | 1 + dScripts/ai/GF/PetDigBuild.cpp | 1 + dScripts/ai/GF/PirateRep.cpp | 2 + .../ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp | 1 + dScripts/ai/NS/WH/RockHydrantSmashable.cpp | 1 + dScripts/ai/PETS/HydrantSmashable.cpp | 1 + dScripts/ai/PROPERTY/AgPropguards.cpp | 1 + dWorldServer/WorldServer.cpp | 5 + dZoneManager/LUTriggers.h | 30 + dZoneManager/Spawner.h | 1 + dZoneManager/Zone.cpp | 1 + dZoneManager/Zone.h | 41 +- tests/dGameTests/GameDependencies.h | 1 + 99 files changed, 821 insertions(+), 648 deletions(-) rename dCommon/{ => dEnums}/PermissionMap.h (100%) rename dCommon/{ => dEnums}/eBlueprintSaveResponseType.h (100%) create mode 100644 dCommon/dEnums/eMovementPlatformState.h create mode 100644 dGame/dGameMessages/DoClientProjectileImpact.h create mode 100644 dGame/dGameMessages/EchoStartSkill.h create mode 100644 dGame/dGameMessages/EchoSyncSkill.h create mode 100644 dGame/dGameMessages/RequestServerProjectileImpact.h create mode 100644 dGame/dGameMessages/StartSkill.h create mode 100644 dGame/dGameMessages/SyncSkill.h create mode 100644 dZoneManager/LUTriggers.h diff --git a/dCommon/dEnums/MissionState.h b/dCommon/dEnums/MissionState.h index fb1841d3..f040d33a 100644 --- a/dCommon/dEnums/MissionState.h +++ b/dCommon/dEnums/MissionState.h @@ -6,7 +6,7 @@ /** * Represents the possible states a mission can be in */ -enum class MissionState : int { +enum class MissionState : int32_t { /** * The mission state is unknown */ diff --git a/dCommon/PermissionMap.h b/dCommon/dEnums/PermissionMap.h similarity index 100% rename from dCommon/PermissionMap.h rename to dCommon/dEnums/PermissionMap.h diff --git a/dCommon/eBlueprintSaveResponseType.h b/dCommon/dEnums/eBlueprintSaveResponseType.h similarity index 100% rename from dCommon/eBlueprintSaveResponseType.h rename to dCommon/dEnums/eBlueprintSaveResponseType.h diff --git a/dCommon/dEnums/eMovementPlatformState.h b/dCommon/dEnums/eMovementPlatformState.h new file mode 100644 index 00000000..1df437d8 --- /dev/null +++ b/dCommon/dEnums/eMovementPlatformState.h @@ -0,0 +1,16 @@ +#ifndef __EMOVEMENTPLATFORMSTATE__H__ +#define __EMOVEMENTPLATFORMSTATE__H__ + +#include <cstdint> + +/** + * The different types of platform movement state, supposedly a bitmap + */ +enum class eMovementPlatformState : uint32_t +{ + Moving = 0b00010, + Stationary = 0b11001, + Stopped = 0b01100 +}; + +#endif //!__EMOVEMENTPLATFORMSTATE__H__ diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 16b2c5a1..c0f71324 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -17,6 +17,11 @@ #include "UserManager.h" #include "dpWorld.h" #include "Player.h" +#include "LUTriggers.h" +#include "User.h" +#include "EntityTimer.h" +#include "EntityCallbackTimer.h" +#include "Loot.h" //Component includes: #include "Component.h" diff --git a/dGame/Entity.h b/dGame/Entity.h index e0d38308..248018c0 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -4,30 +4,35 @@ #include <functional> #include <typeinfo> #include <type_traits> +#include <unordered_map> #include <vector> -#include "../thirdparty/raknet/Source/Replica.h" -#include "../thirdparty/raknet/Source/ReplicaManager.h" - -#include "dCommonVars.h" -#include "User.h" #include "NiPoint3.h" #include "NiQuaternion.h" #include "LDFFormat.h" -#include "Loot.h" -#include "Zone.h" -#include "EntityTimer.h" -#include "EntityCallbackTimer.h" -#include "EntityInfo.h" +namespace Loot { + class Info; +}; + +namespace tinyxml2 { + class XMLDocument; +}; +namespace LUTriggers { + struct Trigger; +}; class Player; +class EntityInfo; +class User; class Spawner; class ScriptComponent; class dpEntity; +class EntityTimer; class Component; class Item; class Character; +class EntityCallbackTimer; namespace CppScripts { class Script; diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index 02b8b59e..99ead79d 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -17,6 +17,7 @@ #include "MissionComponent.h" #include "Game.h" #include "dLogger.h" +#include "MessageIdentifiers.h" EntityManager* EntityManager::m_Address = nullptr; diff --git a/dGame/EntityManager.h b/dGame/EntityManager.h index 40a98076..36bc5962 100644 --- a/dGame/EntityManager.h +++ b/dGame/EntityManager.h @@ -2,15 +2,17 @@ #define ENTITYMANAGER_H #include "dCommonVars.h" -#include "../thirdparty/raknet/Source/Replica.h" #include <map> #include <stack> - -#include "Entity.h" #include <vector> +#include <unordered_map> + +class Entity; +class EntityInfo; +class Player; +class User; struct SystemAddress; -class User; class EntityManager { public: diff --git a/dGame/Player.cpp b/dGame/Player.cpp index 5306584e..4f4bc951 100644 --- a/dGame/Player.cpp +++ b/dGame/Player.cpp @@ -13,7 +13,9 @@ #include "dZoneManager.h" #include "CharacterComponent.h" #include "Mail.h" +#include "User.h" #include "CppScripts.h" +#include "Loot.h" std::vector<Player*> Player::m_Players = {}; diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index 70e76016..93469daa 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -22,6 +22,7 @@ #include "SkillComponent.h" #include "AssetManager.h" #include "CDClientDatabase.h" +#include "dMessageIdentifiers.h" UserManager* UserManager::m_Address = nullptr; diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index ebed10ba..26d1e9e6 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -10,8 +10,9 @@ #include <sstream> - +#include "dMessageIdentifiers.h" #include "DestroyableComponent.h" +#include "EchoSyncSkill.h" #include "PhantomPhysicsComponent.h" #include "RebuildComponent.h" @@ -216,7 +217,7 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) { } // Echo sync - GameMessages::EchoSyncSkill echo; + EchoSyncSkill echo; echo.bDone = true; echo.uiBehaviorHandle = entry.handle; diff --git a/dGame/dBehaviors/SpawnBehavior.cpp b/dGame/dBehaviors/SpawnBehavior.cpp index ac7bb797..8b2020b1 100644 --- a/dGame/dBehaviors/SpawnBehavior.cpp +++ b/dGame/dBehaviors/SpawnBehavior.cpp @@ -7,6 +7,8 @@ #include "dLogger.h" #include "DestroyableComponent.h" #include "RebuildComponent.h" +#include "Entity.h" +#include "EntityInfo.h" void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* origin = EntityManager::Instance()->GetEntity(context->originator); diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 424be0ac..ecd5e7b2 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -13,6 +13,7 @@ #include "VehiclePhysicsComponent.h" #include "GameMessages.h" #include "Item.h" +#include "AMFFormat.h" CharacterComponent::CharacterComponent(Entity* parent, Character* character) : Component(parent) { m_Character = character; diff --git a/dGame/dComponents/MovingPlatformComponent.cpp b/dGame/dComponents/MovingPlatformComponent.cpp index 42699672..2666c60c 100644 --- a/dGame/dComponents/MovingPlatformComponent.cpp +++ b/dGame/dComponents/MovingPlatformComponent.cpp @@ -12,11 +12,12 @@ #include "GameMessages.h" #include "CppScripts.h" #include "SimplePhysicsComponent.h" +#include "Zone.h" MoverSubComponent::MoverSubComponent(const NiPoint3& startPos) { mPosition = {}; - mState = MovementPlatformState::Stopped; + mState = eMovementPlatformState::Stopped; mDesiredWaypointIndex = 0; // -1; mInReverse = false; mShouldStopAtDesiredWaypoint = false; @@ -127,7 +128,7 @@ void MovingPlatformComponent::OnCompleteRebuild() { StartPathing(); } -void MovingPlatformComponent::SetMovementState(MovementPlatformState value) { +void MovingPlatformComponent::SetMovementState(eMovementPlatformState value) { auto* subComponent = static_cast<MoverSubComponent*>(m_MoverSubComponent); subComponent->mState = value; @@ -152,7 +153,7 @@ void MovingPlatformComponent::StartPathing() { auto* subComponent = static_cast<MoverSubComponent*>(m_MoverSubComponent); subComponent->mShouldStopAtDesiredWaypoint = true; - subComponent->mState = MovementPlatformState::Stationary; + subComponent->mState = eMovementPlatformState::Stationary; NiPoint3 targetPosition; @@ -174,7 +175,7 @@ void MovingPlatformComponent::StartPathing() { } m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] { - SetMovementState(MovementPlatformState::Moving); + SetMovementState(eMovementPlatformState::Moving); }); const auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5f; @@ -199,7 +200,7 @@ void MovingPlatformComponent::StartPathing() { void MovingPlatformComponent::ContinuePathing() { auto* subComponent = static_cast<MoverSubComponent*>(m_MoverSubComponent); - subComponent->mState = MovementPlatformState::Stationary; + subComponent->mState = eMovementPlatformState::Stationary; subComponent->mCurrentWaypointIndex = subComponent->mNextWaypointIndex; @@ -282,7 +283,7 @@ void MovingPlatformComponent::ContinuePathing() { m_Parent->CancelCallbackTimers(); m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] { - SetMovementState(MovementPlatformState::Moving); + SetMovementState(eMovementPlatformState::Moving); }); auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5; @@ -313,7 +314,7 @@ void MovingPlatformComponent::StopPathing() { m_PathingStopped = true; - subComponent->mState = MovementPlatformState::Stopped; + subComponent->mState = eMovementPlatformState::Stopped; subComponent->mDesiredWaypointIndex = -1; subComponent->mShouldStopAtDesiredWaypoint = false; diff --git a/dGame/dComponents/MovingPlatformComponent.h b/dGame/dComponents/MovingPlatformComponent.h index efa3a4cf..38b15143 100644 --- a/dGame/dComponents/MovingPlatformComponent.h +++ b/dGame/dComponents/MovingPlatformComponent.h @@ -13,6 +13,9 @@ #include "dCommonVars.h" #include "EntityManager.h" #include "Component.h" +#include "eMovementPlatformState.h" + +class Path; /** * Different types of available platforms @@ -26,16 +29,6 @@ enum class eMoverSubComponentType : uint32_t { simpleMover = 5, }; -/** - * The different types of platform movement state, supposedly a bitmap - */ -enum class MovementPlatformState : uint32_t -{ - Moving = 0b00010, - Stationary = 0b11001, - Stopped = 0b01100 -}; - /** * Sub component for moving platforms that determine the actual current movement state */ @@ -49,7 +42,7 @@ public: /** * The state the platform is currently in */ - MovementPlatformState mState = MovementPlatformState::Stationary; + eMovementPlatformState mState = eMovementPlatformState::Stationary; /** * The waypoint this platform currently wants to traverse to @@ -133,7 +126,7 @@ public: * Updates the movement state for the moving platform * @param value the movement state to set */ - void SetMovementState(MovementPlatformState value); + void SetMovementState(eMovementPlatformState value); /** * Instructs the moving platform to go to some waypoint diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index d11331e7..771a9cc1 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -20,6 +20,7 @@ #include "dConfig.h" #include "dChatFilter.h" #include "Database.h" +#include "EntityInfo.h" std::unordered_map<LOT, PetComponent::PetPuzzleData> PetComponent::buildCache{}; std::unordered_map<LWOOBJID, LWOOBJID> PetComponent::currentActivities{}; diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index cef9cc36..aa3ced46 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -19,6 +19,7 @@ #include "CDComponentsRegistryTable.h" #include "CDPhysicsComponentTable.h" #include "dServer.h" +#include "EntityInfo.h" #include "dpWorld.h" #include "dpEntity.h" diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index e6540417..9498a903 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -11,6 +11,7 @@ #include "CharacterComponent.h" #include "UserManager.h" #include "dLogger.h" +#include "AMFFormat.h" PropertyEntranceComponent::PropertyEntranceComponent(uint32_t componentID, Entity* parent) : Component(parent) { this->propertyQueries = {}; diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 4b5743cd..f64dbc15 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -21,6 +21,7 @@ #include "dServer.h" #include "dZoneManager.h" #include "dConfig.h" +#include "Loot.h" #ifndef M_PI #define M_PI 3.14159265358979323846264338327950288 diff --git a/dGame/dComponents/RebuildComponent.cpp b/dGame/dComponents/RebuildComponent.cpp index c7c4e3a5..83ae818e 100644 --- a/dGame/dComponents/RebuildComponent.cpp +++ b/dGame/dComponents/RebuildComponent.cpp @@ -14,6 +14,7 @@ #include "Spawner.h" #include "MovingPlatformComponent.h" #include "Preconditions.h" +#include "Loot.h" #include "TeamManager.h" #include "CppScripts.h" diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index ee7ca22e..a03dddbe 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -18,6 +18,8 @@ #include "dConfig.h" #include "InventoryComponent.h" #include "DestroyableComponent.h" +#include "dMessageIdentifiers.h" +#include "Loot.h" ScriptedActivityComponent::ScriptedActivityComponent(Entity* parent, int activityID) : Component(parent) { m_ActivityID = activityID; diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index 0608c63b..562c284a 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -19,7 +19,9 @@ #include "BaseCombatAIComponent.h" #include "ScriptComponent.h" #include "BuffComponent.h" - +#include "EchoStartSkill.h" +#include "dMessageIdentifiers.h" +#include "DoClientProjectileImpact.h" ProjectileSyncEntry::ProjectileSyncEntry() { } @@ -240,7 +242,7 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c if (!clientInitalized) { // Echo start skill - GameMessages::EchoStartSkill start; + EchoStartSkill start; start.iCastType = 0; start.skillID = skillId; @@ -384,7 +386,7 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) behavior->Calculate(entry.context, bitStream, entry.branchContext); - GameMessages::DoClientProjectileImpact projectileImpact; + DoClientProjectileImpact projectileImpact; projectileImpact.sBitStream.assign((char*)bitStream->GetData(), bitStream->GetNumberOfBytesUsed()); projectileImpact.i64OwnerID = this->m_Parent->GetObjectID(); diff --git a/dGame/dGameMessages/DoClientProjectileImpact.h b/dGame/dGameMessages/DoClientProjectileImpact.h new file mode 100644 index 00000000..436e3dd2 --- /dev/null +++ b/dGame/dGameMessages/DoClientProjectileImpact.h @@ -0,0 +1,83 @@ +#ifndef __DOCLIENTPROJECTILEIMPACT__H__ +#define __DOCLIENTPROJECTILEIMPACT__H__ + +#include "dMessageIdentifiers.h" +#include "dCommonVars.h" + +/* Tell a client local projectile to impact */ +class DoClientProjectileImpact { + static const GAME_MSG MsgID = GAME_MSG_DO_CLIENT_PROJECTILE_IMPACT; + +public: + DoClientProjectileImpact() { + i64OrgID = LWOOBJID_EMPTY; + i64OwnerID = LWOOBJID_EMPTY; + i64TargetID = LWOOBJID_EMPTY; + } + + DoClientProjectileImpact(std::string _sBitStream, LWOOBJID _i64OrgID = LWOOBJID_EMPTY, LWOOBJID _i64OwnerID = LWOOBJID_EMPTY, LWOOBJID _i64TargetID = LWOOBJID_EMPTY) { + i64OrgID = _i64OrgID; + i64OwnerID = _i64OwnerID; + i64TargetID = _i64TargetID; + sBitStream = _sBitStream; + } + + DoClientProjectileImpact(RakNet::BitStream* stream) : DoClientProjectileImpact() { + Deserialize(stream); + } + + ~DoClientProjectileImpact() { + } + + void Serialize(RakNet::BitStream* stream) { + stream->Write(MsgID); + + stream->Write(i64OrgID != LWOOBJID_EMPTY); + if (i64OrgID != LWOOBJID_EMPTY) stream->Write(i64OrgID); + + stream->Write(i64OwnerID != LWOOBJID_EMPTY); + if (i64OwnerID != LWOOBJID_EMPTY) stream->Write(i64OwnerID); + + stream->Write(i64TargetID != LWOOBJID_EMPTY); + if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); + + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (uint32_t k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } + + } + + bool Deserialize(RakNet::BitStream* stream) { + bool i64OrgIDIsDefault{}; + stream->Read(i64OrgIDIsDefault); + if (i64OrgIDIsDefault != 0) stream->Read(i64OrgID); + + bool i64OwnerIDIsDefault{}; + stream->Read(i64OwnerIDIsDefault); + if (i64OwnerIDIsDefault != 0) stream->Read(i64OwnerID); + + bool i64TargetIDIsDefault{}; + stream->Read(i64TargetIDIsDefault); + if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); + + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (uint32_t k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } + + + return true; + } + + LWOOBJID i64OrgID; + LWOOBJID i64OwnerID; + LWOOBJID i64TargetID; + std::string sBitStream; +}; + +#endif //!__DOCLIENTPROJECTILEIMPACT__H__ diff --git a/dGame/dGameMessages/EchoStartSkill.h b/dGame/dGameMessages/EchoStartSkill.h new file mode 100644 index 00000000..6d912798 --- /dev/null +++ b/dGame/dGameMessages/EchoStartSkill.h @@ -0,0 +1,132 @@ +#ifndef __ECHOSTARTSKILL__H__ +#define __ECHOSTARTSKILL__H__ + +#include "dCommonVars.h" +#include "dMessageIdentifiers.h" +#include "NiPoint3.h" +#include "NiQuaternion.h" + +/* Same as start skill but with different network options. An echo down to other clients that need to play the skill. */ +class EchoStartSkill { + static const GAME_MSG MsgID = GAME_MSG_ECHO_START_SKILL; + +public: + EchoStartSkill() { + bUsedMouse = false; + fCasterLatency = 0.0f; + iCastType = 0; + lastClickedPosit = NiPoint3::ZERO; + optionalTargetID = LWOOBJID_EMPTY; + originatorRot = NiQuaternion::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) { + bUsedMouse = _bUsedMouse; + fCasterLatency = _fCasterLatency; + iCastType = _iCastType; + lastClickedPosit = _lastClickedPosit; + optionalOriginatorID = _optionalOriginatorID; + optionalTargetID = _optionalTargetID; + originatorRot = _originatorRot; + sBitStream = _sBitStream; + skillID = _skillID; + uiSkillHandle = _uiSkillHandle; + } + + EchoStartSkill(RakNet::BitStream* stream) : EchoStartSkill() { + Deserialize(stream); + } + + ~EchoStartSkill() { + } + + void Serialize(RakNet::BitStream* stream) { + stream->Write(MsgID); + + stream->Write(bUsedMouse); + + stream->Write(fCasterLatency != 0.0f); + if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); + + stream->Write(iCastType != 0); + if (iCastType != 0) stream->Write(iCastType); + + stream->Write(lastClickedPosit != NiPoint3::ZERO); + if (lastClickedPosit != NiPoint3::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); + + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (uint32_t k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } + + stream->Write(skillID); + + stream->Write(uiSkillHandle != 0); + if (uiSkillHandle != 0) stream->Write(uiSkillHandle); + } + + bool Deserialize(RakNet::BitStream* stream) { + stream->Read(bUsedMouse); + + bool fCasterLatencyIsDefault{}; + stream->Read(fCasterLatencyIsDefault); + if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); + + bool iCastTypeIsDefault{}; + stream->Read(iCastTypeIsDefault); + if (iCastTypeIsDefault != 0) stream->Read(iCastType); + + bool lastClickedPositIsDefault{}; + stream->Read(lastClickedPositIsDefault); + if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); + + stream->Read(optionalOriginatorID); + + bool optionalTargetIDIsDefault{}; + stream->Read(optionalTargetIDIsDefault); + if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); + + bool originatorRotIsDefault{}; + stream->Read(originatorRotIsDefault); + if (originatorRotIsDefault != 0) stream->Read(originatorRot); + + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (uint32_t k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } + + stream->Read(skillID); + + bool uiSkillHandleIsDefault{}; + stream->Read(uiSkillHandleIsDefault); + if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); + + return true; + } + + bool bUsedMouse; + float fCasterLatency; + int32_t iCastType; + NiPoint3 lastClickedPosit; + LWOOBJID optionalOriginatorID; + LWOOBJID optionalTargetID; + NiQuaternion originatorRot; + std::string sBitStream; + TSkillID skillID; + uint32_t uiSkillHandle; +}; + +#endif //!__ECHOSTARTSKILL__H__ diff --git a/dGame/dGameMessages/EchoSyncSkill.h b/dGame/dGameMessages/EchoSyncSkill.h new file mode 100644 index 00000000..b56beae8 --- /dev/null +++ b/dGame/dGameMessages/EchoSyncSkill.h @@ -0,0 +1,70 @@ +#ifndef __ECHOSYNCSKILL__H__ +#define __ECHOSYNCSKILL__H__ + +#include <string> + +#include "BitStream.h" + +#include "dMessageIdentifiers.h" + +/* Message to synchronize a skill cast */ +class EchoSyncSkill { + static const GAME_MSG MsgID = GAME_MSG_ECHO_SYNC_SKILL; + +public: + EchoSyncSkill() { + bDone = false; + } + + EchoSyncSkill(std::string _sBitStream, uint32_t _uiBehaviorHandle, uint32_t _uiSkillHandle, bool _bDone = false) { + bDone = _bDone; + sBitStream = _sBitStream; + uiBehaviorHandle = _uiBehaviorHandle; + uiSkillHandle = _uiSkillHandle; + } + + EchoSyncSkill(RakNet::BitStream* stream) : EchoSyncSkill() { + Deserialize(stream); + } + + ~EchoSyncSkill() { + } + + void Serialize(RakNet::BitStream* stream) { + stream->Write(MsgID); + + stream->Write(bDone); + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (uint32_t k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } + + stream->Write(uiBehaviorHandle); + stream->Write(uiSkillHandle); + } + + bool Deserialize(RakNet::BitStream* stream) { + stream->Read(bDone); + + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } + + stream->Read(uiBehaviorHandle); + stream->Read(uiSkillHandle); + + return true; + } + + bool bDone{}; + std::string sBitStream{}; + uint32_t uiBehaviorHandle{}; + uint32_t uiSkillHandle{}; +}; + +#endif //!__ECHOSYNCSKILL__H__ diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index b7687c19..c03f58db 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -26,6 +26,11 @@ #include "CDSkillBehaviorTable.h" #include "SkillComponent.h" #include "RacingControlComponent.h" +#include "RequestServerProjectileImpact.h" +#include "SyncSkill.h" +#include "StartSkill.h" +#include "EchoStartSkill.h" +#include "EchoSyncSkill.h" using namespace std; @@ -251,7 +256,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT: { - auto message = GameMessages::RequestServerProjectileImpact(); + auto message = RequestServerProjectileImpact(); message.Deserialize(inStream); @@ -269,7 +274,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System } case GAME_MSG_START_SKILL: { - GameMessages::StartSkill startSkill = GameMessages::StartSkill(); + StartSkill startSkill = StartSkill(); startSkill.Deserialize(inStream); // inStream replaces &bitStream if (startSkill.skillID == 1561 || startSkill.skillID == 1562 || startSkill.skillID == 1541) return; @@ -309,7 +314,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System PacketUtils::WriteHeader(bitStreamLocal, CLIENT, MSG_CLIENT_GAME_MSG); bitStreamLocal.Write(entity->GetObjectID()); - GameMessages::EchoStartSkill echoStartSkill; + EchoStartSkill echoStartSkill; echoStartSkill.bUsedMouse = startSkill.bUsedMouse; echoStartSkill.fCasterLatency = startSkill.fCasterLatency; echoStartSkill.iCastType = startSkill.iCastType; @@ -333,7 +338,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System //bitStreamLocal.Write((unsigned short)GAME_MSG_ECHO_SYNC_SKILL); //bitStreamLocal.Write(inStream); - GameMessages::SyncSkill sync = GameMessages::SyncSkill(inStream); // inStream replaced &bitStream + SyncSkill sync = SyncSkill(inStream); // inStream replaced &bitStream //sync.Serialize(&bitStreamLocal); ostringstream buffer; @@ -356,7 +361,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System delete bs; } - GameMessages::EchoSyncSkill echo = GameMessages::EchoSyncSkill(); + EchoSyncSkill echo = EchoSyncSkill(); echo.bDone = sync.bDone; echo.sBitStream = sync.sBitStream; echo.uiBehaviorHandle = sync.uiBehaviorHandle; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 2423915e..24f0816d 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -28,6 +28,10 @@ #include "GameConfig.h" #include "RocketLaunchLupComponent.h" #include "eUnequippableActiveType.h" +#include "eMovementPlatformState.h" +#include "LeaderboardManager.h" +#include "AMFFormat.h" +#include "Loot.h" #include "RacingTaskParam.h" #include <sstream> @@ -73,6 +77,7 @@ #include "ControlBehaviors.h" #include "AMFDeserialize.h" #include "eBlueprintSaveResponseType.h" +#include "eAninmationFlags.h" void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender) { CBITSTREAM; @@ -330,7 +335,7 @@ void GameMessages::SendStartPathing(Entity* entity) { void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAddr, bool bStopAtDesiredWaypoint, int iIndex, int iDesiredWaypointIndex, int nextIndex, - MovementPlatformState movementState) { + eMovementPlatformState movementState) { CBITSTREAM; CMSGHEADER; @@ -341,7 +346,7 @@ void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAd iIndex = 0; nextIndex = 0; bStopAtDesiredWaypoint = true; - movementState = MovementPlatformState::Stationary; + movementState = eMovementPlatformState::Stationary; } bitStream.Write(entity->GetObjectID()); @@ -575,7 +580,7 @@ void GameMessages::SendModifyLEGOScore(Entity* entity, const SystemAddress& sysA SEND_PACKET; } -void GameMessages::SendUIMessageServerToSingleClient(Entity* entity, const SystemAddress& sysAddr, const std::string& message, NDGFxValue args) { +void GameMessages::SendUIMessageServerToSingleClient(Entity* entity, const SystemAddress& sysAddr, const std::string& message, AMFValue* args) { CBITSTREAM; CMSGHEADER; @@ -593,7 +598,7 @@ void GameMessages::SendUIMessageServerToSingleClient(Entity* entity, const Syste SEND_PACKET; } -void GameMessages::SendUIMessageServerToAllClients(const std::string& message, NDGFxValue args) { +void GameMessages::SendUIMessageServerToAllClients(const std::string& message, AMFValue* args) { CBITSTREAM; CMSGHEADER; diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 8a1c2fe5..6575ad85 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -1,27 +1,26 @@ - #ifndef GAMEMESSAGES_H #define GAMEMESSAGES_H #include "dCommonVars.h" -#include "RakNetTypes.h" +#include <map> #include <string> -#include "dMessageIdentifiers.h" -#include "AMFFormat.h" -#include "AMFFormat_BitStream.h" -#include "NiQuaternion.h" -#include "PropertySelectQueryProperty.h" -#include "TradingManager.h" -#include "LeaderboardManager.h" -#include "MovingPlatformComponent.h" -#include "eAninmationFlags.h" +#include <vector> +#include "eMovementPlatformState.h" +#include "NiPoint3.h" +class AMFValue; +class Entity; +class Item; class NiQuaternion; class User; -class Entity; -class NiPoint3; +class Leaderboard; +class PropertySelectQueryProperty; +class TradeItem; + +enum class eAnimationFlags : uint32_t; + enum class eUnequippableActiveType; enum eInventoryType : uint32_t; -class Item; namespace GameMessages { class PropertyDataMessage; @@ -57,7 +56,7 @@ namespace GameMessages { void SendStartPathing(Entity* entity); void SendPlatformResync(Entity* entity, const SystemAddress& sysAddr, bool bStopAtDesiredWaypoint = false, int iIndex = 0, int iDesiredWaypointIndex = 1, int nextIndex = 1, - MovementPlatformState movementState = MovementPlatformState::Moving); + eMovementPlatformState movementState = eMovementPlatformState::Moving); void SendRestoreToPostLoadStats(Entity* entity, const SystemAddress& sysAddr); void SendServerDoneLoadingAllObjects(Entity* entity, const SystemAddress& sysAddr); @@ -74,8 +73,8 @@ namespace GameMessages { void NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sysAddr, int level, bool sending_rewards); void SendModifyLEGOScore(Entity* entity, const SystemAddress& sysAddr, int64_t score, eLootSourceType sourceType); - void SendUIMessageServerToSingleClient(Entity* entity, const SystemAddress& sysAddr, const std::string& message, NDGFxValue args); - void SendUIMessageServerToAllClients(const std::string& message, NDGFxValue args); + void SendUIMessageServerToSingleClient(Entity* entity, const SystemAddress& sysAddr, const std::string& message, AMFValue* args); + void SendUIMessageServerToAllClients(const std::string& message, AMFValue* args); void SendPlayEmbeddedEffectOnAllClientsNearObject(Entity* entity, std::u16string effectName, const LWOOBJID& fromObjectID, float radius); void SendPlayFXEffect(Entity* entity, int32_t effectID, const std::u16string& effectType, const std::string& name, LWOOBJID secondary, float priority = 1, float scale = 1, bool serialize = true); @@ -589,550 +588,6 @@ namespace GameMessages { void HandleReportBug(RakNet::BitStream* inStream, Entity* entity); void SendRemoveBuff(Entity* entity, bool fromUnEquip, bool removeImmunity, uint32_t buffId); - - /* Message to synchronize a skill cast */ - class EchoSyncSkill { - static const GAME_MSG MsgID = GAME_MSG_ECHO_SYNC_SKILL; - - public: - EchoSyncSkill() { - bDone = false; - } - - EchoSyncSkill(std::string _sBitStream, unsigned int _uiBehaviorHandle, unsigned int _uiSkillHandle, bool _bDone = false) { - bDone = _bDone; - sBitStream = _sBitStream; - uiBehaviorHandle = _uiBehaviorHandle; - uiSkillHandle = _uiSkillHandle; - } - - EchoSyncSkill(RakNet::BitStream* stream) { - bDone = false; - - Deserialize(stream); - } - - ~EchoSyncSkill() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); - - stream->Write(bDone); - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } - - stream->Write(uiBehaviorHandle); - stream->Write(uiSkillHandle); - } - - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bDone); - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } - - stream->Read(uiBehaviorHandle); - stream->Read(uiSkillHandle); - - return true; - } - - bool bDone{}; - std::string sBitStream{}; - unsigned int uiBehaviorHandle{}; - unsigned int uiSkillHandle{}; - }; - - /* Message to synchronize a skill cast */ - class SyncSkill { - static const GAME_MSG MsgID = GAME_MSG_SYNC_SKILL; - - public: - SyncSkill() { - bDone = false; - } - - SyncSkill(std::string _sBitStream, unsigned int _uiBehaviorHandle, unsigned int _uiSkillHandle, bool _bDone = false) { - bDone = _bDone; - sBitStream = _sBitStream; - uiBehaviorHandle = _uiBehaviorHandle; - uiSkillHandle = _uiSkillHandle; - } - - SyncSkill(RakNet::BitStream* stream) { - bDone = false; - Deserialize(stream); - } - - ~SyncSkill() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); - - stream->Write(bDone); - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } - - stream->Write(uiBehaviorHandle); - stream->Write(uiSkillHandle); - } - - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bDone); - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } - - stream->Read(uiBehaviorHandle); - stream->Read(uiSkillHandle); - - return true; - } - - bool bDone{}; - std::string sBitStream{}; - unsigned int uiBehaviorHandle{}; - unsigned int uiSkillHandle{}; - }; - - /* Notifying the server that a locally owned projectil impacted. Sent to the caster of the projectile - should always be the local char. */ - class RequestServerProjectileImpact { - static const GAME_MSG MsgID = GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT; - - public: - RequestServerProjectileImpact() { - i64LocalID = LWOOBJID_EMPTY; - i64TargetID = LWOOBJID_EMPTY; - } - - RequestServerProjectileImpact(std::string _sBitStream, LWOOBJID _i64LocalID = LWOOBJID_EMPTY, LWOOBJID _i64TargetID = LWOOBJID_EMPTY) { - i64LocalID = _i64LocalID; - i64TargetID = _i64TargetID; - sBitStream = _sBitStream; - } - - RequestServerProjectileImpact(RakNet::BitStream* stream) { - i64LocalID = LWOOBJID_EMPTY; - i64TargetID = LWOOBJID_EMPTY; - - Deserialize(stream); - } - - ~RequestServerProjectileImpact() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); - - stream->Write(i64LocalID != LWOOBJID_EMPTY); - if (i64LocalID != LWOOBJID_EMPTY) stream->Write(i64LocalID); - - stream->Write(i64TargetID != LWOOBJID_EMPTY); - if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); - - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } - - } - - bool Deserialize(RakNet::BitStream* stream) { - bool i64LocalIDIsDefault{}; - stream->Read(i64LocalIDIsDefault); - if (i64LocalIDIsDefault != 0) stream->Read(i64LocalID); - - bool i64TargetIDIsDefault{}; - stream->Read(i64TargetIDIsDefault); - if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); - - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } - - - return true; - } - - LWOOBJID i64LocalID; - LWOOBJID i64TargetID; - std::string sBitStream; - }; - - /* Tell a client local projectile to impact */ - class DoClientProjectileImpact { - static const GAME_MSG MsgID = GAME_MSG_DO_CLIENT_PROJECTILE_IMPACT; - - public: - DoClientProjectileImpact() { - i64OrgID = LWOOBJID_EMPTY; - i64OwnerID = LWOOBJID_EMPTY; - i64TargetID = LWOOBJID_EMPTY; - } - - DoClientProjectileImpact(std::string _sBitStream, LWOOBJID _i64OrgID = LWOOBJID_EMPTY, LWOOBJID _i64OwnerID = LWOOBJID_EMPTY, LWOOBJID _i64TargetID = LWOOBJID_EMPTY) { - i64OrgID = _i64OrgID; - i64OwnerID = _i64OwnerID; - i64TargetID = _i64TargetID; - sBitStream = _sBitStream; - } - - DoClientProjectileImpact(RakNet::BitStream* stream) { - i64OrgID = LWOOBJID_EMPTY; - i64OwnerID = LWOOBJID_EMPTY; - i64TargetID = LWOOBJID_EMPTY; - - Deserialize(stream); - } - - ~DoClientProjectileImpact() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); - - stream->Write(i64OrgID != LWOOBJID_EMPTY); - if (i64OrgID != LWOOBJID_EMPTY) stream->Write(i64OrgID); - - stream->Write(i64OwnerID != LWOOBJID_EMPTY); - if (i64OwnerID != LWOOBJID_EMPTY) stream->Write(i64OwnerID); - - stream->Write(i64TargetID != LWOOBJID_EMPTY); - if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); - - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } - - } - - bool Deserialize(RakNet::BitStream* stream) { - bool i64OrgIDIsDefault{}; - stream->Read(i64OrgIDIsDefault); - if (i64OrgIDIsDefault != 0) stream->Read(i64OrgID); - - bool i64OwnerIDIsDefault{}; - stream->Read(i64OwnerIDIsDefault); - if (i64OwnerIDIsDefault != 0) stream->Read(i64OwnerID); - - bool i64TargetIDIsDefault{}; - stream->Read(i64TargetIDIsDefault); - if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); - - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } - - - return true; - } - - LWOOBJID i64OrgID; - LWOOBJID i64OwnerID; - LWOOBJID i64TargetID; - std::string sBitStream; - }; - - /* Same as start skill but with different network options. An echo down to other clients that need to play the skill. */ - class EchoStartSkill { - static const GAME_MSG MsgID = GAME_MSG_ECHO_START_SKILL; - - public: - EchoStartSkill() { - bUsedMouse = false; - fCasterLatency = 0.0f; - iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; - optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; - uiSkillHandle = 0; - } - - EchoStartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, float _fCasterLatency = 0.0f, int _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, unsigned int _uiSkillHandle = 0) { - bUsedMouse = _bUsedMouse; - fCasterLatency = _fCasterLatency; - iCastType = _iCastType; - lastClickedPosit = _lastClickedPosit; - optionalOriginatorID = _optionalOriginatorID; - optionalTargetID = _optionalTargetID; - originatorRot = _originatorRot; - sBitStream = _sBitStream; - skillID = _skillID; - uiSkillHandle = _uiSkillHandle; - } - - EchoStartSkill(RakNet::BitStream* stream) { - bUsedMouse = false; - fCasterLatency = 0.0f; - iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; - optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; - uiSkillHandle = 0; - - Deserialize(stream); - } - - ~EchoStartSkill() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); - - stream->Write(bUsedMouse); - - stream->Write(fCasterLatency != 0.0f); - if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); - - stream->Write(iCastType != 0); - if (iCastType != 0) stream->Write(iCastType); - - stream->Write(lastClickedPosit != NiPoint3::ZERO); - if (lastClickedPosit != NiPoint3::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); - - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } - - stream->Write(skillID); - - stream->Write(uiSkillHandle != 0); - if (uiSkillHandle != 0) stream->Write(uiSkillHandle); - } - - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bUsedMouse); - - bool fCasterLatencyIsDefault{}; - stream->Read(fCasterLatencyIsDefault); - if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); - - bool iCastTypeIsDefault{}; - stream->Read(iCastTypeIsDefault); - if (iCastTypeIsDefault != 0) stream->Read(iCastType); - - bool lastClickedPositIsDefault{}; - stream->Read(lastClickedPositIsDefault); - if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); - - stream->Read(optionalOriginatorID); - - bool optionalTargetIDIsDefault{}; - stream->Read(optionalTargetIDIsDefault); - if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); - - bool originatorRotIsDefault{}; - stream->Read(originatorRotIsDefault); - if (originatorRotIsDefault != 0) stream->Read(originatorRot); - - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } - - stream->Read(skillID); - - bool uiSkillHandleIsDefault{}; - stream->Read(uiSkillHandleIsDefault); - if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); - - return true; - } - - bool bUsedMouse; - float fCasterLatency; - int iCastType; - NiPoint3 lastClickedPosit; - LWOOBJID optionalOriginatorID; - LWOOBJID optionalTargetID; - NiQuaternion originatorRot; - std::string sBitStream; - TSkillID skillID; - unsigned int uiSkillHandle; - }; - - /* Same as sync skill but with different network options. An echo down to other clients that need to play the skill. */ - class StartSkill { - static const GAME_MSG MsgID = GAME_MSG_START_SKILL; - - public: - StartSkill() { - bUsedMouse = false; - consumableItemID = LWOOBJID_EMPTY; - fCasterLatency = 0.0f; - iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; - optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; - uiSkillHandle = 0; - } - - StartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, LWOOBJID _consumableItemID = LWOOBJID_EMPTY, float _fCasterLatency = 0.0f, int _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, unsigned int _uiSkillHandle = 0) { - bUsedMouse = _bUsedMouse; - consumableItemID = _consumableItemID; - fCasterLatency = _fCasterLatency; - iCastType = _iCastType; - lastClickedPosit = _lastClickedPosit; - optionalOriginatorID = _optionalOriginatorID; - optionalTargetID = _optionalTargetID; - originatorRot = _originatorRot; - sBitStream = _sBitStream; - skillID = _skillID; - uiSkillHandle = _uiSkillHandle; - } - - StartSkill(RakNet::BitStream* stream) { - bUsedMouse = false; - consumableItemID = LWOOBJID_EMPTY; - fCasterLatency = 0.0f; - iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; - optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; - uiSkillHandle = 0; - - Deserialize(stream); - } - - ~StartSkill() { - } - - void Serialize(RakNet::BitStream* stream) { - stream->Write((unsigned short)MsgID); - - stream->Write(bUsedMouse); - - stream->Write(consumableItemID != LWOOBJID_EMPTY); - if (consumableItemID != LWOOBJID_EMPTY) stream->Write(consumableItemID); - - stream->Write(fCasterLatency != 0.0f); - if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); - - stream->Write(iCastType != 0); - if (iCastType != 0) stream->Write(iCastType); - - stream->Write(lastClickedPosit != NiPoint3::ZERO); - if (lastClickedPosit != NiPoint3::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); - - uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); - } - - stream->Write(skillID); - - stream->Write(uiSkillHandle != 0); - if (uiSkillHandle != 0) stream->Write(uiSkillHandle); - } - - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bUsedMouse); - - bool consumableItemIDIsDefault{}; - stream->Read(consumableItemIDIsDefault); - if (consumableItemIDIsDefault != 0) stream->Read(consumableItemID); - - bool fCasterLatencyIsDefault{}; - stream->Read(fCasterLatencyIsDefault); - if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); - - bool iCastTypeIsDefault{}; - stream->Read(iCastTypeIsDefault); - if (iCastTypeIsDefault != 0) stream->Read(iCastType); - - bool lastClickedPositIsDefault{}; - stream->Read(lastClickedPositIsDefault); - if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); - - stream->Read(optionalOriginatorID); - - bool optionalTargetIDIsDefault{}; - stream->Read(optionalTargetIDIsDefault); - if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); - - bool originatorRotIsDefault{}; - stream->Read(originatorRotIsDefault); - if (originatorRotIsDefault != 0) stream->Read(originatorRot); - - uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); - for (unsigned int k = 0; k < sBitStreamLength; k++) { - unsigned char character; - stream->Read(character); - sBitStream.push_back(character); - } - - stream->Read(skillID); - - bool uiSkillHandleIsDefault{}; - stream->Read(uiSkillHandleIsDefault); - if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); - - return true; - } - - bool bUsedMouse = false; - LWOOBJID consumableItemID{}; - float fCasterLatency{}; - int iCastType{}; - NiPoint3 lastClickedPosit{}; - LWOOBJID optionalOriginatorID{}; - LWOOBJID optionalTargetID{}; - NiQuaternion originatorRot{}; - std::string sBitStream = ""; - TSkillID skillID = 0; - unsigned int uiSkillHandle = 0; - }; }; #endif // GAMEMESSAGES_H diff --git a/dGame/dGameMessages/RequestServerProjectileImpact.h b/dGame/dGameMessages/RequestServerProjectileImpact.h new file mode 100644 index 00000000..01426361 --- /dev/null +++ b/dGame/dGameMessages/RequestServerProjectileImpact.h @@ -0,0 +1,74 @@ +#ifndef __REQUESTSERVERPROJECTILEIMPACT__H__ +#define __REQUESTSERVERPROJECTILEIMPACT__H__ + +#include "dCommonVars.h" +#include "dMessageIdentifiers.h" + +/* Notifying the server that a locally owned projectile impacted. Sent to the caster of the projectile + should always be the local char. */ +class RequestServerProjectileImpact { + static const GAME_MSG MsgID = GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT; + +public: + RequestServerProjectileImpact() { + i64LocalID = LWOOBJID_EMPTY; + i64TargetID = LWOOBJID_EMPTY; + } + + RequestServerProjectileImpact(std::string _sBitStream, LWOOBJID _i64LocalID = LWOOBJID_EMPTY, LWOOBJID _i64TargetID = LWOOBJID_EMPTY) { + i64LocalID = _i64LocalID; + i64TargetID = _i64TargetID; + sBitStream = _sBitStream; + } + + RequestServerProjectileImpact(RakNet::BitStream* stream) : RequestServerProjectileImpact() { + Deserialize(stream); + } + + ~RequestServerProjectileImpact() { + } + + void Serialize(RakNet::BitStream* stream) { + stream->Write(MsgID); + + stream->Write(i64LocalID != LWOOBJID_EMPTY); + if (i64LocalID != LWOOBJID_EMPTY) stream->Write(i64LocalID); + + stream->Write(i64TargetID != LWOOBJID_EMPTY); + if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); + + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (uint32_t k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } + + } + + bool Deserialize(RakNet::BitStream* stream) { + bool i64LocalIDIsDefault{}; + stream->Read(i64LocalIDIsDefault); + if (i64LocalIDIsDefault != 0) stream->Read(i64LocalID); + + bool i64TargetIDIsDefault{}; + stream->Read(i64TargetIDIsDefault); + if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); + + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (uint32_t k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } + + + return true; + } + + LWOOBJID i64LocalID; + LWOOBJID i64TargetID; + std::string sBitStream; +}; + +#endif //!__REQUESTSERVERPROJECTILEIMPACT__H__ diff --git a/dGame/dGameMessages/StartSkill.h b/dGame/dGameMessages/StartSkill.h new file mode 100644 index 00000000..af82a9b4 --- /dev/null +++ b/dGame/dGameMessages/StartSkill.h @@ -0,0 +1,144 @@ +#ifndef __STARTSKILL__H__ +#define __STARTSKILL__H__ + +#include "dCommonVars.h" +#include "dMessageIdentifiers.h" +#include "NiPoint3.h" +#include "NiQuaternion.h" + +/** + * Same as sync skill but with different network options. An echo down to other clients that need to play the skill. + */ +class StartSkill { + static const GAME_MSG MsgID = GAME_MSG_START_SKILL; + +public: + StartSkill() { + bUsedMouse = false; + consumableItemID = LWOOBJID_EMPTY; + fCasterLatency = 0.0f; + iCastType = 0; + lastClickedPosit = NiPoint3::ZERO; + optionalTargetID = LWOOBJID_EMPTY; + originatorRot = NiQuaternion::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) { + bUsedMouse = _bUsedMouse; + consumableItemID = _consumableItemID; + fCasterLatency = _fCasterLatency; + iCastType = _iCastType; + lastClickedPosit = _lastClickedPosit; + optionalOriginatorID = _optionalOriginatorID; + optionalTargetID = _optionalTargetID; + originatorRot = _originatorRot; + sBitStream = _sBitStream; + skillID = _skillID; + uiSkillHandle = _uiSkillHandle; + } + + StartSkill(RakNet::BitStream* stream) : StartSkill() { + Deserialize(stream); + } + + ~StartSkill() { + } + + void Serialize(RakNet::BitStream* stream) { + stream->Write(MsgID); + + stream->Write(bUsedMouse); + + stream->Write(consumableItemID != LWOOBJID_EMPTY); + if (consumableItemID != LWOOBJID_EMPTY) stream->Write(consumableItemID); + + stream->Write(fCasterLatency != 0.0f); + if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); + + stream->Write(iCastType != 0); + if (iCastType != 0) stream->Write(iCastType); + + stream->Write(lastClickedPosit != NiPoint3::ZERO); + if (lastClickedPosit != NiPoint3::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); + + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (uint32_t k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } + + stream->Write(skillID); + + stream->Write(uiSkillHandle != 0); + if (uiSkillHandle != 0) stream->Write(uiSkillHandle); + } + + bool Deserialize(RakNet::BitStream* stream) { + stream->Read(bUsedMouse); + + bool consumableItemIDIsDefault{}; + stream->Read(consumableItemIDIsDefault); + if (consumableItemIDIsDefault != 0) stream->Read(consumableItemID); + + bool fCasterLatencyIsDefault{}; + stream->Read(fCasterLatencyIsDefault); + if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); + + bool iCastTypeIsDefault{}; + stream->Read(iCastTypeIsDefault); + if (iCastTypeIsDefault != 0) stream->Read(iCastType); + + bool lastClickedPositIsDefault{}; + stream->Read(lastClickedPositIsDefault); + if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); + + stream->Read(optionalOriginatorID); + + bool optionalTargetIDIsDefault{}; + stream->Read(optionalTargetIDIsDefault); + if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); + + bool originatorRotIsDefault{}; + stream->Read(originatorRotIsDefault); + if (originatorRotIsDefault != 0) stream->Read(originatorRot); + + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (uint32_t k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } + + stream->Read(skillID); + + bool uiSkillHandleIsDefault{}; + stream->Read(uiSkillHandleIsDefault); + if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); + + return true; + } + + bool bUsedMouse = false; + LWOOBJID consumableItemID{}; + float fCasterLatency{}; + int32_t iCastType{}; + NiPoint3 lastClickedPosit{}; + LWOOBJID optionalOriginatorID{}; + LWOOBJID optionalTargetID{}; + NiQuaternion originatorRot{}; + std::string sBitStream = ""; + TSkillID skillID = 0; + uint32_t uiSkillHandle = 0; +}; + +#endif //!__STARTSKILL__H__ diff --git a/dGame/dGameMessages/SyncSkill.h b/dGame/dGameMessages/SyncSkill.h new file mode 100644 index 00000000..72a88839 --- /dev/null +++ b/dGame/dGameMessages/SyncSkill.h @@ -0,0 +1,68 @@ +#ifndef __SYNCSKILL__H__ +#define __SYNCSKILL__H__ + +#include <cstdint> +#include <string> + +#include "BitStream.h" + +/* Message to synchronize a skill cast */ +class SyncSkill { + static const GAME_MSG MsgID = GAME_MSG_SYNC_SKILL; + +public: + SyncSkill() { + bDone = false; + } + + SyncSkill(std::string _sBitStream, uint32_t _uiBehaviorHandle, uint32_t _uiSkillHandle, bool _bDone = false) { + bDone = _bDone; + sBitStream = _sBitStream; + uiBehaviorHandle = _uiBehaviorHandle; + uiSkillHandle = _uiSkillHandle; + } + + SyncSkill(RakNet::BitStream* stream) : SyncSkill() { + Deserialize(stream); + } + + ~SyncSkill() { + } + + void Serialize(RakNet::BitStream* stream) { + stream->Write(MsgID); + + stream->Write(bDone); + uint32_t sBitStreamLength = sBitStream.length(); + stream->Write(sBitStreamLength); + for (unsigned int k = 0; k < sBitStreamLength; k++) { + stream->Write(sBitStream[k]); + } + + stream->Write(uiBehaviorHandle); + stream->Write(uiSkillHandle); + } + + bool Deserialize(RakNet::BitStream* stream) { + stream->Read(bDone); + uint32_t sBitStreamLength{}; + stream->Read(sBitStreamLength); + for (uint32_t k = 0; k < sBitStreamLength; k++) { + unsigned char character; + stream->Read(character); + sBitStream.push_back(character); + } + + stream->Read(uiBehaviorHandle); + stream->Read(uiSkillHandle); + + return true; + } + + bool bDone{}; + std::string sBitStream{}; + uint32_t uiBehaviorHandle{}; + uint32_t uiSkillHandle{}; +}; + +#endif //!__SYNCSKILL__H__ diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 4f3626e3..d6721bdd 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -15,6 +15,7 @@ #include "eItemType.h" #include "AssetManager.h" #include "InventoryComponent.h" +#include "Loot.h" Item::Item(const LWOOBJID id, const LOT lot, Inventory* inventory, const uint32_t slot, const uint32_t count, const bool bound, const std::vector<LDFBaseData*>& config, const LWOOBJID parent, LWOOBJID subKey, eLootSourceType lootSourceType) { if (!Inventory::IsValidItem(lot)) { diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index a1ae724a..df1b16d7 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -17,6 +17,7 @@ #include "dServer.h" #include "dZoneManager.h" #include "InventoryComponent.h" +#include "User.h" #include "Database.h" #include "WorldConfig.h" diff --git a/dGame/dMission/Mission.h b/dGame/dMission/Mission.h index b8892f3d..f9902a06 100644 --- a/dGame/dMission/Mission.h +++ b/dGame/dMission/Mission.h @@ -13,6 +13,10 @@ #include "MissionState.h" #include "MissionLockState.h" +namespace tinyxml2 { + class XMLElement; +}; + class MissionComponent; /** @@ -223,7 +227,7 @@ public: /** * @brief Returns the unique mission order ID - * + * * @return The unique order ID */ uint32_t GetUniqueMissionOrderID() { return m_UniqueMissionID; }; diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.cpp b/dGame/dPropertyBehaviors/ControlBehaviors.cpp index d5b71a3a..278b6929 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviors.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviors.cpp @@ -7,6 +7,7 @@ #include "ModelComponent.h" #include "../../dWorldServer/ObjectIDManager.h" #include "dLogger.h" +#include "User.h" uint32_t GetBehaviorIDFromArgument(AMFArrayValue* arguments, const std::string& key = "BehaviorID") { auto* behaviorIDValue = arguments->FindValue<AMFStringValue>(key); diff --git a/dGame/dUtilities/BrickDatabase.cpp b/dGame/dUtilities/BrickDatabase.cpp index 6d1e380c..a6c43d52 100644 --- a/dGame/dUtilities/BrickDatabase.cpp +++ b/dGame/dUtilities/BrickDatabase.cpp @@ -4,6 +4,7 @@ #include "BrickDatabase.h" #include "Game.h" #include "AssetManager.h" +#include "tinyxml2.h" std::vector<Brick> BrickDatabase::emptyCache{}; BrickDatabase* BrickDatabase::m_Address = nullptr; diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 9a63f83c..2192fafb 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -50,6 +50,9 @@ #include "Item.h" #include "PropertyManagementComponent.h" #include "PacketUtils.h" +#include "Loot.h" +#include "EntityInfo.h" +#include "LUTriggers.h" #include "Player.h" #include "PhantomPhysicsComponent.h" #include "ProximityMonitorComponent.h" @@ -66,6 +69,9 @@ #include "AssetManager.h" #include "BinaryPathFinder.h" #include "dConfig.h" +#include "AMFFormat.h" +#include "MovingPlatformComponent.h" +#include "dMessageIdentifiers.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { std::string chatCommand; diff --git a/dGame/dUtilities/VanityUtilities.cpp b/dGame/dUtilities/VanityUtilities.cpp index 3a1259a2..74fd0f67 100644 --- a/dGame/dUtilities/VanityUtilities.cpp +++ b/dGame/dUtilities/VanityUtilities.cpp @@ -14,6 +14,7 @@ #include "Game.h" #include "dLogger.h" #include "BinaryPathFinder.h" +#include "EntityInfo.h" #include <fstream> diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index 39e835d2..61267971 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -31,7 +31,7 @@ #include "dConfig.h" #include "CharacterComponent.h" #include "Database.h" - +#include "dMessageIdentifiers.h" void ClientPackets::HandleChatMessage(const SystemAddress& sysAddr, Packet* packet) { diff --git a/dScripts/02_server/Enemy/AM/AmDarklingDragon.cpp b/dScripts/02_server/Enemy/AM/AmDarklingDragon.cpp index 9e0570ef..28ba0044 100644 --- a/dScripts/02_server/Enemy/AM/AmDarklingDragon.cpp +++ b/dScripts/02_server/Enemy/AM/AmDarklingDragon.cpp @@ -5,6 +5,8 @@ #include "GameMessages.h" #include "SkillComponent.h" #include "BaseCombatAIComponent.h" +#include "EntityInfo.h" +#include "eAninmationFlags.h" void AmDarklingDragon::OnStartup(Entity* self) { self->SetVar<int32_t>(u"weakspot", 0); diff --git a/dScripts/02_server/Enemy/FV/FvMaelstromDragon.cpp b/dScripts/02_server/Enemy/FV/FvMaelstromDragon.cpp index ec513694..e78f537f 100644 --- a/dScripts/02_server/Enemy/FV/FvMaelstromDragon.cpp +++ b/dScripts/02_server/Enemy/FV/FvMaelstromDragon.cpp @@ -3,6 +3,8 @@ #include "SkillComponent.h" #include "BaseCombatAIComponent.h" #include "DestroyableComponent.h" +#include "eAninmationFlags.h" +#include "EntityInfo.h" void FvMaelstromDragon::OnStartup(Entity* self) { self->SetVar<int32_t>(u"weakspot", 0); diff --git a/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp b/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp index 96419c08..d3c59448 100644 --- a/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp +++ b/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp @@ -3,7 +3,9 @@ #include "DestroyableComponent.h" #include "GameMessages.h" #include "EntityManager.h" +#include "EntityInfo.h" #include "SkillComponent.h" +#include "eAninmationFlags.h" void BaseEnemyApe::OnStartup(Entity* self) { self->SetVar<uint32_t>(u"timesStunned", 2); diff --git a/dScripts/02_server/Enemy/General/BaseEnemyMech.cpp b/dScripts/02_server/Enemy/General/BaseEnemyMech.cpp index 8017be2c..8c200566 100644 --- a/dScripts/02_server/Enemy/General/BaseEnemyMech.cpp +++ b/dScripts/02_server/Enemy/General/BaseEnemyMech.cpp @@ -3,6 +3,7 @@ #include "ControllablePhysicsComponent.h" #include "EntityManager.h" #include "dpWorld.h" +#include "EntityInfo.h" #include "GeneralUtils.h" #include "DestroyableComponent.h" diff --git a/dScripts/02_server/Enemy/General/TreasureChestDragonServer.cpp b/dScripts/02_server/Enemy/General/TreasureChestDragonServer.cpp index 15f0709c..19788677 100644 --- a/dScripts/02_server/Enemy/General/TreasureChestDragonServer.cpp +++ b/dScripts/02_server/Enemy/General/TreasureChestDragonServer.cpp @@ -2,6 +2,7 @@ #include "ScriptedActivityComponent.h" #include "TeamManager.h" #include "EntityManager.h" +#include "Loot.h" void TreasureChestDragonServer::OnStartup(Entity* self) { diff --git a/dScripts/02_server/Equipment/BootyDigServer.cpp b/dScripts/02_server/Equipment/BootyDigServer.cpp index d38791d8..73d96b1f 100644 --- a/dScripts/02_server/Equipment/BootyDigServer.cpp +++ b/dScripts/02_server/Equipment/BootyDigServer.cpp @@ -3,6 +3,7 @@ #include "RenderComponent.h" #include "MissionComponent.h" #include "MissionTaskType.h" +#include "Loot.h" void BootyDigServer::OnStartup(Entity* self) { auto* zoneControlObject = EntityManager::Instance()->GetZoneControlEntity(); diff --git a/dScripts/02_server/Map/AG/NpcPirateServer.cpp b/dScripts/02_server/Map/AG/NpcPirateServer.cpp index 47571fa6..154fe2bc 100644 --- a/dScripts/02_server/Map/AG/NpcPirateServer.cpp +++ b/dScripts/02_server/Map/AG/NpcPirateServer.cpp @@ -1,4 +1,5 @@ #include "NpcPirateServer.h" +#include "MissionState.h" #include "InventoryComponent.h" void NpcPirateServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { diff --git a/dScripts/02_server/Map/AG/NpcWispServer.cpp b/dScripts/02_server/Map/AG/NpcWispServer.cpp index cd4a4d9c..d6eab34c 100644 --- a/dScripts/02_server/Map/AG/NpcWispServer.cpp +++ b/dScripts/02_server/Map/AG/NpcWispServer.cpp @@ -3,6 +3,7 @@ #include "EntityManager.h" #include "Entity.h" #include "GameMessages.h" +#include "MissionState.h" void NpcWispServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { if (missionID != 1849 && missionID != 1883) diff --git a/dScripts/02_server/Map/AG/RemoveRentalGear.cpp b/dScripts/02_server/Map/AG/RemoveRentalGear.cpp index 06d964b9..fbb00c79 100644 --- a/dScripts/02_server/Map/AG/RemoveRentalGear.cpp +++ b/dScripts/02_server/Map/AG/RemoveRentalGear.cpp @@ -1,6 +1,7 @@ #include "RemoveRentalGear.h" #include "InventoryComponent.h" #include "Item.h" +#include "MissionState.h" #include "Character.h" /* diff --git a/dScripts/02_server/Map/AG_Spider_Queen/ZoneAgSpiderQueen.cpp b/dScripts/02_server/Map/AG_Spider_Queen/ZoneAgSpiderQueen.cpp index ea517448..5996548f 100644 --- a/dScripts/02_server/Map/AG_Spider_Queen/ZoneAgSpiderQueen.cpp +++ b/dScripts/02_server/Map/AG_Spider_Queen/ZoneAgSpiderQueen.cpp @@ -3,6 +3,7 @@ #include "EntityManager.h" #include "ZoneAgProperty.h" #include "DestroyableComponent.h" +#include "EntityInfo.h" void ZoneAgSpiderQueen::SetGameVariables(Entity* self) { ZoneAgProperty::SetGameVariables(self); diff --git a/dScripts/02_server/Map/AM/AmBlueX.cpp b/dScripts/02_server/Map/AM/AmBlueX.cpp index 97f80e77..8e32694c 100644 --- a/dScripts/02_server/Map/AM/AmBlueX.cpp +++ b/dScripts/02_server/Map/AM/AmBlueX.cpp @@ -1,6 +1,7 @@ #include "AmBlueX.h" #include "SkillComponent.h" #include "EntityManager.h" +#include "EntityInfo.h" #include "Character.h" void AmBlueX::OnUse(Entity* self, Entity* user) { diff --git a/dScripts/02_server/Map/AM/AmShieldGenerator.cpp b/dScripts/02_server/Map/AM/AmShieldGenerator.cpp index d16acb87..5d1b7d08 100644 --- a/dScripts/02_server/Map/AM/AmShieldGenerator.cpp +++ b/dScripts/02_server/Map/AM/AmShieldGenerator.cpp @@ -2,6 +2,7 @@ #include "EntityManager.h" #include "DestroyableComponent.h" #include "GameMessages.h" +#include "EntityInfo.h" #include "MovementAIComponent.h" #include "BaseCombatAIComponent.h" #include "SkillComponent.h" diff --git a/dScripts/02_server/Map/AM/AmShieldGeneratorQuickbuild.cpp b/dScripts/02_server/Map/AM/AmShieldGeneratorQuickbuild.cpp index 9f27b904..3188db33 100644 --- a/dScripts/02_server/Map/AM/AmShieldGeneratorQuickbuild.cpp +++ b/dScripts/02_server/Map/AM/AmShieldGeneratorQuickbuild.cpp @@ -5,6 +5,7 @@ #include "MovementAIComponent.h" #include "BaseCombatAIComponent.h" #include "SkillComponent.h" +#include "EntityInfo.h" #include "RebuildComponent.h" #include "MissionComponent.h" diff --git a/dScripts/02_server/Map/AM/AmSkullkinDrill.cpp b/dScripts/02_server/Map/AM/AmSkullkinDrill.cpp index 321660e2..9b85cf85 100644 --- a/dScripts/02_server/Map/AM/AmSkullkinDrill.cpp +++ b/dScripts/02_server/Map/AM/AmSkullkinDrill.cpp @@ -4,6 +4,7 @@ #include "DestroyableComponent.h" #include "ProximityMonitorComponent.h" #include "MissionComponent.h" +#include "EntityInfo.h" void AmSkullkinDrill::OnStartup(Entity* self) { self->SetNetworkVar(u"bIsInUse", false); diff --git a/dScripts/02_server/Map/AM/AmSkullkinTower.cpp b/dScripts/02_server/Map/AM/AmSkullkinTower.cpp index 180bbdac..01acdeaf 100644 --- a/dScripts/02_server/Map/AM/AmSkullkinTower.cpp +++ b/dScripts/02_server/Map/AM/AmSkullkinTower.cpp @@ -2,6 +2,7 @@ #include "EntityManager.h" #include "DestroyableComponent.h" #include "MovingPlatformComponent.h" +#include "EntityInfo.h" #include "GameMessages.h" #include "MissionComponent.h" diff --git a/dScripts/02_server/Map/FV/EnemyRoninSpawner.cpp b/dScripts/02_server/Map/FV/EnemyRoninSpawner.cpp index b6cae3bb..cfc58fa0 100644 --- a/dScripts/02_server/Map/FV/EnemyRoninSpawner.cpp +++ b/dScripts/02_server/Map/FV/EnemyRoninSpawner.cpp @@ -1,6 +1,7 @@ #include "EnemyRoninSpawner.h" #include "SkillComponent.h" #include "RenderComponent.h" +#include "EntityInfo.h" #include "EntityManager.h" void EnemyRoninSpawner::OnStartup(Entity* self) { diff --git a/dScripts/02_server/Map/General/BankInteractServer.cpp b/dScripts/02_server/Map/General/BankInteractServer.cpp index db5ebb98..b96187cf 100644 --- a/dScripts/02_server/Map/General/BankInteractServer.cpp +++ b/dScripts/02_server/Map/General/BankInteractServer.cpp @@ -1,5 +1,7 @@ #include "BankInteractServer.h" #include "GameMessages.h" +#include "Entity.h" +#include "AMFFormat.h" void BankInteractServer::OnUse(Entity* self, Entity* user) { AMFArrayValue args; diff --git a/dScripts/02_server/Map/General/GrowingFlower.cpp b/dScripts/02_server/Map/General/GrowingFlower.cpp index 7b495841..61bfbc30 100644 --- a/dScripts/02_server/Map/General/GrowingFlower.cpp +++ b/dScripts/02_server/Map/General/GrowingFlower.cpp @@ -1,5 +1,6 @@ #include "GrowingFlower.h" #include "MissionComponent.h" +#include "Loot.h" void GrowingFlower::OnSkillEventFired(Entity* self, Entity* target, const std::string& message) { if (!self->GetVar<bool>(u"blooming") && (message == "waterspray" || message == "shovelgrow")) { diff --git a/dScripts/02_server/Map/General/PetDigServer.cpp b/dScripts/02_server/Map/General/PetDigServer.cpp index e26b079a..0d62ff04 100644 --- a/dScripts/02_server/Map/General/PetDigServer.cpp +++ b/dScripts/02_server/Map/General/PetDigServer.cpp @@ -4,6 +4,7 @@ #include "EntityManager.h" #include "Character.h" #include "PetComponent.h" +#include "User.h" std::vector<LWOOBJID> PetDigServer::treasures{}; diff --git a/dScripts/02_server/Map/General/PropertyPlatform.cpp b/dScripts/02_server/Map/General/PropertyPlatform.cpp index 89687ac3..902b9646 100644 --- a/dScripts/02_server/Map/General/PropertyPlatform.cpp +++ b/dScripts/02_server/Map/General/PropertyPlatform.cpp @@ -1,6 +1,7 @@ #include "PropertyPlatform.h" #include "RebuildComponent.h" #include "GameMessages.h" +#include "MovingPlatformComponent.h" void PropertyPlatform::OnRebuildComplete(Entity* self, Entity* target) { // auto* movingPlatform = self->GetComponent<MovingPlatformComponent>(); @@ -9,7 +10,7 @@ void PropertyPlatform::OnRebuildComplete(Entity* self, Entity* target) { // movingPlatform->SetNoAutoStart(true); // } GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 0, 0, MovementPlatformState::Stationary); + 0, 0, eMovementPlatformState::Stationary); } void PropertyPlatform::OnUse(Entity* self, Entity* user) { @@ -20,7 +21,7 @@ void PropertyPlatform::OnUse(Entity* self, Entity* user) { // movingPlatform->GotoWaypoint(1); // } GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 1, 1, MovementPlatformState::Moving); + 1, 1, eMovementPlatformState::Moving); self->AddCallbackTimer(movementDelay + effectDelay, [self, this]() { self->SetNetworkVar<float_t>(u"startEffect", dieDelay); diff --git a/dScripts/02_server/Map/General/QbSpawner.cpp b/dScripts/02_server/Map/General/QbSpawner.cpp index edee6148..d5c9d001 100644 --- a/dScripts/02_server/Map/General/QbSpawner.cpp +++ b/dScripts/02_server/Map/General/QbSpawner.cpp @@ -1,5 +1,6 @@ #include "QbSpawner.h" #include "BaseCombatAIComponent.h" +#include "EntityInfo.h" #include "MovementAIComponent.h" void QbSpawner::OnStartup(Entity* self) { @@ -133,4 +134,3 @@ void QbSpawner::AggroTargetObject(Entity* self, Entity* enemy) { } } - diff --git a/dScripts/02_server/Map/General/WishingWellServer.cpp b/dScripts/02_server/Map/General/WishingWellServer.cpp index 8ac9e0b2..fa3e13e0 100644 --- a/dScripts/02_server/Map/General/WishingWellServer.cpp +++ b/dScripts/02_server/Map/General/WishingWellServer.cpp @@ -1,6 +1,8 @@ #include "WishingWellServer.h" #include "ScriptedActivityComponent.h" #include "GameMessages.h" +#include "Loot.h" +#include "EntityManager.h" void WishingWellServer::OnStartup(Entity* self) { } diff --git a/dScripts/02_server/Map/NS/NsConcertChoiceBuildManager.cpp b/dScripts/02_server/Map/NS/NsConcertChoiceBuildManager.cpp index 33436525..a338d9c9 100644 --- a/dScripts/02_server/Map/NS/NsConcertChoiceBuildManager.cpp +++ b/dScripts/02_server/Map/NS/NsConcertChoiceBuildManager.cpp @@ -1,4 +1,5 @@ #include "NsConcertChoiceBuildManager.h" +#include "EntityInfo.h" #include "EntityManager.h" const std::vector<Crate> NsConcertChoiceBuildManager::crates{ diff --git a/dScripts/02_server/Map/NS/NsLegoClubDoor.h b/dScripts/02_server/Map/NS/NsLegoClubDoor.h index 0a7a6ee0..db1dcae4 100644 --- a/dScripts/02_server/Map/NS/NsLegoClubDoor.h +++ b/dScripts/02_server/Map/NS/NsLegoClubDoor.h @@ -2,6 +2,7 @@ #include "CppScripts.h" #include "ChooseYourDestinationNsToNt.h" #include "BaseConsoleTeleportServer.h" +#include "AMFFormat.h" class NsLegoClubDoor : public CppScripts::Script, ChooseYourDestinationNsToNt, BaseConsoleTeleportServer { diff --git a/dScripts/02_server/Map/NS/NsLupTeleport.h b/dScripts/02_server/Map/NS/NsLupTeleport.h index 35edf0bc..28bab016 100644 --- a/dScripts/02_server/Map/NS/NsLupTeleport.h +++ b/dScripts/02_server/Map/NS/NsLupTeleport.h @@ -2,6 +2,7 @@ #include "CppScripts.h" #include "ChooseYourDestinationNsToNt.h" #include "BaseConsoleTeleportServer.h" +#include "AMFFormat.h" class NsLupTeleport : public CppScripts::Script, ChooseYourDestinationNsToNt, BaseConsoleTeleportServer { diff --git a/dScripts/02_server/Map/NT/NtCombatChallengeServer.cpp b/dScripts/02_server/Map/NT/NtCombatChallengeServer.cpp index 2b88ccf8..d27ac1f6 100644 --- a/dScripts/02_server/Map/NT/NtCombatChallengeServer.cpp +++ b/dScripts/02_server/Map/NT/NtCombatChallengeServer.cpp @@ -1,6 +1,7 @@ #include "NtCombatChallengeServer.h" #include "GameMessages.h" #include "EntityManager.h" +#include "EntityInfo.h" #include "InventoryComponent.h" #include "MissionComponent.h" diff --git a/dScripts/02_server/Map/NT/NtVandaServer.cpp b/dScripts/02_server/Map/NT/NtVandaServer.cpp index bfc35203..e5653005 100644 --- a/dScripts/02_server/Map/NT/NtVandaServer.cpp +++ b/dScripts/02_server/Map/NT/NtVandaServer.cpp @@ -1,5 +1,6 @@ #include "NtVandaServer.h" #include "InventoryComponent.h" +#include "MissionState.h" void NtVandaServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { diff --git a/dScripts/02_server/Map/Property/AG_Small/EnemySpiderSpawner.cpp b/dScripts/02_server/Map/Property/AG_Small/EnemySpiderSpawner.cpp index 96302a33..695bd92f 100644 --- a/dScripts/02_server/Map/Property/AG_Small/EnemySpiderSpawner.cpp +++ b/dScripts/02_server/Map/Property/AG_Small/EnemySpiderSpawner.cpp @@ -1,6 +1,7 @@ #include "EnemySpiderSpawner.h" #include "GameMessages.h" #include "EntityManager.h" +#include "EntityInfo.h" #include "DestroyableComponent.h" //---------------------------------------------- diff --git a/dScripts/02_server/Map/Property/PropertyBankInteract.cpp b/dScripts/02_server/Map/Property/PropertyBankInteract.cpp index 788768ca..9e727f39 100644 --- a/dScripts/02_server/Map/Property/PropertyBankInteract.cpp +++ b/dScripts/02_server/Map/Property/PropertyBankInteract.cpp @@ -1,6 +1,7 @@ #include "PropertyBankInteract.h" #include "EntityManager.h" #include "GameMessages.h" +#include "AMFFormat.h" void PropertyBankInteract::OnStartup(Entity* self) { auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); diff --git a/dScripts/02_server/Map/VE/VeEpsilonServer.cpp b/dScripts/02_server/Map/VE/VeEpsilonServer.cpp index cc6ecafe..4a2f1bbf 100644 --- a/dScripts/02_server/Map/VE/VeEpsilonServer.cpp +++ b/dScripts/02_server/Map/VE/VeEpsilonServer.cpp @@ -2,6 +2,8 @@ #include "Character.h" #include "EntityManager.h" #include "GameMessages.h" +#include "MissionState.h" +#include "Entity.h" void VeEpsilonServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { auto* character = target->GetCharacter(); diff --git a/dScripts/02_server/Map/VE/VeMissionConsole.cpp b/dScripts/02_server/Map/VE/VeMissionConsole.cpp index 2a424c4d..534f8c06 100644 --- a/dScripts/02_server/Map/VE/VeMissionConsole.cpp +++ b/dScripts/02_server/Map/VE/VeMissionConsole.cpp @@ -2,6 +2,7 @@ #include "InventoryComponent.h" #include "Character.h" #include "GameMessages.h" +#include "Loot.h" void VeMissionConsole::OnUse(Entity* self, Entity* user) { LootGenerator::Instance().DropActivityLoot(user, self, 12551); diff --git a/dScripts/02_server/Map/njhub/EnemySkeletonSpawner.cpp b/dScripts/02_server/Map/njhub/EnemySkeletonSpawner.cpp index 451fa1d5..0e2e4005 100644 --- a/dScripts/02_server/Map/njhub/EnemySkeletonSpawner.cpp +++ b/dScripts/02_server/Map/njhub/EnemySkeletonSpawner.cpp @@ -2,6 +2,7 @@ #include "SkillComponent.h" #include "RenderComponent.h" #include "EntityManager.h" +#include "EntityInfo.h" void EnemySkeletonSpawner::OnStartup(Entity* self) { self->SetProximityRadius(15, "ronin"); diff --git a/dScripts/02_server/Map/njhub/NjDragonEmblemChestServer.cpp b/dScripts/02_server/Map/njhub/NjDragonEmblemChestServer.cpp index fa4d8556..be9fcbd9 100644 --- a/dScripts/02_server/Map/njhub/NjDragonEmblemChestServer.cpp +++ b/dScripts/02_server/Map/njhub/NjDragonEmblemChestServer.cpp @@ -1,5 +1,8 @@ #include "NjDragonEmblemChestServer.h" #include "Character.h" +#include "EntityInfo.h" +#include "Loot.h" +#include "Entity.h" #include "DestroyableComponent.h" void NjDragonEmblemChestServer::OnUse(Entity* self, Entity* user) { diff --git a/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.cpp b/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.cpp index 19f5f42a..69838dc8 100644 --- a/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.cpp +++ b/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.cpp @@ -1,6 +1,7 @@ #include "NjNPCMissionSpinjitzuServer.h" #include "Character.h" #include "EntityManager.h" +#include "MissionState.h" void NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { diff --git a/dScripts/02_server/Map/njhub/RainOfArrows.cpp b/dScripts/02_server/Map/njhub/RainOfArrows.cpp index 141cd3ab..b7c4c074 100644 --- a/dScripts/02_server/Map/njhub/RainOfArrows.cpp +++ b/dScripts/02_server/Map/njhub/RainOfArrows.cpp @@ -1,6 +1,7 @@ #include "RainOfArrows.h" #include "EntityManager.h" #include "SkillComponent.h" +#include "EntityInfo.h" #include "GameMessages.h" void RainOfArrows::OnStartup(Entity* self) { diff --git a/dScripts/02_server/Minigame/General/MinigameTreasureChestServer.cpp b/dScripts/02_server/Minigame/General/MinigameTreasureChestServer.cpp index 66222d59..7df8fc12 100644 --- a/dScripts/02_server/Minigame/General/MinigameTreasureChestServer.cpp +++ b/dScripts/02_server/Minigame/General/MinigameTreasureChestServer.cpp @@ -3,6 +3,7 @@ #include "TeamManager.h" #include "EntityManager.h" #include "dZoneManager.h" +#include "Loot.h" void MinigameTreasureChestServer::OnUse(Entity* self, Entity* user) { auto* sac = self->GetComponent<ScriptedActivityComponent>(); diff --git a/dScripts/02_server/Objects/StinkyFishTarget.cpp b/dScripts/02_server/Objects/StinkyFishTarget.cpp index 19dbce88..21d92fac 100644 --- a/dScripts/02_server/Objects/StinkyFishTarget.cpp +++ b/dScripts/02_server/Objects/StinkyFishTarget.cpp @@ -1,5 +1,6 @@ #include "StinkyFishTarget.h" #include "EntityManager.h" +#include "EntityInfo.h" void StinkyFishTarget::OnStartup(Entity* self) { auto position = self->GetPosition(); diff --git a/dScripts/ActivityManager.cpp b/dScripts/ActivityManager.cpp index 36e85b11..078a7a02 100644 --- a/dScripts/ActivityManager.cpp +++ b/dScripts/ActivityManager.cpp @@ -5,6 +5,7 @@ #include "GameMessages.h" #include <algorithm> #include "dLogger.h" +#include "Loot.h" bool ActivityManager::IsPlayerInActivity(Entity* self, LWOOBJID playerID) { const auto* sac = self->GetComponent<ScriptedActivityComponent>(); diff --git a/dScripts/CppScripts.h b/dScripts/CppScripts.h index e4a6d655..eb9b7a04 100644 --- a/dScripts/CppScripts.h +++ b/dScripts/CppScripts.h @@ -1,12 +1,13 @@ #pragma once -#include "dCommonVars.h" -#include "MissionState.h" + +#include <cstdint> #include <string> #include <vector> class User; class Entity; class NiPoint3; +enum class MissionState : int32_t; namespace CppScripts { /** diff --git a/dScripts/NPCAddRemoveItem.cpp b/dScripts/NPCAddRemoveItem.cpp index ce47b12a..1985a02b 100644 --- a/dScripts/NPCAddRemoveItem.cpp +++ b/dScripts/NPCAddRemoveItem.cpp @@ -1,5 +1,6 @@ #include "NPCAddRemoveItem.h" #include "InventoryComponent.h" +#include "MissionState.h" void NPCAddRemoveItem::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { auto* inventory = target->GetComponent<InventoryComponent>(); diff --git a/dScripts/ScriptedPowerupSpawner.cpp b/dScripts/ScriptedPowerupSpawner.cpp index 730e65ba..3c1d1cca 100644 --- a/dScripts/ScriptedPowerupSpawner.cpp +++ b/dScripts/ScriptedPowerupSpawner.cpp @@ -1,6 +1,7 @@ #include "ScriptedPowerupSpawner.h" #include "RenderComponent.h" #include "EntityManager.h" +#include "Loot.h" void ScriptedPowerupSpawner::OnTemplateStartup(Entity* self) { self->SetVar<uint32_t>(u"currentCycle", 1); diff --git a/dScripts/SpawnPetBaseServer.cpp b/dScripts/SpawnPetBaseServer.cpp index 1d73a5b8..d3c87288 100644 --- a/dScripts/SpawnPetBaseServer.cpp +++ b/dScripts/SpawnPetBaseServer.cpp @@ -2,6 +2,7 @@ #include "GameMessages.h" #include "EntityManager.h" #include "PetComponent.h" +#include "EntityInfo.h" void SpawnPetBaseServer::OnStartup(Entity* self) { SetVariables(self); diff --git a/dScripts/ai/AG/AgImagSmashable.cpp b/dScripts/ai/AG/AgImagSmashable.cpp index 593294e5..195f7b9a 100644 --- a/dScripts/ai/AG/AgImagSmashable.cpp +++ b/dScripts/ai/AG/AgImagSmashable.cpp @@ -2,6 +2,7 @@ #include "EntityManager.h" #include "GeneralUtils.h" #include "GameMessages.h" +#include "EntityInfo.h" #include "DestroyableComponent.h" void AgImagSmashable::OnDie(Entity* self, Entity* killer) { diff --git a/dScripts/ai/AG/AgPicnicBlanket.cpp b/dScripts/ai/AG/AgPicnicBlanket.cpp index 30fb2950..d2a54d57 100644 --- a/dScripts/ai/AG/AgPicnicBlanket.cpp +++ b/dScripts/ai/AG/AgPicnicBlanket.cpp @@ -1,5 +1,7 @@ #include "AgPicnicBlanket.h" +#include "Loot.h" #include "GameMessages.h" +#include "Entity.h" void AgPicnicBlanket::OnUse(Entity* self, Entity* user) { GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); diff --git a/dScripts/ai/AG/AgQbElevator.cpp b/dScripts/ai/AG/AgQbElevator.cpp index ccb4d3b1..f1ac7bb5 100644 --- a/dScripts/ai/AG/AgQbElevator.cpp +++ b/dScripts/ai/AG/AgQbElevator.cpp @@ -15,7 +15,7 @@ void AgQbElevator::OnRebuildComplete(Entity* self, Entity* target) { if (delayTime < 1) delayTime = 1; GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 0, 0, MovementPlatformState::Stationary); + 0, 0, eMovementPlatformState::Stationary); //add a timer that will kill the QB if no players get on in the killTime self->AddTimer("startKillTimer", killTime); @@ -33,7 +33,7 @@ void AgQbElevator::OnProximityUpdate(Entity* self, Entity* entering, std::string self->CancelTimer("StartElevator"); GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 1, 1, MovementPlatformState::Moving); + 1, 1, eMovementPlatformState::Moving); } else if (!self->GetBoolean(u"StartTimer")) { self->SetBoolean(u"StartTimer", true); self->AddTimer("StartElevator", startTime); @@ -45,7 +45,7 @@ void AgQbElevator::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "StartElevator") { GameMessages::SendPlatformResync(self, UNASSIGNED_SYSTEM_ADDRESS, true, 0, - 1, 1, MovementPlatformState::Moving); + 1, 1, eMovementPlatformState::Moving); } else if (timerName == "startKillTimer") { killTimerStartup(self); } else if (timerName == "KillTimer") { diff --git a/dScripts/ai/AG/AgSpaceStuff.cpp b/dScripts/ai/AG/AgSpaceStuff.cpp index 80a87e70..30929ebf 100644 --- a/dScripts/ai/AG/AgSpaceStuff.cpp +++ b/dScripts/ai/AG/AgSpaceStuff.cpp @@ -1,4 +1,5 @@ #include "AgSpaceStuff.h" +#include "EntityInfo.h" #include "GeneralUtils.h" #include "GameMessages.h" #include "EntityManager.h" diff --git a/dScripts/ai/FV/FvPandaSpawnerServer.cpp b/dScripts/ai/FV/FvPandaSpawnerServer.cpp index e1f3fb96..d7dcabcd 100644 --- a/dScripts/ai/FV/FvPandaSpawnerServer.cpp +++ b/dScripts/ai/FV/FvPandaSpawnerServer.cpp @@ -2,6 +2,7 @@ #include "Character.h" #include "EntityManager.h" #include "GameMessages.h" +#include "EntityInfo.h" #include "ScriptedActivityComponent.h" void FvPandaSpawnerServer::OnCollisionPhantom(Entity* self, Entity* target) { diff --git a/dScripts/ai/GF/GfBanana.cpp b/dScripts/ai/GF/GfBanana.cpp index 3a71eded..95a831cd 100644 --- a/dScripts/ai/GF/GfBanana.cpp +++ b/dScripts/ai/GF/GfBanana.cpp @@ -2,6 +2,7 @@ #include "Entity.h" #include "DestroyableComponent.h" +#include "EntityInfo.h" #include "EntityManager.h" void GfBanana::SpawnBanana(Entity* self) { diff --git a/dScripts/ai/GF/PetDigBuild.cpp b/dScripts/ai/GF/PetDigBuild.cpp index ae159575..32e5b2e3 100644 --- a/dScripts/ai/GF/PetDigBuild.cpp +++ b/dScripts/ai/GF/PetDigBuild.cpp @@ -1,5 +1,6 @@ #include "PetDigBuild.h" #include "EntityManager.h" +#include "EntityInfo.h" #include "MissionComponent.h" void PetDigBuild::OnRebuildComplete(Entity* self, Entity* target) { diff --git a/dScripts/ai/GF/PirateRep.cpp b/dScripts/ai/GF/PirateRep.cpp index eb4cf510..81d69672 100644 --- a/dScripts/ai/GF/PirateRep.cpp +++ b/dScripts/ai/GF/PirateRep.cpp @@ -1,5 +1,7 @@ #include "PirateRep.h" #include "Character.h" +#include "MissionState.h" +#include "Entity.h" void PirateRep::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { if (missionID == m_PirateRepMissionID && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp index 47bca374..db914c7f 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp @@ -11,6 +11,7 @@ #include "MovementAIComponent.h" #include "../dWorldServer/ObjectIDManager.h" #include "MissionComponent.h" +#include "Loot.h" #include "InventoryComponent.h" void SGCannon::OnStartup(Entity* self) { diff --git a/dScripts/ai/NS/WH/RockHydrantSmashable.cpp b/dScripts/ai/NS/WH/RockHydrantSmashable.cpp index d76eca8d..b3a01567 100644 --- a/dScripts/ai/NS/WH/RockHydrantSmashable.cpp +++ b/dScripts/ai/NS/WH/RockHydrantSmashable.cpp @@ -1,5 +1,6 @@ #include "RockHydrantSmashable.h" #include "EntityManager.h" +#include "EntityInfo.h" #include "GeneralUtils.h" void RockHydrantSmashable::OnDie(Entity* self, Entity* killer) { diff --git a/dScripts/ai/PETS/HydrantSmashable.cpp b/dScripts/ai/PETS/HydrantSmashable.cpp index 20baa58b..1ff082ea 100644 --- a/dScripts/ai/PETS/HydrantSmashable.cpp +++ b/dScripts/ai/PETS/HydrantSmashable.cpp @@ -1,5 +1,6 @@ #include "HydrantSmashable.h" #include "EntityManager.h" +#include "EntityInfo.h" #include "GeneralUtils.h" void HydrantSmashable::OnDie(Entity* self, Entity* killer) { diff --git a/dScripts/ai/PROPERTY/AgPropguards.cpp b/dScripts/ai/PROPERTY/AgPropguards.cpp index 674c4bdd..2bcfcf94 100644 --- a/dScripts/ai/PROPERTY/AgPropguards.cpp +++ b/dScripts/ai/PROPERTY/AgPropguards.cpp @@ -3,6 +3,7 @@ #include "GameMessages.h" #include "EntityManager.h" #include "dZoneManager.h" +#include "MissionState.h" void AgPropguards::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { auto* character = target->GetCharacter(); diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 73157c09..b655bef3 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -42,6 +42,9 @@ #include "CharacterComponent.h" #include "EntityManager.h" +#include "EntityInfo.h" +#include "User.h" +#include "Loot.h" #include "Entity.h" #include "Character.h" #include "ChatPackets.h" @@ -58,6 +61,8 @@ #include "AssetManager.h" #include "LevelProgressionComponent.h" #include "eBlueprintSaveResponseType.h" +#include "AMFFormat.h" +#include "NiPoint3.h" #include "ZCompression.h" diff --git a/dZoneManager/LUTriggers.h b/dZoneManager/LUTriggers.h new file mode 100644 index 00000000..1869b4c3 --- /dev/null +++ b/dZoneManager/LUTriggers.h @@ -0,0 +1,30 @@ +#ifndef __LUTRIGGERS__H__ +#define __LUTRIGGERS__H__ + +#include <string> +#include <vector> + +class Command; +class Event; + +namespace LUTriggers { + struct Command { + std::string id; + std::string target; + std::string targetName; + std::string args; + }; + + struct Event { + std::string eventID; + std::vector<Command*> commands; + }; + + struct Trigger { + uint32_t id; + bool enabled; + std::vector<Event*> events; + }; +}; + +#endif //!__LUTRIGGERS__H__ diff --git a/dZoneManager/Spawner.h b/dZoneManager/Spawner.h index 908bb3a3..a42c8a65 100644 --- a/dZoneManager/Spawner.h +++ b/dZoneManager/Spawner.h @@ -9,6 +9,7 @@ #include <string> #include <functional> #include "LDFFormat.h" +#include "EntityInfo.h" struct SpawnerNode { NiPoint3 position = NiPoint3::ZERO; diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index ec73237e..79d940af 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -6,6 +6,7 @@ #include "dLogger.h" #include "GeneralUtils.h" #include "BinaryIO.h" +#include "LUTriggers.h" #include "AssetManager.h" #include "CDClientManager.h" diff --git a/dZoneManager/Zone.h b/dZoneManager/Zone.h index 978438aa..9c5322a1 100644 --- a/dZoneManager/Zone.h +++ b/dZoneManager/Zone.h @@ -1,35 +1,18 @@ #pragma once + #include "dZMCommon.h" #include "LDFFormat.h" -#include "../thirdparty/tinyxml2/tinyxml2.h" +#include "tinyxml2.h" #include <string> #include <vector> #include <map> -class Level; - -class LUTriggers { -public: - - struct Command { - std::string id; - std::string target; - std::string targetName; - std::string args; - }; - - struct Event { - std::string eventID; - std::vector<Command*> commands; - }; - - struct Trigger { - uint32_t id; - bool enabled; - std::vector<Event*> events; - }; +namespace LUTriggers { + struct Trigger; }; +class Level; + struct SceneRef { std::string filename; uint32_t id; @@ -110,11 +93,11 @@ enum class PropertyPathType : int32_t { GenetatedRectangle = 2 }; -enum class PropertyType : int32_t{ +enum class PropertyType : int32_t { Premiere = 0, - Prize = 1, - LUP = 2, - Headspace = 3 + Prize = 1, + LUP = 2, + Headspace = 3 }; enum class PropertyRentalTimeUnit : int32_t { @@ -222,7 +205,7 @@ public: uint32_t GetWorldID() const { return m_WorldID; } [[nodiscard]] std::string GetZoneName() const { return m_ZoneName; } - std::string GetZoneRawPath() const { return m_ZoneRawPath;} + std::string GetZoneRawPath() const { return m_ZoneRawPath; } std::string GetZonePath() const { return m_ZonePath; } const NiPoint3& GetSpawnPos() const { return m_Spawnpoint; } @@ -254,7 +237,7 @@ private: uint32_t m_PathDataLength; uint32_t m_PathChunkVersion; - std::vector<Path> m_Paths; + std::vector<Path> m_Paths; std::map<LWOSCENEID, uint32_t, mapCompareLwoSceneIDs> m_MapRevisions; //rhs is the revision! diff --git a/tests/dGameTests/GameDependencies.h b/tests/dGameTests/GameDependencies.h index ee52dec6..81875ab6 100644 --- a/tests/dGameTests/GameDependencies.h +++ b/tests/dGameTests/GameDependencies.h @@ -4,6 +4,7 @@ #include "Game.h" #include "dLogger.h" #include "dServer.h" +#include "EntityInfo.h" #include "EntityManager.h" #include <gtest/gtest.h> From 1ac898ba000b7a6e075163a64c1f94c8d3682a97 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 6 Jan 2023 21:21:40 -0800 Subject: [PATCH 224/322] Remove GameConfig (#874) * Remove GameConfig * Fully remove GmeConfig * Update worldconfig.ini Co-authored-by: Aaron Kimbrell <aronwk.aaron@gmail.com> --- dCommon/dConfig.h | 1 - dGame/dGameMessages/GameMessages.cpp | 3 +- dGame/dUtilities/CMakeLists.txt | 1 - dGame/dUtilities/GameConfig.cpp | 50 ------------------------ dGame/dUtilities/GameConfig.h | 38 ------------------ dGame/dUtilities/SlashCommandHandler.cpp | 20 ---------- docs/Commands.md | 2 - resources/worldconfig.ini | 3 ++ 8 files changed, 4 insertions(+), 114 deletions(-) delete mode 100644 dGame/dUtilities/GameConfig.cpp delete mode 100644 dGame/dUtilities/GameConfig.h diff --git a/dCommon/dConfig.h b/dCommon/dConfig.h index a6dd5df7..562c1ce9 100644 --- a/dCommon/dConfig.h +++ b/dCommon/dConfig.h @@ -24,7 +24,6 @@ public: * Reloads the config file to reset values */ void ReloadConfig(); - private: void ProcessLine(const std::string& line); diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 24f0816d..634e6a1e 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -25,7 +25,6 @@ #include "dConfig.h" #include "TeamManager.h" #include "ChatPackets.h" -#include "GameConfig.h" #include "RocketLaunchLupComponent.h" #include "eUnequippableActiveType.h" #include "eMovementPlatformState.h" @@ -1005,7 +1004,7 @@ void GameMessages::SendSetNetworkScriptVar(Entity* entity, const SystemAddress& } void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, LOT item, int currency, NiPoint3 spawnPos, int count) { - if (GameConfig::GetValue<int32_t>("no_drops") == 1) { + if (Game::config->GetValue("disable_drops") == "1") { return; } diff --git a/dGame/dUtilities/CMakeLists.txt b/dGame/dUtilities/CMakeLists.txt index 2c453a2e..55ca5797 100644 --- a/dGame/dUtilities/CMakeLists.txt +++ b/dGame/dUtilities/CMakeLists.txt @@ -1,5 +1,4 @@ set(DGAME_DUTILITIES_SOURCES "BrickDatabase.cpp" - "GameConfig.cpp" "GUID.cpp" "Loot.cpp" "Mail.cpp" diff --git a/dGame/dUtilities/GameConfig.cpp b/dGame/dUtilities/GameConfig.cpp deleted file mode 100644 index ad201e6f..00000000 --- a/dGame/dUtilities/GameConfig.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include "GameConfig.h" -#include <sstream> - -std::map<std::string, std::string> GameConfig::m_Config{}; -std::string GameConfig::m_EmptyString{}; - -void GameConfig::Load(const std::string& filepath) { - m_EmptyString = ""; - std::ifstream in(filepath); - if (!in.good()) return; - - std::string line; - while (std::getline(in, line)) { - if (line.length() > 0) { - if (line[0] != '#') ProcessLine(line); - } - } -} - -const std::string& GameConfig::GetValue(const std::string& key) { - const auto& it = m_Config.find(key); - - if (it != m_Config.end()) { - return it->second; - } - - return m_EmptyString; -} - -void GameConfig::SetValue(const std::string& key, const std::string& value) { - m_Config.insert_or_assign(key, value); -} - -void GameConfig::ProcessLine(const std::string& line) { - std::stringstream ss(line); - std::string segment; - std::vector<std::string> seglist; - - while (std::getline(ss, segment, '=')) { - seglist.push_back(segment); - } - - if (seglist.size() != 2) return; - - //Make sure that on Linux, we remove special characters: - if (!seglist[1].empty() && seglist[1][seglist[1].size() - 1] == '\r') - seglist[1].erase(seglist[1].size() - 1); - - m_Config.insert_or_assign(seglist[0], seglist[1]); -} diff --git a/dGame/dUtilities/GameConfig.h b/dGame/dUtilities/GameConfig.h deleted file mode 100644 index 55089f89..00000000 --- a/dGame/dUtilities/GameConfig.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once -#include <fstream> -#include <string> -#include <vector> -#include <map> - -#include "GeneralUtils.h" - -class GameConfig { -public: - static void Load(const std::string& filepath); - - static const std::string& GetValue(const std::string& key); - - static void SetValue(const std::string& key, const std::string& value); - - template <typename T> - static T GetValue(const std::string& key) { - T value; - - if (GeneralUtils::TryParse(GetValue(key), value)) { - return value; - } - - return T(); - } - - template <typename T> - static void SetValue(const std::string& key, const T& value) { - SetValue(key, std::to_string(value)); - } - -private: - static void ProcessLine(const std::string& line); - - static std::map<std::string, std::string> m_Config; - static std::string m_EmptyString; -}; diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 2192fafb..9ee4c1e6 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -63,7 +63,6 @@ #include "BuffComponent.h" #include "SkillComponent.h" #include "VanityUtilities.h" -#include "GameConfig.h" #include "ScriptedActivityComponent.h" #include "LevelProgressionComponent.h" #include "AssetManager.h" @@ -1701,25 +1700,6 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "config-set" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 2) { - GameConfig::SetValue(args[0], args[1]); - - ChatPackets::SendSystemMessage( - sysAddr, u"Set config value: " + GeneralUtils::UTF8ToUTF16(args[0]) + u" to " + GeneralUtils::UTF8ToUTF16(args[1]) - ); - } - - if (chatCommand == "config-get" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { - const auto& value = GameConfig::GetValue(args[0]); - - std::u16string u16key = GeneralUtils::UTF8ToUTF16(args[0]); - if (value.empty()) { - ChatPackets::SendSystemMessage(sysAddr, u"No value found for " + u16key); - } else { - ChatPackets::SendSystemMessage(sysAddr, u"Value for " + u16key + u": " + GeneralUtils::UTF8ToUTF16(value)); - } - } - if (chatCommand == "metrics" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { for (const auto variable : Metrics::GetAllMetrics()) { auto* metric = Metrics::GetMetric(variable); diff --git a/docs/Commands.md b/docs/Commands.md index 060c2ba0..7c4f494f 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -36,8 +36,6 @@ |Command|Usage|Description|Admin Level Requirement| |--- |--- |--- |--- | |announce|`/announce`|Sends a announcement. `/setanntitle` and `/setannmsg` must be called first to configure the announcement.|8| -|config-set|`/config-set <key> <value>`|Set configuration item.|8| -|config-get|`/config-get <key>`|Get current value of a configuration item.|8| |kill|`/kill <username>`|Smashes the character whom the given user is playing.|8| |metrics|`/metrics`|Prints some information about the server's performance.|8| |setannmsg|`/setannmsg <title>`|Sets the message of an announcement.|8| diff --git a/resources/worldconfig.ini b/resources/worldconfig.ini index ee6b6651..0c24c447 100644 --- a/resources/worldconfig.ini +++ b/resources/worldconfig.ini @@ -43,3 +43,6 @@ pets_take_imagination=1 # If you would like to increase the maximum number of best friends a player can have on the server # Change the value below to what you would like this to be (5 is live accurate) max_number_of_best_friends=5 + +# Disables loot drops +disable_drops=0 From 80f8dd800374e6cfd1597c17a8d493ca2b9cfa61 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 6 Jan 2023 23:59:19 -0600 Subject: [PATCH 225/322] Imminuty updates (#925) * WIP Immunities * Immunity getters * remove redundent variable replace it use with it's equivalent * remove unused lookups, fix typos * fix tests * added imunity test * address feedback * more immunity tests * explicit this --- dCommon/dEnums/dCommonVars.h | 2 +- dCommon/dEnums/dMessageIdentifiers.h | 2 + dGame/dBehaviors/ImmunityBehavior.cpp | 94 +++++-- dGame/dBehaviors/ImmunityBehavior.h | 23 +- .../ControllablePhysicsComponent.cpp | 58 ++++- .../ControllablePhysicsComponent.h | 35 +++ dGame/dComponents/DestroyableComponent.cpp | 77 +++++- dGame/dComponents/DestroyableComponent.h | 51 +++- dGame/dComponents/InventoryComponent.cpp | 2 +- dGame/dComponents/PossessorComponent.cpp | 2 +- dGame/dComponents/RailActivatorComponent.cpp | 4 +- dGame/dGameMessages/GameMessages.cpp | 67 ++++- dGame/dGameMessages/GameMessages.h | 31 ++- .../02_server/Enemy/General/BaseEnemyApe.cpp | 2 +- dScripts/02_server/Map/AM/AmSkullkinDrill.cpp | 6 +- .../02_server/Map/GF/GfCaptainsCannon.cpp | 4 +- dScripts/02_server/Map/GF/MastTeleport.cpp | 4 +- .../02_server/Map/NT/NtAssemblyTubeServer.cpp | 4 +- .../02_server/Map/NT/NtParadoxPanelServer.cpp | 4 +- .../02_server/Map/NT/NtParadoxTeleServer.cpp | 4 +- .../Map/NT/NtVentureCannonServer.cpp | 4 +- dScripts/BaseConsoleTeleportServer.cpp | 10 +- .../EquipmentScripts/PersonalFortress.cpp | 49 ++-- .../ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp | 2 +- .../DestroyableComponentTests.cpp | 239 +++++++++++++++++- 25 files changed, 681 insertions(+), 99 deletions(-) diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index 1fd5d071..9bf824e0 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -366,7 +366,7 @@ enum eControlSceme { SCHEME_WEAR_A_ROBOT //== freecam? }; -enum eStunState { +enum class eStateChangeType : uint32_t { PUSH, POP }; diff --git a/dCommon/dEnums/dMessageIdentifiers.h b/dCommon/dEnums/dMessageIdentifiers.h index 129585a0..ed4167c8 100644 --- a/dCommon/dEnums/dMessageIdentifiers.h +++ b/dCommon/dEnums/dMessageIdentifiers.h @@ -293,6 +293,7 @@ enum GAME_MSG : unsigned short { GAME_MSG_POP_EQUIPPED_ITEMS_STATE = 192, GAME_MSG_SET_GM_LEVEL = 193, GAME_MSG_SET_STUNNED = 198, + GAME_MSG_SET_STUN_IMMUNITY = 200, GAME_MSG_KNOCKBACK = 202, GAME_MSG_REBUILD_CANCEL = 209, GAME_MSG_ENABLE_REBUILD = 213, @@ -512,6 +513,7 @@ enum GAME_MSG : unsigned short { GAME_MSG_UPDATE_CHAT_MODE = 1395, GAME_MSG_VEHICLE_NOTIFY_FINISHED_RACE = 1396, GAME_MSG_SET_CONSUMABLE_ITEM = 1409, + GAME_MSG_SET_STATUS_IMMUNITY = 1435, GAME_MSG_SET_PET_NAME_MODERATED = 1448, GAME_MSG_MODIFY_LEGO_SCORE = 1459, GAME_MSG_RESTORE_TO_POST_LOAD_STATS = 1468, diff --git a/dGame/dBehaviors/ImmunityBehavior.cpp b/dGame/dBehaviors/ImmunityBehavior.cpp index 69c652f9..f4a41c52 100644 --- a/dGame/dBehaviors/ImmunityBehavior.cpp +++ b/dGame/dBehaviors/ImmunityBehavior.cpp @@ -6,28 +6,47 @@ #include "Game.h" #include "dLogger.h" #include "DestroyableComponent.h" +#include "ControllablePhysicsComponent.h" void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { auto* target = EntityManager::Instance()->GetEntity(branch.target); - if (target == nullptr) { + if (!target) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); - return; } - auto* destroyable = static_cast<DestroyableComponent*>(target->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - - if (destroyable == nullptr) { - return; + auto* destroyableComponent = target->GetComponent<DestroyableComponent>(); + if (destroyableComponent) { + destroyableComponent->SetStatusImmunity( + eStateChangeType::PUSH, + this->m_ImmuneToBasicAttack, + this->m_ImmuneToDamageOverTime, + this->m_ImmuneToKnockback, + this->m_ImmuneToInterrupt, + this->m_ImmuneToSpeed, + this->m_ImmuneToImaginationGain, + this->m_ImmuneToImaginationLoss, + this->m_ImmuneToQuickbuildInterrupt, + this->m_ImmuneToPullToPoint + ); } - if (!this->m_immuneBasicAttack) { - return; + auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>(); + if (controllablePhysicsComponent) { + controllablePhysicsComponent->SetStunImmunity( + eStateChangeType::PUSH, + context->caster, + this->m_ImmuneToStunAttack, + this->m_ImmuneToStunEquip, + this->m_ImmuneToStunInteract, + this->m_ImmuneToStunJump, + this->m_ImmuneToStunMove, + this->m_ImmuneToStunTurn, + this->m_ImmuneToStunUseItem + ); } - destroyable->PushImmunity(); - context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } @@ -38,21 +57,60 @@ void ImmunityBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bi void ImmunityBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) { auto* target = EntityManager::Instance()->GetEntity(second); - if (target == nullptr) { + if (!target) { Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", second); - return; } - auto* destroyable = static_cast<DestroyableComponent*>(target->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - - if (destroyable == nullptr) { - return; + auto* destroyableComponent = target->GetComponent<DestroyableComponent>(); + if (destroyableComponent) { + destroyableComponent->SetStatusImmunity( + eStateChangeType::POP, + this->m_ImmuneToBasicAttack, + this->m_ImmuneToDamageOverTime, + this->m_ImmuneToKnockback, + this->m_ImmuneToInterrupt, + this->m_ImmuneToSpeed, + this->m_ImmuneToImaginationGain, + this->m_ImmuneToImaginationLoss, + this->m_ImmuneToQuickbuildInterrupt, + this->m_ImmuneToPullToPoint + ); + } + + auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>(); + if (controllablePhysicsComponent) { + controllablePhysicsComponent->SetStunImmunity( + eStateChangeType::POP, + context->caster, + this->m_ImmuneToStunAttack, + this->m_ImmuneToStunEquip, + this->m_ImmuneToStunInteract, + this->m_ImmuneToStunJump, + this->m_ImmuneToStunMove, + this->m_ImmuneToStunTurn, + this->m_ImmuneToStunUseItem + ); } - destroyable->PopImmunity(); } void ImmunityBehavior::Load() { - this->m_immuneBasicAttack = GetBoolean("immune_basic_attack"); + //Stun + this->m_ImmuneToStunAttack = GetBoolean("immune_stun_attack", false); + this->m_ImmuneToStunEquip = GetBoolean("immune_stun_equip", false); + this->m_ImmuneToStunInteract = GetBoolean("immune_stun_interact", false); + this->m_ImmuneToStunMove = GetBoolean("immune_stun_move", false); + this->m_ImmuneToStunTurn = GetBoolean("immune_stun_rotate", false); + + // Status + this->m_ImmuneToBasicAttack = GetBoolean("immune_basic_attack", false); + this->m_ImmuneToDamageOverTime = GetBoolean("immune_damage_over_time", false); + this->m_ImmuneToKnockback = GetBoolean("immune_knockback", false); + this->m_ImmuneToInterrupt = GetBoolean("immune_interrupt", false); + this->m_ImmuneToSpeed = GetBoolean("immune_speed", false); + this->m_ImmuneToImaginationGain = GetBoolean("immune_imagination_gain", false); + this->m_ImmuneToImaginationLoss = GetBoolean("immune_imagination_loss", false); + this->m_ImmuneToQuickbuildInterrupt = GetBoolean("immune_quickbuild_interrupts", false); + this->m_ImmuneToPullToPoint = GetBoolean("immune_pulltopoint", false); } diff --git a/dGame/dBehaviors/ImmunityBehavior.h b/dGame/dBehaviors/ImmunityBehavior.h index f9409e4c..02cc0fae 100644 --- a/dGame/dBehaviors/ImmunityBehavior.h +++ b/dGame/dBehaviors/ImmunityBehavior.h @@ -4,8 +4,6 @@ class ImmunityBehavior final : public Behavior { public: - uint32_t m_immuneBasicAttack; - /* * Inherited */ @@ -20,4 +18,25 @@ public: void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void Load() override; + +private: + // stuns + bool m_ImmuneToStunAttack = false; + bool m_ImmuneToStunEquip = false; + bool m_ImmuneToStunInteract = false; + bool m_ImmuneToStunJump = false; // Unused + bool m_ImmuneToStunMove = false; + bool m_ImmuneToStunTurn = false; + bool m_ImmuneToStunUseItem = false; // Unused + + //status + bool m_ImmuneToBasicAttack = false; + bool m_ImmuneToDamageOverTime = false; + bool m_ImmuneToKnockback = false; + bool m_ImmuneToInterrupt = false; + bool m_ImmuneToSpeed = false; + bool m_ImmuneToImaginationGain = false; + bool m_ImmuneToImaginationLoss = false; + bool m_ImmuneToQuickbuildInterrupt = false; + bool m_ImmuneToPullToPoint = false; // Unused in cdclient, but used in client }; diff --git a/dGame/dComponents/ControllablePhysicsComponent.cpp b/dGame/dComponents/ControllablePhysicsComponent.cpp index a5e447c8..2920a84f 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/ControllablePhysicsComponent.cpp @@ -35,6 +35,14 @@ ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Com m_DirtyPickupRadiusScale = true; m_IsTeleporting = false; + m_ImmuneToStunAttackCount = 0; + m_ImmuneToStunEquipCount = 0; + m_ImmuneToStunInteractCount = 0; + m_ImmuneToStunJumpCount = 0; + m_ImmuneToStunMoveCount = 0; + m_ImmuneToStunTurnCount = 0; + m_ImmuneToStunUseItemCount = 0; + if (entity->GetLOT() != 1) // Other physics entities we care about will be added by BaseCombatAI return; @@ -71,7 +79,14 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bo outBitStream->Write(m_JetpackBypassChecks); } - outBitStream->Write0(); //This contains info about immunities, but for now I'm leaving it out. + outBitStream->Write1(); // always write these on construction + outBitStream->Write(m_ImmuneToStunMoveCount); + outBitStream->Write(m_ImmuneToStunJumpCount); + outBitStream->Write(m_ImmuneToStunTurnCount); + outBitStream->Write(m_ImmuneToStunAttackCount); + outBitStream->Write(m_ImmuneToStunUseItemCount); + outBitStream->Write(m_ImmuneToStunEquipCount); + outBitStream->Write(m_ImmuneToStunInteractCount); } if (m_IgnoreMultipliers) m_DirtyCheats = false; @@ -298,3 +313,44 @@ void ControllablePhysicsComponent::RemoveSpeedboost(float value) { SetSpeedMultiplier(m_SpeedBoost / 500.0f); // 500 being the base speed EntityManager::Instance()->SerializeEntity(m_Parent); } + +void ControllablePhysicsComponent::SetStunImmunity( + const eStateChangeType state, + const LWOOBJID originator, + const bool bImmuneToStunAttack, + const bool bImmuneToStunEquip, + const bool bImmuneToStunInteract, + const bool bImmuneToStunJump, + const bool bImmuneToStunMove, + const bool bImmuneToStunTurn, + const bool bImmuneToStunUseItem){ + + if (state == eStateChangeType::POP){ + if (bImmuneToStunAttack && m_ImmuneToStunAttackCount > 0) m_ImmuneToStunAttackCount -= 1; + if (bImmuneToStunEquip && m_ImmuneToStunEquipCount > 0) m_ImmuneToStunEquipCount -= 1; + if (bImmuneToStunInteract && m_ImmuneToStunInteractCount > 0) m_ImmuneToStunInteractCount -= 1; + if (bImmuneToStunJump && m_ImmuneToStunJumpCount > 0) m_ImmuneToStunJumpCount -= 1; + if (bImmuneToStunMove && m_ImmuneToStunMoveCount > 0) m_ImmuneToStunMoveCount -= 1; + if (bImmuneToStunTurn && m_ImmuneToStunTurnCount > 0) m_ImmuneToStunTurnCount -= 1; + if (bImmuneToStunUseItem && m_ImmuneToStunUseItemCount > 0) m_ImmuneToStunUseItemCount -= 1; + } else if (state == eStateChangeType::PUSH) { + if (bImmuneToStunAttack) m_ImmuneToStunAttackCount += 1; + if (bImmuneToStunEquip) m_ImmuneToStunEquipCount += 1; + if (bImmuneToStunInteract) m_ImmuneToStunInteractCount += 1; + if (bImmuneToStunJump) m_ImmuneToStunJumpCount += 1; + if (bImmuneToStunMove) m_ImmuneToStunMoveCount += 1; + if (bImmuneToStunTurn) m_ImmuneToStunTurnCount += 1; + if (bImmuneToStunUseItem) m_ImmuneToStunUseItemCount += 1; + } + + GameMessages::SendSetStunImmunity( + m_Parent->GetObjectID(), state, m_Parent->GetSystemAddress(), originator, + bImmuneToStunAttack, + bImmuneToStunEquip, + bImmuneToStunInteract, + bImmuneToStunJump, + bImmuneToStunMove, + bImmuneToStunTurn, + bImmuneToStunUseItem + ); +} diff --git a/dGame/dComponents/ControllablePhysicsComponent.h b/dGame/dComponents/ControllablePhysicsComponent.h index e029d607..ba3e1bf4 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.h +++ b/dGame/dComponents/ControllablePhysicsComponent.h @@ -264,6 +264,30 @@ public: std::vector<float> GetActiveSpeedboosts() { return m_ActivePickupRadiusScales; }; + /** + * Push or Pop a layer of stun immunity to this entity + */ + void SetStunImmunity( + const eStateChangeType state, + const LWOOBJID originator = LWOOBJID_EMPTY, + const bool bImmuneToStunAttack = false, + const bool bImmuneToStunEquip = false, + const bool bImmuneToStunInteract = false, + const bool bImmuneToStunJump = false, + const bool bImmuneToStunMove = false, + const bool bImmuneToStunTurn = false, + const bool bImmuneToStunUseItem = false + ); + + // getters for stun immunities + const bool GetImmuneToStunAttack() { return m_ImmuneToStunAttackCount > 0;}; + const bool GetImmuneToStunEquip() { return m_ImmuneToStunEquipCount > 0;}; + const bool GetImmuneToStunInteract() { return m_ImmuneToStunInteractCount > 0;}; + const bool GetImmuneToStunJump() { return m_ImmuneToStunJumpCount > 0;}; + const bool GetImmuneToStunMove() { return m_ImmuneToStunMoveCount > 0;}; + const bool GetImmuneToStunTurn() { return m_ImmuneToStunTurnCount > 0;}; + const bool GetImmuneToStunUseItem() { return m_ImmuneToStunUseItemCount > 0;}; + private: /** * The entity that owns this component @@ -389,6 +413,17 @@ private: * The active speed boost for this entity */ float m_SpeedBoost; + + /** + * stun immunity counters + */ + int32_t m_ImmuneToStunAttackCount; + int32_t m_ImmuneToStunEquipCount; + int32_t m_ImmuneToStunInteractCount; + int32_t m_ImmuneToStunJumpCount; + int32_t m_ImmuneToStunMoveCount; + int32_t m_ImmuneToStunTurnCount; + int32_t m_ImmuneToStunUseItemCount; }; #endif // CONTROLLABLEPHYSICSCOMPONENT_H diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 1b127c41..3e146335 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -55,8 +55,17 @@ DestroyableComponent::DestroyableComponent(Entity* parent) : Component(parent) { m_LootMatrixID = 0; m_MinCoins = 0; m_MaxCoins = 0; - m_ImmuneStacks = 0; m_DamageReduction = 0; + + m_ImmuneToBasicAttackCount = 0; + m_ImmuneToDamageOverTimeCount = 0; + m_ImmuneToKnockbackCount = 0; + m_ImmuneToInterruptCount = 0; + m_ImmuneToSpeedCount = 0; + m_ImmuneToImaginationGainCount = 0; + m_ImmuneToImaginationLossCount = 0; + m_ImmuneToQuickbuildInterruptCount = 0; + m_ImmuneToPullToPointCount = 0; } DestroyableComponent::~DestroyableComponent() { @@ -106,7 +115,16 @@ void DestroyableComponent::Reinitialize(LOT templateID) { void DestroyableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags) { if (bIsInitialUpdate) { - outBitStream->Write0(); //Contains info about immunities this object has, but it's left out for now. + outBitStream->Write1(); // always write these on construction + outBitStream->Write(m_ImmuneToBasicAttackCount); + outBitStream->Write(m_ImmuneToDamageOverTimeCount); + outBitStream->Write(m_ImmuneToKnockbackCount); + outBitStream->Write(m_ImmuneToInterruptCount); + outBitStream->Write(m_ImmuneToSpeedCount); + outBitStream->Write(m_ImmuneToImaginationGainCount); + outBitStream->Write(m_ImmuneToImaginationLossCount); + outBitStream->Write(m_ImmuneToQuickbuildInterruptCount); + outBitStream->Write(m_ImmuneToPullToPointCount); } outBitStream->Write(m_DirtyHealth || bIsInitialUpdate); @@ -336,7 +354,7 @@ void DestroyableComponent::SetDamageReduction(int32_t value) { void DestroyableComponent::SetIsImmune(bool value) { m_DirtyHealth = true; - m_ImmuneStacks = value ? 1 : 0; + m_ImmuneToBasicAttackCount = value ? 1 : 0; } void DestroyableComponent::SetIsGMImmune(bool value) { @@ -439,7 +457,7 @@ void DestroyableComponent::SetAttacksToBlock(const uint32_t value) { } bool DestroyableComponent::IsImmune() const { - return m_ImmuneStacks > 0 || m_IsGMImmune; + return m_IsGMImmune || m_ImmuneToBasicAttackCount > 0; } bool DestroyableComponent::IsKnockbackImmune() const { @@ -804,12 +822,53 @@ void DestroyableComponent::SetFaction(int32_t factionID, bool ignoreChecks) { AddFaction(factionID, ignoreChecks); } -void DestroyableComponent::PushImmunity(int32_t stacks) { - m_ImmuneStacks += stacks; -} +void DestroyableComponent::SetStatusImmunity( + const eStateChangeType state, + const bool bImmuneToBasicAttack, + const bool bImmuneToDamageOverTime, + const bool bImmuneToKnockback, + const bool bImmuneToInterrupt, + const bool bImmuneToSpeed, + const bool bImmuneToImaginationGain, + const bool bImmuneToImaginationLoss, + const bool bImmuneToQuickbuildInterrupt, + const bool bImmuneToPullToPoint) { -void DestroyableComponent::PopImmunity(int32_t stacks) { - m_ImmuneStacks -= stacks; + if (state == eStateChangeType::POP) { + if (bImmuneToBasicAttack && m_ImmuneToBasicAttackCount > 0) m_ImmuneToBasicAttackCount -= 1; + if (bImmuneToDamageOverTime && m_ImmuneToDamageOverTimeCount > 0) m_ImmuneToDamageOverTimeCount -= 1; + if (bImmuneToKnockback && m_ImmuneToKnockbackCount > 0) m_ImmuneToKnockbackCount -= 1; + if (bImmuneToInterrupt && m_ImmuneToInterruptCount > 0) m_ImmuneToInterruptCount -= 1; + if (bImmuneToSpeed && m_ImmuneToSpeedCount > 0) m_ImmuneToSpeedCount -= 1; + if (bImmuneToImaginationGain && m_ImmuneToImaginationGainCount > 0) m_ImmuneToImaginationGainCount -= 1; + if (bImmuneToImaginationLoss && m_ImmuneToImaginationLossCount > 0) m_ImmuneToImaginationLossCount -= 1; + if (bImmuneToQuickbuildInterrupt && m_ImmuneToQuickbuildInterruptCount > 0) m_ImmuneToQuickbuildInterruptCount -= 1; + if (bImmuneToPullToPoint && m_ImmuneToPullToPointCount > 0) m_ImmuneToPullToPointCount -= 1; + + } else if (state == eStateChangeType::PUSH){ + if (bImmuneToBasicAttack) m_ImmuneToBasicAttackCount += 1; + if (bImmuneToDamageOverTime) m_ImmuneToDamageOverTimeCount += 1; + if (bImmuneToKnockback) m_ImmuneToKnockbackCount += 1; + if (bImmuneToInterrupt) m_ImmuneToInterruptCount += 1; + if (bImmuneToSpeed) m_ImmuneToSpeedCount += 1; + if (bImmuneToImaginationGain) m_ImmuneToImaginationGainCount += 1; + if (bImmuneToImaginationLoss) m_ImmuneToImaginationLossCount += 1; + if (bImmuneToQuickbuildInterrupt) m_ImmuneToQuickbuildInterruptCount += 1; + if (bImmuneToPullToPoint) m_ImmuneToPullToPointCount += 1; + } + + GameMessages::SendSetStatusImmunity( + m_Parent->GetObjectID(), state, m_Parent->GetSystemAddress(), + bImmuneToBasicAttack, + bImmuneToDamageOverTime, + bImmuneToKnockback, + bImmuneToInterrupt, + bImmuneToSpeed, + bImmuneToImaginationGain, + bImmuneToImaginationLoss, + bImmuneToQuickbuildInterrupt, + bImmuneToPullToPoint + ); } void DestroyableComponent::FixStats() { diff --git a/dGame/dComponents/DestroyableComponent.h b/dGame/dComponents/DestroyableComponent.h index 5bb990a7..2736f47c 100644 --- a/dGame/dComponents/DestroyableComponent.h +++ b/dGame/dComponents/DestroyableComponent.h @@ -396,16 +396,31 @@ public: void Smash(LWOOBJID source, eKillType killType = eKillType::VIOLENT, const std::u16string& deathType = u"", uint32_t skillID = 0); /** - * Pushes a layer of immunity to this entity, making it immune for longer - * @param stacks the amount of immunity to add + * Push or Pop a layer of status immunity to this entity */ - void PushImmunity(int32_t stacks = 1); + void SetStatusImmunity( + const eStateChangeType state, + const bool bImmuneToBasicAttack = false, + const bool bImmuneToDamageOverTime = false, + const bool bImmuneToKnockback = false, + const bool bImmuneToInterrupt = false, + const bool bImmuneToSpeed = false, + const bool bImmuneToImaginationGain = false, + const bool bImmuneToImaginationLoss = false, + const bool bImmuneToQuickbuildInterrupt = false, + const bool bImmuneToPullToPoint = false + ); - /** - * Pops layers of immunity, making it immune for less longer - * @param stacks the number of layers of immunity to remove - */ - void PopImmunity(int32_t stacks = 1); + // Getters for status immunities + const bool GetImmuneToBasicAttack() {return m_ImmuneToBasicAttackCount > 0;}; + const bool GetImmuneToDamageOverTime() {return m_ImmuneToDamageOverTimeCount > 0;}; + const bool GetImmuneToKnockback() {return m_ImmuneToKnockbackCount > 0;}; + const bool GetImmuneToInterrupt() {return m_ImmuneToInterruptCount > 0;}; + const bool GetImmuneToSpeed() {return m_ImmuneToSpeedCount > 0;}; + const bool GetImmuneToImaginationGain() {return m_ImmuneToImaginationGainCount > 0;}; + const bool GetImmuneToImaginationLoss() {return m_ImmuneToImaginationLossCount > 0;}; + const bool GetImmuneToQuickbuildInterrupt() {return m_ImmuneToQuickbuildInterruptCount > 0;}; + const bool GetImmuneToPullToPoint() {return m_ImmuneToPullToPointCount > 0;}; /** * Utility to reset all stats to the default stats based on items and completed missions @@ -428,7 +443,7 @@ public: /** * Notify subscribed scripts of Damage actions. - * + * * @param attacker The attacking Entity * @param damage The amount of damage that was done */ @@ -493,11 +508,6 @@ private: */ uint32_t m_AttacksToBlock; - /** - * The layers of immunity this entity has left - */ - int32_t m_ImmuneStacks; - /** * The amount of damage that should be reduced from every attack */ @@ -577,6 +587,19 @@ private: * The list of scripts subscribed to this components actions */ std::map<LWOOBJID, CppScripts::Script*> m_SubscribedScripts; + + /** + * status immunity counters + */ + uint32_t m_ImmuneToBasicAttackCount; + uint32_t m_ImmuneToDamageOverTimeCount; + uint32_t m_ImmuneToKnockbackCount; + uint32_t m_ImmuneToInterruptCount; + uint32_t m_ImmuneToSpeedCount; + uint32_t m_ImmuneToImaginationGainCount; + uint32_t m_ImmuneToImaginationLossCount; + uint32_t m_ImmuneToQuickbuildInterruptCount; + uint32_t m_ImmuneToPullToPointCount; }; #endif // DESTROYABLECOMPONENT_H diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 6247f32d..e5ff2f2a 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -959,7 +959,7 @@ void InventoryComponent::HandlePossession(Item* item) { return; } - GameMessages::SendSetStunned(m_Parent->GetObjectID(), eStunState::PUSH, m_Parent->GetSystemAddress(), LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); + GameMessages::SendSetStunned(m_Parent->GetObjectID(), eStateChangeType::PUSH, m_Parent->GetSystemAddress(), LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); // Set the mount Item ID so that we know what were handling possessorComponent->SetMountItemID(item->GetId()); diff --git a/dGame/dComponents/PossessorComponent.cpp b/dGame/dComponents/PossessorComponent.cpp index f0cad5ca..69046c3b 100644 --- a/dGame/dComponents/PossessorComponent.cpp +++ b/dGame/dComponents/PossessorComponent.cpp @@ -54,7 +54,7 @@ void PossessorComponent::Mount(Entity* mount) { // GM's to send GameMessages::SendSetJetPackMode(m_Parent, false); GameMessages::SendVehicleUnlockInput(mount->GetObjectID(), false, m_Parent->GetSystemAddress()); - GameMessages::SendSetStunned(m_Parent->GetObjectID(), eStunState::PUSH, m_Parent->GetSystemAddress(), LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); + GameMessages::SendSetStunned(m_Parent->GetObjectID(), eStateChangeType::PUSH, m_Parent->GetSystemAddress(), LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); EntityManager::Instance()->SerializeEntity(m_Parent); EntityManager::Instance()->SerializeEntity(mount); diff --git a/dGame/dComponents/RailActivatorComponent.cpp b/dGame/dComponents/RailActivatorComponent.cpp index 1b94fc4a..25fad26e 100644 --- a/dGame/dComponents/RailActivatorComponent.cpp +++ b/dGame/dComponents/RailActivatorComponent.cpp @@ -95,7 +95,7 @@ void RailActivatorComponent::OnUse(Entity* originator) { void RailActivatorComponent::OnRailMovementReady(Entity* originator) const { // Stun the originator - GameMessages::SendSetStunned(originator->GetObjectID(), PUSH, originator->GetSystemAddress(), LWOOBJID_EMPTY, + GameMessages::SendSetStunned(originator->GetObjectID(), eStateChangeType::PUSH, originator->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true ); @@ -123,7 +123,7 @@ void RailActivatorComponent::OnRailMovementReady(Entity* originator) const { void RailActivatorComponent::OnCancelRailMovement(Entity* originator) { // Remove the stun from the originator - GameMessages::SendSetStunned(originator->GetObjectID(), POP, originator->GetSystemAddress(), LWOOBJID_EMPTY, + GameMessages::SendSetStunned(originator->GetObjectID(), eStateChangeType::POP, originator->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true ); diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 634e6a1e..c6c7d2d1 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -2904,7 +2904,7 @@ void GameMessages::HandleCinematicUpdate(RakNet::BitStream* inStream, Entity* en } } -void GameMessages::SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, const SystemAddress& sysAddr, +void GameMessages::SendSetStunned(LWOOBJID objectId, eStateChangeType stateChangeType, const SystemAddress& sysAddr, LWOOBJID originator, bool bCantAttack, bool bCantEquip, bool bCantInteract, bool bCantJump, bool bCantMove, bool bCantTurn, bool bCantUseItem, bool bDontTerminateInteract, bool bIgnoreImmunity, @@ -2952,6 +2952,69 @@ void GameMessages::SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, SEND_PACKET; } +void GameMessages::SendSetStunImmunity(LWOOBJID target, eStateChangeType state, const SystemAddress& sysAddr, + LWOOBJID originator, + bool bImmuneToStunAttack, + bool bImmuneToStunEquip, + bool bImmuneToStunInteract, + bool bImmuneToStunJump, + bool bImmuneToStunMove, + bool bImmuneToStunTurn, + bool bImmuneToStunUseItem) { + CBITSTREAM; + CMSGHEADER; + + bitStream.Write(target); + bitStream.Write(GAME_MSG::GAME_MSG_SET_STUN_IMMUNITY); + + bitStream.Write(originator != LWOOBJID_EMPTY); + if (originator != LWOOBJID_EMPTY) bitStream.Write(originator); + + bitStream.Write(state); + + bitStream.Write(bImmuneToStunAttack); + bitStream.Write(bImmuneToStunEquip); + bitStream.Write(bImmuneToStunInteract); + bitStream.Write(bImmuneToStunJump); + bitStream.Write(bImmuneToStunMove); + bitStream.Write(bImmuneToStunTurn); + bitStream.Write(bImmuneToStunUseItem); + + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET; +} + +void GameMessages::SendSetStatusImmunity(LWOOBJID objectId, eStateChangeType state, const SystemAddress& sysAddr, + bool bImmuneToBasicAttack, + bool bImmuneToDamageOverTime, + bool bImmuneToKnockback, + bool bImmuneToInterrupt, + bool bImmuneToSpeed, + bool bImmuneToImaginationGain, + bool bImmuneToImaginationLoss, + bool bImmuneToQuickbuildInterrupt, + bool bImmuneToPullToPoint) { + CBITSTREAM; + CMSGHEADER; + + bitStream.Write(objectId); + bitStream.Write(GAME_MSG::GAME_MSG_SET_STATUS_IMMUNITY); + + bitStream.Write(state); + + bitStream.Write(bImmuneToBasicAttack); + bitStream.Write(bImmuneToDamageOverTime); + bitStream.Write(bImmuneToKnockback); + bitStream.Write(bImmuneToInterrupt); + bitStream.Write(bImmuneToSpeed); + bitStream.Write(bImmuneToImaginationGain); + bitStream.Write(bImmuneToImaginationLoss); + bitStream.Write(bImmuneToQuickbuildInterrupt); + bitStream.Write(bImmuneToPullToPoint); + + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET; +} void GameMessages::SendOrientToAngle(LWOOBJID objectId, bool bRelativeToCurrent, float fAngle, const SystemAddress& sysAddr) { CBITSTREAM; @@ -3991,7 +4054,7 @@ void GameMessages::HandleDismountComplete(RakNet::BitStream* inStream, Entity* e EntityManager::Instance()->SerializeEntity(entity); // We aren't mounted so remove the stun - GameMessages::SendSetStunned(entity->GetObjectID(), eStunState::POP, UNASSIGNED_SYSTEM_ADDRESS, LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); + GameMessages::SendSetStunned(entity->GetObjectID(), eStateChangeType::POP, UNASSIGNED_SYSTEM_ADDRESS, LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); } } } diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 6575ad85..6fa4e694 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -268,7 +268,7 @@ namespace GameMessages { float leadOut = -1.0f, bool leavePlayerLocked = false); void HandleCinematicUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void SendSetStunned(LWOOBJID objectId, eStunState stateChangeType, const SystemAddress& sysAddr, + void SendSetStunned(LWOOBJID objectId, eStateChangeType stateChangeType, const SystemAddress& sysAddr, LWOOBJID originator = LWOOBJID_EMPTY, bool bCantAttack = false, bool bCantEquip = false, bool bCantInteract = false, bool bCantJump = false, bool bCantMove = false, bool bCantTurn = false, bool bCantUseItem = false, bool bDontTerminateInteract = false, bool bIgnoreImmunity = true, @@ -277,6 +277,35 @@ namespace GameMessages { bool bCantMoveOutChangeWasApplied = false, bool bCantTurnOutChangeWasApplied = false, bool bCantUseItemOutChangeWasApplied = false); + void SendSetStunImmunity( + LWOOBJID target, + eStateChangeType state, + const SystemAddress& sysAddr, + LWOOBJID originator = LWOOBJID_EMPTY, + bool bImmuneToStunAttack = false, + bool bImmuneToStunEquip = false, + bool bImmuneToStunInteract = false, + bool bImmuneToStunJump = false, + bool bImmuneToStunMove = false, + bool bImmuneToStunTurn = false, + bool bImmuneToStunUseItem = false + ); + + void SendSetStatusImmunity( + LWOOBJID objectId, + eStateChangeType state, + const SystemAddress& sysAddr, + bool bImmuneToBasicAttack = false, + bool bImmuneToDamageOverTime = false, + bool bImmuneToKnockback = false, + bool bImmuneToInterrupt = false, + bool bImmuneToSpeed = false, + bool bImmuneToImaginationGain = false, + bool bImmuneToImaginationLoss = false, + bool bImmuneToQuickbuildInterrupt = false, + bool bImmuneToPullToPoint = false + ); + void SendOrientToAngle(LWOOBJID objectId, bool bRelativeToCurrent, float fAngle, const SystemAddress& sysAddr); void SendAddRunSpeedModifier(LWOOBJID objectId, LWOOBJID caster, uint32_t modifier, const SystemAddress& sysAddr); diff --git a/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp b/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp index d3c59448..ea3ce9b8 100644 --- a/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp +++ b/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp @@ -131,7 +131,7 @@ void BaseEnemyApe::StunApe(Entity* self, bool stunState) { skillComponent->Interrupt(); } - GameMessages::SendSetStunned(self->GetObjectID(), stunState ? PUSH : POP, UNASSIGNED_SYSTEM_ADDRESS, self->GetObjectID(), + GameMessages::SendSetStunned(self->GetObjectID(), stunState ? eStateChangeType::PUSH : eStateChangeType::POP, UNASSIGNED_SYSTEM_ADDRESS, self->GetObjectID(), true, true, true, true, true, true, true, true, true); diff --git a/dScripts/02_server/Map/AM/AmSkullkinDrill.cpp b/dScripts/02_server/Map/AM/AmSkullkinDrill.cpp index 9b85cf85..da1954d6 100644 --- a/dScripts/02_server/Map/AM/AmSkullkinDrill.cpp +++ b/dScripts/02_server/Map/AM/AmSkullkinDrill.cpp @@ -147,21 +147,21 @@ void AmSkullkinDrill::OnUse(Entity* self, Entity* user) { } void AmSkullkinDrill::FreezePlayer(Entity* self, Entity* player, bool bFreeze) { - eStunState eChangeType = POP; + auto StateChangeType = eStateChangeType::POP; if (bFreeze) { if (player->GetIsDead()) { return; } - eChangeType = PUSH; + StateChangeType = eStateChangeType::PUSH; } else { if (player->GetIsDead()) { // } } - GameMessages::SendSetStunned(player->GetObjectID(), eChangeType, player->GetSystemAddress(), self->GetObjectID(), + GameMessages::SendSetStunned(player->GetObjectID(), StateChangeType, player->GetSystemAddress(), self->GetObjectID(), true, false, true, false, true, false, true ); } diff --git a/dScripts/02_server/Map/GF/GfCaptainsCannon.cpp b/dScripts/02_server/Map/GF/GfCaptainsCannon.cpp index 7d67c781..eeabeef6 100644 --- a/dScripts/02_server/Map/GF/GfCaptainsCannon.cpp +++ b/dScripts/02_server/Map/GF/GfCaptainsCannon.cpp @@ -13,7 +13,7 @@ void GfCaptainsCannon::OnUse(Entity* self, Entity* user) { self->SetVar<bool>(u"bIsInUse", true); self->SetNetworkVar<bool>(u"bIsInUse", true); - GameMessages::SendSetStunned(user->GetObjectID(), PUSH, user->GetSystemAddress(), + GameMessages::SendSetStunned(user->GetObjectID(), eStateChangeType::PUSH, user->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true, true ); @@ -63,7 +63,7 @@ void GfCaptainsCannon::OnTimerDone(Entity* self, std::string timerName) { GameMessages::SendPlay2DAmbientSound(player, "{7457d85c-4537-4317-ac9d-2f549219ea87}"); } else if (timerName == "cinematicTimer") { - GameMessages::SendSetStunned(playerId, POP, player->GetSystemAddress(), + GameMessages::SendSetStunned(playerId, eStateChangeType::POP, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true, true ); diff --git a/dScripts/02_server/Map/GF/MastTeleport.cpp b/dScripts/02_server/Map/GF/MastTeleport.cpp index ebde7b20..dac5783c 100644 --- a/dScripts/02_server/Map/GF/MastTeleport.cpp +++ b/dScripts/02_server/Map/GF/MastTeleport.cpp @@ -16,7 +16,7 @@ void MastTeleport::OnRebuildComplete(Entity* self, Entity* target) { if (Preconditions::Check(target, 154) && Preconditions::Check(target, 44)) { self->SetVar<LWOOBJID>(u"userID", target->GetObjectID()); - GameMessages::SendSetStunned(target->GetObjectID(), PUSH, target->GetSystemAddress(), + GameMessages::SendSetStunned(target->GetObjectID(), eStateChangeType::PUSH, target->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true ); @@ -81,7 +81,7 @@ void MastTeleport::OnTimerDone(Entity* self, std::string timerName) { GameMessages::SendTeleport(playerId, position, NiQuaternion::IDENTITY, player->GetSystemAddress()); - GameMessages::SendSetStunned(playerId, POP, player->GetSystemAddress(), + GameMessages::SendSetStunned(playerId, eStateChangeType::POP, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true ); } diff --git a/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp b/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp index f30f4fc7..5410047d 100644 --- a/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp +++ b/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp @@ -36,7 +36,7 @@ void NtAssemblyTubeServer::RunAssemblyTube(Entity* self, Entity* player) { if (player->IsPlayer() && !bPlayerBeingTeleported) { auto teleCinematic = self->GetVar<std::u16string>(u"Cinematic"); - GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, + GameMessages::SendSetStunned(playerID, eStateChangeType::PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true ); @@ -108,7 +108,7 @@ void NtAssemblyTubeServer::UnlockPlayer(Entity* self, Entity* player) { m_TeleportingPlayerTable[playerID] = false; - GameMessages::SendSetStunned(playerID, POP, player->GetSystemAddress(), LWOOBJID_EMPTY, + GameMessages::SendSetStunned(playerID, eStateChangeType::POP, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true ); } diff --git a/dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp b/dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp index 06482c82..8d14050b 100644 --- a/dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp +++ b/dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp @@ -34,11 +34,11 @@ void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) { GameMessages::SendPlayAnimation(player, u"rebuild-celebrate"); GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SparkStop", 0, 0, player->GetObjectID(), "", player->GetSystemAddress()); - GameMessages::SendSetStunned(player->GetObjectID(), eStunState::POP, player->GetSystemAddress(), LWOOBJID_EMPTY, false, false, true, false, true, true, false, false, true); + GameMessages::SendSetStunned(player->GetObjectID(), eStateChangeType::POP, player->GetSystemAddress(), LWOOBJID_EMPTY, false, false, true, false, true, true, false, false, true); self->SetVar(u"bActive", false); }); GameMessages::SendPlayAnimation(user, u"nexus-powerpanel", 6.0f); - GameMessages::SendSetStunned(user->GetObjectID(), eStunState::PUSH, user->GetSystemAddress(), LWOOBJID_EMPTY, false, false, true, false, true, true, false, false, true); + GameMessages::SendSetStunned(user->GetObjectID(), eStateChangeType::PUSH, user->GetSystemAddress(), LWOOBJID_EMPTY, false, false, true, false, true, true, false, false, true); return; } diff --git a/dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp b/dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp index 8003e93f..64af4d34 100644 --- a/dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp +++ b/dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp @@ -22,7 +22,7 @@ void NtParadoxTeleServer::OnProximityUpdate(Entity* self, Entity* entering, std: const auto bPlayerBeingTeleported = m_TeleportingPlayerTable[playerID]; if (player->IsPlayer() && !bPlayerBeingTeleported) { - GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, + GameMessages::SendSetStunned(playerID, eStateChangeType::PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true ); @@ -100,7 +100,7 @@ void NtParadoxTeleServer::UnlockPlayer(Entity* self, Entity* player) { m_TeleportingPlayerTable[playerID] = false; - GameMessages::SendSetStunned(playerID, POP, player->GetSystemAddress(), LWOOBJID_EMPTY, + GameMessages::SendSetStunned(playerID, eStateChangeType::POP, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true ); diff --git a/dScripts/02_server/Map/NT/NtVentureCannonServer.cpp b/dScripts/02_server/Map/NT/NtVentureCannonServer.cpp index d7f4cb99..e6cd2df6 100644 --- a/dScripts/02_server/Map/NT/NtVentureCannonServer.cpp +++ b/dScripts/02_server/Map/NT/NtVentureCannonServer.cpp @@ -14,7 +14,7 @@ void NtVentureCannonServer::OnUse(Entity* self, Entity* user) { self->SetNetworkVar(u"bIsInUse", true); - GameMessages::SendSetStunned(playerID, PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, + GameMessages::SendSetStunned(playerID, eStateChangeType::PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true ); @@ -92,7 +92,7 @@ void NtVentureCannonServer::ExitCannonEnded(Entity* self, Entity* player) { } void NtVentureCannonServer::UnlockCannonPlayer(Entity* self, Entity* player) { - GameMessages::SendSetStunned(player->GetObjectID(), POP, player->GetSystemAddress(), LWOOBJID_EMPTY, + GameMessages::SendSetStunned(player->GetObjectID(), eStateChangeType::POP, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true ); diff --git a/dScripts/BaseConsoleTeleportServer.cpp b/dScripts/BaseConsoleTeleportServer.cpp index a8538de5..d0162e9c 100644 --- a/dScripts/BaseConsoleTeleportServer.cpp +++ b/dScripts/BaseConsoleTeleportServer.cpp @@ -15,7 +15,8 @@ void BaseConsoleTeleportServer::BaseOnMessageBoxResponse(Entity* self, Entity* s if (button == 1) { - GameMessages::SendSetStunned(player->GetObjectID(), PUSH, player->GetSystemAddress(), player->GetObjectID(), + GameMessages::SendSetStunned( + player->GetObjectID(), eStateChangeType::PUSH, player->GetSystemAddress(), player->GetObjectID(), true, true, true, true, true, true, true ); @@ -82,11 +83,10 @@ void BaseConsoleTeleportServer::TransferPlayer(Entity* self, Entity* player, int return; } - // Ignoring extra effects for now - - /*GameMessages::SendSetStunned(player->GetObjectID(), POP, player->GetSystemAddress(), player->GetObjectID(), + GameMessages::SendSetStunned( + player->GetObjectID(), eStateChangeType::POP, player->GetSystemAddress(), player->GetObjectID(), true, true, true, true, true, true, true - );*/ + ); GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, player->GetObjectID()); diff --git a/dScripts/EquipmentScripts/PersonalFortress.cpp b/dScripts/EquipmentScripts/PersonalFortress.cpp index e7e89e80..f5062f9b 100644 --- a/dScripts/EquipmentScripts/PersonalFortress.cpp +++ b/dScripts/EquipmentScripts/PersonalFortress.cpp @@ -2,49 +2,56 @@ #include "GameMessages.h" #include "SkillComponent.h" #include "DestroyableComponent.h" +#include "ControllablePhysicsComponent.h" #include "EntityManager.h" void PersonalFortress::OnStartup(Entity* self) { auto* owner = self->GetOwner(); self->AddTimer("FireSkill", 1.5); - GameMessages::SendSetStunned(owner->GetObjectID(), PUSH, owner->GetSystemAddress(), LWOOBJID_EMPTY, - true, true, true, true, true, true, true, true, true - ); auto* destroyableComponent = owner->GetComponent<DestroyableComponent>(); + if (destroyableComponent) destroyableComponent->SetStatusImmunity( + eStateChangeType::PUSH, + true, true, true, true, true, false, true, false, false + ); - if (destroyableComponent != nullptr) { - destroyableComponent->PushImmunity(); - } + auto* controllablePhysicsComponent = owner->GetComponent<ControllablePhysicsComponent>(); + if (controllablePhysicsComponent) controllablePhysicsComponent->SetStunImmunity( + eStateChangeType::PUSH, LWOOBJID_EMPTY, + true, true, true, true, true, true + ); + + GameMessages::SendSetStunned(owner->GetObjectID(), eStateChangeType::PUSH, owner->GetSystemAddress(), LWOOBJID_EMPTY, + true, true, true, true, true, true, true, true, true + ); EntityManager::Instance()->SerializeEntity(owner); } void PersonalFortress::OnDie(Entity* self, Entity* killer) { auto* owner = self->GetOwner(); - GameMessages::SendSetStunned(owner->GetObjectID(), POP, owner->GetSystemAddress(), LWOOBJID_EMPTY, + auto* destroyableComponent = owner->GetComponent<DestroyableComponent>(); + if (destroyableComponent) destroyableComponent->SetStatusImmunity( + eStateChangeType::POP, + true, true, true, true, true, false, true, false, false + ); + + auto* controllablePhysicsComponent = owner->GetComponent<ControllablePhysicsComponent>(); + if (controllablePhysicsComponent) controllablePhysicsComponent->SetStunImmunity( + eStateChangeType::POP, LWOOBJID_EMPTY, + true, true, true, true, true, true + ); + + GameMessages::SendSetStunned(owner->GetObjectID(), eStateChangeType::POP, owner->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true, true, true ); - auto* destroyableComponent = owner->GetComponent<DestroyableComponent>(); - - if (destroyableComponent != nullptr) { - destroyableComponent->PopImmunity(); - } - EntityManager::Instance()->SerializeEntity(owner); } void PersonalFortress::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "FireSkill") { - auto* owner = self->GetOwner(); - auto* skillComponent = self->GetComponent<SkillComponent>(); - - if (skillComponent == nullptr) { - return; - } - - skillComponent->CalculateBehavior(650, 13364, LWOOBJID_EMPTY, true, false); + if (skillComponent) skillComponent->CalculateBehavior(650, 13364, LWOOBJID_EMPTY, true, false); } } diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp index db914c7f..f9146ec4 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp @@ -77,7 +77,7 @@ void SGCannon::OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int auto* player = EntityManager::Instance()->GetEntity(self->GetVar<LWOOBJID>(PlayerIDVariable)); if (player != nullptr) { Game::logger->Log("SGCannon", "Player is ready"); - /*GameMessages::SendSetStunned(player->GetObjectID(), PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, + /*GameMessages::SendSetStunned(player->GetObjectID(), eStateChangeType::PUSH, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true);*/ Game::logger->Log("SGCannon", "Sending ActivityEnter"); diff --git a/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp index 97288909..5448a4c2 100644 --- a/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp +++ b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp @@ -41,10 +41,19 @@ protected: TEST_F(DestroyableTest, DestroyableComponentSerializeConstructionTest) { destroyableComponent->Serialize(&bitStream, true, flags); // Assert that the full number of bits are present - ASSERT_EQ(bitStream.GetNumberOfUnreadBits(), 460); + ASSERT_EQ(bitStream.GetNumberOfUnreadBits(), 748); { // Now read in the full serialized construction BitStream - bool optionStatusImmunityInfo{}; // Values under this option are unused. + bool optionStatusImmunityInfo{}; + uint32_t ImmuneToBasicAttackCount{}; + uint32_t ImmuneToDamageOverTimeCount{}; + uint32_t ImmuneToKnockbackCount{}; + uint32_t ImmuneToInterruptCount{}; + uint32_t ImmuneToSpeedCount{}; + uint32_t ImmuneToImaginationGainCount{}; + uint32_t ImmuneToImaginationLossCount{}; + uint32_t ImmuneToQuickbuildInterruptCount{}; + uint32_t ImmuneToPullToPointCount{}; bool optionStatsInfo{}; uint32_t currentHealth{}; float maxHealth{}; @@ -70,7 +79,15 @@ TEST_F(DestroyableTest, DestroyableComponentSerializeConstructionTest) { bool optionIsOnThreatList{}; bool isThreatened{}; bitStream.Read(optionStatusImmunityInfo); - + bitStream.Read(ImmuneToBasicAttackCount); + bitStream.Read(ImmuneToDamageOverTimeCount); + bitStream.Read(ImmuneToKnockbackCount); + bitStream.Read(ImmuneToInterruptCount); + bitStream.Read(ImmuneToSpeedCount); + bitStream.Read(ImmuneToImaginationGainCount); + bitStream.Read(ImmuneToImaginationLossCount); + bitStream.Read(ImmuneToQuickbuildInterruptCount); + bitStream.Read(ImmuneToPullToPointCount); bitStream.Read(optionStatsInfo); bitStream.Read(currentHealth); bitStream.Read(maxHealth); @@ -101,7 +118,16 @@ TEST_F(DestroyableTest, DestroyableComponentSerializeConstructionTest) { bitStream.Read(optionIsOnThreatList); bitStream.Read(isThreatened); - EXPECT_EQ(optionStatusImmunityInfo, false); + EXPECT_EQ(optionStatusImmunityInfo, true); + EXPECT_EQ(ImmuneToBasicAttackCount, 0); + EXPECT_EQ(ImmuneToDamageOverTimeCount, 0); + EXPECT_EQ(ImmuneToKnockbackCount, 0); + EXPECT_EQ(ImmuneToInterruptCount, 0); + EXPECT_EQ(ImmuneToSpeedCount, 0); + EXPECT_EQ(ImmuneToImaginationGainCount, 0); + EXPECT_EQ(ImmuneToImaginationLossCount, 0); + EXPECT_EQ(ImmuneToQuickbuildInterruptCount, 0); + EXPECT_EQ(ImmuneToPullToPointCount, 0); EXPECT_EQ(optionStatsInfo, true); EXPECT_EQ(currentHealth, 23); @@ -298,3 +324,208 @@ TEST_F(DestroyableTest, DestroyableComponentValiditiyTest) { EXPECT_FALSE(destroyableComponent->IsFriend(enemyEntity)); delete enemyEntity; } + +TEST_F(DestroyableTest, DestroyableComponentImmunityTest) { + // assert to show that they are empty + ASSERT_FALSE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + // set them all to true (count 1) and check + destroyableComponent->SetStatusImmunity(eStateChangeType::PUSH, true, true, true, true, true, true, true, true, true); + ASSERT_TRUE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_TRUE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_TRUE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_TRUE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_TRUE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_TRUE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_TRUE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_TRUE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_TRUE(destroyableComponent->GetImmuneToPullToPoint()); + + // remove them to check that they get removed properly + destroyableComponent->SetStatusImmunity(eStateChangeType::POP, true, true, true, true, true, true, true, true, true); + ASSERT_FALSE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + + // should not crash to remove them again + destroyableComponent->SetStatusImmunity(eStateChangeType::POP, true, true, true, true, true, true, true, true, true); + ASSERT_FALSE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + + // just do one + destroyableComponent->SetStatusImmunity(eStateChangeType::PUSH, true); + ASSERT_TRUE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + // now stack it to 2 on basic attack + destroyableComponent->SetStatusImmunity(eStateChangeType::PUSH, true); + ASSERT_TRUE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + // remove one and still shoudl be true + destroyableComponent->SetStatusImmunity(eStateChangeType::POP, true); + ASSERT_TRUE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + // go back to 0 + destroyableComponent->SetStatusImmunity(eStateChangeType::POP, true); + ASSERT_FALSE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + // check individual ones now + destroyableComponent->SetStatusImmunity(eStateChangeType::PUSH, true, false, false, false, false, false, false, false, false); + ASSERT_TRUE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + destroyableComponent->SetStatusImmunity(eStateChangeType::POP, true, false, false, false, false, false, false, false, false); + + destroyableComponent->SetStatusImmunity(eStateChangeType::PUSH, false, true, false, false, false, false, false, false, false); + ASSERT_FALSE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_TRUE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + destroyableComponent->SetStatusImmunity(eStateChangeType::POP, false, true, false, false, false, false, false, false, false); + + destroyableComponent->SetStatusImmunity(eStateChangeType::PUSH, false, false, true, false, false, false, false, false, false); + ASSERT_FALSE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_TRUE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + destroyableComponent->SetStatusImmunity(eStateChangeType::POP, false, false, true, false, false, false, false, false, false); + + destroyableComponent->SetStatusImmunity(eStateChangeType::PUSH, false, false, false, true, false, false, false, false, false); + ASSERT_FALSE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_TRUE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + destroyableComponent->SetStatusImmunity(eStateChangeType::POP, false, false, false, true, false, false, false, false, false); + + destroyableComponent->SetStatusImmunity(eStateChangeType::PUSH, false, false, false, false, true, false, false, false, false); + ASSERT_FALSE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_TRUE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + destroyableComponent->SetStatusImmunity(eStateChangeType::POP, false, false, false, false, true, false, false, false, false); + + destroyableComponent->SetStatusImmunity(eStateChangeType::PUSH, false, false, false, false, false, true, false, false, false); + ASSERT_FALSE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_TRUE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + destroyableComponent->SetStatusImmunity(eStateChangeType::POP, false, false, false, false, false, true, false, false, false); + + destroyableComponent->SetStatusImmunity(eStateChangeType::PUSH, false, false, false, false, false, false, true, false, false); + ASSERT_FALSE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_TRUE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + destroyableComponent->SetStatusImmunity(eStateChangeType::POP, false, false, false, false, false, false, true, false, false); + + + destroyableComponent->SetStatusImmunity(eStateChangeType::PUSH, false, false, false, false, false, false, false, true, false); + ASSERT_FALSE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_TRUE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToPullToPoint()); + destroyableComponent->SetStatusImmunity(eStateChangeType::POP, false, false, false, false, false, false, false, true, false); + + + destroyableComponent->SetStatusImmunity(eStateChangeType::PUSH, false, false, false, false, false, false, false, false, true); + ASSERT_FALSE(destroyableComponent->GetImmuneToBasicAttack()); + ASSERT_FALSE(destroyableComponent->GetImmuneToDamageOverTime()); + ASSERT_FALSE(destroyableComponent->GetImmuneToKnockback()); + ASSERT_FALSE(destroyableComponent->GetImmuneToInterrupt()); + ASSERT_FALSE(destroyableComponent->GetImmuneToSpeed()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationGain()); + ASSERT_FALSE(destroyableComponent->GetImmuneToImaginationLoss()); + ASSERT_FALSE(destroyableComponent->GetImmuneToQuickbuildInterrupt()); + ASSERT_TRUE(destroyableComponent->GetImmuneToPullToPoint()); + destroyableComponent->SetStatusImmunity(eStateChangeType::POP, false, false, false, false, false, false, false, false, true); + +} + From 5374c555f549cc47dbedebf71dcdd9c47a9825f8 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 7 Jan 2023 00:14:51 -0600 Subject: [PATCH 226/322] Implement bubble seriliaztion in controllable physics (#942) * bubble * "Correct" serialization and enum * Enum update * figured out what things do * accurate types and cleanup * add sanity check add getter add slash command for testing * fix default * cleanup slash command * handle game message probably remove funny slash command add all bubble GM's Co-authored-by: Jett <55758076+Jettford@users.noreply.github.com> --- dCommon/dEnums/dMessageIdentifiers.h | 7 ++- dCommon/dEnums/eBubbleType.h | 14 +++++ .../ControllablePhysicsComponent.cpp | 49 ++++++++++++++--- .../ControllablePhysicsComponent.h | 53 +++++++++++++++++-- dGame/dGameMessages/GameMessageHandler.cpp | 9 +++- dGame/dGameMessages/GameMessages.cpp | 40 ++++++++++++++ dGame/dGameMessages/GameMessages.h | 9 ++++ dGame/dUtilities/SlashCommandHandler.cpp | 1 + 8 files changed, 168 insertions(+), 14 deletions(-) create mode 100644 dCommon/dEnums/eBubbleType.h diff --git a/dCommon/dEnums/dMessageIdentifiers.h b/dCommon/dEnums/dMessageIdentifiers.h index ed4167c8..c1afc497 100644 --- a/dCommon/dEnums/dMessageIdentifiers.h +++ b/dCommon/dEnums/dMessageIdentifiers.h @@ -374,6 +374,8 @@ enum GAME_MSG : unsigned short { GAME_MSG_PET_TAMING_TRY_BUILD_RESULT = 668, GAME_MSG_NOTIFY_TAMING_BUILD_SUCCESS = 673, GAME_MSG_NOTIFY_TAMING_MODEL_LOADED_ON_SERVER = 674, + GAME_MSG_ACTIVATE_BUBBLE_BUFF = 678, + GAME_MSG_DEACTIVATE_BUBBLE_BUFF = 679, GAME_MSG_ADD_PET_TO_PLAYER = 681, GAME_MSG_REQUEST_SET_PET_NAME = 683, GAME_MSG_SET_PET_NAME = 684, @@ -386,7 +388,10 @@ enum GAME_MSG : unsigned short { GAME_MSG_QUERY_PROPERTY_DATA = 717, GAME_MSG_PROPERTY_EDITOR_BEGIN = 724, GAME_MSG_PROPERTY_EDITOR_END = 725, - GAME_MSG_START_PATHING = 735, + GAME_MSG_IS_MINIFIG_IN_A_BUBBLE = 729, + GAME_MSG_START_PATHING = 733, + GAME_MSG_ACTIVATE_BUBBLE_BUFF_FROM_SERVER = 734, + GAME_MSG_DEACTIVATE_BUBBLE_BUFF_FROM_SERVER = 735, GAME_MSG_NOTIFY_CLIENT_ZONE_OBJECT = 737, GAME_MSG_UPDATE_REPUTATION = 746, GAME_MSG_PROPERTY_RENTAL_RESPONSE = 750, diff --git a/dCommon/dEnums/eBubbleType.h b/dCommon/dEnums/eBubbleType.h new file mode 100644 index 00000000..4aa6fad1 --- /dev/null +++ b/dCommon/dEnums/eBubbleType.h @@ -0,0 +1,14 @@ +#pragma once + +#ifndef __EBUBBLETYPE__H__ +#define __EBUBBLETYPE__H__ + +#include <cstdint> + +enum class eBubbleType : uint32_t { + DEFAULT = 0, + ENERGY = 1, + SKUNK = 2, +}; + +#endif //!__EBUBBLETYPE__H__ diff --git a/dGame/dComponents/ControllablePhysicsComponent.cpp b/dGame/dComponents/ControllablePhysicsComponent.cpp index 2920a84f..6a6d69ce 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/ControllablePhysicsComponent.cpp @@ -31,8 +31,15 @@ ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Com m_GravityScale = 1; m_DirtyCheats = false; m_IgnoreMultipliers = false; + + m_DirtyEquippedItemInfo = true; m_PickupRadius = 0.0f; - m_DirtyPickupRadiusScale = true; + + m_DirtyBubble = false; + m_IsInBubble = false; + m_SpecialAnims = false; + m_BubbleType = eBubbleType::DEFAULT; + m_IsTeleporting = false; m_ImmuneToStunAttackCount = 0; @@ -99,14 +106,22 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bo m_DirtyCheats = false; } - outBitStream->Write(m_DirtyPickupRadiusScale); - if (m_DirtyPickupRadiusScale) { + outBitStream->Write(m_DirtyEquippedItemInfo); + if (m_DirtyEquippedItemInfo) { outBitStream->Write(m_PickupRadius); - outBitStream->Write0(); //No clue what this is so im leaving it false. - m_DirtyPickupRadiusScale = false; + outBitStream->Write(m_InJetpackMode); + m_DirtyEquippedItemInfo = false; } - outBitStream->Write0(); + outBitStream->Write(m_DirtyBubble); + if (m_DirtyBubble) { + outBitStream->Write(m_IsInBubble); + if (m_IsInBubble) { + outBitStream->Write(m_BubbleType); + outBitStream->Write(m_SpecialAnims); + } + m_DirtyBubble = false; + } outBitStream->Write(m_DirtyPosition || bIsInitialUpdate); if (m_DirtyPosition || bIsInitialUpdate) { @@ -263,7 +278,7 @@ void ControllablePhysicsComponent::AddPickupRadiusScale(float value) { m_ActivePickupRadiusScales.push_back(value); if (value > m_PickupRadius) { m_PickupRadius = value; - m_DirtyPickupRadiusScale = true; + m_DirtyEquippedItemInfo = true; } } @@ -279,7 +294,7 @@ void ControllablePhysicsComponent::RemovePickupRadiusScale(float value) { // Recalculate pickup radius since we removed one by now m_PickupRadius = 0.0f; - m_DirtyPickupRadiusScale = true; + m_DirtyEquippedItemInfo = true; for (uint32_t i = 0; i < m_ActivePickupRadiusScales.size(); i++) { auto candidateRadius = m_ActivePickupRadiusScales[i]; if (m_PickupRadius < candidateRadius) m_PickupRadius = candidateRadius; @@ -314,6 +329,24 @@ void ControllablePhysicsComponent::RemoveSpeedboost(float value) { EntityManager::Instance()->SerializeEntity(m_Parent); } +void ControllablePhysicsComponent::ActivateBubbleBuff(eBubbleType bubbleType, bool specialAnims){ + if (m_IsInBubble) { + Game::logger->Log("ControllablePhysicsComponent", "Already in bubble"); + return; + } + m_BubbleType = bubbleType; + m_IsInBubble = true; + m_DirtyBubble = true; + m_SpecialAnims = specialAnims; + EntityManager::Instance()->SerializeEntity(m_Parent); +} + +void ControllablePhysicsComponent::DeactivateBubbleBuff(){ + m_DirtyBubble = true; + m_IsInBubble = false; + EntityManager::Instance()->SerializeEntity(m_Parent); +}; + void ControllablePhysicsComponent::SetStunImmunity( const eStateChangeType state, const LWOOBJID originator, diff --git a/dGame/dComponents/ControllablePhysicsComponent.h b/dGame/dComponents/ControllablePhysicsComponent.h index ba3e1bf4..a05a11fd 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.h +++ b/dGame/dComponents/ControllablePhysicsComponent.h @@ -9,6 +9,7 @@ #include "Component.h" #include "dpCollisionChecks.h" #include "PhantomPhysicsComponent.h" +#include "eBubbleType.h" class Entity; class dpEntity; @@ -257,14 +258,40 @@ public: */ std::vector<float> GetActivePickupRadiusScales() { return m_ActivePickupRadiusScales; }; - + /** + * Add a Speed boost to the entity + * This will recalculate the speed boost based on what is being added + */ void AddSpeedboost(float value); + /** + * Remove speed boost from entity + * This will recalculate the speed boost based on what is the last one in te vector + */ void RemoveSpeedboost(float value); + /** + * The speed boosts of this component. + * @return All active Speed boosts for this component. + */ std::vector<float> GetActiveSpeedboosts() { return m_ActivePickupRadiusScales; }; /** + * Activates the Bubble Buff + */ + void ActivateBubbleBuff(eBubbleType bubbleType = eBubbleType::DEFAULT, bool specialAnims = true); + + /** + * Deactivates the Bubble Buff + */ + void DeactivateBubbleBuff(); + + /** + * Gets if the Entity is in a bubble + */ + bool GetIsInBubble(){ return m_IsInBubble; }; + + /** * Push or Pop a layer of stun immunity to this entity */ void SetStunImmunity( @@ -387,7 +414,7 @@ private: /** * Whether the pickup scale is dirty. */ - bool m_DirtyPickupRadiusScale; + bool m_DirtyEquippedItemInfo; /** * The list of pickup radius scales for this entity @@ -414,7 +441,27 @@ private: */ float m_SpeedBoost; - /** + /* + * If Bubble info is dirty + */ + bool m_DirtyBubble; + + /* + * If the entity is in a bubble + */ + bool m_IsInBubble; + + /* + * The type of bubble the entity has + */ + eBubbleType m_BubbleType; + + /* + * If the entity should be using the special animations + */ + bool m_SpecialAnims; + + /** * stun immunity counters */ int32_t m_ImmuneToStunAttackCount; diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index c03f58db..a91a1e2a 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -665,9 +665,14 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_DISMOUNT_COMPLETE: GameMessages::HandleDismountComplete(inStream, entity, sysAddr); break; - + case GAME_MSG_DEACTIVATE_BUBBLE_BUFF: + GameMessages::HandleDeactivateBubbleBuff(inStream, entity); + break; + case GAME_MSG_ACTIVATE_BUBBLE_BUFF: + GameMessages::HandleActivateBubbleBuff(inStream, entity); + break; default: - //Game::logger->Log("GameMessageHandler", "Unknown game message ID: %X", messageID); + // Game::logger->Log("GameMessageHandler", "Unknown game message ID: %i", messageID); break; } } diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index c6c7d2d1..7e9ea898 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -6084,3 +6084,43 @@ void GameMessages::HandleUpdatePlayerStatistic(RakNet::BitStream* inStream, Enti characterComponent->UpdatePlayerStatistic((StatisticID)updateID, (uint64_t)std::max(updateValue, int64_t(0))); } } + +void GameMessages::HandleDeactivateBubbleBuff(RakNet::BitStream* inStream, Entity* entity) { + auto controllablePhysicsComponent = entity->GetComponent<ControllablePhysicsComponent>(); + if (controllablePhysicsComponent) controllablePhysicsComponent->DeactivateBubbleBuff(); +} + +void GameMessages::HandleActivateBubbleBuff(RakNet::BitStream* inStream, Entity* entity) { + bool specialAnimations; + if (!inStream->Read(specialAnimations)) return; + + std::u16string type = GeneralUtils::ReadWString(inStream); + auto bubbleType = eBubbleType::DEFAULT; + if (type == u"skunk") bubbleType = eBubbleType::SKUNK; + else if (type == u"energy") bubbleType = eBubbleType::ENERGY; + + auto controllablePhysicsComponent = entity->GetComponent<ControllablePhysicsComponent>(); + if (controllablePhysicsComponent) controllablePhysicsComponent->ActivateBubbleBuff(bubbleType, specialAnimations); +} + +void GameMessages::SendActivateBubbleBuffFromServer(LWOOBJID objectId, const SystemAddress& sysAddr) { + CBITSTREAM; + CMSGHEADER; + + bitStream.Write(objectId); + bitStream.Write(GAME_MSG::GAME_MSG_ACTIVATE_BUBBLE_BUFF_FROM_SERVER); + + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET; +} + +void GameMessages::SendDeactivateBubbleBuffFromServer(LWOOBJID objectId, const SystemAddress& sysAddr) { + CBITSTREAM; + CMSGHEADER; + + bitStream.Write(objectId); + bitStream.Write(GAME_MSG::GAME_MSG_DEACTIVATE_BUBBLE_BUFF_FROM_SERVER); + + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; + SEND_PACKET; +} diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 6fa4e694..0675ae76 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -617,6 +617,15 @@ namespace GameMessages { void HandleReportBug(RakNet::BitStream* inStream, Entity* entity); void SendRemoveBuff(Entity* entity, bool fromUnEquip, bool removeImmunity, uint32_t buffId); + + // bubble + void HandleDeactivateBubbleBuff(RakNet::BitStream* inStream, Entity* entity); + + void HandleActivateBubbleBuff(RakNet::BitStream* inStream, Entity* entity); + + void SendActivateBubbleBuffFromServer(LWOOBJID objectId, const SystemAddress& sysAddr); + + void SendDeactivateBubbleBuffFromServer(LWOOBJID objectId, const SystemAddress& sysAddr); }; #endif // GAMEMESSAGES_H diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 9ee4c1e6..e6e29ceb 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -68,6 +68,7 @@ #include "AssetManager.h" #include "BinaryPathFinder.h" #include "dConfig.h" +#include "eBubbleType.h" #include "AMFFormat.h" #include "MovingPlatformComponent.h" #include "dMessageIdentifiers.h" From a28a2e60cfaeef09394e8d46e49f75248d8b4f25 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 6 Jan 2023 22:16:43 -0800 Subject: [PATCH 227/322] Add property Teleport behavior (#846) * Add property Teleport behavior Untested. Will mark pr as ready for review when this has been tested * Fix issues --- dGame/dBehaviors/Behavior.cpp | 5 +- dGame/dBehaviors/CMakeLists.txt | 1 + dGame/dBehaviors/PropertyTeleportBehavior.cpp | 61 +++++++++++++++++++ dGame/dBehaviors/PropertyTeleportBehavior.h | 21 +++++++ 4 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 dGame/dBehaviors/PropertyTeleportBehavior.cpp create mode 100644 dGame/dBehaviors/PropertyTeleportBehavior.h diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index 40c37a95..c8c1a1de 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -48,6 +48,7 @@ #include "PlayEffectBehavior.h" #include "DamageAbsorptionBehavior.h" #include "VentureVisionBehavior.h" +#include "PropertyTeleportBehavior.h" #include "BlockBehavior.h" #include "ClearTargetBehavior.h" #include "PullToPointBehavior.h" @@ -263,7 +264,9 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) { case BehaviorTemplates::BEHAVIOR_DAMAGE_REDUCTION: behavior = new DamageReductionBehavior(behaviorId); break; - case BehaviorTemplates::BEHAVIOR_PROPERTY_TELEPORT: break; + case BehaviorTemplates::BEHAVIOR_PROPERTY_TELEPORT: + behavior = new PropertyTeleportBehavior(behaviorId); + break; case BehaviorTemplates::BEHAVIOR_PROPERTY_CLEAR_TARGET: behavior = new ClearTargetBehavior(behaviorId); break; diff --git a/dGame/dBehaviors/CMakeLists.txt b/dGame/dBehaviors/CMakeLists.txt index e274872d..7b331fe0 100644 --- a/dGame/dBehaviors/CMakeLists.txt +++ b/dGame/dBehaviors/CMakeLists.txt @@ -35,6 +35,7 @@ set(DGAME_DBEHAVIORS_SOURCES "AirMovementBehavior.cpp" "OverTimeBehavior.cpp" "PlayEffectBehavior.cpp" "ProjectileAttackBehavior.cpp" + "PropertyTeleportBehavior.cpp" "PullToPointBehavior.cpp" "RemoveBuffBehavior.cpp" "RepairBehavior.cpp" diff --git a/dGame/dBehaviors/PropertyTeleportBehavior.cpp b/dGame/dBehaviors/PropertyTeleportBehavior.cpp new file mode 100644 index 00000000..447b085b --- /dev/null +++ b/dGame/dBehaviors/PropertyTeleportBehavior.cpp @@ -0,0 +1,61 @@ +#include "PropertyTeleportBehavior.h" + +#include "BehaviorBranchContext.h" +#include "BehaviorContext.h" +#include "Character.h" +#include "CharacterComponent.h" +#include "ChatPackets.h" +#include "WorldPackets.h" +#include "EntityManager.h" +#include "Game.h" +#include "ZoneInstanceManager.h" +#include "dZoneManager.h" + +void PropertyTeleportBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { + auto* caster = EntityManager::Instance()->GetEntity(context->caster); + if (!caster) return; + + auto* character = caster->GetCharacter(); + if (!character) return; + + LWOOBJID objId = caster->GetObjectID(); + + LWOMAPID targetMapId = m_MapId; + LWOCLONEID targetCloneId = character->GetPropertyCloneID(); + + if (dZoneManager::Instance()->GetZoneID().GetCloneID() == character->GetPropertyCloneID()) { + targetMapId = character->GetLastNonInstanceZoneID(); + targetCloneId = 0; + } else { + character->SetLastNonInstanceZoneID(dZoneManager::Instance()->GetZoneID().GetMapID()); + } + + ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, targetMapId, targetCloneId, false, [objId](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { + + auto* entity = EntityManager::Instance()->GetEntity(objId); + if (!entity) return; + + const auto sysAddr = entity->GetSystemAddress(); + + if (zoneClone != 0) ChatPackets::SendSystemMessage(sysAddr, u"Transfering to your property!"); + else ChatPackets::SendSystemMessage(sysAddr, u"Transfering back to previous world!"); + + Game::logger->Log("PropertyTeleportBehavior", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort); + if (entity->GetCharacter()) { + entity->GetCharacter()->SetZoneID(zoneID); + entity->GetCharacter()->SetZoneInstance(zoneInstance); + entity->GetCharacter()->SetZoneClone(zoneClone); + entity->GetComponent<CharacterComponent>()->SetLastRocketConfig(u""); + } + + entity->GetCharacter()->SaveXMLToDatabase(); + + WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift); + return; + }); +} + +void PropertyTeleportBehavior::Load() { + this->m_CancelIfInteracting = GetBoolean("cancel_if_interacting"); // TODO unused + this->m_MapId = LWOMAPID(GetInt("mapID")); +} diff --git a/dGame/dBehaviors/PropertyTeleportBehavior.h b/dGame/dBehaviors/PropertyTeleportBehavior.h new file mode 100644 index 00000000..74eed03b --- /dev/null +++ b/dGame/dBehaviors/PropertyTeleportBehavior.h @@ -0,0 +1,21 @@ +#pragma once +#include "Behavior.h" + +class PropertyTeleportBehavior final : public Behavior +{ +public: + /* + * Inherited + */ + + explicit PropertyTeleportBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { + } + + void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + + void Load() override; + +private: + LWOMAPID m_MapId; + bool m_CancelIfInteracting; +}; From a580e3a2f5edd0e2b90b693b036f9e66dad760df Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 6 Jan 2023 22:17:09 -0800 Subject: [PATCH 228/322] Update lookup command (#909) * Update lookup command * Fix bugs Update SlashCommandHandler.cpp --- dGame/dUtilities/SlashCommandHandler.cpp | 10 ++++++++-- docs/Commands.md | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index e6e29ceb..cc1c82a9 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -1198,11 +1198,17 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit EntityManager::Instance()->SerializeEntity(entity); } - if (chatCommand == "lookup" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) { + if (chatCommand == "lookup" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { auto query = CDClientDatabase::CreatePreppedStmt( "SELECT `id`, `name` FROM `Objects` WHERE `displayName` LIKE ?1 OR `name` LIKE ?1 OR `description` LIKE ?1 LIMIT 50"); + // Concatenate all of the arguments into a single query so a multi word query can be used properly. + std::string conditional = args[0]; + args.erase(args.begin()); + for (auto& argument : args) { + conditional += ' ' + argument; + } - const std::string query_text = "%" + args[0] + "%"; + const std::string query_text = "%" + conditional + "%"; query.bind(1, query_text.c_str()); auto tables = query.execQuery(); diff --git a/docs/Commands.md b/docs/Commands.md index 7c4f494f..7dc11ff1 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -78,7 +78,7 @@ These commands are primarily for development and testing. The usage of many of t |inspect|`/inspect <component> (-m <waypoint> \| -a <animation> \| -s \| -p \| -f (faction) \| -t)`|Finds the closest entity with the given component or LDF variable (ignoring players and racing cars), printing its ID, distance from the player, and whether it is sleeping, as well as the the IDs of all components the entity has. See [Detailed `/inspect` Usage](#detailed-inspect-usage) below.|8| |list-spawns|`/list-spawns`|Lists all the character spawn points in the zone. Additionally, this command will display the current scene that plays when the character lands in the next zone, if there is one.|8| |locrow|`/locrow`|Prints the your current position and rotation information to the console.|8| -|lookup|`/lookup <query>`|Searches through the Objects table in the client SQLite database for items whose display name, name, or description contains the query.|8| +|lookup|`/lookup <query>`|Searches through the Objects table in the client SQLite database for items whose display name, name, or description contains the query. Query can be multiple words delimited by spaces.|8| |playanimation|`/playanimation <id>`|Plays animation with given ID. Alias: `/playanim`.|8| |playeffect|`/playeffect <effect id> <effect type> <effect name>`|Plays an effect.|8| |playlvlfx|`/playlvlfx`|Plays the level up animation on your character.|8| From 8920cd106325f2c1d577f5c1089cf66bde14e34c Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 7 Jan 2023 01:48:59 -0800 Subject: [PATCH 229/322] Use field names instead of numbers for CDClient tables (#945) --- dDatabase/Tables/CDActivitiesTable.cpp | 39 ++-- dDatabase/Tables/CDActivityRewardsTable.cpp | 15 +- dDatabase/Tables/CDAnimationsTable.cpp | 27 +-- dDatabase/Tables/CDBehaviorParameterTable.cpp | 7 +- dDatabase/Tables/CDBehaviorTemplateTable.cpp | 7 +- dDatabase/Tables/CDBrickIDTableTable.cpp | 5 +- .../Tables/CDComponentsRegistryTable.cpp | 13 +- dDatabase/Tables/CDCurrencyTableTable.cpp | 11 +- .../Tables/CDDestructibleComponentTable.cpp | 29 +-- dDatabase/Tables/CDEmoteTable.cpp | 17 +- dDatabase/Tables/CDEmoteTable.h | 4 +- dDatabase/Tables/CDFeatureGatingTable.cpp | 11 +- .../Tables/CDInventoryComponentTable.cpp | 9 +- dDatabase/Tables/CDItemComponentTable.cpp | 169 +++++++++--------- dDatabase/Tables/CDItemSetSkillsTable.cpp | 7 +- dDatabase/Tables/CDItemSetsTable.cpp | 31 ++-- .../Tables/CDLevelProgressionLookupTable.cpp | 7 +- dDatabase/Tables/CDLootMatrixTable.cpp | 19 +- dDatabase/Tables/CDLootTableTable.cpp | 13 +- dDatabase/Tables/CDMissionEmailTable.cpp | 17 +- .../Tables/CDMissionNPCComponentTable.cpp | 11 +- dDatabase/Tables/CDMissionTasksTable.cpp | 27 +-- dDatabase/Tables/CDMissionsTable.cpp | 105 +++++------ .../Tables/CDMovementAIComponentTable.cpp | 17 +- dDatabase/Tables/CDObjectSkillsTable.cpp | 9 +- dDatabase/Tables/CDObjectsTable.cpp | 55 +++--- dDatabase/Tables/CDPackageComponentTable.cpp | 7 +- dDatabase/Tables/CDPhysicsComponentTable.cpp | 33 ++-- .../CDPropertyEntranceComponentTable.cpp | 11 +- dDatabase/Tables/CDPropertyTemplateTable.cpp | 9 +- .../CDProximityMonitorComponentTable.cpp | 9 +- dDatabase/Tables/CDRailActivatorComponent.cpp | 33 ++-- dDatabase/Tables/CDRarityTableTable.cpp | 9 +- dDatabase/Tables/CDRebuildComponentTable.cpp | 21 +-- dDatabase/Tables/CDRewardsTable.cpp | 13 +- dDatabase/Tables/CDScriptComponentTable.cpp | 7 +- dDatabase/Tables/CDSkillBehaviorTable.cpp | 39 ++-- dDatabase/Tables/CDVendorComponentTable.cpp | 11 +- dDatabase/Tables/CDZoneTableTable.cpp | 55 +++--- 39 files changed, 488 insertions(+), 450 deletions(-) diff --git a/dDatabase/Tables/CDActivitiesTable.cpp b/dDatabase/Tables/CDActivitiesTable.cpp index 835ca3d2..d6fa354e 100644 --- a/dDatabase/Tables/CDActivitiesTable.cpp +++ b/dDatabase/Tables/CDActivitiesTable.cpp @@ -21,25 +21,25 @@ CDActivitiesTable::CDActivitiesTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Activities"); while (!tableData.eof()) { CDActivities entry; - entry.ActivityID = tableData.getIntField(0, -1); - entry.locStatus = tableData.getIntField(1, -1); - entry.instanceMapID = tableData.getIntField(2, -1); - entry.minTeams = tableData.getIntField(3, -1); - entry.maxTeams = tableData.getIntField(4, -1); - entry.minTeamSize = tableData.getIntField(5, -1); - entry.maxTeamSize = tableData.getIntField(6, -1); - entry.waitTime = tableData.getIntField(7, -1); - entry.startDelay = tableData.getIntField(8, -1); - entry.requiresUniqueData = tableData.getIntField(9, -1); - entry.leaderboardType = tableData.getIntField(10, -1); - entry.localize = tableData.getIntField(11, -1); - entry.optionalCostLOT = tableData.getIntField(12, -1); - entry.optionalCostCount = tableData.getIntField(13, -1); - entry.showUIRewards = tableData.getIntField(14, -1); - entry.CommunityActivityFlagID = tableData.getIntField(15, -1); - entry.gate_version = tableData.getStringField(16, ""); - entry.noTeamLootOnDeath = tableData.getIntField(17, -1); - entry.optionalPercentage = tableData.getFloatField(18, -1.0f); + entry.ActivityID = tableData.getIntField("ActivityID", -1); + entry.locStatus = tableData.getIntField("locStatus", -1); + entry.instanceMapID = tableData.getIntField("instanceMapID", -1); + entry.minTeams = tableData.getIntField("minTeams", -1); + entry.maxTeams = tableData.getIntField("maxTeams", -1); + entry.minTeamSize = tableData.getIntField("minTeamSize", -1); + entry.maxTeamSize = tableData.getIntField("maxTeamSize", -1); + entry.waitTime = tableData.getIntField("waitTime", -1); + entry.startDelay = tableData.getIntField("startDelay", -1); + entry.requiresUniqueData = tableData.getIntField("requiresUniqueData", -1); + entry.leaderboardType = tableData.getIntField("leaderboardType", -1); + entry.localize = tableData.getIntField("localize", -1); + entry.optionalCostLOT = tableData.getIntField("optionalCostLOT", -1); + entry.optionalCostCount = tableData.getIntField("optionalCostCount", -1); + entry.showUIRewards = tableData.getIntField("showUIRewards", -1); + entry.CommunityActivityFlagID = tableData.getIntField("CommunityActivityFlagID", -1); + entry.gate_version = tableData.getStringField("gate_version", ""); + entry.noTeamLootOnDeath = tableData.getIntField("noTeamLootOnDeath", -1); + entry.optionalPercentage = tableData.getFloatField("optionalPercentage", -1.0f); this->entries.push_back(entry); tableData.nextRow(); @@ -70,3 +70,4 @@ std::vector<CDActivities> CDActivitiesTable::Query(std::function<bool(CDActiviti std::vector<CDActivities> CDActivitiesTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDActivityRewardsTable.cpp b/dDatabase/Tables/CDActivityRewardsTable.cpp index f1719204..3922d9fb 100644 --- a/dDatabase/Tables/CDActivityRewardsTable.cpp +++ b/dDatabase/Tables/CDActivityRewardsTable.cpp @@ -21,13 +21,13 @@ CDActivityRewardsTable::CDActivityRewardsTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ActivityRewards"); while (!tableData.eof()) { CDActivityRewards entry; - entry.objectTemplate = tableData.getIntField(0, -1); - entry.ActivityRewardIndex = tableData.getIntField(1, -1); - entry.activityRating = tableData.getIntField(2, -1); - entry.LootMatrixIndex = tableData.getIntField(3, -1); - entry.CurrencyIndex = tableData.getIntField(4, -1); - entry.ChallengeRating = tableData.getIntField(5, -1); - entry.description = tableData.getStringField(6, ""); + entry.objectTemplate = tableData.getIntField("objectTemplate", -1); + entry.ActivityRewardIndex = tableData.getIntField("ActivityRewardIndex", -1); + entry.activityRating = tableData.getIntField("activityRating", -1); + entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); + entry.CurrencyIndex = tableData.getIntField("CurrencyIndex", -1); + entry.ChallengeRating = tableData.getIntField("ChallengeRating", -1); + entry.description = tableData.getStringField("description", ""); this->entries.push_back(entry); tableData.nextRow(); @@ -58,3 +58,4 @@ std::vector<CDActivityRewards> CDActivityRewardsTable::Query(std::function<bool( std::vector<CDActivityRewards> CDActivityRewardsTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDAnimationsTable.cpp b/dDatabase/Tables/CDAnimationsTable.cpp index 399804f8..e21d44c5 100644 --- a/dDatabase/Tables/CDAnimationsTable.cpp +++ b/dDatabase/Tables/CDAnimationsTable.cpp @@ -21,19 +21,19 @@ CDAnimationsTable::CDAnimationsTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Animations"); while (!tableData.eof()) { CDAnimations entry; - entry.animationGroupID = tableData.getIntField(0, -1); - entry.animation_type = tableData.getStringField(1, ""); - entry.animation_name = tableData.getStringField(2, ""); - entry.chance_to_play = tableData.getFloatField(3, -1.0f); - entry.min_loops = tableData.getIntField(4, -1); - entry.max_loops = tableData.getIntField(5, -1); - entry.animation_length = tableData.getFloatField(6, -1.0f); - entry.hideEquip = tableData.getIntField(7, -1) == 1 ? true : false; - entry.ignoreUpperBody = tableData.getIntField(8, -1) == 1 ? true : false; - entry.restartable = tableData.getIntField(9, -1) == 1 ? true : false; - entry.face_animation_name = tableData.getStringField(10, ""); - entry.priority = tableData.getFloatField(11, -1.0f); - entry.blendTime = tableData.getFloatField(12, -1.0f); + entry.animationGroupID = tableData.getIntField("animationGroupID", -1); + entry.animation_type = tableData.getStringField("animation_type", ""); + entry.animation_name = tableData.getStringField("animation_name", ""); + entry.chance_to_play = tableData.getFloatField("chance_to_play", -1.0f); + entry.min_loops = tableData.getIntField("min_loops", -1); + entry.max_loops = tableData.getIntField("max_loops", -1); + entry.animation_length = tableData.getFloatField("animation_length", -1.0f); + entry.hideEquip = tableData.getIntField("hideEquip", -1) == 1 ? true : false; + entry.ignoreUpperBody = tableData.getIntField("ignoreUpperBody", -1) == 1 ? true : false; + entry.restartable = tableData.getIntField("restartable", -1) == 1 ? true : false; + entry.face_animation_name = tableData.getStringField("face_animation_name", ""); + entry.priority = tableData.getFloatField("priority", -1.0f); + entry.blendTime = tableData.getFloatField("blendTime", -1.0f); this->entries.push_back(entry); tableData.nextRow(); @@ -64,3 +64,4 @@ std::vector<CDAnimations> CDAnimationsTable::Query(std::function<bool(CDAnimatio std::vector<CDAnimations> CDAnimationsTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDBehaviorParameterTable.cpp b/dDatabase/Tables/CDBehaviorParameterTable.cpp index d09a71b2..b894688b 100644 --- a/dDatabase/Tables/CDBehaviorParameterTable.cpp +++ b/dDatabase/Tables/CDBehaviorParameterTable.cpp @@ -8,8 +8,8 @@ CDBehaviorParameterTable::CDBehaviorParameterTable(void) { uint64_t hash = 0; while (!tableData.eof()) { CDBehaviorParameter entry; - entry.behaviorID = tableData.getIntField(0, -1); - auto candidateStringToAdd = std::string(tableData.getStringField(1, "")); + entry.behaviorID = tableData.getIntField("behaviorID", -1); + auto candidateStringToAdd = std::string(tableData.getStringField("parameterID", "")); auto parameter = m_ParametersList.find(candidateStringToAdd); if (parameter != m_ParametersList.end()) { entry.parameterID = parameter; @@ -19,7 +19,7 @@ CDBehaviorParameterTable::CDBehaviorParameterTable(void) { } hash = entry.behaviorID; hash = (hash << 31U) | entry.parameterID->second; - entry.value = tableData.getFloatField(2, -1.0f); + entry.value = tableData.getFloatField("value", -1.0f); m_Entries.insert(std::make_pair(hash, entry)); @@ -62,3 +62,4 @@ std::map<std::string, float> CDBehaviorParameterTable::GetParametersByBehaviorID } return returnInfo; } + diff --git a/dDatabase/Tables/CDBehaviorTemplateTable.cpp b/dDatabase/Tables/CDBehaviorTemplateTable.cpp index 1628756f..4adb9bce 100644 --- a/dDatabase/Tables/CDBehaviorTemplateTable.cpp +++ b/dDatabase/Tables/CDBehaviorTemplateTable.cpp @@ -21,9 +21,9 @@ CDBehaviorTemplateTable::CDBehaviorTemplateTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorTemplate"); while (!tableData.eof()) { CDBehaviorTemplate entry; - entry.behaviorID = tableData.getIntField(0, -1); - entry.templateID = tableData.getIntField(1, -1); - entry.effectID = tableData.getIntField(2, -1); + entry.behaviorID = tableData.getIntField("behaviorID", -1); + entry.templateID = tableData.getIntField("templateID", -1); + entry.effectID = tableData.getIntField("effectID", -1); auto candidateToAdd = tableData.getStringField(3, ""); auto parameter = m_EffectHandles.find(candidateToAdd); if (parameter != m_EffectHandles.end()) { @@ -75,3 +75,4 @@ const CDBehaviorTemplate CDBehaviorTemplateTable::GetByBehaviorID(uint32_t behav return entry->second; } } + diff --git a/dDatabase/Tables/CDBrickIDTableTable.cpp b/dDatabase/Tables/CDBrickIDTableTable.cpp index 9dbdf2c0..7cd3e86f 100644 --- a/dDatabase/Tables/CDBrickIDTableTable.cpp +++ b/dDatabase/Tables/CDBrickIDTableTable.cpp @@ -21,8 +21,8 @@ CDBrickIDTableTable::CDBrickIDTableTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BrickIDTable"); while (!tableData.eof()) { CDBrickIDTable entry; - entry.NDObjectID = tableData.getIntField(0, -1); - entry.LEGOBrickID = tableData.getIntField(1, -1); + entry.NDObjectID = tableData.getIntField("NDObjectID", -1); + entry.LEGOBrickID = tableData.getIntField("LEGOBrickID", -1); this->entries.push_back(entry); tableData.nextRow(); @@ -53,3 +53,4 @@ std::vector<CDBrickIDTable> CDBrickIDTableTable::Query(std::function<bool(CDBric std::vector<CDBrickIDTable> CDBrickIDTableTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDComponentsRegistryTable.cpp b/dDatabase/Tables/CDComponentsRegistryTable.cpp index 8e5ae108..987c66ab 100644 --- a/dDatabase/Tables/CDComponentsRegistryTable.cpp +++ b/dDatabase/Tables/CDComponentsRegistryTable.cpp @@ -24,9 +24,9 @@ CDComponentsRegistryTable::CDComponentsRegistryTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ComponentsRegistry"); while (!tableData.eof()) { CDComponentsRegistry entry; - entry.id = tableData.getIntField(0, -1); - entry.component_type = tableData.getIntField(1, -1); - entry.component_id = tableData.getIntField(2, -1); + entry.id = tableData.getIntField("id", -1); + entry.component_type = tableData.getIntField("component_type", -1); + entry.component_id = tableData.getIntField("component_id", -1); this->mappedEntries.insert_or_assign(((uint64_t)entry.component_type) << 32 | ((uint64_t)entry.id), entry.component_id); @@ -91,9 +91,9 @@ int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, uint32_t componen auto tableData = CDClientDatabase::ExecuteQuery(query.str()); while (!tableData.eof()) { CDComponentsRegistry entry; - entry.id = tableData.getIntField(0, -1); - entry.component_type = tableData.getIntField(1, -1); - entry.component_id = tableData.getIntField(2, -1); + entry.id = tableData.getIntField("id", -1); + entry.component_type = tableData.getIntField("component_type", -1); + entry.component_id = tableData.getIntField("component_id", -1); //this->entries.push_back(entry); @@ -126,3 +126,4 @@ int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, uint32_t componen return defaultValue; #endif } + diff --git a/dDatabase/Tables/CDCurrencyTableTable.cpp b/dDatabase/Tables/CDCurrencyTableTable.cpp index a1923a73..21870f00 100644 --- a/dDatabase/Tables/CDCurrencyTableTable.cpp +++ b/dDatabase/Tables/CDCurrencyTableTable.cpp @@ -21,11 +21,11 @@ CDCurrencyTableTable::CDCurrencyTableTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM CurrencyTable"); while (!tableData.eof()) { CDCurrencyTable entry; - entry.currencyIndex = tableData.getIntField(0, -1); - entry.npcminlevel = tableData.getIntField(1, -1); - entry.minvalue = tableData.getIntField(2, -1); - entry.maxvalue = tableData.getIntField(3, -1); - entry.id = tableData.getIntField(4, -1); + entry.currencyIndex = tableData.getIntField("currencyIndex", -1); + entry.npcminlevel = tableData.getIntField("npcminlevel", -1); + entry.minvalue = tableData.getIntField("minvalue", -1); + entry.maxvalue = tableData.getIntField("maxvalue", -1); + entry.id = tableData.getIntField("id", -1); this->entries.push_back(entry); tableData.nextRow(); @@ -56,3 +56,4 @@ std::vector<CDCurrencyTable> CDCurrencyTableTable::Query(std::function<bool(CDCu std::vector<CDCurrencyTable> CDCurrencyTableTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDDestructibleComponentTable.cpp b/dDatabase/Tables/CDDestructibleComponentTable.cpp index d7438fc7..2480fc24 100644 --- a/dDatabase/Tables/CDDestructibleComponentTable.cpp +++ b/dDatabase/Tables/CDDestructibleComponentTable.cpp @@ -21,20 +21,20 @@ CDDestructibleComponentTable::CDDestructibleComponentTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM DestructibleComponent"); while (!tableData.eof()) { CDDestructibleComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.faction = tableData.getIntField(1, -1); - entry.factionList = tableData.getStringField(2, ""); - entry.life = tableData.getIntField(3, -1); - entry.imagination = tableData.getIntField(4, -1); - entry.LootMatrixIndex = tableData.getIntField(5, -1); - entry.CurrencyIndex = tableData.getIntField(6, -1); - entry.level = tableData.getIntField(7, -1); - entry.armor = tableData.getFloatField(8, -1.0f); - entry.death_behavior = tableData.getIntField(9, -1); - entry.isnpc = tableData.getIntField(10, -1) == 1 ? true : false; - entry.attack_priority = tableData.getIntField(11, -1); - entry.isSmashable = tableData.getIntField(12, -1) == 1 ? true : false; - entry.difficultyLevel = tableData.getIntField(13, -1); + entry.id = tableData.getIntField("id", -1); + entry.faction = tableData.getIntField("faction", -1); + entry.factionList = tableData.getStringField("factionList", ""); + entry.life = tableData.getIntField("life", -1); + entry.imagination = tableData.getIntField("imagination", -1); + entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); + entry.CurrencyIndex = tableData.getIntField("CurrencyIndex", -1); + entry.level = tableData.getIntField("level", -1); + entry.armor = tableData.getFloatField("armor", -1.0f); + entry.death_behavior = tableData.getIntField("death_behavior", -1); + entry.isnpc = tableData.getIntField("isnpc", -1) == 1 ? true : false; + entry.attack_priority = tableData.getIntField("attack_priority", -1); + entry.isSmashable = tableData.getIntField("isSmashable", -1) == 1 ? true : false; + entry.difficultyLevel = tableData.getIntField("difficultyLevel", -1); this->entries.push_back(entry); tableData.nextRow(); @@ -65,3 +65,4 @@ std::vector<CDDestructibleComponent> CDDestructibleComponentTable::Query(std::fu std::vector<CDDestructibleComponent> CDDestructibleComponentTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDEmoteTable.cpp b/dDatabase/Tables/CDEmoteTable.cpp index e3898422..b97e02e8 100644 --- a/dDatabase/Tables/CDEmoteTable.cpp +++ b/dDatabase/Tables/CDEmoteTable.cpp @@ -5,14 +5,14 @@ CDEmoteTableTable::CDEmoteTableTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Emotes"); while (!tableData.eof()) { CDEmoteTable* entry = new CDEmoteTable(); - entry->ID = tableData.getIntField(0, -1); - entry->animationName = tableData.getStringField(1, ""); - entry->iconFilename = tableData.getStringField(2, ""); - entry->channel = tableData.getIntField(3, -1); - entry->locked = tableData.getIntField(5, -1) != 0; - entry->localize = tableData.getIntField(6, -1) != 0; - entry->locState = tableData.getIntField(7, -1); - entry->gateVersion = tableData.getIntField(8, -1); + entry->ID = tableData.getIntField("id", -1); + entry->animationName = tableData.getStringField("animationName", ""); + entry->iconFilename = tableData.getStringField("iconFilename", ""); + entry->channel = tableData.getIntField("channel", -1); + entry->locked = tableData.getIntField("locked", -1) != 0; + entry->localize = tableData.getIntField("localize", -1) != 0; + entry->locState = tableData.getIntField("locStatus", -1); + entry->gateVersion = tableData.getStringField("gate_version", ""); entries.insert(std::make_pair(entry->ID, entry)); tableData.nextRow(); @@ -42,3 +42,4 @@ CDEmoteTable* CDEmoteTableTable::GetEmote(int id) { return nullptr; } + diff --git a/dDatabase/Tables/CDEmoteTable.h b/dDatabase/Tables/CDEmoteTable.h index a22ae23e..1f4fb246 100644 --- a/dDatabase/Tables/CDEmoteTable.h +++ b/dDatabase/Tables/CDEmoteTable.h @@ -19,7 +19,7 @@ struct CDEmoteTable { channel = -1; locked = false; localize = false; - gateVersion = -1; + gateVersion = ""; } int ID; @@ -29,7 +29,7 @@ struct CDEmoteTable { int channel; bool locked; bool localize; - int gateVersion; + std::string gateVersion; }; //! CDEmoteTable table diff --git a/dDatabase/Tables/CDFeatureGatingTable.cpp b/dDatabase/Tables/CDFeatureGatingTable.cpp index dfc65387..0abcdb25 100644 --- a/dDatabase/Tables/CDFeatureGatingTable.cpp +++ b/dDatabase/Tables/CDFeatureGatingTable.cpp @@ -21,11 +21,11 @@ CDFeatureGatingTable::CDFeatureGatingTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM FeatureGating"); while (!tableData.eof()) { CDFeatureGating entry; - entry.featureName = tableData.getStringField(0, ""); - entry.major = tableData.getIntField(1, -1); - entry.current = tableData.getIntField(2, -1); - entry.minor = tableData.getIntField(3, -1); - entry.description = tableData.getStringField(4, ""); + entry.featureName = tableData.getStringField("featureName", ""); + entry.major = tableData.getIntField("major", -1); + entry.current = tableData.getIntField("current", -1); + entry.minor = tableData.getIntField("minor", -1); + entry.description = tableData.getStringField("description", ""); this->entries.push_back(entry); tableData.nextRow(); @@ -66,3 +66,4 @@ bool CDFeatureGatingTable::FeatureUnlocked(const std::string& feature) const { std::vector<CDFeatureGating> CDFeatureGatingTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDInventoryComponentTable.cpp b/dDatabase/Tables/CDInventoryComponentTable.cpp index 65f09c9b..cf956775 100644 --- a/dDatabase/Tables/CDInventoryComponentTable.cpp +++ b/dDatabase/Tables/CDInventoryComponentTable.cpp @@ -21,10 +21,10 @@ CDInventoryComponentTable::CDInventoryComponentTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM InventoryComponent"); while (!tableData.eof()) { CDInventoryComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.itemid = tableData.getIntField(1, -1); - entry.count = tableData.getIntField(2, -1); - entry.equip = tableData.getIntField(3, -1) == 1 ? true : false; + entry.id = tableData.getIntField("id", -1); + entry.itemid = tableData.getIntField("itemid", -1); + entry.count = tableData.getIntField("count", -1); + entry.equip = tableData.getIntField("equip", -1) == 1 ? true : false; this->entries.push_back(entry); tableData.nextRow(); @@ -55,3 +55,4 @@ std::vector<CDInventoryComponent> CDInventoryComponentTable::Query(std::function std::vector<CDInventoryComponent> CDInventoryComponentTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDItemComponentTable.cpp b/dDatabase/Tables/CDItemComponentTable.cpp index 6ff192fd..a3cb4159 100644 --- a/dDatabase/Tables/CDItemComponentTable.cpp +++ b/dDatabase/Tables/CDItemComponentTable.cpp @@ -23,48 +23,48 @@ CDItemComponentTable::CDItemComponentTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemComponent"); while (!tableData.eof()) { CDItemComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.equipLocation = tableData.getStringField(1, ""); - entry.baseValue = tableData.getIntField(2, -1); - entry.isKitPiece = tableData.getIntField(3, -1) == 1 ? true : false; - entry.rarity = tableData.getIntField(4, 0); - entry.itemType = tableData.getIntField(5, -1); - entry.itemInfo = tableData.getInt64Field(6, -1); - entry.inLootTable = tableData.getIntField(7, -1) == 1 ? true : false; - entry.inVendor = tableData.getIntField(8, -1) == 1 ? true : false; - entry.isUnique = tableData.getIntField(9, -1) == 1 ? true : false; - entry.isBOP = tableData.getIntField(10, -1) == 1 ? true : false; - entry.isBOE = tableData.getIntField(11, -1) == 1 ? true : false; - entry.reqFlagID = tableData.getIntField(12, -1); - entry.reqSpecialtyID = tableData.getIntField(13, -1); - entry.reqSpecRank = tableData.getIntField(14, -1); - entry.reqAchievementID = tableData.getIntField(15, -1); - entry.stackSize = tableData.getIntField(16, -1); - entry.color1 = tableData.getIntField(17, -1); - entry.decal = tableData.getIntField(18, -1); - entry.offsetGroupID = tableData.getIntField(19, -1); - entry.buildTypes = tableData.getIntField(20, -1); - entry.reqPrecondition = tableData.getStringField(21, ""); - entry.animationFlag = tableData.getIntField(22, 0); - entry.equipEffects = tableData.getIntField(23, -1); - entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; - entry.itemRating = tableData.getIntField(25, -1); - entry.isTwoHanded = tableData.getIntField(26, -1) == 1 ? true : false; - entry.minNumRequired = tableData.getIntField(27, -1); - entry.delResIndex = tableData.getIntField(28, -1); - entry.currencyLOT = tableData.getIntField(29, -1); - entry.altCurrencyCost = tableData.getIntField(30, -1); - entry.subItems = tableData.getStringField(31, ""); - entry.audioEventUse = tableData.getStringField(32, ""); - entry.noEquipAnimation = tableData.getIntField(33, -1) == 1 ? true : false; - entry.commendationLOT = tableData.getIntField(34, -1); - entry.commendationCost = tableData.getIntField(35, -1); - entry.audioEquipMetaEventSet = tableData.getStringField(36, ""); - entry.currencyCosts = tableData.getStringField(37, ""); - entry.ingredientInfo = tableData.getStringField(38, ""); - entry.locStatus = tableData.getIntField(39, -1); - entry.forgeType = tableData.getIntField(40, -1); - entry.SellMultiplier = tableData.getFloatField(41, -1.0f); + entry.id = tableData.getIntField("id", -1); + entry.equipLocation = tableData.getStringField("equipLocation", ""); + entry.baseValue = tableData.getIntField("baseValue", -1); + entry.isKitPiece = tableData.getIntField("isKitPiece", -1) == 1 ? true : false; + entry.rarity = tableData.getIntField("rarity", 0); + entry.itemType = tableData.getIntField("itemType", -1); + entry.itemInfo = tableData.getInt64Field("itemInfo", -1); + entry.inLootTable = tableData.getIntField("inLootTable", -1) == 1 ? true : false; + entry.inVendor = tableData.getIntField("inVendor", -1) == 1 ? true : false; + entry.isUnique = tableData.getIntField("isUnique", -1) == 1 ? true : false; + entry.isBOP = tableData.getIntField("isBOP", -1) == 1 ? true : false; + entry.isBOE = tableData.getIntField("isBOE", -1) == 1 ? true : false; + entry.reqFlagID = tableData.getIntField("reqFlagID", -1); + entry.reqSpecialtyID = tableData.getIntField("reqSpecialtyID", -1); + entry.reqSpecRank = tableData.getIntField("reqSpecRank", -1); + entry.reqAchievementID = tableData.getIntField("reqAchievementID", -1); + entry.stackSize = tableData.getIntField("stackSize", -1); + entry.color1 = tableData.getIntField("color1", -1); + entry.decal = tableData.getIntField("decal", -1); + entry.offsetGroupID = tableData.getIntField("offsetGroupID", -1); + entry.buildTypes = tableData.getIntField("buildTypes", -1); + entry.reqPrecondition = tableData.getStringField("reqPrecondition", ""); + entry.animationFlag = tableData.getIntField("animationFlag", 0); + entry.equipEffects = tableData.getIntField("equipEffects", -1); + entry.readyForQA = tableData.getIntField("readyForQA", -1) == 1 ? true : false; + entry.itemRating = tableData.getIntField("itemRating", -1); + entry.isTwoHanded = tableData.getIntField("isTwoHanded", -1) == 1 ? true : false; + entry.minNumRequired = tableData.getIntField("minNumRequired", -1); + entry.delResIndex = tableData.getIntField("delResIndex", -1); + entry.currencyLOT = tableData.getIntField("currencyLOT", -1); + entry.altCurrencyCost = tableData.getIntField("altCurrencyCost", -1); + entry.subItems = tableData.getStringField("subItems", ""); + entry.audioEventUse = tableData.getStringField("audioEventUse", ""); + entry.noEquipAnimation = tableData.getIntField("noEquipAnimation", -1) == 1 ? true : false; + entry.commendationLOT = tableData.getIntField("commendationLOT", -1); + entry.commendationCost = tableData.getIntField("commendationCost", -1); + entry.audioEquipMetaEventSet = tableData.getStringField("audioEquipMetaEventSet", ""); + entry.currencyCosts = tableData.getStringField("currencyCosts", ""); + entry.ingredientInfo = tableData.getStringField("ingredientInfo", ""); + entry.locStatus = tableData.getIntField("locStatus", -1); + entry.forgeType = tableData.getIntField("forgeType", -1); + entry.SellMultiplier = tableData.getFloatField("SellMultiplier", -1.0f); this->entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); @@ -101,48 +101,48 @@ const CDItemComponent& CDItemComponentTable::GetItemComponentByID(unsigned int s while (!tableData.eof()) { CDItemComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.equipLocation = tableData.getStringField(1, ""); - entry.baseValue = tableData.getIntField(2, -1); - entry.isKitPiece = tableData.getIntField(3, -1) == 1 ? true : false; - entry.rarity = tableData.getIntField(4, 0); - entry.itemType = tableData.getIntField(5, -1); - entry.itemInfo = tableData.getInt64Field(6, -1); - entry.inLootTable = tableData.getIntField(7, -1) == 1 ? true : false; - entry.inVendor = tableData.getIntField(8, -1) == 1 ? true : false; - entry.isUnique = tableData.getIntField(9, -1) == 1 ? true : false; - entry.isBOP = tableData.getIntField(10, -1) == 1 ? true : false; - entry.isBOE = tableData.getIntField(11, -1) == 1 ? true : false; - entry.reqFlagID = tableData.getIntField(12, -1); - entry.reqSpecialtyID = tableData.getIntField(13, -1); - entry.reqSpecRank = tableData.getIntField(14, -1); - entry.reqAchievementID = tableData.getIntField(15, -1); - entry.stackSize = tableData.getIntField(16, -1); - entry.color1 = tableData.getIntField(17, -1); - entry.decal = tableData.getIntField(18, -1); - entry.offsetGroupID = tableData.getIntField(19, -1); - entry.buildTypes = tableData.getIntField(20, -1); - entry.reqPrecondition = tableData.getStringField(21, ""); - entry.animationFlag = tableData.getIntField(22, 0); - entry.equipEffects = tableData.getIntField(23, -1); - entry.readyForQA = tableData.getIntField(24, -1) == 1 ? true : false; - entry.itemRating = tableData.getIntField(25, -1); - entry.isTwoHanded = tableData.getIntField(26, -1) == 1 ? true : false; - entry.minNumRequired = tableData.getIntField(27, -1); - entry.delResIndex = tableData.getIntField(28, -1); - entry.currencyLOT = tableData.getIntField(29, -1); - entry.altCurrencyCost = tableData.getIntField(30, -1); - entry.subItems = tableData.getStringField(31, ""); - UNUSED(entry.audioEventUse = tableData.getStringField(32, "")); - entry.noEquipAnimation = tableData.getIntField(33, -1) == 1 ? true : false; - entry.commendationLOT = tableData.getIntField(34, -1); - entry.commendationCost = tableData.getIntField(35, -1); - UNUSED(entry.audioEquipMetaEventSet = tableData.getStringField(36, "")); - entry.currencyCosts = tableData.getStringField(37, ""); - UNUSED(entry.ingredientInfo = tableData.getStringField(38, "")); - entry.locStatus = tableData.getIntField(39, -1); - entry.forgeType = tableData.getIntField(40, -1); - entry.SellMultiplier = tableData.getFloatField(41, -1.0f); + entry.id = tableData.getIntField("id", -1); + entry.equipLocation = tableData.getStringField("equipLocation", ""); + entry.baseValue = tableData.getIntField("baseValue", -1); + entry.isKitPiece = tableData.getIntField("isKitPiece", -1) == 1 ? true : false; + entry.rarity = tableData.getIntField("rarity", 0); + entry.itemType = tableData.getIntField("itemType", -1); + entry.itemInfo = tableData.getInt64Field("itemInfo", -1); + entry.inLootTable = tableData.getIntField("inLootTable", -1) == 1 ? true : false; + entry.inVendor = tableData.getIntField("inVendor", -1) == 1 ? true : false; + entry.isUnique = tableData.getIntField("isUnique", -1) == 1 ? true : false; + entry.isBOP = tableData.getIntField("isBOP", -1) == 1 ? true : false; + entry.isBOE = tableData.getIntField("isBOE", -1) == 1 ? true : false; + entry.reqFlagID = tableData.getIntField("reqFlagID", -1); + entry.reqSpecialtyID = tableData.getIntField("reqSpecialtyID", -1); + entry.reqSpecRank = tableData.getIntField("reqSpecRank", -1); + entry.reqAchievementID = tableData.getIntField("reqAchievementID", -1); + entry.stackSize = tableData.getIntField("stackSize", -1); + entry.color1 = tableData.getIntField("color1", -1); + entry.decal = tableData.getIntField("decal", -1); + entry.offsetGroupID = tableData.getIntField("offsetGroupID", -1); + entry.buildTypes = tableData.getIntField("buildTypes", -1); + entry.reqPrecondition = tableData.getStringField("reqPrecondition", ""); + entry.animationFlag = tableData.getIntField("animationFlag", 0); + entry.equipEffects = tableData.getIntField("equipEffects", -1); + entry.readyForQA = tableData.getIntField("readyForQA", -1) == 1 ? true : false; + entry.itemRating = tableData.getIntField("itemRating", -1); + entry.isTwoHanded = tableData.getIntField("isTwoHanded", -1) == 1 ? true : false; + entry.minNumRequired = tableData.getIntField("minNumRequired", -1); + entry.delResIndex = tableData.getIntField("delResIndex", -1); + entry.currencyLOT = tableData.getIntField("currencyLOT", -1); + entry.altCurrencyCost = tableData.getIntField("altCurrencyCost", -1); + entry.subItems = tableData.getStringField("subItems", ""); + UNUSED(entry.audioEventUse = tableData.getStringField("audioEventUse", "")); + entry.noEquipAnimation = tableData.getIntField("noEquipAnimation", -1) == 1 ? true : false; + entry.commendationLOT = tableData.getIntField("commendationLOT", -1); + entry.commendationCost = tableData.getIntField("commendationCost", -1); + UNUSED(entry.audioEquipMetaEventSet = tableData.getStringField("audioEquipMetaEventSet", "")); + entry.currencyCosts = tableData.getStringField("currencyCosts", ""); + UNUSED(entry.ingredientInfo = tableData.getStringField("ingredientInfo", "")); + entry.locStatus = tableData.getIntField("locStatus", -1); + entry.forgeType = tableData.getIntField("forgeType", -1); + entry.SellMultiplier = tableData.getFloatField("SellMultiplier", -1.0f); this->entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); @@ -177,3 +177,4 @@ std::map<LOT, uint32_t> CDItemComponentTable::ParseCraftingCurrencies(const CDIt return currencies; } + diff --git a/dDatabase/Tables/CDItemSetSkillsTable.cpp b/dDatabase/Tables/CDItemSetSkillsTable.cpp index e94cf527..107e25d9 100644 --- a/dDatabase/Tables/CDItemSetSkillsTable.cpp +++ b/dDatabase/Tables/CDItemSetSkillsTable.cpp @@ -21,9 +21,9 @@ CDItemSetSkillsTable::CDItemSetSkillsTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSetSkills"); while (!tableData.eof()) { CDItemSetSkills entry; - entry.SkillSetID = tableData.getIntField(0, -1); - entry.SkillID = tableData.getIntField(1, -1); - entry.SkillCastType = tableData.getIntField(2, -1); + entry.SkillSetID = tableData.getIntField("SkillSetID", -1); + entry.SkillID = tableData.getIntField("SkillID", -1); + entry.SkillCastType = tableData.getIntField("SkillCastType", -1); this->entries.push_back(entry); tableData.nextRow(); @@ -65,3 +65,4 @@ std::vector<CDItemSetSkills> CDItemSetSkillsTable::GetBySkillID(unsigned int Ski return toReturn; } + diff --git a/dDatabase/Tables/CDItemSetsTable.cpp b/dDatabase/Tables/CDItemSetsTable.cpp index 606e0cf9..1f9d7409 100644 --- a/dDatabase/Tables/CDItemSetsTable.cpp +++ b/dDatabase/Tables/CDItemSetsTable.cpp @@ -21,21 +21,21 @@ CDItemSetsTable::CDItemSetsTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSets"); while (!tableData.eof()) { CDItemSets entry; - entry.setID = tableData.getIntField(0, -1); - entry.locStatus = tableData.getIntField(1, -1); - entry.itemIDs = tableData.getStringField(2, ""); - entry.kitType = tableData.getIntField(3, -1); - entry.kitRank = tableData.getIntField(4, -1); - entry.kitImage = tableData.getIntField(5, -1); - entry.skillSetWith2 = tableData.getIntField(6, -1); - entry.skillSetWith3 = tableData.getIntField(7, -1); - entry.skillSetWith4 = tableData.getIntField(8, -1); - entry.skillSetWith5 = tableData.getIntField(9, -1); - entry.skillSetWith6 = tableData.getIntField(10, -1); - entry.localize = tableData.getIntField(11, -1) == 1 ? true : false; - entry.gate_version = tableData.getStringField(12, ""); - entry.kitID = tableData.getIntField(13, -1); - entry.priority = tableData.getFloatField(14, -1.0f); + entry.setID = tableData.getIntField("setID", -1); + entry.locStatus = tableData.getIntField("locStatus", -1); + entry.itemIDs = tableData.getStringField("itemIDs", ""); + entry.kitType = tableData.getIntField("kitType", -1); + entry.kitRank = tableData.getIntField("kitRank", -1); + entry.kitImage = tableData.getIntField("kitImage", -1); + entry.skillSetWith2 = tableData.getIntField("skillSetWith2", -1); + entry.skillSetWith3 = tableData.getIntField("skillSetWith3", -1); + entry.skillSetWith4 = tableData.getIntField("skillSetWith4", -1); + entry.skillSetWith5 = tableData.getIntField("skillSetWith5", -1); + entry.skillSetWith6 = tableData.getIntField("skillSetWith6", -1); + entry.localize = tableData.getIntField("localize", -1) == 1 ? true : false; + entry.gate_version = tableData.getStringField("gate_version", ""); + entry.kitID = tableData.getIntField("kitID", -1); + entry.priority = tableData.getFloatField("priority", -1.0f); this->entries.push_back(entry); tableData.nextRow(); @@ -66,3 +66,4 @@ std::vector<CDItemSets> CDItemSetsTable::Query(std::function<bool(CDItemSets)> p std::vector<CDItemSets> CDItemSetsTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDLevelProgressionLookupTable.cpp b/dDatabase/Tables/CDLevelProgressionLookupTable.cpp index 121c9f62..b3231308 100644 --- a/dDatabase/Tables/CDLevelProgressionLookupTable.cpp +++ b/dDatabase/Tables/CDLevelProgressionLookupTable.cpp @@ -21,9 +21,9 @@ CDLevelProgressionLookupTable::CDLevelProgressionLookupTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LevelProgressionLookup"); while (!tableData.eof()) { CDLevelProgressionLookup entry; - entry.id = tableData.getIntField(0, -1); - entry.requiredUScore = tableData.getIntField(1, -1); - entry.BehaviorEffect = tableData.getStringField(2, ""); + entry.id = tableData.getIntField("id", -1); + entry.requiredUScore = tableData.getIntField("requiredUScore", -1); + entry.BehaviorEffect = tableData.getStringField("BehaviorEffect", ""); this->entries.push_back(entry); tableData.nextRow(); @@ -54,3 +54,4 @@ std::vector<CDLevelProgressionLookup> CDLevelProgressionLookupTable::Query(std:: std::vector<CDLevelProgressionLookup> CDLevelProgressionLookupTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDLootMatrixTable.cpp b/dDatabase/Tables/CDLootMatrixTable.cpp index d47c081b..93a2fda1 100644 --- a/dDatabase/Tables/CDLootMatrixTable.cpp +++ b/dDatabase/Tables/CDLootMatrixTable.cpp @@ -21,15 +21,15 @@ CDLootMatrixTable::CDLootMatrixTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootMatrix"); while (!tableData.eof()) { CDLootMatrix entry; - entry.LootMatrixIndex = tableData.getIntField(0, -1); - entry.LootTableIndex = tableData.getIntField(1, -1); - entry.RarityTableIndex = tableData.getIntField(2, -1); - entry.percent = tableData.getFloatField(3, -1.0f); - entry.minToDrop = tableData.getIntField(4, -1); - entry.maxToDrop = tableData.getIntField(5, -1); - entry.id = tableData.getIntField(6, -1); - entry.flagID = tableData.getIntField(7, -1); - UNUSED(entry.gate_version = tableData.getStringField(8, "")); + entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); + entry.LootTableIndex = tableData.getIntField("LootTableIndex", -1); + entry.RarityTableIndex = tableData.getIntField("RarityTableIndex", -1); + entry.percent = tableData.getFloatField("percent", -1.0f); + entry.minToDrop = tableData.getIntField("minToDrop", -1); + entry.maxToDrop = tableData.getIntField("maxToDrop", -1); + entry.id = tableData.getIntField("id", -1); + entry.flagID = tableData.getIntField("flagID", -1); + UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); this->entries.push_back(entry); tableData.nextRow(); @@ -60,3 +60,4 @@ std::vector<CDLootMatrix> CDLootMatrixTable::Query(std::function<bool(CDLootMatr const std::vector<CDLootMatrix>& CDLootMatrixTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDLootTableTable.cpp b/dDatabase/Tables/CDLootTableTable.cpp index da8c824b..91cced47 100644 --- a/dDatabase/Tables/CDLootTableTable.cpp +++ b/dDatabase/Tables/CDLootTableTable.cpp @@ -21,12 +21,12 @@ CDLootTableTable::CDLootTableTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootTable"); while (!tableData.eof()) { CDLootTable entry; - entry.id = tableData.getIntField(0, -1); - entry.itemid = tableData.getIntField(0, -1); - entry.LootTableIndex = tableData.getIntField(1, -1); - entry.id = tableData.getIntField(2, -1); - entry.MissionDrop = tableData.getIntField(3, -1) == 1 ? true : false; - entry.sortPriority = tableData.getIntField(4, -1); + entry.id = tableData.getIntField("id", -1); + entry.itemid = tableData.getIntField("itemid", -1); + entry.LootTableIndex = tableData.getIntField("LootTableIndex", -1); + entry.id = tableData.getIntField("id", -1); + entry.MissionDrop = tableData.getIntField("MissionDrop", -1) == 1 ? true : false; + entry.sortPriority = tableData.getIntField("sortPriority", -1); this->entries.push_back(entry); tableData.nextRow(); @@ -57,3 +57,4 @@ std::vector<CDLootTable> CDLootTableTable::Query(std::function<bool(CDLootTable) const std::vector<CDLootTable>& CDLootTableTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDMissionEmailTable.cpp b/dDatabase/Tables/CDMissionEmailTable.cpp index a8beb95b..4fac7be2 100644 --- a/dDatabase/Tables/CDMissionEmailTable.cpp +++ b/dDatabase/Tables/CDMissionEmailTable.cpp @@ -21,14 +21,14 @@ CDMissionEmailTable::CDMissionEmailTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionEmail"); while (!tableData.eof()) { CDMissionEmail entry; - entry.ID = tableData.getIntField(0, -1); - entry.messageType = tableData.getIntField(1, -1); - entry.notificationGroup = tableData.getIntField(2, -1); - entry.missionID = tableData.getIntField(3, -1); - entry.attachmentLOT = tableData.getIntField(4, 0); - entry.localize = (bool)tableData.getIntField(5, -1); - entry.locStatus = tableData.getIntField(6, -1); - entry.gate_version = tableData.getStringField(7, ""); + entry.ID = tableData.getIntField("ID", -1); + entry.messageType = tableData.getIntField("messageType", -1); + entry.notificationGroup = tableData.getIntField("notificationGroup", -1); + entry.missionID = tableData.getIntField("missionID", -1); + entry.attachmentLOT = tableData.getIntField("attachmentLOT", 0); + entry.localize = (bool)tableData.getIntField("localize", -1); + entry.locStatus = tableData.getIntField("locStatus", -1); + entry.gate_version = tableData.getStringField("gate_version", ""); this->entries.push_back(entry); tableData.nextRow(); @@ -59,3 +59,4 @@ std::vector<CDMissionEmail> CDMissionEmailTable::Query(std::function<bool(CDMiss std::vector<CDMissionEmail> CDMissionEmailTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDMissionNPCComponentTable.cpp b/dDatabase/Tables/CDMissionNPCComponentTable.cpp index e2589890..461cc909 100644 --- a/dDatabase/Tables/CDMissionNPCComponentTable.cpp +++ b/dDatabase/Tables/CDMissionNPCComponentTable.cpp @@ -21,11 +21,11 @@ CDMissionNPCComponentTable::CDMissionNPCComponentTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionNPCComponent"); while (!tableData.eof()) { CDMissionNPCComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.missionID = tableData.getIntField(1, -1); - entry.offersMission = tableData.getIntField(2, -1) == 1 ? true : false; - entry.acceptsMission = tableData.getIntField(3, -1) == 1 ? true : false; - entry.gate_version = tableData.getStringField(4, ""); + entry.id = tableData.getIntField("id", -1); + entry.missionID = tableData.getIntField("missionID", -1); + entry.offersMission = tableData.getIntField("offersMission", -1) == 1 ? true : false; + entry.acceptsMission = tableData.getIntField("acceptsMission", -1) == 1 ? true : false; + entry.gate_version = tableData.getStringField("gate_version", ""); this->entries.push_back(entry); tableData.nextRow(); @@ -56,3 +56,4 @@ std::vector<CDMissionNPCComponent> CDMissionNPCComponentTable::Query(std::functi std::vector<CDMissionNPCComponent> CDMissionNPCComponentTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDMissionTasksTable.cpp b/dDatabase/Tables/CDMissionTasksTable.cpp index 81de2088..c22da1ef 100644 --- a/dDatabase/Tables/CDMissionTasksTable.cpp +++ b/dDatabase/Tables/CDMissionTasksTable.cpp @@ -21,19 +21,19 @@ CDMissionTasksTable::CDMissionTasksTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionTasks"); while (!tableData.eof()) { CDMissionTasks entry; - entry.id = tableData.getIntField(0, -1); - UNUSED(entry.locStatus = tableData.getIntField(1, -1)); - entry.taskType = tableData.getIntField(2, -1); - entry.target = tableData.getIntField(3, -1); - entry.targetGroup = tableData.getStringField(4, ""); - entry.targetValue = tableData.getIntField(5, -1); - entry.taskParam1 = tableData.getStringField(6, ""); - UNUSED(entry.largeTaskIcon = tableData.getStringField(7, "")); - UNUSED(entry.IconID = tableData.getIntField(8, -1)); - entry.uid = tableData.getIntField(9, -1); - UNUSED(entry.largeTaskIconID = tableData.getIntField(10, -1)); - UNUSED(entry.localize = tableData.getIntField(11, -1) == 1 ? true : false); - UNUSED(entry.gate_version = tableData.getStringField(12, "")); + entry.id = tableData.getIntField("id", -1); + UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1)); + entry.taskType = tableData.getIntField("taskType", -1); + entry.target = tableData.getIntField("target", -1); + entry.targetGroup = tableData.getStringField("targetGroup", ""); + entry.targetValue = tableData.getIntField("targetValue", -1); + entry.taskParam1 = tableData.getStringField("taskParam1", ""); + UNUSED(entry.largeTaskIcon = tableData.getStringField("largeTaskIcon", "")); + UNUSED(entry.IconID = tableData.getIntField("IconID", -1)); + entry.uid = tableData.getIntField("uid", -1); + UNUSED(entry.largeTaskIconID = tableData.getIntField("largeTaskIconID", -1)); + UNUSED(entry.localize = tableData.getIntField("localize", -1) == 1 ? true : false); + UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); this->entries.push_back(entry); tableData.nextRow(); @@ -78,3 +78,4 @@ std::vector<CDMissionTasks*> CDMissionTasksTable::GetByMissionID(uint32_t missio const std::vector<CDMissionTasks>& CDMissionTasksTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDMissionsTable.cpp b/dDatabase/Tables/CDMissionsTable.cpp index 7e59657d..a87b4327 100644 --- a/dDatabase/Tables/CDMissionsTable.cpp +++ b/dDatabase/Tables/CDMissionsTable.cpp @@ -23,58 +23,58 @@ CDMissionsTable::CDMissionsTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions"); while (!tableData.eof()) { CDMissions entry; - entry.id = tableData.getIntField(0, -1); - entry.defined_type = tableData.getStringField(1, ""); - entry.defined_subtype = tableData.getStringField(2, ""); - entry.UISortOrder = tableData.getIntField(3, -1); - entry.offer_objectID = tableData.getIntField(4, -1); - entry.target_objectID = tableData.getIntField(5, -1); - entry.reward_currency = tableData.getInt64Field(6, -1); - entry.LegoScore = tableData.getIntField(7, -1); - entry.reward_reputation = tableData.getIntField(8, -1); - entry.isChoiceReward = tableData.getIntField(9, -1) == 1 ? true : false; - entry.reward_item1 = tableData.getIntField(10, 0); - entry.reward_item1_count = tableData.getIntField(11, 0); - entry.reward_item2 = tableData.getIntField(12, 0); - entry.reward_item2_count = tableData.getIntField(13, 0); - entry.reward_item3 = tableData.getIntField(14, 0); - entry.reward_item3_count = tableData.getIntField(15, 0); - entry.reward_item4 = tableData.getIntField(16, 0); - entry.reward_item4_count = tableData.getIntField(17, 0); - entry.reward_emote = tableData.getIntField(18, -1); - entry.reward_emote2 = tableData.getIntField(19, -1); - entry.reward_emote3 = tableData.getIntField(20, -1); - entry.reward_emote4 = tableData.getIntField(21, -1); - entry.reward_maximagination = tableData.getIntField(22, -1); - entry.reward_maxhealth = tableData.getIntField(23, -1); - entry.reward_maxinventory = tableData.getIntField(24, -1); - entry.reward_maxmodel = tableData.getIntField(25, -1); - entry.reward_maxwidget = tableData.getIntField(26, -1); - entry.reward_maxwallet = tableData.getIntField(27, -1); - entry.repeatable = tableData.getIntField(28, -1) == 1 ? true : false; - entry.reward_currency_repeatable = tableData.getIntField(29, -1); - entry.reward_item1_repeatable = tableData.getIntField(30, -1); - entry.reward_item1_repeat_count = tableData.getIntField(31, -1); - entry.reward_item2_repeatable = tableData.getIntField(32, -1); - entry.reward_item2_repeat_count = tableData.getIntField(33, -1); - entry.reward_item3_repeatable = tableData.getIntField(34, -1); - entry.reward_item3_repeat_count = tableData.getIntField(35, -1); - entry.reward_item4_repeatable = tableData.getIntField(36, -1); - entry.reward_item4_repeat_count = tableData.getIntField(37, -1); - entry.time_limit = tableData.getIntField(38, -1); - entry.isMission = tableData.getIntField(39, -1) ? true : false; - entry.missionIconID = tableData.getIntField(40, -1); - entry.prereqMissionID = tableData.getStringField(41, ""); - entry.localize = tableData.getIntField(42, -1) == 1 ? true : false; - entry.inMOTD = tableData.getIntField(43, -1) == 1 ? true : false; - entry.cooldownTime = tableData.getInt64Field(44, -1); - entry.isRandom = tableData.getIntField(45, -1) == 1 ? true : false; - entry.randomPool = tableData.getStringField(46, ""); - entry.UIPrereqID = tableData.getIntField(47, -1); - UNUSED(entry.gate_version = tableData.getStringField(48, "")); - UNUSED(entry.HUDStates = tableData.getStringField(49, "")); - UNUSED(entry.locStatus = tableData.getIntField(50, -1)); - entry.reward_bankinventory = tableData.getIntField(51, -1); + entry.id = tableData.getIntField("id", -1); + entry.defined_type = tableData.getStringField("defined_type", ""); + entry.defined_subtype = tableData.getStringField("defined_subtype", ""); + entry.UISortOrder = tableData.getIntField("UISortOrder", -1); + entry.offer_objectID = tableData.getIntField("offer_objectID", -1); + entry.target_objectID = tableData.getIntField("target_objectID", -1); + entry.reward_currency = tableData.getInt64Field("reward_currency", -1); + entry.LegoScore = tableData.getIntField("LegoScore", -1); + entry.reward_reputation = tableData.getIntField("reward_reputation", -1); + entry.isChoiceReward = tableData.getIntField("isChoiceReward", -1) == 1 ? true : false; + entry.reward_item1 = tableData.getIntField("reward_item1", 0); + entry.reward_item1_count = tableData.getIntField("reward_item1_count", 0); + entry.reward_item2 = tableData.getIntField("reward_item2", 0); + entry.reward_item2_count = tableData.getIntField("reward_item2_count", 0); + entry.reward_item3 = tableData.getIntField("reward_item3", 0); + entry.reward_item3_count = tableData.getIntField("reward_item3_count", 0); + entry.reward_item4 = tableData.getIntField("reward_item4", 0); + entry.reward_item4_count = tableData.getIntField("reward_item4_count", 0); + entry.reward_emote = tableData.getIntField("reward_emote", -1); + entry.reward_emote2 = tableData.getIntField("reward_emote2", -1); + entry.reward_emote3 = tableData.getIntField("reward_emote3", -1); + entry.reward_emote4 = tableData.getIntField("reward_emote4", -1); + entry.reward_maximagination = tableData.getIntField("reward_maximagination", -1); + entry.reward_maxhealth = tableData.getIntField("reward_maxhealth", -1); + entry.reward_maxinventory = tableData.getIntField("reward_maxinventory", -1); + entry.reward_maxmodel = tableData.getIntField("reward_maxmodel", -1); + entry.reward_maxwidget = tableData.getIntField("reward_maxwidget", -1); + entry.reward_maxwallet = tableData.getIntField("reward_maxwallet", -1); + entry.repeatable = tableData.getIntField("repeatable", -1) == 1 ? true : false; + entry.reward_currency_repeatable = tableData.getIntField("reward_currency_repeatable", -1); + entry.reward_item1_repeatable = tableData.getIntField("reward_item1_repeatable", -1); + entry.reward_item1_repeat_count = tableData.getIntField("reward_item1_repeat_count", -1); + entry.reward_item2_repeatable = tableData.getIntField("reward_item2_repeatable", -1); + entry.reward_item2_repeat_count = tableData.getIntField("reward_item2_repeat_count", -1); + entry.reward_item3_repeatable = tableData.getIntField("reward_item3_repeatable", -1); + entry.reward_item3_repeat_count = tableData.getIntField("reward_item3_repeat_count", -1); + entry.reward_item4_repeatable = tableData.getIntField("reward_item4_repeatable", -1); + entry.reward_item4_repeat_count = tableData.getIntField("reward_item4_repeat_count", -1); + entry.time_limit = tableData.getIntField("time_limit", -1); + entry.isMission = tableData.getIntField("isMission", -1) ? true : false; + entry.missionIconID = tableData.getIntField("missionIconID", -1); + entry.prereqMissionID = tableData.getStringField("prereqMissionID", ""); + entry.localize = tableData.getIntField("localize", -1) == 1 ? true : false; + entry.inMOTD = tableData.getIntField("inMOTD", -1) == 1 ? true : false; + entry.cooldownTime = tableData.getInt64Field("cooldownTime", -1); + entry.isRandom = tableData.getIntField("isRandom", -1) == 1 ? true : false; + entry.randomPool = tableData.getStringField("randomPool", ""); + entry.UIPrereqID = tableData.getIntField("UIPrereqID", -1); + UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); + UNUSED(entry.HUDStates = tableData.getStringField("HUDStates", "")); + UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1)); + entry.reward_bankinventory = tableData.getIntField("reward_bankinventory", -1); this->entries.push_back(entry); tableData.nextRow(); @@ -131,3 +131,4 @@ const CDMissions& CDMissionsTable::GetByMissionID(uint32_t missionID, bool& foun return Default; } + diff --git a/dDatabase/Tables/CDMovementAIComponentTable.cpp b/dDatabase/Tables/CDMovementAIComponentTable.cpp index a98be8ba..333ec202 100644 --- a/dDatabase/Tables/CDMovementAIComponentTable.cpp +++ b/dDatabase/Tables/CDMovementAIComponentTable.cpp @@ -21,14 +21,14 @@ CDMovementAIComponentTable::CDMovementAIComponentTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MovementAIComponent"); while (!tableData.eof()) { CDMovementAIComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.MovementType = tableData.getStringField(1, ""); - entry.WanderChance = tableData.getFloatField(2, -1.0f); - entry.WanderDelayMin = tableData.getFloatField(3, -1.0f); - entry.WanderDelayMax = tableData.getFloatField(4, -1.0f); - entry.WanderSpeed = tableData.getFloatField(5, -1.0f); - entry.WanderRadius = tableData.getFloatField(6, -1.0f); - entry.attachedPath = tableData.getStringField(7, ""); + entry.id = tableData.getIntField("id", -1); + entry.MovementType = tableData.getStringField("MovementType", ""); + entry.WanderChance = tableData.getFloatField("WanderChance", -1.0f); + entry.WanderDelayMin = tableData.getFloatField("WanderDelayMin", -1.0f); + entry.WanderDelayMax = tableData.getFloatField("WanderDelayMax", -1.0f); + entry.WanderSpeed = tableData.getFloatField("WanderSpeed", -1.0f); + entry.WanderRadius = tableData.getFloatField("WanderRadius", -1.0f); + entry.attachedPath = tableData.getStringField("attachedPath", ""); this->entries.push_back(entry); tableData.nextRow(); @@ -59,3 +59,4 @@ std::vector<CDMovementAIComponent> CDMovementAIComponentTable::Query(std::functi std::vector<CDMovementAIComponent> CDMovementAIComponentTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDObjectSkillsTable.cpp b/dDatabase/Tables/CDObjectSkillsTable.cpp index 1a5c4790..dc797529 100644 --- a/dDatabase/Tables/CDObjectSkillsTable.cpp +++ b/dDatabase/Tables/CDObjectSkillsTable.cpp @@ -21,10 +21,10 @@ CDObjectSkillsTable::CDObjectSkillsTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ObjectSkills"); while (!tableData.eof()) { CDObjectSkills entry; - entry.objectTemplate = tableData.getIntField(0, -1); - entry.skillID = tableData.getIntField(1, -1); - entry.castOnType = tableData.getIntField(2, -1); - entry.AICombatWeight = tableData.getIntField(3, -1); + entry.objectTemplate = tableData.getIntField("objectTemplate", -1); + entry.skillID = tableData.getIntField("skillID", -1); + entry.castOnType = tableData.getIntField("castOnType", -1); + entry.AICombatWeight = tableData.getIntField("AICombatWeight", -1); this->entries.push_back(entry); tableData.nextRow(); @@ -55,3 +55,4 @@ std::vector<CDObjectSkills> CDObjectSkillsTable::Query(std::function<bool(CDObje std::vector<CDObjectSkills> CDObjectSkillsTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDObjectsTable.cpp b/dDatabase/Tables/CDObjectsTable.cpp index 03979af2..5133becc 100644 --- a/dDatabase/Tables/CDObjectsTable.cpp +++ b/dDatabase/Tables/CDObjectsTable.cpp @@ -18,20 +18,20 @@ CDObjectsTable::CDObjectsTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Objects"); while (!tableData.eof()) { CDObjects entry; - entry.id = tableData.getIntField(0, -1); - entry.name = tableData.getStringField(1, ""); - entry.placeable = tableData.getIntField(2, -1); - entry.type = tableData.getStringField(3, ""); - entry.description = tableData.getStringField(4, ""); - entry.localize = tableData.getIntField(5, -1); - entry.npcTemplateID = tableData.getIntField(6, -1); - entry.displayName = tableData.getStringField(7, ""); - entry.interactionDistance = tableData.getFloatField(8, -1.0f); - entry.nametag = tableData.getIntField(9, -1); - entry._internalNotes = tableData.getStringField(10, ""); - entry.locStatus = tableData.getIntField(11, -1); - entry.gate_version = tableData.getStringField(12, ""); - entry.HQ_valid = tableData.getIntField(13, -1); + entry.id = tableData.getIntField("id", -1); + entry.name = tableData.getStringField("name", ""); + entry.placeable = tableData.getIntField("placeable", -1); + entry.type = tableData.getStringField("type", ""); + entry.description = tableData.getStringField("description", ""); + entry.localize = tableData.getIntField("localize", -1); + entry.npcTemplateID = tableData.getIntField("npcTemplateID", -1); + entry.displayName = tableData.getStringField("displayName", ""); + entry.interactionDistance = tableData.getFloatField("interactionDistance", -1.0f); + entry.nametag = tableData.getIntField("nametag", -1); + entry._internalNotes = tableData.getStringField("_internalNotes", ""); + entry.locStatus = tableData.getIntField("locStatus", -1); + entry.gate_version = tableData.getStringField("gate_version", ""); + entry.HQ_valid = tableData.getIntField("HQ_valid", -1); this->entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); @@ -71,20 +71,20 @@ const CDObjects& CDObjectsTable::GetByID(unsigned int LOT) { // Now get the data while (!tableData.eof()) { CDObjects entry; - entry.id = tableData.getIntField(0, -1); - entry.name = tableData.getStringField(1, ""); - UNUSED(entry.placeable = tableData.getIntField(2, -1)); - entry.type = tableData.getStringField(3, ""); + entry.id = tableData.getIntField("id", -1); + entry.name = tableData.getStringField("name", ""); + UNUSED(entry.placeable = tableData.getIntField("placeable", -1)); + entry.type = tableData.getStringField("type", ""); UNUSED(ntry.description = tableData.getStringField(4, "")); - UNUSED(entry.localize = tableData.getIntField(5, -1)); - UNUSED(entry.npcTemplateID = tableData.getIntField(6, -1)); - UNUSED(entry.displayName = tableData.getStringField(7, "")); - entry.interactionDistance = tableData.getFloatField(8, -1.0f); - UNUSED(entry.nametag = tableData.getIntField(9, -1)); - UNUSED(entry._internalNotes = tableData.getStringField(10, "")); - UNUSED(entry.locStatus = tableData.getIntField(11, -1)); - UNUSED(entry.gate_version = tableData.getStringField(12, "")); - UNUSED(entry.HQ_valid = tableData.getIntField(13, -1)); + UNUSED(entry.localize = tableData.getIntField("localize", -1)); + UNUSED(entry.npcTemplateID = tableData.getIntField("npcTemplateID", -1)); + UNUSED(entry.displayName = tableData.getStringField("displayName", "")); + entry.interactionDistance = tableData.getFloatField("interactionDistance", -1.0f); + UNUSED(entry.nametag = tableData.getIntField("nametag", -1)); + UNUSED(entry._internalNotes = tableData.getStringField("_internalNotes", "")); + UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1)); + 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)); tableData.nextRow(); @@ -100,3 +100,4 @@ const CDObjects& CDObjectsTable::GetByID(unsigned int LOT) { return m_default; } + diff --git a/dDatabase/Tables/CDPackageComponentTable.cpp b/dDatabase/Tables/CDPackageComponentTable.cpp index 83673c6f..eabe68da 100644 --- a/dDatabase/Tables/CDPackageComponentTable.cpp +++ b/dDatabase/Tables/CDPackageComponentTable.cpp @@ -21,9 +21,9 @@ CDPackageComponentTable::CDPackageComponentTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PackageComponent"); while (!tableData.eof()) { CDPackageComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.LootMatrixIndex = tableData.getIntField(1, -1); - entry.packageType = tableData.getIntField(2, -1); + entry.id = tableData.getIntField("id", -1); + entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); + entry.packageType = tableData.getIntField("packageType", -1); this->entries.push_back(entry); tableData.nextRow(); @@ -54,3 +54,4 @@ std::vector<CDPackageComponent> CDPackageComponentTable::Query(std::function<boo std::vector<CDPackageComponent> CDPackageComponentTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDPhysicsComponentTable.cpp b/dDatabase/Tables/CDPhysicsComponentTable.cpp index 8cb7a3b0..f85d83c4 100644 --- a/dDatabase/Tables/CDPhysicsComponentTable.cpp +++ b/dDatabase/Tables/CDPhysicsComponentTable.cpp @@ -4,22 +4,22 @@ CDPhysicsComponentTable::CDPhysicsComponentTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PhysicsComponent"); while (!tableData.eof()) { CDPhysicsComponent* entry = new CDPhysicsComponent(); - entry->id = tableData.getIntField(0, -1); - entry->bStatic = tableData.getIntField(1, -1) != 0; - entry->physicsAsset = tableData.getStringField(2, ""); - UNUSED(entry->jump = tableData.getIntField(3, -1) != 0); - UNUSED(entry->doublejump = tableData.getIntField(4, -1) != 0); - entry->speed = tableData.getFloatField(5, -1); - UNUSED(entry->rotSpeed = tableData.getFloatField(6, -1)); - entry->playerHeight = tableData.getFloatField(7); - entry->playerRadius = tableData.getFloatField(8); - entry->pcShapeType = tableData.getIntField(9); - entry->collisionGroup = tableData.getIntField(10); - UNUSED(entry->airSpeed = tableData.getFloatField(11)); - UNUSED(entry->boundaryAsset = tableData.getStringField(12)); - UNUSED(entry->jumpAirSpeed = tableData.getFloatField(13)); - UNUSED(entry->friction = tableData.getFloatField(14)); - UNUSED(entry->gravityVolumeAsset = tableData.getStringField(15)); + entry->id = tableData.getIntField("id", -1); + entry->bStatic = tableData.getIntField("static", -1) != 0; + entry->physicsAsset = tableData.getStringField("physics_asset", ""); + UNUSED(entry->jump = tableData.getIntField("jump", -1) != 0); + UNUSED(entry->doublejump = tableData.getIntField("doublejump", -1) != 0); + entry->speed = tableData.getFloatField("speed", -1); + UNUSED(entry->rotSpeed = tableData.getFloatField("rotSpeed", -1)); + entry->playerHeight = tableData.getFloatField("playerHeight"); + entry->playerRadius = tableData.getFloatField("playerRadius"); + entry->pcShapeType = tableData.getIntField("pcShapeType"); + entry->collisionGroup = tableData.getIntField("collisionGroup"); + UNUSED(entry->airSpeed = tableData.getFloatField("airSpeed")); + UNUSED(entry->boundaryAsset = tableData.getStringField("boundaryAsset")); + UNUSED(entry->jumpAirSpeed = tableData.getFloatField("jumpAirSpeed")); + UNUSED(entry->friction = tableData.getFloatField("friction")); + UNUSED(entry->gravityVolumeAsset = tableData.getStringField("gravityVolumeAsset")); m_entries.insert(std::make_pair(entry->id, entry)); tableData.nextRow(); @@ -47,3 +47,4 @@ CDPhysicsComponent* CDPhysicsComponentTable::GetByID(unsigned int componentID) { return nullptr; } + diff --git a/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp b/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp index 01a2ae37..127ebc9d 100644 --- a/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp +++ b/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp @@ -18,11 +18,11 @@ CDPropertyEntranceComponentTable::CDPropertyEntranceComponentTable() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyEntranceComponent;"); while (!tableData.eof()) { auto entry = CDPropertyEntranceComponent{ - static_cast<uint32_t>(tableData.getIntField(0, -1)), - static_cast<uint32_t>(tableData.getIntField(1, -1)), - tableData.getStringField(2, ""), - static_cast<bool>(tableData.getIntField(3, false)), - tableData.getStringField(4, "") + static_cast<uint32_t>(tableData.getIntField("id", -1)), + static_cast<uint32_t>(tableData.getIntField("mapID", -1)), + tableData.getStringField("propertyName", ""), + static_cast<bool>(tableData.getIntField("isOnProperty", false)), + tableData.getStringField("groupType", "") }; this->entries.push_back(entry); @@ -46,3 +46,4 @@ CDPropertyEntranceComponent CDPropertyEntranceComponentTable::GetByID(uint32_t i return defaultEntry; } + diff --git a/dDatabase/Tables/CDPropertyTemplateTable.cpp b/dDatabase/Tables/CDPropertyTemplateTable.cpp index 7dd118eb..bf56da7b 100644 --- a/dDatabase/Tables/CDPropertyTemplateTable.cpp +++ b/dDatabase/Tables/CDPropertyTemplateTable.cpp @@ -17,10 +17,10 @@ CDPropertyTemplateTable::CDPropertyTemplateTable() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyTemplate;"); while (!tableData.eof()) { auto entry = CDPropertyTemplate{ - static_cast<uint32_t>(tableData.getIntField(0, -1)), - static_cast<uint32_t>(tableData.getIntField(1, -1)), - static_cast<uint32_t>(tableData.getIntField(2, -1)), - tableData.getStringField(3, "") + static_cast<uint32_t>(tableData.getIntField("id", -1)), + static_cast<uint32_t>(tableData.getIntField("mapID", -1)), + static_cast<uint32_t>(tableData.getIntField("vendorMapID", -1)), + tableData.getStringField("spawnName", "") }; this->entries.push_back(entry); @@ -44,3 +44,4 @@ CDPropertyTemplate CDPropertyTemplateTable::GetByMapID(uint32_t mapID) { return defaultEntry; } + diff --git a/dDatabase/Tables/CDProximityMonitorComponentTable.cpp b/dDatabase/Tables/CDProximityMonitorComponentTable.cpp index 092f3ca1..98cde098 100644 --- a/dDatabase/Tables/CDProximityMonitorComponentTable.cpp +++ b/dDatabase/Tables/CDProximityMonitorComponentTable.cpp @@ -21,10 +21,10 @@ CDProximityMonitorComponentTable::CDProximityMonitorComponentTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ProximityMonitorComponent"); while (!tableData.eof()) { CDProximityMonitorComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.Proximities = tableData.getStringField(1, ""); - entry.LoadOnClient = tableData.getIntField(2, -1); - entry.LoadOnServer = tableData.getIntField(3, -1); + entry.id = tableData.getIntField("id", -1); + entry.Proximities = tableData.getStringField("Proximities", ""); + entry.LoadOnClient = tableData.getIntField("LoadOnClient", -1); + entry.LoadOnServer = tableData.getIntField("LoadOnServer", -1); this->entries.push_back(entry); tableData.nextRow(); @@ -55,3 +55,4 @@ std::vector<CDProximityMonitorComponent> CDProximityMonitorComponentTable::Query std::vector<CDProximityMonitorComponent> CDProximityMonitorComponentTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDRailActivatorComponent.cpp b/dDatabase/Tables/CDRailActivatorComponent.cpp index 4c141256..4d1b5e7e 100644 --- a/dDatabase/Tables/CDRailActivatorComponent.cpp +++ b/dDatabase/Tables/CDRailActivatorComponent.cpp @@ -6,35 +6,35 @@ CDRailActivatorComponentTable::CDRailActivatorComponentTable() { while (!tableData.eof()) { CDRailActivatorComponent entry; - entry.id = tableData.getIntField(0); + entry.id = tableData.getIntField("id", 0); - entry.startAnimation = GeneralUtils::ASCIIToUTF16(tableData.getStringField(1, "")); - entry.loopAnimation = GeneralUtils::ASCIIToUTF16(tableData.getStringField(2, "")); - entry.stopAnimation = GeneralUtils::ASCIIToUTF16(tableData.getStringField(3, "")); - entry.startSound = GeneralUtils::ASCIIToUTF16(tableData.getStringField(4, "")); - entry.loopSound = GeneralUtils::ASCIIToUTF16(tableData.getStringField(5, "")); - entry.stopSound = GeneralUtils::ASCIIToUTF16(tableData.getStringField(6, "")); + entry.startAnimation = GeneralUtils::ASCIIToUTF16(tableData.getStringField("startAnim", "")); + entry.loopAnimation = GeneralUtils::ASCIIToUTF16(tableData.getStringField("loopAnim", "")); + entry.stopAnimation = GeneralUtils::ASCIIToUTF16(tableData.getStringField("stopAnim", "")); + entry.startSound = GeneralUtils::ASCIIToUTF16(tableData.getStringField("startSound", "")); + entry.loopSound = GeneralUtils::ASCIIToUTF16(tableData.getStringField("loopSound", "")); + entry.stopSound = GeneralUtils::ASCIIToUTF16(tableData.getStringField("stopSound", "")); - std::string loopEffectString(tableData.getStringField(7, "")); + std::string loopEffectString(tableData.getStringField("effectIDs", "")); entry.loopEffectID = EffectPairFromString(loopEffectString); - entry.preconditions = tableData.getStringField(8, "-1"); + entry.preconditions = tableData.getStringField("preconditions", "-1"); - entry.playerCollision = tableData.getIntField(9, 0); + entry.playerCollision = tableData.getIntField("playerCollision", 0); - entry.cameraLocked = tableData.getIntField(10, 0); + entry.cameraLocked = tableData.getIntField("cameraLocked", 0); - std::string startEffectString(tableData.getStringField(11, "")); + std::string startEffectString(tableData.getStringField("StartEffectID", "")); entry.startEffectID = EffectPairFromString(startEffectString); - std::string stopEffectString(tableData.getStringField(12, "")); + std::string stopEffectString(tableData.getStringField("StopEffectID", "")); entry.stopEffectID = EffectPairFromString(stopEffectString); - entry.damageImmune = tableData.getIntField(13, 0); + entry.damageImmune = tableData.getIntField("DamageImmune", 0); - entry.noAggro = tableData.getIntField(14, 0); + entry.noAggro = tableData.getIntField("NoAggro", 0); - entry.showNameBillboard = tableData.getIntField(15, 0); + entry.showNameBillboard = tableData.getIntField("ShowNameBillboard", 0); m_Entries.push_back(entry); tableData.nextRow(); @@ -70,3 +70,4 @@ std::pair<uint32_t, std::u16string> CDRailActivatorComponentTable::EffectPairFro return {}; } + diff --git a/dDatabase/Tables/CDRarityTableTable.cpp b/dDatabase/Tables/CDRarityTableTable.cpp index 67878cd2..cfa8d01c 100644 --- a/dDatabase/Tables/CDRarityTableTable.cpp +++ b/dDatabase/Tables/CDRarityTableTable.cpp @@ -21,10 +21,10 @@ CDRarityTableTable::CDRarityTableTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RarityTable"); while (!tableData.eof()) { CDRarityTable entry; - entry.id = tableData.getIntField(0, -1); - entry.randmax = tableData.getFloatField(1, -1); - entry.rarity = tableData.getIntField(2, -1); - entry.RarityTableIndex = tableData.getIntField(3, -1); + entry.id = tableData.getIntField("id", -1); + entry.randmax = tableData.getFloatField("randmax", -1); + entry.rarity = tableData.getIntField("rarity", -1); + entry.RarityTableIndex = tableData.getIntField("RarityTableIndex", -1); this->entries.push_back(entry); tableData.nextRow(); @@ -55,3 +55,4 @@ std::vector<CDRarityTable> CDRarityTableTable::Query(std::function<bool(CDRarity const std::vector<CDRarityTable>& CDRarityTableTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDRebuildComponentTable.cpp b/dDatabase/Tables/CDRebuildComponentTable.cpp index c4299b98..111592d4 100644 --- a/dDatabase/Tables/CDRebuildComponentTable.cpp +++ b/dDatabase/Tables/CDRebuildComponentTable.cpp @@ -21,16 +21,16 @@ CDRebuildComponentTable::CDRebuildComponentTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RebuildComponent"); while (!tableData.eof()) { CDRebuildComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.reset_time = tableData.getFloatField(1, -1.0f); - entry.complete_time = tableData.getFloatField(2, -1.0f); - entry.take_imagination = tableData.getIntField(3, -1); - entry.interruptible = tableData.getIntField(4, -1) == 1 ? true : false; - entry.self_activator = tableData.getIntField(5, -1) == 1 ? true : false; - entry.custom_modules = tableData.getStringField(6, ""); - entry.activityID = tableData.getIntField(7, -1); - entry.post_imagination_cost = tableData.getIntField(8, -1); - entry.time_before_smash = tableData.getFloatField(9, -1.0f); + entry.id = tableData.getIntField("id", -1); + entry.reset_time = tableData.getFloatField("reset_time", -1.0f); + entry.complete_time = tableData.getFloatField("complete_time", -1.0f); + entry.take_imagination = tableData.getIntField("take_imagination", -1); + entry.interruptible = tableData.getIntField("interruptible", -1) == 1 ? true : false; + entry.self_activator = tableData.getIntField("self_activator", -1) == 1 ? true : false; + entry.custom_modules = tableData.getStringField("custom_modules", ""); + entry.activityID = tableData.getIntField("activityID", -1); + 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); tableData.nextRow(); @@ -61,3 +61,4 @@ std::vector<CDRebuildComponent> CDRebuildComponentTable::Query(std::function<boo std::vector<CDRebuildComponent> CDRebuildComponentTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDRewardsTable.cpp b/dDatabase/Tables/CDRewardsTable.cpp index 99d56f26..a53e02b5 100644 --- a/dDatabase/Tables/CDRewardsTable.cpp +++ b/dDatabase/Tables/CDRewardsTable.cpp @@ -4,12 +4,12 @@ CDRewardsTable::CDRewardsTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Rewards"); while (!tableData.eof()) { CDRewards* entry = new CDRewards(); - entry->id = tableData.getIntField(0, -1); - entry->levelID = tableData.getIntField(1, -1); - entry->missionID = tableData.getIntField(2, -1); - entry->rewardType = tableData.getIntField(3, -1); - entry->value = tableData.getIntField(4, -1); - entry->count = tableData.getIntField(5, -1); + entry->id = tableData.getIntField("id", -1); + entry->levelID = tableData.getIntField("LevelID", -1); + entry->missionID = tableData.getIntField("MissionID", -1); + entry->rewardType = tableData.getIntField("RewardType", -1); + entry->value = tableData.getIntField("value", -1); + entry->count = tableData.getIntField("count", -1); m_entries.insert(std::make_pair(entry->id, entry)); tableData.nextRow(); @@ -38,3 +38,4 @@ std::vector<CDRewards*> CDRewardsTable::GetByLevelID(uint32_t levelID) { return result; } + diff --git a/dDatabase/Tables/CDScriptComponentTable.cpp b/dDatabase/Tables/CDScriptComponentTable.cpp index b34f96f1..d91dcee9 100644 --- a/dDatabase/Tables/CDScriptComponentTable.cpp +++ b/dDatabase/Tables/CDScriptComponentTable.cpp @@ -18,9 +18,9 @@ CDScriptComponentTable::CDScriptComponentTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ScriptComponent"); while (!tableData.eof()) { CDScriptComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.script_name = tableData.getStringField(1, ""); - entry.client_script_name = tableData.getStringField(2, ""); + 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)); tableData.nextRow(); @@ -45,3 +45,4 @@ const CDScriptComponent& CDScriptComponentTable::GetByID(unsigned int id) { return m_ToReturnWhenNoneFound; } + diff --git a/dDatabase/Tables/CDSkillBehaviorTable.cpp b/dDatabase/Tables/CDSkillBehaviorTable.cpp index e3986578..b6b601a1 100644 --- a/dDatabase/Tables/CDSkillBehaviorTable.cpp +++ b/dDatabase/Tables/CDSkillBehaviorTable.cpp @@ -23,25 +23,25 @@ CDSkillBehaviorTable::CDSkillBehaviorTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM SkillBehavior"); while (!tableData.eof()) { CDSkillBehavior entry; - entry.skillID = tableData.getIntField(0, -1); - UNUSED(entry.locStatus = tableData.getIntField(1, -1)); - entry.behaviorID = tableData.getIntField(2, -1); - entry.imaginationcost = tableData.getIntField(3, -1); - entry.cooldowngroup = tableData.getIntField(4, -1); - entry.cooldown = tableData.getFloatField(5, -1.0f); - UNUSED(entry.isNpcEditor = tableData.getIntField(6, -1) == 1 ? true : false); - UNUSED(entry.skillIcon = tableData.getIntField(7, -1)); - UNUSED(entry.oomSkillID = tableData.getStringField(8, "")); - UNUSED(entry.oomBehaviorEffectID = tableData.getIntField(9, -1)); - UNUSED(entry.castTypeDesc = tableData.getIntField(10, -1)); - UNUSED(entry.imBonusUI = tableData.getIntField(11, -1)); - UNUSED(entry.lifeBonusUI = tableData.getIntField(12, -1)); - UNUSED(entry.armorBonusUI = tableData.getIntField(13, -1)); - UNUSED(entry.damageUI = tableData.getIntField(14, -1)); - UNUSED(entry.hideIcon = tableData.getIntField(15, -1) == 1 ? true : false); - UNUSED(entry.localize = tableData.getIntField(16, -1) == 1 ? true : false); - UNUSED(entry.gate_version = tableData.getStringField(17, "")); - UNUSED(entry.cancelType = tableData.getIntField(18, -1)); + entry.skillID = tableData.getIntField("skillID", -1); + UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1)); + entry.behaviorID = tableData.getIntField("behaviorID", -1); + entry.imaginationcost = tableData.getIntField("imaginationcost", -1); + entry.cooldowngroup = tableData.getIntField("cooldowngroup", -1); + entry.cooldown = tableData.getFloatField("cooldown", -1.0f); + UNUSED(entry.isNpcEditor = tableData.getIntField("isNpcEditor", -1) == 1 ? true : false); + UNUSED(entry.skillIcon = tableData.getIntField("skillIcon", -1)); + UNUSED(entry.oomSkillID = tableData.getStringField("oomSkillID", "")); + UNUSED(entry.oomBehaviorEffectID = tableData.getIntField("oomBehaviorEffectID", -1)); + UNUSED(entry.castTypeDesc = tableData.getIntField("castTypeDesc", -1)); + UNUSED(entry.imBonusUI = tableData.getIntField("imBonusUI", -1)); + UNUSED(entry.lifeBonusUI = tableData.getIntField("lifeBonusUI", -1)); + UNUSED(entry.armorBonusUI = tableData.getIntField("armorBonusUI", -1)); + UNUSED(entry.damageUI = tableData.getIntField("damageUI", -1)); + UNUSED(entry.hideIcon = tableData.getIntField("hideIcon", -1) == 1 ? true : false); + UNUSED(entry.localize = tableData.getIntField("localize", -1) == 1 ? true : false); + UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); + UNUSED(entry.cancelType = tableData.getIntField("cancelType", -1)); this->entries.insert(std::make_pair(entry.skillID, entry)); //this->entries.push_back(entry); @@ -82,3 +82,4 @@ const CDSkillBehavior& CDSkillBehaviorTable::GetSkillByID(unsigned int skillID) return m_empty; } + diff --git a/dDatabase/Tables/CDVendorComponentTable.cpp b/dDatabase/Tables/CDVendorComponentTable.cpp index f1dd96db..86d87d4b 100644 --- a/dDatabase/Tables/CDVendorComponentTable.cpp +++ b/dDatabase/Tables/CDVendorComponentTable.cpp @@ -21,11 +21,11 @@ CDVendorComponentTable::CDVendorComponentTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM VendorComponent"); while (!tableData.eof()) { CDVendorComponent entry; - entry.id = tableData.getIntField(0, -1); - entry.buyScalar = tableData.getFloatField(1, -1.0f); - entry.sellScalar = tableData.getFloatField(2, -1.0f); - entry.refreshTimeSeconds = tableData.getFloatField(3, -1.0f); - entry.LootMatrixIndex = tableData.getIntField(4, -1); + entry.id = tableData.getIntField("id", -1); + entry.buyScalar = tableData.getFloatField("buyScalar", -1.0f); + entry.sellScalar = tableData.getFloatField("sellScalar", -1.0f); + entry.refreshTimeSeconds = tableData.getFloatField("refreshTimeSeconds", -1.0f); + entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); this->entries.push_back(entry); tableData.nextRow(); @@ -56,3 +56,4 @@ std::vector<CDVendorComponent> CDVendorComponentTable::Query(std::function<bool( std::vector<CDVendorComponent> CDVendorComponentTable::GetEntries(void) const { return this->entries; } + diff --git a/dDatabase/Tables/CDZoneTableTable.cpp b/dDatabase/Tables/CDZoneTableTable.cpp index e172f79a..04f7d102 100644 --- a/dDatabase/Tables/CDZoneTableTable.cpp +++ b/dDatabase/Tables/CDZoneTableTable.cpp @@ -18,33 +18,33 @@ CDZoneTableTable::CDZoneTableTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ZoneTable"); while (!tableData.eof()) { CDZoneTable entry; - entry.zoneID = tableData.getIntField(0, -1); - entry.locStatus = tableData.getIntField(1, -1); - entry.zoneName = tableData.getStringField(2, ""); - entry.scriptID = tableData.getIntField(3, -1); - entry.ghostdistance_min = tableData.getFloatField(4, -1.0f); - entry.ghostdistance = tableData.getFloatField(5, -1.0f); - entry.population_soft_cap = tableData.getIntField(6, -1); - entry.population_hard_cap = tableData.getIntField(7, -1); - UNUSED(entry.DisplayDescription = tableData.getStringField(8, "")); - UNUSED(entry.mapFolder = tableData.getStringField(9, "")); - entry.smashableMinDistance = tableData.getFloatField(10, -1.0f); - entry.smashableMaxDistance = tableData.getFloatField(11, -1.0f); - UNUSED(entry.mixerProgram = tableData.getStringField(12, "")); - UNUSED(entry.clientPhysicsFramerate = tableData.getStringField(13, "")); - UNUSED(entry.serverPhysicsFramerate = tableData.getStringField(14, "")); - entry.zoneControlTemplate = tableData.getIntField(15, -1); - entry.widthInChunks = tableData.getIntField(16, -1); - entry.heightInChunks = tableData.getIntField(17, -1); - entry.petsAllowed = tableData.getIntField(18, -1) == 1 ? true : false; - entry.localize = tableData.getIntField(19, -1) == 1 ? true : false; - entry.fZoneWeight = tableData.getFloatField(20, -1.0f); - UNUSED(entry.thumbnail = tableData.getStringField(21, "")); - entry.PlayerLoseCoinsOnDeath = tableData.getIntField(22, -1) == 1 ? true : false; - UNUSED(entry.disableSaveLoc = tableData.getIntField(23, -1) == 1 ? true : false); - entry.teamRadius = tableData.getFloatField(24, -1.0f); - UNUSED(entry.gate_version = tableData.getStringField(25, "")); - UNUSED(entry.mountsAllowed = tableData.getIntField(26, -1) == 1 ? true : false); + entry.zoneID = tableData.getIntField("zoneID", -1); + entry.locStatus = tableData.getIntField("locStatus", -1); + entry.zoneName = tableData.getStringField("zoneName", ""); + entry.scriptID = tableData.getIntField("scriptID", -1); + entry.ghostdistance_min = tableData.getFloatField("ghostdistance_min", -1.0f); + entry.ghostdistance = tableData.getFloatField("ghostdistance", -1.0f); + entry.population_soft_cap = tableData.getIntField("population_soft_cap", -1); + entry.population_hard_cap = tableData.getIntField("population_hard_cap", -1); + UNUSED(entry.DisplayDescription = tableData.getStringField("DisplayDescription", "")); + UNUSED(entry.mapFolder = tableData.getStringField("mapFolder", "")); + entry.smashableMinDistance = tableData.getFloatField("smashableMinDistance", -1.0f); + entry.smashableMaxDistance = tableData.getFloatField("smashableMaxDistance", -1.0f); + UNUSED(entry.mixerProgram = tableData.getStringField("mixerProgram", "")); + UNUSED(entry.clientPhysicsFramerate = tableData.getStringField("clientPhysicsFramerate", "")); + UNUSED(entry.serverPhysicsFramerate = tableData.getStringField("serverPhysicsFramerate", "")); + entry.zoneControlTemplate = tableData.getIntField("zoneControlTemplate", -1); + entry.widthInChunks = tableData.getIntField("widthInChunks", -1); + entry.heightInChunks = tableData.getIntField("heightInChunks", -1); + entry.petsAllowed = tableData.getIntField("petsAllowed", -1) == 1 ? true : false; + entry.localize = tableData.getIntField("localize", -1) == 1 ? true : false; + entry.fZoneWeight = tableData.getFloatField("fZoneWeight", -1.0f); + UNUSED(entry.thumbnail = tableData.getStringField("thumbnail", "")); + entry.PlayerLoseCoinsOnDeath = tableData.getIntField("PlayerLoseCoinsOnDeath", -1) == 1 ? true : false; + UNUSED(entry.disableSaveLoc = tableData.getIntField("disableSaveLoc", -1) == 1 ? true : false); + entry.teamRadius = tableData.getFloatField("teamRadius", -1.0f); + UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); + UNUSED(entry.mountsAllowed = tableData.getIntField("mountsAllowed", -1) == 1 ? true : false); this->m_Entries.insert(std::make_pair(entry.zoneID, entry)); tableData.nextRow(); @@ -71,3 +71,4 @@ const CDZoneTable* CDZoneTableTable::Query(unsigned int zoneID) { return nullptr; } + From e67f310632196310dbe15e8a9a35b307225e25d8 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 8 Jan 2023 01:01:53 -0800 Subject: [PATCH 230/322] Fix missing template override for AMFFormats (#946) --- dGame/dGameMessages/GameMessages.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 7e9ea898..9aafd0fc 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -77,6 +77,7 @@ #include "AMFDeserialize.h" #include "eBlueprintSaveResponseType.h" #include "eAninmationFlags.h" +#include "AMFFormat_BitStream.h" void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender) { CBITSTREAM; From ce39e3ad6b7822d49480f9535e4a509183fc50c0 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Wed, 11 Jan 2023 01:10:14 -0600 Subject: [PATCH 231/322] Add ldf controlls to vanity npc tools make vanity npc use more forgiving --- dGame/dUtilities/VanityUtilities.cpp | 127 ++++++++++++++------------- dGame/dUtilities/VanityUtilities.h | 1 + 2 files changed, 69 insertions(+), 59 deletions(-) diff --git a/dGame/dUtilities/VanityUtilities.cpp b/dGame/dUtilities/VanityUtilities.cpp index 74fd0f67..7fabfbce 100644 --- a/dGame/dUtilities/VanityUtilities.cpp +++ b/dGame/dUtilities/VanityUtilities.cpp @@ -65,17 +65,21 @@ void VanityUtilities::SpawnVanity() { npcIndex = GeneralUtils::GenerateRandomNumber<uint32_t>(0, npcList.size() - 1); } - const auto& npc = npcList[npcIndex]; + auto& npc = npcList[npcIndex]; taken.push_back(npcIndex); // Spawn the NPC - std::vector<LDFBaseData*> data = { new LDFData<std::vector<std::u16string>>( - u"syncLDF", { u"custom_script_client" }), - new LDFData<std::u16string>(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") }; + Game::logger->Log("VanityUtilities", "ldf size is %i", npc.ldf.size()); + if (npc.ldf.empty()) { + npc.ldf = { + new LDFData<std::vector<std::u16string>>(u"syncLDF", { u"custom_script_client" }), + new LDFData<std::u16string>(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") + }; + } // Spawn the NPC - auto* npcEntity = SpawnNPC(npc.m_LOT, npc.m_Name, location.m_Position, location.m_Rotation, npc.m_Equipment, data); + auto* npcEntity = SpawnNPC(npc.m_LOT, npc.m_Name, location.m_Position, location.m_Rotation, npc.m_Equipment, npc.ldf); npcEntity->SetVar<std::vector<std::string>>(u"chats", m_PartyPhrases); @@ -86,11 +90,11 @@ void VanityUtilities::SpawnVanity() { } // Loop through all NPCs - for (const auto& pair : m_NPCs) { - if (pair.m_Locations.find(Game::server->GetZoneID()) == pair.m_Locations.end()) + for (auto& npc : m_NPCs) { + if (npc.m_Locations.find(Game::server->GetZoneID()) == npc.m_Locations.end()) continue; - const std::vector<VanityNPCLocation>& locations = pair.m_Locations.at(Game::server->GetZoneID()); + const std::vector<VanityNPCLocation>& locations = npc.m_Locations.at(Game::server->GetZoneID()); // Pick a random location const auto& location = locations[GeneralUtils::GenerateRandomNumber<int>( @@ -101,27 +105,30 @@ void VanityUtilities::SpawnVanity() { continue; } - std::vector<LDFBaseData*> data = { new LDFData<std::vector<std::u16string>>( - u"syncLDF", { u"custom_script_client" }), - new LDFData<std::u16string>(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") }; + if (npc.ldf.empty()) { + npc.ldf = { + new LDFData<std::vector<std::u16string>>(u"syncLDF", { u"custom_script_client" }), + new LDFData<std::u16string>(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") + }; + } // Spawn the NPC - auto* npc = SpawnNPC(pair.m_LOT, pair.m_Name, location.m_Position, location.m_Rotation, pair.m_Equipment, data); + auto* npcEntity = SpawnNPC(npc.m_LOT, npc.m_Name, location.m_Position, location.m_Rotation, npc.m_Equipment, npc.ldf); - npc->SetVar<std::vector<std::string>>(u"chats", pair.m_Phrases); + npcEntity->SetVar<std::vector<std::string>>(u"chats", npc.m_Phrases); - auto* scriptComponent = npc->GetComponent<ScriptComponent>(); + auto* scriptComponent = npcEntity->GetComponent<ScriptComponent>(); if (scriptComponent != nullptr) { - scriptComponent->SetScript(pair.m_Script); + scriptComponent->SetScript(npc.m_Script); scriptComponent->SetSerialized(false); - for (const auto& pair : pair.m_Flags) { - npc->SetVar<bool>(GeneralUtils::ASCIIToUTF16(pair.first), pair.second); + for (const auto& npc : npc.m_Flags) { + npcEntity->SetVar<bool>(GeneralUtils::ASCIIToUTF16(npc.first), npc.second); } } - SetupNPCTalk(npc); + SetupNPCTalk(npcEntity); } if (zoneID == 1200) { @@ -266,10 +273,7 @@ void VanityUtilities::ParseXML(const std::string& file) { // Get the NPC name auto* name = npc->Attribute("name"); - if (name == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC name"); - continue; - } + if (!name) name = ""; // Get the NPC lot auto* lot = npc->Attribute("lot"); @@ -281,71 +285,76 @@ void VanityUtilities::ParseXML(const std::string& file) { // Get the equipment auto* equipment = npc->FirstChildElement("equipment"); - - if (equipment == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC equipment"); - continue; - } - - auto* text = equipment->GetText(); - std::vector<LOT> inventory; - if (text != nullptr) { - std::string equipmentString(text); + if (equipment) { + auto* text = equipment->GetText(); - std::vector<std::string> splitEquipment = GeneralUtils::SplitString(equipmentString, ','); + if (text != nullptr) { + std::string equipmentString(text); - for (auto& item : splitEquipment) { - inventory.push_back(std::stoi(item)); + std::vector<std::string> splitEquipment = GeneralUtils::SplitString(equipmentString, ','); + + for (auto& item : splitEquipment) { + inventory.push_back(std::stoi(item)); + } } } + // Get the phrases auto* phrases = npc->FirstChildElement("phrases"); - if (phrases == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC phrases"); - continue; - } + std::vector<std::string> phraseList = {}; - std::vector<std::string> phraseList; - - for (auto* phrase = phrases->FirstChildElement("phrase"); phrase != nullptr; - phrase = phrase->NextSiblingElement("phrase")) { - // Get the phrase - auto* text = phrase->GetText(); - - if (text == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC phrase"); - continue; + if (phrases) { + for (auto* phrase = phrases->FirstChildElement("phrase"); phrase != nullptr; + phrase = phrase->NextSiblingElement("phrase")) { + // Get the phrase + auto* text = phrase->GetText(); + if (text == nullptr) { + Game::logger->Log("VanityUtilities", "Failed to parse NPC phrase"); + continue; + } + phraseList.push_back(text); } - - phraseList.push_back(text); } // Get the script auto* scriptElement = npc->FirstChildElement("script"); - std::string scriptName; + std::string scriptName = ""; if (scriptElement != nullptr) { auto* scriptNameAttribute = scriptElement->Attribute("name"); - - if (scriptNameAttribute == nullptr) { - Game::logger->Log("VanityUtilities", "Failed to parse NPC script name"); - continue; - } - - scriptName = scriptNameAttribute; + if (scriptNameAttribute) scriptName = scriptNameAttribute; } + auto* ldfElement = npc->FirstChildElement("ldf"); + std::vector<std::u16string> keys = {}; + + std::vector<LDFBaseData*> 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<std::vector<std::u16string>>(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"); diff --git a/dGame/dUtilities/VanityUtilities.h b/dGame/dUtilities/VanityUtilities.h index 2f1886ed..0cca0aba 100644 --- a/dGame/dUtilities/VanityUtilities.h +++ b/dGame/dUtilities/VanityUtilities.h @@ -20,6 +20,7 @@ struct VanityNPC std::string m_Script; std::map<std::string, bool> m_Flags; std::map<uint32_t, std::vector<VanityNPCLocation>> m_Locations; + std::vector<LDFBaseData*> ldf; }; struct VanityParty From e7bc4ef77345ff29cb3a56a2e30bf72fddc690aa Mon Sep 17 00:00:00 2001 From: "Gie \"Max\" Vanommeslaeghe" <gievanom@hotmail.com> Date: Wed, 11 Jan 2023 20:08:54 +0100 Subject: [PATCH 232/322] add hardcore mode --- dGame/dComponents/DestroyableComponent.cpp | 70 ++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 3e146335..e08de3e6 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -2,6 +2,7 @@ #include <BitStream.h> #include "dLogger.h" #include "Game.h" +#include "dConfig.h" #include "AMFFormat.h" #include "AMFFormat_BitStream.h" @@ -666,6 +667,75 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 return; } Smash(source, eKillType::VIOLENT, u"", skillID); + + //check if hardcore mode is enabled + if (Game::config->GetValue("hardcore_mode") == "1") { + //check if this is a player: + if (m_Parent->GetLOT() == 1) { + //get hardcore_lose_uscore_on_death_percent from dconfig: + auto hardcore_lose_uscore_on_death_percent = std::stoi(Game::config->GetValue("hardcore_lose_uscore_on_death_percent")); + + //remove hardcore_lose_uscore_on_death_percent from the player's uscore: + auto* character = m_Parent->GetComponent<CharacterComponent>(); + auto uscore = character->GetUScore(); + + auto uscore_to_lose = uscore * hardcore_lose_uscore_on_death_percent / 100; + character->SetUScore(uscore - uscore_to_lose); + + //get hardcore_dropinventory on death from dconfig: + auto hardcore_dropinventory_on_death = (bool)std::stoi(Game::config->GetValue("hardcore_dropinventory_on_death")); + + if (hardcore_dropinventory_on_death == false) return; + + //drop all items from inventory: + auto* inventory = m_Parent->GetComponent<InventoryComponent>(); + + //get the items inventory: + auto items = inventory->GetInventory(eInventoryType::ITEMS); + for (auto item : items->GetItems()) { + //check if this is an equipped item: + if (item.second->IsEquipped()) { + //unequip the item: + inventory->UnEquipItem(item.second); + } + + //drop the item: + GameMessages::SendDropClientLoot(m_Parent, source, item.second->GetLot(), 0, m_Parent->GetPosition(), item.second->GetCount()); + + //remove from inventory: + inventory->RemoveItem(item.second->GetLot(), item.second->GetCount()); + } + + //get character: + auto* chars = m_Parent->GetCharacter(); + if (chars) { + auto coins = chars->GetCoins(); + + //lose all coins: + chars->SetCoins(0, eLootSourceType::LOOT_SOURCE_NONE); + + //drop all coins: + GameMessages::SendDropClientLoot(m_Parent, source, 0, coins, m_Parent->GetPosition(), 0); + } + } else { + //award the player some u-score: + auto* player = EntityManager::Instance()->GetEntity(source); + if (player && player->GetLOT() == 1) { + auto* playerStats = player->GetComponent<CharacterComponent>(); + if (playerStats) { + //get the maximum health from this enemy: + auto maxHealth = GetMaxHealth(); + + //get the u-score to award from dconfig: + auto hardcore_uscore_enemies_multiplier = std::stoi(Game::config->GetValue("hardcore_uscore_enemies_multiplier")); + int uscore = maxHealth * hardcore_uscore_enemies_multiplier; + + playerStats->SetUScore(playerStats->GetUScore() + uscore); + GameMessages::SendModifyLEGOScore(player, player->GetSystemAddress(), uscore, eLootSourceType::LOOT_SOURCE_NONE); + } + } + } + } } void DestroyableComponent::Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd) { From bfa4fbd5a9d66f50e75b680d9e3652744186ba11 Mon Sep 17 00:00:00 2001 From: "Gie \"Max\" Vanommeslaeghe" <gievanom@hotmail.com> Date: Wed, 11 Jan 2023 20:11:06 +0100 Subject: [PATCH 233/322] add hardcore_mode to settings --- resources/worldconfig.ini | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/resources/worldconfig.ini b/resources/worldconfig.ini index 0c24c447..abedfb4b 100644 --- a/resources/worldconfig.ini +++ b/resources/worldconfig.ini @@ -46,3 +46,15 @@ max_number_of_best_friends=5 # Disables loot drops disable_drops=0 + +# Hardcore mode settings +hardcore_enabled=0 + +# Drop your entire inventory on death + coins (drops on the ground, so can be retrieved) +hardcore_dropinventory=1 + +# Enemies drop their max hp * this value. 0 will effectively disable it. +hardcore_uscore_enemies_multiplier=2 + +# Percentage of u-score to lose on player death +hardcore_lose_uscore_on_death_percent=10 From 5557a98129490287d547e880898272aea90ae5c2 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Wed, 11 Jan 2023 14:10:48 -0600 Subject: [PATCH 234/322] fix hardmode example config options (#952) --- resources/worldconfig.ini | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/resources/worldconfig.ini b/resources/worldconfig.ini index abedfb4b..64b4fb40 100644 --- a/resources/worldconfig.ini +++ b/resources/worldconfig.ini @@ -48,10 +48,10 @@ max_number_of_best_friends=5 disable_drops=0 # Hardcore mode settings -hardcore_enabled=0 +hardcore_mode=0 # Drop your entire inventory on death + coins (drops on the ground, so can be retrieved) -hardcore_dropinventory=1 +hardcore_dropinventory_on_death=1 # Enemies drop their max hp * this value. 0 will effectively disable it. hardcore_uscore_enemies_multiplier=2 From 7aacfc1bf039212ddf60fd54eb2a7ebf52037084 Mon Sep 17 00:00:00 2001 From: wincent <wincent.holm@gmail.com> Date: Wed, 11 Jan 2023 21:50:21 +0100 Subject: [PATCH 235/322] Fixed crashes related to hardcore mode --- dGame/dComponents/DestroyableComponent.cpp | 42 ++++++++++++---------- dGame/dUtilities/SlashCommandHandler.cpp | 13 +++++-- 2 files changed, 34 insertions(+), 21 deletions(-) diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index e08de3e6..0e8ce56e 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -666,46 +666,46 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 return; } - Smash(source, eKillType::VIOLENT, u"", skillID); //check if hardcore mode is enabled if (Game::config->GetValue("hardcore_mode") == "1") { //check if this is a player: if (m_Parent->GetLOT() == 1) { //get hardcore_lose_uscore_on_death_percent from dconfig: - auto hardcore_lose_uscore_on_death_percent = std::stoi(Game::config->GetValue("hardcore_lose_uscore_on_death_percent")); + auto hardcoreLoseUscoreOnDeathPercent = std::stoi(Game::config->GetValue("hardcore_lose_uscore_on_death_percent")); //remove hardcore_lose_uscore_on_death_percent from the player's uscore: auto* character = m_Parent->GetComponent<CharacterComponent>(); auto uscore = character->GetUScore(); - auto uscore_to_lose = uscore * hardcore_lose_uscore_on_death_percent / 100; - character->SetUScore(uscore - uscore_to_lose); + auto uscoreToLose = uscore * hardcoreLoseUscoreOnDeathPercent / 100; + character->SetUScore(uscore - uscoreToLose); - //get hardcore_dropinventory on death from dconfig: - auto hardcore_dropinventory_on_death = (bool)std::stoi(Game::config->GetValue("hardcore_dropinventory_on_death")); + GameMessages::SendModifyLEGOScore(m_Parent, m_Parent->GetSystemAddress(), -uscoreToLose, eLootSourceType::LOOT_SOURCE_MISSION); - if (hardcore_dropinventory_on_death == false) return; + // Reload the player + EntityManager::Instance()->DestructEntity(m_Parent); + EntityManager::Instance()->ConstructEntity(m_Parent); + + auto hardcoreDropinventoryOnDeath = (bool)std::stoi(Game::config->GetValue("hardcore_dropinventory_on_death")); + + if (hardcoreDropinventoryOnDeath == false) return; //drop all items from inventory: auto* inventory = m_Parent->GetComponent<InventoryComponent>(); //get the items inventory: auto items = inventory->GetInventory(eInventoryType::ITEMS); - for (auto item : items->GetItems()) { - //check if this is an equipped item: - if (item.second->IsEquipped()) { - //unequip the item: - inventory->UnEquipItem(item.second); - } - + auto itemMap = items->GetItems(); + for (const auto& item : itemMap) { //drop the item: GameMessages::SendDropClientLoot(m_Parent, source, item.second->GetLot(), 0, m_Parent->GetPosition(), item.second->GetCount()); - //remove from inventory: - inventory->RemoveItem(item.second->GetLot(), item.second->GetCount()); + item.second->SetCount(0, false, false); } + EntityManager::Instance()->SerializeEntity(m_Parent); + //get character: auto* chars = m_Parent->GetCharacter(); if (chars) { @@ -727,15 +727,19 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 auto maxHealth = GetMaxHealth(); //get the u-score to award from dconfig: - auto hardcore_uscore_enemies_multiplier = std::stoi(Game::config->GetValue("hardcore_uscore_enemies_multiplier")); - int uscore = maxHealth * hardcore_uscore_enemies_multiplier; + auto hardcoreUscoreEnemiesMultiplier = std::stoi(Game::config->GetValue("hardcore_uscore_enemies_multiplier")); + int uscore = maxHealth * hardcoreUscoreEnemiesMultiplier; playerStats->SetUScore(playerStats->GetUScore() + uscore); - GameMessages::SendModifyLEGOScore(player, player->GetSystemAddress(), uscore, eLootSourceType::LOOT_SOURCE_NONE); + GameMessages::SendModifyLEGOScore(player, player->GetSystemAddress(), uscore, eLootSourceType::LOOT_SOURCE_MISSION); + + EntityManager::Instance()->SerializeEntity(m_Parent); } } } } + + Smash(source, eKillType::VIOLENT, u"", skillID); } void DestroyableComponent::Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd) { diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index cc1c82a9..70637990 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -1312,7 +1312,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if ((chatCommand == "giveuscore") && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if ((chatCommand == "giveuscore") && args.size() >= 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { int32_t uscore; if (!GeneralUtils::TryParse(args[0], uscore)) { @@ -1323,7 +1323,16 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit CharacterComponent* character = entity->GetComponent<CharacterComponent>(); if (character) character->SetUScore(character->GetUScore() + uscore); // LOOT_SOURCE_MODERATION should work but it doesn't. Relog to see uscore changes - GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), uscore, eLootSourceType::LOOT_SOURCE_MODERATION); + + eLootSourceType lootType = eLootSourceType::LOOT_SOURCE_MODERATION; + + int32_t type; + if (args.size() >= 2 && GeneralUtils::TryParse(args[1], type)) + { + lootType = (eLootSourceType) type; + } + + GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), uscore, lootType); } if ((chatCommand == "setlevel") && args.size() >= 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { From 7bca43ffc1fb2576fb2b517747d8cc7455d9fc88 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 11 Jan 2023 22:36:03 -0800 Subject: [PATCH 236/322] Fix tests (#953) --- tests/dGameTests/GameDependencies.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/dGameTests/GameDependencies.h b/tests/dGameTests/GameDependencies.h index 81875ab6..353b53b8 100644 --- a/tests/dGameTests/GameDependencies.h +++ b/tests/dGameTests/GameDependencies.h @@ -6,6 +6,7 @@ #include "dServer.h" #include "EntityInfo.h" #include "EntityManager.h" +#include "dConfig.h" #include <gtest/gtest.h> class dZoneManager; @@ -30,6 +31,7 @@ protected: info.lot = 999; Game::logger = new dLogger("./testing.log", true, true); Game::server = new dServerMock(); + Game::config = new dConfig("worldconfig.ini"); } void TearDownDependencies() { @@ -39,6 +41,7 @@ protected: Game::logger->Flush(); delete Game::logger; } + if (Game::config) delete Game::config; } EntityInfo info; From 872270704c44408cbc466526c5e891a839b6c722 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 12 Jan 2023 13:16:24 -0600 Subject: [PATCH 237/322] Hardmode cleanups (#954) * load values once so that it doesn't check every time don't return, just skip don't realod char * address feedback * don't drop the only item you can't get again * address most feedback * move settings for HC mode * fix comment * claenup whitespace --- dGame/EntityManager.cpp | 11 ++ dGame/EntityManager.h | 11 ++ dGame/dComponents/DestroyableComponent.cpp | 145 +++++++++++---------- dGame/dComponents/DestroyableComponent.h | 3 + 4 files changed, 100 insertions(+), 70 deletions(-) diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index 99ead79d..67553b41 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -18,6 +18,7 @@ #include "Game.h" #include "dLogger.h" #include "MessageIdentifiers.h" +#include "dConfig.h" EntityManager* EntityManager::m_Address = nullptr; @@ -58,6 +59,16 @@ void EntityManager::Initialize() { m_GhostingExcludedZones.end(), dZoneManager::Instance()->GetZoneID().GetMapID() ) == m_GhostingExcludedZones.end(); + + // grab hardcore mode settings and load them with sane defaults + auto hcmode = Game::config->GetValue("hardcore_mode"); + m_HardcoreMode = hcmode.empty() ? false : (hcmode == "1"); + auto hcUscorePercent = Game::config->GetValue("hardcore_lose_uscore_on_death_percent"); + m_HardcoreLoseUscoreOnDeathPercent = hcUscorePercent.empty() ? 10 : std::stoi(hcUscorePercent); + auto hcUscoreMult = Game::config->GetValue("hardcore_uscore_enemies_multiplier"); + m_HardcoreUscoreEnemiesMultiplier = hcUscoreMult.empty() ? 2 : std::stoi(hcUscoreMult); + auto hcDropInv = Game::config->GetValue("hardcore_dropinventory_on_death"); + m_HardcoreDropinventoryOnDeath = hcDropInv.empty() ? false : (hcDropInv == "1"); } EntityManager::~EntityManager() { diff --git a/dGame/EntityManager.h b/dGame/EntityManager.h index 36bc5962..8a930de3 100644 --- a/dGame/EntityManager.h +++ b/dGame/EntityManager.h @@ -78,6 +78,11 @@ public: static bool IsExcludedFromGhosting(LOT lot); + const bool GetHardcoreMode() { return m_HardcoreMode; }; + const uint32_t GetHardcoreLoseUscoreOnDeathPercent() { return m_HardcoreLoseUscoreOnDeathPercent; }; + const bool GetHardcoreDropinventoryOnDeath() { return m_HardcoreDropinventoryOnDeath; }; + const uint32_t GetHardcoreUscoreEnemiesMultiplier() { return m_HardcoreUscoreEnemiesMultiplier; }; + private: static EntityManager* m_Address; //For singleton method static std::vector<LWOMAPID> m_GhostingExcludedZones; @@ -102,6 +107,12 @@ private: // Map of spawnname to entity object ID std::unordered_map<std::string, LWOOBJID> m_SpawnPoints; + + // hardcore mode vars + bool m_HardcoreMode; + uint32_t m_HardcoreLoseUscoreOnDeathPercent; + bool m_HardcoreDropinventoryOnDeath; + uint32_t m_HardcoreUscoreEnemiesMultiplier; }; #endif // ENTITYMANAGER_H diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 0e8ce56e..1455ce58 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -668,77 +668,10 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32 } //check if hardcore mode is enabled - if (Game::config->GetValue("hardcore_mode") == "1") { - //check if this is a player: - if (m_Parent->GetLOT() == 1) { - //get hardcore_lose_uscore_on_death_percent from dconfig: - auto hardcoreLoseUscoreOnDeathPercent = std::stoi(Game::config->GetValue("hardcore_lose_uscore_on_death_percent")); - - //remove hardcore_lose_uscore_on_death_percent from the player's uscore: - auto* character = m_Parent->GetComponent<CharacterComponent>(); - auto uscore = character->GetUScore(); - - auto uscoreToLose = uscore * hardcoreLoseUscoreOnDeathPercent / 100; - character->SetUScore(uscore - uscoreToLose); - - GameMessages::SendModifyLEGOScore(m_Parent, m_Parent->GetSystemAddress(), -uscoreToLose, eLootSourceType::LOOT_SOURCE_MISSION); - - // Reload the player - EntityManager::Instance()->DestructEntity(m_Parent); - EntityManager::Instance()->ConstructEntity(m_Parent); - - auto hardcoreDropinventoryOnDeath = (bool)std::stoi(Game::config->GetValue("hardcore_dropinventory_on_death")); - - if (hardcoreDropinventoryOnDeath == false) return; - - //drop all items from inventory: - auto* inventory = m_Parent->GetComponent<InventoryComponent>(); - - //get the items inventory: - auto items = inventory->GetInventory(eInventoryType::ITEMS); - auto itemMap = items->GetItems(); - for (const auto& item : itemMap) { - //drop the item: - GameMessages::SendDropClientLoot(m_Parent, source, item.second->GetLot(), 0, m_Parent->GetPosition(), item.second->GetCount()); - - item.second->SetCount(0, false, false); - } - - EntityManager::Instance()->SerializeEntity(m_Parent); - - //get character: - auto* chars = m_Parent->GetCharacter(); - if (chars) { - auto coins = chars->GetCoins(); - - //lose all coins: - chars->SetCoins(0, eLootSourceType::LOOT_SOURCE_NONE); - - //drop all coins: - GameMessages::SendDropClientLoot(m_Parent, source, 0, coins, m_Parent->GetPosition(), 0); - } - } else { - //award the player some u-score: - auto* player = EntityManager::Instance()->GetEntity(source); - if (player && player->GetLOT() == 1) { - auto* playerStats = player->GetComponent<CharacterComponent>(); - if (playerStats) { - //get the maximum health from this enemy: - auto maxHealth = GetMaxHealth(); - - //get the u-score to award from dconfig: - auto hardcoreUscoreEnemiesMultiplier = std::stoi(Game::config->GetValue("hardcore_uscore_enemies_multiplier")); - int uscore = maxHealth * hardcoreUscoreEnemiesMultiplier; - - playerStats->SetUScore(playerStats->GetUScore() + uscore); - GameMessages::SendModifyLEGOScore(player, player->GetSystemAddress(), uscore, eLootSourceType::LOOT_SOURCE_MISSION); - - EntityManager::Instance()->SerializeEntity(m_Parent); - } - } - } + if (EntityManager::Instance()->GetHardcoreMode()) { + DoHardcoreModeDrops(source); } - + Smash(source, eKillType::VIOLENT, u"", skillID); } @@ -1045,3 +978,75 @@ void DestroyableComponent::FixStats() { void DestroyableComponent::AddOnHitCallback(const std::function<void(Entity*)>& callback) { m_OnHitCallbacks.push_back(callback); } + +void DestroyableComponent::DoHardcoreModeDrops(const LWOOBJID source){ + //check if this is a player: + if (m_Parent->IsPlayer()) { + //remove hardcore_lose_uscore_on_death_percent from the player's uscore: + auto* character = m_Parent->GetComponent<CharacterComponent>(); + auto uscore = character->GetUScore(); + + auto uscoreToLose = uscore * (EntityManager::Instance()->GetHardcoreLoseUscoreOnDeathPercent() / 100); + character->SetUScore(uscore - uscoreToLose); + + GameMessages::SendModifyLEGOScore(m_Parent, m_Parent->GetSystemAddress(), -uscoreToLose, eLootSourceType::LOOT_SOURCE_MISSION); + + if (EntityManager::Instance()->GetHardcoreDropinventoryOnDeath()) { + //drop all items from inventory: + auto* inventory = m_Parent->GetComponent<InventoryComponent>(); + if (inventory) { + //get the items inventory: + auto items = inventory->GetInventory(eInventoryType::ITEMS); + if (items){ + auto itemMap = items->GetItems(); + if (!itemMap.empty()){ + for (const auto& item : itemMap) { + //drop the item: + if (!item.second) continue; + // don't drop the thinkng cap + if (item.second->GetLot() == 6086) continue; + GameMessages::SendDropClientLoot(m_Parent, source, item.second->GetLot(), 0, m_Parent->GetPosition(), item.second->GetCount()); + item.second->SetCount(0, false, false); + } + EntityManager::Instance()->SerializeEntity(m_Parent); + } + } + } + } + + //get character: + auto* chars = m_Parent->GetCharacter(); + if (chars) { + auto coins = chars->GetCoins(); + + //lose all coins: + chars->SetCoins(0, eLootSourceType::LOOT_SOURCE_NONE); + + //drop all coins: + GameMessages::SendDropClientLoot(m_Parent, source, LOT_NULL, coins, m_Parent->GetPosition()); + } + + // Reload the player since we can't normally reduce uscore from the server and we want the UI to update + // do this last so we don't get killed.... again + EntityManager::Instance()->DestructEntity(m_Parent); + EntityManager::Instance()->ConstructEntity(m_Parent); + return; + } + + //award the player some u-score: + auto* player = EntityManager::Instance()->GetEntity(source); + if (player && player->IsPlayer()) { + auto* playerStats = player->GetComponent<CharacterComponent>(); + if (playerStats) { + //get the maximum health from this enemy: + auto maxHealth = GetMaxHealth(); + + int uscore = maxHealth * EntityManager::Instance()->GetHardcoreUscoreEnemiesMultiplier(); + + playerStats->SetUScore(playerStats->GetUScore() + uscore); + GameMessages::SendModifyLEGOScore(player, player->GetSystemAddress(), uscore, eLootSourceType::LOOT_SOURCE_MISSION); + + EntityManager::Instance()->SerializeEntity(m_Parent); + } + } +} diff --git a/dGame/dComponents/DestroyableComponent.h b/dGame/dComponents/DestroyableComponent.h index 2736f47c..854144d9 100644 --- a/dGame/dComponents/DestroyableComponent.h +++ b/dGame/dComponents/DestroyableComponent.h @@ -452,6 +452,9 @@ public: void Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd); void Unsubscribe(LWOOBJID scriptObjId); + // handle hardcode mode drops + void DoHardcoreModeDrops(const LWOOBJID source); + private: /** * Whether or not the health should be serialized From fbaf1cbb256c42b31b70947e71c17a37ff2bc8ab Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 17 Jan 2023 04:06:09 -0800 Subject: [PATCH 238/322] Dont preemptively delete objects (#958) Let finalizeShutdown take care of it --- dMasterServer/MasterServer.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 82645797..77571e22 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -248,8 +248,6 @@ int main(int argc, char** argv) { std::cout << "Account created successfully!\n"; - Database::Destroy("MasterServer"); - delete Game::logger; return EXIT_SUCCESS; } From 7418e02365683baa8a0b7e6442ade907cb9dfb43 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 17 Jan 2023 04:07:34 -0800 Subject: [PATCH 239/322] Update AmTeapotServer.cpp (#949) --- dScripts/02_server/Map/AM/AmTeapotServer.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/dScripts/02_server/Map/AM/AmTeapotServer.cpp b/dScripts/02_server/Map/AM/AmTeapotServer.cpp index 32abafd6..1f47cb1a 100644 --- a/dScripts/02_server/Map/AM/AmTeapotServer.cpp +++ b/dScripts/02_server/Map/AM/AmTeapotServer.cpp @@ -1,14 +1,21 @@ #include "AmTeapotServer.h" #include "InventoryComponent.h" #include "GameMessages.h" - +#include "Item.h" void AmTeapotServer::OnUse(Entity* self, Entity* user) { auto* inventoryComponent = user->GetComponent<InventoryComponent>(); if (!inventoryComponent) return; - if (inventoryComponent->GetLotCount(BLUE_FLOWER_LEAVES) >= 10) { - inventoryComponent->RemoveItem(BLUE_FLOWER_LEAVES, 10); + auto* blueFlowerItem = inventoryComponent->FindItemByLot(BLUE_FLOWER_LEAVES, eInventoryType::ITEMS); + if (!blueFlowerItem) { + blueFlowerItem = inventoryComponent->FindItemByLot(BLUE_FLOWER_LEAVES, eInventoryType::VAULT_ITEMS); + if (!blueFlowerItem) return; + } + + // The client allows you to use the teapot only if you have a stack of 10 leaves in some inventory somewhere. + if (blueFlowerItem->GetCount() >= 10) { + blueFlowerItem->SetCount(blueFlowerItem->GetCount() - 10); inventoryComponent->AddItem(WU_S_IMAGINATION_TEA, 1); } GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); From 14085d09bd8b682da8c6d493cb5ba96daafa1c20 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 17 Jan 2023 11:26:50 -0800 Subject: [PATCH 240/322] Add note for compiling with multiple jobs (#948) * Fix overread in projectile behavior * Fix stuns * Correctly read in bitStream * Fix projectile behavior * Address movement type issues * Update shutdown time to be accurate * Fix small issues * Fix missing template * Add note for compile jobs --- README.md | 4 ++++ build.sh | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 27de7d6d..df782a32 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,10 @@ You can either run `build.sh` when in the root folder of the repository: Or manually run the commands used in [build.sh](build.sh). +If you would like to build the server faster, append `-j<number>` where number is the number of simultaneous compile jobs to run at once. It is recommended that you have this number always be 1 less than your core count to prevent slowdowns. The command would look like this if you would build with 4 jobs at once: +```bash +./build.sh -j4 +``` ### Notes Depending on your operating system, you may need to adjust some pre-processor defines in [CMakeVariables.txt](./CMakeVariables.txt) before building: * If you are on MacOS, ensure OPENSSL_ROOT_DIR is pointing to the openssl root directory. diff --git a/build.sh b/build.sh index a736a4ee..b8d33492 100755 --- a/build.sh +++ b/build.sh @@ -9,5 +9,5 @@ cd build cmake .. # To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `cmake --build . --config Release -j8' -cmake --build . --config Release +cmake --build . --config Release $1 From 6fd80e3117304ea28d437ade85fdca4bc95b7217 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 20 Jan 2023 01:50:46 -0600 Subject: [PATCH 241/322] Don't enable HC on minigame worlds (#959) * Fix max's ouchi * use smarter logic * fix whitespace * clone --- dGame/EntityManager.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index 67553b41..22c31291 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -69,6 +69,10 @@ void EntityManager::Initialize() { m_HardcoreUscoreEnemiesMultiplier = hcUscoreMult.empty() ? 2 : std::stoi(hcUscoreMult); auto hcDropInv = Game::config->GetValue("hardcore_dropinventory_on_death"); m_HardcoreDropinventoryOnDeath = hcDropInv.empty() ? false : (hcDropInv == "1"); + + // If cloneID is not zero, then hardcore mode is disabled + // aka minigames and props + if (dZoneManager::Instance()->GetZoneID().GetCloneID() != 0) m_HardcoreMode = false; } EntityManager::~EntityManager() { From c8cd51ef63472fa8cafd7492a085ef7d134275b2 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 20 Jan 2023 00:07:25 -0800 Subject: [PATCH 242/322] Fix warning for overrides (#961) --- dCommon/AMFFormat.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dCommon/AMFFormat.h b/dCommon/AMFFormat.h index 2b423abd..6e479ef6 100644 --- a/dCommon/AMFFormat.h +++ b/dCommon/AMFFormat.h @@ -257,7 +257,7 @@ private: /*! \return The AMF value type */ - AMFValueType GetValueType() { return ValueType; } + AMFValueType GetValueType() override { return ValueType; } public: static const AMFValueType ValueType = AMFArray; @@ -362,7 +362,7 @@ private: /*! \return The AMF value type */ - AMFValueType GetValueType() { return ValueType; } + AMFValueType GetValueType() override { return ValueType; } ~AMFObjectValue() override; public: From cff94b6c225ab3d92408b63e4541d2cea5a419a1 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 21 Jan 2023 07:37:09 -0800 Subject: [PATCH 243/322] Fix hash collisions in achievements (#962) --- dGame/dComponents/AchievementCacheKey.h | 43 +++++++++++++++++++++++++ dGame/dComponents/MissionComponent.cpp | 19 ++++++----- dGame/dComponents/MissionComponent.h | 14 ++++---- 3 files changed, 60 insertions(+), 16 deletions(-) create mode 100644 dGame/dComponents/AchievementCacheKey.h diff --git a/dGame/dComponents/AchievementCacheKey.h b/dGame/dComponents/AchievementCacheKey.h new file mode 100644 index 00000000..d8892197 --- /dev/null +++ b/dGame/dComponents/AchievementCacheKey.h @@ -0,0 +1,43 @@ +#ifndef __ACHIEVEMENTCACHEKEY__H__ +#define __ACHIEVEMENTCACHEKEY__H__ + +class AchievementCacheKey { +public: + AchievementCacheKey() { + targets = ""; + value = 0; + type = MissionTaskType::MISSION_TASK_TYPE_UNKNOWN; + }; + + bool operator==(const AchievementCacheKey& point) const { + return this->targets == point.targets && this->value == point.value && this->type == point.type; + }; + void SetTargets(const std::string value) { this->targets = value; }; + void SetValue(uint32_t value) { this->value = value; }; + void SetType(MissionTaskType value) { this->type = value; }; + + std::string GetTargets() const { return this->targets; }; + uint32_t GetValue() const { return this->value; }; + MissionTaskType GetType() const { return this->type; }; +private: + std::string targets; + uint32_t value; + MissionTaskType type; + +}; + +// Specialization of hash for the above class +namespace std { + template<> + struct hash<AchievementCacheKey> { + size_t operator()(const AchievementCacheKey& key) const { + size_t hash = 0; + GeneralUtils::hash_combine(hash, key.GetType()); + GeneralUtils::hash_combine(hash, key.GetValue()); + GeneralUtils::hash_combine(hash, key.GetTargets()); + return hash; + }; + }; +}; + +#endif //!__ACHIEVEMENTCACHEKEY__H__ diff --git a/dGame/dComponents/MissionComponent.cpp b/dGame/dComponents/MissionComponent.cpp index 96f213e5..2ef6c2f6 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -17,10 +17,11 @@ #include "dZoneManager.h" #include "Mail.h" #include "MissionPrerequisites.h" +#include "AchievementCacheKey.h" // MARK: Mission Component -std::unordered_map<size_t, std::vector<uint32_t>> MissionComponent::m_AchievementCache = {}; +std::unordered_map<AchievementCacheKey, std::vector<uint32_t>> MissionComponent::m_AchievementCache = {}; //! Initializer MissionComponent::MissionComponent(Entity* parent) : Component(parent) { @@ -391,12 +392,12 @@ bool MissionComponent::LookForAchievements(MissionTaskType type, int32_t value, const std::vector<uint32_t>& MissionComponent::QueryAchievements(MissionTaskType type, int32_t value, const std::string targets) { // Create a hash which represent this query for achievements - size_t hash = 0; - GeneralUtils::hash_combine(hash, type); - GeneralUtils::hash_combine(hash, value); - GeneralUtils::hash_combine(hash, targets); + AchievementCacheKey toFind; + toFind.SetType(type); + toFind.SetValue(value); + toFind.SetTargets(targets); - const std::unordered_map<size_t, std::vector<uint32_t>>::iterator& iter = m_AchievementCache.find(hash); + const auto& iter = m_AchievementCache.find(toFind); // Check if this query is cached if (iter != m_AchievementCache.end()) { @@ -447,11 +448,9 @@ const std::vector<uint32_t>& MissionComponent::QueryAchievements(MissionTaskType } } } - // Insert into cache - m_AchievementCache.insert_or_assign(hash, result); - - return m_AchievementCache.find(hash)->second; + m_AchievementCache.insert_or_assign(toFind, result); + return m_AchievementCache.find(toFind)->second; } bool MissionComponent::RequiresItem(const LOT lot) { diff --git a/dGame/dComponents/MissionComponent.h b/dGame/dComponents/MissionComponent.h index 58185a68..a3e39a88 100644 --- a/dGame/dComponents/MissionComponent.h +++ b/dGame/dComponents/MissionComponent.h @@ -17,11 +17,13 @@ #include "CDMissionsTable.h" #include "Component.h" - /** - * The mission inventory of an entity. Tracks mission state for each mission that can be accepted and allows for - * progression of each of the mission task types (see MissionTaskType). - */ -class MissionComponent : public Component +class AchievementCacheKey; + +/** + * The mission inventory of an entity. Tracks mission state for each mission that can be accepted and allows for + * progression of each of the mission task types (see MissionTaskType). + */ +class MissionComponent: public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_MISSION; @@ -192,7 +194,7 @@ private: * As achievements can be hard to query, we here store a list of all the mission IDs that can be unlocked for a * combination of tasks and values, so that they can be easily re-queried later */ - static std::unordered_map<size_t, std::vector<uint32_t>> m_AchievementCache; + static std::unordered_map<AchievementCacheKey, std::vector<uint32_t>> m_AchievementCache; /** * Order of missions in the UI. This value is incremented by 1 From faf42d2f8cf432df2993b031f079b0b8c6d7dbe7 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Sun, 22 Jan 2023 17:38:47 -0600 Subject: [PATCH 244/322] cleanup enums to make them more consistent --- dChatServer/ChatPacketHandler.cpp | 56 +++---- dChatServer/ChatPacketHandler.h | 4 +- dCommon/dEnums/ItemSetPassiveAbilityID.h | 105 ------------- dCommon/dEnums/MissionLockState.h | 13 -- dCommon/dEnums/MissionState.h | 56 ------- dCommon/dEnums/MissionTaskType.h | 31 ---- dCommon/dEnums/PermissionMap.h | 42 ------ dCommon/dEnums/RacingTaskParam.h | 20 --- ...esponseCode.h => eAddFriendResponseCode.h} | 6 +- ...esponseType.h => eAddFriendResponseType.h} | 8 +- dCommon/dEnums/eBubbleType.h | 4 +- dCommon/dEnums/eHelpType.h | 41 +++++ dCommon/dEnums/eItemSetPassiveAbilityID.h | 58 +++++++ dCommon/dEnums/eItemType.h | 50 +++--- dCommon/dEnums/eMissionLockState.h | 12 ++ dCommon/dEnums/eMissionState.h | 56 +++++++ dCommon/dEnums/eMissionTaskType.h | 43 ++++++ dCommon/dEnums/ePackageType.h | 13 ++ dCommon/dEnums/ePermissionMap.h | 46 ++++++ dCommon/dEnums/eRacingTaskParam.h | 25 +++ dGame/Character.cpp | 16 +- dGame/Character.h | 9 +- dGame/Entity.cpp | 5 +- dGame/TradingManager.cpp | 5 +- dGame/dComponents/AchievementCacheKey.h | 10 +- dGame/dComponents/DestroyableComponent.cpp | 15 +- dGame/dComponents/InventoryComponent.cpp | 27 ++-- dGame/dComponents/InventoryComponent.h | 10 +- dGame/dComponents/MissionComponent.cpp | 19 +-- dGame/dComponents/MissionComponent.h | 18 +-- dGame/dComponents/MissionOfferComponent.cpp | 9 +- dGame/dComponents/PetComponent.cpp | 4 +- .../PropertyManagementComponent.cpp | 3 +- dGame/dComponents/RacingControlComponent.cpp | 19 +-- dGame/dComponents/RebuildComponent.cpp | 6 +- .../dComponents/ScriptedActivityComponent.cpp | 3 +- dGame/dGameMessages/GameMessageHandler.cpp | 3 +- dGame/dGameMessages/GameMessages.cpp | 55 +++---- dGame/dInventory/Inventory.cpp | 51 ++++--- dGame/dInventory/Item.cpp | 6 +- dGame/dInventory/ItemSet.cpp | 3 +- dGame/dInventory/ItemSetPassiveAbility.cpp | 142 +++++++++--------- dGame/dMission/Mission.cpp | 70 +++++---- dGame/dMission/Mission.h | 15 +- dGame/dMission/MissionPrerequisites.cpp | 4 +- dGame/dMission/MissionTask.cpp | 51 ++++--- dGame/dMission/MissionTask.h | 4 +- dGame/dUtilities/Loot.cpp | 10 +- dGame/dUtilities/Mail.cpp | 5 +- dGame/dUtilities/Preconditions.cpp | 10 +- dGame/dUtilities/SlashCommandHandler.cpp | 3 +- dNet/ClientPackets.cpp | 2 +- .../02_server/Equipment/BootyDigServer.cpp | 7 +- .../Equipment/MaestromExtracticatorServer.cpp | 3 +- .../02_server/Map/AG/NpcAgCourseStarter.cpp | 4 +- dScripts/02_server/Map/AG/NpcCowboyServer.cpp | 14 +- dScripts/02_server/Map/AG/NpcCowboyServer.h | 2 +- .../02_server/Map/AG/NpcEpsilonServer.cpp | 2 +- dScripts/02_server/Map/AG/NpcEpsilonServer.h | 2 +- .../02_server/Map/AG/NpcNjAssistantServer.cpp | 9 +- .../02_server/Map/AG/NpcNjAssistantServer.h | 2 +- dScripts/02_server/Map/AG/NpcPirateServer.cpp | 8 +- dScripts/02_server/Map/AG/NpcPirateServer.h | 2 +- dScripts/02_server/Map/AG/NpcWispServer.cpp | 10 +- dScripts/02_server/Map/AG/NpcWispServer.h | 2 +- .../02_server/Map/AG/RemoveRentalGear.cpp | 6 +- dScripts/02_server/Map/AG/RemoveRentalGear.h | 2 +- .../02_server/Map/AM/AmDropshipComputer.cpp | 3 +- dScripts/02_server/Map/FV/FvFong.cpp | 6 +- dScripts/02_server/Map/FV/FvFong.h | 2 +- .../02_server/Map/FV/ImgBrickConsoleQB.cpp | 5 +- dScripts/02_server/Map/GF/GfTikiTorch.cpp | 3 +- .../02_server/Map/General/ExplodingAsset.cpp | 5 +- .../02_server/Map/General/GrowingFlower.cpp | 12 +- .../General/ImaginationBackpackHealServer.cpp | 6 +- .../02_server/Map/General/PetDigServer.cpp | 7 +- .../02_server/Map/General/PropertyDevice.cpp | 3 +- .../Map/General/TouchMissionUpdateServer.cpp | 3 +- .../02_server/Map/NT/NtAssemblyTubeServer.cpp | 4 +- dScripts/02_server/Map/NT/NtDukeServer.cpp | 7 +- dScripts/02_server/Map/NT/NtDukeServer.h | 2 +- .../02_server/Map/NT/NtParadoxPanelServer.cpp | 3 +- .../02_server/Map/NT/NtParadoxTeleServer.cpp | 3 +- .../Map/NT/NtSentinelWalkwayServer.cpp | 3 +- dScripts/02_server/Map/NT/NtVandaServer.cpp | 6 +- dScripts/02_server/Map/NT/NtVandaServer.h | 2 +- .../Map/NT/NtVentureSpeedPadServer.cpp | 3 +- .../02_server/Map/PR/SpawnGryphonServer.cpp | 3 +- .../Map/Property/AG_Small/ZoneAgProperty.cpp | 11 +- .../02_server/Map/SS/SsModularBuildServer.cpp | 3 +- .../02_server/Map/VE/VeBricksampleServer.cpp | 3 +- dScripts/02_server/Map/VE/VeEpsilonServer.cpp | 6 +- dScripts/02_server/Map/VE/VeEpsilonServer.h | 2 +- dScripts/02_server/Map/njhub/NjColeNPC.cpp | 5 +- dScripts/02_server/Map/njhub/NjColeNPC.h | 2 +- .../02_server/Map/njhub/NjJayMissionItems.cpp | 2 +- .../02_server/Map/njhub/NjJayMissionItems.h | 2 +- .../Map/njhub/NjNPCMissionSpinjitzuServer.cpp | 7 +- .../Map/njhub/NjNPCMissionSpinjitzuServer.h | 2 +- dScripts/02_server/Map/njhub/NjWuNPC.cpp | 11 +- dScripts/02_server/Map/njhub/NjWuNPC.h | 2 +- dScripts/BasePropertyServer.cpp | 6 +- dScripts/BaseSurvivalServer.cpp | 11 +- dScripts/BaseWavesServer.cpp | 23 +-- dScripts/CppScripts.h | 8 +- dScripts/Darkitect.cpp | 3 +- dScripts/NPCAddRemoveItem.cpp | 8 +- dScripts/NPCAddRemoveItem.h | 2 +- dScripts/NtFactionSpyServer.cpp | 3 +- dScripts/ai/AG/ActSharkPlayerDeathTrigger.cpp | 4 +- dScripts/ai/FV/FvFreeGfNinjas.cpp | 7 +- dScripts/ai/FV/FvFreeGfNinjas.h | 2 +- dScripts/ai/GENERAL/LegoDieRoll.cpp | 3 +- dScripts/ai/GF/GfJailkeepMission.cpp | 9 +- dScripts/ai/GF/GfJailkeepMission.h | 2 +- dScripts/ai/GF/PetDigBuild.cpp | 3 +- dScripts/ai/GF/PirateRep.cpp | 6 +- dScripts/ai/GF/PirateRep.h | 2 +- .../ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp | 9 +- dScripts/ai/NP/NpcNpSpacemanBob.cpp | 5 +- dScripts/ai/NP/NpcNpSpacemanBob.h | 2 +- dScripts/ai/NS/NsConcertInstrument.cpp | 6 +- dScripts/ai/NS/NsJohnnyMissionServer.cpp | 5 +- dScripts/ai/NS/NsJohnnyMissionServer.h | 2 +- dScripts/ai/NS/NsModularBuild.cpp | 3 +- dScripts/ai/PROPERTY/AG/AgPropGuard.cpp | 11 +- dScripts/ai/PROPERTY/AG/AgPropGuard.h | 2 +- dScripts/ai/PROPERTY/AgPropguards.cpp | 8 +- dScripts/ai/PROPERTY/AgPropguards.h | 2 +- .../OBJECTS/FvRaceSmashEggImagineServer.cpp | 7 +- .../RACING/OBJECTS/RaceImagineCrateServer.cpp | 5 +- .../ai/RACING/OBJECTS/RaceImaginePowerup.cpp | 5 +- .../ai/RACING/OBJECTS/RaceSmashServer.cpp | 7 +- 133 files changed, 898 insertions(+), 808 deletions(-) delete mode 100644 dCommon/dEnums/ItemSetPassiveAbilityID.h delete mode 100644 dCommon/dEnums/MissionLockState.h delete mode 100644 dCommon/dEnums/MissionState.h delete mode 100644 dCommon/dEnums/MissionTaskType.h delete mode 100644 dCommon/dEnums/PermissionMap.h delete mode 100644 dCommon/dEnums/RacingTaskParam.h rename dCommon/dEnums/{AddFriendResponseCode.h => eAddFriendResponseCode.h} (50%) rename dCommon/dEnums/{AddFriendResponseType.h => eAddFriendResponseType.h} (59%) create mode 100644 dCommon/dEnums/eHelpType.h create mode 100644 dCommon/dEnums/eItemSetPassiveAbilityID.h create mode 100644 dCommon/dEnums/eMissionLockState.h create mode 100644 dCommon/dEnums/eMissionState.h create mode 100644 dCommon/dEnums/eMissionTaskType.h create mode 100644 dCommon/dEnums/ePackageType.h create mode 100644 dCommon/dEnums/ePermissionMap.h create mode 100644 dCommon/dEnums/eRacingTaskParam.h diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index 119083ee..592c3870 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -8,8 +8,8 @@ #include "dServer.h" #include "GeneralUtils.h" #include "dLogger.h" -#include "AddFriendResponseCode.h" -#include "AddFriendResponseType.h" +#include "eAddFriendResponseCode.h" +#include "eAddFriendResponseType.h" #include "RakString.h" #include "dConfig.h" @@ -115,7 +115,7 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { auto requestor = playerContainer.GetPlayerData(requestorPlayerID); if (requestor->playerName == playerName) { - SendFriendResponse(requestor, requestor, AddFriendResponseType::MYTHRAN); + SendFriendResponse(requestor, requestor, eAddFriendResponseType::MYTHRAN); return; }; std::unique_ptr<PlayerData> requestee(playerContainer.GetPlayerData(playerName)); @@ -153,7 +153,7 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { requestee.reset(new PlayerData()); requestee->playerName = playerName; - SendFriendResponse(requestor, requestee.get(), result->next() ? AddFriendResponseType::NOTONLINE : AddFriendResponseType::INVALIDCHARACTER); + SendFriendResponse(requestor, requestee.get(), result->next() ? eAddFriendResponseType::NOTONLINE : eAddFriendResponseType::INVALIDCHARACTER); return; } @@ -197,10 +197,10 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { if (oldBestFriendStatus != bestFriendStatus) { if (requestee->countOfBestFriends >= maxNumberOfBestFriends || requestor->countOfBestFriends >= maxNumberOfBestFriends) { if (requestee->countOfBestFriends >= maxNumberOfBestFriends) { - SendFriendResponse(requestor, requestee.get(), AddFriendResponseType::THEIRFRIENDLISTFULL, false); + SendFriendResponse(requestor, requestee.get(), eAddFriendResponseType::THEIRFRIENDLISTFULL, false); } if (requestor->countOfBestFriends >= maxNumberOfBestFriends) { - SendFriendResponse(requestor, requestee.get(), AddFriendResponseType::YOURFRIENDSLISTFULL, false); + SendFriendResponse(requestor, requestee.get(), eAddFriendResponseType::YOURFRIENDSLISTFULL, false); } } else { // Then update the database with this new info. @@ -215,8 +215,8 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { if (bestFriendStatus == 3U) { requestee->countOfBestFriends += 1; requestor->countOfBestFriends += 1; - if (requestee->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) SendFriendResponse(requestee.get(), requestor, AddFriendResponseType::ACCEPTED, false, true); - if (requestor->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) SendFriendResponse(requestor, requestee.get(), AddFriendResponseType::ACCEPTED, false, true); + if (requestee->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) SendFriendResponse(requestee.get(), requestor, eAddFriendResponseType::ACCEPTED, false, true); + if (requestor->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) SendFriendResponse(requestor, requestee.get(), eAddFriendResponseType::ACCEPTED, false, true); for (auto& friendData : requestor->friends) { if (friendData.friendID == requestee->playerID) { friendData.isBestFriend = true; @@ -230,7 +230,7 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { } } } else { - if (requestor->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) SendFriendResponse(requestor, requestee.get(), AddFriendResponseType::WAITINGAPPROVAL, true, true); + if (requestor->sysAddr != UNASSIGNED_SYSTEM_ADDRESS) SendFriendResponse(requestor, requestee.get(), eAddFriendResponseType::WAITINGAPPROVAL, true, true); } } else { // Do not send this if we are requesting to be a best friend. @@ -247,7 +247,7 @@ void ChatPacketHandler::HandleFriendResponse(Packet* packet) { inStream.Read(playerID); inStream.Read(playerID); - AddFriendResponseCode clientResponseCode = static_cast<AddFriendResponseCode>(packet->data[0x14]); + eAddFriendResponseCode clientResponseCode = static_cast<eAddFriendResponseCode>(packet->data[0x14]); std::string friendName = PacketUtils::ReadString(0x15, packet, true); //Now to try and find both of these: @@ -255,29 +255,29 @@ void ChatPacketHandler::HandleFriendResponse(Packet* packet) { auto requestee = playerContainer.GetPlayerData(friendName); if (!requestor || !requestee) return; - AddFriendResponseType serverResponseCode{}; + eAddFriendResponseType serverResponseCode{}; uint8_t isAlreadyBestFriends = 0U; // We need to convert this response code to one we can actually send back to the client. switch (clientResponseCode) { - case AddFriendResponseCode::ACCEPTED: - serverResponseCode = AddFriendResponseType::ACCEPTED; + case eAddFriendResponseCode::ACCEPTED: + serverResponseCode = eAddFriendResponseType::ACCEPTED; break; - case AddFriendResponseCode::BUSY: - serverResponseCode = AddFriendResponseType::BUSY; + case eAddFriendResponseCode::BUSY: + serverResponseCode = eAddFriendResponseType::BUSY; break; - case AddFriendResponseCode::CANCELLED: - serverResponseCode = AddFriendResponseType::CANCELLED; + case eAddFriendResponseCode::CANCELLED: + serverResponseCode = eAddFriendResponseType::CANCELLED; break; - case AddFriendResponseCode::REJECTED: - serverResponseCode = AddFriendResponseType::DECLINED; + case eAddFriendResponseCode::REJECTED: + serverResponseCode = eAddFriendResponseType::DECLINED; break; } // Now that we have handled the base cases, we need to check the other cases. - if (serverResponseCode == AddFriendResponseType::ACCEPTED) { + if (serverResponseCode == eAddFriendResponseType::ACCEPTED) { for (auto friendData : requestor->friends) { if (friendData.friendID == requestee->playerID) { - serverResponseCode = AddFriendResponseType::ALREADYFRIEND; + serverResponseCode = eAddFriendResponseType::ALREADYFRIEND; if (friendData.isBestFriend) { isAlreadyBestFriends = 1U; } @@ -286,7 +286,7 @@ void ChatPacketHandler::HandleFriendResponse(Packet* packet) { } // This message is NOT sent for best friends and is handled differently for those requests. - if (serverResponseCode == AddFriendResponseType::ACCEPTED) { + if (serverResponseCode == eAddFriendResponseType::ACCEPTED) { // Add the each player to the others friend list. FriendData requestorData; requestorData.zoneID = requestor->zoneID; @@ -313,8 +313,8 @@ void ChatPacketHandler::HandleFriendResponse(Packet* packet) { statement->execute(); } - if (serverResponseCode != AddFriendResponseType::DECLINED) SendFriendResponse(requestor, requestee, serverResponseCode, isAlreadyBestFriends); - if (serverResponseCode != AddFriendResponseType::ALREADYFRIEND) SendFriendResponse(requestee, requestor, serverResponseCode, isAlreadyBestFriends); + if (serverResponseCode != eAddFriendResponseType::DECLINED) SendFriendResponse(requestor, requestee, serverResponseCode, isAlreadyBestFriends); + if (serverResponseCode != eAddFriendResponseType::ALREADYFRIEND) SendFriendResponse(requestee, requestor, serverResponseCode, isAlreadyBestFriends); } void ChatPacketHandler::HandleRemoveFriend(Packet* packet) { @@ -922,7 +922,7 @@ void ChatPacketHandler::SendFriendRequest(PlayerData* receiver, PlayerData* send //Make sure people aren't requesting people that they're already friends with: for (auto fr : receiver->friends) { if (fr.friendID == sender->playerID) { - SendFriendResponse(sender, receiver, AddFriendResponseType::ALREADYFRIEND, fr.isBestFriend); + SendFriendResponse(sender, receiver, eAddFriendResponseType::ALREADYFRIEND, fr.isBestFriend); return; //we have this player as a friend, yeet this function so it doesn't send another request. } } @@ -940,7 +940,7 @@ void ChatPacketHandler::SendFriendRequest(PlayerData* receiver, PlayerData* send SEND_PACKET; } -void ChatPacketHandler::SendFriendResponse(PlayerData* receiver, PlayerData* sender, AddFriendResponseType responseCode, uint8_t isBestFriendsAlready, uint8_t isBestFriendRequest) { +void ChatPacketHandler::SendFriendResponse(PlayerData* receiver, PlayerData* sender, eAddFriendResponseType responseCode, uint8_t isBestFriendsAlready, uint8_t isBestFriendRequest) { if (!receiver || !sender) return; CBITSTREAM; @@ -951,11 +951,11 @@ void ChatPacketHandler::SendFriendResponse(PlayerData* receiver, PlayerData* sen PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_ADD_FRIEND_RESPONSE); bitStream.Write(responseCode); // For all requests besides accepted, write a flag that says whether or not we are already best friends with the receiver. - bitStream.Write<uint8_t>(responseCode != AddFriendResponseType::ACCEPTED ? isBestFriendsAlready : sender->sysAddr != UNASSIGNED_SYSTEM_ADDRESS); + bitStream.Write<uint8_t>(responseCode != eAddFriendResponseType::ACCEPTED ? isBestFriendsAlready : sender->sysAddr != UNASSIGNED_SYSTEM_ADDRESS); // Then write the player name PacketUtils::WritePacketWString(sender->playerName.c_str(), 33, &bitStream); // Then if this is an acceptance code, write the following extra info. - if (responseCode == AddFriendResponseType::ACCEPTED) { + if (responseCode == eAddFriendResponseType::ACCEPTED) { bitStream.Write(sender->playerID); bitStream.Write(sender->zoneID); bitStream.Write(isBestFriendRequest); //isBFF diff --git a/dChatServer/ChatPacketHandler.h b/dChatServer/ChatPacketHandler.h index fffd1ca4..f2d83502 100644 --- a/dChatServer/ChatPacketHandler.h +++ b/dChatServer/ChatPacketHandler.h @@ -4,7 +4,7 @@ #include "BitStream.h" struct PlayerData; -enum class AddFriendResponseType : uint8_t; +enum class eAddFriendResponseType : uint8_t; namespace ChatPacketHandler { void HandleFriendlistRequest(Packet* packet); @@ -35,6 +35,6 @@ namespace ChatPacketHandler { void SendFriendUpdate(PlayerData* friendData, PlayerData* playerData, uint8_t notifyType, uint8_t isBestFriend); void SendFriendRequest(PlayerData* receiver, PlayerData* sender); - void SendFriendResponse(PlayerData* receiver, PlayerData* sender, AddFriendResponseType responseCode, uint8_t isBestFriendsAlready = 0U, uint8_t isBestFriendRequest = 0U); + void SendFriendResponse(PlayerData* receiver, PlayerData* sender, eAddFriendResponseType responseCode, uint8_t isBestFriendsAlready = 0U, uint8_t isBestFriendRequest = 0U); void SendRemoveFriend(PlayerData* receiver, std::string& personToRemove, bool isSuccessful); }; diff --git a/dCommon/dEnums/ItemSetPassiveAbilityID.h b/dCommon/dEnums/ItemSetPassiveAbilityID.h deleted file mode 100644 index 92caea19..00000000 --- a/dCommon/dEnums/ItemSetPassiveAbilityID.h +++ /dev/null @@ -1,105 +0,0 @@ -#pragma once - -/** -2 Engineer (Rank 1) Item Set -3 Engineer (Rank 2) Item Set -4 Engineer (Rank 3) Item Set -7 Knight (Rank 1) Item Set -8 Knight (Rank 2) Item Set -9 Knight (Rank 3) Item Set -10 Space Ranger (Rank 1) Item Set -11 Space Ranger (Rank 2) Item Set -12 Space Ranger (Rank 3) Item Set -13 Samurai (Rank 1) Item Set -14 Samurai (Rank 2) Item Set -15 Samurai (Rank 3) Item Set -16 Sorcerer (Rank 1) Item Set -17 Sorcerer (Rank 2) Item Set -18 Sorcerer (Rank 3) Item Set -19 Space Marauder (Rank 1) Item Set -20 Space Marauder (Rank 2) Item Set -21 Space Marauder (Rank 3) Item Set -22 Shinobi (Rank 1) Item Set -23 Shinobi (Rank 2) Item Set -24 Shinobi (Rank 3) Item Set -25 Inventor (Rank 1) Item Set -26 Inventor (Rank 2) Item Set -27 Inventor (Rank 3) Item Set -28 Summoner (Rank 1) Item Set -29 Summoner (Rank 2) Item Set -30 Summoner (Rank 3) Item Set -31 Adventurer (Rank 1) Item Set -32 Adventurer (Rank 2) Item Set -33 Adventurer (Rank 3) Item Set -34 Daredevil (Rank 1) Item Set -35 Daredevil (Rank 2) Item Set -36 Daredevil (Rank 3) Item Set -37 Buccaneer (Rank 1) Item Set -38 Buccaneer (Rank 2) Item Set -39 Buccaneer (Rank 3) Item Set -40 Bone Suit Item Set -41 Imagination Spinjitzu Item Set -42 Bat Lord Item Set -43 Mosaic Jester Item Set -44 Explorien Bot Item Set -45 [Unnamed] Item Set -46 [Unnamed] Item Set -47 [Unnamed] Item Set -48 Earth Spinjitzu Item Set -49 [Unnamed] Item Set -50 Fire Spinjitzu Item Set -51 Ice Spinjitzu Item Set -52 Lightning Spinjitzu Item Set - */ -enum class ItemSetPassiveAbilityID -{ - EngineerRank1 = 2, - EngineerRank2 = 3, - EngineerRank3 = 4, - KnightRank1 = 7, - KnightRank2 = 8, - KnightRank3 = 9, - SpaceRangerRank1 = 10, - SpaceRangerRank2 = 11, - SpaceRangerRank3 = 12, - SamuraiRank1 = 13, - SamuraiRank2 = 14, - SamuraiRank3 = 15, - SorcererRank1 = 16, - SorcererRank2 = 17, - SorcererRank3 = 18, - SpaceMarauderRank1 = 19, - SpaceMarauderRank2 = 20, - SpaceMarauderRank3 = 21, - ShinobiRank1 = 22, - ShinobiRank2 = 23, - ShinobiRank3 = 24, - InventorRank1 = 25, - InventorRank2 = 26, - InventorRank3 = 27, - SummonerRank1 = 28, - SummonerRank2 = 29, - SummonerRank3 = 30, - AdventurerRank1 = 31, - AdventurerRank2 = 32, - AdventurerRank3 = 33, - DaredevilRank1 = 34, - DaredevilRank2 = 35, - DaredevilRank3 = 36, - BuccaneerRank1 = 37, - BuccaneerRank2 = 38, - BuccaneerRank3 = 39, - BoneSuit = 40, - ImaginationSpinjitzu = 41, - BatLord = 42, - MosaicJester = 43, - ExplorienBot = 44, - Unnamed1 = 45, - Unnamed2 = 46, - Unnamed3 = 47, - EarthSpinjitzu = 48, - Unnamed4 = 49, - FireSpinjitzu = 50, - IceSpinjitzu = 51, - LightningSpinjitzu = 52 -}; diff --git a/dCommon/dEnums/MissionLockState.h b/dCommon/dEnums/MissionLockState.h deleted file mode 100644 index 9fd2252a..00000000 --- a/dCommon/dEnums/MissionLockState.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#ifndef MISSIONLOCKSTATE_H -#define MISSIONLOCKSTATE_H - -enum class MissionLockState : int -{ - MISSION_LOCK_LOCKED, - MISSION_LOCK_NEW, - MISSION_LOCK_UNLOCKED, -}; - -#endif diff --git a/dCommon/dEnums/MissionState.h b/dCommon/dEnums/MissionState.h deleted file mode 100644 index f040d33a..00000000 --- a/dCommon/dEnums/MissionState.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once - -#ifndef __MISSIONSTATE__H__ -#define __MISSIONSTATE__H__ - -/** - * Represents the possible states a mission can be in - */ -enum class MissionState : int32_t { - /** - * The mission state is unknown - */ - MISSION_STATE_UNKNOWN = -1, - - /** - * The mission is yielding rewards - */ - MISSION_STATE_REWARDING = 0, - - /** - * The mission can be accepted - */ - MISSION_STATE_AVAILABLE = 1, - - /** - * The mission has been accepted but not yet completed - */ - MISSION_STATE_ACTIVE = 2, - - /** - * All the tasks for the mission have been completed and the entity can turn the mission in to complete it - */ - MISSION_STATE_READY_TO_COMPLETE = 4, //!< The mission is ready to complete - - /** - * The mission has been completed - */ - MISSION_STATE_COMPLETE = 8, - - /** - * The mission is available again and has been completed before. Used for daily missions. - */ - MISSION_STATE_COMPLETE_AVAILABLE = 9, - - /** - * The mission is active and has been completed before. Used for daily missions. - */ - MISSION_STATE_COMPLETE_ACTIVE = 10, - - /** - * The mission has been completed before and has now been completed again. Used for daily missions. - */ - MISSION_STATE_COMPLETE_READY_TO_COMPLETE = 12 -}; - -#endif //!__MISSIONSTATE__H__ diff --git a/dCommon/dEnums/MissionTaskType.h b/dCommon/dEnums/MissionTaskType.h deleted file mode 100644 index 6c9b2668..00000000 --- a/dCommon/dEnums/MissionTaskType.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#ifndef MISSIONTASKTYPE_H -#define MISSIONTASKTYPE_H - -//! An enum for mission task types -enum class MissionTaskType : int { - MISSION_TASK_TYPE_UNKNOWN = -1, //!< The task type is unknown - MISSION_TASK_TYPE_SMASH = 0, //!< A task for smashing something - MISSION_TASK_TYPE_SCRIPT = 1, //!< A task handled by a server LUA script - MISSION_TASK_TYPE_ACTIVITY = 2, //!< A task for completing a quickbuild - MISSION_TASK_TYPE_ENVIRONMENT = 3, //!< A task for something in the environment - MISSION_TASK_TYPE_MISSION_INTERACTION = 4, //!< A task for interacting with a mission - MISSION_TASK_TYPE_EMOTE = 5, //!< A task for playing an emote - MISSION_TASK_TYPE_FOOD = 9, //!< A task for eating food - MISSION_TASK_TYPE_SKILL = 10, //!< A task for performing a skill - MISSION_TASK_TYPE_ITEM_COLLECTION = 11, //!< A task for collecting an item - MISSION_TASK_TYPE_LOCATION = 12, //!< A task for finding a location - MISSION_TASK_TYPE_MINIGAME = 14, //!< A task for doing something in a minigame - MISSION_TASK_TYPE_NON_MISSION_INTERACTION = 15, //!< A task for interacting with a non-mission - MISSION_TASK_TYPE_MISSION_COMPLETE = 16, //!< A task for completing a mission - MISSION_TASK_TYPE_EARN_REPUTATION = 17, //!< A task for earning reputation - MISSION_TASK_TYPE_POWERUP = 21, //!< A task for collecting a powerup - MISSION_TASK_TYPE_PET_TAMING = 22, //!< A task for taming a pet - MISSION_TASK_TYPE_RACING = 23, //!< A task for racing - MISSION_TASK_TYPE_PLAYER_FLAG = 24, //!< A task for setting a player flag - MISSION_TASK_TYPE_PLACE_MODEL = 25, //!< A task for picking up a model - MISSION_TASK_TYPE_VISIT_PROPERTY = 30 //!< A task for visiting a property -}; - -#endif diff --git a/dCommon/dEnums/PermissionMap.h b/dCommon/dEnums/PermissionMap.h deleted file mode 100644 index 8c271f17..00000000 --- a/dCommon/dEnums/PermissionMap.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include <cstdint> - -/** - * Bitmap of permissions and restrictions for characters. - */ -enum class PermissionMap : uint64_t -{ - /** - * Reserved for future use, bit 0-3. - */ - - /** - * The character has restricted trade acccess, bit 4. - */ - RestrictedTradeAccess = 0x1 << 4, - - /** - * The character has restricted mail access, bit 5. - */ - RestrictedMailAccess = 0x1 << 5, - - /** - * The character has restricted chat access, bit 6. - */ - RestrictedChatAccess = 0x1 << 6, - - // - // Combined permissions - // - - /** - * The character is marked as 'old', restricted from trade and mail. - */ - Old = RestrictedTradeAccess | RestrictedMailAccess, - - /** - * The character is soft banned, restricted from trade, mail, and chat. - */ - SoftBanned = RestrictedTradeAccess | RestrictedMailAccess | RestrictedChatAccess, -}; diff --git a/dCommon/dEnums/RacingTaskParam.h b/dCommon/dEnums/RacingTaskParam.h deleted file mode 100644 index 5958cb5a..00000000 --- a/dCommon/dEnums/RacingTaskParam.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#include <cstdint> - -enum class RacingTaskParam : int32_t { - RACING_TASK_PARAM_FINISH_WITH_PLACEMENT = 1, //<! A task param for finishing with a specific placement. - RACING_TASK_PARAM_LAP_TIME = 2, //<! A task param for finishing with a specific lap time. - RACING_TASK_PARAM_TOTAL_TRACK_TIME = 3, //<! A task param for finishing with a specific track time. - RACING_TASK_PARAM_COMPLETE_ANY_RACING_TASK = 4, //<! A task param for completing a racing task. - RACING_TASK_PARAM_COMPLETE_TRACK_TASKS = 5, //<! A task param for completing a task for a specific track. - RACING_TASK_PARAM_MODULAR_BUILDING = 6, //<! A task param for modular building with racing builds. - RACING_TASK_PARAM_SAFE_DRIVER = 10, //<! A task param for completing a race without smashing. - RACING_TASK_PARAM_SMASHABLES = 11, //<! A task param for smashing entities during a race. - RACING_TASK_PARAM_COLLECT_IMAGINATION = 12, //<! A task param for collecting imagination during a race. - RACING_TASK_PARAM_COMPETED_IN_RACE = 13, //<! A task param for competing in a race. - RACING_TASK_PARAM_WIN_RACE_IN_WORLD = 14, //<! A task param for winning a race in a specific world. - RACING_TASK_PARAM_FIRST_PLACE_MULTIPLE_TRACKS = 15, //<! A task param for finishing in first place on multiple tracks. - RACING_TASK_PARAM_LAST_PLACE_FINISH = 16, //<! A task param for finishing in last place. - RACING_TASK_PARAM_SMASH_SPECIFIC_SMASHABLE = 17 //<! A task param for smashing dragon eggs during a race. -}; diff --git a/dCommon/dEnums/AddFriendResponseCode.h b/dCommon/dEnums/eAddFriendResponseCode.h similarity index 50% rename from dCommon/dEnums/AddFriendResponseCode.h rename to dCommon/dEnums/eAddFriendResponseCode.h index bb2faff7..56304c82 100644 --- a/dCommon/dEnums/AddFriendResponseCode.h +++ b/dCommon/dEnums/eAddFriendResponseCode.h @@ -1,11 +1,11 @@ #pragma once -#ifndef __ADDFRIENDRESPONSECODE__H__ -#define __ADDFRIENDRESPONSECODE__H__ +#ifndef __EADDFRIENDRESPONSECODE__H__ +#define __EADDFRIENDRESPONSECODE__H__ #include <cstdint> -enum class AddFriendResponseCode : uint8_t { +enum class eAddFriendResponseCode : uint8_t { ACCEPTED = 0, REJECTED, BUSY, diff --git a/dCommon/dEnums/AddFriendResponseType.h b/dCommon/dEnums/eAddFriendResponseType.h similarity index 59% rename from dCommon/dEnums/AddFriendResponseType.h rename to dCommon/dEnums/eAddFriendResponseType.h index 305796e8..5568aafb 100644 --- a/dCommon/dEnums/AddFriendResponseType.h +++ b/dCommon/dEnums/eAddFriendResponseType.h @@ -1,11 +1,11 @@ #pragma once -#ifndef __ADDFRIENDRESPONSETYPE__H__ -#define __ADDFRIENDRESPONSETYPE__H__ +#ifndef __EADDFRIENDRESPONSETYPE__H__ +#define __EADDFRIENDRESPONSETYPE__H__ #include <cstdint> -enum class AddFriendResponseType : uint8_t { +enum class eAddFriendResponseType : uint8_t { ACCEPTED = 0, ALREADYFRIEND, INVALIDCHARACTER, @@ -21,4 +21,4 @@ enum class AddFriendResponseType : uint8_t { FRIENDISFREETRIAL }; -#endif //!__ADDFRIENDRESPONSETYPE__H__ +#endif //!__EADDFRIENDRESPONSETYPE__H__ diff --git a/dCommon/dEnums/eBubbleType.h b/dCommon/dEnums/eBubbleType.h index 4aa6fad1..9ceef4b5 100644 --- a/dCommon/dEnums/eBubbleType.h +++ b/dCommon/dEnums/eBubbleType.h @@ -7,8 +7,8 @@ enum class eBubbleType : uint32_t { DEFAULT = 0, - ENERGY = 1, - SKUNK = 2, + ENERGY, + SKUNK }; #endif //!__EBUBBLETYPE__H__ diff --git a/dCommon/dEnums/eHelpType.h b/dCommon/dEnums/eHelpType.h new file mode 100644 index 00000000..d1838cc6 --- /dev/null +++ b/dCommon/dEnums/eHelpType.h @@ -0,0 +1,41 @@ + +#ifndef __EHELPTYPE__H__ +#define __EHELPTYPE__H__ + +#include <cstdint> + +enum class eHelpType : int32_t { + NONE = 0, + UNLOCK_MINIMAP = 2, + TOGGLETOOLTIP_OUTOFTIME_REBUILD = 3, + TOGGLETOOLTIP_LEAVELOSE_REBUILD = 4, + TOGGLECONTROLSTUTORIAL_WALKING = 6, + DISPLAYTUTORIAL_PASSPORT_1ST_SMASH = 7, + TOOLTIP_1ST_IMAGINATION_PICKUP = 8, + UNKNOWN9 = 9, + PETTAMINGMINIGAME_TUTORIAL_01 = 15, + PR_BOUNCER_TUTORIAL_03 = 16, + PR_TOOLTIP_1ST_PET_JUMPED_ON_SWITCH = 17, + PR_DIG_TUTORIAL_01 = 18, + PR_DIG_TUTORIAL_03 = 19, + PR_BOUNCER_TUTORIAL_01 = 20, + PR_NO_IMAGINATION_HIBERNATE = 21, + UNKNOWN22 = 22, + TOGGLECONTROLSTUTORIAL_JUMPING = 26, + TOGGLECONTROLSTUTORIAL_DOUBLEJUMPING = 27, + TOGGLECONTROLSTUTORIAL_CAMERA = 28, + TOGGLECONTROLSTUTORIAL_SMASH = 30, + UNKNOWN38 = 38, + UI_MOD_BUILD_PUT_ON_HAT = 40, + UI_MOD_BUILD_EQUIP_FIRST_MODULE = 41, + UNKNOWN42 = 42, + UNKNOWN43 = 43, + UI_MOD_BUILD_GO_LAUNCH_ROCKET = 44, + UI_MOD_BUILD_TALK_TO_SKYLANE = 45, + UNKNOWN53 = 53, + PET_DESPAWN_BY_OWNER_HIBERNATE = 69, + PET_DESPAWN_TAMING_NEW_PET = 70, + UI_INVENTORY_FULL_CANNOT_PICKUP_ITEM = 86 +}; + +#endif //!__EHELPTYPE__H__ diff --git a/dCommon/dEnums/eItemSetPassiveAbilityID.h b/dCommon/dEnums/eItemSetPassiveAbilityID.h new file mode 100644 index 00000000..8641d0f2 --- /dev/null +++ b/dCommon/dEnums/eItemSetPassiveAbilityID.h @@ -0,0 +1,58 @@ +#pragma once + +#ifndef __EITEMSETPASSIVEABILITYID__H__ +#define __EITEMSETPASSIVEABILITYID__H__ + +enum class eItemSetPassiveAbilityID { + EngineerRank1 = 2, + EngineerRank2 = 3, + EngineerRank3 = 4, + KnightRank1 = 7, + KnightRank2 = 8, + KnightRank3 = 9, + SpaceRangerRank1 = 10, + SpaceRangerRank2 = 11, + SpaceRangerRank3 = 12, + SamuraiRank1 = 13, + SamuraiRank2 = 14, + SamuraiRank3 = 15, + SorcererRank1 = 16, + SorcererRank2 = 17, + SorcererRank3 = 18, + SpaceMarauderRank1 = 19, + SpaceMarauderRank2 = 20, + SpaceMarauderRank3 = 21, + ShinobiRank1 = 22, + ShinobiRank2 = 23, + ShinobiRank3 = 24, + InventorRank1 = 25, + InventorRank2 = 26, + InventorRank3 = 27, + SummonerRank1 = 28, + SummonerRank2 = 29, + SummonerRank3 = 30, + AdventurerRank1 = 31, + AdventurerRank2 = 32, + AdventurerRank3 = 33, + DaredevilRank1 = 34, + DaredevilRank2 = 35, + DaredevilRank3 = 36, + BuccaneerRank1 = 37, + BuccaneerRank2 = 38, + BuccaneerRank3 = 39, + BoneSuit = 40, + ImaginationSpinjitzu = 41, + BatLord = 42, + MosaicJester = 43, + ExplorienBot = 44, + Unnamed1 = 45, + Unnamed2 = 46, + Unnamed3 = 47, + EarthSpinjitzu = 48, + Unnamed4 = 49, + FireSpinjitzu = 50, + IceSpinjitzu = 51, + LightningSpinjitzu = 52 +}; + +#endif //!__EITEMSETPASSIVEABILITYID__H__ diff --git a/dCommon/dEnums/eItemType.h b/dCommon/dEnums/eItemType.h index e68ce695..69eb18e9 100644 --- a/dCommon/dEnums/eItemType.h +++ b/dCommon/dEnums/eItemType.h @@ -6,31 +6,31 @@ #include <cstdint> enum class eItemType : int32_t { - ITEM_TYPE_UNKNOWN = -1, //!< An unknown item type - ITEM_TYPE_BRICK = 1, //!< A brick - ITEM_TYPE_HAT = 2, //!< A hat / head item - ITEM_TYPE_HAIR = 3, //!< A hair item - ITEM_TYPE_NECK = 4, //!< A neck item - ITEM_TYPE_LEFT_HAND = 5, //!< A left handed item - ITEM_TYPE_RIGHT_HAND = 6, //!< A right handed item - ITEM_TYPE_LEGS = 7, //!< A pants item - ITEM_TYPE_LEFT_TRINKET = 8, //!< A left handled trinket item - ITEM_TYPE_RIGHT_TRINKET = 9, //!< A right handed trinket item - ITEM_TYPE_BEHAVIOR = 10, //!< A behavior - ITEM_TYPE_PROPERTY = 11, //!< A property - ITEM_TYPE_MODEL = 12, //!< A model - ITEM_TYPE_COLLECTIBLE = 13, //!< A collectible item - ITEM_TYPE_CONSUMABLE = 14, //!< A consumable item - ITEM_TYPE_CHEST = 15, //!< A chest item - ITEM_TYPE_EGG = 16, //!< An egg - ITEM_TYPE_PET_FOOD = 17, //!< A pet food item - ITEM_TYPE_QUEST_OBJECT = 18, //!< A quest item - ITEM_TYPE_PET_INVENTORY_ITEM = 19, //!< A pet inventory item - ITEM_TYPE_PACKAGE = 20, //!< A package - ITEM_TYPE_LOOT_MODEL = 21, //!< A loot model - ITEM_TYPE_VEHICLE = 22, //!< A vehicle - ITEM_TYPE_CURRENCY = 23, //!< Currency - ITEM_TYPE_MOUNT = 24 //!< A Mount + UNKNOWN = -1, + BRICK, + HAT, + HAIR, + NECK, + LEFT_HAND, + RIGHT_HAND, + LEGS, + LEFT_TRINKET, + RIGHT_TRINKET, + BEHAVIOR, + PROPERTY, + MODEL, + COLLECTIBLE, + CONSUMABLE, + CHEST, + EGG, + PET_FOOD, + QUEST_OBJECT, + PET_INVENTORY_ITEM, + PACKAGE, + LOOT_MODEL, + VEHICLE, + LUP_MODEL, + MOUNT }; #endif //!__EITEMTYPE__H__ diff --git a/dCommon/dEnums/eMissionLockState.h b/dCommon/dEnums/eMissionLockState.h new file mode 100644 index 00000000..52752767 --- /dev/null +++ b/dCommon/dEnums/eMissionLockState.h @@ -0,0 +1,12 @@ +#pragma once + +#ifndef __EMISSIONLOCKSTATE__H__ +#define __EMISSIONLOCKSTATE__H__ + +enum class eMissionLockState : int { + LOCKED, + NEW, + UNLOCKED, +}; + +#endif //!__EMISSIONLOCKSTATE__H__ diff --git a/dCommon/dEnums/eMissionState.h b/dCommon/dEnums/eMissionState.h new file mode 100644 index 00000000..e080f455 --- /dev/null +++ b/dCommon/dEnums/eMissionState.h @@ -0,0 +1,56 @@ +#pragma once + +#ifndef __MISSIONSTATE__H__ +#define __MISSIONSTATE__H__ + +/** + * Represents the possible states a mission can be in + */ +enum class eMissionState : int { + /** + * The mission state is unknown + */ + UNKNOWN = -1, + + /** + * The mission is yielding rewards + */ + REWARDING = 0, + + /** + * The mission can be accepted + */ + AVAILABLE = 1, + + /** + * The mission has been accepted but not yet completed + */ + ACTIVE = 2, + + /** + * All the tasks for the mission have been completed and the entity can turn the mission in to complete it + */ + READY_TO_COMPLETE = 4, //!< The mission is ready to complete + + /** + * The mission has been completed + */ + COMPLETE = 8, + + /** + * The mission is available again and has been completed before. Used for daily missions. + */ + COMPLETE_AVAILABLE = 9, + + /** + * The mission is active and has been completed before. Used for daily missions. + */ + COMPLETE_ACTIVE = 10, + + /** + * The mission has been completed before and has now been completed again. Used for daily missions. + */ + COMPLETE_READY_TO_COMPLETE = 12 +}; + +#endif //!__MISSIONSTATE__H__ diff --git a/dCommon/dEnums/eMissionTaskType.h b/dCommon/dEnums/eMissionTaskType.h new file mode 100644 index 00000000..2636f88c --- /dev/null +++ b/dCommon/dEnums/eMissionTaskType.h @@ -0,0 +1,43 @@ +#pragma once + +#ifndef __EMISSIONTASKTYPE__H__ +#define __EMISSIONTASKTYPE__H__ + +enum class eMissionTaskType : int { + UNKNOWN = -1, + SMASH, + SCRIPT, + ACTIVITY, + COLLECTION, + TALK_TO_NPC, + EMOTE, + SHASH_CHAIN, + BUY, + SELL, + USE_ITEM, + USE_SKILL, + GATHER, + EXPLORE, + DELIVERY, + PERFORM_ACTIVITY, + INTERACT, + META, + EARN_REPUTATION, + VOTING, + SHOWCASE_DELIVERY, + REVIECE_CAST, + POWERUP, + PET_TAMING, + RACING, + PLAYER_FLAG, + PLACE_MODEL, + REMOVE_MODEL, + ADD_BEHAVIOR, + REMOVE_BEHAVIOR, + CLAIM_PROPERTY, + VISIT_PROPERTY, + TIME_PLAYED, + DONATION +}; + +#endif //!__EMISSIONTASKTYPE__H__ diff --git a/dCommon/dEnums/ePackageType.h b/dCommon/dEnums/ePackageType.h new file mode 100644 index 00000000..2c1c9977 --- /dev/null +++ b/dCommon/dEnums/ePackageType.h @@ -0,0 +1,13 @@ +#ifndef __EPACKAGETYPE__H__ +#define __EPACKAGETYPE__H__ + +enum class ePackageType { + INVALID = -1, + ITEM, + BRICKS, + MODELS, + CAR_MODELS +}; + + +#endif //!__EPACKAGETYPE__H__ diff --git a/dCommon/dEnums/ePermissionMap.h b/dCommon/dEnums/ePermissionMap.h new file mode 100644 index 00000000..d15c9fd3 --- /dev/null +++ b/dCommon/dEnums/ePermissionMap.h @@ -0,0 +1,46 @@ +#pragma once + +#include <cstdint> + +#ifndef __EPERMISSIONMAP__H__ +#define __EPERMISSIONMAP__H__ + +/** + * Bitmap of permissions and restrictions for characters. + */ +enum class ePermissionMap : uint64_t { + /** + * Reserved for future use, bit 0-3. + */ + + /** + * The character has restricted trade acccess, bit 4. + */ + RestrictedTradeAccess = 0x1 << 4, + + /** + * The character has restricted mail access, bit 5. + */ + RestrictedMailAccess = 0x1 << 5, + + /** + * The character has restricted chat access, bit 6. + */ + RestrictedChatAccess = 0x1 << 6, + + // + // Combined permissions + // + + /** + * The character is marked as 'old', restricted from trade and mail. + */ + Old = RestrictedTradeAccess | RestrictedMailAccess, + + /** + * The character is soft banned, restricted from trade, mail, and chat. + */ + SoftBanned = RestrictedTradeAccess | RestrictedMailAccess | RestrictedChatAccess, +}; + +#endif //!__EPERMISSIONMAP__H__ diff --git a/dCommon/dEnums/eRacingTaskParam.h b/dCommon/dEnums/eRacingTaskParam.h new file mode 100644 index 00000000..df50e382 --- /dev/null +++ b/dCommon/dEnums/eRacingTaskParam.h @@ -0,0 +1,25 @@ +#pragma once + +#ifndef __ERACINGTASKPARAM__H__ +#define __ERACINGTASKPARAM__H__ + +#include <cstdint> + +enum class eRacingTaskParam : int32_t { + FINISH_WITH_PLACEMENT = 1, + LAP_TIME, + TOTAL_TRACK_TIME, + COMPLETE_ANY_RACING_TASK, + COMPLETE_TRACK_TASKS, + MODULAR_BUILDING, + SAFE_DRIVER = 10, + SMASHABLES, + COLLECT_IMAGINATION, + COMPETED_IN_RACE, + WIN_RACE_IN_WORLD, + FIRST_PLACE_MULTIPLE_TRACKS, + LAST_PLACE_FINISH, + SMASH_SPECIFIC_SMASHABLE +}; + +#endif //!__ERACINGTASKPARAM__H__ diff --git a/dGame/Character.cpp b/dGame/Character.cpp index 67a0bf1b..572a3e9e 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -16,6 +16,8 @@ #include "ChatPackets.h" #include "Inventory.h" #include "InventoryComponent.h" +#include "eMissionTaskType.h" +#include "eMissionState.h" Character::Character(uint32_t id, User* parentUser) { //First load the name, etc: @@ -34,7 +36,7 @@ Character::Character(uint32_t id, User* parentUser) { m_UnapprovedName = res->getString(2).c_str(); m_NameRejected = res->getBoolean(3); m_PropertyCloneID = res->getUInt(4); - m_PermissionMap = static_cast<PermissionMap>(res->getUInt64(5)); + m_PermissionMap = static_cast<ePermissionMap>(res->getUInt64(5)); } delete res; @@ -93,7 +95,7 @@ void Character::UpdateFromDatabase() { m_UnapprovedName = res->getString(2).c_str(); m_NameRejected = res->getBoolean(3); m_PropertyCloneID = res->getUInt(4); - m_PermissionMap = static_cast<PermissionMap>(res->getUInt64(5)); + m_PermissionMap = static_cast<ePermissionMap>(res->getUInt64(5)); } delete res; @@ -423,7 +425,7 @@ void Character::SetPlayerFlag(const uint32_t flagId, const bool value) { auto* missionComponent = player->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_PLAYER_FLAG, flagId); + missionComponent->Progress(eMissionTaskType::PLAYER_FLAG, flagId); } } } @@ -535,7 +537,7 @@ void Character::OnZoneLoad() { if (missionComponent != nullptr) { // Fix the monument race flag - if (missionComponent->GetMissionState(319) >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { + if (missionComponent->GetMissionState(319) >= eMissionState::READY_TO_COMPLETE) { SetPlayerFlag(33, true); } } @@ -550,7 +552,7 @@ void Character::OnZoneLoad() { /** * Restrict old character to 1 million coins */ - if (HasPermission(PermissionMap::Old)) { + if (HasPermission(ePermissionMap::Old)) { if (GetCoins() > 1000000) { SetCoins(1000000, eLootSourceType::LOOT_SOURCE_NONE); } @@ -568,11 +570,11 @@ void Character::OnZoneLoad() { } } -PermissionMap Character::GetPermissionMap() const { +ePermissionMap Character::GetPermissionMap() const { return m_PermissionMap; } -bool Character::HasPermission(PermissionMap permission) const { +bool Character::HasPermission(ePermissionMap permission) const { return (static_cast<uint64_t>(m_PermissionMap) & static_cast<uint64_t>(permission)) != 0; } diff --git a/dGame/Character.h b/dGame/Character.h index 07bde36c..abded1b3 100644 --- a/dGame/Character.h +++ b/dGame/Character.h @@ -9,11 +9,12 @@ #include "NiPoint3.h" #include "NiQuaternion.h" -#include "PermissionMap.h" +#include "ePermissionMap.h" class User; struct Packet; class Entity; +enum class ePermissionMap : uint64_t; /** * Meta information about a character, like their name and style @@ -385,14 +386,14 @@ public: * Gets the permissions of the character, determining what actions a character may do * @return the permissions for this character */ - PermissionMap GetPermissionMap() const; + ePermissionMap GetPermissionMap() const; /** * Check if this character has a certain permission * @param permission the ID of the permission to check for * @return whether the character has the specified permission */ - bool HasPermission(PermissionMap permission) const; + bool HasPermission(ePermissionMap permission) const; /** * Gets all the emotes this character has unlocked so far @@ -481,7 +482,7 @@ private: /** * Bitmap of permission attributes this character has. */ - PermissionMap m_PermissionMap; + ePermissionMap m_PermissionMap; /** * The default name of this character diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index c0f71324..eefa5107 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -22,6 +22,7 @@ #include "EntityTimer.h" #include "EntityCallbackTimer.h" #include "Loot.h" +#include "eMissionTaskType.h" //Component includes: #include "Component.h" @@ -1318,7 +1319,7 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) { auto* missionComponent = other->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_LOCATION, 0, 0, GeneralUtils::UTF16ToWTF8(poi)); + missionComponent->Progress(eMissionTaskType::EXPLORE, 0, 0, GeneralUtils::UTF16ToWTF8(poi)); } } @@ -1614,7 +1615,7 @@ void Entity::PickupItem(const LWOOBJID& objectID) { auto* missionComponent = GetComponent<MissionComponent>(); if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_POWERUP, skill.skillID); + missionComponent->Progress(eMissionTaskType::POWERUP, skill.skillID); } } } else { diff --git a/dGame/TradingManager.cpp b/dGame/TradingManager.cpp index ed55f217..e1eac422 100644 --- a/dGame/TradingManager.cpp +++ b/dGame/TradingManager.cpp @@ -9,6 +9,7 @@ #include "Character.h" #include "CharacterComponent.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" TradingManager* TradingManager::m_Address = nullptr; @@ -161,14 +162,14 @@ void Trade::Complete() { for (const auto& tradeItem : m_ItemsA) { auto* itemToRemove = inventoryA->FindItemById(tradeItem.itemId); if (itemToRemove) itemToRemove->SetCount(itemToRemove->GetCount() - tradeItem.itemCount); - missionsA->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); + missionsA->Progress(eMissionTaskType::GATHER, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); inventoryB->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); } for (const auto& tradeItem : m_ItemsB) { auto* itemToRemove = inventoryB->FindItemById(tradeItem.itemId); if (itemToRemove) itemToRemove->SetCount(itemToRemove->GetCount() - tradeItem.itemCount); - missionsB->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); + missionsB->Progress(eMissionTaskType::GATHER, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); inventoryA->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); } diff --git a/dGame/dComponents/AchievementCacheKey.h b/dGame/dComponents/AchievementCacheKey.h index d8892197..398e0231 100644 --- a/dGame/dComponents/AchievementCacheKey.h +++ b/dGame/dComponents/AchievementCacheKey.h @@ -1,3 +1,5 @@ +#include "eMissionTaskType.h" + #ifndef __ACHIEVEMENTCACHEKEY__H__ #define __ACHIEVEMENTCACHEKEY__H__ @@ -6,7 +8,7 @@ public: AchievementCacheKey() { targets = ""; value = 0; - type = MissionTaskType::MISSION_TASK_TYPE_UNKNOWN; + type = eMissionTaskType::UNKNOWN; }; bool operator==(const AchievementCacheKey& point) const { @@ -14,15 +16,15 @@ public: }; void SetTargets(const std::string value) { this->targets = value; }; void SetValue(uint32_t value) { this->value = value; }; - void SetType(MissionTaskType value) { this->type = value; }; + void SetType(eMissionTaskType value) { this->type = value; }; std::string GetTargets() const { return this->targets; }; uint32_t GetValue() const { return this->value; }; - MissionTaskType GetType() const { return this->type; }; + eMissionTaskType GetType() const { return this->type; }; private: std::string targets; uint32_t value; - MissionTaskType type; + eMissionTaskType type; }; diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 1455ce58..4763c863 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -32,6 +32,7 @@ #include "InventoryComponent.h" #include "dZoneManager.h" #include "WorldConfig.h" +#include "eMissionTaskType.h" DestroyableComponent::DestroyableComponent(Entity* parent) : Component(parent) { m_iArmor = 0; @@ -467,9 +468,9 @@ bool DestroyableComponent::IsKnockbackImmune() const { if (characterComponent != nullptr && inventoryComponent != nullptr && characterComponent->GetCurrentActivity() == eGameActivities::ACTIVITY_QUICKBUILDING) { const auto hasPassive = inventoryComponent->HasAnyPassive({ - ItemSetPassiveAbilityID::EngineerRank2, ItemSetPassiveAbilityID::EngineerRank3, - ItemSetPassiveAbilityID::SummonerRank2, ItemSetPassiveAbilityID::SummonerRank3, - ItemSetPassiveAbilityID::InventorRank2, ItemSetPassiveAbilityID::InventorRank3, + eItemSetPassiveAbilityID::EngineerRank2, eItemSetPassiveAbilityID::EngineerRank3, + eItemSetPassiveAbilityID::SummonerRank2, eItemSetPassiveAbilityID::SummonerRank3, + eItemSetPassiveAbilityID::InventorRank2, eItemSetPassiveAbilityID::InventorRank3, }, 5); if (hasPassive) { @@ -736,12 +737,12 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType if (memberMissions == nullptr) continue; - memberMissions->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, m_Parent->GetLOT()); - memberMissions->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, m_Parent->GetLOT(), skillID); + memberMissions->Progress(eMissionTaskType::SMASH, m_Parent->GetLOT()); + memberMissions->Progress(eMissionTaskType::USE_SKILL, m_Parent->GetLOT(), skillID); } } else { - missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, m_Parent->GetLOT()); - missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, m_Parent->GetLOT(), skillID); + missions->Progress(eMissionTaskType::SMASH, m_Parent->GetLOT()); + missions->Progress(eMissionTaskType::USE_SKILL, m_Parent->GetLOT(), skillID); } } } diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index e5ff2f2a..8925554e 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -28,6 +28,7 @@ #include "eItemType.h" #include "eUnequippableActiveType.h" #include "CppScripts.h" +#include "eMissionTaskType.h" InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document): Component(parent) { this->m_Dirty = true; @@ -196,7 +197,7 @@ void InventoryComponent::AddItem( auto* item = new Item(lot, inventory, slot, count, config, parent, showFlyingLoot, isModMoveAndEquip, subKey, bound, lootSourceType); if (missions != nullptr && !IsTransferInventory(inventoryType)) { - missions->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, LWOOBJID_EMPTY, "", count, IsTransferInventory(inventorySourceType)); + missions->Progress(eMissionTaskType::GATHER, lot, LWOOBJID_EMPTY, "", count, IsTransferInventory(inventorySourceType)); } return; @@ -284,7 +285,7 @@ void InventoryComponent::AddItem( } if (missions != nullptr && !IsTransferInventory(inventoryType)) { - missions->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, LWOOBJID_EMPTY, "", count - outOfSpace, IsTransferInventory(inventorySourceType)); + missions->Progress(eMissionTaskType::GATHER, lot, LWOOBJID_EMPTY, "", count - outOfSpace, IsTransferInventory(inventorySourceType)); } } @@ -373,7 +374,7 @@ void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType in if (missionComponent != nullptr) { if (IsTransferInventory(inventory)) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, LWOOBJID_EMPTY, "", -static_cast<int32_t>(count)); + missionComponent->Progress(eMissionTaskType::GATHER, lot, LWOOBJID_EMPTY, "", -static_cast<int32_t>(count)); } } } @@ -841,9 +842,9 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { const auto type = static_cast<eItemType>(item->GetInfo().itemType); - if (!building && (item->GetLot() == 6086 || type == eItemType::ITEM_TYPE_LOOT_MODEL || type == eItemType::ITEM_TYPE_VEHICLE)) return; + if (!building && (item->GetLot() == 6086 || type == eItemType::LOOT_MODEL || type == eItemType::VEHICLE)) return; - if (type != eItemType::ITEM_TYPE_LOOT_MODEL && type != eItemType::ITEM_TYPE_MODEL) { + if (type != eItemType::LOOT_MODEL && type != eItemType::MODEL) { if (!item->GetBound() && !item->GetPreconditionExpression()->Check(m_Parent)) { return; } @@ -1202,14 +1203,14 @@ void InventoryComponent::TriggerPassiveAbility(PassiveAbilityTrigger trigger, En } } -bool InventoryComponent::HasAnyPassive(const std::vector<ItemSetPassiveAbilityID>& passiveIDs, int32_t equipmentRequirement) const { +bool InventoryComponent::HasAnyPassive(const std::vector<eItemSetPassiveAbilityID>& passiveIDs, int32_t equipmentRequirement) const { for (auto* set : m_Itemsets) { if (set->GetEquippedCount() < equipmentRequirement) { continue; } // Check if the set has any of the passive abilities - if (std::find(passiveIDs.begin(), passiveIDs.end(), static_cast<ItemSetPassiveAbilityID>(set->GetID())) != passiveIDs.end()) { + if (std::find(passiveIDs.begin(), passiveIDs.end(), static_cast<eItemSetPassiveAbilityID>(set->GetID())) != passiveIDs.end()) { return true; } } @@ -1285,15 +1286,15 @@ void InventoryComponent::RemoveDatabasePet(LWOOBJID id) { BehaviorSlot InventoryComponent::FindBehaviorSlot(const eItemType type) { switch (type) { - case eItemType::ITEM_TYPE_HAT: + case eItemType::HAT: return BehaviorSlot::Head; - case eItemType::ITEM_TYPE_NECK: + case eItemType::NECK: return BehaviorSlot::Neck; - case eItemType::ITEM_TYPE_LEFT_HAND: + case eItemType::LEFT_HAND: return BehaviorSlot::Offhand; - case eItemType::ITEM_TYPE_RIGHT_HAND: + case eItemType::RIGHT_HAND: return BehaviorSlot::Primary; - case eItemType::ITEM_TYPE_CONSUMABLE: + case eItemType::CONSUMABLE: return BehaviorSlot::Consumable; default: return BehaviorSlot::Invalid; @@ -1343,7 +1344,7 @@ std::vector<uint32_t> InventoryComponent::FindBuffs(Item* item, bool castOnEquip } if (missions != nullptr && castOnEquip) { - missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, result.skillID); + missions->Progress(eMissionTaskType::USE_SKILL, result.skillID); } // If item is not a proxy, add its buff to the added buffs. diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index f63a8d70..b660de15 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -17,7 +17,7 @@ #include "DatabasePet.h" #include "Component.h" #include "ItemSetPassiveAbility.h" -#include "ItemSetPassiveAbilityID.h" +#include "eItemSetPassiveAbilityID.h" #include "PossessorComponent.h" #include "eInventoryType.h" @@ -291,7 +291,7 @@ public: * @param equipmentRequirement the number of equipment required to be allowed to have the ability * @return if the entity has any of the passed passive abilities equipped */ - bool HasAnyPassive(const std::vector<ItemSetPassiveAbilityID>& passiveIDs, int32_t equipmentRequirement) const; + bool HasAnyPassive(const std::vector<eItemSetPassiveAbilityID>& passiveIDs, int32_t equipmentRequirement) const; /** * Despawns the currently active pet, if any @@ -354,14 +354,14 @@ public: /** * Call this when you equip an item. This calls OnFactionTriggerItemEquipped for any scripts found on the items. - * + * * @param equippedItem The item script to lookup and call equip on */ void EquipScripts(Item* equippedItem); - + /** * Call this when you unequip an item. This calls OnFactionTriggerItemUnequipped for any scripts found on the items. - * + * * @param unequippedItem The item script to lookup and call unequip on */ void UnequipScripts(Item* unequippedItem); diff --git a/dGame/dComponents/MissionComponent.cpp b/dGame/dComponents/MissionComponent.cpp index 2ef6c2f6..cbae7f9f 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -18,6 +18,7 @@ #include "Mail.h" #include "MissionPrerequisites.h" #include "AchievementCacheKey.h" +#include "eMissionState.h" // MARK: Mission Component @@ -53,11 +54,11 @@ Mission* MissionComponent::GetMission(const uint32_t missionId) const { } -MissionState MissionComponent::GetMissionState(const uint32_t missionId) const { +eMissionState MissionComponent::GetMissionState(const uint32_t missionId) const { auto* mission = GetMission(missionId); if (mission == nullptr) { - return CanAccept(missionId) ? MissionState::MISSION_STATE_AVAILABLE : MissionState::MISSION_STATE_UNKNOWN; + return CanAccept(missionId) ? eMissionState::AVAILABLE : eMissionState::UNKNOWN; } return mission->GetMissionState(); @@ -143,7 +144,7 @@ void MissionComponent::RemoveMission(uint32_t missionId) { m_Missions.erase(missionId); } -void MissionComponent::Progress(MissionTaskType type, int32_t value, LWOOBJID associate, const std::string& targets, int32_t count, bool ignoreAchievements) { +void MissionComponent::Progress(eMissionTaskType type, int32_t value, LWOOBJID associate, const std::string& targets, int32_t count, bool ignoreAchievements) { for (const auto& pair : m_Missions) { auto* mission = pair.second; @@ -215,7 +216,7 @@ void MissionComponent::ForceProgressTaskType(const uint32_t missionId, const uin } for (auto* element : mission->GetTasks()) { - if (element->GetType() != static_cast<MissionTaskType>(taskType)) continue; + if (element->GetType() != static_cast<eMissionTaskType>(taskType)) continue; element->AddProgress(value); } @@ -253,7 +254,7 @@ void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, } for (auto* element : mission->GetTasks()) { - if (element->GetType() != static_cast<MissionTaskType>(taskType) || !element->InAllTargets(value)) continue; + if (element->GetType() != static_cast<eMissionTaskType>(taskType) || !element->InAllTargets(value)) continue; element->AddProgress(1); } @@ -281,7 +282,7 @@ bool MissionComponent::GetMissionInfo(uint32_t missionId, CDMissions& result) { #define MISSION_NEW_METHOD -bool MissionComponent::LookForAchievements(MissionTaskType type, int32_t value, bool progress, LWOOBJID associate, const std::string& targets, int32_t count) { +bool MissionComponent::LookForAchievements(eMissionTaskType type, int32_t value, bool progress, LWOOBJID associate, const std::string& targets, int32_t count) { #ifdef MISSION_NEW_METHOD // Query for achievments, using the cache const auto& result = QueryAchievements(type, value, targets); @@ -390,7 +391,7 @@ bool MissionComponent::LookForAchievements(MissionTaskType type, int32_t value, #endif } -const std::vector<uint32_t>& MissionComponent::QueryAchievements(MissionTaskType type, int32_t value, const std::string targets) { +const std::vector<uint32_t>& MissionComponent::QueryAchievements(eMissionTaskType type, int32_t value, const std::string targets) { // Create a hash which represent this query for achievements AchievementCacheKey toFind; toFind.SetType(type); @@ -484,7 +485,7 @@ bool MissionComponent::RequiresItem(const LOT lot) { } for (auto* task : mission->GetTasks()) { - if (task->IsComplete() || task->GetType() != MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { + if (task->IsComplete() || task->GetType() != eMissionTaskType::GATHER) { continue; } @@ -496,7 +497,7 @@ bool MissionComponent::RequiresItem(const LOT lot) { } } - const auto required = LookForAchievements(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, lot, false); + const auto required = LookForAchievements(eMissionTaskType::GATHER, lot, false); return required; } diff --git a/dGame/dComponents/MissionComponent.h b/dGame/dComponents/MissionComponent.h index a3e39a88..231b3321 100644 --- a/dGame/dComponents/MissionComponent.h +++ b/dGame/dComponents/MissionComponent.h @@ -19,11 +19,11 @@ class AchievementCacheKey; -/** - * The mission inventory of an entity. Tracks mission state for each mission that can be accepted and allows for - * progression of each of the mission task types (see MissionTaskType). - */ -class MissionComponent: public Component + /** + * The mission inventory of an entity. Tracks mission state for each mission that can be accepted and allows for + * progression of each of the mission task types (see eMissionTaskType). + */ +class MissionComponent : public Component { public: static const uint32_t ComponentType = COMPONENT_TYPE_MISSION; @@ -52,7 +52,7 @@ public: * @param missionId the ID of the mission to get the mission state for * @return the mission state of the mission specified by the ID */ - MissionState GetMissionState(uint32_t missionId) const; + eMissionState GetMissionState(uint32_t missionId) const; /** * Checks if the entity has all the requirements for accepting the mission specified by the ID. @@ -93,7 +93,7 @@ public: * @param count the number to progress by, for example the number of items * @param ignoreAchievements do not progress achievements */ - void Progress(MissionTaskType type, int32_t value, LWOOBJID associate = 0, const std::string& targets = "", int32_t count = 1, bool ignoreAchievements = false); + void Progress(eMissionTaskType type, int32_t value, LWOOBJID associate = 0, const std::string& targets = "", int32_t count = 1, bool ignoreAchievements = false); /** * Forces progression for a mission and task, ignoring checks @@ -140,7 +140,7 @@ public: * @param count the number of values to progress by (differs by task type) * @return true if a achievement was accepted, false otherwise */ - bool LookForAchievements(MissionTaskType type, int32_t value, bool progress = true, LWOOBJID associate = LWOOBJID_EMPTY, const std::string& targets = "", int32_t count = 1); + bool LookForAchievements(eMissionTaskType type, int32_t value, bool progress = true, LWOOBJID associate = LWOOBJID_EMPTY, const std::string& targets = "", int32_t count = 1); /** * Checks if there's a mission active that requires the collection of the specified LOT @@ -188,7 +188,7 @@ private: * @param targets optional targets to progress with * @return list of mission IDs (achievements) that can be progressed for the given parameters */ - static const std::vector<uint32_t>& QueryAchievements(MissionTaskType type, int32_t value, const std::string targets); + static const std::vector<uint32_t>& QueryAchievements(eMissionTaskType type, int32_t value, const std::string targets); /** * As achievements can be hard to query, we here store a list of all the mission IDs that can be unlocked for a diff --git a/dGame/dComponents/MissionOfferComponent.cpp b/dGame/dComponents/MissionOfferComponent.cpp index 2f2ed0f0..f8446868 100644 --- a/dGame/dComponents/MissionOfferComponent.cpp +++ b/dGame/dComponents/MissionOfferComponent.cpp @@ -14,6 +14,7 @@ #include "dLogger.h" #include "Game.h" #include "MissionPrerequisites.h" +#include "eMissionState.h" OfferedMission::OfferedMission(const uint32_t missionId, const bool offersMission, const bool acceptsMission) { this->missionId = missionId; @@ -170,10 +171,10 @@ void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifi for (const auto sample : randomMissionPool) { const auto state = missionComponent->GetMissionState(sample); - if (state == MissionState::MISSION_STATE_ACTIVE || - state == MissionState::MISSION_STATE_COMPLETE_ACTIVE || - state == MissionState::MISSION_STATE_READY_TO_COMPLETE || - state == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE || + if (state == eMissionState::ACTIVE || + state == eMissionState::COMPLETE_ACTIVE || + state == eMissionState::READY_TO_COMPLETE || + state == eMissionState::COMPLETE_READY_TO_COMPLETE || sample == specifiedMissionId) { mission = missionComponent->GetMission(sample); diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 771a9cc1..5549f952 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -21,6 +21,8 @@ #include "dChatFilter.h" #include "Database.h" #include "EntityInfo.h" +#include "eMissionTaskType.h" + std::unordered_map<LOT, PetComponent::PetPuzzleData> PetComponent::buildCache{}; std::unordered_map<LWOOBJID, LWOOBJID> PetComponent::currentActivities{}; @@ -602,7 +604,7 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { auto* missionComponent = tamer->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_PET_TAMING, m_Parent->GetLOT()); + missionComponent->Progress(eMissionTaskType::PET_TAMING, m_Parent->GetLOT()); } SetStatus(1); diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index 8d23c17e..ce2c8e5e 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -18,6 +18,7 @@ #include "RocketLaunchpadControlComponent.h" #include "PropertyEntranceComponent.h" #include "InventoryComponent.h" +#include "eMissionTaskType.h" #include <vector> #include "CppScripts.h" @@ -404,7 +405,7 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N }); // Progress place model missions auto missionComponent = entity->GetComponent<MissionComponent>(); - if (missionComponent != nullptr) missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_PLACE_MODEL, 0); + if (missionComponent != nullptr) missionComponent->Progress(eMissionTaskType::PLACE_MODEL, 0); } void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int deleteReason) { diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index f64dbc15..4b27ac0f 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -15,13 +15,14 @@ #include "Player.h" #include "PossessableComponent.h" #include "PossessorComponent.h" -#include "RacingTaskParam.h" +#include "eRacingTaskParam.h" #include "Spawner.h" #include "VehiclePhysicsComponent.h" #include "dServer.h" #include "dZoneManager.h" #include "dConfig.h" #include "Loot.h" +#include "eMissionTaskType.h" #ifndef M_PI #define M_PI 3.14159265358979323846264338327950288 @@ -395,18 +396,18 @@ void RacingControlComponent::HandleMessageBoxResponse(Entity* player, if (missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPETED_IN_RACE); // Progress task for competing in a race - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, data->smashedTimes, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SAFE_DRIVER); // Finish a race without being smashed. + missionComponent->Progress(eMissionTaskType::RACING, 0, (LWOOBJID)eRacingTaskParam::COMPETED_IN_RACE); // Progress task for competing in a race + missionComponent->Progress(eMissionTaskType::RACING, data->smashedTimes, (LWOOBJID)eRacingTaskParam::SAFE_DRIVER); // Finish a race without being smashed. // If solo racing is enabled OR if there are 3 players in the race, progress placement tasks. if (m_SoloRacing || m_LoadedPlayers > 2) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, data->finished, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_FINISH_WITH_PLACEMENT); // Finish in 1st place on a race + missionComponent->Progress(eMissionTaskType::RACING, data->finished, (LWOOBJID)eRacingTaskParam::FINISH_WITH_PLACEMENT); // Finish in 1st place on a race if (data->finished == 1) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_FIRST_PLACE_MULTIPLE_TRACKS); // Finish in 1st place on multiple tracks. - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_WIN_RACE_IN_WORLD); // Finished first place in specific world. + missionComponent->Progress(eMissionTaskType::RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)eRacingTaskParam::FIRST_PLACE_MULTIPLE_TRACKS); // Finish in 1st place on multiple tracks. + missionComponent->Progress(eMissionTaskType::RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)eRacingTaskParam::WIN_RACE_IN_WORLD); // Finished first place in specific world. } if (data->finished == m_LoadedPlayers) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_LAST_PLACE_FINISH); // Finished first place in specific world. + missionComponent->Progress(eMissionTaskType::RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)eRacingTaskParam::LAST_PLACE_FINISH); // Finished first place in specific world. } } } else if (id == "ACT_RACE_EXIT_THE_RACE?" || id == "Exit") { @@ -828,7 +829,7 @@ void RacingControlComponent::Update(float deltaTime) { if (missionComponent != nullptr) { // Progress lap time tasks - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, (lapTime) * 1000, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_LAP_TIME); + missionComponent->Progress(eMissionTaskType::RACING, (lapTime) * 1000, (LWOOBJID)eRacingTaskParam::LAP_TIME); if (player.lap == 3) { m_Finished++; @@ -844,7 +845,7 @@ void RacingControlComponent::Update(float deltaTime) { raceTime, raceTime * 1000); // Entire race time - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, (raceTime) * 1000, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_TOTAL_TRACK_TIME); + missionComponent->Progress(eMissionTaskType::RACING, (raceTime) * 1000, (LWOOBJID)eRacingTaskParam::TOTAL_TRACK_TIME); auto* characterComponent = playerEntity->GetComponent<CharacterComponent>(); if (characterComponent != nullptr) { diff --git a/dGame/dComponents/RebuildComponent.cpp b/dGame/dComponents/RebuildComponent.cpp index 83ae818e..bf7bd3e5 100644 --- a/dGame/dComponents/RebuildComponent.cpp +++ b/dGame/dComponents/RebuildComponent.cpp @@ -7,7 +7,7 @@ #include "dLogger.h" #include "CharacterComponent.h" #include "MissionComponent.h" -#include "MissionTaskType.h" +#include "eMissionTaskType.h" #include "dServer.h" #include "PacketUtils.h" @@ -473,12 +473,12 @@ void RebuildComponent::CompleteRebuild(Entity* user) { auto* member = EntityManager::Instance()->GetEntity(memberId); if (member) { auto* missionComponent = member->GetComponent<MissionComponent>(); - if (missionComponent) missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ACTIVITY, m_ActivityId); + if (missionComponent) missionComponent->Progress(eMissionTaskType::ACTIVITY, m_ActivityId); } } } else{ auto* missionComponent = builder->GetComponent<MissionComponent>(); - if (missionComponent) missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ACTIVITY, m_ActivityId); + if (missionComponent) missionComponent->Progress(eMissionTaskType::ACTIVITY, m_ActivityId); } LootGenerator::Instance().DropActivityLoot(builder, m_Parent, m_ActivityId, 1); } diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index a03dddbe..067446e7 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -20,6 +20,7 @@ #include "DestroyableComponent.h" #include "dMessageIdentifiers.h" #include "Loot.h" +#include "eMissionTaskType.h" ScriptedActivityComponent::ScriptedActivityComponent(Entity* parent, int activityID) : Component(parent) { m_ActivityID = activityID; @@ -552,7 +553,7 @@ void ActivityInstance::StartZone() { void ActivityInstance::RewardParticipant(Entity* participant) { auto* missionComponent = participant->GetComponent<MissionComponent>(); if (missionComponent) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ACTIVITY, m_ActivityInfo.ActivityID); + missionComponent->Progress(eMissionTaskType::ACTIVITY, m_ActivityInfo.ActivityID); } // First, get the activity data diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index a91a1e2a..16942ecc 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -31,6 +31,7 @@ #include "StartSkill.h" #include "EchoStartSkill.h" #include "EchoSyncSkill.h" +#include "eMissionTaskType.h" using namespace std; @@ -281,7 +282,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System MissionComponent* comp = entity->GetComponent<MissionComponent>(); if (comp) { - comp->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, startSkill.skillID); + comp->Progress(eMissionTaskType::USE_SKILL, startSkill.skillID); } CDSkillBehaviorTable* skillTable = CDClientManager::Instance()->GetTable<CDSkillBehaviorTable>("SkillBehavior"); diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 9aafd0fc..58d72d3c 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -31,7 +31,9 @@ #include "LeaderboardManager.h" #include "AMFFormat.h" #include "Loot.h" -#include "RacingTaskParam.h" +#include "eRacingTaskParam.h" +#include "eMissionTaskType.h" +#include "eMissionState.h" #include <sstream> #include <future> @@ -3264,7 +3266,7 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* // Check if the player has restricted trade access auto* character = entity->GetCharacter(); - if (character->HasPermission(PermissionMap::RestrictedTradeAccess)) { + if (character->HasPermission(ePermissionMap::RestrictedTradeAccess)) { // Send a message to the player ChatPackets::SendSystemMessage( sysAddr, @@ -3284,7 +3286,7 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* if (invitee != nullptr && invitee->IsPlayer()) { character = invitee->GetCharacter(); - if (character->HasPermission(PermissionMap::RestrictedTradeAccess)) { + if (character->HasPermission(ePermissionMap::RestrictedTradeAccess)) { // Send a message to the player ChatPackets::SendSystemMessage( sysAddr, @@ -4707,25 +4709,10 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti LOT tokenId = -1; - if (missionComponent->GetMissionState(545) == MissionState::MISSION_STATE_COMPLETE) // "Join Assembly!" - { - tokenId = 8318; // "Assembly Token" - } - - if (missionComponent->GetMissionState(556) == MissionState::MISSION_STATE_COMPLETE) // "Join Venture League!" - { - tokenId = 8321; // "Venture League Token" - } - - if (missionComponent->GetMissionState(567) == MissionState::MISSION_STATE_COMPLETE) // "Join The Sentinels!" - { - tokenId = 8319; // "Sentinels Token" - } - - if (missionComponent->GetMissionState(578) == MissionState::MISSION_STATE_COMPLETE) // "Join Paradox!" - { - tokenId = 8320; // "Paradox Token" - } + 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; @@ -5031,8 +5018,8 @@ void GameMessages::HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, if (missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MISSION_INTERACTION, interactedObject->GetLOT(), interactedObject->GetObjectID()); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_NON_MISSION_INTERACTION, interactedObject->GetLOT(), interactedObject->GetObjectID()); + missionComponent->Progress(eMissionTaskType::TALK_TO_NPC, interactedObject->GetLOT(), interactedObject->GetObjectID()); + missionComponent->Progress(eMissionTaskType::INTERACT, interactedObject->GetLOT(), interactedObject->GetObjectID()); } void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) { @@ -5059,7 +5046,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) if (targetEntity != nullptr) { targetEntity->OnEmoteReceived(emoteID, entity); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_EMOTE, emoteID, targetID); + missionComponent->Progress(eMissionTaskType::EMOTE, emoteID, targetID); } } else { Game::logger->LogDebug("GameMessages", "Target ID is empty, using backup"); @@ -5071,7 +5058,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) if (Vector3::DistanceSquared(scripted->GetPosition(), referencePoint) > 5.0f * 5.0f) continue; scripted->OnEmoteReceived(emoteID, entity); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_EMOTE, emoteID, scripted->GetObjectID()); + missionComponent->Progress(eMissionTaskType::EMOTE, emoteID, scripted->GetObjectID()); } } @@ -5163,7 +5150,7 @@ void GameMessages::HandleRespondToMission(RakNet::BitStream* inStream, Entity* e void GameMessages::HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* entity) { bool bIsComplete{}; - MissionState iMissionState{}; + eMissionState iMissionState{}; int missionID{}; LWOOBJID responder{}; Entity* player = nullptr; @@ -5185,9 +5172,9 @@ void GameMessages::HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* en return; } - if (iMissionState == MissionState::MISSION_STATE_AVAILABLE || iMissionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) { + if (iMissionState == eMissionState::AVAILABLE || iMissionState == eMissionState::COMPLETE_AVAILABLE) { missionComponent->AcceptMission(missionID); - } else if (iMissionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || iMissionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + } else if (iMissionState == eMissionState::READY_TO_COMPLETE || iMissionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { missionComponent->CompleteMission(missionID); } } @@ -5219,7 +5206,7 @@ void GameMessages::HandleHasBeenCollected(RakNet::BitStream* inStream, Entity* e MissionComponent* missionComponent = static_cast<MissionComponent*>(player->GetComponent(COMPONENT_TYPE_MISSION)); if (missionComponent) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT, entity->GetLOT(), entity->GetObjectID()); + missionComponent->Progress(eMissionTaskType::COLLECTION, entity->GetLOT(), entity->GetObjectID()); } } @@ -5438,7 +5425,7 @@ void GameMessages::HandleRemoveItemFromInventory(RakNet::BitStream* inStream, En auto* missionComponent = entity->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, item->GetLot(), LWOOBJID_EMPTY, "", -iStackCount); + missionComponent->Progress(eMissionTaskType::GATHER, item->GetLot(), LWOOBJID_EMPTY, "", -iStackCount); } } } @@ -5593,8 +5580,8 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* if (entity->GetLOT() != 9980 || Game::server->GetZoneID() != 1200) { if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, entity->GetLOT(), entity->GetObjectID()); - if (count >= 7 && everyPieceSwapped) missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, LWOOBJID_EMPTY, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_MODULAR_BUILDING); + missionComponent->Progress(eMissionTaskType::SCRIPT, entity->GetLOT(), entity->GetObjectID()); + if (count >= 7 && everyPieceSwapped) missionComponent->Progress(eMissionTaskType::RACING, LWOOBJID_EMPTY, (LWOOBJID)eRacingTaskParam::MODULAR_BUILDING); } } } @@ -5826,7 +5813,7 @@ void GameMessages::HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* auto* missions = static_cast<MissionComponent*>(entity->GetComponent(COMPONENT_TYPE_MISSION)); if (missions != nullptr) { - missions->Progress(MissionTaskType::MISSION_TASK_TYPE_FOOD, itemLot); + missions->Progress(eMissionTaskType::USE_ITEM, itemLot); } } diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index 990b08f3..69a643ae 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -231,41 +231,42 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) { const auto itemType = static_cast<eItemType>(itemComponent.itemType); switch (itemType) { - case eItemType::ITEM_TYPE_BRICK: + case eItemType::BRICK: return BRICKS; - case eItemType::ITEM_TYPE_BEHAVIOR: + case eItemType::BEHAVIOR: return BEHAVIORS; - case eItemType::ITEM_TYPE_PROPERTY: + case eItemType::PROPERTY: return PROPERTY_DEEDS; - case eItemType::ITEM_TYPE_MODEL: - case eItemType::ITEM_TYPE_VEHICLE: - case eItemType::ITEM_TYPE_LOOT_MODEL: - case eItemType::ITEM_TYPE_MOUNT: + case eItemType::MODEL: + case eItemType::VEHICLE: + case eItemType::LOOT_MODEL: + case eItemType::LUP_MODEL: + case eItemType::MOUNT: return MODELS; - case eItemType::ITEM_TYPE_HAT: - case eItemType::ITEM_TYPE_HAIR: - case eItemType::ITEM_TYPE_NECK: - case eItemType::ITEM_TYPE_LEFT_HAND: - case eItemType::ITEM_TYPE_RIGHT_HAND: - case eItemType::ITEM_TYPE_LEGS: - case eItemType::ITEM_TYPE_LEFT_TRINKET: - case eItemType::ITEM_TYPE_RIGHT_TRINKET: - case eItemType::ITEM_TYPE_COLLECTIBLE: - case eItemType::ITEM_TYPE_CONSUMABLE: - case eItemType::ITEM_TYPE_CHEST: - case eItemType::ITEM_TYPE_EGG: - case eItemType::ITEM_TYPE_PET_FOOD: - case eItemType::ITEM_TYPE_PET_INVENTORY_ITEM: - case eItemType::ITEM_TYPE_PACKAGE: - case eItemType::ITEM_TYPE_CURRENCY: + case eItemType::HAT: + case eItemType::HAIR: + case eItemType::NECK: + case eItemType::LEFT_HAND: + case eItemType::RIGHT_HAND: + case eItemType::LEGS: + case eItemType::LEFT_TRINKET: + case eItemType::RIGHT_TRINKET: + case eItemType::COLLECTIBLE: + case eItemType::CONSUMABLE: + case eItemType::CHEST: + case eItemType::EGG: + case eItemType::PET_FOOD: + case eItemType::PET_INVENTORY_ITEM: + case eItemType::PACKAGE: + return ITEMS; - case eItemType::ITEM_TYPE_QUEST_OBJECT: - case eItemType::ITEM_TYPE_UNKNOWN: + case eItemType::QUEST_OBJECT: + case eItemType::UNKNOWN: default: return QUEST; } diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index d6721bdd..2a054ae8 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -76,7 +76,7 @@ Item::Item( const auto type = static_cast<eItemType>(info->itemType); - if (type == eItemType::ITEM_TYPE_MOUNT) { + if (type == eItemType::MOUNT) { id = GeneralUtils::SetBit(id, OBJECT_BIT_CLIENT); } @@ -283,10 +283,10 @@ void Item::UseNonEquip(Item* item) { } const auto type = static_cast<eItemType>(info->itemType); - if (type == eItemType::ITEM_TYPE_MOUNT) { + if (type == eItemType::MOUNT) { playerInventoryComponent->HandlePossession(this); // TODO Check if mounts are allowed to be spawned - } else if (type == eItemType::ITEM_TYPE_PET_INVENTORY_ITEM && subKey != LWOOBJID_EMPTY) { + } else if (type == eItemType::PET_INVENTORY_ITEM && subKey != LWOOBJID_EMPTY) { const auto& databasePet = playerInventoryComponent->GetDatabasePet(subKey); if (databasePet.lot != LOT_NULL) { playerInventoryComponent->SpawnPet(this); diff --git a/dGame/dInventory/ItemSet.cpp b/dGame/dInventory/ItemSet.cpp index 1c67f6d6..e246f9f7 100644 --- a/dGame/dInventory/ItemSet.cpp +++ b/dGame/dInventory/ItemSet.cpp @@ -6,6 +6,7 @@ #include "CDClientDatabase.h" #include "Game.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" #include <algorithm> ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) { @@ -130,7 +131,7 @@ void ItemSet::OnEquip(const LOT lot) { const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SKILL, skill); + missionComponent->Progress(eMissionTaskType::USE_SKILL, skill); skillComponent->HandleUnmanaged(behaviorId, m_InventoryComponent->GetParent()->GetObjectID()); } diff --git a/dGame/dInventory/ItemSetPassiveAbility.cpp b/dGame/dInventory/ItemSetPassiveAbility.cpp index 83db4405..bf7c19cb 100644 --- a/dGame/dInventory/ItemSetPassiveAbility.cpp +++ b/dGame/dInventory/ItemSetPassiveAbility.cpp @@ -3,7 +3,7 @@ #include "DestroyableComponent.h" #include "SkillComponent.h" #include "ItemSet.h" -#include "ItemSetPassiveAbilityID.h" +#include "eItemSetPassiveAbilityID.h" ItemSetPassiveAbility::ItemSetPassiveAbility(PassiveAbilityTrigger trigger, Entity* parent, ItemSet* itemSet) { m_Trigger = trigger; @@ -46,31 +46,31 @@ void ItemSetPassiveAbility::Activate(Entity* target) { EntityManager::Instance()->SerializeEntity(m_Parent); - const auto id = static_cast<ItemSetPassiveAbilityID>(m_ItemSet->GetID()); + const auto id = static_cast<eItemSetPassiveAbilityID>(m_ItemSet->GetID()); const auto parentID = m_Parent->GetObjectID(); const auto equippedCount = m_ItemSet->GetEquippedCount(); switch (id) { // Assembly - case ItemSetPassiveAbilityID::InventorRank1: - case ItemSetPassiveAbilityID::SummonerRank1: - case ItemSetPassiveAbilityID::EngineerRank1: { + case eItemSetPassiveAbilityID::InventorRank1: + case eItemSetPassiveAbilityID::SummonerRank1: + case eItemSetPassiveAbilityID::EngineerRank1: { if (equippedCount < 4) return; m_Cooldown = 11.0f; skillComponent->CalculateBehavior(394, 4401, parentID); break; } - case ItemSetPassiveAbilityID::InventorRank2: - case ItemSetPassiveAbilityID::SummonerRank2: - case ItemSetPassiveAbilityID::EngineerRank2: { + case eItemSetPassiveAbilityID::InventorRank2: + case eItemSetPassiveAbilityID::SummonerRank2: + case eItemSetPassiveAbilityID::EngineerRank2: { if (equippedCount < 4) return; m_Cooldown = 11.0f; skillComponent->CalculateBehavior(581, 9433, parentID); break; } - case ItemSetPassiveAbilityID::InventorRank3: - case ItemSetPassiveAbilityID::SummonerRank3: - case ItemSetPassiveAbilityID::EngineerRank3: { + case eItemSetPassiveAbilityID::InventorRank3: + case eItemSetPassiveAbilityID::SummonerRank3: + case eItemSetPassiveAbilityID::EngineerRank3: { if (equippedCount < 4) return; m_Cooldown = 11.0f; skillComponent->CalculateBehavior(582, 9435, parentID); @@ -78,57 +78,57 @@ void ItemSetPassiveAbility::Activate(Entity* target) { } // Sentinel - case ItemSetPassiveAbilityID::KnightRank1: { + case eItemSetPassiveAbilityID::KnightRank1: { if (equippedCount < 4) return; m_Cooldown = 11.0f; skillComponent->CalculateBehavior(559, 8884, parentID); break; } - case ItemSetPassiveAbilityID::KnightRank2: { + case eItemSetPassiveAbilityID::KnightRank2: { if (equippedCount < 4) return; m_Cooldown = 11.0f; skillComponent->CalculateBehavior(560, 8885, parentID); break; } - case ItemSetPassiveAbilityID::KnightRank3: { + case eItemSetPassiveAbilityID::KnightRank3: { if (equippedCount < 4) return; m_Cooldown = 11.0f; skillComponent->CalculateBehavior(561, 8890, parentID); break; } - case ItemSetPassiveAbilityID::SpaceRangerRank1: { + case eItemSetPassiveAbilityID::SpaceRangerRank1: { if (equippedCount < 4) return; m_Cooldown = 11.0f; skillComponent->CalculateBehavior(1101, 24612, parentID); break; } - case ItemSetPassiveAbilityID::SpaceRangerRank2: { + case eItemSetPassiveAbilityID::SpaceRangerRank2: { if (equippedCount < 4) return; m_Cooldown = 11.0f; skillComponent->CalculateBehavior(1102, 24617, parentID); break; } - case ItemSetPassiveAbilityID::SpaceRangerRank3: { + case eItemSetPassiveAbilityID::SpaceRangerRank3: { if (equippedCount < 4) return; m_Cooldown = 11.0f; skillComponent->CalculateBehavior(1103, 24622, parentID); break; } - case ItemSetPassiveAbilityID::SamuraiRank1: { + case eItemSetPassiveAbilityID::SamuraiRank1: { if (equippedCount < 4) return; m_Cooldown = 11.0f; skillComponent->CalculateBehavior(562, 8899, parentID); break; } - case ItemSetPassiveAbilityID::SamuraiRank2: { + case eItemSetPassiveAbilityID::SamuraiRank2: { if (equippedCount < 4) return; m_Cooldown = 11.0f; skillComponent->CalculateBehavior(563, 8904, parentID); break; } - case ItemSetPassiveAbilityID::SamuraiRank3: { + case eItemSetPassiveAbilityID::SamuraiRank3: { if (equippedCount < 4) return; m_Cooldown = 11.0f; skillComponent->CalculateBehavior(564, 8909, parentID); @@ -143,47 +143,47 @@ void ItemSetPassiveAbility::Activate(Entity* target) { std::vector<ItemSetPassiveAbility> ItemSetPassiveAbility::FindAbilities(uint32_t itemSetID, Entity* parent, ItemSet* itemSet) { std::vector<ItemSetPassiveAbility> abilities; - switch (static_cast<ItemSetPassiveAbilityID>(itemSetID)) { + switch (static_cast<eItemSetPassiveAbilityID>(itemSetID)) { // Assembly - case ItemSetPassiveAbilityID::SummonerRank1: - case ItemSetPassiveAbilityID::SummonerRank2: - case ItemSetPassiveAbilityID::SummonerRank3: - case ItemSetPassiveAbilityID::InventorRank1: - case ItemSetPassiveAbilityID::InventorRank2: - case ItemSetPassiveAbilityID::InventorRank3: - case ItemSetPassiveAbilityID::EngineerRank1: - case ItemSetPassiveAbilityID::EngineerRank2: - case ItemSetPassiveAbilityID::EngineerRank3: { + case eItemSetPassiveAbilityID::SummonerRank1: + case eItemSetPassiveAbilityID::SummonerRank2: + case eItemSetPassiveAbilityID::SummonerRank3: + case eItemSetPassiveAbilityID::InventorRank1: + case eItemSetPassiveAbilityID::InventorRank2: + case eItemSetPassiveAbilityID::InventorRank3: + case eItemSetPassiveAbilityID::EngineerRank1: + case eItemSetPassiveAbilityID::EngineerRank2: + case eItemSetPassiveAbilityID::EngineerRank3: { abilities.emplace_back(PassiveAbilityTrigger::AssemblyImagination, parent, itemSet); break; } // Sentinel - case ItemSetPassiveAbilityID::KnightRank1: - case ItemSetPassiveAbilityID::KnightRank2: - case ItemSetPassiveAbilityID::KnightRank3: - case ItemSetPassiveAbilityID::SpaceRangerRank1: - case ItemSetPassiveAbilityID::SpaceRangerRank2: - case ItemSetPassiveAbilityID::SpaceRangerRank3: - case ItemSetPassiveAbilityID::SamuraiRank1: - case ItemSetPassiveAbilityID::SamuraiRank2: - case ItemSetPassiveAbilityID::SamuraiRank3: { + case eItemSetPassiveAbilityID::KnightRank1: + case eItemSetPassiveAbilityID::KnightRank2: + case eItemSetPassiveAbilityID::KnightRank3: + case eItemSetPassiveAbilityID::SpaceRangerRank1: + case eItemSetPassiveAbilityID::SpaceRangerRank2: + case eItemSetPassiveAbilityID::SpaceRangerRank3: + case eItemSetPassiveAbilityID::SamuraiRank1: + case eItemSetPassiveAbilityID::SamuraiRank2: + case eItemSetPassiveAbilityID::SamuraiRank3: { abilities.emplace_back(PassiveAbilityTrigger::SentinelArmor, parent, itemSet); abilities.emplace_back(PassiveAbilityTrigger::EnemySmashed, parent, itemSet); break; } // Paradox - case ItemSetPassiveAbilityID::BatLord: - case ItemSetPassiveAbilityID::SpaceMarauderRank1: - case ItemSetPassiveAbilityID::SpaceMarauderRank2: - case ItemSetPassiveAbilityID::SpaceMarauderRank3: - case ItemSetPassiveAbilityID::SorcererRank1: - case ItemSetPassiveAbilityID::SorcererRank2: - case ItemSetPassiveAbilityID::SorcererRank3: - case ItemSetPassiveAbilityID::ShinobiRank1: - case ItemSetPassiveAbilityID::ShinobiRank2: - case ItemSetPassiveAbilityID::ShinobiRank3: { + case eItemSetPassiveAbilityID::BatLord: + case eItemSetPassiveAbilityID::SpaceMarauderRank1: + case eItemSetPassiveAbilityID::SpaceMarauderRank2: + case eItemSetPassiveAbilityID::SpaceMarauderRank3: + case eItemSetPassiveAbilityID::SorcererRank1: + case eItemSetPassiveAbilityID::SorcererRank2: + case eItemSetPassiveAbilityID::SorcererRank3: + case eItemSetPassiveAbilityID::ShinobiRank1: + case eItemSetPassiveAbilityID::ShinobiRank2: + case eItemSetPassiveAbilityID::ShinobiRank3: { abilities.emplace_back(PassiveAbilityTrigger::EnemySmashed, parent, itemSet); break; @@ -205,110 +205,110 @@ void ItemSetPassiveAbility::OnEnemySmshed(Entity* target) { EntityManager::Instance()->SerializeEntity(m_Parent); - const auto id = static_cast<ItemSetPassiveAbilityID>(m_ItemSet->GetID()); + const auto id = static_cast<eItemSetPassiveAbilityID>(m_ItemSet->GetID()); const auto parentID = m_Parent->GetObjectID(); const auto equippedCount = m_ItemSet->GetEquippedCount(); switch (id) { // Bat Lord - case ItemSetPassiveAbilityID::BatLord: { + case eItemSetPassiveAbilityID::BatLord: { if (equippedCount < 5) return; destroyableComponent->Heal(3); break; } // Sentinel - case ItemSetPassiveAbilityID::KnightRank1: { + case eItemSetPassiveAbilityID::KnightRank1: { if (equippedCount < 5) return; destroyableComponent->Repair(1); break; } - case ItemSetPassiveAbilityID::KnightRank2: { + case eItemSetPassiveAbilityID::KnightRank2: { if (equippedCount < 5) return; destroyableComponent->Repair(1); break; } - case ItemSetPassiveAbilityID::KnightRank3: { + case eItemSetPassiveAbilityID::KnightRank3: { if (equippedCount < 5) return; destroyableComponent->Repair(1); break; } - case ItemSetPassiveAbilityID::SpaceRangerRank1: { + case eItemSetPassiveAbilityID::SpaceRangerRank1: { if (equippedCount < 5) return; destroyableComponent->Repair(1); break; } - case ItemSetPassiveAbilityID::SpaceRangerRank2: { + case eItemSetPassiveAbilityID::SpaceRangerRank2: { if (equippedCount < 5) return; destroyableComponent->Repair(1); break; } - case ItemSetPassiveAbilityID::SpaceRangerRank3: { + case eItemSetPassiveAbilityID::SpaceRangerRank3: { if (equippedCount < 5) return; destroyableComponent->Repair(1); break; } - case ItemSetPassiveAbilityID::SamuraiRank1: { + case eItemSetPassiveAbilityID::SamuraiRank1: { if (equippedCount < 5) return; destroyableComponent->Repair(1); break; } - case ItemSetPassiveAbilityID::SamuraiRank2: { + case eItemSetPassiveAbilityID::SamuraiRank2: { if (equippedCount < 5) return; destroyableComponent->Repair(1); break; } - case ItemSetPassiveAbilityID::SamuraiRank3: { + case eItemSetPassiveAbilityID::SamuraiRank3: { if (equippedCount < 5) return; destroyableComponent->Repair(1); break; } // Paradox - case ItemSetPassiveAbilityID::SpaceMarauderRank1: { + case eItemSetPassiveAbilityID::SpaceMarauderRank1: { if (equippedCount < 4) return; destroyableComponent->Imagine(1); break; } - case ItemSetPassiveAbilityID::SpaceMarauderRank2: { + case eItemSetPassiveAbilityID::SpaceMarauderRank2: { if (equippedCount < 4) return; destroyableComponent->Imagine(2); break; } - case ItemSetPassiveAbilityID::SpaceMarauderRank3: { + case eItemSetPassiveAbilityID::SpaceMarauderRank3: { if (equippedCount < 4) return; destroyableComponent->Imagine(3); break; } - case ItemSetPassiveAbilityID::ShinobiRank1: { + case eItemSetPassiveAbilityID::ShinobiRank1: { if (equippedCount < 4) return; destroyableComponent->Imagine(1); break; } - case ItemSetPassiveAbilityID::ShinobiRank2: { + case eItemSetPassiveAbilityID::ShinobiRank2: { if (equippedCount < 4) return; destroyableComponent->Imagine(2); break; } - case ItemSetPassiveAbilityID::ShinobiRank3: { - if (equippedCount < 4 || !target) return; - skillComponent->CalculateBehavior(695, 11399, target->GetObjectID()); + case eItemSetPassiveAbilityID::ShinobiRank3: { + if (equippedCount < 4) return; + destroyableComponent->Imagine(3); break; } - case ItemSetPassiveAbilityID::SorcererRank1: { + case eItemSetPassiveAbilityID::SorcererRank1: { if (equippedCount < 4) return; destroyableComponent->Imagine(1); break; } - case ItemSetPassiveAbilityID::SorcererRank2: { + case eItemSetPassiveAbilityID::SorcererRank2: { if (equippedCount < 4) return; destroyableComponent->Imagine(2); break; } - case ItemSetPassiveAbilityID::SorcererRank3: { + case eItemSetPassiveAbilityID::SorcererRank3: { if (equippedCount < 4) return; destroyableComponent->Imagine(3); break; diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index df1b16d7..0e1acdac 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -12,7 +12,7 @@ #include "GameMessages.h" #include "Mail.h" #include "MissionComponent.h" -#include "RacingTaskParam.h" +#include "eRacingTaskParam.h" #include "dLogger.h" #include "dServer.h" #include "dZoneManager.h" @@ -20,6 +20,10 @@ #include "User.h" #include "Database.h" #include "WorldConfig.h" +#include "eMissionState.h" +#include "eMissionTaskType.h" +#include "eMissionLockState.h" + Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { m_MissionComponent = missionComponent; @@ -32,7 +36,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { m_Reward = 0; - m_State = MissionState::MISSION_STATE_UNKNOWN; + m_State = eMissionState::UNKNOWN; auto* missionsTable = CDClientManager::Instance()->GetTable<CDMissionsTable>("Missions"); @@ -60,7 +64,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { void Mission::LoadFromXml(tinyxml2::XMLElement* element) { // Start custom XML if (element->Attribute("state") != nullptr) { - m_State = static_cast<MissionState>(std::stoul(element->Attribute("state"))); + m_State = static_cast<eMissionState>(std::stoul(element->Attribute("state"))); } // End custom XML @@ -85,8 +89,8 @@ void Mission::LoadFromXml(tinyxml2::XMLElement* element) { const auto type = m_Tasks[index]->GetType(); - if (type == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT || - type == MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY) { + if (type == eMissionTaskType::COLLECTION || + type == eMissionTaskType::VISIT_PROPERTY) { std::vector<uint32_t> uniques; const auto value = std::stoul(task->Attribute("v")); @@ -100,7 +104,7 @@ void Mission::LoadFromXml(tinyxml2::XMLElement* element) { uniques.push_back(unique); - if (m_MissionComponent != nullptr && type == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT) { + if (m_MissionComponent != nullptr && type == eMissionTaskType::COLLECTION) { m_MissionComponent->AddCollectible(unique); } @@ -144,8 +148,8 @@ void Mission::UpdateXml(tinyxml2::XMLElement* element) { } for (auto* task : m_Tasks) { - if (task->GetType() == MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT || - task->GetType() == MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY) { + if (task->GetType() == eMissionTaskType::COLLECTION || + task->GetType() == eMissionTaskType::VISIT_PROPERTY) { auto* child = element->GetDocument()->NewElement("sv"); @@ -229,7 +233,7 @@ std::vector<MissionTask*> Mission::GetTasks() const { return m_Tasks; } -MissionState Mission::GetMissionState() const { +eMissionState Mission::GetMissionState() const { return m_State; } @@ -246,47 +250,47 @@ bool Mission::IsRepeatable() const { } bool Mission::IsComplete() const { - return m_State == MissionState::MISSION_STATE_COMPLETE; + return m_State == eMissionState::COMPLETE; } bool Mission::IsActive() const { - return m_State == MissionState::MISSION_STATE_ACTIVE || m_State == MissionState::MISSION_STATE_COMPLETE_AVAILABLE; + return m_State == eMissionState::ACTIVE || m_State == eMissionState::COMPLETE_AVAILABLE; } void Mission::MakeActive() { - SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_ACTIVE : MissionState::MISSION_STATE_COMPLETE_ACTIVE); + SetMissionState(m_Completions == 0 ? eMissionState::ACTIVE : eMissionState::COMPLETE_ACTIVE); } bool Mission::IsReadyToComplete() const { - return m_State == MissionState::MISSION_STATE_READY_TO_COMPLETE || m_State == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE; + return m_State == eMissionState::READY_TO_COMPLETE || m_State == eMissionState::COMPLETE_READY_TO_COMPLETE; } void Mission::MakeReadyToComplete() { - SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_READY_TO_COMPLETE : MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE); + SetMissionState(m_Completions == 0 ? eMissionState::READY_TO_COMPLETE : eMissionState::COMPLETE_READY_TO_COMPLETE); } bool Mission::IsAvalible() const { - return m_State == MissionState::MISSION_STATE_AVAILABLE || m_State == MissionState::MISSION_STATE_COMPLETE_AVAILABLE; + return m_State == eMissionState::AVAILABLE || m_State == eMissionState::COMPLETE_AVAILABLE; } bool Mission::IsFetchMission() const { - return m_Tasks.size() == 1 && m_Tasks[0]->GetType() == MissionTaskType::MISSION_TASK_TYPE_MISSION_INTERACTION; + return m_Tasks.size() == 1 && m_Tasks[0]->GetType() == eMissionTaskType::TALK_TO_NPC; } void Mission::MakeAvalible() { - SetMissionState(m_Completions == 0 ? MissionState::MISSION_STATE_AVAILABLE : MissionState::MISSION_STATE_COMPLETE_AVAILABLE); + SetMissionState(m_Completions == 0 ? eMissionState::AVAILABLE : eMissionState::COMPLETE_AVAILABLE); } void Mission::Accept() { - SetMissionTypeState(MissionLockState::MISSION_LOCK_NEW, info->defined_type, info->defined_subtype); + SetMissionTypeState(eMissionLockState::NEW, info->defined_type, info->defined_subtype); - SetMissionState(m_Completions > 0 ? MissionState::MISSION_STATE_COMPLETE_ACTIVE : MissionState::MISSION_STATE_ACTIVE); + SetMissionState(m_Completions > 0 ? eMissionState::COMPLETE_ACTIVE : eMissionState::ACTIVE); Catchup(); } void Mission::Complete(const bool yieldRewards) { - if (m_State != MissionState::MISSION_STATE_ACTIVE && m_State != MissionState::MISSION_STATE_COMPLETE_ACTIVE) { + if (m_State != eMissionState::ACTIVE && m_State != eMissionState::COMPLETE_ACTIVE) { // If we are accepting a mission here there is no point to giving it a unique ID since we just complete it immediately. Accept(); } @@ -295,13 +299,13 @@ void Mission::Complete(const bool yieldRewards) { task->Complete(); } - SetMissionState(MissionState::MISSION_STATE_REWARDING, true); + SetMissionState(eMissionState::REWARDING, true); if (yieldRewards) { YieldRewards(); } - SetMissionState(MissionState::MISSION_STATE_COMPLETE); + SetMissionState(eMissionState::COMPLETE); m_Completions++; @@ -320,11 +324,11 @@ void Mission::Complete(const bool yieldRewards) { auto* missionComponent = entity->GetComponent<MissionComponent>(); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MISSION_COMPLETE, info->id); + missionComponent->Progress(eMissionTaskType::META, info->id); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, info->id, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPLETE_ANY_RACING_TASK); + missionComponent->Progress(eMissionTaskType::RACING, info->id, (LWOOBJID)eRacingTaskParam::COMPLETE_ANY_RACING_TASK); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, info->id, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COMPLETE_TRACK_TASKS); + missionComponent->Progress(eMissionTaskType::RACING, info->id, (LWOOBJID)eRacingTaskParam::COMPLETE_TRACK_TASKS); auto* missionEmailTable = CDClientManager::Instance()->GetTable<CDMissionEmailTable>("MissionEmail"); @@ -371,7 +375,7 @@ void Mission::Catchup() { for (auto* task : m_Tasks) { const auto type = task->GetType(); - if (type == MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { + if (type == eMissionTaskType::GATHER) { for (auto target : task->GetAllTargets()) { const auto count = inventory->GetLotCountNonTransfer(target); @@ -381,7 +385,7 @@ void Mission::Catchup() { } } - if (type == MissionTaskType::MISSION_TASK_TYPE_PLAYER_FLAG) { + if (type == eMissionTaskType::PLAYER_FLAG) { for (auto target : task->GetAllTargets()) { const auto flag = GetUser()->GetLastUsedChar()->GetPlayerFlag(target); @@ -416,7 +420,7 @@ void Mission::YieldRewards() { // Remove mission items for (auto* task : m_Tasks) { - if (task->GetType() != MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION) { + if (task->GetType() != eMissionTaskType::GATHER) { continue; } @@ -429,7 +433,7 @@ void Mission::YieldRewards() { inventoryComponent->RemoveItem(target, task->GetClientInfo().targetValue, eInventoryType::ITEMS); inventoryComponent->RemoveItem(target, task->GetClientInfo().targetValue, eInventoryType::QUEST); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, target, LWOOBJID_EMPTY, "", -task->GetClientInfo().targetValue); + missionComponent->Progress(eMissionTaskType::GATHER, target, LWOOBJID_EMPTY, "", -task->GetClientInfo().targetValue); } } } @@ -525,7 +529,7 @@ void Mission::YieldRewards() { } if (info->reward_reputation > 0) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_EARN_REPUTATION, 0, 0L, "", info->reward_reputation); + missionComponent->Progress(eMissionTaskType::EARN_REPUTATION, 0, 0L, "", info->reward_reputation); auto character = entity->GetComponent<CharacterComponent>(); if (character) { character->SetReputation(character->GetReputation() + info->reward_reputation); @@ -560,7 +564,7 @@ void Mission::YieldRewards() { } } -void Mission::Progress(MissionTaskType type, int32_t value, LWOOBJID associate, const std::string& targets, int32_t count) { +void Mission::Progress(eMissionTaskType type, int32_t value, LWOOBJID associate, const std::string& targets, int32_t count) { const auto isRemoval = count < 0; if (isRemoval && (IsComplete() || IsAchievement())) { @@ -584,7 +588,7 @@ void Mission::Progress(MissionTaskType type, int32_t value, LWOOBJID associate, } } -void Mission::SetMissionState(const MissionState state, const bool sendingRewards) { +void Mission::SetMissionState(const eMissionState state, const bool sendingRewards) { this->m_State = state; auto* entity = GetAssociate(); @@ -596,7 +600,7 @@ void Mission::SetMissionState(const MissionState state, const bool sendingReward GameMessages::SendNotifyMission(entity, entity->GetParentUser()->GetSystemAddress(), info->id, static_cast<int>(state), sendingRewards); } -void Mission::SetMissionTypeState(MissionLockState state, const std::string& type, const std::string& subType) { +void Mission::SetMissionTypeState(eMissionLockState state, const std::string& type, const std::string& subType) { // TODO } diff --git a/dGame/dMission/Mission.h b/dGame/dMission/Mission.h index f9902a06..b04c3548 100644 --- a/dGame/dMission/Mission.h +++ b/dGame/dMission/Mission.h @@ -10,13 +10,12 @@ #include "MissionTask.h" #include "dCommonVars.h" #include "Entity.h" -#include "MissionState.h" -#include "MissionLockState.h" namespace tinyxml2 { class XMLElement; }; - +enum class eMissionState : int; +enum class eMissionLockState : int; class MissionComponent; /** @@ -53,7 +52,7 @@ public: * Returns the current state of this mission * @return the current state of this mission */ - MissionState GetMissionState() const; + eMissionState GetMissionState() const; /** * Returns the database information that represents to this mission. @@ -102,12 +101,12 @@ public: * @param state the mission state to set * @param sendingRewards a flag indicating to the client that rewards wil lfollow */ - void SetMissionState(MissionState state, bool sendingRewards = false); + void SetMissionState(eMissionState state, bool sendingRewards = false); /** * Currently unimplemented */ - void SetMissionTypeState(MissionLockState state, const std::string& type, const std::string& subType); + void SetMissionTypeState(eMissionLockState state, const std::string& type, const std::string& subType); /** * Returns whether this mission is an achievement @@ -208,7 +207,7 @@ public: * @param targets optional multiple targets that need to be met for progression * @param count optional count to progress with */ - void Progress(MissionTaskType type, int32_t value, LWOOBJID associate = 0, const std::string& targets = "", int32_t count = 1); + void Progress(eMissionTaskType type, int32_t value, LWOOBJID associate = 0, const std::string& targets = "", int32_t count = 1); /** * Returns if the mission ID that's given belongs to an existing mission @@ -251,7 +250,7 @@ private: /** * The current state this mission is in */ - MissionState m_State; + eMissionState m_State; /** * The number of times the entity has completed this mission diff --git a/dGame/dMission/MissionPrerequisites.cpp b/dGame/dMission/MissionPrerequisites.cpp index 46fa73a6..6b55151c 100644 --- a/dGame/dMission/MissionPrerequisites.cpp +++ b/dGame/dMission/MissionPrerequisites.cpp @@ -106,8 +106,8 @@ bool PrerequisiteExpression::Execute(const std::unordered_map<uint32_t, Mission* if (this->sub != 0) { // Special case for one Wisp Lee repeatable mission. a = mission->GetClientInfo().id == 1883 ? - mission->GetMissionState() == static_cast<MissionState>(this->sub) : - mission->GetMissionState() >= static_cast<MissionState>(this->sub); + mission->GetMissionState() == static_cast<eMissionState>(this->sub) : + mission->GetMissionState() >= static_cast<eMissionState>(this->sub); } else if (mission->IsComplete()) { a = true; } diff --git a/dGame/dMission/MissionTask.cpp b/dGame/dMission/MissionTask.cpp index d52e6e95..e339d232 100644 --- a/dGame/dMission/MissionTask.cpp +++ b/dGame/dMission/MissionTask.cpp @@ -13,6 +13,7 @@ #include "dZoneManager.h" #include "InventoryComponent.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) { this->info = info; @@ -42,8 +43,8 @@ MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) } -MissionTaskType MissionTask::GetType() const { - return static_cast<MissionTaskType>(info->taskType); +eMissionTaskType MissionTask::GetType() const { + return static_cast<eMissionTaskType>(info->taskType); } @@ -187,7 +188,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& const auto type = GetType(); if (count < 0) { - if (mission->IsMission() && type == MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION && InAllTargets(value)) { + if (mission->IsMission() && type == eMissionTaskType::GATHER && InAllTargets(value)) { if (parameters.size() > 0 && (parameters[0] & 1) != 0) { return; } @@ -218,10 +219,10 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& std::vector<LDFBaseData*> settings; switch (type) { - case MissionTaskType::MISSION_TASK_TYPE_UNKNOWN: + case eMissionTaskType::UNKNOWN: break; - case MissionTaskType::MISSION_TASK_TYPE_ACTIVITY: + case eMissionTaskType::ACTIVITY: { if (InAllTargets(value)) { AddProgress(count); @@ -256,8 +257,8 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } - case MissionTaskType::MISSION_TASK_TYPE_FOOD: - case MissionTaskType::MISSION_TASK_TYPE_MISSION_INTERACTION: + case eMissionTaskType::USE_ITEM: + case eMissionTaskType::TALK_TO_NPC: { if (GetTarget() != value) break; @@ -266,7 +267,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } - case MissionTaskType::MISSION_TASK_TYPE_EMOTE: + case eMissionTaskType::EMOTE: { if (!InParameters(value)) break; @@ -287,7 +288,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } - case MissionTaskType::MISSION_TASK_TYPE_SKILL: + case eMissionTaskType::USE_SKILL: { // This is a complicated check because for some missions we need to check for the associate being in the parameters instead of the value being in the parameters. if (associate == LWOOBJID_EMPTY && GetAllTargets().size() == 1 && GetAllTargets()[0] == -1) { @@ -298,7 +299,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } - case MissionTaskType::MISSION_TASK_TYPE_MINIGAME: + case eMissionTaskType::PERFORM_ACTIVITY: { auto* minigameManager = EntityManager::Instance()->GetEntity(associate); if (minigameManager == nullptr) @@ -327,7 +328,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } - case MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY: + case eMissionTaskType::VISIT_PROPERTY: { if (!InAllTargets(value)) break; @@ -340,7 +341,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } - case MissionTaskType::MISSION_TASK_TYPE_ENVIRONMENT: + case eMissionTaskType::COLLECTION: { if (!InAllTargets(value)) break; @@ -375,7 +376,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } - case MissionTaskType::MISSION_TASK_TYPE_LOCATION: + case eMissionTaskType::EXPLORE: { if (info->targetGroup != targets) break; @@ -384,9 +385,9 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } - case MissionTaskType::MISSION_TASK_TYPE_RACING: + case eMissionTaskType::RACING: { - // The meaning of associate can be found in RacingTaskParam.h + // The meaning of associate can be found in eRacingTaskParam.h if (parameters.empty()) break; if (!InAllTargets(dZoneManager::Instance()->GetZone()->GetWorldID()) && !(parameters[0] == 4 || parameters[0] == 5) && !InAllTargets(value)) break; @@ -426,15 +427,15 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } - case MissionTaskType::MISSION_TASK_TYPE_PET_TAMING: - case MissionTaskType::MISSION_TASK_TYPE_SCRIPT: - case MissionTaskType::MISSION_TASK_TYPE_NON_MISSION_INTERACTION: - case MissionTaskType::MISSION_TASK_TYPE_MISSION_COMPLETE: - case MissionTaskType::MISSION_TASK_TYPE_POWERUP: - case MissionTaskType::MISSION_TASK_TYPE_SMASH: - case MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION: - case MissionTaskType::MISSION_TASK_TYPE_PLAYER_FLAG: - case MissionTaskType::MISSION_TASK_TYPE_EARN_REPUTATION: + case eMissionTaskType::PET_TAMING: + case eMissionTaskType::SCRIPT: + case eMissionTaskType::INTERACT: + case eMissionTaskType::META: + case eMissionTaskType::POWERUP: + case eMissionTaskType::SMASH: + case eMissionTaskType::GATHER: + case eMissionTaskType::PLAYER_FLAG: + case eMissionTaskType::EARN_REPUTATION: { if (!InAllTargets(value)) break; @@ -442,7 +443,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } - case MissionTaskType::MISSION_TASK_TYPE_PLACE_MODEL: + case eMissionTaskType::PLACE_MODEL: { AddProgress(count); break; diff --git a/dGame/dMission/MissionTask.h b/dGame/dMission/MissionTask.h index ea4b8a05..f867b632 100644 --- a/dGame/dMission/MissionTask.h +++ b/dGame/dMission/MissionTask.h @@ -4,9 +4,9 @@ #define MISSIONTASK_H #include "CDMissionTasksTable.h" -#include "MissionTaskType.h" #include "dCommonVars.h" +enum class eMissionTaskType : int; class Mission; /** @@ -57,7 +57,7 @@ public: * Returns the type of this task * @return the type of this task */ - MissionTaskType GetType() const; + eMissionTaskType GetType() const; /** * Returns the value that should be progressed to, to complete the mission (the target value) diff --git a/dGame/dUtilities/Loot.cpp b/dGame/dUtilities/Loot.cpp index 784d873f..44e35a91 100644 --- a/dGame/dUtilities/Loot.cpp +++ b/dGame/dUtilities/Loot.cpp @@ -13,6 +13,8 @@ #include "GeneralUtils.h" #include "InventoryComponent.h" #include "MissionComponent.h" +#include "eMissionState.h" + LootGenerator::LootGenerator() { CDLootTableTable* lootTableTable = CDClientManager::Instance()->GetTable<CDLootTableTable>("LootTable"); @@ -186,13 +188,13 @@ std::unordered_map<LOT, int32_t> LootGenerator::RollLootMatrix(Entity* player, u // convert faction token proxy if (drop.itemID == 13763) { - if (missionComponent->GetMissionState(545) == MissionState::MISSION_STATE_COMPLETE) + if (missionComponent->GetMissionState(545) == eMissionState::COMPLETE) drop.itemID = 8318; // "Assembly Token" - else if (missionComponent->GetMissionState(556) == MissionState::MISSION_STATE_COMPLETE) + else if (missionComponent->GetMissionState(556) == eMissionState::COMPLETE) drop.itemID = 8321; // "Venture League Token" - else if (missionComponent->GetMissionState(567) == MissionState::MISSION_STATE_COMPLETE) + else if (missionComponent->GetMissionState(567) == eMissionState::COMPLETE) drop.itemID = 8319; // "Sentinels Token" - else if (missionComponent->GetMissionState(578) == MissionState::MISSION_STATE_COMPLETE) + else if (missionComponent->GetMissionState(578) == eMissionState::COMPLETE) drop.itemID = 8320; // "Paradox Token" } diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index a4ac63e1..48f21a5d 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -24,6 +24,7 @@ #include "Character.h" #include "dZoneManager.h" #include "WorldConfig.h" +#include "eMissionTaskType.h" void Mail::SendMail(const Entity* recipient, const std::string& subject, const std::string& body, const LOT attachment, const uint16_t attachmentCount) { @@ -165,7 +166,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd if (!character) return; - if (character->HasPermission(PermissionMap::RestrictedMailAccess)) { + if (character->HasPermission(ePermissionMap::RestrictedMailAccess)) { // Send a message to the player ChatPackets::SendSystemMessage( sysAddr, @@ -268,7 +269,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd auto* missionCompoent = entity->GetComponent<MissionComponent>(); if (missionCompoent != nullptr) { - missionCompoent->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, itemLOT, LWOOBJID_EMPTY, "", -attachmentCount); + missionCompoent->Progress(eMissionTaskType::GATHER, itemLOT, LWOOBJID_EMPTY, "", -attachmentCount); } } diff --git a/dGame/dUtilities/Preconditions.cpp b/dGame/dUtilities/Preconditions.cpp index c23ac53b..8602586c 100644 --- a/dGame/dUtilities/Preconditions.cpp +++ b/dGame/dUtilities/Preconditions.cpp @@ -12,7 +12,7 @@ #include "LevelProgressionComponent.h" #include "DestroyableComponent.h" #include "GameMessages.h" - +#include "eMissionState.h" std::map<uint32_t, Precondition*> Preconditions::cache = {}; @@ -142,19 +142,19 @@ bool Precondition::CheckValue(Entity* player, const uint32_t value, bool evaluat case PreconditionType::HasAchievement: mission = missionComponent->GetMission(value); - return mission == nullptr || mission->GetMissionState() >= MissionState::MISSION_STATE_COMPLETE; + return mission == nullptr || mission->GetMissionState() >= eMissionState::COMPLETE; case PreconditionType::MissionAvailable: mission = missionComponent->GetMission(value); - return mission == nullptr || mission->GetMissionState() >= MissionState::MISSION_STATE_AVAILABLE; + return mission == nullptr || mission->GetMissionState() >= eMissionState::AVAILABLE; case PreconditionType::OnMission: mission = missionComponent->GetMission(value); - return mission == nullptr || mission->GetMissionState() >= MissionState::MISSION_STATE_ACTIVE; + return mission == nullptr || mission->GetMissionState() >= eMissionState::ACTIVE; case PreconditionType::MissionComplete: mission = missionComponent->GetMission(value); - return mission == nullptr ? false : mission->GetMissionState() >= MissionState::MISSION_STATE_COMPLETE; + return mission == nullptr ? false : mission->GetMissionState() >= eMissionState::COMPLETE; case PreconditionType::PetDeployed: return false; // TODO case PreconditionType::HasFlag: diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 70637990..1bd3f6f3 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -72,6 +72,7 @@ #include "AMFFormat.h" #include "MovingPlatformComponent.h" #include "dMessageIdentifiers.h" +#include "eMissionState.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { std::string chatCommand; @@ -685,7 +686,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - mission->SetMissionState(MissionState::MISSION_STATE_ACTIVE); + mission->SetMissionState(eMissionState::ACTIVE); return; } diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index 61267971..9e8153cc 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -268,7 +268,7 @@ void ClientPackets::HandleChatModerationRequest(const SystemAddress& sysAddr, Pa // Check if the player has restricted chat access auto* character = entity->GetCharacter(); - if (character->HasPermission(PermissionMap::RestrictedChatAccess)) { + if (character->HasPermission(ePermissionMap::RestrictedChatAccess)) { // Send a message to the player ChatPackets::SendSystemMessage( sysAddr, diff --git a/dScripts/02_server/Equipment/BootyDigServer.cpp b/dScripts/02_server/Equipment/BootyDigServer.cpp index 73d96b1f..375bc4e5 100644 --- a/dScripts/02_server/Equipment/BootyDigServer.cpp +++ b/dScripts/02_server/Equipment/BootyDigServer.cpp @@ -2,7 +2,8 @@ #include "EntityManager.h" #include "RenderComponent.h" #include "MissionComponent.h" -#include "MissionTaskType.h" +#include "eMissionTaskType.h" +#include "eMissionState.h" #include "Loot.h" void BootyDigServer::OnStartup(Entity* self) { @@ -37,8 +38,8 @@ BootyDigServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string auto* missionComponent = player->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { auto* mission = missionComponent->GetMission(1881); - if (mission != nullptr && (mission->GetMissionState() == MissionState::MISSION_STATE_ACTIVE || mission->GetMissionState() == MissionState::MISSION_STATE_COMPLETE_ACTIVE)) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + if (mission != nullptr && (mission->GetMissionState() == eMissionState::ACTIVE || mission->GetMissionState() == eMissionState::COMPLETE_ACTIVE)) { + mission->Progress(eMissionTaskType::SCRIPT, self->GetLOT()); auto* renderComponent = self->GetComponent<RenderComponent>(); if (renderComponent != nullptr) diff --git a/dScripts/02_server/Equipment/MaestromExtracticatorServer.cpp b/dScripts/02_server/Equipment/MaestromExtracticatorServer.cpp index caaba28f..c01d2362 100644 --- a/dScripts/02_server/Equipment/MaestromExtracticatorServer.cpp +++ b/dScripts/02_server/Equipment/MaestromExtracticatorServer.cpp @@ -3,6 +3,7 @@ #include "GeneralUtils.h" #include "EntityManager.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" void MaestromExtracticatorServer::OnStartup(Entity* self) { //self:SetNetworkVar("current_anim", failAnim) @@ -24,7 +25,7 @@ void MaestromExtracticatorServer::OnFireEventServerSide(Entity* self, Entity* se auto missionComponent = player->GetComponent<MissionComponent>(); if (missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, 14718); + missionComponent->Progress(eMissionTaskType::SMASH, 14718); CollectSample(self, sender->GetObjectID()); sender->ScheduleKillAfterUpdate(); } diff --git a/dScripts/02_server/Map/AG/NpcAgCourseStarter.cpp b/dScripts/02_server/Map/AG/NpcAgCourseStarter.cpp index 503d966a..d2cc647e 100644 --- a/dScripts/02_server/Map/AG/NpcAgCourseStarter.cpp +++ b/dScripts/02_server/Map/AG/NpcAgCourseStarter.cpp @@ -3,6 +3,8 @@ #include "ScriptedActivityComponent.h" #include "GameMessages.h" #include "LeaderboardManager.h" +#include "eMissionTaskType.h" +#include "eMissionState.h" #include "MissionComponent.h" #include <ctime> @@ -89,7 +91,7 @@ void NpcAgCourseStarter::OnFireEventServerSide(Entity* self, Entity* sender, std auto* missionComponent = sender->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { missionComponent->ForceProgressTaskType(1884, 1, 1, false); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, -finish, self->GetObjectID(), + missionComponent->Progress(eMissionTaskType::PERFORM_ACTIVITY, -finish, self->GetObjectID(), "performact_time"); } diff --git a/dScripts/02_server/Map/AG/NpcCowboyServer.cpp b/dScripts/02_server/Map/AG/NpcCowboyServer.cpp index c4940e4d..c5a0e8f9 100644 --- a/dScripts/02_server/Map/AG/NpcCowboyServer.cpp +++ b/dScripts/02_server/Map/AG/NpcCowboyServer.cpp @@ -1,8 +1,8 @@ #include "NpcCowboyServer.h" -#include "MissionState.h" +#include "eMissionState.h" #include "InventoryComponent.h" -void NpcCowboyServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void NpcCowboyServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { if (missionID != 1880) { return; } @@ -13,14 +13,14 @@ void NpcCowboyServer::OnMissionDialogueOK(Entity* self, Entity* target, int miss return; } - if (missionState == MissionState::MISSION_STATE_COMPLETE_ACTIVE || - missionState == MissionState::MISSION_STATE_ACTIVE || - missionState == MissionState::MISSION_STATE_AVAILABLE || - missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) { + if (missionState == eMissionState::COMPLETE_ACTIVE || + missionState == eMissionState::ACTIVE || + missionState == eMissionState::AVAILABLE || + missionState == eMissionState::COMPLETE_AVAILABLE) { if (inventoryComponent->GetLotCount(14378) == 0) { inventoryComponent->AddItem(14378, 1, eLootSourceType::LOOT_SOURCE_NONE); } - } else if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + } else if (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { inventoryComponent->RemoveItem(14378, 1); } } diff --git a/dScripts/02_server/Map/AG/NpcCowboyServer.h b/dScripts/02_server/Map/AG/NpcCowboyServer.h index e600d798..4493315c 100644 --- a/dScripts/02_server/Map/AG/NpcCowboyServer.h +++ b/dScripts/02_server/Map/AG/NpcCowboyServer.h @@ -3,5 +3,5 @@ class NpcCowboyServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; }; diff --git a/dScripts/02_server/Map/AG/NpcEpsilonServer.cpp b/dScripts/02_server/Map/AG/NpcEpsilonServer.cpp index f6b8f5c4..a928e9d9 100644 --- a/dScripts/02_server/Map/AG/NpcEpsilonServer.cpp +++ b/dScripts/02_server/Map/AG/NpcEpsilonServer.cpp @@ -1,7 +1,7 @@ #include "NpcEpsilonServer.h" #include "GameMessages.h" -void NpcEpsilonServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void NpcEpsilonServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { //If we are completing the Nexus Force join mission, play the celebration for it: if (missionID == 1851) { diff --git a/dScripts/02_server/Map/AG/NpcEpsilonServer.h b/dScripts/02_server/Map/AG/NpcEpsilonServer.h index 798da33e..4de76bcd 100644 --- a/dScripts/02_server/Map/AG/NpcEpsilonServer.h +++ b/dScripts/02_server/Map/AG/NpcEpsilonServer.h @@ -2,6 +2,6 @@ #include "CppScripts.h" class NpcEpsilonServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState); + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState); }; diff --git a/dScripts/02_server/Map/AG/NpcNjAssistantServer.cpp b/dScripts/02_server/Map/AG/NpcNjAssistantServer.cpp index a53d8ba3..183765d7 100644 --- a/dScripts/02_server/Map/AG/NpcNjAssistantServer.cpp +++ b/dScripts/02_server/Map/AG/NpcNjAssistantServer.cpp @@ -3,24 +3,25 @@ #include "InventoryComponent.h" #include "MissionComponent.h" #include "Item.h" +#include "eMissionState.h" -void NpcNjAssistantServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void NpcNjAssistantServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { if (missionID != mailMission) return; - if (missionState == MissionState::MISSION_STATE_COMPLETE || missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { + if (missionState == eMissionState::COMPLETE || missionState == eMissionState::READY_TO_COMPLETE) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"switch", 0, 0, LWOOBJID_EMPTY, "", target->GetSystemAddress()); auto* inv = static_cast<InventoryComponent*>(target->GetComponent(COMPONENT_TYPE_INVENTORY)); // If we are ready to complete our missions, we take the kit from you: - if (inv && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { + if (inv && missionState == eMissionState::READY_TO_COMPLETE) { auto* id = inv->FindItemByLot(14397); //the kit's lot if (id != nullptr) { inv->RemoveItem(id->GetLot(), id->GetCount()); } } - } else if (missionState == MissionState::MISSION_STATE_AVAILABLE) { + } else if (missionState == eMissionState::AVAILABLE) { auto* missionComponent = static_cast<MissionComponent*>(target->GetComponent(COMPONENT_TYPE_MISSION)); missionComponent->CompleteMission(mailAchievement, true); } diff --git a/dScripts/02_server/Map/AG/NpcNjAssistantServer.h b/dScripts/02_server/Map/AG/NpcNjAssistantServer.h index 7ba847d0..1f932752 100644 --- a/dScripts/02_server/Map/AG/NpcNjAssistantServer.h +++ b/dScripts/02_server/Map/AG/NpcNjAssistantServer.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class NpcNjAssistantServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState); + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState); private: int mailMission = 1728; //mission to get the item out of your mailbox diff --git a/dScripts/02_server/Map/AG/NpcPirateServer.cpp b/dScripts/02_server/Map/AG/NpcPirateServer.cpp index 154fe2bc..6e7e696c 100644 --- a/dScripts/02_server/Map/AG/NpcPirateServer.cpp +++ b/dScripts/02_server/Map/AG/NpcPirateServer.cpp @@ -1,17 +1,17 @@ #include "NpcPirateServer.h" -#include "MissionState.h" +#include "eMissionState.h" #include "InventoryComponent.h" -void NpcPirateServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void NpcPirateServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { auto* inventory = target->GetComponent<InventoryComponent>(); if (inventory != nullptr && missionID == 1881) { auto* luckyShovel = inventory->FindItemByLot(14591); // Add or remove the lucky shovel based on whether the mission was completed or started - if ((missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) + if ((missionState == eMissionState::AVAILABLE || missionState == eMissionState::COMPLETE_AVAILABLE) && luckyShovel == nullptr) { inventory->AddItem(14591, 1, eLootSourceType::LOOT_SOURCE_NONE); - } else if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + } else if (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { inventory->RemoveItem(14591, 1); } } diff --git a/dScripts/02_server/Map/AG/NpcPirateServer.h b/dScripts/02_server/Map/AG/NpcPirateServer.h index dcb399c5..118aec89 100644 --- a/dScripts/02_server/Map/AG/NpcPirateServer.h +++ b/dScripts/02_server/Map/AG/NpcPirateServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NpcPirateServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; }; diff --git a/dScripts/02_server/Map/AG/NpcWispServer.cpp b/dScripts/02_server/Map/AG/NpcWispServer.cpp index d6eab34c..99345973 100644 --- a/dScripts/02_server/Map/AG/NpcWispServer.cpp +++ b/dScripts/02_server/Map/AG/NpcWispServer.cpp @@ -3,9 +3,9 @@ #include "EntityManager.h" #include "Entity.h" #include "GameMessages.h" -#include "MissionState.h" +#include "eMissionState.h" -void NpcWispServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void NpcWispServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { if (missionID != 1849 && missionID != 1883) return; @@ -17,16 +17,16 @@ void NpcWispServer::OnMissionDialogueOK(Entity* self, Entity* target, int missio auto* maelstromVacuum = inventory->FindItemByLot(maelstromVacuumLot); // For the daily we add the maelstrom vacuum if the player doesn't have it yet - if (missionID == 1883 && (missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE) + if (missionID == 1883 && (missionState == eMissionState::AVAILABLE || missionState == eMissionState::COMPLETE_AVAILABLE) && maelstromVacuum == nullptr) { inventory->AddItem(maelstromVacuumLot, 1, eLootSourceType::LOOT_SOURCE_NONE); - } else if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + } else if (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { inventory->RemoveItem(maelstromVacuumLot, 1); } // Next up hide or show the samples based on the mission state auto visible = 1; - if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + if (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { visible = 0; } diff --git a/dScripts/02_server/Map/AG/NpcWispServer.h b/dScripts/02_server/Map/AG/NpcWispServer.h index 86c9c33d..6eaa09e9 100644 --- a/dScripts/02_server/Map/AG/NpcWispServer.h +++ b/dScripts/02_server/Map/AG/NpcWispServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NpcWispServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState); + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState); }; diff --git a/dScripts/02_server/Map/AG/RemoveRentalGear.cpp b/dScripts/02_server/Map/AG/RemoveRentalGear.cpp index fbb00c79..6e7bd4de 100644 --- a/dScripts/02_server/Map/AG/RemoveRentalGear.cpp +++ b/dScripts/02_server/Map/AG/RemoveRentalGear.cpp @@ -1,7 +1,7 @@ #include "RemoveRentalGear.h" #include "InventoryComponent.h" #include "Item.h" -#include "MissionState.h" +#include "eMissionState.h" #include "Character.h" /* @@ -17,10 +17,10 @@ -------------------------------------------------------------- */ -void RemoveRentalGear::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void RemoveRentalGear::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { if (missionID != defaultMission && missionID != 313) return; - if (missionState == MissionState::MISSION_STATE_COMPLETE || missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { + if (missionState == eMissionState::COMPLETE || missionState == eMissionState::READY_TO_COMPLETE) { auto inv = static_cast<InventoryComponent*>(target->GetComponent(COMPONENT_TYPE_INVENTORY)); if (!inv) return; diff --git a/dScripts/02_server/Map/AG/RemoveRentalGear.h b/dScripts/02_server/Map/AG/RemoveRentalGear.h index 49ca0860..cc33b5f6 100644 --- a/dScripts/02_server/Map/AG/RemoveRentalGear.h +++ b/dScripts/02_server/Map/AG/RemoveRentalGear.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class RemoveRentalGear : public CppScripts::Script { - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState); + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState); private: int defaultMission = 768; //mission to remove gearSets on completion diff --git a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp index 909beaaf..15ca7267 100644 --- a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp +++ b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp @@ -3,6 +3,7 @@ #include "RebuildComponent.h" #include "InventoryComponent.h" #include "dZoneManager.h" +#include "eMissionState.h" void AmDropshipComputer::OnStartup(Entity* self) { self->AddTimer("reset", 45.0f); @@ -22,7 +23,7 @@ void AmDropshipComputer::OnUse(Entity* self, Entity* user) { return; } - if (inventoryComponent->GetLotCount(m_NexusTalonDataCard) != 0 || missionComponent->GetMission(979)->GetMissionState() == MissionState::MISSION_STATE_COMPLETE) { + if (inventoryComponent->GetLotCount(m_NexusTalonDataCard) != 0 || missionComponent->GetMission(979)->GetMissionState() == eMissionState::COMPLETE) { return; } diff --git a/dScripts/02_server/Map/FV/FvFong.cpp b/dScripts/02_server/Map/FV/FvFong.cpp index 7f63e5e5..13c637e7 100644 --- a/dScripts/02_server/Map/FV/FvFong.cpp +++ b/dScripts/02_server/Map/FV/FvFong.cpp @@ -1,9 +1,9 @@ #include "FvFong.h" #include "Darkitect.h" -#include "MissionState.h" +#include "eMissionState.h" -void FvFong::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { - if (missionID == 734 && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { +void FvFong::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { + if (missionID == 734 && missionState == eMissionState::READY_TO_COMPLETE) { Darkitect Baron; Baron.Reveal(self, target); } diff --git a/dScripts/02_server/Map/FV/FvFong.h b/dScripts/02_server/Map/FV/FvFong.h index 074e6d8c..c0b6d48b 100644 --- a/dScripts/02_server/Map/FV/FvFong.h +++ b/dScripts/02_server/Map/FV/FvFong.h @@ -4,5 +4,5 @@ class FvFong : public CppScripts::Script { public: - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; }; diff --git a/dScripts/02_server/Map/FV/ImgBrickConsoleQB.cpp b/dScripts/02_server/Map/FV/ImgBrickConsoleQB.cpp index 4a12324f..9c7b858f 100644 --- a/dScripts/02_server/Map/FV/ImgBrickConsoleQB.cpp +++ b/dScripts/02_server/Map/FV/ImgBrickConsoleQB.cpp @@ -4,6 +4,7 @@ #include "EntityManager.h" #include "GameMessages.h" #include "MissionComponent.h" +#include "eMissionState.h" #include "InventoryComponent.h" int32_t ImgBrickConsoleQB::ResetBricks = 30; @@ -71,13 +72,13 @@ void ImgBrickConsoleQB::OnUse(Entity* self, Entity* user) { auto* inventoryComponent = player->GetComponent<InventoryComponent>(); if (missionComponent != nullptr && inventoryComponent != nullptr) { - if (missionComponent->GetMissionState(1302) == MissionState::MISSION_STATE_ACTIVE) { + if (missionComponent->GetMissionState(1302) == eMissionState::ACTIVE) { inventoryComponent->RemoveItem(13074, 1); missionComponent->ForceProgressTaskType(1302, 1, 1); } - if (missionComponent->GetMissionState(1926) == MissionState::MISSION_STATE_ACTIVE) { + if (missionComponent->GetMissionState(1926) == eMissionState::ACTIVE) { inventoryComponent->RemoveItem(14472, 1); missionComponent->ForceProgressTaskType(1926, 1, 1); diff --git a/dScripts/02_server/Map/GF/GfTikiTorch.cpp b/dScripts/02_server/Map/GF/GfTikiTorch.cpp index 3a06b054..db7ee6b5 100644 --- a/dScripts/02_server/Map/GF/GfTikiTorch.cpp +++ b/dScripts/02_server/Map/GF/GfTikiTorch.cpp @@ -3,6 +3,7 @@ #include "EntityManager.h" #include "MissionComponent.h" #include "RenderComponent.h" +#include "eMissionTaskType.h" void GfTikiTorch::OnStartup(Entity* self) { LightTorch(self); @@ -65,7 +66,7 @@ void GfTikiTorch::OnSkillEventFired(Entity* self, Entity* caster, const std::str auto* casterMissionComponent = caster->GetComponent<MissionComponent>(); if (casterMissionComponent != nullptr) { for (const auto missionID : m_missions) { - casterMissionComponent->ForceProgressTaskType(missionID, static_cast<uint32_t>(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); + casterMissionComponent->ForceProgressTaskType(missionID, static_cast<uint32_t>(eMissionTaskType::SCRIPT), 1); } } diff --git a/dScripts/02_server/Map/General/ExplodingAsset.cpp b/dScripts/02_server/Map/General/ExplodingAsset.cpp index 46ff1522..16340ee6 100644 --- a/dScripts/02_server/Map/General/ExplodingAsset.cpp +++ b/dScripts/02_server/Map/General/ExplodingAsset.cpp @@ -3,6 +3,7 @@ #include "GameMessages.h" #include "MissionComponent.h" #include "SkillComponent.h" +#include "eMissionTaskType.h" //TODO: this has to be updated so that you only get killed if you're in a certain radius. //And so that all entities in a certain radius are killed, not just the attacker. @@ -51,14 +52,14 @@ void ExplodingAsset::OnHit(Entity* self, Entity* attacker) { if (missionComponent != nullptr) { if (missionID != 0) { missionComponent->ForceProgressValue(missionID, - static_cast<uint32_t>(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), + static_cast<uint32_t>(eMissionTaskType::SCRIPT), self->GetLOT(), false); } if (!achievementIDs.empty()) { for (const auto& achievementID : GeneralUtils::SplitString(achievementIDs, u'_')) { missionComponent->ForceProgressValue(std::stoi(GeneralUtils::UTF16ToWTF8(achievementID)), - static_cast<uint32_t>(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), + static_cast<uint32_t>(eMissionTaskType::SCRIPT), self->GetLOT()); } } diff --git a/dScripts/02_server/Map/General/GrowingFlower.cpp b/dScripts/02_server/Map/General/GrowingFlower.cpp index 61bfbc30..ad88528f 100644 --- a/dScripts/02_server/Map/General/GrowingFlower.cpp +++ b/dScripts/02_server/Map/General/GrowingFlower.cpp @@ -1,5 +1,7 @@ #include "GrowingFlower.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" +#include "eMissionState.h" #include "Loot.h" void GrowingFlower::OnSkillEventFired(Entity* self, Entity* target, const std::string& message) { @@ -16,13 +18,13 @@ void GrowingFlower::OnSkillEventFired(Entity* self, Entity* target, const std::s auto* missionComponent = target->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { for (const auto mission : achievementIDs) - missionComponent->ForceProgressTaskType(mission, static_cast<uint32_t>(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); + missionComponent->ForceProgressTaskType(mission, static_cast<uint32_t>(eMissionTaskType::SCRIPT), 1); - if (mission1 && missionComponent->GetMissionState(mission1) == MissionState::MISSION_STATE_ACTIVE) - missionComponent->ForceProgressTaskType(mission1, static_cast<uint32_t>(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); + if (mission1 && missionComponent->GetMissionState(mission1) == eMissionState::ACTIVE) + missionComponent->ForceProgressTaskType(mission1, static_cast<uint32_t>(eMissionTaskType::SCRIPT), 1); - if (mission2 && missionComponent->GetMissionState(mission2) == MissionState::MISSION_STATE_ACTIVE) - missionComponent->ForceProgressTaskType(mission2, static_cast<uint32_t>(MissionTaskType::MISSION_TASK_TYPE_SCRIPT), 1); + if (mission2 && missionComponent->GetMissionState(mission2) == eMissionState::ACTIVE) + missionComponent->ForceProgressTaskType(mission2, static_cast<uint32_t>(eMissionTaskType::SCRIPT), 1); } } } diff --git a/dScripts/02_server/Map/General/ImaginationBackpackHealServer.cpp b/dScripts/02_server/Map/General/ImaginationBackpackHealServer.cpp index 1e0d35cf..8b3da9fa 100644 --- a/dScripts/02_server/Map/General/ImaginationBackpackHealServer.cpp +++ b/dScripts/02_server/Map/General/ImaginationBackpackHealServer.cpp @@ -1,6 +1,8 @@ #include "ImaginationBackpackHealServer.h" #include "GameMessages.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" +#include "eMissionState.h" void ImaginationBackpackHealServer::OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) { if (message == "CastImaginationBackpack") { @@ -11,8 +13,8 @@ void ImaginationBackpackHealServer::OnSkillEventFired(Entity* self, Entity* cast return; auto* missionComponent = caster->GetComponent<MissionComponent>(); - if (missionComponent != nullptr && missionComponent->GetMissionState(healMission) == MissionState::MISSION_STATE_ACTIVE) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + if (missionComponent != nullptr && missionComponent->GetMissionState(healMission) == eMissionState::ACTIVE) { + missionComponent->Progress(eMissionTaskType::SCRIPT, self->GetLOT()); GameMessages::SendNotifyClientObject(self->GetObjectID(), u"ClearMaelstrom", 0, 0, caster->GetObjectID(), "", caster->GetSystemAddress()); } diff --git a/dScripts/02_server/Map/General/PetDigServer.cpp b/dScripts/02_server/Map/General/PetDigServer.cpp index 0d62ff04..81d70faf 100644 --- a/dScripts/02_server/Map/General/PetDigServer.cpp +++ b/dScripts/02_server/Map/General/PetDigServer.cpp @@ -5,6 +5,7 @@ #include "Character.h" #include "PetComponent.h" #include "User.h" +#include "eMissionState.h" std::vector<LWOOBJID> PetDigServer::treasures{}; @@ -163,13 +164,13 @@ void PetDigServer::ProgressPetDigMissions(const Entity* owner, const Entity* che if (missionComponent != nullptr) { // Can You Dig It progress const auto digMissionState = missionComponent->GetMissionState(843); - if (digMissionState == MissionState::MISSION_STATE_ACTIVE) { + if (digMissionState == eMissionState::ACTIVE) { missionComponent->ForceProgress(843, 1216, 1); } // Pet Excavator progress const auto excavatorMissionState = missionComponent->GetMissionState(505); - if (excavatorMissionState == MissionState::MISSION_STATE_ACTIVE) { + if (excavatorMissionState == eMissionState::ACTIVE) { if (chest->HasVar(u"PetDig")) { int32_t playerFlag = 1260 + chest->GetVarAs<int32_t>(u"PetDig"); Character* player = owner->GetCharacter(); @@ -193,7 +194,7 @@ void PetDigServer::SpawnPet(Entity* self, const Entity* owner, const DigInfo dig // Some treasures require a mission to be active if (digInfo.requiredMission >= 0) { auto* missionComponent = owner->GetComponent<MissionComponent>(); - if (missionComponent != nullptr && missionComponent->GetMissionState(digInfo.requiredMission) < MissionState::MISSION_STATE_ACTIVE) { + if (missionComponent != nullptr && missionComponent->GetMissionState(digInfo.requiredMission) < eMissionState::ACTIVE) { return; } } diff --git a/dScripts/02_server/Map/General/PropertyDevice.cpp b/dScripts/02_server/Map/General/PropertyDevice.cpp index 64771de1..0ad9f5c9 100644 --- a/dScripts/02_server/Map/General/PropertyDevice.cpp +++ b/dScripts/02_server/Map/General/PropertyDevice.cpp @@ -2,6 +2,7 @@ #include "GameMessages.h" #include "EntityManager.h" #include "MissionComponent.h" +#include "eMissionState.h" void PropertyDevice::OnStartup(Entity* self) { auto* zoneControl = EntityManager::Instance()->GetZoneControlEntity(); @@ -17,7 +18,7 @@ void PropertyDevice::OnRebuildComplete(Entity* self, Entity* target) { auto* missionComponent = target->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { - if (missionComponent->GetMissionState(m_PropertyMissionID) == MissionState::MISSION_STATE_ACTIVE) { + if (missionComponent->GetMissionState(m_PropertyMissionID) == eMissionState::ACTIVE) { GameMessages::SendPlayFXEffect(self->GetObjectID(), 641, u"create", "callhome"); missionComponent->ForceProgress(m_PropertyMissionID, 1793, self->GetLOT()); } diff --git a/dScripts/02_server/Map/General/TouchMissionUpdateServer.cpp b/dScripts/02_server/Map/General/TouchMissionUpdateServer.cpp index f732305e..00c1b900 100644 --- a/dScripts/02_server/Map/General/TouchMissionUpdateServer.cpp +++ b/dScripts/02_server/Map/General/TouchMissionUpdateServer.cpp @@ -3,6 +3,7 @@ #include "Entity.h" #include "GameMessages.h" #include "MissionComponent.h" +#include "eMissionState.h" void TouchMissionUpdateServer::OnStartup(Entity* self) { self->SetProximityRadius(20, "touchCheck"); // Those does not have a collider for some reason? @@ -29,7 +30,7 @@ void TouchMissionUpdateServer::OnCollisionPhantom(Entity* self, Entity* target) const auto state = mission->GetMissionState(); - if (state >= MissionState::MISSION_STATE_COMPLETE || mission->GetCompletions() > 1) { + if (state >= eMissionState::COMPLETE || mission->GetCompletions() > 1) { return; } diff --git a/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp b/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp index 5410047d..b4d75296 100644 --- a/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp +++ b/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp @@ -2,6 +2,8 @@ #include "GameMessages.h" #include "EntityManager.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" +#include "eMissionState.h" void NtAssemblyTubeServer::OnStartup(Entity* self) { self->SetProximityRadius(5, "teleport"); @@ -22,7 +24,7 @@ void NtAssemblyTubeServer::OnProximityUpdate(Entity* self, Entity* entering, std auto* missionComponent = player->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + missionComponent->Progress(eMissionTaskType::SCRIPT, self->GetLOT()); } } diff --git a/dScripts/02_server/Map/NT/NtDukeServer.cpp b/dScripts/02_server/Map/NT/NtDukeServer.cpp index 327d3290..d48d50c7 100644 --- a/dScripts/02_server/Map/NT/NtDukeServer.cpp +++ b/dScripts/02_server/Map/NT/NtDukeServer.cpp @@ -1,6 +1,7 @@ #include "NtDukeServer.h" #include "InventoryComponent.h" #include "MissionComponent.h" +#include "eMissionState.h" void NtDukeServer::SetVariables(Entity* self) { self->SetVar<float_t>(m_SpyProximityVariable, 35.0f); @@ -19,7 +20,7 @@ void NtDukeServer::SetVariables(Entity* self) { self->SetVar<std::vector<LWOOBJID>>(m_SpyCinematicObjectsVariable, { self->GetObjectID() }); } -void NtDukeServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void NtDukeServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { // Handles adding and removing the sword for the Crux Prime Sword mission auto* missionComponent = target->GetComponent<MissionComponent>(); @@ -29,9 +30,9 @@ void NtDukeServer::OnMissionDialogueOK(Entity* self, Entity* target, int mission auto state = missionComponent->GetMissionState(m_SwordMissionID); auto lotCount = inventoryComponent->GetLotCount(m_SwordLot); - if ((state == MissionState::MISSION_STATE_AVAILABLE || state == MissionState::MISSION_STATE_ACTIVE) && lotCount < 1) { + if ((state == eMissionState::AVAILABLE || state == eMissionState::ACTIVE) && lotCount < 1) { inventoryComponent->AddItem(m_SwordLot, 1, eLootSourceType::LOOT_SOURCE_NONE); - } else if (state == MissionState::MISSION_STATE_READY_TO_COMPLETE) { + } else if (state == eMissionState::READY_TO_COMPLETE) { inventoryComponent->RemoveItem(m_SwordLot, lotCount); } } diff --git a/dScripts/02_server/Map/NT/NtDukeServer.h b/dScripts/02_server/Map/NT/NtDukeServer.h index 0878e86c..2103ba8d 100644 --- a/dScripts/02_server/Map/NT/NtDukeServer.h +++ b/dScripts/02_server/Map/NT/NtDukeServer.h @@ -3,7 +3,7 @@ class NtDukeServer : public NtFactionSpyServer { void SetVariables(Entity* self) override; - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; const uint32_t m_SwordMissionID = 1448; const LOT m_SwordLot = 13777; }; diff --git a/dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp b/dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp index 8d14050b..0cb0bec4 100644 --- a/dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp +++ b/dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp @@ -3,6 +3,7 @@ #include "MissionComponent.h" #include "EntityManager.h" #include "Character.h" +#include "eMissionState.h" void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"bActive", 1, 0, user->GetObjectID(), "", user->GetSystemAddress()); @@ -16,7 +17,7 @@ void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) { const auto playerID = user->GetObjectID(); for (const auto mission : tPlayerOnMissions) { - if (missionComponent->GetMissionState(mission) != MissionState::MISSION_STATE_ACTIVE) { + if (missionComponent->GetMissionState(mission) != eMissionState::ACTIVE) { continue; } diff --git a/dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp b/dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp index 64af4d34..8b4f19fe 100644 --- a/dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp +++ b/dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp @@ -2,6 +2,7 @@ #include "GameMessages.h" #include "EntityManager.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" void NtParadoxTeleServer::OnStartup(Entity* self) { self->SetProximityRadius(5, "teleport"); @@ -44,7 +45,7 @@ void NtParadoxTeleServer::OnProximityUpdate(Entity* self, Entity* entering, std: auto* missionComponent = player->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + missionComponent->Progress(eMissionTaskType::SCRIPT, self->GetLOT()); } } diff --git a/dScripts/02_server/Map/NT/NtSentinelWalkwayServer.cpp b/dScripts/02_server/Map/NT/NtSentinelWalkwayServer.cpp index 7b943172..66bfe46f 100644 --- a/dScripts/02_server/Map/NT/NtSentinelWalkwayServer.cpp +++ b/dScripts/02_server/Map/NT/NtSentinelWalkwayServer.cpp @@ -2,6 +2,7 @@ #include "PhantomPhysicsComponent.h" #include "EntityManager.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" void NtSentinelWalkwayServer::OnStartup(Entity* self) { auto* phantomPhysicsComponent = self->GetComponent<PhantomPhysicsComponent>(); @@ -38,6 +39,6 @@ void NtSentinelWalkwayServer::OnProximityUpdate(Entity* self, Entity* entering, auto* missionComponent = player->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + missionComponent->Progress(eMissionTaskType::SCRIPT, self->GetLOT()); } } diff --git a/dScripts/02_server/Map/NT/NtVandaServer.cpp b/dScripts/02_server/Map/NT/NtVandaServer.cpp index e5653005..7750d566 100644 --- a/dScripts/02_server/Map/NT/NtVandaServer.cpp +++ b/dScripts/02_server/Map/NT/NtVandaServer.cpp @@ -1,11 +1,11 @@ #include "NtVandaServer.h" #include "InventoryComponent.h" -#include "MissionState.h" +#include "eMissionState.h" -void NtVandaServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void NtVandaServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { // Removes the alien parts after completing the mission - if (missionID == m_AlienPartMissionID && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE) { + if (missionID == m_AlienPartMissionID && missionState == eMissionState::READY_TO_COMPLETE) { auto* inventoryComponent = target->GetComponent<InventoryComponent>(); for (const auto& alienPartLot : m_AlienPartLots) { inventoryComponent->RemoveItem(alienPartLot, 1); diff --git a/dScripts/02_server/Map/NT/NtVandaServer.h b/dScripts/02_server/Map/NT/NtVandaServer.h index 69e868f5..58162cd9 100644 --- a/dScripts/02_server/Map/NT/NtVandaServer.h +++ b/dScripts/02_server/Map/NT/NtVandaServer.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class NtVandaServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; const uint32_t m_AlienPartMissionID = 1183; const std::vector<LOT> m_AlienPartLots = { 12479, 12480, 12481 }; }; diff --git a/dScripts/02_server/Map/NT/NtVentureSpeedPadServer.cpp b/dScripts/02_server/Map/NT/NtVentureSpeedPadServer.cpp index 0995d1df..07d33555 100644 --- a/dScripts/02_server/Map/NT/NtVentureSpeedPadServer.cpp +++ b/dScripts/02_server/Map/NT/NtVentureSpeedPadServer.cpp @@ -1,6 +1,7 @@ #include "NtVentureSpeedPadServer.h" #include "SkillComponent.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" void NtVentureSpeedPadServer::OnStartup(Entity* self) { self->SetProximityRadius(3, "speedboost"); @@ -17,7 +18,7 @@ void NtVentureSpeedPadServer::OnProximityUpdate(Entity* self, Entity* entering, auto* missionComponent = player->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + missionComponent->Progress(eMissionTaskType::SCRIPT, self->GetLOT()); } auto* skillComponent = player->GetComponent<SkillComponent>(); diff --git a/dScripts/02_server/Map/PR/SpawnGryphonServer.cpp b/dScripts/02_server/Map/PR/SpawnGryphonServer.cpp index 22e5ff59..2b7e3904 100644 --- a/dScripts/02_server/Map/PR/SpawnGryphonServer.cpp +++ b/dScripts/02_server/Map/PR/SpawnGryphonServer.cpp @@ -2,6 +2,7 @@ #include "InventoryComponent.h" #include "GameMessages.h" #include "MissionComponent.h" +#include "eMissionState.h" void SpawnGryphonServer::SetVariables(Entity* self) { self->SetVar<LOT>(u"petLOT", 12433); @@ -17,7 +18,7 @@ void SpawnGryphonServer::OnUse(Entity* self, Entity* user) { // Little extra for handling the case of the egg being placed the first time if (missionComponent != nullptr && inventoryComponent != nullptr - && missionComponent->GetMissionState(1391) == MissionState::MISSION_STATE_ACTIVE) { + && missionComponent->GetMissionState(1391) == eMissionState::ACTIVE) { inventoryComponent->RemoveItem(12483, inventoryComponent->GetLotCount(12483)); GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); return; diff --git a/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp b/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp index db2bb78a..b6172df1 100644 --- a/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp +++ b/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp @@ -6,6 +6,7 @@ #include "dZoneManager.h" #include "RenderComponent.h" #include "MissionComponent.h" +#include "eMissionState.h" void ZoneAgProperty::SetGameVariables(Entity* self) { self->SetVar<std::string>(GuardGroup, "Guard"); @@ -80,7 +81,7 @@ void ZoneAgProperty::PropGuardCheck(Entity* self, Entity* player) { const auto state = missionComponent->GetMissionState(self->GetVar<uint32_t>(guardMissionFlag)); const auto firstState = missionComponent->GetMissionState(self->GetVar<uint32_t>(guardFirstMissionFlag)); - if (firstState < MissionState::MISSION_STATE_COMPLETE || (state != MissionState::MISSION_STATE_COMPLETE && state != MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE)) + if (firstState < eMissionState::COMPLETE || (state != eMissionState::COMPLETE && state != eMissionState::COMPLETE_READY_TO_COMPLETE)) ActivateSpawner(self->GetVar<std::string>(PropertyMGSpawner)); } @@ -304,13 +305,13 @@ void ZoneAgProperty::OnZonePropertyModelPlaced(Entity* self, Entity* player) { if (!character->GetPlayerFlag(101)) { BaseZonePropertyModelPlaced(self, player); character->SetPlayerFlag(101, true); - if (missionComponent->GetMissionState(871) == MissionState::MISSION_STATE_ACTIVE) { + if (missionComponent->GetMissionState(871) == eMissionState::ACTIVE) { self->SetNetworkVar<std::u16string>(u"Tooltip", u"AnotherModel"); } } else if (!character->GetPlayerFlag(102)) { character->SetPlayerFlag(102, true); - if (missionComponent->GetMissionState(871) == MissionState::MISSION_STATE_ACTIVE) { + if (missionComponent->GetMissionState(871) == eMissionState::ACTIVE) { self->SetNetworkVar<std::u16string>(u"Tooltip", u"TwoMoreModels"); } @@ -331,7 +332,7 @@ void ZoneAgProperty::OnZonePropertyModelPickedUp(Entity* self, Entity* player) { if (!character->GetPlayerFlag(109)) { character->SetPlayerFlag(109, true); - if (missionComponent->GetMissionState(891) == MissionState::MISSION_STATE_ACTIVE && !character->GetPlayerFlag(110)) { + if (missionComponent->GetMissionState(891) == eMissionState::ACTIVE && !character->GetPlayerFlag(110)) { self->SetNetworkVar<std::u16string>(u"Tooltip", u"Rotate"); } } @@ -353,7 +354,7 @@ void ZoneAgProperty::OnZonePropertyModelRotated(Entity* self, Entity* player) { if (!character->GetPlayerFlag(110)) { character->SetPlayerFlag(110, true); - if (missionComponent->GetMissionState(891) == MissionState::MISSION_STATE_ACTIVE) { + if (missionComponent->GetMissionState(891) == eMissionState::ACTIVE) { self->SetNetworkVar<std::u16string>(u"Tooltip", u"PlaceModel"); self->SetVar<std::string>(u"tutorial", "place_model"); } diff --git a/dScripts/02_server/Map/SS/SsModularBuildServer.cpp b/dScripts/02_server/Map/SS/SsModularBuildServer.cpp index d5b6da50..82c802cc 100644 --- a/dScripts/02_server/Map/SS/SsModularBuildServer.cpp +++ b/dScripts/02_server/Map/SS/SsModularBuildServer.cpp @@ -1,5 +1,6 @@ #include "SsModularBuildServer.h" #include "MissionComponent.h" +#include "eMissionState.h" void SsModularBuildServer::OnModularBuildExit(Entity* self, Entity* player, bool bCompleted, std::vector<LOT> modules) { int missionNum = 1732; @@ -8,7 +9,7 @@ void SsModularBuildServer::OnModularBuildExit(Entity* self, Entity* player, bool MissionComponent* mission = static_cast<MissionComponent*>(player->GetComponent(COMPONENT_TYPE_MISSION)); Mission* rocketMission = mission->GetMission(missionNum); - if (rocketMission->GetMissionState() == MissionState::MISSION_STATE_ACTIVE) { + if (rocketMission->GetMissionState() == eMissionState::ACTIVE) { mission->ForceProgress(missionNum, 2478, 1); } } diff --git a/dScripts/02_server/Map/VE/VeBricksampleServer.cpp b/dScripts/02_server/Map/VE/VeBricksampleServer.cpp index 5166d0c3..36306d07 100644 --- a/dScripts/02_server/Map/VE/VeBricksampleServer.cpp +++ b/dScripts/02_server/Map/VE/VeBricksampleServer.cpp @@ -3,10 +3,11 @@ #include "EntityManager.h" #include "MissionComponent.h" #include "GameMessages.h" +#include "eMissionState.h" void VeBricksampleServer::OnUse(Entity* self, Entity* user) { auto* missionComponent = user->GetComponent<MissionComponent>(); - if (missionComponent != nullptr && missionComponent->GetMissionState(1183) == MissionState::MISSION_STATE_ACTIVE) { + if (missionComponent != nullptr && missionComponent->GetMissionState(1183) == eMissionState::ACTIVE) { const auto loot = self->GetVar<int32_t>(m_LootVariable); auto* inventoryComponent = user->GetComponent<InventoryComponent>(); diff --git a/dScripts/02_server/Map/VE/VeEpsilonServer.cpp b/dScripts/02_server/Map/VE/VeEpsilonServer.cpp index 4a2f1bbf..c69f9cc2 100644 --- a/dScripts/02_server/Map/VE/VeEpsilonServer.cpp +++ b/dScripts/02_server/Map/VE/VeEpsilonServer.cpp @@ -2,17 +2,17 @@ #include "Character.h" #include "EntityManager.h" #include "GameMessages.h" -#include "MissionState.h" +#include "eMissionState.h" #include "Entity.h" -void VeEpsilonServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void VeEpsilonServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { auto* character = target->GetCharacter(); if (character == nullptr) return; // Resets the player flags that track which consoles they've used if ((missionID == m_ConsoleMissionID || missionID == m_ConsoleRepeatMissionID) - && (missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE)) { + && (missionState == eMissionState::AVAILABLE || missionState == eMissionState::COMPLETE_AVAILABLE)) { for (auto i = 0; i < 10; i++) { character->SetPlayerFlag(m_ConsoleBaseFlag + i, false); diff --git a/dScripts/02_server/Map/VE/VeEpsilonServer.h b/dScripts/02_server/Map/VE/VeEpsilonServer.h index d1236e96..971cd93e 100644 --- a/dScripts/02_server/Map/VE/VeEpsilonServer.h +++ b/dScripts/02_server/Map/VE/VeEpsilonServer.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class VeEpsilonServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; const uint32_t m_ConsoleMissionID = 1220; const uint32_t m_ConsoleRepeatMissionID = 1225; const uint32_t m_ConsoleBaseFlag = 1010; diff --git a/dScripts/02_server/Map/njhub/NjColeNPC.cpp b/dScripts/02_server/Map/njhub/NjColeNPC.cpp index f151db40..672fdd95 100644 --- a/dScripts/02_server/Map/njhub/NjColeNPC.cpp +++ b/dScripts/02_server/Map/njhub/NjColeNPC.cpp @@ -1,6 +1,7 @@ #include "NjColeNPC.h" #include "MissionComponent.h" #include "InventoryComponent.h" +#include "eMissionState.h" void NjColeNPC::OnEmoteReceived(Entity* self, int32_t emote, Entity* target) { if (emote != 393) { @@ -26,10 +27,10 @@ void NjColeNPC::OnEmoteReceived(Entity* self, int32_t emote, Entity* target) { missionComponent->ForceProgressTaskType(1818, 1, 1); } -void NjColeNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void NjColeNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(self, target, missionID, missionState); - if (missionID == 1818 && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { + if (missionID == 1818 && missionState >= eMissionState::READY_TO_COMPLETE) { auto* missionComponent = target->GetComponent<MissionComponent>(); auto* inventoryComponent = target->GetComponent<InventoryComponent>(); diff --git a/dScripts/02_server/Map/njhub/NjColeNPC.h b/dScripts/02_server/Map/njhub/NjColeNPC.h index cf8e67e1..a2536e32 100644 --- a/dScripts/02_server/Map/njhub/NjColeNPC.h +++ b/dScripts/02_server/Map/njhub/NjColeNPC.h @@ -3,5 +3,5 @@ class NjColeNPC : public NjNPCMissionSpinjitzuServer { void OnEmoteReceived(Entity* self, int32_t emote, Entity* target) override; - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; }; diff --git a/dScripts/02_server/Map/njhub/NjJayMissionItems.cpp b/dScripts/02_server/Map/njhub/NjJayMissionItems.cpp index cc871b86..46131446 100644 --- a/dScripts/02_server/Map/njhub/NjJayMissionItems.cpp +++ b/dScripts/02_server/Map/njhub/NjJayMissionItems.cpp @@ -1,6 +1,6 @@ #include "NjJayMissionItems.h" -void NjJayMissionItems::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void NjJayMissionItems::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(self, target, missionID, missionState); NPCAddRemoveItem::OnMissionDialogueOK(self, target, missionID, missionState); } diff --git a/dScripts/02_server/Map/njhub/NjJayMissionItems.h b/dScripts/02_server/Map/njhub/NjJayMissionItems.h index c49f49ea..bdaee3ea 100644 --- a/dScripts/02_server/Map/njhub/NjJayMissionItems.h +++ b/dScripts/02_server/Map/njhub/NjJayMissionItems.h @@ -5,6 +5,6 @@ #include <map> class NjJayMissionItems : public NjNPCMissionSpinjitzuServer, NPCAddRemoveItem { - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; std::map<uint32_t, std::vector<ItemSetting>> GetSettings() override; }; diff --git a/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.cpp b/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.cpp index 69838dc8..30bba804 100644 --- a/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.cpp +++ b/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.cpp @@ -1,13 +1,12 @@ #include "NjNPCMissionSpinjitzuServer.h" #include "Character.h" #include "EntityManager.h" -#include "MissionState.h" +#include "eMissionState.h" -void NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, - MissionState missionState) { +void NjNPCMissionSpinjitzuServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { const auto& element = self->GetVar<std::u16string>(ElementVariable); - if (missionID == ElementMissions.at(element) && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { + if (missionID == ElementMissions.at(element) && missionState >= eMissionState::READY_TO_COMPLETE) { const auto targetID = target->GetObjectID(); diff --git a/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.h b/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.h index 8f25a86a..3c705925 100644 --- a/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.h +++ b/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.h @@ -18,7 +18,7 @@ static std::map<std::u16string, uint32_t> ElementMissions = { class NjNPCMissionSpinjitzuServer : public CppScripts::Script { public: - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; private: const std::u16string ElementVariable = u"element"; }; diff --git a/dScripts/02_server/Map/njhub/NjWuNPC.cpp b/dScripts/02_server/Map/njhub/NjWuNPC.cpp index 855e4433..9efc623b 100644 --- a/dScripts/02_server/Map/njhub/NjWuNPC.cpp +++ b/dScripts/02_server/Map/njhub/NjWuNPC.cpp @@ -3,8 +3,9 @@ #include "Character.h" #include "EntityManager.h" #include "GameMessages.h" +#include "eMissionState.h" -void NjWuNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void NjWuNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { // The Dragon statue daily mission if (missionID == m_MainDragonMissionID) { @@ -14,8 +15,8 @@ void NjWuNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, M return; switch (missionState) { - case MissionState::MISSION_STATE_AVAILABLE: - case MissionState::MISSION_STATE_COMPLETE_AVAILABLE: + case eMissionState::AVAILABLE: + case eMissionState::COMPLETE_AVAILABLE: { // Reset the sub missions for (const auto& subMissionID : m_SubDragonMissionIDs) { @@ -33,8 +34,8 @@ void NjWuNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, M return; } - case MissionState::MISSION_STATE_READY_TO_COMPLETE: - case MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE: + case eMissionState::READY_TO_COMPLETE: + case eMissionState::COMPLETE_READY_TO_COMPLETE: { character->SetPlayerFlag(NJ_WU_SHOW_DAILY_CHEST, true); diff --git a/dScripts/02_server/Map/njhub/NjWuNPC.h b/dScripts/02_server/Map/njhub/NjWuNPC.h index d0cd750b..f8c52303 100644 --- a/dScripts/02_server/Map/njhub/NjWuNPC.h +++ b/dScripts/02_server/Map/njhub/NjWuNPC.h @@ -2,7 +2,7 @@ #include "AmTemplateSkillVolume.h" class NjWuNPC : public AmTemplateSkillVolume { - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; const uint32_t m_MainDragonMissionID = 2040; const std::vector<uint32_t> m_SubDragonMissionIDs = { 2064, 2065, 2066, 2067 }; diff --git a/dScripts/BasePropertyServer.cpp b/dScripts/BasePropertyServer.cpp index a182c9c1..7552eeca 100644 --- a/dScripts/BasePropertyServer.cpp +++ b/dScripts/BasePropertyServer.cpp @@ -8,6 +8,8 @@ #include "RenderComponent.h" #include "PropertyManagementComponent.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" +#include "eMissionState.h" void BasePropertyServer::SetGameVariables(Entity* self) { self->SetVar<std::string>(ClaimMarkerGroup, ""); @@ -97,7 +99,7 @@ void BasePropertyServer::BasePlayerLoaded(Entity* self, Entity* player) { if (missionComponent != nullptr) { missionComponent->Progress( - MissionTaskType::MISSION_TASK_TYPE_VISIT_PROPERTY, + eMissionTaskType::VISIT_PROPERTY, mapID.GetMapID(), mapID.GetCloneID() ); @@ -150,7 +152,7 @@ void BasePropertyServer::PropGuardCheck(Entity* self, Entity* player) { auto* missionComponent = player->GetComponent<MissionComponent>(); if (missionComponent != nullptr - && missionComponent->GetMissionState(self->GetVar<uint32_t>(guardMissionFlag)) != MissionState::MISSION_STATE_COMPLETE) { + && missionComponent->GetMissionState(self->GetVar<uint32_t>(guardMissionFlag)) != eMissionState::COMPLETE) { ActivateSpawner(self->GetVar<std::string>(PropertyMGSpawner)); } } diff --git a/dScripts/BaseSurvivalServer.cpp b/dScripts/BaseSurvivalServer.cpp index 270b6741..3d72628d 100644 --- a/dScripts/BaseSurvivalServer.cpp +++ b/dScripts/BaseSurvivalServer.cpp @@ -4,7 +4,8 @@ #include "EntityManager.h" #include "dZoneManager.h" #include "Player.h" -#include "MissionTaskType.h" +#include "eMissionTaskType.h" +#include "eMissionState.h" #include "MissionComponent.h" #include "Character.h" @@ -361,16 +362,16 @@ void BaseSurvivalServer::GameOver(Entity* self) { // Update all mission progression auto* missionComponent = player->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, time, self->GetObjectID(), + missionComponent->Progress(eMissionTaskType::PERFORM_ACTIVITY, time, self->GetObjectID(), self->GetVar<std::string>(MissionTypeVariable)); for (const auto& survivalMission : missionsToUpdate) { auto* mission = missionComponent->GetMission(survivalMission.first); if (mission != nullptr && (uint32_t)time >= survivalMission.second - && (mission->GetMissionState() == MissionState::MISSION_STATE_ACTIVE - || mission->GetMissionState() == MissionState::MISSION_STATE_COMPLETE_ACTIVE)) { + && (mission->GetMissionState() == eMissionState::ACTIVE + || mission->GetMissionState() == eMissionState::COMPLETE_ACTIVE)) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + mission->Progress(eMissionTaskType::SCRIPT, self->GetLOT()); } } } diff --git a/dScripts/BaseWavesServer.cpp b/dScripts/BaseWavesServer.cpp index 8c32f984..ad40a77d 100644 --- a/dScripts/BaseWavesServer.cpp +++ b/dScripts/BaseWavesServer.cpp @@ -4,7 +4,8 @@ #include "EntityManager.h" #include "dZoneManager.h" #include "Player.h" -#include "MissionTaskType.h" +#include "eMissionTaskType.h" +#include "eMissionState.h" #include "MissionComponent.h" #include "Character.h" @@ -373,7 +374,7 @@ void BaseWavesServer::GameOver(Entity* self, bool won) { // Update all mission progression auto* missionComponent = player->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, time, self->GetObjectID(), self->GetVar<std::string>(MissionTypeVariable)); + missionComponent->Progress(eMissionTaskType::PERFORM_ACTIVITY, time, self->GetObjectID(), self->GetVar<std::string>(MissionTypeVariable)); } StopActivity(self, playerID, wave, time, score); @@ -510,15 +511,15 @@ bool BaseWavesServer::UpdateSpawnedEnemies(Entity* self, LWOOBJID enemyID, uint3 // Get the mission state auto missionState = missionComponent->GetMissionState(missionID); // For some reason these achievements are not accepted by default, so we accept them here if they arent already. - if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { + if (missionState != eMissionState::COMPLETE && missionState != eMissionState::UNKNOWN) { missionComponent->AcceptMission(missionID); missionState = missionComponent->GetMissionState(missionID); } - if (missionState != MissionState::MISSION_STATE_COMPLETE) { + if (missionState != eMissionState::COMPLETE) { auto mission = missionComponent->GetMission(missionID); if (mission != nullptr) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + mission->Progress(eMissionTaskType::SCRIPT, self->GetLOT()); } } } @@ -528,15 +529,15 @@ bool BaseWavesServer::UpdateSpawnedEnemies(Entity* self, LWOOBJID enemyID, uint3 // Get the mission state auto missionState = missionComponent->GetMissionState(missionID); // For some reason these achievements are not accepted by default, so we accept them here if they arent already. - if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { + if (missionState != eMissionState::COMPLETE && missionState != eMissionState::UNKNOWN) { missionComponent->AcceptMission(missionID); missionState = missionComponent->GetMissionState(missionID); } - if (missionState != MissionState::MISSION_STATE_COMPLETE) { + if (missionState != eMissionState::COMPLETE) { auto mission = missionComponent->GetMission(missionID); if (mission != nullptr) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + mission->Progress(eMissionTaskType::SCRIPT, self->GetLOT()); } } } @@ -564,14 +565,14 @@ void BaseWavesServer::UpdateMissionForAllPlayers(Entity* self, uint32_t missionI // Get the mission state auto missionState = missionComponent->GetMissionState(missionID); // For some reason these achievements are not accepted by default, so we accept them here if they arent already. - if (missionState != MissionState::MISSION_STATE_COMPLETE && missionState != MissionState::MISSION_STATE_UNKNOWN) { + if (missionState != eMissionState::COMPLETE && missionState != eMissionState::UNKNOWN) { missionComponent->AcceptMission(missionID); missionState = missionComponent->GetMissionState(missionID); } - if (missionState != MissionState::MISSION_STATE_COMPLETE) { + if (missionState != eMissionState::COMPLETE) { auto mission = missionComponent->GetMission(missionID); if (mission != nullptr) { - mission->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + mission->Progress(eMissionTaskType::SCRIPT, self->GetLOT()); } } } diff --git a/dScripts/CppScripts.h b/dScripts/CppScripts.h index eb9b7a04..21ff8427 100644 --- a/dScripts/CppScripts.h +++ b/dScripts/CppScripts.h @@ -7,7 +7,7 @@ class User; class Entity; class NiPoint3; -enum class MissionState : int32_t; +enum class eMissionState : int32_t; namespace CppScripts { /** @@ -49,7 +49,7 @@ namespace CppScripts { * * Equivalent to 'function onMissionDialogueOK(self, msg)' */ - virtual void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) {}; + virtual void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) {}; /** * Invoked when the client or the server invoked an event server-side. @@ -327,7 +327,7 @@ namespace CppScripts { /** * Used by items to tell their owner that they were equipped. - * + * * @param itemOwner The owner of the item * @param itemObjId The items Object ID */ @@ -335,7 +335,7 @@ namespace CppScripts { /** * Used by items to tell their owner that they were unequipped. - * + * * @param itemOwner The owner of the item * @param itemObjId The items Object ID */ diff --git a/dScripts/Darkitect.cpp b/dScripts/Darkitect.cpp index 323d0247..b4364332 100644 --- a/dScripts/Darkitect.cpp +++ b/dScripts/Darkitect.cpp @@ -4,6 +4,7 @@ #include "EntityManager.h" #include "GameMessages.h" #include "Character.h" +#include "eMissionState.h" void Darkitect::Reveal(Entity* self, Entity* player) { const auto playerID = player->GetObjectID(); @@ -24,7 +25,7 @@ void Darkitect::Reveal(Entity* self, Entity* player) { destroyableComponent->SetHealth(1); destroyableComponent->SetImagination(0); - if (missionComponent->GetMissionState(1295) == MissionState::MISSION_STATE_ACTIVE) { + if (missionComponent->GetMissionState(1295) == eMissionState::ACTIVE) { character->SetPlayerFlag(1911, true); } diff --git a/dScripts/NPCAddRemoveItem.cpp b/dScripts/NPCAddRemoveItem.cpp index 1985a02b..f1ef8c0d 100644 --- a/dScripts/NPCAddRemoveItem.cpp +++ b/dScripts/NPCAddRemoveItem.cpp @@ -1,8 +1,8 @@ #include "NPCAddRemoveItem.h" #include "InventoryComponent.h" -#include "MissionState.h" +#include "eMissionState.h" -void NPCAddRemoveItem::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void NPCAddRemoveItem::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { auto* inventory = target->GetComponent<InventoryComponent>(); if (inventory == nullptr) return; @@ -11,9 +11,9 @@ void NPCAddRemoveItem::OnMissionDialogueOK(Entity* self, Entity* target, int mis if (missionSetting.first == missionID) { for (const auto& itemSetting : missionSetting.second) { for (const auto& lot : itemSetting.items) { - if (itemSetting.add && (missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_COMPLETE_AVAILABLE)) { + if (itemSetting.add && (missionState == eMissionState::AVAILABLE || missionState == eMissionState::COMPLETE_AVAILABLE)) { inventory->AddItem(lot, 1, eLootSourceType::LOOT_SOURCE_NONE); - } else if (itemSetting.remove && (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE || missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE)) { + } else if (itemSetting.remove && (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE)) { inventory->RemoveItem(lot, 1); } } diff --git a/dScripts/NPCAddRemoveItem.h b/dScripts/NPCAddRemoveItem.h index a266f817..73a7f2c9 100644 --- a/dScripts/NPCAddRemoveItem.h +++ b/dScripts/NPCAddRemoveItem.h @@ -12,7 +12,7 @@ struct ItemSetting { */ class NPCAddRemoveItem : public CppScripts::Script { protected: - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; virtual std::map<uint32_t, std::vector<ItemSetting>> GetSettings(); private: void OnStartup(Entity* self) override; diff --git a/dScripts/NtFactionSpyServer.cpp b/dScripts/NtFactionSpyServer.cpp index ac068a32..684e6a0e 100644 --- a/dScripts/NtFactionSpyServer.cpp +++ b/dScripts/NtFactionSpyServer.cpp @@ -4,6 +4,7 @@ #include "InventoryComponent.h" #include "GameMessages.h" #include "MissionComponent.h" +#include "eMissionState.h" void NtFactionSpyServer::OnStartup(Entity* self) { SetVariables(self); @@ -54,7 +55,7 @@ bool NtFactionSpyServer::IsSpy(Entity* self, Entity* possibleSpy) { auto* character = possibleSpy->GetCharacter(); // A player is a spy if they have the spy mission, have the spy equipment equipped and don't have the spy flag set yet - return missionComponent != nullptr && missionComponent->GetMissionState(spyData.missionID) == MissionState::MISSION_STATE_ACTIVE + return missionComponent != nullptr && missionComponent->GetMissionState(spyData.missionID) == eMissionState::ACTIVE && inventoryComponent != nullptr && inventoryComponent->IsEquipped(spyData.itemID) && character != nullptr && !character->GetPlayerFlag(spyData.flagID); } diff --git a/dScripts/ai/AG/ActSharkPlayerDeathTrigger.cpp b/dScripts/ai/AG/ActSharkPlayerDeathTrigger.cpp index 420fc4d7..49fb6b87 100644 --- a/dScripts/ai/AG/ActSharkPlayerDeathTrigger.cpp +++ b/dScripts/ai/AG/ActSharkPlayerDeathTrigger.cpp @@ -1,6 +1,6 @@ #include "ActSharkPlayerDeathTrigger.h" #include "MissionComponent.h" -#include "MissionTaskType.h" +#include "eMissionTaskType.h" #include "Entity.h" void ActSharkPlayerDeathTrigger::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, @@ -9,7 +9,7 @@ void ActSharkPlayerDeathTrigger::OnFireEventServerSide(Entity* self, Entity* sen auto missionComponent = sender->GetComponent<MissionComponent>(); if (!missionComponent) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, 8419); + missionComponent->Progress(eMissionTaskType::SCRIPT, 8419); if (sender->GetIsDead() || !sender->GetPlayerReadyForUpdates()) return; //Don't kill already dead players or players not ready diff --git a/dScripts/ai/FV/FvFreeGfNinjas.cpp b/dScripts/ai/FV/FvFreeGfNinjas.cpp index 1751b6a7..d690a6f7 100644 --- a/dScripts/ai/FV/FvFreeGfNinjas.cpp +++ b/dScripts/ai/FV/FvFreeGfNinjas.cpp @@ -1,9 +1,10 @@ #include "FvFreeGfNinjas.h" #include "Character.h" #include "MissionComponent.h" +#include "eMissionState.h" -void FvFreeGfNinjas::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { - if (missionID == 705 && missionState == MissionState::MISSION_STATE_AVAILABLE) { +void FvFreeGfNinjas::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { + if (missionID == 705 && missionState == eMissionState::AVAILABLE) { auto* missionComponent = target->GetComponent<MissionComponent>(); if (missionComponent == nullptr) return; @@ -29,7 +30,7 @@ void FvFreeGfNinjas::OnUse(Entity* self, Entity* user) { if (missionComponent == nullptr) return; - if (missionComponent->GetMissionState(705) == MissionState::MISSION_STATE_ACTIVE) { + if (missionComponent->GetMissionState(705) == eMissionState::ACTIVE) { auto* character = user->GetCharacter(); if (character != nullptr) character->SetPlayerFlag(68, true); diff --git a/dScripts/ai/FV/FvFreeGfNinjas.h b/dScripts/ai/FV/FvFreeGfNinjas.h index c7e4876e..01b0b6bd 100644 --- a/dScripts/ai/FV/FvFreeGfNinjas.h +++ b/dScripts/ai/FV/FvFreeGfNinjas.h @@ -3,6 +3,6 @@ class FvFreeGfNinjas : public CppScripts::Script { public: - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; void OnUse(Entity* self, Entity* user) override; }; diff --git a/dScripts/ai/GENERAL/LegoDieRoll.cpp b/dScripts/ai/GENERAL/LegoDieRoll.cpp index e86550f9..89819271 100644 --- a/dScripts/ai/GENERAL/LegoDieRoll.cpp +++ b/dScripts/ai/GENERAL/LegoDieRoll.cpp @@ -2,6 +2,7 @@ #include "Entity.h" #include "GameMessages.h" #include "MissionComponent.h" +#include "eMissionState.h" void LegoDieRoll::OnStartup(Entity* self) { self->AddTimer("DoneRolling", 10.0f); @@ -39,7 +40,7 @@ void LegoDieRoll::OnTimerDone(Entity* self, std::string timerName) { if (missionComponent != nullptr) { const auto rollMissionState = missionComponent->GetMissionState(756); - if (rollMissionState == MissionState::MISSION_STATE_ACTIVE) { + if (rollMissionState == eMissionState::ACTIVE) { missionComponent->ForceProgress(756, 1103, 1); } } diff --git a/dScripts/ai/GF/GfJailkeepMission.cpp b/dScripts/ai/GF/GfJailkeepMission.cpp index eaa8c73d..b8d4cd30 100644 --- a/dScripts/ai/GF/GfJailkeepMission.cpp +++ b/dScripts/ai/GF/GfJailkeepMission.cpp @@ -1,18 +1,19 @@ #include "GfJailkeepMission.h" #include "MissionComponent.h" #include "Character.h" +#include "eMissionState.h" -void GfJailkeepMission::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void GfJailkeepMission::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { auto* missionComponent = target->GetComponent<MissionComponent>(); if (missionComponent == nullptr) return; - if (missionID == 385 && missionState == MissionState::MISSION_STATE_AVAILABLE) { + if (missionID == 385 && missionState == eMissionState::AVAILABLE) { missionComponent->AcceptMission(386, true); missionComponent->AcceptMission(387, true); missionComponent->AcceptMission(388, true); missionComponent->AcceptMission(390, true); - } else if (missionID == 385 && missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + } else if (missionID == 385 && missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { auto* character = target->GetCharacter(); if (character != nullptr && character->GetPlayerFlag(68)) { missionComponent->AcceptMission(701); @@ -28,7 +29,7 @@ void GfJailkeepMission::OnUse(Entity* self, Entity* user) { if (missionComponent == nullptr) return; - if (missionComponent->GetMissionState(385) == MissionState::MISSION_STATE_ACTIVE) { + if (missionComponent->GetMissionState(385) == eMissionState::ACTIVE) { missionComponent->AcceptMission(386, true); missionComponent->AcceptMission(387, true); missionComponent->AcceptMission(388, true); diff --git a/dScripts/ai/GF/GfJailkeepMission.h b/dScripts/ai/GF/GfJailkeepMission.h index a120d29b..651a6e1b 100644 --- a/dScripts/ai/GF/GfJailkeepMission.h +++ b/dScripts/ai/GF/GfJailkeepMission.h @@ -5,5 +5,5 @@ class GfJailkeepMission final : public CppScripts::Script { public: void OnUse(Entity* self, Entity* user) override; - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; }; diff --git a/dScripts/ai/GF/PetDigBuild.cpp b/dScripts/ai/GF/PetDigBuild.cpp index 32e5b2e3..2c3da9fc 100644 --- a/dScripts/ai/GF/PetDigBuild.cpp +++ b/dScripts/ai/GF/PetDigBuild.cpp @@ -2,6 +2,7 @@ #include "EntityManager.h" #include "EntityInfo.h" #include "MissionComponent.h" +#include "eMissionState.h" void PetDigBuild::OnRebuildComplete(Entity* self, Entity* target) { auto flagNumber = self->GetVar<std::u16string>(u"flagNum"); @@ -22,7 +23,7 @@ void PetDigBuild::OnRebuildComplete(Entity* self, Entity* target) { info.settings.push_back(new LDFData<std::u16string>(u"groupID", u"Flag" + flagNumber)); } else { auto* missionComponent = target->GetComponent<MissionComponent>(); - if (missionComponent != nullptr && missionComponent->GetMissionState(746) == MissionState::MISSION_STATE_ACTIVE) { + if (missionComponent != nullptr && missionComponent->GetMissionState(746) == eMissionState::ACTIVE) { info.lot = 9307; // Special Captain Jack treasure that drops a mission item } else { info.lot = 3495; // Normal AG treasure diff --git a/dScripts/ai/GF/PirateRep.cpp b/dScripts/ai/GF/PirateRep.cpp index 81d69672..ccfa7af6 100644 --- a/dScripts/ai/GF/PirateRep.cpp +++ b/dScripts/ai/GF/PirateRep.cpp @@ -1,10 +1,10 @@ #include "PirateRep.h" #include "Character.h" -#include "MissionState.h" +#include "eMissionState.h" #include "Entity.h" -void PirateRep::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { - if (missionID == m_PirateRepMissionID && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { +void PirateRep::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { + if (missionID == m_PirateRepMissionID && missionState >= eMissionState::READY_TO_COMPLETE) { auto* character = target->GetCharacter(); if (character) { character->SetPlayerFlag(ePlayerFlags::GF_PIRATE_REP, true); diff --git a/dScripts/ai/GF/PirateRep.h b/dScripts/ai/GF/PirateRep.h index 8fc82c5e..754971be 100644 --- a/dScripts/ai/GF/PirateRep.h +++ b/dScripts/ai/GF/PirateRep.h @@ -3,7 +3,7 @@ class PirateRep : public CppScripts::Script { public: - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; private: const int m_PirateRepMissionID = 301; }; diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp index f9146ec4..2948ae3d 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp @@ -13,6 +13,7 @@ #include "MissionComponent.h" #include "Loot.h" #include "InventoryComponent.h" +#include "eMissionTaskType.h" void SGCannon::OnStartup(Entity* self) { Game::logger->Log("SGCannon", "OnStartup"); @@ -554,9 +555,9 @@ void SGCannon::StopGame(Entity* self, bool cancel) { auto* missionComponent = player->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar<uint32_t>(TotalScoreVariable), self->GetObjectID(), "performact_score"); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_MINIGAME, self->GetVar<uint32_t>(MaxStreakVariable), self->GetObjectID(), "performact_streak"); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_ACTIVITY, m_CannonLot, 0, "", self->GetVar<uint32_t>(TotalScoreVariable)); + missionComponent->Progress(eMissionTaskType::PERFORM_ACTIVITY, self->GetVar<uint32_t>(TotalScoreVariable), self->GetObjectID(), "performact_score"); + missionComponent->Progress(eMissionTaskType::PERFORM_ACTIVITY, self->GetVar<uint32_t>(MaxStreakVariable), self->GetObjectID(), "performact_streak"); + missionComponent->Progress(eMissionTaskType::ACTIVITY, m_CannonLot, 0, "", self->GetVar<uint32_t>(TotalScoreVariable)); } LootGenerator::Instance().GiveActivityLoot(player, self, GetGameID(self), self->GetVar<uint32_t>(TotalScoreVariable)); @@ -666,7 +667,7 @@ void SGCannon::RegisterHit(Entity* self, Entity* target, const std::string& time auto missionComponent = player->GetComponent<MissionComponent>(); if (missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_SMASH, spawnInfo.lot, self->GetObjectID()); + missionComponent->Progress(eMissionTaskType::SMASH, spawnInfo.lot, self->GetObjectID()); } void SGCannon::UpdateStreak(Entity* self) { diff --git a/dScripts/ai/NP/NpcNpSpacemanBob.cpp b/dScripts/ai/NP/NpcNpSpacemanBob.cpp index 5157e488..d242d08f 100644 --- a/dScripts/ai/NP/NpcNpSpacemanBob.cpp +++ b/dScripts/ai/NP/NpcNpSpacemanBob.cpp @@ -1,9 +1,10 @@ #include "NpcNpSpacemanBob.h" #include "DestroyableComponent.h" #include "MissionComponent.h" +#include "eMissionState.h" -void NpcNpSpacemanBob::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { - if (missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE && missionID == 173) { +void NpcNpSpacemanBob::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { + if (missionState == eMissionState::READY_TO_COMPLETE && missionID == 173) { DestroyableComponent* destroyable = static_cast<DestroyableComponent*>(target->GetComponent(COMPONENT_TYPE_DESTROYABLE)); destroyable->SetImagination(6); MissionComponent* mission = static_cast<MissionComponent*>(target->GetComponent(COMPONENT_TYPE_MISSION)); diff --git a/dScripts/ai/NP/NpcNpSpacemanBob.h b/dScripts/ai/NP/NpcNpSpacemanBob.h index 08cc850d..84c59deb 100644 --- a/dScripts/ai/NP/NpcNpSpacemanBob.h +++ b/dScripts/ai/NP/NpcNpSpacemanBob.h @@ -4,6 +4,6 @@ class NpcNpSpacemanBob : public CppScripts::Script { public: - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState); + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState); }; diff --git a/dScripts/ai/NS/NsConcertInstrument.cpp b/dScripts/ai/NS/NsConcertInstrument.cpp index bba3986d..c7478a05 100644 --- a/dScripts/ai/NS/NsConcertInstrument.cpp +++ b/dScripts/ai/NS/NsConcertInstrument.cpp @@ -7,6 +7,8 @@ #include "SoundTriggerComponent.h" #include "InventoryComponent.h" #include "MissionComponent.h" +#include "eMissionState.h" +#include "eMissionTaskType.h" // Constants are at the bottom @@ -146,8 +148,8 @@ void NsConcertInstrument::StopPlayingInstrument(Entity* self, Entity* player) { // Player might be null if they left if (player != nullptr) { auto* missions = player->GetComponent<MissionComponent>(); - if (missions != nullptr && missions->GetMissionState(176) == MissionState::MISSION_STATE_ACTIVE) { - missions->Progress(MissionTaskType::MISSION_TASK_TYPE_SCRIPT, self->GetLOT()); + if (missions != nullptr && missions->GetMissionState(176) == eMissionState::ACTIVE) { + missions->Progress(eMissionTaskType::SCRIPT, self->GetLOT()); } GameMessages::SendEndCinematic(player->GetObjectID(), cinematics.at(instrumentLot), UNASSIGNED_SYSTEM_ADDRESS, 1.0f); diff --git a/dScripts/ai/NS/NsJohnnyMissionServer.cpp b/dScripts/ai/NS/NsJohnnyMissionServer.cpp index 2d9ae93c..107d3c44 100644 --- a/dScripts/ai/NS/NsJohnnyMissionServer.cpp +++ b/dScripts/ai/NS/NsJohnnyMissionServer.cpp @@ -1,8 +1,9 @@ #include "NsJohnnyMissionServer.h" #include "MissionComponent.h" +#include "eMissionState.h" -void NsJohnnyMissionServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { - if (missionID == 773 && missionState <= MissionState::MISSION_STATE_ACTIVE) { +void NsJohnnyMissionServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { + if (missionID == 773 && missionState <= eMissionState::ACTIVE) { auto* missionComponent = target->GetComponent<MissionComponent>(); if (missionComponent != nullptr) { missionComponent->AcceptMission(774); diff --git a/dScripts/ai/NS/NsJohnnyMissionServer.h b/dScripts/ai/NS/NsJohnnyMissionServer.h index 8de39afa..c37ea06c 100644 --- a/dScripts/ai/NS/NsJohnnyMissionServer.h +++ b/dScripts/ai/NS/NsJohnnyMissionServer.h @@ -2,5 +2,5 @@ #include "CppScripts.h" class NsJohnnyMissionServer : public CppScripts::Script { - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; }; diff --git a/dScripts/ai/NS/NsModularBuild.cpp b/dScripts/ai/NS/NsModularBuild.cpp index 065d061e..2e00aa19 100644 --- a/dScripts/ai/NS/NsModularBuild.cpp +++ b/dScripts/ai/NS/NsModularBuild.cpp @@ -1,11 +1,12 @@ #include "NsModularBuild.h" #include "MissionComponent.h" +#include "eMissionState.h" void NsModularBuild::OnModularBuildExit(Entity* self, Entity* player, bool bCompleted, std::vector<LOT> modules) { if (bCompleted) { MissionComponent* mission = static_cast<MissionComponent*>(player->GetComponent(COMPONENT_TYPE_MISSION)); - if (mission->GetMissionState(m_MissionNum) == MissionState::MISSION_STATE_ACTIVE) { + if (mission->GetMissionState(m_MissionNum) == eMissionState::ACTIVE) { for (LOT mod : modules) { if (mod == 9516 || mod == 9517 || mod == 9518) { mission->ForceProgress(m_MissionNum, 1178, 1); diff --git a/dScripts/ai/PROPERTY/AG/AgPropGuard.cpp b/dScripts/ai/PROPERTY/AG/AgPropGuard.cpp index 51f76a27..853da92d 100644 --- a/dScripts/ai/PROPERTY/AG/AgPropGuard.cpp +++ b/dScripts/ai/PROPERTY/AG/AgPropGuard.cpp @@ -5,18 +5,19 @@ #include "InventoryComponent.h" #include "MissionComponent.h" #include "Item.h" +#include "eMissionState.h" -void AgPropGuard::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void AgPropGuard::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { auto* character = target->GetCharacter(); auto* missionComponent = target->GetComponent<MissionComponent>(); auto* inventoryComponent = target->GetComponent<InventoryComponent>(); const auto state = missionComponent->GetMissionState(320); - if (missionID == 768 && missionState == MissionState::MISSION_STATE_AVAILABLE) { + if (missionID == 768 && missionState == eMissionState::AVAILABLE) { if (!character->GetPlayerFlag(71)) { // TODO: Cinematic "MissionCam" } - } else if (missionID == 768 && missionState >= MissionState::MISSION_STATE_READY_TO_COMPLETE) { + } else if (missionID == 768 && missionState >= eMissionState::READY_TO_COMPLETE) { //remove the inventory items for (int item : gearSets) { auto* id = inventoryComponent->FindItemByLot(item); @@ -27,8 +28,8 @@ void AgPropGuard::OnMissionDialogueOK(Entity* self, Entity* target, int missionI } } } else if ( - (missionID == 320 && state == MissionState::MISSION_STATE_AVAILABLE) /*|| - (state == MissionState::MISSION_STATE_COMPLETE && missionID == 891 && missionState == MissionState::MISSION_STATE_READY_TO_COMPLETE)*/ + (missionID == 320 && state == eMissionState::AVAILABLE) /*|| + (state == eMissionState::COMPLETE && missionID == 891 && missionState == eMissionState::READY_TO_COMPLETE)*/ ) { //GameMessages::SendNotifyClientObject(EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(), u"GuardChat", target->GetObjectID(), 0, target->GetObjectID(), "", target->GetSystemAddress()); diff --git a/dScripts/ai/PROPERTY/AG/AgPropGuard.h b/dScripts/ai/PROPERTY/AG/AgPropGuard.h index f68573dd..2b41f006 100644 --- a/dScripts/ai/PROPERTY/AG/AgPropGuard.h +++ b/dScripts/ai/PROPERTY/AG/AgPropGuard.h @@ -4,7 +4,7 @@ class AgPropGuard final : public CppScripts::Script { public: - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; private: std::vector<int> gearSets = { 14359,14321,14353,14315 }; diff --git a/dScripts/ai/PROPERTY/AgPropguards.cpp b/dScripts/ai/PROPERTY/AgPropguards.cpp index 2bcfcf94..9fc6010a 100644 --- a/dScripts/ai/PROPERTY/AgPropguards.cpp +++ b/dScripts/ai/PROPERTY/AgPropguards.cpp @@ -3,9 +3,9 @@ #include "GameMessages.h" #include "EntityManager.h" #include "dZoneManager.h" -#include "MissionState.h" +#include "eMissionState.h" -void AgPropguards::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) { +void AgPropguards::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { auto* character = target->GetCharacter(); if (character == nullptr) return; @@ -14,11 +14,11 @@ void AgPropguards::OnMissionDialogueOK(Entity* self, Entity* target, int mission if (flag == 0) return; - if ((missionState == MissionState::MISSION_STATE_AVAILABLE || missionState == MissionState::MISSION_STATE_ACTIVE) + if ((missionState == eMissionState::AVAILABLE || missionState == eMissionState::ACTIVE) && !character->GetPlayerFlag(flag)) { // If the player just started the mission, play a cinematic highlighting the target GameMessages::SendPlayCinematic(target->GetObjectID(), u"MissionCam", target->GetSystemAddress()); - } else if (missionState == MissionState::MISSION_STATE_COMPLETE_READY_TO_COMPLETE) { + } else if (missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { // Makes the guard disappear once the mission has been completed const auto zoneControlID = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); GameMessages::SendNotifyClientObject(zoneControlID, u"GuardChat", 0, 0, self->GetObjectID(), diff --git a/dScripts/ai/PROPERTY/AgPropguards.h b/dScripts/ai/PROPERTY/AgPropguards.h index 511b7b6a..25701f86 100644 --- a/dScripts/ai/PROPERTY/AgPropguards.h +++ b/dScripts/ai/PROPERTY/AgPropguards.h @@ -2,7 +2,7 @@ #include "CppScripts.h" class AgPropguards : public CppScripts::Script { - void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, MissionState missionState) override; + void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; private: static uint32_t GetFlagForMission(uint32_t missionID); }; diff --git a/dScripts/ai/RACING/OBJECTS/FvRaceSmashEggImagineServer.cpp b/dScripts/ai/RACING/OBJECTS/FvRaceSmashEggImagineServer.cpp index 32dbf619..f69a3eb6 100644 --- a/dScripts/ai/RACING/OBJECTS/FvRaceSmashEggImagineServer.cpp +++ b/dScripts/ai/RACING/OBJECTS/FvRaceSmashEggImagineServer.cpp @@ -3,8 +3,9 @@ #include "DestroyableComponent.h" #include "EntityManager.h" #include "PossessableComponent.h" -#include "RacingTaskParam.h" +#include "eRacingTaskParam.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" void FvRaceSmashEggImagineServer::OnDie(Entity* self, Entity* killer) { if (killer != nullptr) { @@ -29,8 +30,8 @@ void FvRaceSmashEggImagineServer::OnDie(Entity* self, Entity* killer) { } if (missionComponent == nullptr) return; // Dragon eggs have their own smash server so we handle mission progression for them here. - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASH_SPECIFIC_SMASHABLE); + missionComponent->Progress(eMissionTaskType::RACING, 0, (LWOOBJID)eRacingTaskParam::SMASHABLES); + missionComponent->Progress(eMissionTaskType::RACING, self->GetLOT(), (LWOOBJID)eRacingTaskParam::SMASH_SPECIFIC_SMASHABLE); } } diff --git a/dScripts/ai/RACING/OBJECTS/RaceImagineCrateServer.cpp b/dScripts/ai/RACING/OBJECTS/RaceImagineCrateServer.cpp index a35007b4..6a29f9a8 100644 --- a/dScripts/ai/RACING/OBJECTS/RaceImagineCrateServer.cpp +++ b/dScripts/ai/RACING/OBJECTS/RaceImagineCrateServer.cpp @@ -3,9 +3,10 @@ #include "EntityManager.h" #include "PossessableComponent.h" #include "RaceImagineCrateServer.h" -#include "RacingTaskParam.h" +#include "eRacingTaskParam.h" #include "MissionComponent.h" #include "SkillComponent.h" +#include "eMissionTaskType.h" void RaceImagineCrateServer::OnDie(Entity* self, Entity* killer) { if (self->GetVar<bool>(u"bIsDead")) { @@ -49,7 +50,7 @@ void RaceImagineCrateServer::OnDie(Entity* self, Entity* killer) { // Progress racing smashable missions if (missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); + missionComponent->Progress(eMissionTaskType::RACING, 0, (LWOOBJID)eRacingTaskParam::SMASHABLES); } } } diff --git a/dScripts/ai/RACING/OBJECTS/RaceImaginePowerup.cpp b/dScripts/ai/RACING/OBJECTS/RaceImaginePowerup.cpp index 9bdd0813..92a50873 100644 --- a/dScripts/ai/RACING/OBJECTS/RaceImaginePowerup.cpp +++ b/dScripts/ai/RACING/OBJECTS/RaceImaginePowerup.cpp @@ -2,8 +2,9 @@ #include "EntityManager.h" #include "PossessorComponent.h" #include "RaceImaginePowerup.h" -#include "RacingTaskParam.h" +#include "eRacingTaskParam.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" void RaceImaginePowerup::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { @@ -31,6 +32,6 @@ void RaceImaginePowerup::OnFireEventServerSide(Entity* self, Entity* sender, std auto* missionComponent = sender->GetComponent<MissionComponent>(); if (missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_COLLECT_IMAGINATION); + missionComponent->Progress(eMissionTaskType::RACING, self->GetLOT(), (LWOOBJID)eRacingTaskParam::COLLECT_IMAGINATION); } } diff --git a/dScripts/ai/RACING/OBJECTS/RaceSmashServer.cpp b/dScripts/ai/RACING/OBJECTS/RaceSmashServer.cpp index d0dc3d78..295f38ee 100644 --- a/dScripts/ai/RACING/OBJECTS/RaceSmashServer.cpp +++ b/dScripts/ai/RACING/OBJECTS/RaceSmashServer.cpp @@ -2,8 +2,9 @@ #include "EntityManager.h" #include "PossessableComponent.h" #include "RaceSmashServer.h" -#include "RacingTaskParam.h" +#include "eRacingTaskParam.h" #include "MissionComponent.h" +#include "eMissionTaskType.h" void RaceSmashServer::OnDie(Entity* self, Entity* killer) { // Crate is smashed by the car @@ -22,9 +23,9 @@ void RaceSmashServer::OnDie(Entity* self, Entity* killer) { // Progress racing smashable missions if (missionComponent == nullptr) return; - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, 0, (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASHABLES); + missionComponent->Progress(eMissionTaskType::RACING, 0, (LWOOBJID)eRacingTaskParam::SMASHABLES); // Progress missions that ask us to smash a specific smashable. - missionComponent->Progress(MissionTaskType::MISSION_TASK_TYPE_RACING, self->GetLOT(), (LWOOBJID)RacingTaskParam::RACING_TASK_PARAM_SMASH_SPECIFIC_SMASHABLE); + missionComponent->Progress(eMissionTaskType::RACING, self->GetLOT(), (LWOOBJID)eRacingTaskParam::SMASH_SPECIFIC_SMASHABLE); } } } From bff14fd391307f69187bb4478f14bf7de94516bf Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Sun, 22 Jan 2023 17:39:38 -0600 Subject: [PATCH 245/322] add blame ignore --- .git-blame-ignore-revs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 37567a02..14e48fbe 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -6,3 +6,6 @@ # convert to unix line endings 72477e01e2711e0f61cdb192ee266e5e21b8846f + +# enum cleanup +faf42d2f8cf432df2993b031f079b0b8c6d7dbe7 From 90d184ba93537597411eb5849eb918caf5becc0e Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Tue, 24 Jan 2023 22:36:30 +0000 Subject: [PATCH 246/322] Remove Clang Tidy configurations. (#969) --- .clang-format | 37 ------------------------------------- .clang-tidy | 17 ----------------- 2 files changed, 54 deletions(-) delete mode 100644 .clang-format delete mode 100644 .clang-tidy diff --git a/.clang-format b/.clang-format deleted file mode 100644 index 5af12d3a..00000000 --- a/.clang-format +++ /dev/null @@ -1,37 +0,0 @@ ---- -BraceWrapping: - AfterCaseLabel: false - AfterClass: false - AfterControlStatement: false - AfterEnum: false - AfterFunction: false - AfterNamespace: false - AfterObjCDeclaration: false - AfterStruct: false - AfterUnion: false - AfterExternBlock: false - BeforeCatch: false - BeforeElse: false - IndentBraces: false - SplitEmptyFunction: false - SplitEmptyRecord: false - SplitEmptyNamespace: false - BeforeLambdaBody: false - BeforeWhile: false -BreakBeforeBraces: Attach -ColumnLimit: 0 -IndentWidth: 4 -IndentCaseLabels: true -IncludeBlocks: Regroup -IncludeCategories: - - Regex: '<[[:alnum:].]+\.h>' - Priority: 1 - - Regex: '<[[:alnum:].]+>' - Priority: 2 - - Regex: '.*/.*' - Priority: 3 - - Regex: '.*' - Priority: 4 -DerivePointerAlignment: false -PointerAlignment: Left -... diff --git a/.clang-tidy b/.clang-tidy deleted file mode 100644 index ea50801d..00000000 --- a/.clang-tidy +++ /dev/null @@ -1,17 +0,0 @@ -Checks: '-*,readability-*,performance-*,modernize-*,-modernize-use-trailing-return-type,bugprone-*' -WarningsAsErrors: true -HeaderFilterRegex: '' -FormatStyle: none -CheckOptions: - - key: readability-identifier-naming.ClassCase - value: CamelCase - - key: readability-identifier-naming.ClassMethodCase - value: CamelCase - - key: readability-identifier-naming.ClassMemberPrefix - value: m_ - - key: readability-identifier-naming.ClassMemberCase - value: CamelCase - - key: readability-identifier-naming.ClassConstantCase - value: UPPER_CASE - - key: readability-identifier-naming.FunctionCase - value: CamelCase \ No newline at end of file From cdffd5ff30772c2223c05a92ee04b31aa4867b37 Mon Sep 17 00:00:00 2001 From: "Gie \"Max\" Vanommeslaeghe" <gievanom@hotmail.com> Date: Wed, 25 Jan 2023 00:09:32 +0100 Subject: [PATCH 247/322] Fix: 968 bug using lookup command with no parameters crashes instance (#970) * Update SlashCommandHandler.cpp * Update SlashCommandHandler.cpp --- dGame/dUtilities/SlashCommandHandler.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 1bd3f6f3..d8be44c6 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -1199,7 +1199,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit EntityManager::Instance()->SerializeEntity(entity); } - if (chatCommand == "lookup" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "lookup" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { auto query = CDClientDatabase::CreatePreppedStmt( "SELECT `id`, `name` FROM `Objects` WHERE `displayName` LIKE ?1 OR `name` LIKE ?1 OR `description` LIKE ?1 LIMIT 50"); // Concatenate all of the arguments into a single query so a multi word query can be used properly. From 6aa69de4fd4cb29144c71687024873571960938a Mon Sep 17 00:00:00 2001 From: Jett <55758076+Jettford@users.noreply.github.com> Date: Thu, 26 Jan 2023 00:21:12 +0000 Subject: [PATCH 248/322] Resolution of accidental shifting of eItemType enum (#976) --- dCommon/dEnums/eItemType.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dCommon/dEnums/eItemType.h b/dCommon/dEnums/eItemType.h index 69eb18e9..41c7765b 100644 --- a/dCommon/dEnums/eItemType.h +++ b/dCommon/dEnums/eItemType.h @@ -7,7 +7,7 @@ enum class eItemType : int32_t { UNKNOWN = -1, - BRICK, + BRICK = 1, HAT, HAIR, NECK, From d17f51183ea2f063e60505694a09f7ae8d47d8f1 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 26 Jan 2023 18:41:40 -0800 Subject: [PATCH 249/322] Allow landing animation in Return to the Venture Explorer (#977) --- dGame/dComponents/CharacterComponent.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index ecd5e7b2..98540bd0 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -43,7 +43,6 @@ bool CharacterComponent::LandingAnimDisabled(int zoneID) { switch (zoneID) { case 0: case 556: - case 1001: case 1101: case 1202: case 1203: From 91c0c1fcfb682ff68ded75d71b5b211e4e630b75 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 10 Feb 2023 02:29:53 -0600 Subject: [PATCH 250/322] Split out LUTriggers into it's own component (#986) * Split out LUTriggers into it's own component * some cleanup * fix debug log * use emplace and tryParse * slight refactor to make the work on startup rather than at runtime Also TODO's for getting targets via all the possible methods * address feedback --- dCommon/dEnums/dCommonVars.h | 1 + dCommon/dEnums/eTriggerCommandType.h | 119 +++++++++++++++ dCommon/dEnums/eTriggerEventType.h | 53 +++++++ dGame/Entity.cpp | 137 +++-------------- dGame/Entity.h | 11 +- dGame/EntityManager.cpp | 3 +- dGame/dComponents/CMakeLists.txt | 1 + dGame/dComponents/SwitchComponent.cpp | 5 +- dGame/dComponents/TriggerComponent.cpp | 187 +++++++++++++++++++++++ dGame/dComponents/TriggerComponent.h | 34 +++++ dGame/dUtilities/SlashCommandHandler.cpp | 9 +- dZoneManager/LUTriggers.h | 7 +- dZoneManager/Zone.cpp | 7 +- 13 files changed, 437 insertions(+), 137 deletions(-) create mode 100644 dCommon/dEnums/eTriggerCommandType.h create mode 100644 dCommon/dEnums/eTriggerEventType.h create mode 100644 dGame/dComponents/TriggerComponent.cpp create mode 100644 dGame/dComponents/TriggerComponent.h diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index 9bf824e0..c90fd8e6 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -414,6 +414,7 @@ enum eReplicaComponentType : int32_t { COMPONENT_TYPE_MODULE_ASSEMBLY = 61, //!< The ModuleAssembly Component COMPONENT_TYPE_PROPERTY_VENDOR = 65, //!< The PropertyVendor Component COMPONENT_TYPE_ROCKET_LAUNCH = 67, //!< The RocketLaunch Component + COMPONENT_TYPE_TRIGGER = 69, COMPONENT_TYPE_RACING_CONTROL = 71, //!< The RacingControl Component COMPONENT_TYPE_MISSION_OFFER = 73, //!< The MissionOffer Component COMPONENT_TYPE_EXHIBIT = 75, //!< The Exhibit Component diff --git a/dCommon/dEnums/eTriggerCommandType.h b/dCommon/dEnums/eTriggerCommandType.h new file mode 100644 index 00000000..fadfafb8 --- /dev/null +++ b/dCommon/dEnums/eTriggerCommandType.h @@ -0,0 +1,119 @@ +#ifndef __ETRIGGERCOMMANDTYPE__H__ +#define __ETRIGGERCOMMANDTYPE__H__ + +// For info about Trigger Command see: +// https://docs.lu-dev.net/en/latest/file-structures/lutriggers.html?highlight=trigger#possible-values-commands + +enum class eTriggerCommandType { + INVALID, + ZONE_PLAYER, + FIRE_EVENT, + DESTROY_OBJ, + TOGGLE_TRIGGER, + RESET_REBUILD, + SET_PATH, + SET_PICK_TYPE, + MOVE_OBJECT, + ROTATE_OBJECT, + PUSH_OBJECT, + REPEL_OBJECT, + SET_TIMER, + CANCEL_TIMER, + PLAY_CINEMATIC, + TOGGLE_BBB, + UPDATE_MISSION, + SET_BOUNCER_STATE, + BOUNCE_ALL_ON_BOUNCER, + TURN_AROUND_ON_PATH, + GO_FORWARD_ON_PATH, + GO_BACKWARD_ON_PATH, + STOP_PATHING, + START_PATHING, + LOCK_OR_UNLOCK_CONTROLS, + PLAY_EFFECT, + STOP_EFFECT, + ACTIVATE_MUSIC_CUE, + DEACTIVATE_MUSIC_CUE, + FLASH_MUSIC_CUE, + SET_MUSIC_PARAMETER, + PLAY_2D_AMBIENT_SOUND, + STOP_2D_AMBIENT_SOUND, + PLAY_3D_AMBIENT_SOUND, + STOP_3D_AMBIENT_SOUND, + ACTIVATE_MIXER_PROGRAM, + DEACTIVATE_MIXER_PROGRAM, + CAST_SKILL, + DISPLAY_ZONE_SUMMARY, + SET_PHYSICS_VOLUME_EFFECT, + SET_PHYSICS_VOLUME_STATUS, + SET_MODEL_TO_BUILD, + SPAWN_MODEL_BRICKS, + ACTIVATE_SPAWNER_NETWORK, + DEACTIVATE_SPAWNER_NETWORK, + RESET_SPAWNER_NETWORK, + DESTROY_SPAWNER_NETWORK_OBJECTS, + GO_TO_WAYPOINT, + ACTIVATE_PHYSICS +}; + + +class TriggerCommandType { +public: + static eTriggerCommandType StringToTriggerCommandType(std::string commandString) { + const std::map<std::string, eTriggerCommandType> TriggerCommandMap = { + { "zonePlayer", eTriggerCommandType::ZONE_PLAYER}, + { "fireEvent", eTriggerCommandType::FIRE_EVENT}, + { "destroyObj", eTriggerCommandType::DESTROY_OBJ}, + { "toggleTrigger", eTriggerCommandType::TOGGLE_TRIGGER}, + { "resetRebuild", eTriggerCommandType::RESET_REBUILD}, + { "setPath", eTriggerCommandType::SET_PATH}, + { "setPickType", eTriggerCommandType::SET_PICK_TYPE}, + { "moveObject", eTriggerCommandType::MOVE_OBJECT}, + { "rotateObject", eTriggerCommandType::ROTATE_OBJECT}, + { "pushObject", eTriggerCommandType::PUSH_OBJECT}, + { "repelObject", eTriggerCommandType::REPEL_OBJECT}, + { "setTimer", eTriggerCommandType::SET_TIMER}, + { "cancelTimer", eTriggerCommandType::CANCEL_TIMER}, + { "playCinematic", eTriggerCommandType::PLAY_CINEMATIC}, + { "toggleBBB", eTriggerCommandType::TOGGLE_BBB}, + { "updateMission", eTriggerCommandType::UPDATE_MISSION}, + { "setBouncerState", eTriggerCommandType::SET_BOUNCER_STATE}, + { "bounceAllOnBouncer", eTriggerCommandType::BOUNCE_ALL_ON_BOUNCER}, + { "turnAroundOnPath", eTriggerCommandType::TURN_AROUND_ON_PATH}, + { "goForwardOnPath", eTriggerCommandType::GO_FORWARD_ON_PATH}, + { "goBackwardOnPath", eTriggerCommandType::GO_BACKWARD_ON_PATH}, + { "stopPathing", eTriggerCommandType::STOP_PATHING}, + { "startPathing", eTriggerCommandType::START_PATHING}, + { "LockOrUnlockControls", eTriggerCommandType::LOCK_OR_UNLOCK_CONTROLS}, + { "PlayEffect", eTriggerCommandType::PLAY_EFFECT}, + { "StopEffect", eTriggerCommandType::STOP_EFFECT}, + { "activateMusicCue", eTriggerCommandType::ACTIVATE_MUSIC_CUE}, + { "deactivateMusicCue", eTriggerCommandType::DEACTIVATE_MUSIC_CUE}, + { "flashMusicCue", eTriggerCommandType::FLASH_MUSIC_CUE}, + { "setMusicParameter", eTriggerCommandType::SET_MUSIC_PARAMETER}, + { "play2DAmbientSound", eTriggerCommandType::PLAY_2D_AMBIENT_SOUND}, + { "stop2DAmbientSound", eTriggerCommandType::STOP_2D_AMBIENT_SOUND}, + { "play3DAmbientSound", eTriggerCommandType::PLAY_3D_AMBIENT_SOUND}, + { "stop3DAmbientSound", eTriggerCommandType::STOP_3D_AMBIENT_SOUND}, + { "activateMixerProgram", eTriggerCommandType::ACTIVATE_MIXER_PROGRAM}, + { "deactivateMixerProgram", eTriggerCommandType::DEACTIVATE_MIXER_PROGRAM}, + { "CastSkill", eTriggerCommandType::CAST_SKILL}, + { "displayZoneSummary", eTriggerCommandType::DISPLAY_ZONE_SUMMARY}, + { "SetPhysicsVolumeEffect", eTriggerCommandType::SET_PHYSICS_VOLUME_EFFECT}, + { "SetPhysicsVolumeStatus", eTriggerCommandType::SET_PHYSICS_VOLUME_STATUS}, + { "setModelToBuild", eTriggerCommandType::SET_MODEL_TO_BUILD}, + { "spawnModelBricks", eTriggerCommandType::SPAWN_MODEL_BRICKS}, + { "ActivateSpawnerNetwork", eTriggerCommandType::ACTIVATE_SPAWNER_NETWORK}, + { "DeactivateSpawnerNetwork", eTriggerCommandType::DEACTIVATE_SPAWNER_NETWORK}, + { "ResetSpawnerNetwork", eTriggerCommandType::RESET_SPAWNER_NETWORK}, + { "DestroySpawnerNetworkObjects", eTriggerCommandType::DESTROY_SPAWNER_NETWORK_OBJECTS}, + { "Go_To_Waypoint", eTriggerCommandType::GO_TO_WAYPOINT}, + { "ActivatePhysics", eTriggerCommandType::ACTIVATE_PHYSICS} + }; + + auto intermed = TriggerCommandMap.find(commandString); + return (intermed != TriggerCommandMap.end()) ? intermed->second : eTriggerCommandType::INVALID; + }; +}; + +#endif //!__ETRIGGERCOMMANDTYPE__H__ diff --git a/dCommon/dEnums/eTriggerEventType.h b/dCommon/dEnums/eTriggerEventType.h new file mode 100644 index 00000000..1705ce22 --- /dev/null +++ b/dCommon/dEnums/eTriggerEventType.h @@ -0,0 +1,53 @@ +#ifndef __ETRIGGEREVENTTYPE__H__ +#define __ETRIGGEREVENTTYPE__H__ + +enum class eTriggerEventType { + INVALID, + DESTROY, + CUSTOM_EVENT, + ENTER, + EXIT, + CREATE, + HIT, + TIMER_DONE, + REBUILD_COMPLETE, + ACTIVATED, + DEACTIVATED, + ARRIVED, + ARRIVED_AT_END_OF_PATH, + ZONE_SUMMARY_DISMISSED, + ARRIVED_AT_DESIRED_WAYPOINT, + PET_ON_SWITCH, + PET_OFF_SWITCH, + INTERACT +}; + +class TriggerEventType { +public: + static eTriggerEventType StringToTriggerEventType(std::string commandString) { + const std::map<std::string, eTriggerEventType> TriggerEventMap = { + {"OnDestroy", eTriggerEventType::DESTROY}, + {"OnCustomEvent", eTriggerEventType::CUSTOM_EVENT}, + {"OnEnter", eTriggerEventType::ENTER}, + {"OnExit", eTriggerEventType::EXIT}, + {"OnCreate", eTriggerEventType::CREATE}, + {"OnHit", eTriggerEventType::HIT}, + {"OnTimerDone", eTriggerEventType::TIMER_DONE}, + {"OnRebuildComplete", eTriggerEventType::REBUILD_COMPLETE}, + {"OnActivated", eTriggerEventType::ACTIVATED}, + {"OnDeactivated", eTriggerEventType::DEACTIVATED}, + {"OnArrived", eTriggerEventType::ARRIVED}, + {"OnArrivedAtEndOfPath", eTriggerEventType::ARRIVED_AT_END_OF_PATH}, + {"OnZoneSummaryDismissed", eTriggerEventType::ZONE_SUMMARY_DISMISSED}, + {"OnArrivedAtDesiredWaypoint", eTriggerEventType::ARRIVED_AT_DESIRED_WAYPOINT}, + {"OnPetOnSwitch", eTriggerEventType::PET_ON_SWITCH}, + {"OnPetOffSwitch", eTriggerEventType::PET_OFF_SWITCH}, + {"OnInteract", eTriggerEventType::INTERACT}, + }; + + auto intermed = TriggerEventMap.find(commandString); + return (intermed != TriggerEventMap.end()) ? intermed->second : eTriggerEventType::INVALID; + }; +}; + +#endif //!__ETRIGGEREVENTTYPE__H__ diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index eefa5107..94693385 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -23,6 +23,7 @@ #include "EntityCallbackTimer.h" #include "Loot.h" #include "eMissionTaskType.h" +#include "eTriggerEventType.h" //Component includes: #include "Component.h" @@ -68,6 +69,7 @@ #include "ShootingGalleryComponent.h" #include "RailActivatorComponent.h" #include "LUPExhibitComponent.h" +#include "TriggerComponent.h" Entity::Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity) { m_ObjectID = objectID; @@ -76,7 +78,6 @@ Entity::Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity) m_Character = nullptr; m_GMLevel = 0; m_CollectibleID = 0; - m_Trigger = nullptr; //new LUTriggers::Trigger(); m_NetworkID = 0; m_Groups = {}; m_OwnerOverride = LWOOBJID_EMPTY; @@ -132,30 +133,9 @@ void Entity::Initialize() { * Setup trigger */ - const auto triggerName = GetVarAsString(u"trigger_id"); + const auto triggerInfo = GetVarAsString(u"trigger_id"); - if (!triggerName.empty()) { - std::stringstream ss(triggerName); - std::vector<std::string> tokens; - std::string token; - while (std::getline(ss, token, ':')) { - tokens.push_back(token); - } - - uint32_t sceneID = std::stoi(tokens[0]); - uint32_t triggerID = std::stoi(tokens[1]); - - if (m_Trigger != nullptr) { - delete m_Trigger; - m_Trigger = nullptr; - } - - m_Trigger = dZoneManager::Instance()->GetZone()->GetTrigger(sceneID, triggerID); - - if (m_Trigger == nullptr) { - m_Trigger = new LUTriggers::Trigger(); - } - } + if (!triggerInfo.empty()) m_Components.emplace(COMPONENT_TYPE_TRIGGER, new TriggerComponent(this, triggerInfo)); /** * Setup groups @@ -769,7 +749,7 @@ void Entity::Initialize() { no_ghosting: - TriggerEvent("OnCreate"); + TriggerEvent(eTriggerEventType::CREATE); if (m_Character) { auto* controllablePhysicsComponent = GetComponent<ControllablePhysicsComponent>(); @@ -946,12 +926,16 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke outBitStream->Write0(); //No ldf data } - if (m_Trigger != nullptr && m_Trigger->events.size() > 0) { - outBitStream->Write1(); - } else { + TriggerComponent* triggerComponent; + if (TryGetComponent(COMPONENT_TYPE_TRIGGER, triggerComponent)) { + // has trigger component, check to see if we have events to handle + auto* trigger = triggerComponent->GetTrigger(); + outBitStream->Write<bool>(trigger && trigger->events.size() > 0); + } else { // no trigger componenet, so definitely no triggers outBitStream->Write0(); } + if (m_ParentEntity != nullptr || m_SpawnerID != 0) { outBitStream->Write1(); if (m_ParentEntity != nullptr) outBitStream->Write(GeneralUtils::SetBit(m_ParentEntity->GetObjectID(), OBJECT_BIT_CLIENT)); @@ -1310,7 +1294,7 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) { switchComp->EntityEnter(other); } - TriggerEvent("OnEnter", other); + TriggerEvent(eTriggerEventType::ENTER, other); // POI system const auto& poi = GetVar<std::u16string>(u"POI"); @@ -1344,7 +1328,7 @@ void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) { auto* other = EntityManager::Instance()->GetEntity(otherEntity); if (!other) return; - TriggerEvent("OnLeave", other); + TriggerEvent(eTriggerEventType::EXIT, other); SwitchComponent* switchComp = GetComponent<SwitchComponent>(); if (switchComp) { @@ -1392,7 +1376,7 @@ void Entity::OnEmoteReceived(const int32_t emote, Entity* target) { } void Entity::OnUse(Entity* originator) { - TriggerEvent("OnInteract"); + TriggerEvent(eTriggerEventType::INTERACT); for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnUse(this, originator); @@ -1736,94 +1720,9 @@ bool Entity::IsPlayer() const { return m_TemplateID == 1 && GetSystemAddress() != UNASSIGNED_SYSTEM_ADDRESS; } -void Entity::TriggerEvent(std::string eventID, Entity* optionalTarget) { - if (m_Trigger != nullptr && m_Trigger->enabled) { - for (LUTriggers::Event* triggerEvent : m_Trigger->events) { - if (triggerEvent->eventID == eventID) { - for (LUTriggers::Command* cmd : triggerEvent->commands) { - HandleTriggerCommand(cmd->id, cmd->target, cmd->targetName, cmd->args, optionalTarget); - } - } - } - } -} - -// This should probably get it's own triggers class at some point... -void Entity::HandleTriggerCommand(std::string id, std::string target, std::string targetName, std::string args, Entity* optionalTarget) { - std::vector<std::string> argArray; - // Parse args - std::stringstream ssData(args); - std::string token; - char deliminator = ','; - - while (std::getline(ssData, token, deliminator)) { - std::string lowerToken; - for (char character : token) { - lowerToken.push_back(std::tolower(character)); // make lowercase to ensure it works - } - argArray.push_back(lowerToken); - } - - std::vector<Entity*> targetEntities; - if (target == "self") targetEntities.push_back(this); - if (target == "objGroup") targetEntities = EntityManager::Instance()->GetEntitiesInGroup(targetName); - if (optionalTarget) targetEntities.push_back(optionalTarget); - if (targetEntities.size() == 0) return; - for (Entity* targetEntity : targetEntities) { - if (!targetEntity) continue; - - if (id == "SetPhysicsVolumeEffect") { - PhantomPhysicsComponent* phanPhys = GetComponent<PhantomPhysicsComponent>(); - if (!phanPhys) return; - - phanPhys->SetPhysicsEffectActive(true); - uint32_t effectType = 0; - if (argArray[0] == "push") effectType = 0; - else if (argArray[0] == "attract") effectType = 1; - else if (argArray[0] == "repulse") effectType = 2; - else if (argArray[0] == "gravity") effectType = 3; - else if (argArray[0] == "friction") effectType = 4; - - phanPhys->SetEffectType(effectType); - phanPhys->SetDirectionalMultiplier(std::stof(argArray[1])); - if (argArray.size() > 4) { - NiPoint3 direction = NiPoint3::ZERO; - GeneralUtils::TryParse<float>(argArray[2], direction.x); - GeneralUtils::TryParse<float>(argArray[3], direction.y); - GeneralUtils::TryParse<float>(argArray[4], direction.z); - phanPhys->SetDirection(direction); - } - if (argArray.size() > 5) { - phanPhys->SetMin(std::stoi(argArray[6])); - phanPhys->SetMax(std::stoi(argArray[7])); - } - - if (target == "self") { - EntityManager::Instance()->ConstructEntity(this); - } - } else if (id == "updateMission") { - CDMissionTasksTable* missionTasksTable = CDClientManager::Instance()->GetTable<CDMissionTasksTable>("MissionTasks"); - std::vector<CDMissionTasks> missionTasks = missionTasksTable->Query([=](CDMissionTasks entry) { - std::string lowerTargetGroup; - for (char character : entry.targetGroup) { - lowerTargetGroup.push_back(std::tolower(character)); // make lowercase to ensure it works - } - - return (lowerTargetGroup == argArray[4]); - }); - - for (const CDMissionTasks& task : missionTasks) { - MissionComponent* missionComponent = targetEntity->GetComponent<MissionComponent>(); - if (!missionComponent) continue; - - missionComponent->ForceProgress(task.id, task.uid, std::stoi(argArray[2])); - } - } else if (id == "fireEvent") { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(targetEntity)) { - script->OnFireEventServerSide(targetEntity, this, args, 0, 0, 0); - } - } - } +void Entity::TriggerEvent(eTriggerEventType event, Entity* optionalTarget) { + auto* triggerComponent = GetComponent<TriggerComponent>(); + if (triggerComponent) triggerComponent->TriggerEvent(event, optionalTarget); } Entity* Entity::GetOwner() const { diff --git a/dGame/Entity.h b/dGame/Entity.h index 248018c0..0bde01e2 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -18,9 +18,6 @@ namespace Loot { namespace tinyxml2 { class XMLDocument; }; -namespace LUTriggers { - struct Trigger; -}; class Player; class EntityInfo; @@ -33,6 +30,7 @@ class Component; class Item; class Character; class EntityCallbackTimer; +enum class eTriggerEventType; namespace CppScripts { class Script; @@ -67,8 +65,6 @@ public: Entity* GetParentEntity() const { return m_ParentEntity; } - LUTriggers::Trigger* GetTrigger() const { return m_Trigger; } - std::vector<std::string>& GetGroups() { return m_Groups; }; Spawner* GetSpawner() const { return m_Spawner; } @@ -221,9 +217,8 @@ public: void RegisterCoinDrop(uint64_t count); void ScheduleKillAfterUpdate(Entity* murderer = nullptr); - void TriggerEvent(std::string eveneventtID, Entity* optionalTarget = nullptr); + void TriggerEvent(eTriggerEventType event, Entity* optionalTarget = nullptr); void ScheduleDestructionAfterUpdate() { m_ShouldDestroyAfterUpdate = true; } - void HandleTriggerCommand(std::string id, std::string target, std::string targetName, std::string args, Entity* optionalTarget); virtual NiPoint3 GetRespawnPosition() const { return NiPoint3::ZERO; } virtual NiQuaternion GetRespawnRotation() const { return NiQuaternion::IDENTITY; } @@ -308,8 +303,6 @@ protected: bool m_HasSpawnerNodeID; uint32_t m_SpawnerNodeID; - LUTriggers::Trigger* m_Trigger; - Character* m_Character; Entity* m_ParentEntity; //For spawners and the like diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index 22c31291..dae27af6 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -19,6 +19,7 @@ #include "dLogger.h" #include "MessageIdentifiers.h" #include "dConfig.h" +#include "eTriggerEventType.h" EntityManager* EntityManager::m_Address = nullptr; @@ -585,7 +586,7 @@ void EntityManager::ScheduleForKill(Entity* entity) { SwitchComponent* switchComp = entity->GetComponent<SwitchComponent>(); if (switchComp) { - entity->TriggerEvent("OnDectivated"); + entity->TriggerEvent(eTriggerEventType::DEACTIVATED); } const auto objectId = entity->GetObjectID(); diff --git a/dGame/dComponents/CMakeLists.txt b/dGame/dComponents/CMakeLists.txt index 0995428b..b396829a 100644 --- a/dGame/dComponents/CMakeLists.txt +++ b/dGame/dComponents/CMakeLists.txt @@ -38,5 +38,6 @@ set(DGAME_DCOMPONENTS_SOURCES "BaseCombatAIComponent.cpp" "SkillComponent.cpp" "SoundTriggerComponent.cpp" "SwitchComponent.cpp" + "TriggerComponent.cpp" "VehiclePhysicsComponent.cpp" "VendorComponent.cpp" PARENT_SCOPE) diff --git a/dGame/dComponents/SwitchComponent.cpp b/dGame/dComponents/SwitchComponent.cpp index 2263a866..dbdf37a9 100644 --- a/dGame/dComponents/SwitchComponent.cpp +++ b/dGame/dComponents/SwitchComponent.cpp @@ -1,5 +1,6 @@ #include "SwitchComponent.h" #include "EntityManager.h" +#include "eTriggerEventType.h" std::vector<SwitchComponent*> SwitchComponent::petSwitches; @@ -42,7 +43,7 @@ void SwitchComponent::EntityEnter(Entity* entity) { } m_Active = true; if (!m_Parent) return; - m_Parent->TriggerEvent("OnActivated"); + m_Parent->TriggerEvent(eTriggerEventType::ACTIVATED); const auto grpName = m_Parent->GetVarAsString(u"grp_name"); @@ -78,7 +79,7 @@ void SwitchComponent::Update(float deltaTime) { if (m_Timer <= 0.0f) { m_Active = false; if (!m_Parent) return; - m_Parent->TriggerEvent("OnDectivated"); + m_Parent->TriggerEvent(eTriggerEventType::DEACTIVATED); const auto grpName = m_Parent->GetVarAsString(u"grp_name"); diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp new file mode 100644 index 00000000..4ed95a15 --- /dev/null +++ b/dGame/dComponents/TriggerComponent.cpp @@ -0,0 +1,187 @@ +#include "TriggerComponent.h" +#include "dZoneManager.h" +#include "LUTriggers.h" +#include "eTriggerCommandType.h" +#include "MissionComponent.h" +#include "PhantomPhysicsComponent.h" +#include "CDMissionTasksTable.h" + +TriggerComponent::TriggerComponent(Entity* parent, const std::string triggerInfo): Component(parent) { + m_Parent = parent; + m_Trigger = nullptr; + + std::vector<std::string> tokens = GeneralUtils::SplitString(triggerInfo, ':'); + + uint32_t sceneID; + GeneralUtils::TryParse<uint32_t>(tokens.at(0), sceneID); + uint32_t triggerID; + GeneralUtils::TryParse<uint32_t>(tokens.at(1), triggerID); + + m_Trigger = dZoneManager::Instance()->GetZone()->GetTrigger(sceneID, triggerID); + + if (!m_Trigger) m_Trigger = new LUTriggers::Trigger(); +} + +void TriggerComponent::TriggerEvent(eTriggerEventType event, Entity* optionalTarget) { + if (m_Trigger && m_Trigger->enabled) { + for (LUTriggers::Event* triggerEvent : m_Trigger->events) { + if (triggerEvent->id == event) { + for (LUTriggers::Command* command : triggerEvent->commands) { + HandleTriggerCommand(command, optionalTarget); + } + } + } + } +} + +void TriggerComponent::HandleTriggerCommand(LUTriggers::Command* command, Entity* optionalTarget) { + auto argArray = GeneralUtils::SplitString(command->args, ','); + + // determine targets + std::vector<Entity*> targetEntities = GatherTargets(command, optionalTarget); + + // if we have no targets, then we are done + if (targetEntities.empty()) return; + + for (Entity* targetEntity : targetEntities) { + if (!targetEntity) continue; + + switch (command->id) { + case eTriggerCommandType::ZONE_PLAYER: break; + case eTriggerCommandType::FIRE_EVENT: + HandleFireEvent(targetEntity, command->args); + break; + case eTriggerCommandType::DESTROY_OBJ: break; + case eTriggerCommandType::TOGGLE_TRIGGER: break; + case eTriggerCommandType::RESET_REBUILD: break; + case eTriggerCommandType::SET_PATH: break; + case eTriggerCommandType::SET_PICK_TYPE: break; + case eTriggerCommandType::MOVE_OBJECT: break; + case eTriggerCommandType::ROTATE_OBJECT: break; + case eTriggerCommandType::PUSH_OBJECT: break; + case eTriggerCommandType::REPEL_OBJECT: break; + case eTriggerCommandType::SET_TIMER: break; + case eTriggerCommandType::CANCEL_TIMER: break; + case eTriggerCommandType::PLAY_CINEMATIC: break; + case eTriggerCommandType::TOGGLE_BBB: break; + case eTriggerCommandType::UPDATE_MISSION: + HandleUpdateMission(targetEntity, argArray); + break; + case eTriggerCommandType::SET_BOUNCER_STATE: break; + case eTriggerCommandType::BOUNCE_ALL_ON_BOUNCER: break; + case eTriggerCommandType::TURN_AROUND_ON_PATH: break; + case eTriggerCommandType::GO_FORWARD_ON_PATH: break; + case eTriggerCommandType::GO_BACKWARD_ON_PATH: break; + case eTriggerCommandType::STOP_PATHING: break; + case eTriggerCommandType::START_PATHING: break; + case eTriggerCommandType::LOCK_OR_UNLOCK_CONTROLS: break; + case eTriggerCommandType::PLAY_EFFECT: break; + case eTriggerCommandType::STOP_EFFECT: break; + case eTriggerCommandType::ACTIVATE_MUSIC_CUE: break; + case eTriggerCommandType::DEACTIVATE_MUSIC_CUE: break; + case eTriggerCommandType::FLASH_MUSIC_CUE: break; + case eTriggerCommandType::SET_MUSIC_PARAMETER: break; + case eTriggerCommandType::PLAY_2D_AMBIENT_SOUND: break; + case eTriggerCommandType::STOP_2D_AMBIENT_SOUND: break; + case eTriggerCommandType::PLAY_3D_AMBIENT_SOUND: break; + case eTriggerCommandType::STOP_3D_AMBIENT_SOUND: break; + case eTriggerCommandType::ACTIVATE_MIXER_PROGRAM: break; + case eTriggerCommandType::DEACTIVATE_MIXER_PROGRAM: break; + case eTriggerCommandType::CAST_SKILL: break; + case eTriggerCommandType::DISPLAY_ZONE_SUMMARY: break; + case eTriggerCommandType::SET_PHYSICS_VOLUME_EFFECT: + HandleSetPhysicsVolume(targetEntity, argArray, command->target); + break; + case eTriggerCommandType::SET_PHYSICS_VOLUME_STATUS: break; + case eTriggerCommandType::SET_MODEL_TO_BUILD: break; + case eTriggerCommandType::SPAWN_MODEL_BRICKS: break; + case eTriggerCommandType::ACTIVATE_SPAWNER_NETWORK: break; + case eTriggerCommandType::DEACTIVATE_SPAWNER_NETWORK: break; + case eTriggerCommandType::RESET_SPAWNER_NETWORK: break; + case eTriggerCommandType::DESTROY_SPAWNER_NETWORK_OBJECTS: break; + case eTriggerCommandType::GO_TO_WAYPOINT: break; + case eTriggerCommandType::ACTIVATE_PHYSICS: break; + default: + Game::logger->LogDebug("TriggerComponent", "Event %i was not handled!", command->id); + break; + } + } +} + +std::vector<Entity*> TriggerComponent::GatherTargets(LUTriggers::Command* command, Entity* optionalTarget) { + std::vector<Entity*> entities = {}; + + if (command->target == "self") entities.push_back(m_Parent); + else if (command->target == "zone") { /*TODO*/ } + else if (command->target == "target") { /*TODO*/ } + else if (command->target == "targetTeam") { /*TODO*/ } + else if (command->target == "objGroup") entities = EntityManager::Instance()->GetEntitiesInGroup(command->targetName); + else if (command->target == "allPlayers") { /*TODO*/ } + else if (command->target == "allNPCs") { /*TODO*/ } + + if (optionalTarget) entities.push_back(optionalTarget); + + return entities; +} + +void TriggerComponent::HandleSetPhysicsVolume(Entity* targetEntity, std::vector<std::string> argArray, std::string target) { + PhantomPhysicsComponent* phanPhys = m_Parent->GetComponent<PhantomPhysicsComponent>(); + if (!phanPhys) return; + + phanPhys->SetPhysicsEffectActive(true); + uint32_t effectType = 0; + std::transform(argArray.at(0).begin(), argArray.at(0).end(), argArray.at(0).begin(), ::tolower); //Transform to lowercase + if (argArray.at(0) == "push") effectType = 0; + else if (argArray.at(0) == "attract") effectType = 1; + else if (argArray.at(0) == "repulse") effectType = 2; + else if (argArray.at(0) == "gravity") effectType = 3; + else if (argArray.at(0) == "friction") effectType = 4; + + phanPhys->SetEffectType(effectType); + phanPhys->SetDirectionalMultiplier(std::stof(argArray.at(1))); + if (argArray.size() > 4) { + NiPoint3 direction = NiPoint3::ZERO; + GeneralUtils::TryParse<float>(argArray.at(2), direction.x); + GeneralUtils::TryParse<float>(argArray.at(3), direction.y); + GeneralUtils::TryParse<float>(argArray.at(4), direction.z); + phanPhys->SetDirection(direction); + } + if (argArray.size() > 5) { + uint32_t min; + GeneralUtils::TryParse<uint32_t>(argArray.at(6), min); + phanPhys->SetMin(min); + + uint32_t max; + GeneralUtils::TryParse<uint32_t>(argArray.at(7), max); + phanPhys->SetMax(max); + } + + // TODO: why is this contruct and not serialize? + if (target == "self") EntityManager::Instance()->ConstructEntity(m_Parent); +} + +void TriggerComponent::HandleUpdateMission(Entity* targetEntity, std::vector<std::string> argArray) { + CDMissionTasksTable* missionTasksTable = CDClientManager::Instance()->GetTable<CDMissionTasksTable>("MissionTasks"); + std::vector<CDMissionTasks> missionTasks = missionTasksTable->Query([=](CDMissionTasks entry) { + std::string lowerTargetGroup; + for (char character : entry.targetGroup) { + lowerTargetGroup.push_back(std::tolower(character)); // make lowercase to ensure it works + } + + return (lowerTargetGroup == argArray[4]); + }); + + for (const CDMissionTasks& task : missionTasks) { + MissionComponent* missionComponent = targetEntity->GetComponent<MissionComponent>(); + if (!missionComponent) continue; + + missionComponent->ForceProgress(task.id, task.uid, std::stoi(argArray[2])); + } +} + +void TriggerComponent::HandleFireEvent(Entity* targetEntity, std::string args) { + for (CppScripts::Script* script : CppScripts::GetEntityScripts(targetEntity)) { + script->OnFireEventServerSide(targetEntity, m_Parent, args, 0, 0, 0); + } +} + diff --git a/dGame/dComponents/TriggerComponent.h b/dGame/dComponents/TriggerComponent.h new file mode 100644 index 00000000..d7711696 --- /dev/null +++ b/dGame/dComponents/TriggerComponent.h @@ -0,0 +1,34 @@ +#ifndef __TRIGGERCOMPONENT__H__ +#define __TRIGGERCOMPONENT__H__ + +#include "Component.h" + +namespace LUTriggers { + struct Trigger; + struct Command; +}; + +class TriggerComponent : public Component { +public: + static const uint32_t ComponentType = COMPONENT_TYPE_TRIGGER; + + explicit TriggerComponent(Entity* parent, const std::string triggerInfo); + + void TriggerEvent(eTriggerEventType event, Entity* optionalTarget = nullptr); + LUTriggers::Trigger* GetTrigger() const { return m_Trigger; } + +private: + + void HandleTriggerCommand(LUTriggers::Command* command, Entity* optionalTarget); + std::vector<std::string> ParseArgs(std::string args); + std::vector<Entity*> GatherTargets(LUTriggers::Command* command, Entity* optionalTarget); + + // Trigger Event Handlers + void HandleSetPhysicsVolume(Entity* targetEntity, std::vector<std::string> argArray, std::string target); + void HandleUpdateMission(Entity* targetEntity, std::vector<std::string> argArray); + void HandleFireEvent(Entity* targetEntity, std::string args); + void HandleCastSkill(Entity* targetEntity, uint32_t skillID); + + LUTriggers::Trigger* m_Trigger; +}; +#endif //!__TRIGGERCOMPONENT__H__ diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index d8be44c6..e558e19c 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -73,6 +73,7 @@ #include "MovingPlatformComponent.h" #include "dMessageIdentifiers.h" #include "eMissionState.h" +#include "TriggerComponent.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { std::string chatCommand; @@ -1984,8 +1985,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Active: " + (GeneralUtils::to_u16string(phantomPhysicsComponent->GetPhysicsEffectActive()))); } - if (closest->GetTrigger() != nullptr) { - ChatPackets::SendSystemMessage(sysAddr, u"Trigger: " + (GeneralUtils::to_u16string(closest->GetTrigger()->id))); + auto* triggerComponent = closest->GetComponent<TriggerComponent>(); + if (triggerComponent){ + auto trigger = triggerComponent->GetTrigger(); + if (trigger) { + ChatPackets::SendSystemMessage(sysAddr, u"Trigger: " + (GeneralUtils::to_u16string(trigger->id))); + } } } } diff --git a/dZoneManager/LUTriggers.h b/dZoneManager/LUTriggers.h index 1869b4c3..a93cd67d 100644 --- a/dZoneManager/LUTriggers.h +++ b/dZoneManager/LUTriggers.h @@ -6,17 +6,20 @@ class Command; class Event; +enum class eTriggerCommandType; +enum class eTriggerEventType; + namespace LUTriggers { struct Command { - std::string id; + eTriggerCommandType id; std::string target; std::string targetName; std::string args; }; struct Event { - std::string eventID; + eTriggerEventType id; std::vector<Command*> commands; }; diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 79d940af..c32f8447 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -14,6 +14,9 @@ #include "Spawner.h" #include "dZoneManager.h" +#include "eTriggerCommandType.h" +#include "eTriggerEventType.h" + Zone::Zone(const LWOMAPID& mapID, const LWOINSTANCEID& instanceID, const LWOCLONEID& cloneID) : m_ZoneID(mapID, instanceID, cloneID) { m_NumberOfScenesLoaded = 0; @@ -296,11 +299,11 @@ std::vector<LUTriggers::Trigger*> Zone::LoadLUTriggers(std::string triggerFile, auto currentEvent = currentTrigger->FirstChildElement("event"); while (currentEvent) { LUTriggers::Event* newEvent = new LUTriggers::Event(); - newEvent->eventID = currentEvent->Attribute("id"); + newEvent->id = TriggerEventType::StringToTriggerEventType(currentEvent->Attribute("id")); auto currentCommand = currentEvent->FirstChildElement("command"); while (currentCommand) { LUTriggers::Command* newCommand = new LUTriggers::Command(); - newCommand->id = currentCommand->Attribute("id"); + newCommand->id = TriggerCommandType::StringToTriggerCommandType(currentCommand->Attribute("id")); newCommand->target = currentCommand->Attribute("target"); if (currentCommand->Attribute("targetName") != NULL) { newCommand->targetName = currentCommand->Attribute("targetName"); From 3cd0d1ec3df09b1cc741cd333760dd94a11c276b Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 10 Feb 2023 02:30:17 -0600 Subject: [PATCH 251/322] Make wrapper for casting skills (#987) * Make wrapper for casting skills this is to reduce magic numbers in the code base Only updated one use of this to demo that this works. Will be do more in a sepearate PR. Also, inadvertantly fix damage stacking and self-damage in the teslapack * add skill<->behavior caching * explicit by reference * address emo's feedback --- dGame/dComponents/SkillComponent.cpp | 26 +++++++++++++++++++ dGame/dComponents/SkillComponent.h | 14 ++++++++++ .../EquipmentTriggers/CoilBackpackBase.cpp | 4 +-- dScripts/EquipmentTriggers/CoilBackpackBase.h | 4 +-- dScripts/EquipmentTriggers/GemPack.h | 3 +-- dScripts/EquipmentTriggers/ShardArmor.h | 3 +-- dScripts/EquipmentTriggers/TeslaPack.h | 3 +-- 7 files changed, 46 insertions(+), 11 deletions(-) diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index 562c284a..2391dc3b 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -22,10 +22,13 @@ #include "EchoStartSkill.h" #include "dMessageIdentifiers.h" #include "DoClientProjectileImpact.h" +#include "CDClientManager.h" ProjectileSyncEntry::ProjectileSyncEntry() { } +std::unordered_map<uint32_t, uint32_t> SkillComponent::m_skillBehaviorCache = {}; + bool SkillComponent::CastPlayerSkill(const uint32_t behaviorId, const uint32_t skillUid, RakNet::BitStream* bitStream, const LWOOBJID target, uint32_t skillID) { auto* context = new BehaviorContext(this->m_Parent->GetObjectID()); @@ -210,6 +213,29 @@ void SkillComponent::RegisterCalculatedProjectile(const LWOOBJID projectileId, B this->m_managedProjectiles.push_back(entry); } +bool SkillComponent::CastSkill(const uint32_t skillId, LWOOBJID target, const LWOOBJID optionalOriginatorID){ + uint32_t behaviorId = -1; + // try to find it via the cache + const auto& pair = m_skillBehaviorCache.find(skillId); + + // if it's not in the cache look it up and cache it + if (pair == m_skillBehaviorCache.end()) { + auto skillTable = CDClientManager::Instance()->GetTable<CDSkillBehaviorTable>("SkillBehavior"); + behaviorId = skillTable->GetSkillByID(skillId).behaviorID; + m_skillBehaviorCache.insert_or_assign(skillId, behaviorId); + } else { + behaviorId = pair->second; + } + + // check to see if we got back a valid behavior + if (behaviorId == -1) { + Game::logger->LogDebug("SkillComponent", "Tried to cast skill %i but found no behavior", skillId); + return false; + } + + return CalculateBehavior(skillId, behaviorId, target, false, false, optionalOriginatorID).success; +} + SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, const uint32_t behaviorId, const LWOOBJID target, const bool ignoreTarget, const bool clientInitalized, const LWOOBJID originatorOverride) { auto* bitStream = new RakNet::BitStream(); diff --git a/dGame/dComponents/SkillComponent.h b/dGame/dComponents/SkillComponent.h index f43276f1..2bdcb88f 100644 --- a/dGame/dComponents/SkillComponent.h +++ b/dGame/dComponents/SkillComponent.h @@ -119,6 +119,15 @@ public: */ void RegisterPlayerProjectile(LWOOBJID projectileId, BehaviorContext* context, const BehaviorBranchContext& branch, LOT lot); + /** + * Wrapper for CalculateBehavior that mimics the call structure in scripts and helps reduce magic numbers + * @param skillId the skill to cast + * @param target the target of the skill + * @param optionalOriginatorID change the originator of the skill + * @return if the case succeeded + */ + bool CastSkill(const uint32_t skillId, LWOOBJID target = LWOOBJID_EMPTY, const LWOOBJID optionalOriginatorID = LWOOBJID_EMPTY); + /** * Initializes a server-side skill calculation. * @param skillId the skill ID @@ -190,6 +199,11 @@ private: */ uint32_t m_skillUid; + /** + * Cache for looking up a behavior id via a skill ID + */ + static std::unordered_map<uint32_t, uint32_t> m_skillBehaviorCache; + /** * Sync a server-side projectile calculation. * @param entry the projectile information diff --git a/dScripts/EquipmentTriggers/CoilBackpackBase.cpp b/dScripts/EquipmentTriggers/CoilBackpackBase.cpp index d3102e0e..4e323a08 100644 --- a/dScripts/EquipmentTriggers/CoilBackpackBase.cpp +++ b/dScripts/EquipmentTriggers/CoilBackpackBase.cpp @@ -14,10 +14,10 @@ void CoilBackpackBase::NotifyHitOrHealResult(Entity* self, Entity* attacker, int if (self->GetVar<uint8_t>(u"coilCount") > 4) { auto* skillComponent = self->GetComponent<SkillComponent>(); if (!skillComponent) return; - skillComponent->CalculateBehavior(m_SkillId, m_BehaviorId, self->GetObjectID()); + skillComponent->CastSkill(m_SkillId); self->SetVar<uint8_t>(u"coilCount", 0); } - } + } } void CoilBackpackBase::OnFactionTriggerItemUnequipped(Entity* itemOwner, LWOOBJID itemObjId) { diff --git a/dScripts/EquipmentTriggers/CoilBackpackBase.h b/dScripts/EquipmentTriggers/CoilBackpackBase.h index 290c6c0f..2d641346 100644 --- a/dScripts/EquipmentTriggers/CoilBackpackBase.h +++ b/dScripts/EquipmentTriggers/CoilBackpackBase.h @@ -5,9 +5,8 @@ class CoilBackpackBase: public CppScripts::Script { public: - CoilBackpackBase(uint32_t skillId, uint32_t behaviorId) { + CoilBackpackBase(uint32_t skillId) { m_SkillId = skillId; - m_BehaviorId = behaviorId; }; void OnFactionTriggerItemEquipped(Entity* itemOwner, LWOOBJID itemObjId) override; @@ -15,7 +14,6 @@ public: void OnFactionTriggerItemUnequipped(Entity* itemOwner, LWOOBJID itemObjId) override; private: uint32_t m_SkillId = 0; - uint32_t m_BehaviorId = 0; }; #endif //!__GemPackBase__H__ diff --git a/dScripts/EquipmentTriggers/GemPack.h b/dScripts/EquipmentTriggers/GemPack.h index 13bf7b0b..d71181ab 100644 --- a/dScripts/EquipmentTriggers/GemPack.h +++ b/dScripts/EquipmentTriggers/GemPack.h @@ -5,10 +5,9 @@ class GemPack : public CoilBackpackBase { public: - GemPack() : CoilBackpackBase(skillId, behaviorId) {}; + GemPack() : CoilBackpackBase(skillId) {}; private: static const uint32_t skillId = 1488; - static const uint32_t behaviorId = 36779; }; #endif //!__GEMPACK__H__ diff --git a/dScripts/EquipmentTriggers/ShardArmor.h b/dScripts/EquipmentTriggers/ShardArmor.h index 01d2fe33..5486db54 100644 --- a/dScripts/EquipmentTriggers/ShardArmor.h +++ b/dScripts/EquipmentTriggers/ShardArmor.h @@ -5,10 +5,9 @@ class ShardArmor : public CoilBackpackBase { public: - ShardArmor() : CoilBackpackBase(skillId, behaviorId) {}; + ShardArmor() : CoilBackpackBase(skillId) {}; private: static const uint32_t skillId = 1249; - static const uint32_t behaviorId = 29086; }; #endif //!__SHARDARMOR__H__ diff --git a/dScripts/EquipmentTriggers/TeslaPack.h b/dScripts/EquipmentTriggers/TeslaPack.h index 6e8bc9a4..3ba09f5c 100644 --- a/dScripts/EquipmentTriggers/TeslaPack.h +++ b/dScripts/EquipmentTriggers/TeslaPack.h @@ -5,10 +5,9 @@ class TeslaPack : public CoilBackpackBase { public: - TeslaPack() : CoilBackpackBase(skillId, behaviorId) {}; + TeslaPack() : CoilBackpackBase(skillId) {}; private: static const uint32_t skillId = 1001; - static const uint32_t behaviorId = 20917; }; #endif //!__TESLAPACK__H__ From 72c93c8913957062eead0005fa0c15f3b6249650 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 13 Feb 2023 18:55:44 -0800 Subject: [PATCH 252/322] Further implement Property Behavior parsing (#936) Further implements the ControlBehavior processing and adds preparations for cheat detection --- CMakeLists.txt | 1 + dCommon/dEnums/dCommonVars.h | 3 +- dGame/dGameMessages/GameMessages.cpp | 2 +- dGame/dPropertyBehaviors/BehaviorStates.h | 5 +- dGame/dPropertyBehaviors/BlockDefinition.cpp | 9 + dGame/dPropertyBehaviors/BlockDefinition.h | 25 + dGame/dPropertyBehaviors/CMakeLists.txt | 10 +- .../AddActionMessage.cpp | 39 ++ .../AddActionMessage.h | 30 + .../ControlBehaviorMessages/AddMessage.cpp | 13 + .../ControlBehaviorMessages/AddMessage.h | 16 + .../AddStripMessage.cpp | 56 ++ .../ControlBehaviorMessages/AddStripMessage.h | 32 ++ .../BehaviorMessageBase.h | 48 ++ .../ControlBehaviorMessages/CMakeLists.txt | 16 + .../MergeStripsMessage.cpp | 20 + .../MergeStripsMessage.h | 26 + .../MigrateActionsMessage.cpp | 24 + .../MigrateActionsMessage.h | 28 + .../MoveToInventoryMessage.cpp | 11 + .../MoveToInventoryMessage.h | 19 + .../RearrangeStripMessage.cpp | 16 + .../RearrangeStripMessage.h | 22 + .../RemoveActionsMessage.cpp | 15 + .../RemoveActionsMessage.h | 22 + .../RemoveStripMessage.cpp | 8 + .../RemoveStripMessage.h | 18 + .../ControlBehaviorMessages/RenameMessage.cpp | 11 + .../ControlBehaviorMessages/RenameMessage.h | 18 + .../SplitStripMessage.cpp | 29 + .../SplitStripMessage.h | 30 + .../UpdateActionMessage.cpp | 38 ++ .../UpdateActionMessage.h | 30 + .../UpdateStripUiMessage.cpp | 20 + .../UpdateStripUiMessage.h | 24 + dGame/dPropertyBehaviors/ControlBehaviors.cpp | 540 +++++++----------- dGame/dPropertyBehaviors/ControlBehaviors.h | 47 +- tests/dGameTests/CMakeLists.txt | 2 + .../dGameMessagesTests/CMakeLists.txt | 5 + .../dGameMessagesTests/GameMessageTests.cpp | 191 ++++++- .../TestBitStreams/CMakeLists.txt | 24 + .../dGameMessagesTests/TestBitStreams/add | Bin 0 -> 1024 bytes .../TestBitStreams/addAction | Bin 0 -> 1024 bytes .../TestBitStreams/addStrip | Bin 0 -> 1024 bytes .../TestBitStreams/mergeStrips | Bin 0 -> 1024 bytes .../TestBitStreams/migrateActions | Bin 0 -> 1024 bytes .../TestBitStreams/modelTypeChanged | Bin 0 -> 1024 bytes .../TestBitStreams/rearrangeStrip | Bin 0 -> 1024 bytes .../TestBitStreams/removeActions | Bin 0 -> 1024 bytes .../TestBitStreams/removeStrip | Bin 0 -> 1024 bytes .../dGameMessagesTests/TestBitStreams/rename | Bin 0 -> 1024 bytes .../TestBitStreams/sendBehaviorListToClient | Bin 0 -> 1024 bytes .../TestBitStreams/splitStrip | Bin 0 -> 1024 bytes .../TestBitStreams/toggleExecutionUpdates | Bin 0 -> 1024 bytes .../TestBitStreams/updateAction | Bin 0 -> 1024 bytes .../TestBitStreams/updateStripUI | Bin 0 -> 1024 bytes 56 files changed, 1181 insertions(+), 362 deletions(-) create mode 100644 dGame/dPropertyBehaviors/BlockDefinition.cpp create mode 100644 dGame/dPropertyBehaviors/BlockDefinition.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/CMakeLists.txt create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/CMakeLists.txt create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/add create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/addAction create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/addStrip create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/mergeStrips create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/migrateActions create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/modelTypeChanged create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/rearrangeStrip create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/removeActions create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/removeStrip create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/rename create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/sendBehaviorListToClient create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/splitStrip create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/toggleExecutionUpdates create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/updateAction create mode 100644 tests/dGameTests/dGameMessagesTests/TestBitStreams/updateStripUI diff --git a/CMakeLists.txt b/CMakeLists.txt index 54f0d0dd..41d4219f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -163,6 +163,7 @@ set(INCLUDED_DIRECTORIES "dGame/dMission" "dGame/dEntity" "dGame/dPropertyBehaviors" + "dGame/dPropertyBehaviors/ControlBehaviorMessages" "dGame/dUtilities" "dPhysics" "dNavigation" diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index c90fd8e6..1d4a4c55 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -43,8 +43,7 @@ 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; -typedef uint32_t BEHAVIORSTATE; +typedef uint32_t StripId; typedef int32_t PetTamingPiece; //!< Pet Taming Pieces diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 58d72d3c..1d897727 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -2475,7 +2475,7 @@ void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* e auto owner = PropertyManagementComponent::Instance()->GetOwner(); if (!owner) return; - ControlBehaviors::ProcessCommand(entity, sysAddr, static_cast<AMFArrayValue*>(amfArguments.get()), command, owner); + ControlBehaviors::Instance().ProcessCommand(entity, sysAddr, static_cast<AMFArrayValue*>(amfArguments.get()), command, owner); } void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { diff --git a/dGame/dPropertyBehaviors/BehaviorStates.h b/dGame/dPropertyBehaviors/BehaviorStates.h index e09e45ba..80cb1dbb 100644 --- a/dGame/dPropertyBehaviors/BehaviorStates.h +++ b/dGame/dPropertyBehaviors/BehaviorStates.h @@ -3,12 +3,9 @@ #ifndef __BEHAVIORSTATES__H__ #define __BEHAVIORSTATES__H__ -#include <string> #include <cstdint> -#include "dCommonVars.h" - -enum States : BEHAVIORSTATE { +enum class BehaviorState : uint32_t { HOME_STATE = 0, //!< The HOME behavior state CIRCLE_STATE, //!< The CIRCLE behavior state SQUARE_STATE, //!< The SQUARE behavior state diff --git a/dGame/dPropertyBehaviors/BlockDefinition.cpp b/dGame/dPropertyBehaviors/BlockDefinition.cpp new file mode 100644 index 00000000..2950ac82 --- /dev/null +++ b/dGame/dPropertyBehaviors/BlockDefinition.cpp @@ -0,0 +1,9 @@ +#include "BlockDefinition.h" + +BlockDefinition BlockDefinition::blockDefinitionDefault{}; + +BlockDefinition::BlockDefinition(std::string defaultValue, float minimumValue, float maximumValue) { + this->defaultValue = defaultValue; + this->minimumValue = minimumValue; + this->maximumValue = maximumValue; +} diff --git a/dGame/dPropertyBehaviors/BlockDefinition.h b/dGame/dPropertyBehaviors/BlockDefinition.h new file mode 100644 index 00000000..3a5a6bf1 --- /dev/null +++ b/dGame/dPropertyBehaviors/BlockDefinition.h @@ -0,0 +1,25 @@ +#ifndef __BLOCKDEFINITION__H__ +#define __BLOCKDEFINITION__H__ + +#include <string> + +class AMFArrayValue; + +class BlockDefinition { +public: + BlockDefinition(std::string defaultValue = "", float minimumValue = 0.0f, 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; }; +private: + std::string defaultValue; + float minimumValue; + float maximumValue; +}; + +#endif //!__BLOCKDEFINITION__H__ diff --git a/dGame/dPropertyBehaviors/CMakeLists.txt b/dGame/dPropertyBehaviors/CMakeLists.txt index 4f5d60aa..5e33a5f5 100644 --- a/dGame/dPropertyBehaviors/CMakeLists.txt +++ b/dGame/dPropertyBehaviors/CMakeLists.txt @@ -1,4 +1,12 @@ set(DGAME_DPROPERTYBEHAVIORS_SOURCES + "BlockDefinition.cpp" "ControlBehaviors.cpp" - PARENT_SCOPE ) + +add_subdirectory(ControlBehaviorMessages) + +foreach(file ${DGAME_DPROPERTYBEHAVIORS_CONTROLBEHAVIORMESSAGES}) + set(DGAME_DPROPERTYBEHAVIORS_SOURCES ${DGAME_DPROPERTYBEHAVIORS_SOURCES} "ControlBehaviorMessages/${file}") +endforeach() + +set(DGAME_DPROPERTYBEHAVIORS_SOURCES ${DGAME_DPROPERTYBEHAVIORS_SOURCES} PARENT_SCOPE) diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp new file mode 100644 index 00000000..f91512fe --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp @@ -0,0 +1,39 @@ +#include "AddActionMessage.h" + +AddActionMessage::AddActionMessage(AMFArrayValue* arguments) { + auto* actionIndexAmf = arguments->FindValue<AMFDoubleValue>("actionIndex"); + if (!actionIndexAmf) return; + + actionIndex = static_cast<uint32_t>(actionIndexAmf->GetDoubleValue()); + + stripId = GetStripIDFromArgument(arguments); + + stateId = GetBehaviorStateFromArgument(arguments); + + type = ""; + valueParameterName = ""; + valueParameterString = ""; + valueParameterDouble = 0.0; + auto* action = arguments->FindValue<AMFArrayValue>("action"); + if (!action) return; + + for (auto& typeValueMap : action->GetAssociativeMap()) { + if (typeValueMap.first == "Type") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + type = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + valueParameterName = typeValueMap.first; + // Message is the only known string parameter + if (valueParameterName == "Message") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + valueParameterString = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFDouble) continue; + valueParameterDouble = static_cast<AMFDoubleValue*>(typeValueMap.second)->GetDoubleValue(); + } + } + } + + behaviorId = GetBehaviorIDFromArgument(arguments); + Game::logger->LogDebug("AddActionMessage", "acnNdx %i stpId %i sttId %i t %s vpn %s vps %s vpd %f bhId %i", actionIndex, stripId, stateId, type.c_str(), valueParameterName.c_str(), valueParameterString.c_str(), valueParameterDouble, behaviorId); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h new file mode 100644 index 00000000..1f1577ec --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h @@ -0,0 +1,30 @@ +#ifndef __ADDACTIONMESSAGE__H__ +#define __ADDACTIONMESSAGE__H__ + +#include "BehaviorMessageBase.h" + +class AMFArrayValue; + +class AddActionMessage : public BehaviorMessageBase { +public: + AddActionMessage(AMFArrayValue* arguments); + const uint32_t GetActionIndex() { return actionIndex; }; + const StripId GetStripId() { return stripId; }; + const BehaviorState GetStateId() { return stateId; }; + const std::string& GetType() { return type; }; + const std::string& GetValueParameterName() { return valueParameterName; }; + const std::string& GetValueParameterString() { return valueParameterString; }; + const double GetValueParameterDouble() { return valueParameterDouble; }; + const uint32_t GetBehaviorId() { return behaviorId; }; +private: + uint32_t actionIndex; + StripId stripId; + BehaviorState stateId; + std::string type; + std::string valueParameterName; + std::string valueParameterString; + double valueParameterDouble; + uint32_t behaviorId; +}; + +#endif //!__ADDACTIONMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp new file mode 100644 index 00000000..ecddb8e3 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp @@ -0,0 +1,13 @@ +#include "AddMessage.h" + +AddMessage::AddMessage(AMFArrayValue* arguments) { + behaviorId = GetBehaviorIDFromArgument(arguments); + + behaviorIndex = 0; + auto* behaviorIndexValue = arguments->FindValue<AMFDoubleValue>("BehaviorIndex"); + + if (!behaviorIndexValue) return; + + behaviorIndex = static_cast<uint32_t>(behaviorIndexValue->GetDoubleValue()); + Game::logger->LogDebug("AddMessage", "bhId %i ndx %i", behaviorId, behaviorIndex); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h new file mode 100644 index 00000000..ff8e0c8b --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h @@ -0,0 +1,16 @@ +#ifndef __ADDMESSAGE__H__ +#define __ADDMESSAGE__H__ + +#include "BehaviorMessageBase.h" + +class AddMessage : public BehaviorMessageBase { +public: + AddMessage(AMFArrayValue* arguments); + const uint32_t GetBehaviorIndex() { return behaviorIndex; }; + const uint32_t GetBehaviorId() { return behaviorId; }; +private: + uint32_t behaviorId; + uint32_t behaviorIndex; +}; + +#endif //!__ADDMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp new file mode 100644 index 00000000..23662174 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp @@ -0,0 +1,56 @@ +#include "AddStripMessage.h" + +AddStripMessage::AddStripMessage(AMFArrayValue* arguments) { + auto* strip = arguments->FindValue<AMFArrayValue>("strip"); + if (!strip) return; + + auto* actions = strip->FindValue<AMFArrayValue>("actions"); + if (!actions) return; + + auto* uiArray = arguments->FindValue<AMFArrayValue>("ui"); + if (!uiArray) return; + + auto* xPositionValue = uiArray->FindValue<AMFDoubleValue>("x"); + if (!xPositionValue) return; + + xPosition = xPositionValue->GetDoubleValue(); + + auto* yPositionValue = uiArray->FindValue<AMFDoubleValue>("y"); + if (!yPositionValue) return; + + yPosition = yPositionValue->GetDoubleValue(); + + stripId = GetStripIDFromArgument(arguments); + + stateId = GetBehaviorStateFromArgument(arguments); + + behaviorId = GetBehaviorIDFromArgument(arguments); + + type = ""; + valueParameterName = ""; + valueParameterString = ""; + valueParameterDouble = 0.0; + for (uint32_t position = 0; position < actions->GetDenseValueSize(); position++) { + auto* actionAsArray = actions->GetValueAt<AMFArrayValue>(position); + if (!actionAsArray) continue; + + for (auto& typeValueMap : actionAsArray->GetAssociativeMap()) { + if (typeValueMap.first == "Type") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + + type = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + valueParameterName = typeValueMap.first; + // Message is the only known string parameter + if (valueParameterName == "Message") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + valueParameterString = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFDouble) continue; + valueParameterDouble = static_cast<AMFDoubleValue*>(typeValueMap.second)->GetDoubleValue(); + } + } + } + Game::logger->LogDebug("AddStripMessage", "x %f y %f stpId %i sttId %i bhId %i t %s vpn %s vps %s vpd %f", xPosition, yPosition, stripId, stateId, behaviorId, type.c_str(), valueParameterName.c_str(), valueParameterString.c_str(), valueParameterDouble); + } +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h new file mode 100644 index 00000000..bb720bae --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h @@ -0,0 +1,32 @@ +#ifndef __ADDSTRIPMESSAGE__H__ +#define __ADDSTRIPMESSAGE__H__ + +#include "BehaviorMessageBase.h" + +class AMFArrayValue; + +class AddStripMessage : public BehaviorMessageBase { +public: + AddStripMessage(AMFArrayValue* arguments); + const StripId GetStripId() { return stripId; }; + const BehaviorState GetStateId() { return stateId; }; + const std::string& GetType() { return type; }; + const std::string& GetValueParameterName() { return valueParameterName; }; + const std::string& GetValueParameterString() { return valueParameterString; }; + const double GetXPosition() { return xPosition; }; + const double GetYPosition() { return yPosition; }; + const double GetValueParameterDouble() { return valueParameterDouble; }; + const uint32_t GetBehaviorId() { return behaviorId; }; +private: + double xPosition; + double yPosition; + StripId stripId; + BehaviorState stateId; + uint32_t behaviorId; + std::string type; + std::string valueParameterName; + std::string valueParameterString; + double valueParameterDouble; +}; + +#endif //!__ADDSTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h new file mode 100644 index 00000000..78025672 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h @@ -0,0 +1,48 @@ +#ifndef __BEHAVIORMESSAGEBASE__H__ +#define __BEHAVIORMESSAGEBASE__H__ + +#include <stdexcept> +#include <string> + +#include "AMFFormat.h" +#include "BehaviorStates.h" +#include "dCommonVars.h" + +#include "Game.h" +#include "dLogger.h" + +class BehaviorMessageBase { +public: + uint32_t GetBehaviorIDFromArgument(AMFArrayValue* arguments, const std::string& key = "BehaviorID") { + auto* behaviorIDValue = arguments->FindValue<AMFStringValue>(key); + uint32_t behaviorID = -1; + + if (behaviorIDValue) { + behaviorID = std::stoul(behaviorIDValue->GetStringValue()); + } else if (arguments->FindValue<AMFUndefinedValue>(key) == nullptr) { + throw std::invalid_argument("Unable to find behavior ID from argument \"" + key + "\""); + } + + return behaviorID; + } + + BehaviorState GetBehaviorStateFromArgument(AMFArrayValue* arguments, const std::string& key = "stateID") { + auto* stateIDValue = arguments->FindValue<AMFDoubleValue>(key); + if (!stateIDValue) throw std::invalid_argument("Unable to find behavior state from argument \"" + key + "\""); + + BehaviorState stateID = static_cast<BehaviorState>(stateIDValue->GetDoubleValue()); + + return stateID; + } + + StripId GetStripIDFromArgument(AMFArrayValue* arguments, const std::string& key = "stripID") { + auto* stripIDValue = arguments->FindValue<AMFDoubleValue>(key); + if (!stripIDValue) throw std::invalid_argument("Unable to find strip ID from argument \"" + key + "\""); + + StripId stripID = static_cast<StripId>(stripIDValue->GetDoubleValue()); + + return stripID; + } +}; + +#endif //!__BEHAVIORMESSAGEBASE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/CMakeLists.txt b/dGame/dPropertyBehaviors/ControlBehaviorMessages/CMakeLists.txt new file mode 100644 index 00000000..8390cd22 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/CMakeLists.txt @@ -0,0 +1,16 @@ +set(DGAME_DPROPERTYBEHAVIORS_CONTROLBEHAVIORMESSAGES + "AddActionMessage.cpp" + "AddMessage.cpp" + "AddStripMessage.cpp" + "MergeStripsMessage.cpp" + "MigrateActionsMessage.cpp" + "MoveToInventoryMessage.cpp" + "RearrangeStripMessage.cpp" + "RemoveActionsMessage.cpp" + "RemoveStripMessage.cpp" + "RenameMessage.cpp" + "SplitStripMessage.cpp" + "UpdateActionMessage.cpp" + "UpdateStripUiMessage.cpp" + PARENT_SCOPE +) diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp new file mode 100644 index 00000000..d810e861 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp @@ -0,0 +1,20 @@ +#include "MergeStripsMessage.h" + +MergeStripsMessage::MergeStripsMessage(AMFArrayValue* arguments) { + srcStripID = GetStripIDFromArgument(arguments, "srcStripID"); + + dstStateID = GetBehaviorStateFromArgument(arguments, "dstStateID"); + + srcStateID = GetBehaviorStateFromArgument(arguments, "srcStateID"); + + auto* dstActionIndexValue = arguments->FindValue<AMFDoubleValue>("dstActionIndex"); + if (!dstActionIndexValue) return; + + dstActionIndex = static_cast<uint32_t>(dstActionIndexValue->GetDoubleValue()); + + dstStripID = GetStripIDFromArgument(arguments, "dstStripID"); + + behaviorID = GetBehaviorIDFromArgument(arguments); + Game::logger->LogDebug("MergeStripsMessage", "srcStpId %i dstStpId %i srcSttId %i dstSttId %i dstAcnNdx %i bhId %i", srcStripID, dstStripID, srcStateID, dstStateID, dstActionIndex, behaviorID); +} + diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h new file mode 100644 index 00000000..af3aa16f --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h @@ -0,0 +1,26 @@ +#ifndef __MERGESTRIPSMESSAGE__H__ +#define __MERGESTRIPSMESSAGE__H__ + +#include "BehaviorMessageBase.h" + +class AMFArrayValue; + +class MergeStripsMessage : public BehaviorMessageBase { +public: + MergeStripsMessage(AMFArrayValue* arguments); + const StripId GetSrcStripID() { return srcStripID; }; + const BehaviorState GetDstStateID() { return dstStateID; }; + const BehaviorState GetSrcStateID() { return srcStateID; }; + const uint32_t GetDstActionIndex() { return dstActionIndex; }; + const StripId GetDstStripID() { return dstStripID; }; + const uint32_t GetBehaviorID() { return behaviorID; }; +private: + StripId srcStripID; + BehaviorState dstStateID; + BehaviorState srcStateID; + uint32_t dstActionIndex; + StripId dstStripID; + uint32_t behaviorID; +}; + +#endif //!__MERGESTRIPSMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp new file mode 100644 index 00000000..8bb4e819 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp @@ -0,0 +1,24 @@ +#include "MigrateActionsMessage.h" + +MigrateActionsMessage::MigrateActionsMessage(AMFArrayValue* arguments) { + auto* srcActionIndexAmf = arguments->FindValue<AMFDoubleValue>("srcActionIndex"); + if (!srcActionIndexAmf) return; + + srcActionIndex = static_cast<uint32_t>(srcActionIndexAmf->GetDoubleValue()); + + srcStripID = GetStripIDFromArgument(arguments, "srcStripID"); + + srcStateID = GetBehaviorStateFromArgument(arguments, "srcStateID"); + + auto* dstActionIndexAmf = arguments->FindValue<AMFDoubleValue>("dstActionIndex"); + if (!dstActionIndexAmf) return; + + dstActionIndex = static_cast<uint32_t>(dstActionIndexAmf->GetDoubleValue()); + + dstStripID = GetStripIDFromArgument(arguments, "dstStripID"); + + dstStateID = GetBehaviorStateFromArgument(arguments, "dstStateID"); + + behaviorID = GetBehaviorIDFromArgument(arguments); + Game::logger->LogDebug("MigrateActionsMessage", "srcAcnNdx %i dstAcnNdx %i srcStpId %i dstStpId %i srcSttId %i dstSttId %i bhid %i", srcActionIndex, dstActionIndex, srcStripID, dstStripID, srcStateID, dstStateID, behaviorID); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h new file mode 100644 index 00000000..26018d69 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h @@ -0,0 +1,28 @@ +#ifndef __MIGRATEACTIONSMESSAGE__H__ +#define __MIGRATEACTIONSMESSAGE__H__ + +#include "BehaviorMessageBase.h" + +class AMFArrayValue; + +class MigrateActionsMessage : public BehaviorMessageBase { +public: + MigrateActionsMessage(AMFArrayValue* arguments); + const uint32_t GetSrcActionIndex() { return srcActionIndex; }; + const StripId GetSrcStripID() { return srcStripID; }; + const BehaviorState GetSrcStateID() { return srcStateID; }; + const uint32_t GetDstActionIndex() { return dstActionIndex; }; + const StripId GetDstStripID() { return dstStripID; }; + const BehaviorState GetDstStateID() { return dstStateID; }; + const uint32_t GetBehaviorID() { return behaviorID; }; +private: + uint32_t srcActionIndex; + StripId srcStripID; + BehaviorState srcStateID; + uint32_t dstActionIndex; + StripId dstStripID; + BehaviorState dstStateID; + uint32_t behaviorID; +}; + +#endif //!__MIGRATEACTIONSMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp new file mode 100644 index 00000000..7ad7a875 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp @@ -0,0 +1,11 @@ +#include "MoveToInventoryMessage.h" + +MoveToInventoryMessage::MoveToInventoryMessage(AMFArrayValue* arguments) { + behaviorID = GetBehaviorIDFromArgument(arguments); + + auto* behaviorIndexValue = arguments->FindValue<AMFDoubleValue>("BehaviorIndex"); + if (!behaviorIndexValue) return; + + behaviorIndex = static_cast<uint32_t>(behaviorIndexValue->GetDoubleValue()); + Game::logger->LogDebug("MoveToInventoryMessage", "bhId %i bhNdx %i", behaviorID, behaviorIndex); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h new file mode 100644 index 00000000..2cf71f3c --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h @@ -0,0 +1,19 @@ +#ifndef __MOVETOINVENTORYMESSAGE__H__ +#define __MOVETOINVENTORYMESSAGE__H__ + +#include "BehaviorMessageBase.h" + +class AMFArrayValue; + +#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 GetBehaviorID() { return behaviorID; }; + const uint32_t GetBehaviorIndex() { return behaviorIndex; }; +private: + uint32_t behaviorID; + uint32_t behaviorIndex; +}; + +#endif //!__MOVETOINVENTORYMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp new file mode 100644 index 00000000..0347aca6 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp @@ -0,0 +1,16 @@ +#include "RearrangeStripMessage.h" + +RearrangeStripMessage::RearrangeStripMessage(AMFArrayValue* arguments) { + auto* srcActionIndexValue = arguments->FindValue<AMFDoubleValue>("srcActionIndex"); + srcActionIndex = static_cast<uint32_t>(srcActionIndexValue->GetDoubleValue()); + + stripID = GetStripIDFromArgument(arguments); + + behaviorID = GetBehaviorIDFromArgument(arguments); + + auto* dstActionIndexValue = arguments->FindValue<AMFDoubleValue>("dstActionIndex"); + dstActionIndex = static_cast<uint32_t>(dstActionIndexValue->GetDoubleValue()); + + stateID = GetBehaviorStateFromArgument(arguments); + Game::logger->LogDebug("RearrangeStripMessage", "srcAcnNdx %i dstAcnNdx %i stpId %i bhId %i sttId %i", srcActionIndex, dstActionIndex, stripID, behaviorID, stateID); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h new file mode 100644 index 00000000..4cca0827 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h @@ -0,0 +1,22 @@ +#ifndef __REARRANGESTRIPMESSAGE__H__ +#define __REARRANGESTRIPMESSAGE__H__ + +#include "BehaviorMessageBase.h" + +class RearrangeStripMessage : public BehaviorMessageBase { +public: + RearrangeStripMessage(AMFArrayValue* arguments); + const uint32_t GetSrcActionIndex() { return srcActionIndex; }; + const uint32_t GetStripID() { return stripID; }; + const uint32_t GetBehaviorID() { return behaviorID; }; + const uint32_t GetDstActionIndex() { return dstActionIndex; }; + const BehaviorState GetStateID() { return stateID; }; +private: + uint32_t srcActionIndex; + uint32_t stripID; + uint32_t behaviorID; + uint32_t dstActionIndex; + BehaviorState stateID; +}; + +#endif //!__REARRANGESTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp new file mode 100644 index 00000000..cb1226e3 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp @@ -0,0 +1,15 @@ +#include "RemoveActionsMessage.h" + +RemoveActionsMessage::RemoveActionsMessage(AMFArrayValue* arguments) { + behaviorID = GetBehaviorIDFromArgument(arguments); + + auto* actionIndexAmf = arguments->FindValue<AMFDoubleValue>("actionIndex"); + if (!actionIndexAmf) return; + + actionIndex = static_cast<uint32_t>(actionIndexAmf->GetDoubleValue()); + + stripID = GetStripIDFromArgument(arguments); + + stateID = GetBehaviorStateFromArgument(arguments); + Game::logger->LogDebug("RemoveActionsMessage", "bhId %i acnNdx %i stpId %i sttId %i", behaviorID, actionIndex, stripID, stateID); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h new file mode 100644 index 00000000..33678f59 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h @@ -0,0 +1,22 @@ +#ifndef __REMOVEACTIONSMESSAGE__H__ +#define __REMOVEACTIONSMESSAGE__H__ + +#include "BehaviorMessageBase.h" + +class AMFArrayValue; + +class RemoveActionsMessage : public BehaviorMessageBase { +public: + RemoveActionsMessage(AMFArrayValue* arguments); + const uint32_t GetBehaviorID() { return behaviorID; }; + const uint32_t GetActionIndex() { return actionIndex; }; + const StripId GetStripID() { return stripID; }; + const BehaviorState GetStateID() { return stateID; }; +private: + uint32_t behaviorID; + uint32_t actionIndex; + StripId stripID; + BehaviorState stateID; +}; + +#endif //!__REMOVEACTIONSMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp new file mode 100644 index 00000000..3c48ed16 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp @@ -0,0 +1,8 @@ +#include "RemoveStripMessage.h" + +RemoveStripMessage::RemoveStripMessage(AMFArrayValue* arguments) { + stripId = GetStripIDFromArgument(arguments); + behaviorState = GetBehaviorStateFromArgument(arguments); + behaviorId = GetBehaviorIDFromArgument(arguments); + Game::logger->LogDebug("RemoveStripMessage", "stpId %i bhStt %i bhId %i", stripId, behaviorState, behaviorId); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h new file mode 100644 index 00000000..312bab31 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h @@ -0,0 +1,18 @@ +#ifndef __REMOVESTRIPMESSAGE__H__ +#define __REMOVESTRIPMESSAGE__H__ + +#include "BehaviorMessageBase.h" + +class RemoveStripMessage : public BehaviorMessageBase { +public: + RemoveStripMessage(AMFArrayValue* arguments); + const StripId GetStripId() { return stripId; }; + const BehaviorState GetBehaviorState() { return behaviorState; }; + const uint32_t GetBehaviorId() { return behaviorId; }; +private: + StripId stripId; + BehaviorState behaviorState; + uint32_t behaviorId; +}; + +#endif //!__REMOVESTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp new file mode 100644 index 00000000..38c49462 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp @@ -0,0 +1,11 @@ +#include "RenameMessage.h" + +RenameMessage::RenameMessage(AMFArrayValue* arguments) { + behaviorID = GetBehaviorIDFromArgument(arguments); + + auto* nameAmf = arguments->FindValue<AMFStringValue>("Name"); + if (!nameAmf) return; + + name = nameAmf->GetStringValue(); + Game::logger->LogDebug("RenameMessage", "bhId %i n %s", behaviorID, name.c_str()); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h new file mode 100644 index 00000000..be42d66f --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h @@ -0,0 +1,18 @@ +#ifndef __RENAMEMESSAGE__H__ +#define __RENAMEMESSAGE__H__ + +#include "BehaviorMessageBase.h" + +class AMFArrayValue; + +class RenameMessage : public BehaviorMessageBase { +public: + RenameMessage(AMFArrayValue* arguments); + const uint32_t GetBehaviorID() { return behaviorID; }; + const std::string& GetName() { return name; }; +private: + uint32_t behaviorID; + std::string name; +}; + +#endif //!__RENAMEMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp new file mode 100644 index 00000000..d3493aeb --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp @@ -0,0 +1,29 @@ +#include "SplitStripMessage.h" + +SplitStripMessage::SplitStripMessage(AMFArrayValue* arguments) { + auto* srcActionIndexValue = arguments->FindValue<AMFDoubleValue>("srcActionIndex"); + if (!srcActionIndexValue) return; + + srcActionIndex = static_cast<uint32_t>(srcActionIndexValue->GetDoubleValue()); + + srcStripId = GetStripIDFromArgument(arguments, "srcStripID"); + + srcStateId = GetBehaviorStateFromArgument(arguments, "srcStateID"); + + dstStripId = GetStripIDFromArgument(arguments, "dstStripID"); + + dstStateId = GetBehaviorStateFromArgument(arguments, "dstStateID"); + + auto* dstStripUiArray = arguments->FindValue<AMFArrayValue>("dstStripUI"); + if (!dstStripUiArray) return; + + auto* xPositionValue = dstStripUiArray->FindValue<AMFDoubleValue>("x"); + auto* yPositionValue = dstStripUiArray->FindValue<AMFDoubleValue>("y"); + if (!xPositionValue || !yPositionValue) return; + + yPosition = yPositionValue->GetDoubleValue(); + xPosition = xPositionValue->GetDoubleValue(); + + behaviorId = GetBehaviorIDFromArgument(arguments); + Game::logger->LogDebug("SplitStripMessage", "bhid %i x %f y %f srcStp %i dstStp %i srcStt %i dstStt %i srcActNdx %i", behaviorId, xPosition, yPosition, srcStripId, dstStripId, srcStateId, dstStateId, srcActionIndex); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h new file mode 100644 index 00000000..e06a9dc4 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h @@ -0,0 +1,30 @@ +#ifndef __SPLITSTRIPMESSAGE__H__ +#define __SPLITSTRIPMESSAGE__H__ + +#include "BehaviorMessageBase.h" + +class AMFArrayValue; + +class SplitStripMessage : public BehaviorMessageBase { +public: + SplitStripMessage(AMFArrayValue* arguments); + const uint32_t GetSrcActionIndex() { return srcActionIndex; }; + const StripId GetSrcStripId() { return srcStripId; }; + const BehaviorState GetSrcStateId() { return srcStateId; }; + const StripId GetDstStripId() { return dstStripId; }; + const BehaviorState GetDstStateId() { return dstStateId; }; + const double GetYPosition() { return yPosition; }; + const double GetXPosition() { return xPosition; }; + const uint32_t GetBehaviorId() { return behaviorId; }; +private: + uint32_t srcActionIndex; + StripId srcStripId; + BehaviorState srcStateId; + StripId dstStripId; + BehaviorState dstStateId; + double yPosition; + double xPosition; + uint32_t behaviorId; +}; + +#endif //!__SPLITSTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp new file mode 100644 index 00000000..1d4cc868 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp @@ -0,0 +1,38 @@ +#include "UpdateActionMessage.h" + +UpdateActionMessage::UpdateActionMessage(AMFArrayValue* arguments) { + type = ""; + valueParameterName = ""; + valueParameterString = ""; + valueParameterDouble = 0.0; + auto* actionAsArray = arguments->FindValue<AMFArrayValue>("action"); + if (!actionAsArray) return; + for (auto& typeValueMap : actionAsArray->GetAssociativeMap()) { + if (typeValueMap.first == "Type") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + type = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + valueParameterName = typeValueMap.first; + // Message is the only known string parameter + if (valueParameterName == "Message") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + valueParameterString = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFDouble) continue; + valueParameterDouble = static_cast<AMFDoubleValue*>(typeValueMap.second)->GetDoubleValue(); + } + } + } + + behaviorID = GetBehaviorIDFromArgument(arguments); + + auto* actionIndexValue = arguments->FindValue<AMFDoubleValue>("actionIndex"); + if (!actionIndexValue) return; + + actionIndex = static_cast<uint32_t>(actionIndexValue->GetDoubleValue()); + + stripID = GetStripIDFromArgument(arguments); + + stateID = GetBehaviorStateFromArgument(arguments); + Game::logger->LogDebug("UpdateActionMessage", "t %s vpn %s vps %s vpd %f bhId %i acnNdx %i stpId %i sttId %i", type.c_str(), valueParameterName.c_str(), valueParameterString.c_str(), valueParameterDouble, behaviorID, actionIndex, stripID, stateID); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h new file mode 100644 index 00000000..a42be22b --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h @@ -0,0 +1,30 @@ +#ifndef __UPDATEACTIONMESSAGE__H__ +#define __UPDATEACTIONMESSAGE__H__ + +#include "BehaviorMessageBase.h" + +class AMFArrayValue; + +class UpdateActionMessage : public BehaviorMessageBase { +public: + UpdateActionMessage(AMFArrayValue* arguments); + const std::string& GetType() { return type; }; + const std::string& GetValueParameterName() { return valueParameterName; }; + const std::string& GetValueParameterString() { return valueParameterString; }; + const double GetValueParameterDouble() { return valueParameterDouble; }; + const uint32_t GetBehaviorID() { return behaviorID; }; + const uint32_t GetActionIndex() { return actionIndex; }; + const StripId GetStripID() { return stripID; }; + const BehaviorState GetStateID() { return stateID; }; +private: + std::string type; + std::string valueParameterName; + std::string valueParameterString; + double valueParameterDouble; + uint32_t behaviorID; + uint32_t actionIndex; + StripId stripID; + BehaviorState stateID; +}; + +#endif //!__UPDATEACTIONMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp new file mode 100644 index 00000000..60e2f0f3 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp @@ -0,0 +1,20 @@ +#include "UpdateStripUiMessage.h" + +UpdateStripUiMessage::UpdateStripUiMessage(AMFArrayValue* arguments) { + auto* uiArray = arguments->FindValue<AMFArrayValue>("ui"); + if (!uiArray) return; + + auto* xPositionValue = uiArray->FindValue<AMFDoubleValue>("x"); + auto* yPositionValue = uiArray->FindValue<AMFDoubleValue>("y"); + if (!xPositionValue || !yPositionValue) return; + + yPosition = yPositionValue->GetDoubleValue(); + xPosition = xPositionValue->GetDoubleValue(); + + stripID = GetStripIDFromArgument(arguments); + + stateID = GetBehaviorStateFromArgument(arguments); + + behaviorID = GetBehaviorIDFromArgument(arguments); + Game::logger->LogDebug("UpdateStripUIMessage", "x %f y %f stpId %i sttId %i bhId %i", xPosition, yPosition, stripID, stateID, behaviorID); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h new file mode 100644 index 00000000..ca626120 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h @@ -0,0 +1,24 @@ +#ifndef __UPDATESTRIPUIMESSAGE__H__ +#define __UPDATESTRIPUIMESSAGE__H__ + +#include "BehaviorMessageBase.h" + +class AMFArrayValue; + +class UpdateStripUiMessage : public BehaviorMessageBase { +public: + UpdateStripUiMessage(AMFArrayValue* arguments); + const double GetYPosition() { return yPosition; }; + const double GetXPosition() { return xPosition; }; + const StripId GetStripID() { return stripID; }; + const BehaviorState GetStateID() { return stateID; }; + const uint32_t GetBehaviorID() { return behaviorID; }; +private: + double yPosition; + double xPosition; + StripId stripID; + BehaviorState stateID; + uint32_t behaviorID; +}; + +#endif //!__UPDATESTRIPUIMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.cpp b/dGame/dPropertyBehaviors/ControlBehaviors.cpp index 278b6929..3e8bbacc 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviors.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviors.cpp @@ -7,40 +7,29 @@ #include "ModelComponent.h" #include "../../dWorldServer/ObjectIDManager.h" #include "dLogger.h" +#include "BehaviorStates.h" +#include "AssetManager.h" +#include "BlockDefinition.h" #include "User.h" +#include "tinyxml2.h" +#include "CDClientDatabase.h" -uint32_t GetBehaviorIDFromArgument(AMFArrayValue* arguments, const std::string& key = "BehaviorID") { - auto* behaviorIDValue = arguments->FindValue<AMFStringValue>(key); - uint32_t behaviorID = -1; +// Message includes +#include "AddActionMessage.h" +#include "AddStripMessage.h" +#include "AddMessage.h" +#include "MigrateActionsMessage.h" +#include "MoveToInventoryMessage.h" +#include "MergeStripsMessage.h" +#include "RearrangeStripMessage.h" +#include "RemoveActionsMessage.h" +#include "RemoveStripMessage.h" +#include "RenameMessage.h" +#include "SplitStripMessage.h" +#include "UpdateActionMessage.h" +#include "UpdateStripUiMessage.h" - if (behaviorIDValue) { - behaviorID = std::stoul(behaviorIDValue->GetStringValue()); - } else if (arguments->FindValue<AMFUndefinedValue>(key) == nullptr){ - throw std::invalid_argument("Unable to find behavior ID from argument \"" + key + "\""); - } - - return behaviorID; -} - -BEHAVIORSTATE GetBehaviorStateFromArgument(AMFArrayValue* arguments, const std::string& key = "stateID") { - auto* stateIDValue = arguments->FindValue<AMFDoubleValue>(key); - if (!stateIDValue) throw std::invalid_argument("Unable to find behavior state from argument \"" + key + "\""); - - BEHAVIORSTATE stateID = static_cast<BEHAVIORSTATE>(stateIDValue->GetDoubleValue()); - - return stateID; -} - -STRIPID GetStripIDFromArgument(AMFArrayValue* arguments, const std::string& key = "stripID") { - auto* stripIDValue = arguments->FindValue<AMFDoubleValue>(key); - if (!stripIDValue) throw std::invalid_argument("Unable to find strip ID from argument \"" + key + "\""); - - STRIPID stripID = static_cast<STRIPID>(stripIDValue->GetDoubleValue()); - - return stripID; -} - -void RequestUpdatedID(int32_t behaviorID, ModelComponent* modelComponent, Entity* modelOwner, const SystemAddress& sysAddr) { +void ControlBehaviors::RequestUpdatedID(int32_t behaviorID, ModelComponent* modelComponent, Entity* modelOwner, const SystemAddress& sysAddr) { // auto behavior = modelComponent->FindBehavior(behaviorID); // if (behavior->GetBehaviorID() == -1 || behavior->GetShouldSetNewID()) { // ObjectIDManager::Instance()->RequestPersistentID( @@ -66,11 +55,7 @@ void RequestUpdatedID(int32_t behaviorID, ModelComponent* modelComponent, Entity // } } -void SendBehaviorListToClient( - Entity* modelEntity, - const SystemAddress& sysAddr, - Entity* modelOwner - ) { +void ControlBehaviors::SendBehaviorListToClient(Entity* modelEntity, const SystemAddress& sysAddr, Entity* modelOwner) { auto* modelComponent = modelEntity->GetComponent<ModelComponent>(); if (!modelComponent) return; @@ -98,7 +83,7 @@ void SendBehaviorListToClient( GameMessages::SendUIMessageServerToSingleClient(modelOwner, sysAddr, "UpdateBehaviorList", &behaviorsToSerialize); } -void ModelTypeChanged(AMFArrayValue* arguments, ModelComponent* ModelComponent) { +void ControlBehaviors::ModelTypeChanged(AMFArrayValue* arguments, ModelComponent* ModelComponent) { auto* modelTypeAmf = arguments->FindValue<AMFDoubleValue>("ModelType"); if (!modelTypeAmf) return; @@ -107,292 +92,57 @@ void ModelTypeChanged(AMFArrayValue* arguments, ModelComponent* ModelComponent) //TODO Update the model type here } -void ToggleExecutionUpdates() { +void ControlBehaviors::ToggleExecutionUpdates() { //TODO do something with this info } -void AddStrip(AMFArrayValue* arguments) { - auto* strip = arguments->FindValue<AMFArrayValue>("strip"); - if (!strip) return; - - auto* actions = strip->FindValue<AMFArrayValue>("actions"); - if (!actions) return; - - auto* uiArray = arguments->FindValue<AMFArrayValue>("ui"); - if (!uiArray) return; - - auto* xPositionValue = uiArray->FindValue<AMFDoubleValue>("x"); - if (!xPositionValue) return; - - double xPosition = xPositionValue->GetDoubleValue(); - - auto* yPositionValue = uiArray->FindValue<AMFDoubleValue>("y"); - if (!yPositionValue) return; - - double yPosition = yPositionValue->GetDoubleValue(); - - STRIPID stripID = GetStripIDFromArgument(arguments); - - BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); - - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); - - std::string type = ""; - std::string valueParameterName = ""; - std::string valueParameterString = ""; - double valueParameterDouble = 0.0; - for (uint32_t position = 0; position < actions->GetDenseValueSize(); position++) { - auto* actionAsArray = actions->GetValueAt<AMFArrayValue>(position); - if (!actionAsArray) continue; - - for (auto& typeValueMap : actionAsArray->GetAssociativeMap()) { - if (typeValueMap.first == "Type") { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; - - type = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); - } else { - valueParameterName = typeValueMap.first; - // Message is the only known string parameter - if (valueParameterName == "Message") { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; - valueParameterString = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); - } else { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFDouble) continue; - valueParameterDouble = static_cast<AMFDoubleValue*>(typeValueMap.second)->GetDoubleValue(); - } - } - } - // modelComponent->AddStrip(stateID, stripID, type, behaviorID, valueParameterName, valueParameterString, valueParameterDouble, "", xPosition, yPosition); - type.clear(); - valueParameterName.clear(); - valueParameterString.clear(); - valueParameterDouble = 0.0; - } - // RequestUpdatedID(behaviorID); +void ControlBehaviors::AddStrip(AMFArrayValue* arguments) { + AddStripMessage addStripMessage(arguments); } -void RemoveStrip(AMFArrayValue* arguments) { - STRIPID stripID = GetStripIDFromArgument(arguments); - - BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); - - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); - - // modelComponent->RemoveStrip(stateID, stripID, behaviorID); - - // RequestUpdatedID(behaviorID); +void ControlBehaviors::RemoveStrip(AMFArrayValue* arguments) { + RemoveStripMessage removeStrip(arguments); } -void MergeStrips(AMFArrayValue* arguments) { - STRIPID srcStripID = GetStripIDFromArgument(arguments, "srcStripID"); - - BEHAVIORSTATE dstStateID = GetBehaviorStateFromArgument(arguments, "dstStateID"); - - BEHAVIORSTATE srcStateID = GetBehaviorStateFromArgument(arguments, "srcStateID"); - - auto* dstActionIndexValue = arguments->FindValue<AMFDoubleValue>("dstActionIndex"); - if (!dstActionIndexValue) return; - - uint32_t dstActionIndex = static_cast<uint32_t>(dstActionIndexValue->GetDoubleValue()); - - STRIPID dstStripID = GetStripIDFromArgument(arguments, "dstStripID"); - - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); - - // modelComponent->MergeStrips(srcStripID, dstStripID, srcStateID, dstStateID, behaviorID, dstActionIndex); - - // RequestUpdatedID(behaviorID); +void ControlBehaviors::MergeStrips(AMFArrayValue* arguments) { + MergeStripsMessage mergeStripsMessage(arguments); } -void SplitStrip(AMFArrayValue* arguments) { - auto* srcActionIndexValue = arguments->FindValue<AMFDoubleValue>("srcActionIndex"); - if (!srcActionIndexValue) return; - - uint32_t srcActionIndex = static_cast<uint32_t>(srcActionIndexValue->GetDoubleValue()); - - STRIPID srcStripID = GetStripIDFromArgument(arguments, "srcStripID"); - - BEHAVIORSTATE srcStateID = GetBehaviorStateFromArgument(arguments, "srcStateID"); - - STRIPID dstStripID = GetStripIDFromArgument(arguments, "dstStripID"); - - BEHAVIORSTATE dstStateID = GetBehaviorStateFromArgument(arguments, "dstStateID"); - - auto* dstStripUIArray = arguments->FindValue<AMFArrayValue>("dstStripUI"); - if (!dstStripUIArray) return; - - auto* xPositionValue = dstStripUIArray->FindValue<AMFDoubleValue>("x"); - auto* yPositionValue = dstStripUIArray->FindValue<AMFDoubleValue>("y"); - if (!xPositionValue || !yPositionValue) return; - - // x and y position 15 are just where the game puts the strip by default if none is given. - double yPosition = yPositionValue->GetDoubleValue(); - double xPosition = xPositionValue->GetDoubleValue(); - - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); - - // modelComponent->SplitStrip(srcActionIndex, srcStripID, srcStateID, dstStripID, dstStateID, behaviorID, yPosition, xPosition); - - // RequestUpdatedID(behaviorID); +void ControlBehaviors::SplitStrip(AMFArrayValue* arguments) { + SplitStripMessage splitStripMessage(arguments); } -void UpdateStripUI(AMFArrayValue* arguments) { - auto* uiArray = arguments->FindValue<AMFArrayValue>("ui"); - if (!uiArray) return; - - auto* xPositionValue = uiArray->FindValue<AMFDoubleValue>("x"); - auto* yPositionValue = uiArray->FindValue<AMFDoubleValue>("y"); - if (!xPositionValue || !yPositionValue) return; - - double yPosition = yPositionValue->GetDoubleValue(); - double xPosition = xPositionValue->GetDoubleValue(); - - STRIPID stripID = GetStripIDFromArgument(arguments); - - BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); - - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); - - // modelComponent->UpdateUIOfStrip(stateID, stripID, xPosition, yPosition, behaviorID); - - // RequestUpdatedID(behaviorID); +void ControlBehaviors::UpdateStripUI(AMFArrayValue* arguments) { + UpdateStripUiMessage updateStripUiMessage(arguments); } -void AddAction(AMFArrayValue* arguments) { - auto* actionIndexAmf = arguments->FindValue<AMFDoubleValue>("actionIndex"); - if (!actionIndexAmf) return; - - uint32_t actionIndex = static_cast<uint32_t>(actionIndexAmf->GetDoubleValue()); - - STRIPID stripID = GetStripIDFromArgument(arguments); - - BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); - - std::string type = ""; - std::string valueParameterName = ""; - std::string valueParameterString = ""; - double valueParameterDouble = 0.0; - auto* action = arguments->FindValue<AMFArrayValue>("action"); - if (!action) return; - - for (auto& typeValueMap : action->GetAssociativeMap()) { - if (typeValueMap.first == "Type") { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; - type = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); - } else { - valueParameterName = typeValueMap.first; - // Message is the only known string parameter - if (valueParameterName == "Message") { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; - valueParameterString = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); - } else { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFDouble) continue; - valueParameterDouble = static_cast<AMFDoubleValue*>(typeValueMap.second)->GetDoubleValue(); - } - } - } - - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); - - // modelComponent->AddAction(stateID, stripID, type, valueParameterName, valueParameterString, valueParameterDouble, "", actionIndex, behaviorID); - - // RequestUpdatedID(behaviorID); +void ControlBehaviors::AddAction(AMFArrayValue* arguments) { + AddActionMessage addActionMessage(arguments); } -void MigrateActions(AMFArrayValue* arguments) { - auto* srcActionIndexAmf = arguments->FindValue<AMFDoubleValue>("srcActionIndex"); - if (!srcActionIndexAmf) return; - - uint32_t srcActionIndex = static_cast<uint32_t>(srcActionIndexAmf->GetDoubleValue()); - - STRIPID srcStripID = GetStripIDFromArgument(arguments, "srcStripID"); - - BEHAVIORSTATE srcStateID = GetBehaviorStateFromArgument(arguments, "srcStateID"); - - auto* dstActionIndexAmf = arguments->FindValue<AMFDoubleValue>("dstActionIndex"); - if (!dstActionIndexAmf) return; - - uint32_t dstActionIndex = static_cast<uint32_t>(dstActionIndexAmf->GetDoubleValue()); - - STRIPID dstStripID = GetStripIDFromArgument(arguments, "dstStripID"); - - BEHAVIORSTATE dstStateID = GetBehaviorStateFromArgument(arguments, "dstStateID"); - - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); - - // modelComponent->MigrateActions(srcActionIndex, srcStripID, srcStateID, dstActionIndex, dstStripID, dstStateID, behaviorID); - - // RequestUpdatedID(behaviorID); +void ControlBehaviors::MigrateActions(AMFArrayValue* arguments) { + MigrateActionsMessage migrateActionsMessage(arguments); } -void RearrangeStrip(AMFArrayValue* arguments) { - auto* srcActionIndexValue = arguments->FindValue<AMFDoubleValue>("srcActionIndex"); - uint32_t srcActionIndex = static_cast<uint32_t>(srcActionIndexValue->GetDoubleValue()); - - uint32_t stripID = GetStripIDFromArgument(arguments); - - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); - - auto* dstActionIndexValue = arguments->FindValue<AMFDoubleValue>("dstActionIndex"); - uint32_t dstActionIndex = static_cast<uint32_t>(dstActionIndexValue->GetDoubleValue()); - - BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); - - // modelComponent->RearrangeStrip(stateID, stripID, srcActionIndex, dstActionIndex, behaviorID); - - // RequestUpdatedID(behaviorID); +void ControlBehaviors::RearrangeStrip(AMFArrayValue* arguments) { + RearrangeStripMessage rearrangeStripMessage(arguments); } -void Add(AMFArrayValue* arguments) { - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); - - uint32_t behaviorIndex = 0; - auto* behaviorIndexAmf = arguments->FindValue<AMFDoubleValue>("BehaviorIndex"); - - if (!behaviorIndexAmf) return; - - behaviorIndex = static_cast<uint32_t>(behaviorIndexAmf->GetDoubleValue()); - - // modelComponent->AddBehavior(behaviorID, behaviorIndex, modelOwner); - - // SendBehaviorListToClient(); +void ControlBehaviors::Add(AMFArrayValue* arguments) { + AddMessage addMessage(arguments); } -void RemoveActions(AMFArrayValue* arguments) { - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); - - auto* actionIndexAmf = arguments->FindValue<AMFDoubleValue>("actionIndex"); - if (!actionIndexAmf) return; - - uint32_t actionIndex = static_cast<uint32_t>(actionIndexAmf->GetDoubleValue()); - - STRIPID stripID = GetStripIDFromArgument(arguments); - - BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); - - // modelComponent->RemoveAction(stateID, stripID, actionIndex, behaviorID); - - // RequestUpdatedID(behaviorID); +void ControlBehaviors::RemoveActions(AMFArrayValue* arguments) { + RemoveActionsMessage removeActionsMessage(arguments); } -void Rename(Entity* modelEntity, const SystemAddress& sysAddr, Entity* modelOwner, AMFArrayValue* arguments) { - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); - - auto* nameAmf = arguments->FindValue<AMFStringValue>("Name"); - if (!nameAmf) return; - - auto name = nameAmf->GetStringValue(); - - // modelComponent->Rename(behaviorID, name); - - SendBehaviorListToClient(modelEntity, sysAddr, modelOwner); - - // RequestUpdatedID(behaviorID); +void ControlBehaviors::Rename(Entity* modelEntity, const SystemAddress& sysAddr, Entity* modelOwner, AMFArrayValue* arguments) { + RenameMessage renameMessage(arguments); } // TODO This is also supposed to serialize the state of the behaviors in progress but those aren't implemented yet -void SendBehaviorBlocksToClient(ModelComponent* modelComponent, const SystemAddress& sysAddr, Entity* modelOwner, AMFArrayValue* arguments) { - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); +void ControlBehaviors::SendBehaviorBlocksToClient(ModelComponent* modelComponent, const SystemAddress& sysAddr, Entity* modelOwner, AMFArrayValue* arguments) { + // uint32_t behaviorID = ControlBehaviors::GetBehaviorIDFromArgument(arguments); // auto modelBehavior = modelComponent->FindBehavior(behaviorID); @@ -496,47 +246,26 @@ void SendBehaviorBlocksToClient(ModelComponent* modelComponent, const SystemAddr // GameMessages::SendUIMessageServerToSingleClient(modelOwner, sysAddr, "UpdateBehaviorBlocks", &behaviorInfo); } -void UpdateAction(AMFArrayValue* arguments) { - std::string type = ""; - std::string valueParameterName = ""; - std::string valueParameterString = ""; - double valueParameterDouble = 0.0; - auto* actionAsArray = arguments->FindValue<AMFArrayValue>("action"); - if (!actionAsArray) return; - for (auto& typeValueMap : actionAsArray->GetAssociativeMap()) { - if (typeValueMap.first == "Type") { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; - type = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); - } else { - valueParameterName = typeValueMap.first; - // Message is the only known string parameter - if (valueParameterName == "Message") { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; - valueParameterString = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); - } else { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFDouble) continue; - valueParameterDouble = static_cast<AMFDoubleValue*>(typeValueMap.second)->GetDoubleValue(); - } +void ControlBehaviors::UpdateAction(AMFArrayValue* arguments) { + UpdateActionMessage updateActionMessage(arguments); + auto* blockDefinition = GetBlockInfo(updateActionMessage.GetType()); + + if (updateActionMessage.GetValueParameterString().size() > 0) { + if (updateActionMessage.GetValueParameterString().size() < blockDefinition->GetMinimumValue() || + updateActionMessage.GetValueParameterString().size() > blockDefinition->GetMaximumValue()) { + Game::logger->Log("ControlBehaviors", "Updated block %s is out of range. Ignoring update", updateActionMessage.GetType().c_str()); + return; + } + } else { + if (updateActionMessage.GetValueParameterDouble() < blockDefinition->GetMinimumValue() || + updateActionMessage.GetValueParameterDouble() > blockDefinition->GetMaximumValue()) { + Game::logger->Log("ControlBehaviors", "Updated block %s is out of range. Ignoring update", updateActionMessage.GetType().c_str()); + return; } } - - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); - - auto* actionIndexValue = arguments->FindValue<AMFDoubleValue>("actionIndex"); - if (!actionIndexValue) return; - - uint32_t actionIndex = static_cast<uint32_t>(actionIndexValue->GetDoubleValue()); - - STRIPID stripID = GetStripIDFromArgument(arguments); - - BEHAVIORSTATE stateID = GetBehaviorStateFromArgument(arguments); - - // modelComponent->UpdateAction(stateID, stripID, type, valueParameterName, valueParameterString, valueParameterDouble, "", actionIndex, behaviorID); - - // RequestUpdatedID(behaviorID); } -void MoveToInventory(ModelComponent* modelComponent, const SystemAddress& sysAddr, Entity* modelOwner, AMFArrayValue* arguments) { +void ControlBehaviors::MoveToInventory(ModelComponent* modelComponent, const SystemAddress& sysAddr, Entity* modelOwner, AMFArrayValue* arguments) { // This closes the UI menu should it be open while the player is removing behaviors AMFArrayValue args; @@ -545,20 +274,13 @@ void MoveToInventory(ModelComponent* modelComponent, const SystemAddress& sysAdd GameMessages::SendUIMessageServerToSingleClient(modelOwner, modelOwner->GetParentUser()->GetSystemAddress(), "ToggleBehaviorEditor", &args); - uint32_t behaviorID = GetBehaviorIDFromArgument(arguments); - - auto* behaviorIndexValue = arguments->FindValue<AMFDoubleValue>("BehaviorIndex"); - if (!behaviorIndexValue) return; - - uint32_t behaviorIndex = static_cast<uint32_t>(behaviorIndexValue->GetDoubleValue()); - - // modelComponent->MoveBehaviorToInventory(behaviorID, behaviorIndex, modelOwner); + MoveToInventoryMessage moveToInventoryMessage(arguments); SendBehaviorListToClient(modelComponent->GetParent(), sysAddr, modelOwner); } void ControlBehaviors::ProcessCommand(Entity* modelEntity, const SystemAddress& sysAddr, AMFArrayValue* arguments, std::string command, Entity* modelOwner) { - if (!modelEntity || !modelOwner || !arguments) return; + if (!isInitialized || !modelEntity || !modelOwner || !arguments) return; auto* modelComponent = modelEntity->GetComponent<ModelComponent>(); if (!modelComponent) return; @@ -600,3 +322,135 @@ void ControlBehaviors::ProcessCommand(Entity* modelEntity, const SystemAddress& else Game::logger->Log("ControlBehaviors", "Unknown behavior command (%s)\n", command.c_str()); } + +ControlBehaviors::ControlBehaviors() { + auto blocksDefStreamBuffer = Game::assetManager->GetFileAsBuffer("ui\\ingame\\blocksdef.xml"); + if (!blocksDefStreamBuffer.m_Success) { + Game::logger->Log("ControlBehaviors", "failed to open blocksdef"); + return; + } + std::istream blocksBuffer(&blocksDefStreamBuffer); + if (!blocksBuffer.good()) { + Game::logger->Log("ControlBehaviors", "Blocks buffer is not good!"); + return; + } + + tinyxml2::XMLDocument m_Doc; + + std::string read{}; + + std::string buffer{}; + bool commentBlockStart = false; + while (std::getline(blocksBuffer, read)) { + // tinyxml2 should handle comment blocks but the client has one that fails the processing. + // This preprocessing just removes all comments from the read file out of an abundance of caution. + if (read.find("<!--") != std::string::npos) { + commentBlockStart = true; + } + if (read.find("-->") != std::string::npos) { + commentBlockStart = false; + continue; + } + if (!commentBlockStart) buffer += read; + } + + auto ret = m_Doc.Parse(buffer.c_str()); + if (ret == tinyxml2::XML_SUCCESS) { + Game::logger->LogDebug("ControlBehaviors", "Successfully parsed the blocksdef file!"); + } else { + Game::logger->Log("Character", "Failed to parse BlocksDef xmlData due to error %i!", ret); + return; + } + auto* blockLibrary = m_Doc.FirstChildElement(); + if (!blockLibrary) { + Game::logger->Log("ControlBehaviors", "No Block Library child element found."); + return; + } + + // Now parse the blocksdef for the cheat detection server side. + // The client does these checks, but a bad actor can bypass the client checks + auto* blockSections = blockLibrary->FirstChildElement(); + while (blockSections) { + auto* block = blockSections->FirstChildElement(); + std::string blockName{}; + while (block) { + blockName = block->Name(); + + BlockDefinition* blockDefinition = new BlockDefinition(); + std::string name{}; + std::string typeName{}; + + auto* argument = block->FirstChildElement("Argument"); + if (argument) { + auto* defaultDefinition = argument->FirstChildElement("DefaultValue"); + if (defaultDefinition) blockDefinition->SetDefaultValue(defaultDefinition->GetText()); + + auto* typeDefinition = argument->FirstChildElement("Type"); + if (typeDefinition) typeName = typeDefinition->GetText(); + + auto* nameDefinition = argument->FirstChildElement("Name"); + if (nameDefinition) name = nameDefinition->GetText(); + + // Now we parse the blocksdef file for the relevant information + if (typeName == "String") { + blockDefinition->SetMaximumValue(50); // The client has a hardcoded limit of 50 characters in a string field + } else if (typeName == "Float" || typeName == "Integer") { + auto* maximumDefinition = argument->FirstChildElement("Maximum"); + if (maximumDefinition) blockDefinition->SetMaximumValue(std::stof(maximumDefinition->GetText())); + + auto* minimumDefinition = argument->FirstChildElement("Minimum"); + if (minimumDefinition) blockDefinition->SetMinimumValue(std::stof(minimumDefinition->GetText())); + } else if (typeName == "Enumeration") { + auto* values = argument->FirstChildElement("Values"); + if (values) { + auto* value = values->FirstChildElement("Value"); + while (value) { + if (value->GetText() == blockDefinition->GetDefaultValue()) blockDefinition->GetDefaultValue() = std::to_string(blockDefinition->GetMaximumValue()); + blockDefinition->SetMaximumValue(blockDefinition->GetMaximumValue() + 1); + value = value->NextSiblingElement("Value"); + } + blockDefinition->SetMaximumValue(blockDefinition->GetMaximumValue() - 1); // Maximum value is 0 indexed + } else { + values = argument->FirstChildElement("EnumerationSource"); + if (!values) { + Game::logger->Log("ControlBehaviors", "Failed to parse EnumerationSource from block (%s)", blockName.c_str()); + continue; + } + + auto* serviceNameNode = values->FirstChildElement("ServiceName"); + if (!serviceNameNode) { + Game::logger->Log("ControlBehaviors", "Failed to parse ServiceName from block (%s)", blockName.c_str()); + continue; + } + + std::string serviceName = serviceNameNode->GetText(); + if (serviceName == "GetBehaviorSoundList") { + auto res = CDClientDatabase::ExecuteQuery("SELECT MAX(id) as countSounds FROM UGBehaviorSounds;"); + blockDefinition->SetMaximumValue(res.getIntField("countSounds")); + blockDefinition->SetDefaultValue("0"); + } else { + Game::logger->Log("ControlBehaviors", "Unsupported Enumeration ServiceType (%s)", serviceName.c_str()); + continue; + } + } + } else { + Game::logger->Log("ControlBehaviors", "Unsupported block value type (%s)!", typeName.c_str()); + continue; + } + } + blockTypes.insert(std::make_pair(blockName, blockDefinition)); + block = block->NextSiblingElement(); + } + blockSections = blockSections->NextSiblingElement(); + } + isInitialized = true; + Game::logger->LogDebug("ControlBehaviors", "Created all base block classes"); + for (auto b : blockTypes) { + Game::logger->LogDebug("ControlBehaviors", "block name is %s default %s min %f max %f", b.first.c_str(), b.second->GetDefaultValue().c_str(), b.second->GetMinimumValue(), b.second->GetMaximumValue()); + } +} + +BlockDefinition* ControlBehaviors::GetBlockInfo(const BlockName& blockName) { + auto blockDefinition = blockTypes.find(blockName); + return blockDefinition != blockTypes.end() ? blockDefinition->second : &BlockDefinition::blockDefinitionDefault; +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.h b/dGame/dPropertyBehaviors/ControlBehaviors.h index d487f929..a562aafe 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviors.h +++ b/dGame/dPropertyBehaviors/ControlBehaviors.h @@ -3,15 +3,23 @@ #ifndef __CONTROLBEHAVIORS__H__ #define __CONTROLBEHAVIORS__H__ +#include <map> #include <string> -#include "RakNetTypes.h" +#include "Singleton.h" -class Entity; class AMFArrayValue; +class BlockDefinition; +class Entity; class ModelComponent; +class SystemAddress; -namespace ControlBehaviors { +// Type definition to clarify what is used where +typedef std::string BlockName; //! A block name + +class ControlBehaviors: public Singleton<ControlBehaviors> { +public: + ControlBehaviors(); /** * @brief Main driver for processing Property Behavior commands * @@ -22,6 +30,39 @@ namespace ControlBehaviors { * @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); + + /** + * @brief Gets a blocks parameter values by the name + * No exception will be thrown in this function. + * + * @param blockName The block name to get the parameters of + * + * @return A pair of the block parameter name to its typing + */ + BlockDefinition* GetBlockInfo(const BlockName& blockName); +private: + void RequestUpdatedID(int32_t behaviorID, ModelComponent* modelComponent, Entity* modelOwner, const SystemAddress& sysAddr); + void SendBehaviorListToClient(Entity* modelEntity, const SystemAddress& sysAddr, Entity* modelOwner); + void ModelTypeChanged(AMFArrayValue* arguments, ModelComponent* ModelComponent); + void ToggleExecutionUpdates(); + void AddStrip(AMFArrayValue* arguments); + void RemoveStrip(AMFArrayValue* arguments); + void MergeStrips(AMFArrayValue* arguments); + void SplitStrip(AMFArrayValue* arguments); + void UpdateStripUI(AMFArrayValue* arguments); + void AddAction(AMFArrayValue* arguments); + void MigrateActions(AMFArrayValue* arguments); + void RearrangeStrip(AMFArrayValue* arguments); + void Add(AMFArrayValue* arguments); + void RemoveActions(AMFArrayValue* arguments); + void Rename(Entity* modelEntity, const SystemAddress& sysAddr, Entity* modelOwner, AMFArrayValue* arguments); + void SendBehaviorBlocksToClient(ModelComponent* modelComponent, const SystemAddress& sysAddr, Entity* modelOwner, AMFArrayValue* arguments); + void UpdateAction(AMFArrayValue* arguments); + void MoveToInventory(ModelComponent* modelComponent, const SystemAddress& sysAddr, Entity* modelOwner, AMFArrayValue* arguments); + std::map<BlockName, BlockDefinition*> blockTypes{}; + + // If false, property behaviors will not be able to be edited. + bool isInitialized = false; }; #endif //!__CONTROLBEHAVIORS__H__ diff --git a/tests/dGameTests/CMakeLists.txt b/tests/dGameTests/CMakeLists.txt index ba7d4d1c..b1fdaa07 100644 --- a/tests/dGameTests/CMakeLists.txt +++ b/tests/dGameTests/CMakeLists.txt @@ -8,6 +8,8 @@ list(APPEND DGAMETEST_SOURCES ${DCOMPONENTS_TESTS}) add_subdirectory(dGameMessagesTests) list(APPEND DGAMETEST_SOURCES ${DGAMEMESSAGES_TESTS}) +file(COPY ${GAMEMESSAGE_TESTBITSTREAMS} DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) + # Add the executable. Remember to add all tests above this! add_executable(dGameTests ${DGAMETEST_SOURCES}) diff --git a/tests/dGameTests/dGameMessagesTests/CMakeLists.txt b/tests/dGameTests/dGameMessagesTests/CMakeLists.txt index 2417d29c..54c43777 100644 --- a/tests/dGameTests/dGameMessagesTests/CMakeLists.txt +++ b/tests/dGameTests/dGameMessagesTests/CMakeLists.txt @@ -5,5 +5,10 @@ SET(DGAMEMESSAGES_TESTS get_filename_component(thisFolderName ${CMAKE_CURRENT_SOURCE_DIR} NAME) list(TRANSFORM DGAMEMESSAGES_TESTS PREPEND "${thisFolderName}/") +# Copy test files to testing directory +add_subdirectory(TestBitStreams) +list(TRANSFORM GAMEMESSAGE_TESTBITSTREAMS PREPEND "${thisFolderName}/") +set(GAMEMESSAGE_TESTBITSTREAMS ${GAMEMESSAGE_TESTBITSTREAMS} PARENT_SCOPE) + # Export to parent scope set(DGAMEMESSAGES_TESTS ${DGAMEMESSAGES_TESTS} PARENT_SCOPE) diff --git a/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp b/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp index 3d8b2d04..7905c19a 100644 --- a/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp +++ b/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp @@ -1,15 +1,50 @@ #include "GameMessages.h" #include "GameDependencies.h" -#include <gtest/gtest.h> +#include "AMFDeserialize.h" -class GameMessageTests : public GameDependenciesTest { - protected: - void SetUp() override { - SetUpDependencies(); - } - void TearDown() override { - TearDownDependencies(); +#include "AddActionMessage.h" +#include "AddStripMessage.h" +#include "AddMessage.h" +#include "MigrateActionsMessage.h" +#include "MoveToInventoryMessage.h" +#include "MergeStripsMessage.h" +#include "RearrangeStripMessage.h" +#include "RemoveActionsMessage.h" +#include "RemoveStripMessage.h" +#include "RenameMessage.h" +#include "SplitStripMessage.h" +#include "UpdateActionMessage.h" +#include "UpdateStripUiMessage.h" + +#include <gtest/gtest.h> +#include <fstream> + +class GameMessageTests: public GameDependenciesTest { +protected: + void SetUp() override { + SetUpDependencies(); + } + void TearDown() override { + TearDownDependencies(); + } + + std::string ReadFromFile(std::string filename) { + std::ifstream file(filename, std::ios::binary); + std::string readFile; + while (file.good()) { + char readCharacter = file.get(); + readFile.push_back(readCharacter); } + + return readFile; + } + + AMFArrayValue* ReadArrayFromBitStream(RakNet::BitStream* inStream) { + AMFDeserialize des; + AMFValue* readArray = des.Read(inStream); + EXPECT_EQ(readArray->GetValueType(), AMFValueType::AMFArray); + return static_cast<AMFArrayValue*>(readArray); + } }; /** @@ -50,3 +85,143 @@ TEST_F(GameMessageTests, SendBlueprintLoadItemResponse) { ASSERT_EQ(bitStream->GetNumberOfUnreadBits(), 0); } + +TEST_F(GameMessageTests, ControlBehaviorAddStrip) { + auto data = ReadFromFile("addStrip"); + RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); + AddStripMessage addStrip(ReadArrayFromBitStream(&inStream)); + ASSERT_FLOAT_EQ(addStrip.GetXPosition(), 50.65); + ASSERT_FLOAT_EQ(addStrip.GetYPosition(), 178.05); + ASSERT_EQ(addStrip.GetStripId(), 0); + ASSERT_EQ(static_cast<uint32_t>(addStrip.GetStateId()), 0); + ASSERT_EQ(addStrip.GetBehaviorId(), -1); + ASSERT_EQ(addStrip.GetType(), "DropImagination"); + ASSERT_EQ(addStrip.GetValueParameterName(), "Amount"); + ASSERT_EQ(addStrip.GetValueParameterString(), ""); + ASSERT_FLOAT_EQ(addStrip.GetValueParameterDouble(), 1.0); +} + +TEST_F(GameMessageTests, ControlBehaviorRemoveStrip) { + auto data = ReadFromFile("removeStrip"); + RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); + RemoveStripMessage removeStrip(ReadArrayFromBitStream(&inStream)); + ASSERT_EQ(static_cast<int32_t>(removeStrip.GetStripId()), 1); + ASSERT_EQ(static_cast<int32_t>(removeStrip.GetBehaviorState()), 0); + ASSERT_EQ(removeStrip.GetBehaviorId(), -1); +} + +TEST_F(GameMessageTests, ControlBehaviorMergeStrips) { + auto data = ReadFromFile("mergeStrips"); + RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); + MergeStripsMessage mergeStrips(ReadArrayFromBitStream(&inStream)); + ASSERT_EQ(mergeStrips.GetSrcStripID(), 2); + ASSERT_EQ(mergeStrips.GetDstStripID(), 0); + ASSERT_EQ(static_cast<uint32_t>(mergeStrips.GetSrcStateID()), 0); + ASSERT_EQ(static_cast<uint32_t>(mergeStrips.GetDstStateID()), 0); + ASSERT_EQ(mergeStrips.GetDstActionIndex(), 0); + ASSERT_EQ(mergeStrips.GetBehaviorID(), -1); +} + +TEST_F(GameMessageTests, ControlBehaviorSplitStrip) { + auto data = ReadFromFile("splitStrip"); + RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); + SplitStripMessage splitStrip(ReadArrayFromBitStream(&inStream)); + ASSERT_EQ(splitStrip.GetBehaviorId(), -1); + + ASSERT_FLOAT_EQ(splitStrip.GetXPosition(), 275.65); + ASSERT_FLOAT_EQ(splitStrip.GetYPosition(), 28.7); + ASSERT_EQ(splitStrip.GetSrcStripId(), 0); + ASSERT_EQ(splitStrip.GetDstStripId(), 2); + ASSERT_EQ(static_cast<uint32_t>(splitStrip.GetSrcStateId()), 0); + ASSERT_EQ(static_cast<uint32_t>(splitStrip.GetDstStateId()), 0); + ASSERT_EQ(splitStrip.GetSrcActionIndex(), 1); +} + +TEST_F(GameMessageTests, ControlBehaviorUpdateStripUI) { + auto data = ReadFromFile("updateStripUI"); + RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); + UpdateStripUiMessage updateStripUi(ReadArrayFromBitStream(&inStream)); + ASSERT_FLOAT_EQ(updateStripUi.GetXPosition(), 116.65); + ASSERT_FLOAT_EQ(updateStripUi.GetYPosition(), 35.35); + ASSERT_EQ(updateStripUi.GetStripID(), 0); + ASSERT_EQ(static_cast<uint32_t>(updateStripUi.GetStateID()), 0); + ASSERT_EQ(updateStripUi.GetBehaviorID(), -1); +} + +TEST_F(GameMessageTests, ControlBehaviorAddAction) { + auto data = ReadFromFile("addAction"); + RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); + AddActionMessage addAction(ReadArrayFromBitStream(&inStream)); + ASSERT_EQ(addAction.GetActionIndex(), 3); + ASSERT_EQ(addAction.GetStripId(), 0); + ASSERT_EQ(static_cast<uint32_t>(addAction.GetStateId()), 0); + ASSERT_EQ(addAction.GetType(), "DoDamage"); + ASSERT_EQ(addAction.GetValueParameterName(), ""); + ASSERT_EQ(addAction.GetValueParameterString(), ""); + ASSERT_EQ(addAction.GetValueParameterDouble(), 0.0); + ASSERT_EQ(addAction.GetBehaviorId(), -1); +} + +TEST_F(GameMessageTests, ControlBehaviorMigrateActions) { + auto data = ReadFromFile("migrateActions"); + RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); + MigrateActionsMessage migrateActions(ReadArrayFromBitStream(&inStream)); + ASSERT_EQ(migrateActions.GetSrcActionIndex(), 1); + ASSERT_EQ(migrateActions.GetDstActionIndex(), 2); + ASSERT_EQ(migrateActions.GetSrcStripID(), 1); + ASSERT_EQ(migrateActions.GetDstStripID(), 0); + ASSERT_EQ(static_cast<uint32_t>(migrateActions.GetSrcStateID()), 0); + ASSERT_EQ(static_cast<uint32_t>(migrateActions.GetDstStateID()), 0); + ASSERT_EQ(migrateActions.GetBehaviorID(), -1); +} + +TEST_F(GameMessageTests, ControlBehaviorRearrangeStrip) { + auto data = ReadFromFile("rearrangeStrip"); + RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); + RearrangeStripMessage rearrangeStrip(ReadArrayFromBitStream(&inStream)); + ASSERT_EQ(rearrangeStrip.GetSrcActionIndex(), 2); + ASSERT_EQ(rearrangeStrip.GetDstActionIndex(), 1); + ASSERT_EQ(rearrangeStrip.GetStripID(), 0); + ASSERT_EQ(rearrangeStrip.GetBehaviorID(), -1); + ASSERT_EQ(static_cast<uint32_t>(rearrangeStrip.GetStateID()), 0); +} + +TEST_F(GameMessageTests, ControlBehaviorAdd) { + auto data = ReadFromFile("add"); + RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); + AddMessage add(ReadArrayFromBitStream(&inStream)); + ASSERT_EQ(add.GetBehaviorId(), 10446); + ASSERT_EQ(add.GetBehaviorIndex(), 0); +} + +TEST_F(GameMessageTests, ControlBehaviorRemoveActions) { + auto data = ReadFromFile("removeActions"); + RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); + RemoveActionsMessage removeActions(ReadArrayFromBitStream(&inStream)); + ASSERT_EQ(removeActions.GetBehaviorID(), -1); + ASSERT_EQ(removeActions.GetActionIndex(), 1); + ASSERT_EQ(removeActions.GetStripID(), 0); + ASSERT_EQ(static_cast<uint32_t>(removeActions.GetStateID()), 0); +} + +TEST_F(GameMessageTests, ControlBehaviorRename) { + auto data = ReadFromFile("rename"); + RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); + RenameMessage rename(ReadArrayFromBitStream(&inStream)); + ASSERT_EQ(rename.GetName(), "test"); + ASSERT_EQ(rename.GetBehaviorID(), -1); +} + +TEST_F(GameMessageTests, ControlBehaviorUpdateAction) { + auto data = ReadFromFile("updateAction"); + RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); + UpdateActionMessage updateAction(ReadArrayFromBitStream(&inStream)); + ASSERT_EQ(updateAction.GetType(), "FlyDown"); + ASSERT_EQ(updateAction.GetValueParameterName(), "Distance"); + ASSERT_EQ(updateAction.GetValueParameterString(), ""); + ASSERT_EQ(updateAction.GetValueParameterDouble(), 50.0); + ASSERT_EQ(updateAction.GetBehaviorID(), -1); + ASSERT_EQ(updateAction.GetActionIndex(), 1); + ASSERT_EQ(updateAction.GetStripID(), 0); + ASSERT_EQ(static_cast<uint32_t>(updateAction.GetStateID()), 0); +} diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/CMakeLists.txt b/tests/dGameTests/dGameMessagesTests/TestBitStreams/CMakeLists.txt new file mode 100644 index 00000000..e32ed3ef --- /dev/null +++ b/tests/dGameTests/dGameMessagesTests/TestBitStreams/CMakeLists.txt @@ -0,0 +1,24 @@ +set(GAMEMESSAGE_TESTBITSTREAMS +"sendBehaviorListToClient" +"modelTypeChanged" +"toggleExecutionUpdates" +"addStrip" +"removeStrip" +"mergeStrips" +"splitStrip" +"updateStripUI" +"addAction" +"migrateActions" +"rearrangeStrip" +"add" +"removeActions" +"rename" +"updateAction" +) + +# Get the folder name and prepend it to the files above +get_filename_component(thisFolderName ${CMAKE_CURRENT_SOURCE_DIR} NAME) +list(TRANSFORM GAMEMESSAGE_TESTBITSTREAMS PREPEND "${thisFolderName}/") + +# Export our list of files +set(GAMEMESSAGE_TESTBITSTREAMS ${GAMEMESSAGE_TESTBITSTREAMS} PARENT_SCOPE) diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/add b/tests/dGameTests/dGameMessagesTests/TestBitStreams/add new file mode 100644 index 0000000000000000000000000000000000000000..13c0dd922c3979d837799c25c92ac420f602bd1f GIT binary patch literal 1024 zcmd;N6m?3?NG!|DFY<I@<2E!fF)?FgW?*1QOi2NfV8B?$z`)1`WD0<}ObiJinu&=6 z%w;&>0HlG~!I2Tj0AW^6mI($x6&wna6$BU<IUWlzu&{vm49-{IN;x<%uo$);U=RQr z#}UCecYO>$P?Nw3BcKsLV-y~+@T<Al0M$E59ARJtnb+7LvAy<q0njKOg9eCEObiY{ z2Q%;&mn4>?db+RzRRMvB10%>$K(_~%6lE5G#ZZVEAg>&V^ME)Sh;z<`PQG5xzyP!j z1xP@74X3Y80?8-*TXy0<kZys}7EpTTq61)gpl`uo#llvwc`)^stG|QgxuNn5s@AI% za_29DaTTBpb|@_%&~gxD4>V{Qn1JFSK1|#Jst!hh<Y9Kh#E@xp|H9mT<Bj5Bkhw4b zvk&H9bnzX>AnIZMg{e3A4+$5TdYFGLCW?a1FSGFmhX+g^Myo^hO_&5x2Qx<is&50- zK7r#LU~^!!wrM5UyjM|eU|Il_Jb>VfndlV;V7h|oXXI*|j4b}t1elyA_1T`1y5k(S z`krG{^wWJH`8f|#>_PO0euz65p!UP)2M;As!f67-RIt4k|E7TH3$fF|bj<U^w(n$} z#69{T@eR{=0qRc}AC!wg0G6ASW2?aWA66weraimvoc8SVp`aaa4%&9zb@q6e;RH)B w4yoc0cR<rm!ZZaGK7;X}L&)*@z#hW?56a3w0CQ&-O90qDf&B~}pme<z0KNDLEdT%j literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/addAction b/tests/dGameTests/dGameMessagesTests/TestBitStreams/addAction new file mode 100644 index 0000000000000000000000000000000000000000..d91d0ee451448a87cab9c2caded85a01a15ea26b GIT binary patch literal 1024 zcmd;N<V{R2$;{8=WaJE~EJ$S&bjf!~%uP&BW#lg|DatJHbYW$H0&$2+&%Bh>3aB85 zgQ!z#Mq*iJevzjO15ig|Nh*>KMoysC#FP|AuoXZysz4s59r%sofEX7Ha+m`a8$}!# zk(EH*jYQP|+2uf-2gK1poO3R8^7VQK1{NS28Aw1m4X3Y80?8-*TXy0<kZys}7EpTT zq61)g1E~5H3tPeF!PHx>{tlMsh8eDEy-Fc>{xTR>0m@*9(gFf42SN6Ld;tPXKn&u; z#2r9_NB|@cvl~em&P4Yw%-uKMC>{ox3j;9wVE#oH-*F709_C+|dV~LvaDl0Z`PX8i zDA@cm8*gxUz~o`HI#l0;Nf31~a|EFJHbCtYIL-k!2S#g~R)WoY71ai&1sEYFelZih z!r;Kb0@KgP)ixO<0~3F0!oc7(sn7P5)E(!r)%P5uqMz;q$<KL^Vh^G}^h4ai0JR@R zKX@pC5>68srh@IY_%{ViUx=L!remHTwtXk-B<|4%iEo&`3s8T;_-r7{fB-}b0I_mx z6<GhnsszWhXV;z6o_#(PwByY|+pfFL9uG5|7@+CJAypjW4k$lingR-+!T8T1<oJAG b58)>;EC;7sm^-^z0>JhiIKt2YO4nNfCR7_k literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/addStrip b/tests/dGameTests/dGameMessagesTests/TestBitStreams/addStrip new file mode 100644 index 0000000000000000000000000000000000000000..60ba6521b2c17299eb4d6ced8ac2edd5a427a1a9 GIT binary patch literal 1024 zcmd;N<Ss5L$}Hey<WEd4$;{6y=458%WaM?s%`eR>VPyb=5B8iPl?AD6@-9XB1)jNy z>6v+nAhnFFrJ0<J%$2OOW&(j@ngeqMtBElX1baF#vSy}0wKFg<a&a>9z*X@f6!C*C z_jG})6m?3?NG!|DFY<I@07@p7q#{W&asZu^n356<a<KyzB_a+eN+7OBCToD4av;tF z;%FewITt$ldOZUJ3y_TrB%qvz(^n^f<P-iaJMkY#w?JtNC_Qu00kFIQRQ-yDtzh$D z>Md7)2g`HA3|F;YrI0&+8H}p{Ww1kO0fCl-AbUU_1py`?2JvCy4j@4!0FsB<jU)_b zqWc%-?i+6u4};8w0hoO-|DucUI0jJ<^Dj)j!GB1&z|_P1YcWw2Y<`)IH#j_C@-SK* zs&B$1h&q@#0#JP$p!NwI=Kz}nqqR*d!REb+Y6H^(j1UvQn2BCtaA078>1X6>n+%eH zi9a=AU~rn$XM0NOj&s=RdyY}jPxpc3=R8QU2hkt;A?{#++7F{2Jd{8QrwI&G!S-7G zn*ydU#7+m(G0zX%zLRwl_vnMfH%#9Js6SzRHjrgN0HOteSUI)|tp8zEf@9jV>&|J< zJ|7C&@#dgy*Ij3ihZ#-`(DdSvDh_c6l%Ft70fo<C{O1sId_J&;@Dmu8gVQa{on0&e N5O*JD=m4ebtpMsK9iadK literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/mergeStrips b/tests/dGameTests/dGameMessagesTests/TestBitStreams/mergeStrips new file mode 100644 index 0000000000000000000000000000000000000000..062fd10b5d3c351b4c28ddc195f98bb0659beac5 GIT binary patch literal 1024 zcmd;N6fG`F4lXImEbw$;Wq<$&QK!_5#Inr%B2O0v(Ujtn;F83WRD?VOL=UQ%EKr?e za!F=>o@ZW4Y6Z+JsD2dl85p^N7UiZErKf^zE{0h9!Jd&1B%YaG1T-3AR&h=y&~~71 zxZ@a*9mijc;xZ8jMh>6}i76>yJrHA&$r>Q19EkIPI2wp^&V^3CUeCb50%Rit2`H!G z^wmiq`GkMVPW%VbEl}D5O3z$$04#3+Rlj0kE7&}kddt<{!SW#gf`O{_Duvwn%V1mu zD1#kJ3kb9v1la@f1qd(!F^CTncK`_@0gyb*ZX{ti6WzZsci(uUco<|Z48ZJz`4?S$ z$1#X{n15mF4gN#I1*RV6UyF&NVDrmtyuslClZVmjP<<07LDa#_5rFF30JTrxI0x7q z7_Dtu2{!LlR2!HUV1$_X#Z2@Hg98H#Og|%6+hmXoO#G<{1B26~KHF1Lcbvmk-*b$L ze!34NKj%S;J&69$4{-+r)P5NK;GqOcI89)f3bxnc-xM%?A$B^Lj`<%l`=qRsxJMr( zzG3<<K>Z2hvw<uF0uU_##LBT%VEqrP5**W>U3X4<_W4lIjyDHwyY4!BJj`%nfTkCR tRB?zqp!|es3MhOA<3ERx<MV+%grC5$9Gq@p?(AX-0Nb}=qY_yERsga49ZdiL literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/migrateActions b/tests/dGameTests/dGameMessagesTests/TestBitStreams/migrateActions new file mode 100644 index 0000000000000000000000000000000000000000..217f44d95ab71b27de401415bd1127a420b4c72a GIT binary patch literal 1024 zcmd;Nlr1hwc1$kG%+K@8OG&L@WdMT@_M$-X;F6-u0#6r&m{V#-Vp(Q>k*5oTXi9NO za7kiGDqNm{0ip+0OctmP(|iU8h<;@A85kJ(fR^WGrWXN?faodC$pqR0R0VSc&=Mp^ z@E4=FK*WKO1872GN(xvH#4E^T4Ukg~#Cbp*4a7O;LMLCZXJB9fvXOxVl+$qf>LieS z!oOuF{sZY2C~X0yXD&JbmN$T^U$L+iY#vO#<?8QXd2X2Ds@AI%a_29DaTTBpb|@_% z&~gxD56BlFzy!n~K1|#JB!~n+@-VxRgyBqd|H9mT<Bj5Bkhw4bvk&H9bnzX>AnIZM zg{e3A4+$5TdYFGLCW?a1FSGFmhX+g^Myo^hO_&5x2Qx<is&50-K7r#LU~^!!wrM5U zyjM|eU|N6?V&WGw(JKrN3@kAHj9hJ#K{7D$rzQ*xPLuj<Pf6Wz4qJWCF)I4$K9KyJ z2PyU-`a?g&9Sl(WVf2HC5-8y`fnh4xUW<QI!1RUK>0ml${U4FjvQFY2eUSKu>AL{+ zCydVqvJ417v;Yt*$5w&$Kdee{OnY|SIqli!LqR*<9JKAa>+JC`!-)Z!UK~=zA?|?k p6Q(Jk@EMH%972xI2lfzt0>g4}x`ny3izNVT--dk*9iVi*6#%+o9`*nL literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/modelTypeChanged b/tests/dGameTests/dGameMessagesTests/TestBitStreams/modelTypeChanged new file mode 100644 index 0000000000000000000000000000000000000000..ef282ce2757f0f91ef87f904b07b6db11cfd7697 GIT binary patch literal 1024 zcmd;N6!y(eNzDnVEJ$T#fC5GVAR`wh?3|I9m!6sekz?cr(nYDc`DLlWB}JJ9i6yC? zE^v*a#YM@%C8%PuDa9p@$t9Wjd7gPGsTDA_4x&JDun|c58TmjKXQmecjezJW&dG$R zLbAjuH6yVsGr!2wg@L~q#WoQKMh>6}i76>ylOaw<CToD4av;tF;%FewITt$ldOZUJ z3y_TrB%qvz(^n^f<P-iaJMkY#w?JtNC_Qu00kFIQRQ-yDtzh$D>Md7)2g`#(4GdJR zS1IJqUk2kUKpE^%T0o%XAjlq&FF=3^h(UaqxC2NK34r8bb|VSHndtt7x%<W&#ls+T zVE|?y%)jX3JB~rr!~6?VZ}1-yE->{l|5{8G1)E=H;|&fEm^_SDhw7U!38D^WjsR5O z2B>`k$2q{}z-VpLO0apaqT0Z;03*c2FJ_`w7#tW_VEP%k+9rc!VB$|r7#N%;_1T`1 zy5k(S`krG{^wWJH`8f|#>_PO0euz65p!UP)2M;As!f67-RIt4k|E7TH3$fF|bd3N1 zyVqr%#69{T@eR{=0qRc}pABRg5P)b<CR2{B0_%TRmEf56?7DN>v(JZucDy-g+jZC3 z<6(vq12nxjq>4k_0p%x5Q$XP}82>qh9G?&DA^Ze}<=}J+b7vPz0N6f<{R|zTbiEY- D3ceex literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/rearrangeStrip b/tests/dGameTests/dGameMessagesTests/TestBitStreams/rearrangeStrip new file mode 100644 index 0000000000000000000000000000000000000000..06dda90b137e18dae0c1b41e46f13a57bc5a6ef0 GIT binary patch literal 1024 zcmd;Nlr1hwc1$kG%+K@8OG&L@Wq<$&{^F9N%mPmrm;i&QQ))(HS!RBbrwfB@N^uFM zrVsW&O^GF`NSYY=fW{T2CKeSX=B1|wgN$TIOi6+0&4ZeTsfz=s3#bgNz64BScL$nI z5eG(OolvhJQ8hqzIS}UoaWoL;oC}?Ny`F)A1;|DQ5>QUV>8q1K@(KTzo%j!=TcETB zl%Bch09f7ts(!`7R<L<6^_Hu@gXOtlhO1hyQplaZ48~P}GT5QCfI!PZkUbz@fB+K^ zgZMCU2aq5V0LjDbMiPcI(ftc^_l-A-he77T0L(s^f6>Kv9D}Hb`4^_%;6Ef>VCrH1 zwU{UhHowfq8yp@mc^It@)i+@hL><f=0jRzWQ2PXqbAZi((b}e!VDnx@wSj2?Mu>@D z%tWs+I54ol^fPj`O$N!p#GjflFgQ)>vppqs$2n~EJ;$i%r~5$ia~`DFgXj<a5O**@ z?T6719!j8u(*%a8V0$h8O##yvVyA=YnExTOPs%!pd-Or#8>a69)Soau8^|&s0MP<K ztQ=bf*8i|7!7=UGb?3BapAQA?cyrLU>#noM!we?|XnJu-6^FP3%1@Z4fWl`m{&NU9 eJ|Eaa_z4Wl!RZ#}&MuY!uze5qF?4{^^;Q6QY9CVo literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/removeActions b/tests/dGameTests/dGameMessagesTests/TestBitStreams/removeActions new file mode 100644 index 0000000000000000000000000000000000000000..56e158e5ec08c6615aa73733fc0cc81386f4c837 GIT binary patch literal 1024 zcmd;N6m?3?NG!|DFY<I@5Kl}l$;{95%u7kFU}XS<5BB`UB}JJ9o-R-U1_q!&Vo55J z03$C@X;Er!ep#v`*nnb)UIs=^AR{p)1tJP$qYC6PVwjEW8ccgQAjSoQ9OM9UFq#q( z2S#KiP*)&PH9&Sb5a$7LG!W;U3!Qwuo`Hb{$VLVdP)@_?tCK+T3ICRz_z$F8ptJ>) zp1J4%Sl$4te#OF8uz4``maD&m<+)*ot6Hy8$eq6o##Mka*rBw5K+8dpJs@9z022^{ z_%Lw?kRTEO$;0eM5{5I;{R?yVjW>#iLFU2$%s!ZZ(ZzQhgQ$o37pC6eKO|gW>S6x1 zm?#Q1zs$xP93C)v7_AP~H(?S)9n2g7sJ;zQ`vi`2fX#u?+NPCY^Ik=@foTCoh>2g! zM6WP7FtEV%Gjg>}2Fbw0pPDc*I8ExaJtcL=Ic)Vk$EfJ1`#|z@9;DcV=nwr6cQ8Qh zhtUrnN}z<(1cs?#doBJ=0n-;^r-SL3=Z9_I$vTO9^g-eqrtbpOpD;cf$TA=R(E>oM z99sp}|F9~-G40uP=d@>^4+ZUbbI`WyuCvF(3?~L?dT~e<hqwdEPnf2F!e=o4a|k&; dAJ{|q2@K1@=@#bBE|vhWeFu&(bb!+JRsfZm8chHI literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/removeStrip b/tests/dGameTests/dGameMessagesTests/TestBitStreams/removeStrip new file mode 100644 index 0000000000000000000000000000000000000000..46ca064086c0239b91e0ff03a8a3fbf2d82dd132 GIT binary patch literal 1024 zcmd;N6m?3?NG!|DFY<I@;4dyI$}I47VPyb=5B5NT#FA9F00RRfH&CW1H8;O3H5jB8 zRaUgPC^;BShipo5iDPm}W`3S$UP@{O)My3=QJ^^32xQawfTrhWrWXN?h3F~H$%Lqa zxru=R&B4en5OHAS0Gg1Pk^(jv><JX22FNQ1;yfUZ2I8D^p_8xIGcd3K*~mZw%4s-# zbrMKE;oq_o|ABN1l(vA<GZ!5I%Nsz|uUOa$HV>xWa`ktxJSfz_K-GGcLhk%!Fs=fW z!49Pb1X>P)>;d@#1ekyr#D|GHfCP~MNFHW4k}#Z!?q8U@Z@f`F3^Er6VD`cMi!Q$7 z7(_kHzcBR%{~_T5QxEg6#Y9oC`DHfV;P8OS!)SG=z6p~c>R{#wK=o~a+9z<F18feA z);6sKoA)ZJ4NMC#LQMQ(CVGXzfq@04pOLF=GDrp{{?vql!D&*T?J21{&S9(XIYvc4 z-3OAN^B~0@M1SaqxPt*|Ka76xPy!{KCNN9|+iUS}3YfkSI~`2N%nwhwChH{b(Fcid zn7#{8f5P}|Aj^ONL<<11a%>e?|HG;T$FyhHoztFuJ`}X$%|Y9)yUrdDGn^Qp>BS*c s9O4crKVg~z3ZKFF&mrXad|(gZCon7rr(2jiyI2Ci_8Dwa0_)!j0E?>|zW@LL literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/rename b/tests/dGameTests/dGameMessagesTests/TestBitStreams/rename new file mode 100644 index 0000000000000000000000000000000000000000..bc8827dcd5a07c742276cec210f2fad51750cf97 GIT binary patch literal 1024 zcmd;N<n&9-O=aUONi8lBbxO@hEX&L<@^oQfWMg1pC`!!(N<swqi%W_!3p`y|f#P5Q z6i6&dMG|1-1&WszqyR;OL25%i88Fpw0@Wm@q&Oy*Waj5V?ZQ;W0Z|1urUXnP>_v7Z znobc1Mr55}XQB`_Kwdcz=K*mv5a*l=oqWBXfq@0cMg|g4PQ&S|lR)wb|CXKj52Rb5 zv;~x&x#$2`-T<n8#llvwc`)^stG|QgxnYK@TCY;boxcpmRe&<sp|pTN%R!JmAYXt0 z6A**=FmVTvAQAw{!|X;9hBMLq3v>64H;RWr=E4BXKA3;e#djQosE7F%rrzK`BwS$X zVg9w4C<->e%*GoW9x!<rtq#>UVG=|g%p3uzz70_O1deln&4JO{rj=mxUPZNmX#qxv ziC@e_uP`_;u)y>)a<xqc$-u;)nlLapP3p5fC3VL+Z1p|IsOYErK=N}Qq}YS#5B(5# zFhK2x(GMO<poG%|hN)nCE&fdb(-&f=gXx&*^Ab+TI*EJqLE;;xZ+#RbeSqu$fd&SK z4p4dmWiA0AR*tO#>wj34;F$L8x^vpI&xe9`yg6vwb=TSBVTKa}G`%>aibLE1<tI#2 kK;bhO|2c#lpAYOI`~-&O;B*UfXBSHV*gk>%5O-_^021LB;s5{u literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/sendBehaviorListToClient b/tests/dGameTests/dGameMessagesTests/TestBitStreams/sendBehaviorListToClient new file mode 100644 index 0000000000000000000000000000000000000000..fcca696dc1b93ff923a04242791f4642f65fe9f5 GIT binary patch literal 1024 zcmd;NWRzfFU?@(_OL0ogNG!|DFY?JOE(ytZ&dE&8D*;L|Fff(@F(;5A0Om3=B!Flp zCJr!{;eZ2>24V+CMj!)(SvgrI7ywmpC`?umU|{5UEWp6R0^&0`Uwtd(;K0CQ*m{6L z0B9UX1moQGG5kPH0w;`sMgWabc)-H1=3)a>?<8@Afe~b0V}r!@+T#U4qj(G&AVx7U zI23uhFz^?bB$lLly08LO0fC4EBgj#SDJj7vMVSR)F%+T($SVipJRpt+;+%7#ldsn^ zFaT{s0iZAefrispCxPS>{w+K4A4s=AX$vSlbI}2?JkYmbuwr2=*gTke%hlh(^4w5) z236}-3c2%_!MF-g20N4%5NJ6FvIiQp3`{_A5FaM)096O0K=LrVVPeQMx_@ErzVSx! zFvwgOfY}H0FS_`SV-WQ)|H9N8{D*`KOg+rM786Cm=9k%cgTn(R52Mwg`X)?*sDqg! z0M)kvYM;Py4zM{eTHCY|Y~HJ=HZUy!N*+M)#Z2@H12A2|^fPj`O-2@fY6477llp8= zN!@V{TYb+lD*EX@ko=qnDfS@xLqEhF3{d-F^n-^IDB(1LVJg^Oi+@wV^o7{zU^?dc zVcU1IPU0SYkobn_y8!hkjL!zL3<y9pF!?hm$5w&$Kdee{OnY|SIqli!LqR*<9JKAa z>+JC`!wHsN98$$0?trGBglP&Wd<Nq`hmhm*fjxx(pBZEu0|U&RT`U1$`x*{2bb!+J FRsisU4MqR} literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/splitStrip b/tests/dGameTests/dGameMessagesTests/TestBitStreams/splitStrip new file mode 100644 index 0000000000000000000000000000000000000000..a23c1682fef381b86d6e9e4da202ba4c217e8426 GIT binary patch literal 1024 zcmd;Nlr1hwc1$kG%+K@8OG&L@WdMT@_M$-X;F6-u0#6sH7z2Z-Q))(HS!RBbrwfB< zN^wbWNn%MVvOHK1niyCe(40_DPDbWRRvlv?*lgp#T)~<K0#=0%j1aR>>~dh_0y?C) zASV-O3s45TBlwF^Tp;4W$N|)qn34k41MvznSp(#h192V@M+0%rxzNei>lqkWfNW$S z0p&EDzB&mcpYU(liT^;l1xi~$>6wcTfaMLK>Q^jm1)B#`Z@KzASe_eZxT^Ikh1~he zU|a<#gB?l>2(%mo*#q(g2rvOLhz}EY00|-ikUY$8Bw;uc-M=t*-*}^V7-TLC!0dzh z7hQbEF^GDYe_`qk{zJkArXJ>Bi;1FO^UG|!!QlauhtcX#eG?`@)WOUVfa==-wNKzU z2iP1Kt!-KfHt$tb8<-YggqZlnO!Nwa0|N_8KO<M$WRMI@{HX~8gVUrw+f!0^oWoY% zbBv09x(_5j=Rt}+i2l$IaR&p`ei;4Wp#(}eO<<S`w%6j{6fk`ub~>1j`5!X-q^y&; zM;|1<VfrpW{R!i<fh+?85G?@2%CS{o{ST`W9Mhg%cTRiu`B2b~HwSII?mBxs%y43W yrWc1)afmyh{Df%=D0~LvKZlUx^MO5tpTMvjoNi(6>|zN3+ZS+*p#zkzw*mkF+Z`$Z literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/toggleExecutionUpdates b/tests/dGameTests/dGameMessagesTests/TestBitStreams/toggleExecutionUpdates new file mode 100644 index 0000000000000000000000000000000000000000..02a72181616c6a1ab46e82146e603ec296fa3031 GIT binary patch literal 1024 zcmd;N<WJ2@Ov*`3VP+I#U|=Z8PfyQDb*)HEE-lH-&kHR`Ni0b%W?*3C1WF13F#`h= zLjss$;s8+$3<n&51Q0toG6ESO%*x3!!2qa`Lt(Ol00Se(V*v&h77(Ao`RZFK2L}cg z!`1@~0zl(9A{ghckKqSu5;$Q5Gy-Uh!UGn5H5VJ8dMAk^42&T28XF|G*B&nb8pUJK z05OV*!J)|0g@M1g1n53b7gnGuAP{k21UV`(B_+6|D6;@8hC<W;dF4Qy2gK1poO3R8 z^7VQK2B2*yKmy8ZIDK^zNIv1;vJ?M-bPJTWfYLJ;9RSM%eG3LF7Pf-TgQ>S%{T(dN z4V7n5wO*x=JAWCBs{m!NLumnlmV+RBpg{`^YX$}oA13YqRR^O$@-Vw$V#qYQe_`&v z@ka45$XpnJ*$4A4y7-P`5cM$s!qgl5hlC4EJ<Pur6Gg%1m)UrO!viJ{qt&7MCQO2; zgP9`$)wcm^pTKbrusJYV+q4pF-m9oKFf9N|9zgKLO!Nu^FkQj)Gjg>}Mizf+0!&Vm z`fN{0-Ej_Eea|r}`sqH9{G10V_8|I0Kg1mjQ2Sx@gNG6*;WU9^D%f6&e^bEph1ls} zI_CLd+jp`~;vRjF_=f4b0QDz~&jzv#2tYJ2`7<cTR)O_DtV(c9dv@J9?b+u;K|9_Y zwC%d<?C~(e36@?QQpF+efTo{>X$mNO2ID`6kmK`#J%pdYupFFjVeaf=2>{#oU>`#V IC|z#_09Q>B!~g&Q literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/updateAction b/tests/dGameTests/dGameMessagesTests/TestBitStreams/updateAction new file mode 100644 index 0000000000000000000000000000000000000000..e007d5e6b3f2d5b0ac733e3e925bcbf4ed522314 GIT binary patch literal 1024 zcmd;N<V{R2$;{8=WaJE~EJ$VJcgv}C$uG|nbjd6(Nz6-5Wn};ZPX|W+;*z4w0#6sH z2m^ySM5||BN@@jE@PoamQ))(HS!RBbrwap6M`B4Tk`6{5pkbv2DL_$2u(dc9asU-3 zrlbUetYl!2fH;DI2}obBXJ8NzXgT;FNIO8qVH8N-0LH;W*8s)JfjAF{qk%Z*T<Bzw zc`QISGJx6FaQf;bkbJ_wWhX%PwLobLC_Qu00kAyG&J_z=!REo#Tdw{Nmgj~Uu4=tX zA$R^V7*_$xV29E$e}Q}t0wDi@?1hOtfCP~Mss4qz`^Fo^!yt2E0A?S|zv$vSjzQGJ z{0mcW@E;N`F!eD1T1*rLn_p(*4Gs^OJd9R{>YFeLq7G(`094-wsC@#*Il$(?Xl>I< zuz9bd+Q75`BgDinW};VsiGc;CpOLF=GDrp{{?vql!D&*T?J21{&S9(XIYvc4-3OAN z^B~0@M1SaqxPt*|Ka76xPy!{KCNN9|+iUS}3YfkSI~`2N<a^p5lywsK=!3*JOy32l zKVf_}kYzvsq6L6hIkpO{|6x^vW7@Op&S}p+9}3#>=AdoYU1yJn8BPq)^x}{z4si#R ppD;}Uh0kF8=MZvyKCp-I6Bw3*(=E)MT`U1$`!?)j=m4ebtpEV}6u|%h literal 0 HcmV?d00001 diff --git a/tests/dGameTests/dGameMessagesTests/TestBitStreams/updateStripUI b/tests/dGameTests/dGameMessagesTests/TestBitStreams/updateStripUI new file mode 100644 index 0000000000000000000000000000000000000000..7d0eed926857d88dbe03d3ab1f097239101fb2a1 GIT binary patch literal 1024 zcmd;NWG&6)WMr;nJ#_{M);KyaSFp~S2?Uz44veBssTql7nfXPYE)4v|B}JJ9o-V8m zPyiH2EJ;NYVB`hLloq4_MT0?VLp?z%MN^7Pz+7aN+(3!k)S`5V!eWp*28IvzjC?>U zH#5BmXoO>ONoIataZV;gH^N>tM<KgG#DS3mXhLF23fM-Fp{Sq+$SnurJRpt+;+%7# zldsn^Ft7mG$Up+hX*hj#5=cJb-?9_`fpiO$wt&(z7aai08$i{sSl9|S52oI7^>?s5 z$iHBqYQ0J!cm6UMR{_dkhtdK9EeApNfP4W0Oh63c!^9mxf=B=)53?Id7|ulZFU;LH z-Y6ahnF|9j`(XY>7vFIVq8{d7n0kZ%kZ^&ihxylHqA1w>G8=Djc);Xgv^rGZgh>!} zFmnW;`ZhrA6FANRHU~y)n^uC&dll6NrUe)wCVnv!y~5zYzyj0H$kjF(Bm)zFYQn(a zG^x+_l++#Pu+{e*qoSYg1If>MkYW#_KlDS~!2q=%Mn8Bcff7y=7^Z^lwfHv$Okaqd z4yI$){}DMY>m=^c2Z?W(z6(%)!uV_;%YXnx3jnclY!z7l!>R<wv}f0y)1G}k6tv^b zLEEmo&K?gloEV_##UWK3;tnW3VVVL8pTYRgA>{acU=QIZFf0eBTbMh$SOUQIJ=n+4 I0ZP|f0dLVDp#T5? literal 0 HcmV?d00001 From 484488e47d511c680660f2764c19c1a27114ae8c Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Thu, 16 Feb 2023 11:14:23 -0600 Subject: [PATCH 253/322] add bounds check to prevent crashing (#992) --- dScripts/02_server/Map/AG/AgMonumentRaceGoal.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/dScripts/02_server/Map/AG/AgMonumentRaceGoal.cpp b/dScripts/02_server/Map/AG/AgMonumentRaceGoal.cpp index 78bbaee5..0dd91bf2 100644 --- a/dScripts/02_server/Map/AG/AgMonumentRaceGoal.cpp +++ b/dScripts/02_server/Map/AG/AgMonumentRaceGoal.cpp @@ -7,9 +7,9 @@ void AgMonumentRaceGoal::OnStartup(Entity* self) { } void AgMonumentRaceGoal::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { - if (name == "RaceGoal" && entering->IsPlayer() && status == "ENTER") { - auto* manager = EntityManager::Instance()->GetEntitiesInGroup("race_manager")[0]; - - manager->OnFireEventServerSide(entering, "course_finish"); + if (name == "RaceGoal" && entering && entering->IsPlayer() && status == "ENTER") { + auto managers = EntityManager::Instance()->GetEntitiesInGroup("race_manager"); + if (managers.empty() || !managers.at(0)) return; + managers.at(0)->OnFireEventServerSide(entering, "course_finish"); } } From d138b7b87885d536d01e6edc676e6bc343dd886c Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 16 Feb 2023 09:30:33 -0800 Subject: [PATCH 254/322] Make ControlBehavior messages far more modular (#991) * Make case consistent * How modular can you go? Holy modular * Add comments * Initialize values --- .../ControlBehaviorMessages/Action.cpp | 31 +++++ .../ControlBehaviorMessages/Action.h | 25 ++++ .../ControlBehaviorMessages/ActionContext.cpp | 31 +++++ .../ControlBehaviorMessages/ActionContext.h | 26 ++++ .../AddActionMessage.cpp | 40 ++---- .../AddActionMessage.h | 24 ++-- .../ControlBehaviorMessages/AddMessage.cpp | 6 +- .../ControlBehaviorMessages/AddMessage.h | 6 +- .../AddStripMessage.cpp | 57 ++------- .../ControlBehaviorMessages/AddStripMessage.h | 35 +++--- .../BehaviorMessageBase.cpp | 33 +++++ .../BehaviorMessageBase.h | 43 ++----- .../ControlBehaviorMessages/CMakeLists.txt | 4 + .../MergeStripsMessage.cpp | 19 +-- .../MergeStripsMessage.h | 19 ++- .../MigrateActionsMessage.cpp | 25 +--- .../MigrateActionsMessage.h | 19 ++- .../MoveToInventoryMessage.cpp | 6 +- .../MoveToInventoryMessage.h | 8 +- .../RearrangeStripMessage.cpp | 16 +-- .../RearrangeStripMessage.h | 13 +- .../RemoveActionsMessage.cpp | 15 +-- .../RemoveActionsMessage.h | 13 +- .../RemoveStripMessage.cpp | 9 +- .../RemoveStripMessage.h | 13 +- .../ControlBehaviorMessages/RenameMessage.cpp | 6 +- .../ControlBehaviorMessages/RenameMessage.h | 6 +- .../SplitStripMessage.cpp | 30 +---- .../SplitStripMessage.h | 26 ++-- .../StripUiPosition.cpp | 22 ++++ .../ControlBehaviorMessages/StripUiPosition.h | 21 ++++ .../UpdateActionMessage.cpp | 39 ++---- .../UpdateActionMessage.h | 26 ++-- .../UpdateStripUiMessage.cpp | 20 +-- .../UpdateStripUiMessage.h | 20 +-- dGame/dPropertyBehaviors/ControlBehaviors.cpp | 24 ++-- tests/dCommonTests/AMFDeserializeTests.cpp | 8 +- .../dGameMessagesTests/GameMessageTests.cpp | 115 +++++++++--------- 38 files changed, 461 insertions(+), 438 deletions(-) create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.h create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.cpp create mode 100644 dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.h diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.cpp new file mode 100644 index 00000000..7da286b0 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.cpp @@ -0,0 +1,31 @@ +#include "Action.h" + +Action::Action() { + type = ""; + valueParameterName = ""; + valueParameterString = ""; + valueParameterDouble = 0.0; +} + +Action::Action(AMFArrayValue* arguments) { + type = ""; + valueParameterName = ""; + valueParameterString = ""; + valueParameterDouble = 0.0; + for (auto& typeValueMap : arguments->GetAssociativeMap()) { + if (typeValueMap.first == "Type") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + type = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + valueParameterName = typeValueMap.first; + // Message is the only known string parameter + if (valueParameterName == "Message") { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; + valueParameterString = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); + } else { + if (typeValueMap.second->GetValueType() != AMFValueType::AMFDouble) continue; + valueParameterDouble = static_cast<AMFDoubleValue*>(typeValueMap.second)->GetDoubleValue(); + } + } + } +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.h new file mode 100644 index 00000000..c97b4050 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.h @@ -0,0 +1,25 @@ +#ifndef __ACTION__H__ +#define __ACTION__H__ + +#include "BehaviorMessageBase.h" + +/** + * @brief Sent if a ControlBehavior message has an Action associated with it + * + */ +class Action { +public: + Action(); + Action(AMFArrayValue* arguments); + const std::string& GetType() { return type; }; + const std::string& GetValueParameterName() { return valueParameterName; }; + const std::string& GetValueParameterString() { return valueParameterString; }; + const double GetValueParameterDouble() { return valueParameterDouble; }; +private: + std::string type; + std::string valueParameterName; + std::string valueParameterString; + double valueParameterDouble; +}; + +#endif //!__ACTION__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.cpp new file mode 100644 index 00000000..480eef45 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.cpp @@ -0,0 +1,31 @@ +#include "ActionContext.h" + +#include <stdexcept> + +#include "AMFFormat.h" + +ActionContext::ActionContext() { + stripId = 0; + stateId = BehaviorState::HOME_STATE; +} + +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->FindValue<AMFDoubleValue>(key); + if (!stateIDValue) throw std::invalid_argument("Unable to find behavior state from argument \"" + key + "\""); + + return static_cast<BehaviorState>(stateIDValue->GetDoubleValue()); +} + +StripId ActionContext::GetStripIdFromArgument(AMFArrayValue* arguments, const std::string& key) { + auto* stripIdValue = arguments->FindValue<AMFDoubleValue>(key); + if (!stripIdValue) throw std::invalid_argument("Unable to find strip ID from argument \"" + key + "\""); + + return static_cast<StripId>(stripIdValue->GetDoubleValue()); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.h new file mode 100644 index 00000000..5f46fd8c --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.h @@ -0,0 +1,26 @@ +#ifndef __ACTIONCONTEXT__H__ +#define __ACTIONCONTEXT__H__ + +#include "BehaviorStates.h" +#include "dCommonVars.h" + +class AMFArrayValue; + +/** + * @brief Sent if contextual State and Strip informationis needed for a ControlBehaviors message + * + */ +class ActionContext { +public: + ActionContext(); + ActionContext(AMFArrayValue* arguments, std::string customStateKey = "stateID", std::string customStripKey = "stripID"); + const StripId GetStripId() { return stripId; }; + const BehaviorState GetStateId() { return stateId; }; +private: + BehaviorState GetBehaviorStateFromArgument(AMFArrayValue* arguments, const std::string& key); + StripId GetStripIdFromArgument(AMFArrayValue* arguments, const std::string& key); + StripId stripId; + BehaviorState stateId; +}; + +#endif //!__ACTIONCONTEXT__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp index f91512fe..4fc7f82b 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp @@ -1,39 +1,13 @@ #include "AddActionMessage.h" -AddActionMessage::AddActionMessage(AMFArrayValue* arguments) { - auto* actionIndexAmf = arguments->FindValue<AMFDoubleValue>("actionIndex"); - if (!actionIndexAmf) return; +AddActionMessage::AddActionMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { + actionContext = ActionContext(arguments); + actionIndex = GetActionIndexFromArgument(arguments); - actionIndex = static_cast<uint32_t>(actionIndexAmf->GetDoubleValue()); + auto* actionValue = arguments->FindValue<AMFArrayValue>("action"); + if (!actionValue) return; - stripId = GetStripIDFromArgument(arguments); + action = Action(actionValue); - stateId = GetBehaviorStateFromArgument(arguments); - - type = ""; - valueParameterName = ""; - valueParameterString = ""; - valueParameterDouble = 0.0; - auto* action = arguments->FindValue<AMFArrayValue>("action"); - if (!action) return; - - for (auto& typeValueMap : action->GetAssociativeMap()) { - if (typeValueMap.first == "Type") { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; - type = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); - } else { - valueParameterName = typeValueMap.first; - // Message is the only known string parameter - if (valueParameterName == "Message") { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; - valueParameterString = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); - } else { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFDouble) continue; - valueParameterDouble = static_cast<AMFDoubleValue*>(typeValueMap.second)->GetDoubleValue(); - } - } - } - - behaviorId = GetBehaviorIDFromArgument(arguments); - Game::logger->LogDebug("AddActionMessage", "acnNdx %i stpId %i sttId %i t %s vpn %s vps %s vpd %f bhId %i", actionIndex, stripId, stateId, type.c_str(), valueParameterName.c_str(), valueParameterString.c_str(), valueParameterDouble, behaviorId); + Game::logger->LogDebug("AddActionMessage", "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); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h index 1f1577ec..4faf6a53 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h @@ -1,30 +1,26 @@ #ifndef __ADDACTIONMESSAGE__H__ #define __ADDACTIONMESSAGE__H__ +#include "Action.h" +#include "ActionContext.h" #include "BehaviorMessageBase.h" class AMFArrayValue; +/** + * @brief Send if a player takes an Action A from the toolbox and adds it to an already existing strip + * + */ class AddActionMessage : public BehaviorMessageBase { public: AddActionMessage(AMFArrayValue* arguments); const uint32_t GetActionIndex() { return actionIndex; }; - const StripId GetStripId() { return stripId; }; - const BehaviorState GetStateId() { return stateId; }; - const std::string& GetType() { return type; }; - const std::string& GetValueParameterName() { return valueParameterName; }; - const std::string& GetValueParameterString() { return valueParameterString; }; - const double GetValueParameterDouble() { return valueParameterDouble; }; - const uint32_t GetBehaviorId() { return behaviorId; }; + Action GetAction() { return action; }; + ActionContext GetActionContext() { return actionContext; }; private: uint32_t actionIndex; - StripId stripId; - BehaviorState stateId; - std::string type; - std::string valueParameterName; - std::string valueParameterString; - double valueParameterDouble; - uint32_t behaviorId; + ActionContext actionContext; + Action action; }; #endif //!__ADDACTIONMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp index ecddb8e3..4f2123b4 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp @@ -1,13 +1,11 @@ #include "AddMessage.h" -AddMessage::AddMessage(AMFArrayValue* arguments) { - behaviorId = GetBehaviorIDFromArgument(arguments); - +AddMessage::AddMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { behaviorIndex = 0; auto* behaviorIndexValue = arguments->FindValue<AMFDoubleValue>("BehaviorIndex"); if (!behaviorIndexValue) return; behaviorIndex = static_cast<uint32_t>(behaviorIndexValue->GetDoubleValue()); - Game::logger->LogDebug("AddMessage", "bhId %i ndx %i", behaviorId, behaviorIndex); + Game::logger->LogDebug("AddMessage", "behaviorId %i index %i", behaviorId, behaviorIndex); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h index ff8e0c8b..a46d5f98 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h @@ -3,13 +3,15 @@ #include "BehaviorMessageBase.h" +/** + * @brief Sent when a player adds a Behavior A from their inventory to a model. + * + */ class AddMessage : public BehaviorMessageBase { public: AddMessage(AMFArrayValue* arguments); const uint32_t GetBehaviorIndex() { return behaviorIndex; }; - const uint32_t GetBehaviorId() { return behaviorId; }; private: - uint32_t behaviorId; uint32_t behaviorIndex; }; diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp index 23662174..c4729c57 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp @@ -1,56 +1,25 @@ #include "AddStripMessage.h" -AddStripMessage::AddStripMessage(AMFArrayValue* arguments) { +#include "Action.h" + +AddStripMessage::AddStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { + actionContext = ActionContext(arguments); + + position = StripUiPosition(arguments); + auto* strip = arguments->FindValue<AMFArrayValue>("strip"); if (!strip) return; auto* actions = strip->FindValue<AMFArrayValue>("actions"); if (!actions) return; - auto* uiArray = arguments->FindValue<AMFArrayValue>("ui"); - if (!uiArray) return; + for (uint32_t actionNumber = 0; actionNumber < actions->GetDenseValueSize(); actionNumber++) { + auto* actionValue = actions->GetValueAt<AMFArrayValue>(actionNumber); + if (!actionValue) continue; - auto* xPositionValue = uiArray->FindValue<AMFDoubleValue>("x"); - if (!xPositionValue) return; + actionsToAdd.push_back(Action(actionValue)); - xPosition = xPositionValue->GetDoubleValue(); - - auto* yPositionValue = uiArray->FindValue<AMFDoubleValue>("y"); - if (!yPositionValue) return; - - yPosition = yPositionValue->GetDoubleValue(); - - stripId = GetStripIDFromArgument(arguments); - - stateId = GetBehaviorStateFromArgument(arguments); - - behaviorId = GetBehaviorIDFromArgument(arguments); - - type = ""; - valueParameterName = ""; - valueParameterString = ""; - valueParameterDouble = 0.0; - for (uint32_t position = 0; position < actions->GetDenseValueSize(); position++) { - auto* actionAsArray = actions->GetValueAt<AMFArrayValue>(position); - if (!actionAsArray) continue; - - for (auto& typeValueMap : actionAsArray->GetAssociativeMap()) { - if (typeValueMap.first == "Type") { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; - - type = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); - } else { - valueParameterName = typeValueMap.first; - // Message is the only known string parameter - if (valueParameterName == "Message") { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; - valueParameterString = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); - } else { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFDouble) continue; - valueParameterDouble = static_cast<AMFDoubleValue*>(typeValueMap.second)->GetDoubleValue(); - } - } - } - Game::logger->LogDebug("AddStripMessage", "x %f y %f stpId %i sttId %i bhId %i t %s vpn %s vps %s vpd %f", xPosition, yPosition, stripId, stateId, behaviorId, type.c_str(), valueParameterName.c_str(), valueParameterString.c_str(), valueParameterDouble); + Game::logger->LogDebug("AddStripMessage", "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()); } + Game::logger->Log("AddStripMessage", "number of actions %i", actionsToAdd.size()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h index bb720bae..db75aef7 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h @@ -1,32 +1,31 @@ #ifndef __ADDSTRIPMESSAGE__H__ #define __ADDSTRIPMESSAGE__H__ +#include "ActionContext.h" #include "BehaviorMessageBase.h" +#include "StripUiPosition.h" +#include <vector> + +class Action; class AMFArrayValue; +/** + * @brief Sent in 2 contexts: + * A player adds an Action A from their toolbox without attaching it to an existing Strip. In this case, only 1 action is sent. + * A player moves a Strip from BehaviorState A directly to BehaviorState B. In this case, a list of actions are sent. + * + */ class AddStripMessage : public BehaviorMessageBase { public: AddStripMessage(AMFArrayValue* arguments); - const StripId GetStripId() { return stripId; }; - const BehaviorState GetStateId() { return stateId; }; - const std::string& GetType() { return type; }; - const std::string& GetValueParameterName() { return valueParameterName; }; - const std::string& GetValueParameterString() { return valueParameterString; }; - const double GetXPosition() { return xPosition; }; - const double GetYPosition() { return yPosition; }; - const double GetValueParameterDouble() { return valueParameterDouble; }; - const uint32_t GetBehaviorId() { return behaviorId; }; + StripUiPosition GetPosition() { return position; }; + ActionContext GetActionContext() { return actionContext; }; + std::vector<Action> GetActionsToAdd() { return actionsToAdd; }; private: - double xPosition; - double yPosition; - StripId stripId; - BehaviorState stateId; - uint32_t behaviorId; - std::string type; - std::string valueParameterName; - std::string valueParameterString; - double valueParameterDouble; + StripUiPosition position; + ActionContext actionContext; + std::vector<Action> actionsToAdd; }; #endif //!__ADDSTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp new file mode 100644 index 00000000..b3d98d51 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp @@ -0,0 +1,33 @@ +#include "BehaviorMessageBase.h" + +#include "AMFFormat.h" +#include "BehaviorStates.h" +#include "dCommonVars.h" + +BehaviorMessageBase::BehaviorMessageBase(AMFArrayValue* arguments) { + behaviorId = 0; + behaviorId = GetBehaviorIdFromArgument(arguments); +} + +int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* arguments) { + const auto* key = "BehaviorID"; + auto* behaviorIDValue = arguments->FindValue<AMFStringValue>(key); + int32_t behaviorID = -1; + + if (behaviorIDValue) { + behaviorID = std::stoul(behaviorIDValue->GetStringValue()); + } else if (!arguments->FindValue<AMFUndefinedValue>(key)) { + throw std::invalid_argument("Unable to find behavior ID"); + } + + return behaviorID; +} + +uint32_t BehaviorMessageBase::GetActionIndexFromArgument(AMFArrayValue* arguments, const std::string& keyName) { + auto* actionIndexAmf = arguments->FindValue<AMFDoubleValue>(keyName); + if (!actionIndexAmf) { + throw std::invalid_argument("Unable to find actionIndex"); + } + + return static_cast<uint32_t>(actionIndexAmf->GetDoubleValue()); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h index 78025672..13b00a35 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h @@ -5,44 +5,25 @@ #include <string> #include "AMFFormat.h" -#include "BehaviorStates.h" #include "dCommonVars.h" #include "Game.h" #include "dLogger.h" +enum class BehaviorState : uint32_t; + +/** + * @brief The behaviorID target of this ControlBehaviors message + * + */ class BehaviorMessageBase { public: - uint32_t GetBehaviorIDFromArgument(AMFArrayValue* arguments, const std::string& key = "BehaviorID") { - auto* behaviorIDValue = arguments->FindValue<AMFStringValue>(key); - uint32_t behaviorID = -1; - - if (behaviorIDValue) { - behaviorID = std::stoul(behaviorIDValue->GetStringValue()); - } else if (arguments->FindValue<AMFUndefinedValue>(key) == nullptr) { - throw std::invalid_argument("Unable to find behavior ID from argument \"" + key + "\""); - } - - return behaviorID; - } - - BehaviorState GetBehaviorStateFromArgument(AMFArrayValue* arguments, const std::string& key = "stateID") { - auto* stateIDValue = arguments->FindValue<AMFDoubleValue>(key); - if (!stateIDValue) throw std::invalid_argument("Unable to find behavior state from argument \"" + key + "\""); - - BehaviorState stateID = static_cast<BehaviorState>(stateIDValue->GetDoubleValue()); - - return stateID; - } - - StripId GetStripIDFromArgument(AMFArrayValue* arguments, const std::string& key = "stripID") { - auto* stripIDValue = arguments->FindValue<AMFDoubleValue>(key); - if (!stripIDValue) throw std::invalid_argument("Unable to find strip ID from argument \"" + key + "\""); - - StripId stripID = static_cast<StripId>(stripIDValue->GetDoubleValue()); - - return stripID; - } + const uint32_t GetBehaviorId() { return behaviorId; }; +protected: + BehaviorMessageBase(AMFArrayValue* arguments); + int32_t GetBehaviorIdFromArgument(AMFArrayValue* arguments); + uint32_t GetActionIndexFromArgument(AMFArrayValue* arguments, const std::string& keyName = "actionIndex"); + int32_t behaviorId = -1; }; #endif //!__BEHAVIORMESSAGEBASE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/CMakeLists.txt b/dGame/dPropertyBehaviors/ControlBehaviorMessages/CMakeLists.txt index 8390cd22..49b0f460 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/CMakeLists.txt +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/CMakeLists.txt @@ -1,7 +1,10 @@ set(DGAME_DPROPERTYBEHAVIORS_CONTROLBEHAVIORMESSAGES + "Action.cpp" + "ActionContext.cpp" "AddActionMessage.cpp" "AddMessage.cpp" "AddStripMessage.cpp" + "BehaviorMessageBase.cpp" "MergeStripsMessage.cpp" "MigrateActionsMessage.cpp" "MoveToInventoryMessage.cpp" @@ -10,6 +13,7 @@ set(DGAME_DPROPERTYBEHAVIORS_CONTROLBEHAVIORMESSAGES "RemoveStripMessage.cpp" "RenameMessage.cpp" "SplitStripMessage.cpp" + "StripUiPosition.cpp" "UpdateActionMessage.cpp" "UpdateStripUiMessage.cpp" PARENT_SCOPE diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp index d810e861..df50641a 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp @@ -1,20 +1,11 @@ #include "MergeStripsMessage.h" -MergeStripsMessage::MergeStripsMessage(AMFArrayValue* arguments) { - srcStripID = GetStripIDFromArgument(arguments, "srcStripID"); +MergeStripsMessage::MergeStripsMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { + sourceActionContext = ActionContext(arguments, "srcStateID", "srcStripID"); - dstStateID = GetBehaviorStateFromArgument(arguments, "dstStateID"); + destinationActionContext = ActionContext(arguments, "dstStateID", "dstStripID"); + dstActionIndex = GetActionIndexFromArgument(arguments, "dstActionIndex"); - srcStateID = GetBehaviorStateFromArgument(arguments, "srcStateID"); - - auto* dstActionIndexValue = arguments->FindValue<AMFDoubleValue>("dstActionIndex"); - if (!dstActionIndexValue) return; - - dstActionIndex = static_cast<uint32_t>(dstActionIndexValue->GetDoubleValue()); - - dstStripID = GetStripIDFromArgument(arguments, "dstStripID"); - - behaviorID = GetBehaviorIDFromArgument(arguments); - Game::logger->LogDebug("MergeStripsMessage", "srcStpId %i dstStpId %i srcSttId %i dstSttId %i dstAcnNdx %i bhId %i", srcStripID, dstStripID, srcStateID, dstStateID, dstActionIndex, behaviorID); + Game::logger->LogDebug("MergeStripsMessage", "srcstripId %i dststripId %i srcstateId %i dststateId %i dstactionIndex %i behaviorId %i", sourceActionContext.GetStripId(), destinationActionContext.GetStripId(), sourceActionContext.GetStateId(), destinationActionContext.GetStateId(), dstActionIndex, behaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h index af3aa16f..0aff7f3a 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h @@ -1,26 +1,25 @@ #ifndef __MERGESTRIPSMESSAGE__H__ #define __MERGESTRIPSMESSAGE__H__ +#include "ActionContext.h" #include "BehaviorMessageBase.h" class AMFArrayValue; +/** + * @brief Sent when a player adds the first Action of Strip A to a Strip B + * + */ class MergeStripsMessage : public BehaviorMessageBase { public: MergeStripsMessage(AMFArrayValue* arguments); - const StripId GetSrcStripID() { return srcStripID; }; - const BehaviorState GetDstStateID() { return dstStateID; }; - const BehaviorState GetSrcStateID() { return srcStateID; }; const uint32_t GetDstActionIndex() { return dstActionIndex; }; - const StripId GetDstStripID() { return dstStripID; }; - const uint32_t GetBehaviorID() { return behaviorID; }; + ActionContext GetSourceActionContext() { return sourceActionContext; }; + ActionContext GetDestinationActionContext() { return destinationActionContext; }; private: - StripId srcStripID; - BehaviorState dstStateID; - BehaviorState srcStateID; + ActionContext sourceActionContext; + ActionContext destinationActionContext; uint32_t dstActionIndex; - StripId dstStripID; - uint32_t behaviorID; }; #endif //!__MERGESTRIPSMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp index 8bb4e819..08f830a4 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp @@ -1,24 +1,11 @@ #include "MigrateActionsMessage.h" -MigrateActionsMessage::MigrateActionsMessage(AMFArrayValue* arguments) { - auto* srcActionIndexAmf = arguments->FindValue<AMFDoubleValue>("srcActionIndex"); - if (!srcActionIndexAmf) return; +MigrateActionsMessage::MigrateActionsMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { + sourceActionContext = ActionContext(arguments, "srcStateID", "srcStripID"); + srcActionIndex = GetActionIndexFromArgument(arguments, "srcActionIndex"); - srcActionIndex = static_cast<uint32_t>(srcActionIndexAmf->GetDoubleValue()); + destinationActionContext = ActionContext(arguments, "dstStateID", "dstStripID"); + dstActionIndex = GetActionIndexFromArgument(arguments, "dstActionIndex"); - srcStripID = GetStripIDFromArgument(arguments, "srcStripID"); - - srcStateID = GetBehaviorStateFromArgument(arguments, "srcStateID"); - - auto* dstActionIndexAmf = arguments->FindValue<AMFDoubleValue>("dstActionIndex"); - if (!dstActionIndexAmf) return; - - dstActionIndex = static_cast<uint32_t>(dstActionIndexAmf->GetDoubleValue()); - - dstStripID = GetStripIDFromArgument(arguments, "dstStripID"); - - dstStateID = GetBehaviorStateFromArgument(arguments, "dstStateID"); - - behaviorID = GetBehaviorIDFromArgument(arguments); - Game::logger->LogDebug("MigrateActionsMessage", "srcAcnNdx %i dstAcnNdx %i srcStpId %i dstStpId %i srcSttId %i dstSttId %i bhid %i", srcActionIndex, dstActionIndex, srcStripID, dstStripID, srcStateID, dstStateID, behaviorID); + Game::logger->LogDebug("MigrateActionsMessage", "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); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h index 26018d69..f60e8748 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h @@ -1,28 +1,27 @@ #ifndef __MIGRATEACTIONSMESSAGE__H__ #define __MIGRATEACTIONSMESSAGE__H__ +#include "ActionContext.h" #include "BehaviorMessageBase.h" class AMFArrayValue; +/** + * @brief Sent when a player moves an Action after the first Action to a different Strip + * + */ class MigrateActionsMessage : public BehaviorMessageBase { public: MigrateActionsMessage(AMFArrayValue* arguments); const uint32_t GetSrcActionIndex() { return srcActionIndex; }; - const StripId GetSrcStripID() { return srcStripID; }; - const BehaviorState GetSrcStateID() { return srcStateID; }; const uint32_t GetDstActionIndex() { return dstActionIndex; }; - const StripId GetDstStripID() { return dstStripID; }; - const BehaviorState GetDstStateID() { return dstStateID; }; - const uint32_t GetBehaviorID() { return behaviorID; }; + ActionContext GetSourceActionContext() { return sourceActionContext; }; + ActionContext GetDestinationActionContext() { return destinationActionContext; }; private: + ActionContext sourceActionContext; + ActionContext destinationActionContext; uint32_t srcActionIndex; - StripId srcStripID; - BehaviorState srcStateID; uint32_t dstActionIndex; - StripId dstStripID; - BehaviorState dstStateID; - uint32_t behaviorID; }; #endif //!__MIGRATEACTIONSMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp index 7ad7a875..92700076 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp @@ -1,11 +1,9 @@ #include "MoveToInventoryMessage.h" -MoveToInventoryMessage::MoveToInventoryMessage(AMFArrayValue* arguments) { - behaviorID = GetBehaviorIDFromArgument(arguments); - +MoveToInventoryMessage::MoveToInventoryMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { auto* behaviorIndexValue = arguments->FindValue<AMFDoubleValue>("BehaviorIndex"); if (!behaviorIndexValue) return; behaviorIndex = static_cast<uint32_t>(behaviorIndexValue->GetDoubleValue()); - Game::logger->LogDebug("MoveToInventoryMessage", "bhId %i bhNdx %i", behaviorID, behaviorIndex); + Game::logger->LogDebug("MoveToInventoryMessage", "behaviorId %i behaviorIndex %i", behaviorId, behaviorIndex); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h index 2cf71f3c..c48f7d17 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h @@ -5,14 +5,16 @@ 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 { +class MoveToInventoryMessage : public BehaviorMessageBase { public: MoveToInventoryMessage(AMFArrayValue* arguments); - const uint32_t GetBehaviorID() { return behaviorID; }; const uint32_t GetBehaviorIndex() { return behaviorIndex; }; private: - uint32_t behaviorID; uint32_t behaviorIndex; }; diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp index 0347aca6..4018a423 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp @@ -1,16 +1,10 @@ #include "RearrangeStripMessage.h" -RearrangeStripMessage::RearrangeStripMessage(AMFArrayValue* arguments) { - auto* srcActionIndexValue = arguments->FindValue<AMFDoubleValue>("srcActionIndex"); - srcActionIndex = static_cast<uint32_t>(srcActionIndexValue->GetDoubleValue()); +RearrangeStripMessage::RearrangeStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { + actionContext = ActionContext(arguments); + srcActionIndex = GetActionIndexFromArgument(arguments, "srcActionIndex"); - stripID = GetStripIDFromArgument(arguments); + dstActionIndex = GetActionIndexFromArgument(arguments, "dstActionIndex"); - behaviorID = GetBehaviorIDFromArgument(arguments); - - auto* dstActionIndexValue = arguments->FindValue<AMFDoubleValue>("dstActionIndex"); - dstActionIndex = static_cast<uint32_t>(dstActionIndexValue->GetDoubleValue()); - - stateID = GetBehaviorStateFromArgument(arguments); - Game::logger->LogDebug("RearrangeStripMessage", "srcAcnNdx %i dstAcnNdx %i stpId %i bhId %i sttId %i", srcActionIndex, dstActionIndex, stripID, behaviorID, stateID); + Game::logger->LogDebug("RearrangeStripMessage", "srcactionIndex %i dstactionIndex %i stripId %i behaviorId %i stateId %i", srcActionIndex, dstActionIndex, actionContext.GetStripId(), behaviorId, actionContext.GetStateId()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h index 4cca0827..46819404 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h @@ -1,22 +1,23 @@ #ifndef __REARRANGESTRIPMESSAGE__H__ #define __REARRANGESTRIPMESSAGE__H__ +#include "ActionContext.h" #include "BehaviorMessageBase.h" +/** + * @brief Sent when a player moves an Action around in the same strip + * + */ class RearrangeStripMessage : public BehaviorMessageBase { public: RearrangeStripMessage(AMFArrayValue* arguments); const uint32_t GetSrcActionIndex() { return srcActionIndex; }; - const uint32_t GetStripID() { return stripID; }; - const uint32_t GetBehaviorID() { return behaviorID; }; const uint32_t GetDstActionIndex() { return dstActionIndex; }; - const BehaviorState GetStateID() { return stateID; }; + ActionContext GetActionContext() { return actionContext; }; private: + ActionContext actionContext; uint32_t srcActionIndex; - uint32_t stripID; - uint32_t behaviorID; uint32_t dstActionIndex; - BehaviorState stateID; }; #endif //!__REARRANGESTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp index cb1226e3..8f00d2b0 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp @@ -1,15 +1,8 @@ #include "RemoveActionsMessage.h" -RemoveActionsMessage::RemoveActionsMessage(AMFArrayValue* arguments) { - behaviorID = GetBehaviorIDFromArgument(arguments); +RemoveActionsMessage::RemoveActionsMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { + actionContext = ActionContext(arguments); + actionIndex = GetActionIndexFromArgument(arguments); - auto* actionIndexAmf = arguments->FindValue<AMFDoubleValue>("actionIndex"); - if (!actionIndexAmf) return; - - actionIndex = static_cast<uint32_t>(actionIndexAmf->GetDoubleValue()); - - stripID = GetStripIDFromArgument(arguments); - - stateID = GetBehaviorStateFromArgument(arguments); - Game::logger->LogDebug("RemoveActionsMessage", "bhId %i acnNdx %i stpId %i sttId %i", behaviorID, actionIndex, stripID, stateID); + Game::logger->LogDebug("RemoveActionsMessage", "behaviorId %i actionIndex %i stripId %i stateId %i", behaviorId, actionIndex, actionContext.GetStripId(), actionContext.GetStateId()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h index 33678f59..457ddba8 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h @@ -1,22 +1,23 @@ #ifndef __REMOVEACTIONSMESSAGE__H__ #define __REMOVEACTIONSMESSAGE__H__ +#include "ActionContext.h" #include "BehaviorMessageBase.h" class AMFArrayValue; +/** + * @brief Sent when a player removes any Action after the first one from a Strip + * + */ class RemoveActionsMessage : public BehaviorMessageBase { public: RemoveActionsMessage(AMFArrayValue* arguments); - const uint32_t GetBehaviorID() { return behaviorID; }; const uint32_t GetActionIndex() { return actionIndex; }; - const StripId GetStripID() { return stripID; }; - const BehaviorState GetStateID() { return stateID; }; + ActionContext GetActionContext() { return actionContext; }; private: - uint32_t behaviorID; + ActionContext actionContext; uint32_t actionIndex; - StripId stripID; - BehaviorState stateID; }; #endif //!__REMOVEACTIONSMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp index 3c48ed16..40288b07 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp @@ -1,8 +1,7 @@ #include "RemoveStripMessage.h" -RemoveStripMessage::RemoveStripMessage(AMFArrayValue* arguments) { - stripId = GetStripIDFromArgument(arguments); - behaviorState = GetBehaviorStateFromArgument(arguments); - behaviorId = GetBehaviorIDFromArgument(arguments); - Game::logger->LogDebug("RemoveStripMessage", "stpId %i bhStt %i bhId %i", stripId, behaviorState, behaviorId); +RemoveStripMessage::RemoveStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { + actionContext = ActionContext(arguments); + + Game::logger->LogDebug("RemoveStripMessage", "stripId %i stateId %i behaviorId %i", actionContext.GetStripId(), actionContext.GetStateId(), behaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h index 312bab31..36e2e401 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h @@ -1,18 +1,19 @@ #ifndef __REMOVESTRIPMESSAGE__H__ #define __REMOVESTRIPMESSAGE__H__ +#include "ActionContext.h" #include "BehaviorMessageBase.h" +/** + * @brief Sent when a player removes the first Action from a strip. + * + */ class RemoveStripMessage : public BehaviorMessageBase { public: RemoveStripMessage(AMFArrayValue* arguments); - const StripId GetStripId() { return stripId; }; - const BehaviorState GetBehaviorState() { return behaviorState; }; - const uint32_t GetBehaviorId() { return behaviorId; }; + ActionContext GetActionContext() { return actionContext; }; private: - StripId stripId; - BehaviorState behaviorState; - uint32_t behaviorId; + ActionContext actionContext; }; #endif //!__REMOVESTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp index 38c49462..0ea3b6d6 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp @@ -1,11 +1,9 @@ #include "RenameMessage.h" -RenameMessage::RenameMessage(AMFArrayValue* arguments) { - behaviorID = GetBehaviorIDFromArgument(arguments); - +RenameMessage::RenameMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { auto* nameAmf = arguments->FindValue<AMFStringValue>("Name"); if (!nameAmf) return; name = nameAmf->GetStringValue(); - Game::logger->LogDebug("RenameMessage", "bhId %i n %s", behaviorID, name.c_str()); + Game::logger->LogDebug("RenameMessage", "behaviorId %i n %s", behaviorId, name.c_str()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h index be42d66f..ba181f63 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h @@ -5,13 +5,15 @@ class AMFArrayValue; +/** + * @brief Sent when a player renames this behavior + * + */ class RenameMessage : public BehaviorMessageBase { public: RenameMessage(AMFArrayValue* arguments); - const uint32_t GetBehaviorID() { return behaviorID; }; const std::string& GetName() { return name; }; private: - uint32_t behaviorID; std::string name; }; diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp index d3493aeb..b4601a17 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp @@ -1,29 +1,11 @@ #include "SplitStripMessage.h" -SplitStripMessage::SplitStripMessage(AMFArrayValue* arguments) { - auto* srcActionIndexValue = arguments->FindValue<AMFDoubleValue>("srcActionIndex"); - if (!srcActionIndexValue) return; +SplitStripMessage::SplitStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { + sourceActionContext = ActionContext(arguments, "srcStateID", "srcStripID"); + srcActionIndex = GetActionIndexFromArgument(arguments, "srcActionIndex"); - srcActionIndex = static_cast<uint32_t>(srcActionIndexValue->GetDoubleValue()); + destinationActionContext = ActionContext(arguments, "dstStateID", "dstStripID"); + destinationPosition = StripUiPosition(arguments, "dstStripUI"); - srcStripId = GetStripIDFromArgument(arguments, "srcStripID"); - - srcStateId = GetBehaviorStateFromArgument(arguments, "srcStateID"); - - dstStripId = GetStripIDFromArgument(arguments, "dstStripID"); - - dstStateId = GetBehaviorStateFromArgument(arguments, "dstStateID"); - - auto* dstStripUiArray = arguments->FindValue<AMFArrayValue>("dstStripUI"); - if (!dstStripUiArray) return; - - auto* xPositionValue = dstStripUiArray->FindValue<AMFDoubleValue>("x"); - auto* yPositionValue = dstStripUiArray->FindValue<AMFDoubleValue>("y"); - if (!xPositionValue || !yPositionValue) return; - - yPosition = yPositionValue->GetDoubleValue(); - xPosition = xPositionValue->GetDoubleValue(); - - behaviorId = GetBehaviorIDFromArgument(arguments); - Game::logger->LogDebug("SplitStripMessage", "bhid %i x %f y %f srcStp %i dstStp %i srcStt %i dstStt %i srcActNdx %i", behaviorId, xPosition, yPosition, srcStripId, dstStripId, srcStateId, dstStateId, srcActionIndex); + Game::logger->LogDebug("SplitStripMessage", "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); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h index e06a9dc4..9210efb0 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h @@ -1,30 +1,28 @@ #ifndef __SPLITSTRIPMESSAGE__H__ #define __SPLITSTRIPMESSAGE__H__ +#include "ActionContext.h" #include "BehaviorMessageBase.h" +#include "StripUiPosition.h" class AMFArrayValue; +/** + * @brief Sent when a player takes an Action from Strip A and does not add it to an existing strip + * + */ class SplitStripMessage : public BehaviorMessageBase { public: SplitStripMessage(AMFArrayValue* arguments); + ActionContext GetSourceActionContext() { return sourceActionContext; }; + ActionContext GetDestinationActionContext() { return destinationActionContext; }; const uint32_t GetSrcActionIndex() { return srcActionIndex; }; - const StripId GetSrcStripId() { return srcStripId; }; - const BehaviorState GetSrcStateId() { return srcStateId; }; - const StripId GetDstStripId() { return dstStripId; }; - const BehaviorState GetDstStateId() { return dstStateId; }; - const double GetYPosition() { return yPosition; }; - const double GetXPosition() { return xPosition; }; - const uint32_t GetBehaviorId() { return behaviorId; }; + StripUiPosition GetPosition() { return destinationPosition; }; private: + ActionContext sourceActionContext; + ActionContext destinationActionContext; uint32_t srcActionIndex; - StripId srcStripId; - BehaviorState srcStateId; - StripId dstStripId; - BehaviorState dstStateId; - double yPosition; - double xPosition; - uint32_t behaviorId; + StripUiPosition destinationPosition; }; #endif //!__SPLITSTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.cpp new file mode 100644 index 00000000..4ddccc55 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.cpp @@ -0,0 +1,22 @@ +#include "StripUiPosition.h" + +#include "AMFFormat.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->FindValue<AMFArrayValue>(uiKeyName); + if (!uiArray) return; + + auto* xPositionValue = uiArray->FindValue<AMFDoubleValue>("x"); + auto* yPositionValue = uiArray->FindValue<AMFDoubleValue>("y"); + if (!xPositionValue || !yPositionValue) return; + + yPosition = yPositionValue->GetDoubleValue(); + xPosition = xPositionValue->GetDoubleValue(); +} diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.h new file mode 100644 index 00000000..809f8890 --- /dev/null +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.h @@ -0,0 +1,21 @@ +#ifndef __STRIPUIPOSITION__H__ +#define __STRIPUIPOSITION__H__ + +class AMFArrayValue; + +/** + * @brief The position of the first Action in a Strip + * + */ +class StripUiPosition { +public: + StripUiPosition(); + StripUiPosition(AMFArrayValue* arguments, std::string uiKeyName = "ui"); + double GetX() { return xPosition; }; + double GetY() { return yPosition; }; +private: + double xPosition; + double yPosition; +}; + +#endif //!__STRIPUIPOSITION__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp index 1d4cc868..53e2d570 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp @@ -1,38 +1,15 @@ #include "UpdateActionMessage.h" -UpdateActionMessage::UpdateActionMessage(AMFArrayValue* arguments) { - type = ""; - valueParameterName = ""; - valueParameterString = ""; - valueParameterDouble = 0.0; - auto* actionAsArray = arguments->FindValue<AMFArrayValue>("action"); - if (!actionAsArray) return; - for (auto& typeValueMap : actionAsArray->GetAssociativeMap()) { - if (typeValueMap.first == "Type") { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; - type = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); - } else { - valueParameterName = typeValueMap.first; - // Message is the only known string parameter - if (valueParameterName == "Message") { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFString) continue; - valueParameterString = static_cast<AMFStringValue*>(typeValueMap.second)->GetStringValue(); - } else { - if (typeValueMap.second->GetValueType() != AMFValueType::AMFDouble) continue; - valueParameterDouble = static_cast<AMFDoubleValue*>(typeValueMap.second)->GetDoubleValue(); - } - } - } +#include "Action.h" - behaviorID = GetBehaviorIDFromArgument(arguments); +UpdateActionMessage::UpdateActionMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { + actionContext = ActionContext(arguments); - auto* actionIndexValue = arguments->FindValue<AMFDoubleValue>("actionIndex"); - if (!actionIndexValue) return; + auto* actionValue = arguments->FindValue<AMFArrayValue>("action"); + if (!actionValue) return; - actionIndex = static_cast<uint32_t>(actionIndexValue->GetDoubleValue()); + action = Action(actionValue); + actionIndex = GetActionIndexFromArgument(arguments); - stripID = GetStripIDFromArgument(arguments); - - stateID = GetBehaviorStateFromArgument(arguments); - Game::logger->LogDebug("UpdateActionMessage", "t %s vpn %s vps %s vpd %f bhId %i acnNdx %i stpId %i sttId %i", type.c_str(), valueParameterName.c_str(), valueParameterString.c_str(), valueParameterDouble, behaviorID, actionIndex, stripID, stateID); + Game::logger->LogDebug("UpdateActionMessage", "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()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h index a42be22b..0a03ce9e 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h @@ -1,30 +1,26 @@ #ifndef __UPDATEACTIONMESSAGE__H__ #define __UPDATEACTIONMESSAGE__H__ +#include "Action.h" +#include "ActionContext.h" #include "BehaviorMessageBase.h" class AMFArrayValue; +/** + * @brief Sent when a player updates the value in an Action + * + */ class UpdateActionMessage : public BehaviorMessageBase { public: UpdateActionMessage(AMFArrayValue* arguments); - const std::string& GetType() { return type; }; - const std::string& GetValueParameterName() { return valueParameterName; }; - const std::string& GetValueParameterString() { return valueParameterString; }; - const double GetValueParameterDouble() { return valueParameterDouble; }; - const uint32_t GetBehaviorID() { return behaviorID; }; const uint32_t GetActionIndex() { return actionIndex; }; - const StripId GetStripID() { return stripID; }; - const BehaviorState GetStateID() { return stateID; }; + ActionContext GetActionContext() { return actionContext; }; + Action GetAction() { return action; }; private: - std::string type; - std::string valueParameterName; - std::string valueParameterString; - double valueParameterDouble; - uint32_t behaviorID; uint32_t actionIndex; - StripId stripID; - BehaviorState stateID; -}; + ActionContext actionContext; + Action action; +}; #endif //!__UPDATEACTIONMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp index 60e2f0f3..073db9b4 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp @@ -1,20 +1,8 @@ #include "UpdateStripUiMessage.h" -UpdateStripUiMessage::UpdateStripUiMessage(AMFArrayValue* arguments) { - auto* uiArray = arguments->FindValue<AMFArrayValue>("ui"); - if (!uiArray) return; +UpdateStripUiMessage::UpdateStripUiMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { + position = StripUiPosition(arguments); + actionContext = ActionContext(arguments); - auto* xPositionValue = uiArray->FindValue<AMFDoubleValue>("x"); - auto* yPositionValue = uiArray->FindValue<AMFDoubleValue>("y"); - if (!xPositionValue || !yPositionValue) return; - - yPosition = yPositionValue->GetDoubleValue(); - xPosition = xPositionValue->GetDoubleValue(); - - stripID = GetStripIDFromArgument(arguments); - - stateID = GetBehaviorStateFromArgument(arguments); - - behaviorID = GetBehaviorIDFromArgument(arguments); - Game::logger->LogDebug("UpdateStripUIMessage", "x %f y %f stpId %i sttId %i bhId %i", xPosition, yPosition, stripID, stateID, behaviorID); + Game::logger->LogDebug("UpdateStripUIMessage", "xPosition %f yPosition %f stripId %i stateId %i behaviorId %i", position.GetX(), position.GetY(), actionContext.GetStripId(), actionContext.GetStateId(), behaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h index ca626120..6d96f90c 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h @@ -1,24 +1,24 @@ #ifndef __UPDATESTRIPUIMESSAGE__H__ #define __UPDATESTRIPUIMESSAGE__H__ +#include "ActionContext.h" #include "BehaviorMessageBase.h" +#include "StripUiPosition.h" class AMFArrayValue; +/** + * @brief Sent when a player moves the first Action in a Strip + * + */ class UpdateStripUiMessage : public BehaviorMessageBase { public: UpdateStripUiMessage(AMFArrayValue* arguments); - const double GetYPosition() { return yPosition; }; - const double GetXPosition() { return xPosition; }; - const StripId GetStripID() { return stripID; }; - const BehaviorState GetStateID() { return stateID; }; - const uint32_t GetBehaviorID() { return behaviorID; }; + StripUiPosition GetPosition() { return position; }; + ActionContext GetActionContext() { return actionContext; }; private: - double yPosition; - double xPosition; - StripId stripID; - BehaviorState stateID; - uint32_t behaviorID; + StripUiPosition position; + ActionContext actionContext; }; #endif //!__UPDATESTRIPUIMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.cpp b/dGame/dPropertyBehaviors/ControlBehaviors.cpp index 3e8bbacc..dfb22b59 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviors.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviors.cpp @@ -15,6 +15,7 @@ #include "CDClientDatabase.h" // Message includes +#include "Action.h" #include "AddActionMessage.h" #include "AddStripMessage.h" #include "AddMessage.h" @@ -248,18 +249,23 @@ void ControlBehaviors::SendBehaviorBlocksToClient(ModelComponent* modelComponent void ControlBehaviors::UpdateAction(AMFArrayValue* arguments) { UpdateActionMessage updateActionMessage(arguments); - auto* blockDefinition = GetBlockInfo(updateActionMessage.GetType()); + auto* blockDefinition = GetBlockInfo(updateActionMessage.GetAction().GetType()); - if (updateActionMessage.GetValueParameterString().size() > 0) { - if (updateActionMessage.GetValueParameterString().size() < blockDefinition->GetMinimumValue() || - updateActionMessage.GetValueParameterString().size() > blockDefinition->GetMaximumValue()) { - Game::logger->Log("ControlBehaviors", "Updated block %s is out of range. Ignoring update", updateActionMessage.GetType().c_str()); + if (!blockDefinition) { + Game::logger->Log("ControlBehaviors", "Received undefined block type %s. Ignoring.", updateActionMessage.GetAction().GetType().c_str()); + return; + } + + if (updateActionMessage.GetAction().GetValueParameterString().size() > 0) { + if (updateActionMessage.GetAction().GetValueParameterString().size() < blockDefinition->GetMinimumValue() || + updateActionMessage.GetAction().GetValueParameterString().size() > blockDefinition->GetMaximumValue()) { + Game::logger->Log("ControlBehaviors", "Updated block %s is out of range. Ignoring update", updateActionMessage.GetAction().GetType().c_str()); return; } } else { - if (updateActionMessage.GetValueParameterDouble() < blockDefinition->GetMinimumValue() || - updateActionMessage.GetValueParameterDouble() > blockDefinition->GetMaximumValue()) { - Game::logger->Log("ControlBehaviors", "Updated block %s is out of range. Ignoring update", updateActionMessage.GetType().c_str()); + if (updateActionMessage.GetAction().GetValueParameterDouble() < blockDefinition->GetMinimumValue() || + updateActionMessage.GetAction().GetValueParameterDouble() > blockDefinition->GetMaximumValue()) { + Game::logger->Log("ControlBehaviors", "Updated block %s is out of range. Ignoring update", updateActionMessage.GetAction().GetType().c_str()); return; } } @@ -452,5 +458,5 @@ ControlBehaviors::ControlBehaviors() { BlockDefinition* ControlBehaviors::GetBlockInfo(const BlockName& blockName) { auto blockDefinition = blockTypes.find(blockName); - return blockDefinition != blockTypes.end() ? blockDefinition->second : &BlockDefinition::blockDefinitionDefault; + return blockDefinition != blockTypes.end() ? blockDefinition->second : nullptr; } diff --git a/tests/dCommonTests/AMFDeserializeTests.cpp b/tests/dCommonTests/AMFDeserializeTests.cpp index a823b0dc..3811a706 100644 --- a/tests/dCommonTests/AMFDeserializeTests.cpp +++ b/tests/dCommonTests/AMFDeserializeTests.cpp @@ -258,9 +258,9 @@ TEST(dCommonTests, AMFDeserializeLivePacketTest) { ASSERT_EQ(actionIndex->GetDoubleValue(), 0.0f); - auto stripIDExecution = stripsPosition0->FindValue<AMFDoubleValue>("id"); + auto stripIdExecution = stripsPosition0->FindValue<AMFDoubleValue>("id"); - ASSERT_EQ(stripIDExecution->GetDoubleValue(), 0.0f); + ASSERT_EQ(stripIdExecution->GetDoubleValue(), 0.0f); auto stateIDExecution = executionState->FindValue<AMFDoubleValue>("stateID"); @@ -298,9 +298,9 @@ TEST(dCommonTests, AMFDeserializeLivePacketTest) { ASSERT_EQ(xPos->GetDoubleValue(), 103.0f); ASSERT_EQ(yPos->GetDoubleValue(), 82.0f); - auto stripID = firstStrip->FindValue<AMFDoubleValue>("id"); + auto stripId = firstStrip->FindValue<AMFDoubleValue>("id"); - ASSERT_EQ(stripID->GetDoubleValue(), 0.0f); + ASSERT_EQ(stripId->GetDoubleValue(), 0.0f); auto firstAction = dynamic_cast<AMFArrayValue*>(actionsInFirstStrip[0]); diff --git a/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp b/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp index 7905c19a..631f0d2d 100644 --- a/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp +++ b/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp @@ -1,7 +1,12 @@ +#include "Action.h" +#include "AMFFormat.h" +#include "AMFDeserialize.h" #include "GameMessages.h" #include "GameDependencies.h" -#include "AMFDeserialize.h" +#include <gtest/gtest.h> + +// Message includes #include "AddActionMessage.h" #include "AddStripMessage.h" #include "AddMessage.h" @@ -16,9 +21,6 @@ #include "UpdateActionMessage.h" #include "UpdateStripUiMessage.h" -#include <gtest/gtest.h> -#include <fstream> - class GameMessageTests: public GameDependenciesTest { protected: void SetUp() override { @@ -27,7 +29,6 @@ protected: void TearDown() override { TearDownDependencies(); } - std::string ReadFromFile(std::string filename) { std::ifstream file(filename, std::ios::binary); std::string readFile; @@ -35,10 +36,8 @@ protected: char readCharacter = file.get(); readFile.push_back(readCharacter); } - return readFile; } - AMFArrayValue* ReadArrayFromBitStream(RakNet::BitStream* inStream) { AMFDeserialize des; AMFValue* readArray = des.Read(inStream); @@ -90,23 +89,23 @@ TEST_F(GameMessageTests, ControlBehaviorAddStrip) { auto data = ReadFromFile("addStrip"); RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); AddStripMessage addStrip(ReadArrayFromBitStream(&inStream)); - ASSERT_FLOAT_EQ(addStrip.GetXPosition(), 50.65); - ASSERT_FLOAT_EQ(addStrip.GetYPosition(), 178.05); - ASSERT_EQ(addStrip.GetStripId(), 0); - ASSERT_EQ(static_cast<uint32_t>(addStrip.GetStateId()), 0); + ASSERT_FLOAT_EQ(addStrip.GetPosition().GetX(), 50.65); + ASSERT_FLOAT_EQ(addStrip.GetPosition().GetY(), 178.05); + ASSERT_EQ(addStrip.GetActionContext().GetStripId(), 0); + ASSERT_EQ(static_cast<uint32_t>(addStrip.GetActionContext().GetStateId()), 0); ASSERT_EQ(addStrip.GetBehaviorId(), -1); - ASSERT_EQ(addStrip.GetType(), "DropImagination"); - ASSERT_EQ(addStrip.GetValueParameterName(), "Amount"); - ASSERT_EQ(addStrip.GetValueParameterString(), ""); - ASSERT_FLOAT_EQ(addStrip.GetValueParameterDouble(), 1.0); + ASSERT_EQ(addStrip.GetActionsToAdd().front().GetType(), "DropImagination"); + ASSERT_EQ(addStrip.GetActionsToAdd().front().GetValueParameterName(), "Amount"); + ASSERT_EQ(addStrip.GetActionsToAdd().front().GetValueParameterString(), ""); + ASSERT_FLOAT_EQ(addStrip.GetActionsToAdd().front().GetValueParameterDouble(), 1.0); } TEST_F(GameMessageTests, ControlBehaviorRemoveStrip) { auto data = ReadFromFile("removeStrip"); RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); RemoveStripMessage removeStrip(ReadArrayFromBitStream(&inStream)); - ASSERT_EQ(static_cast<int32_t>(removeStrip.GetStripId()), 1); - ASSERT_EQ(static_cast<int32_t>(removeStrip.GetBehaviorState()), 0); + ASSERT_EQ(static_cast<int32_t>(removeStrip.GetActionContext().GetStripId()), 1); + ASSERT_EQ(static_cast<int32_t>(removeStrip.GetActionContext().GetStateId()), 0); ASSERT_EQ(removeStrip.GetBehaviorId(), -1); } @@ -114,12 +113,12 @@ TEST_F(GameMessageTests, ControlBehaviorMergeStrips) { auto data = ReadFromFile("mergeStrips"); RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); MergeStripsMessage mergeStrips(ReadArrayFromBitStream(&inStream)); - ASSERT_EQ(mergeStrips.GetSrcStripID(), 2); - ASSERT_EQ(mergeStrips.GetDstStripID(), 0); - ASSERT_EQ(static_cast<uint32_t>(mergeStrips.GetSrcStateID()), 0); - ASSERT_EQ(static_cast<uint32_t>(mergeStrips.GetDstStateID()), 0); + ASSERT_EQ(mergeStrips.GetSourceActionContext().GetStripId(), 2); + ASSERT_EQ(mergeStrips.GetDestinationActionContext().GetStripId(), 0); + ASSERT_EQ(static_cast<uint32_t>(mergeStrips.GetSourceActionContext().GetStateId()), 0); + ASSERT_EQ(static_cast<uint32_t>(mergeStrips.GetDestinationActionContext().GetStateId()), 0); ASSERT_EQ(mergeStrips.GetDstActionIndex(), 0); - ASSERT_EQ(mergeStrips.GetBehaviorID(), -1); + ASSERT_EQ(mergeStrips.GetBehaviorId(), -1); } TEST_F(GameMessageTests, ControlBehaviorSplitStrip) { @@ -128,12 +127,12 @@ TEST_F(GameMessageTests, ControlBehaviorSplitStrip) { SplitStripMessage splitStrip(ReadArrayFromBitStream(&inStream)); ASSERT_EQ(splitStrip.GetBehaviorId(), -1); - ASSERT_FLOAT_EQ(splitStrip.GetXPosition(), 275.65); - ASSERT_FLOAT_EQ(splitStrip.GetYPosition(), 28.7); - ASSERT_EQ(splitStrip.GetSrcStripId(), 0); - ASSERT_EQ(splitStrip.GetDstStripId(), 2); - ASSERT_EQ(static_cast<uint32_t>(splitStrip.GetSrcStateId()), 0); - ASSERT_EQ(static_cast<uint32_t>(splitStrip.GetDstStateId()), 0); + ASSERT_FLOAT_EQ(splitStrip.GetPosition().GetX(), 275.65); + ASSERT_FLOAT_EQ(splitStrip.GetPosition().GetY(), 28.7); + ASSERT_EQ(splitStrip.GetSourceActionContext().GetStripId(), 0); + ASSERT_EQ(splitStrip.GetDestinationActionContext().GetStripId(), 2); + ASSERT_EQ(static_cast<uint32_t>(splitStrip.GetSourceActionContext().GetStateId()), 0); + ASSERT_EQ(static_cast<uint32_t>(splitStrip.GetDestinationActionContext().GetStateId()), 0); ASSERT_EQ(splitStrip.GetSrcActionIndex(), 1); } @@ -141,11 +140,11 @@ TEST_F(GameMessageTests, ControlBehaviorUpdateStripUI) { auto data = ReadFromFile("updateStripUI"); RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); UpdateStripUiMessage updateStripUi(ReadArrayFromBitStream(&inStream)); - ASSERT_FLOAT_EQ(updateStripUi.GetXPosition(), 116.65); - ASSERT_FLOAT_EQ(updateStripUi.GetYPosition(), 35.35); - ASSERT_EQ(updateStripUi.GetStripID(), 0); - ASSERT_EQ(static_cast<uint32_t>(updateStripUi.GetStateID()), 0); - ASSERT_EQ(updateStripUi.GetBehaviorID(), -1); + ASSERT_FLOAT_EQ(updateStripUi.GetPosition().GetX(), 116.65); + ASSERT_FLOAT_EQ(updateStripUi.GetPosition().GetY(), 35.35); + ASSERT_EQ(updateStripUi.GetActionContext().GetStripId(), 0); + ASSERT_EQ(static_cast<uint32_t>(updateStripUi.GetActionContext().GetStateId()), 0); + ASSERT_EQ(updateStripUi.GetBehaviorId(), -1); } TEST_F(GameMessageTests, ControlBehaviorAddAction) { @@ -153,12 +152,12 @@ TEST_F(GameMessageTests, ControlBehaviorAddAction) { RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); AddActionMessage addAction(ReadArrayFromBitStream(&inStream)); ASSERT_EQ(addAction.GetActionIndex(), 3); - ASSERT_EQ(addAction.GetStripId(), 0); - ASSERT_EQ(static_cast<uint32_t>(addAction.GetStateId()), 0); - ASSERT_EQ(addAction.GetType(), "DoDamage"); - ASSERT_EQ(addAction.GetValueParameterName(), ""); - ASSERT_EQ(addAction.GetValueParameterString(), ""); - ASSERT_EQ(addAction.GetValueParameterDouble(), 0.0); + ASSERT_EQ(addAction.GetActionContext().GetStripId(), 0); + ASSERT_EQ(static_cast<uint32_t>(addAction.GetActionContext().GetStateId()), 0); + ASSERT_EQ(addAction.GetAction().GetType(), "DoDamage"); + ASSERT_EQ(addAction.GetAction().GetValueParameterName(), ""); + ASSERT_EQ(addAction.GetAction().GetValueParameterString(), ""); + ASSERT_EQ(addAction.GetAction().GetValueParameterDouble(), 0.0); ASSERT_EQ(addAction.GetBehaviorId(), -1); } @@ -168,11 +167,11 @@ TEST_F(GameMessageTests, ControlBehaviorMigrateActions) { MigrateActionsMessage migrateActions(ReadArrayFromBitStream(&inStream)); ASSERT_EQ(migrateActions.GetSrcActionIndex(), 1); ASSERT_EQ(migrateActions.GetDstActionIndex(), 2); - ASSERT_EQ(migrateActions.GetSrcStripID(), 1); - ASSERT_EQ(migrateActions.GetDstStripID(), 0); - ASSERT_EQ(static_cast<uint32_t>(migrateActions.GetSrcStateID()), 0); - ASSERT_EQ(static_cast<uint32_t>(migrateActions.GetDstStateID()), 0); - ASSERT_EQ(migrateActions.GetBehaviorID(), -1); + ASSERT_EQ(migrateActions.GetSourceActionContext().GetStripId(), 1); + ASSERT_EQ(migrateActions.GetDestinationActionContext().GetStripId(), 0); + ASSERT_EQ(static_cast<uint32_t>(migrateActions.GetSourceActionContext().GetStateId()), 0); + ASSERT_EQ(static_cast<uint32_t>(migrateActions.GetDestinationActionContext().GetStateId()), 0); + ASSERT_EQ(migrateActions.GetBehaviorId(), -1); } TEST_F(GameMessageTests, ControlBehaviorRearrangeStrip) { @@ -181,9 +180,9 @@ TEST_F(GameMessageTests, ControlBehaviorRearrangeStrip) { RearrangeStripMessage rearrangeStrip(ReadArrayFromBitStream(&inStream)); ASSERT_EQ(rearrangeStrip.GetSrcActionIndex(), 2); ASSERT_EQ(rearrangeStrip.GetDstActionIndex(), 1); - ASSERT_EQ(rearrangeStrip.GetStripID(), 0); - ASSERT_EQ(rearrangeStrip.GetBehaviorID(), -1); - ASSERT_EQ(static_cast<uint32_t>(rearrangeStrip.GetStateID()), 0); + ASSERT_EQ(rearrangeStrip.GetActionContext().GetStripId(), 0); + ASSERT_EQ(rearrangeStrip.GetBehaviorId(), -1); + ASSERT_EQ(static_cast<uint32_t>(rearrangeStrip.GetActionContext().GetStateId()), 0); } TEST_F(GameMessageTests, ControlBehaviorAdd) { @@ -198,10 +197,10 @@ TEST_F(GameMessageTests, ControlBehaviorRemoveActions) { auto data = ReadFromFile("removeActions"); RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); RemoveActionsMessage removeActions(ReadArrayFromBitStream(&inStream)); - ASSERT_EQ(removeActions.GetBehaviorID(), -1); + ASSERT_EQ(removeActions.GetBehaviorId(), -1); ASSERT_EQ(removeActions.GetActionIndex(), 1); - ASSERT_EQ(removeActions.GetStripID(), 0); - ASSERT_EQ(static_cast<uint32_t>(removeActions.GetStateID()), 0); + ASSERT_EQ(removeActions.GetActionContext().GetStripId(), 0); + ASSERT_EQ(static_cast<uint32_t>(removeActions.GetActionContext().GetStateId()), 0); } TEST_F(GameMessageTests, ControlBehaviorRename) { @@ -209,19 +208,19 @@ TEST_F(GameMessageTests, ControlBehaviorRename) { RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); RenameMessage rename(ReadArrayFromBitStream(&inStream)); ASSERT_EQ(rename.GetName(), "test"); - ASSERT_EQ(rename.GetBehaviorID(), -1); + ASSERT_EQ(rename.GetBehaviorId(), -1); } TEST_F(GameMessageTests, ControlBehaviorUpdateAction) { auto data = ReadFromFile("updateAction"); RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); UpdateActionMessage updateAction(ReadArrayFromBitStream(&inStream)); - ASSERT_EQ(updateAction.GetType(), "FlyDown"); - ASSERT_EQ(updateAction.GetValueParameterName(), "Distance"); - ASSERT_EQ(updateAction.GetValueParameterString(), ""); - ASSERT_EQ(updateAction.GetValueParameterDouble(), 50.0); - ASSERT_EQ(updateAction.GetBehaviorID(), -1); + ASSERT_EQ(updateAction.GetAction().GetType(), "FlyDown"); + ASSERT_EQ(updateAction.GetAction().GetValueParameterName(), "Distance"); + ASSERT_EQ(updateAction.GetAction().GetValueParameterString(), ""); + ASSERT_EQ(updateAction.GetAction().GetValueParameterDouble(), 50.0); + ASSERT_EQ(updateAction.GetBehaviorId(), -1); ASSERT_EQ(updateAction.GetActionIndex(), 1); - ASSERT_EQ(updateAction.GetStripID(), 0); - ASSERT_EQ(static_cast<uint32_t>(updateAction.GetStateID()), 0); + ASSERT_EQ(updateAction.GetActionContext().GetStripId(), 0); + ASSERT_EQ(static_cast<uint32_t>(updateAction.GetActionContext().GetStateId()), 0); } From 6d989f37f1df153eb33d3654b1b681ee91de5da5 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sun, 19 Feb 2023 06:29:14 -0600 Subject: [PATCH 255/322] Breakout ServerDisconnectIdentifiers into an enum (#995) --- dCommon/dEnums/dCommonVars.h | 14 ----------- dCommon/dEnums/eServerDisconnectIdentifiers.h | 24 +++++++++++++++++++ dGame/User.cpp | 3 ++- dGame/dUtilities/SlashCommandHandler.cpp | 5 ++-- dNet/AuthPackets.cpp | 1 + dNet/dServer.cpp | 2 +- dNet/dServer.h | 3 ++- dWorldServer/WorldServer.cpp | 13 +++++----- 8 files changed, 40 insertions(+), 25 deletions(-) create mode 100644 dCommon/dEnums/eServerDisconnectIdentifiers.h diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index 1d4a4c55..2ba8b209 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -261,20 +261,6 @@ enum eReplicaPacketType { PACKET_TYPE_DESTRUCTION //!< A destruction packet }; -enum ServerDisconnectIdentifiers { - SERVER_DISCON_UNKNOWN_SERVER_ERROR = 0, //!< Unknown server error - SERVER_DISCON_DUPLICATE_LOGIN = 4, //!< Used when another user with the same username is logged in (duplicate login) - SERVER_DISCON_SERVER_SHUTDOWN = 5, //!< Used when the server is shutdown - SERVER_DISCON_SERVER_MAP_LOAD_FAILURE = 6, //!< Used when the server cannot load a map - SERVER_DISCON_INVALID_SESSION_KEY = 7, //!< Used if the session is invalid - SERVER_DISCON_ACCOUNT_NOT_IN_PENDING_LIST = 8, //!< ??? - SERVER_DISCON_CHARACTER_NOT_FOUND = 9, //!< Used if a character that the server has is not found (i.e, corruption with user-player data) - SERVER_DISCON_CHARACTER_CORRUPTED = 10, //!< Similar to abovce - SERVER_DISCON_KICK = 11, //!< Used if the user is kicked from the server - SERVER_DISCON_FREE_TRIAL_EXPIRED = 12, //!< Used if the user's free trial expired - SERVER_DISCON_PLAY_SCHEDULE_TIME_DONE = 13 //!< Used if the user's play time is used up -}; - //! The Behavior Types for use with the AI system enum eCombatBehaviorTypes : uint32_t { PASSIVE = 0, //!< The object is passive diff --git a/dCommon/dEnums/eServerDisconnectIdentifiers.h b/dCommon/dEnums/eServerDisconnectIdentifiers.h new file mode 100644 index 00000000..99d2cd44 --- /dev/null +++ b/dCommon/dEnums/eServerDisconnectIdentifiers.h @@ -0,0 +1,24 @@ +#ifndef __ESERVERDISCONNECTIDENTIFIERS__H__ +#define __ESERVERDISCONNECTIDENTIFIERS__H__ + +#include <cstdint> + +enum class eServerDisconnectIdentifiers : uint32_t { + UNKNOWN_SERVER_ERROR = 0, + WRONG_GAME_VERSION, + WRONG_SERVER_VERSION, + CONNECTION_ON_INVALID_PORT, + DUPLICATE_LOGIN, + SERVER_SHUTDOWN, + SERVER_MAP_LOAD_FAILURE, + INVALID_SESSION_KEY, + ACCOUNT_NOT_IN_PENDING_LIST, + CHARACTER_NOT_FOUND, + CHARACTER_CORRUPTED, + KICK, + SAVE_FAILURE, + FREE_TRIAL_EXPIRED, + PLAY_SCHEDULE_TIME_DONE +}; + +#endif //!__ESERVERDISCONNECTIDENTIFIERS__H__ diff --git a/dGame/User.cpp b/dGame/User.cpp index 20cc3ab4..dc607cd0 100644 --- a/dGame/User.cpp +++ b/dGame/User.cpp @@ -5,6 +5,7 @@ #include "dLogger.h" #include "Game.h" #include "dZoneManager.h" +#include "eServerDisconnectIdentifiers.h" User::User(const SystemAddress& sysAddr, const std::string& username, const std::string& sessionKey) { m_AccountID = 0; @@ -126,6 +127,6 @@ void User::UserOutOfSync() { if (m_AmountOfTimesOutOfSync > m_MaxDesyncAllowed) { //YEET Game::logger->Log("User", "User %s was out of sync %i times out of %i, disconnecting for suspected speedhacking.", m_Username.c_str(), m_AmountOfTimesOutOfSync, m_MaxDesyncAllowed); - Game::server->Disconnect(this->m_SystemAddress, SERVER_DISCON_KICK); + Game::server->Disconnect(this->m_SystemAddress, eServerDisconnectIdentifiers::PLAY_SCHEDULE_TIME_DONE); } } diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index e558e19c..8ae0b441 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -74,6 +74,7 @@ #include "dMessageIdentifiers.h" #include "eMissionState.h" #include "TriggerComponent.h" +#include "eServerDisconnectIdentifiers.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { std::string chatCommand; @@ -1094,7 +1095,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - Game::server->Disconnect(player->GetSystemAddress(), SERVER_DISCON_KICK); + Game::server->Disconnect(player->GetSystemAddress(), eServerDisconnectIdentifiers::KICK); ChatPackets::SendSystemMessage(sysAddr, u"Kicked: " + username); } else { @@ -1140,7 +1141,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit delete userUpdate; if (player != nullptr) { - Game::server->Disconnect(player->GetSystemAddress(), SERVER_DISCON_KICK); + Game::server->Disconnect(player->GetSystemAddress(), eServerDisconnectIdentifiers::FREE_TRIAL_EXPIRED); } ChatPackets::SendSystemMessage(sysAddr, u"Banned: " + GeneralUtils::ASCIIToUTF16(args[0])); diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index 636f3fcf..4e7cb0a6 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -21,6 +21,7 @@ #include "Game.h" #include "dConfig.h" +#include "eServerDisconnectIdentifiers.h" void AuthPackets::HandleHandshake(dServer* server, Packet* packet) { RakNet::BitStream inStream(packet->data, packet->length, false); diff --git a/dNet/dServer.cpp b/dNet/dServer.cpp index a3961d45..c91c7508 100644 --- a/dNet/dServer.cpp +++ b/dNet/dServer.cpp @@ -164,7 +164,7 @@ void dServer::SendToMaster(RakNet::BitStream* bitStream) { mMasterPeer->Send(bitStream, SYSTEM_PRIORITY, RELIABLE_ORDERED, 0, mMasterSystemAddress, false); } -void dServer::Disconnect(const SystemAddress& sysAddr, uint32_t disconNotifyID) { +void dServer::Disconnect(const SystemAddress& sysAddr, eServerDisconnectIdentifiers disconNotifyID) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, SERVER, MSG_SERVER_DISCONNECT_NOTIFY); bitStream.Write(disconNotifyID); diff --git a/dNet/dServer.h b/dNet/dServer.h index d9e74d2e..797647b6 100644 --- a/dNet/dServer.h +++ b/dNet/dServer.h @@ -6,6 +6,7 @@ class dLogger; class dConfig; +enum class eServerDisconnectIdentifiers : uint32_t; enum class ServerType : uint32_t { Master, @@ -41,7 +42,7 @@ public: virtual void Send(RakNet::BitStream* bitStream, const SystemAddress& sysAddr, bool broadcast); void SendToMaster(RakNet::BitStream* bitStream); - void Disconnect(const SystemAddress& sysAddr, uint32_t disconNotifyID); + void Disconnect(const SystemAddress& sysAddr, eServerDisconnectIdentifiers disconNotifyID); bool IsConnected(const SystemAddress& sysAddr); const std::string& GetIP() const { return mIP; } diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index b655bef3..f8d50f5b 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -63,6 +63,7 @@ #include "eBlueprintSaveResponseType.h" #include "AMFFormat.h" #include "NiPoint3.h" +#include "eServerDisconnectIdentifiers.h" #include "ZCompression.h" @@ -765,7 +766,7 @@ void HandlePacket(Packet* packet) { //Verify it: if (userHash != it->second.hash) { Game::logger->Log("WorldServer", "SOMEONE IS TRYING TO HACK? SESSION KEY MISMATCH: ours: %s != master: %s", userHash.c_str(), it->second.hash.c_str()); - Game::server->Disconnect(it->second.sysAddr, SERVER_DISCON_INVALID_SESSION_KEY); + Game::server->Disconnect(it->second.sysAddr, eServerDisconnectIdentifiers::INVALID_SESSION_KEY); return; } else { Game::logger->Log("WorldServer", "User %s authenticated with correct key.", username.c_str()); @@ -855,7 +856,7 @@ void HandlePacket(Packet* packet) { //Check the key: if (sessionKey != std::atoi(user->GetSessionKey().c_str())) { Game::logger->Log("WorldServer", "Got new session alert for user %s, but the session key is invalid.", username.c_str()); - Game::server->Disconnect(user->GetSystemAddress(), SERVER_DISCON_INVALID_SESSION_KEY); + Game::server->Disconnect(user->GetSystemAddress(), eServerDisconnectIdentifiers::INVALID_SESSION_KEY); return; } break; @@ -896,7 +897,7 @@ void HandlePacket(Packet* packet) { // Developers may skip this check if (gmLevel < 8 && clientDatabaseChecksum != databaseChecksum) { Game::logger->Log("WorldServer", "Client's database checksum does not match the server's, aborting connection."); - Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_KICK); + Game::server->Disconnect(packet->systemAddress, eServerDisconnectIdentifiers::WRONG_GAME_VERSION); return; } } @@ -1184,7 +1185,7 @@ void HandlePacket(Packet* packet) { } } else { Game::logger->Log("WorldServer", "Couldn't find character to log in with for user %s (%i)!", user->GetUsername().c_str(), user->GetAccountID()); - Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_CHARACTER_NOT_FOUND); + Game::server->Disconnect(packet->systemAddress, eServerDisconnectIdentifiers::CHARACTER_NOT_FOUND); } } else { Game::logger->Log("WorldServer", "Couldn't get user for level load complete!"); @@ -1269,7 +1270,7 @@ void HandlePacket(Packet* packet) { if (user) { user->UserOutOfSync(); } else { - Game::server->Disconnect(packet->systemAddress, SERVER_DISCON_KICK); + Game::server->Disconnect(packet->systemAddress, eServerDisconnectIdentifiers::KICK); } break; } @@ -1309,7 +1310,7 @@ void WorldShutdownProcess(uint32_t zoneId) { while (Game::server->GetReplicaManager()->GetParticipantCount() > 0) { const auto& player = Game::server->GetReplicaManager()->GetParticipantAtIndex(0); - Game::server->Disconnect(player, SERVER_DISCON_KICK); + Game::server->Disconnect(player, eServerDisconnectIdentifiers::SERVER_SHUTDOWN); } SendShutdownMessageToMaster(); } From b6fc959433d03849ef96b071a77cc7248e62b97a Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 28 Feb 2023 15:30:28 -0800 Subject: [PATCH 256/322] Fix shark stinky fish death animation (#1004) --- dScripts/02_server/Objects/StinkyFishTarget.cpp | 4 +++- dScripts/02_server/Objects/StinkyFishTarget.h | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/dScripts/02_server/Objects/StinkyFishTarget.cpp b/dScripts/02_server/Objects/StinkyFishTarget.cpp index 21d92fac..459e0bbe 100644 --- a/dScripts/02_server/Objects/StinkyFishTarget.cpp +++ b/dScripts/02_server/Objects/StinkyFishTarget.cpp @@ -1,6 +1,7 @@ #include "StinkyFishTarget.h" #include "EntityManager.h" #include "EntityInfo.h" +#include "Entity.h" void StinkyFishTarget::OnStartup(Entity* self) { auto position = self->GetPosition(); @@ -16,6 +17,7 @@ void StinkyFishTarget::OnSkillEventFired(Entity* self, Entity* caster, const std self->SetVar<LWOOBJID>(u"player", caster->GetObjectID()); EntityInfo entityInfo{}; + entityInfo.lot = SHARK_LOT; entityInfo.pos = self->GetPosition(); entityInfo.rot = self->GetRotation(); entityInfo.spawnerID = self->GetObjectID(); @@ -35,7 +37,7 @@ void StinkyFishTarget::OnTimerDone(Entity* self, std::string timerName) { const auto playerID = self->GetVar<LWOOBJID>(u"player"); auto* fish = EntityManager::Instance()->GetEntity(self->GetVar<LWOOBJID>(u"fish")); - if (fish != nullptr) { + if (fish) { fish->Smash(playerID); self->Smash(playerID); } diff --git a/dScripts/02_server/Objects/StinkyFishTarget.h b/dScripts/02_server/Objects/StinkyFishTarget.h index 6c52171d..b8f9e9ae 100644 --- a/dScripts/02_server/Objects/StinkyFishTarget.h +++ b/dScripts/02_server/Objects/StinkyFishTarget.h @@ -2,7 +2,10 @@ #include "CppScripts.h" class StinkyFishTarget : public CppScripts::Script { +public: void OnStartup(Entity* self) override; void OnSkillEventFired(Entity* self, Entity* caster, const std::string& message) override; void OnTimerDone(Entity* self, std::string timerName) override; +private: + const LOT SHARK_LOT = 8570; }; From 3e482602d4f29103ebba4fb29a8a28c3a0166150 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 3 Mar 2023 18:45:01 -0800 Subject: [PATCH 257/322] Fix non-parallel timers in CombatAIComponent (#1008) * Fix non-parelell timers --- dGame/dComponents/BaseCombatAIComponent.cpp | 41 ++++++++------------- dGame/dComponents/BaseCombatAIComponent.h | 5 --- 2 files changed, 15 insertions(+), 31 deletions(-) diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 081496a4..8e778d1d 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -22,6 +22,7 @@ #include "SkillComponent.h" #include "RebuildComponent.h" #include "DestroyableComponent.h" +#include "Metrics.hpp" BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id): Component(parent) { m_Target = LWOOBJID_EMPTY; @@ -228,6 +229,18 @@ void BaseCombatAIComponent::Update(const float deltaTime) { void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { + bool hasSkillToCast = false; + for (auto& entry : m_SkillEntries) { + if (entry.cooldown > 0.0f) { + entry.cooldown -= deltaTime; + } else { + hasSkillToCast = true; + } + } + + bool hadRemainingDowntime = m_SkillTime > 0.0f; + if (m_SkillTime > 0.0f) m_SkillTime -= deltaTime; + auto* rebuild = m_Parent->GetComponent<RebuildComponent>(); if (rebuild != nullptr) { @@ -258,9 +271,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { m_Stunned = false; } - if (m_Stunned) { - return; - } + if (m_Stunned || hadRemainingDowntime) return; auto newTarget = FindTarget(); @@ -325,27 +336,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { SetAiState(AiState::idle); } - for (auto i = 0; i < m_SkillEntries.size(); ++i) { - auto entry = m_SkillEntries.at(i); - - if (entry.cooldown > 0) { - entry.cooldown -= deltaTime; - - m_SkillEntries[i] = entry; - } - } - - if (m_SkillTime > 0) { - m_SkillTime -= deltaTime; - - return; - } - - if (m_Downtime > 0) { - m_Downtime -= deltaTime; - - return; - } + if (!hasSkillToCast) return; if (m_Target == LWOOBJID_EMPTY) { SetAiState(AiState::idle); @@ -353,8 +344,6 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { return; } - m_Downtime = 0.5f; - auto* target = GetTargetEntity(); if (target != nullptr) { diff --git a/dGame/dComponents/BaseCombatAIComponent.h b/dGame/dComponents/BaseCombatAIComponent.h index 1f17d562..6e55a4b1 100644 --- a/dGame/dComponents/BaseCombatAIComponent.h +++ b/dGame/dComponents/BaseCombatAIComponent.h @@ -340,11 +340,6 @@ private: */ bool m_StunImmune = false; - /** - * Time taken between actions - */ - float m_Downtime = 0; - /** * How long this entity needs to execute its skill */ From a0c0a879564279f035066eeff65481c14ae90aab Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 3 Mar 2023 22:58:29 -0800 Subject: [PATCH 258/322] Fix Trigger Missions (#1010) --- dGame/dComponents/TriggerComponent.cpp | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp index 4ed95a15..fe3c7792 100644 --- a/dGame/dComponents/TriggerComponent.cpp +++ b/dGame/dComponents/TriggerComponent.cpp @@ -163,19 +163,14 @@ void TriggerComponent::HandleSetPhysicsVolume(Entity* targetEntity, std::vector< void TriggerComponent::HandleUpdateMission(Entity* targetEntity, std::vector<std::string> argArray) { CDMissionTasksTable* missionTasksTable = CDClientManager::Instance()->GetTable<CDMissionTasksTable>("MissionTasks"); std::vector<CDMissionTasks> missionTasks = missionTasksTable->Query([=](CDMissionTasks entry) { - std::string lowerTargetGroup; - for (char character : entry.targetGroup) { - lowerTargetGroup.push_back(std::tolower(character)); // make lowercase to ensure it works - } - - return (lowerTargetGroup == argArray[4]); + return (entry.targetGroup == argArray.at(4)); }); for (const CDMissionTasks& task : missionTasks) { MissionComponent* missionComponent = targetEntity->GetComponent<MissionComponent>(); if (!missionComponent) continue; - missionComponent->ForceProgress(task.id, task.uid, std::stoi(argArray[2])); + missionComponent->ForceProgress(task.id, task.uid, std::stoi(argArray.at(2))); } } From 2837f68f44a814c27e1d5dbffb4bd9ab1c09106d Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 3 Mar 2023 22:59:37 -0800 Subject: [PATCH 259/322] Fix stuns with mast teleport (#1003) --- dScripts/02_server/Map/GF/MastTeleport.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/dScripts/02_server/Map/GF/MastTeleport.cpp b/dScripts/02_server/Map/GF/MastTeleport.cpp index dac5783c..6e50c6ec 100644 --- a/dScripts/02_server/Map/GF/MastTeleport.cpp +++ b/dScripts/02_server/Map/GF/MastTeleport.cpp @@ -2,6 +2,7 @@ #include "EntityManager.h" #include "GameMessages.h" #include "Preconditions.h" +#include "DestroyableComponent.h" #ifdef _WIN32 #define _USE_MATH_DEFINES @@ -19,6 +20,8 @@ void MastTeleport::OnRebuildComplete(Entity* self, Entity* target) { GameMessages::SendSetStunned(target->GetObjectID(), eStateChangeType::PUSH, target->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true ); + auto* destroyableComponent = target->GetComponent<DestroyableComponent>(); + if (destroyableComponent) destroyableComponent->SetStatusImmunity(eStateChangeType::PUSH, true, true, true, true, true, false, false, true, true); self->AddTimer("Start", 3); } @@ -55,7 +58,7 @@ void MastTeleport::OnTimerDone(Entity* self, std::string timerName) { GameMessages::SendPlayFXEffect(playerId, 6039, u"hook", "hook", LWOOBJID_EMPTY, 1, 1, true); - GameMessages::SendPlayAnimation(player, u"crow-swing-no-equip"); + GameMessages::SendPlayAnimation(player, u"crow-swing-no-equip", 4.0f); GameMessages::SendPlayAnimation(self, u"swing"); @@ -84,5 +87,8 @@ void MastTeleport::OnTimerDone(Entity* self, std::string timerName) { GameMessages::SendSetStunned(playerId, eStateChangeType::POP, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true ); + auto* destroyableComponent = player->GetComponent<DestroyableComponent>(); + if (destroyableComponent) destroyableComponent->SetStatusImmunity(eStateChangeType::POP, true, true, true, true, true, false, false, true, true); + EntityManager::Instance()->SerializeEntity(player); } } From e524b86e12503144f14b538c6bfd523a7d0c4e31 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 4 Mar 2023 01:16:37 -0600 Subject: [PATCH 260/322] breakout the component types into a scoped enum (#1002) * breakout the component types into a scoped enum tested that things are the same as they were before * fix missed rename * fix brick-by-brick name to be crafting because that's what it is --- dCommon/GeneralUtils.h | 6 + dCommon/dEnums/dCommonVars.h | 51 --- dCommon/dEnums/eReplicaComponentType.h | 127 +++++++ .../Tables/CDComponentsRegistryTable.cpp | 5 +- dDatabase/Tables/CDComponentsRegistryTable.h | 6 +- dGame/Entity.cpp | 309 +++++++++--------- dGame/Entity.h | 15 +- dGame/EntityManager.cpp | 5 +- dGame/EntityManager.h | 3 +- dGame/Player.cpp | 5 +- dGame/dBehaviors/BehaviorContext.cpp | 7 +- dGame/dBehaviors/HealBehavior.cpp | 3 +- dGame/dBehaviors/RepairBehavior.cpp | 3 +- dGame/dBehaviors/SpawnBehavior.cpp | 3 +- dGame/dBehaviors/StunBehavior.cpp | 7 +- dGame/dComponents/BaseCombatAIComponent.cpp | 2 +- dGame/dComponents/BaseCombatAIComponent.h | 7 +- dGame/dComponents/BouncerComponent.h | 3 +- dGame/dComponents/BuffComponent.h | 3 +- dGame/dComponents/BuildBorderComponent.h | 3 +- dGame/dComponents/CharacterComponent.h | 3 +- .../ControllablePhysicsComponent.h | 3 +- dGame/dComponents/DestroyableComponent.cpp | 8 +- dGame/dComponents/DestroyableComponent.h | 3 +- dGame/dComponents/InventoryComponent.cpp | 12 +- dGame/dComponents/InventoryComponent.h | 3 +- dGame/dComponents/LUPExhibitComponent.h | 3 +- dGame/dComponents/LevelProgressionComponent.h | 3 +- dGame/dComponents/MissionComponent.h | 3 +- dGame/dComponents/MissionOfferComponent.cpp | 4 +- dGame/dComponents/MissionOfferComponent.h | 3 +- dGame/dComponents/ModelComponent.cpp | 2 +- dGame/dComponents/ModelComponent.h | 3 +- dGame/dComponents/ModuleAssemblyComponent.h | 3 +- dGame/dComponents/MovementAIComponent.cpp | 6 +- dGame/dComponents/MovementAIComponent.h | 3 +- dGame/dComponents/MovingPlatformComponent.h | 3 +- dGame/dComponents/PetComponent.h | 3 +- dGame/dComponents/PhantomPhysicsComponent.cpp | 4 +- dGame/dComponents/PhantomPhysicsComponent.h | 3 +- .../PlayerForcedMovementComponent.h | 3 +- dGame/dComponents/PossessableComponent.h | 3 +- dGame/dComponents/PossessorComponent.h | 3 +- dGame/dComponents/PropertyComponent.h | 3 +- dGame/dComponents/PropertyEntranceComponent.h | 3 +- .../PropertyManagementComponent.cpp | 2 +- .../dComponents/PropertyManagementComponent.h | 3 +- dGame/dComponents/PropertyVendorComponent.h | 3 +- dGame/dComponents/ProximityMonitorComponent.h | 3 +- dGame/dComponents/RacingControlComponent.h | 3 +- dGame/dComponents/RailActivatorComponent.h | 3 +- dGame/dComponents/RebuildComponent.cpp | 2 +- dGame/dComponents/RebuildComponent.h | 3 +- dGame/dComponents/RenderComponent.cpp | 2 +- dGame/dComponents/RenderComponent.h | 3 +- .../RigidbodyPhantomPhysicsComponent.h | 3 +- dGame/dComponents/RocketLaunchLupComponent.h | 3 +- .../RocketLaunchpadControlComponent.h | 3 +- .../dComponents/ScriptedActivityComponent.cpp | 2 +- dGame/dComponents/ScriptedActivityComponent.h | 3 +- dGame/dComponents/ShootingGalleryComponent.h | 3 +- dGame/dComponents/SimplePhysicsComponent.h | 3 +- dGame/dComponents/SkillComponent.cpp | 2 +- dGame/dComponents/SkillComponent.h | 3 +- dGame/dComponents/SoundTriggerComponent.h | 3 +- dGame/dComponents/SwitchComponent.h | 3 +- dGame/dComponents/TriggerComponent.h | 3 +- dGame/dComponents/VehiclePhysicsComponent.h | 3 +- dGame/dComponents/VendorComponent.cpp | 2 +- dGame/dComponents/VendorComponent.h | 3 +- dGame/dGameMessages/GameMessageHandler.cpp | 7 +- dGame/dGameMessages/GameMessages.cpp | 107 +++--- dGame/dInventory/Inventory.cpp | 5 +- dGame/dInventory/Item.cpp | 5 +- dGame/dMission/Mission.cpp | 4 +- dGame/dMission/MissionTask.cpp | 3 +- dGame/dUtilities/Loot.cpp | 4 +- dGame/dUtilities/Mail.cpp | 5 +- dGame/dUtilities/SlashCommandHandler.cpp | 41 +-- dNet/ClientPackets.cpp | 4 +- .../Enemy/AG/BossSpiderQueenEnemyServer.cpp | 9 +- .../02_server/Enemy/General/BaseEnemyMech.cpp | 3 +- .../02_server/Map/AG/AgCagedBricksServer.cpp | 3 +- .../02_server/Map/AG/AgLaserSensorServer.cpp | 5 +- .../02_server/Map/AG/NpcNjAssistantServer.cpp | 5 +- .../02_server/Map/AG/RemoveRentalGear.cpp | 3 +- dScripts/02_server/Map/FV/FvCandle.cpp | 7 +- dScripts/02_server/Map/GF/GfTikiTorch.cpp | 3 +- .../Map/General/TokenConsoleServer.cpp | 3 +- .../Map/General/TouchMissionUpdateServer.cpp | 3 +- .../Property/AG_Small/EnemySpiderSpawner.cpp | 3 +- .../Map/Property/AG_Small/ZoneAgProperty.cpp | 3 +- .../02_server/Map/SS/SsModularBuildServer.cpp | 3 +- dScripts/NtFactionSpyServer.cpp | 3 +- dScripts/ScriptComponent.h | 3 +- dScripts/ai/AG/AgFans.cpp | 9 +- dScripts/ai/AG/AgImagSmashable.cpp | 3 +- dScripts/ai/AG/AgJetEffectServer.cpp | 5 +- dScripts/ai/AG/AgStromlingProperty.cpp | 3 +- dScripts/ai/GF/GfCampfire.cpp | 5 +- .../ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp | 3 +- dScripts/ai/NP/NpcNpSpacemanBob.cpp | 5 +- dScripts/ai/NS/NsGetFactionMissionServer.cpp | 3 +- dScripts/ai/NS/NsModularBuild.cpp | 3 +- .../ai/SPEC/SpecialImaginePowerupSpawner.cpp | 5 +- .../DestroyableComponentTests.cpp | 5 +- 106 files changed, 598 insertions(+), 430 deletions(-) create mode 100644 dCommon/dEnums/eReplicaComponentType.h diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index d43ad9b1..a2a52b45 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -15,6 +15,7 @@ #include "dLogger.h" enum eInventoryType : uint32_t; +enum class eReplicaComponentType : uint32_t; /*! \file GeneralUtils.hpp @@ -181,6 +182,11 @@ namespace GeneralUtils { return static_cast<eInventoryType>(std::stoul(value)); } + template <> + inline eReplicaComponentType Parse(const char* value) { + return static_cast<eReplicaComponentType>(std::stoul(value)); + } + template <typename T> bool TryParse(const char* value, T& dst) { try { diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index 2ba8b209..da8a2e18 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -365,57 +365,6 @@ enum eNotifyType { NOTIFY_TYPE_NAMINGPET }; -enum eReplicaComponentType : int32_t { - COMPONENT_TYPE_CONTROLLABLE_PHYSICS = 1, //!< The ControllablePhysics Component - COMPONENT_TYPE_RENDER = 2, //!< The Render Component - COMPONENT_TYPE_SIMPLE_PHYSICS = 3, //!< The SimplePhysics Component - COMPONENT_TYPE_CHARACTER = 4, //!< The Character Component - COMPONENT_TYPE_SCRIPT = 5, //!< The Script Component - COMPONENT_TYPE_BOUNCER = 6, //!< The Bouncer Component - COMPONENT_TYPE_BUFF = 7, //!< The Buff Component - COMPONENT_TYPE_SKILL = 9, //!< The Skill Component - COMPONENT_TYPE_ITEM = 11, //!< The Item Component - COMPONENT_TYPE_VENDOR = 16, //!< The Vendor Component - COMPONENT_TYPE_INVENTORY = 17, //!< The Inventory Component - COMPONENT_TYPE_SHOOTING_GALLERY = 19, //!< The Shooting Gallery Component - COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS = 20, //!< The RigidBodyPhantomPhysics Component - COMPONENT_TYPE_COLLECTIBLE = 23, //!< The Collectible Component - COMPONENT_TYPE_MOVING_PLATFORM = 25, //!< The MovingPlatform Component - COMPONENT_TYPE_PET = 26, //!< The Pet Component - COMPONENT_TYPE_VEHICLE_PHYSICS = 30, //!< The VehiclePhysics Component - COMPONENT_TYPE_MOVEMENT_AI = 31, //!< The MovementAI Component - COMPONENT_TYPE_PROPERTY = 36, //!< The Property Component - COMPONENT_TYPE_SCRIPTED_ACTIVITY = 39, //!< The ScriptedActivity Component - COMPONENT_TYPE_PHANTOM_PHYSICS = 40, //!< The PhantomPhysics Component - COMPONENT_TYPE_MODEL = 42, //!< The Model Component - COMPONENT_TYPE_PROPERTY_ENTRANCE = 43, //!< The PhantomPhysics Component - COMPONENT_TYPE_PROPERTY_MANAGEMENT = 45, //!< The PropertyManagement Component - COMPONENT_TYPE_REBUILD = 48, //!< The Rebuild Component - COMPONENT_TYPE_SWITCH = 49, //!< The Switch Component - COMPONENT_TYPE_ZONE_CONTROL = 50, //!< The ZoneControl Component - COMPONENT_TYPE_PACKAGE = 53, //!< The Package Component - COMPONENT_TYPE_PLAYER_FLAG = 58, //!< The PlayerFlag Component - COMPONENT_TYPE_BASE_COMBAT_AI = 60, //!< The BaseCombatAI Component - COMPONENT_TYPE_MODULE_ASSEMBLY = 61, //!< The ModuleAssembly Component - COMPONENT_TYPE_PROPERTY_VENDOR = 65, //!< The PropertyVendor Component - COMPONENT_TYPE_ROCKET_LAUNCH = 67, //!< The RocketLaunch Component - COMPONENT_TYPE_TRIGGER = 69, - COMPONENT_TYPE_RACING_CONTROL = 71, //!< The RacingControl Component - COMPONENT_TYPE_MISSION_OFFER = 73, //!< The MissionOffer Component - COMPONENT_TYPE_EXHIBIT = 75, //!< The Exhibit Component - COMPONENT_TYPE_RACING_STATS = 74, //!< The Racing Stats Component - COMPONENT_TYPE_SOUND_TRIGGER = 77, //!< The Sound Trigger Component - COMPONENT_TYPE_PROXIMITY_MONITOR = 78, //!< The Proximity Monitor Component - COMPONENT_TYPE_MISSION = 84, //!< The Mission Component - COMPONENT_TYPE_ROCKET_LAUNCH_LUP = 97, //!< The LUP Launchpad Componen - COMPONENT_TYPE_RAIL_ACTIVATOR = 104, //!< The Rail Activator Component - COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT = 106, //!< The Player Forced Movement Component - COMPONENT_TYPE_POSSESSABLE = 108, //!< The Possessable Component - COMPONENT_TYPE_LEVEL_PROGRESSION = 109, //!< The Level Progression Component - COMPONENT_TYPE_POSSESSOR = 110, //!< The Possessor Component - COMPONENT_TYPE_BUILD_BORDER = 114, //!< The Build Border Component - COMPONENT_TYPE_DESTROYABLE = 1000, //!< The Destroyable Component -}; enum class UseItemResponse : uint32_t { NoImaginationForPet = 1, diff --git a/dCommon/dEnums/eReplicaComponentType.h b/dCommon/dEnums/eReplicaComponentType.h new file mode 100644 index 00000000..3eee16f3 --- /dev/null +++ b/dCommon/dEnums/eReplicaComponentType.h @@ -0,0 +1,127 @@ +#ifndef __EREPLICACOMPONENTTYPE__H__ +#define __EREPLICACOMPONENTTYPE__H__ + +#include <cstdint> + +enum class eReplicaComponentType : uint32_t { + INVALID = 0, + CONTROLLABLE_PHYSICS, + RENDER, + SIMPLE_PHYSICS, + CHARACTER, + SCRIPT, + BOUNCER, + BUFF, // buff is really 98, this is DESTROYABLE + GHOST, + SKILL, + SPAWNER, + ITEM, + REBUILD, + REBUILD_START, + REBUILD_ACTIVATOR, + ICON_ONLY, + VENDOR, + INVENTORY, + PROJECTILE_PHYSICS, + SHOOTING_GALLERY, + RIGID_BODY_PHANTOM_PHYSICS, + DROP_EFFECT, + CHEST, + COLLECTIBLE, + BLUEPRINT, + MOVING_PLATFORM, + PET, + PLATFORM_BOUNDARY, + MODULE, + ARCADE, + VEHICLE_PHYSICS, // Havok demo based + MOVEMENT_AI, + EXHIBIT, + OVERHEAD_ICON, + PET_CONTROL, + MINIFIG, + PROPERTY, + PET_CREATOR, + MODEL_BUILDER, + SCRIPTED_ACTIVITY, + PHANTOM_PHYSICS, + SPRINGPAD, + MODEL, + PROPERTY_ENTRANCE, + FX, + PROPERTY_MANAGEMENT, + VEHICLE_PHYSICS_NEW, // internal physics based on havok + PHYSICS_SYSTEM, + QUICK_BUILD, + SWITCH, + ZONE_CONTROL, // Minigame + CHANGLING, + CHOICE_BUILD, + PACKAGE, + SOUND_REPEATER, + SOUND_AMBIENT_2D, + SOUND_AMBIENT_3D, + PRECONDITION, + PLAYER_FLAG, + CUSTOM_BUILD_ASSEMBLY, + BASE_COMBAT_AI, + MODULE_ASSEMBLY, + SHOWCASE_MODEL_HANDLER, + RACING_MODULE, + GENERIC_ACTIVATOR, + PROPERTY_VENDOR, + HF_LIGHT_DIRECTION_GADGET, + ROCKET_LAUNCH, + ROCKET_LANDING, + TRIGGER, + DROPPED_LOOT, + RACING_CONTROL, + FACTION_TRIGGER, + MISSION_OFFER, + RACING_STATS, + LUP_EXHIBIT, + BBB, + SOUND_TRIGGER, + PROXIMITY_MONITOR, + RACING_SOUND_TRIGGER, + CHAT, + FRIENDS_LIST, + GUILD, + LOCAL_SYSTEM, + MISSION, + MUTABLE_MODEL_BEHAVIORS, + PATHFINDING, + PET_TAMING_CONTROL, + PROPERTY_EDITOR, + SKINNED_RENDER, + SLASH_COMMAND, + STATUS_EFFECT, + TEAMS, + TEXT_EFFECT, + TRADE, + USER_CONTROL, + IGNORE_LIST, + ROCKET_LAUNCH_LUP, + BUFF_REAL, // the real buff component, should just be name BUFF + INTERACTION_MANAGER, + DONATION_VENDOR, + COMBAT_MEDIATOR, + COMMENDATION_VENDOR, + UNKNOWN_103, + RAIL_ACTIVATOR, + ROLLER, + PLAYER_FORCED_MOVEMENT, + CRAFTING, + POSSESSABLE, + LEVEL_PROGRESSION, + POSSESSOR, + MOUNT_CONTROL, + UNKNOWN_112, + PROPERTY_PLAQUE, + BUILD_BORDER, + UNKOWN_115, + CULLING_PLANE, + DESTROYABLE = 1000 // Actually 7 +}; + +#endif //!__EREPLICACOMPONENTTYPE__H__ diff --git a/dDatabase/Tables/CDComponentsRegistryTable.cpp b/dDatabase/Tables/CDComponentsRegistryTable.cpp index 987c66ab..88bb04cc 100644 --- a/dDatabase/Tables/CDComponentsRegistryTable.cpp +++ b/dDatabase/Tables/CDComponentsRegistryTable.cpp @@ -1,4 +1,5 @@ #include "CDComponentsRegistryTable.h" +#include "eReplicaComponentType.h" #define CDCLIENT_CACHE_ALL @@ -25,7 +26,7 @@ CDComponentsRegistryTable::CDComponentsRegistryTable(void) { while (!tableData.eof()) { CDComponentsRegistry entry; entry.id = tableData.getIntField("id", -1); - entry.component_type = tableData.getIntField("component_type", -1); + entry.component_type = static_cast<eReplicaComponentType>(tableData.getIntField("component_type", 0)); entry.component_id = tableData.getIntField("component_id", -1); this->mappedEntries.insert_or_assign(((uint64_t)entry.component_type) << 32 | ((uint64_t)entry.id), entry.component_id); @@ -63,7 +64,7 @@ std::string CDComponentsRegistryTable::GetName(void) const { return "ComponentsRegistry"; } -int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, uint32_t componentType, int32_t defaultValue) { +int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, eReplicaComponentType componentType, int32_t defaultValue) { const auto& iter = this->mappedEntries.find(((uint64_t)componentType) << 32 | ((uint64_t)id)); if (iter == this->mappedEntries.end()) { diff --git a/dDatabase/Tables/CDComponentsRegistryTable.h b/dDatabase/Tables/CDComponentsRegistryTable.h index c3eb0ed2..91e3800c 100644 --- a/dDatabase/Tables/CDComponentsRegistryTable.h +++ b/dDatabase/Tables/CDComponentsRegistryTable.h @@ -7,11 +7,11 @@ \file CDComponentsRegistryTable.hpp \brief Contains data for the ComponentsRegistry table */ - +enum class eReplicaComponentType : uint32_t; //! ComponentsRegistry Entry Struct struct CDComponentsRegistry { unsigned int id; //!< The LOT is used as the ID - unsigned int component_type; //!< See ComponentTypes enum for values + eReplicaComponentType component_type; //!< See ComponentTypes enum for values unsigned int component_id; //!< The ID used within the component's table (0 may either mean it's non-networked, or that the ID is actually 0 }; @@ -36,5 +36,5 @@ public: */ std::string GetName(void) const override; - int32_t GetByIDAndType(uint32_t id, uint32_t componentType, int32_t defaultValue = 0); + int32_t GetByIDAndType(uint32_t id, eReplicaComponentType componentType, int32_t defaultValue = 0); }; diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 94693385..77692966 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -70,6 +70,7 @@ #include "RailActivatorComponent.h" #include "LUPExhibitComponent.h" #include "TriggerComponent.h" +#include "eReplicaComponentType.h" Entity::Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity) { m_ObjectID = objectID; @@ -135,7 +136,7 @@ void Entity::Initialize() { const auto triggerInfo = GetVarAsString(u"trigger_id"); - if (!triggerInfo.empty()) m_Components.emplace(COMPONENT_TYPE_TRIGGER, new TriggerComponent(this, triggerInfo)); + if (!triggerInfo.empty()) m_Components.emplace(eReplicaComponentType::TRIGGER, new TriggerComponent(this, triggerInfo)); /** * Setup groups @@ -164,23 +165,23 @@ void Entity::Initialize() { */ if (m_TemplateID == 14) { - const auto simplePhysicsComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SIMPLE_PHYSICS); + const auto simplePhysicsComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::SIMPLE_PHYSICS); SimplePhysicsComponent* comp = new SimplePhysicsComponent(simplePhysicsComponentID, this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_SIMPLE_PHYSICS, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::SIMPLE_PHYSICS, comp)); ModelComponent* modelcomp = new ModelComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_MODEL, modelcomp)); + m_Components.insert(std::make_pair(eReplicaComponentType::MODEL, modelcomp)); RenderComponent* render = new RenderComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_RENDER, render)); + m_Components.insert(std::make_pair(eReplicaComponentType::RENDER, render)); auto destroyableComponent = new DestroyableComponent(this); destroyableComponent->SetHealth(1); destroyableComponent->SetMaxHealth(1.0f); destroyableComponent->SetFaction(-1, true); destroyableComponent->SetIsSmashable(true); - m_Components.insert(std::make_pair(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)); + m_Components.insert(std::make_pair(eReplicaComponentType::DESTROYABLE, destroyableComponent)); // We have all our components. return; } @@ -193,47 +194,47 @@ void Entity::Initialize() { if (GetParentUser()) { auto missions = new MissionComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_MISSION, missions)); + m_Components.insert(std::make_pair(eReplicaComponentType::MISSION, missions)); missions->LoadFromXml(m_Character->GetXMLDoc()); } - uint32_t petComponentId = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PET); + uint32_t petComponentId = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PET); if (petComponentId > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_PET, new PetComponent(this, petComponentId))); + m_Components.insert(std::make_pair(eReplicaComponentType::PET, new PetComponent(this, petComponentId))); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_ZONE_CONTROL) > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_ZONE_CONTROL, nullptr)); + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::ZONE_CONTROL) > 0) { + m_Components.insert(std::make_pair(eReplicaComponentType::ZONE_CONTROL, nullptr)); } - uint32_t possessableComponentId = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_POSSESSABLE); + uint32_t possessableComponentId = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::POSSESSABLE); if (possessableComponentId > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_POSSESSABLE, new PossessableComponent(this, possessableComponentId))); + m_Components.insert(std::make_pair(eReplicaComponentType::POSSESSABLE, new PossessableComponent(this, possessableComponentId))); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MODULE_ASSEMBLY) > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_MODULE_ASSEMBLY, new ModuleAssemblyComponent(this))); + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::MODULE_ASSEMBLY) > 0) { + m_Components.insert(std::make_pair(eReplicaComponentType::MODULE_ASSEMBLY, new ModuleAssemblyComponent(this))); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_RACING_STATS) > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_RACING_STATS, nullptr)); + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::RACING_STATS) > 0) { + m_Components.insert(std::make_pair(eReplicaComponentType::RACING_STATS, nullptr)); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_EXHIBIT, -1) >= 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_EXHIBIT, new LUPExhibitComponent(this))); + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::LUP_EXHIBIT, -1) >= 0) { + m_Components.insert(std::make_pair(eReplicaComponentType::LUP_EXHIBIT, new LUPExhibitComponent(this))); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_RACING_CONTROL) > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_RACING_CONTROL, new RacingControlComponent(this))); + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::RACING_CONTROL) > 0) { + m_Components.insert(std::make_pair(eReplicaComponentType::RACING_CONTROL, new RacingControlComponent(this))); } - const auto propertyEntranceComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY_ENTRANCE); + const auto propertyEntranceComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROPERTY_ENTRANCE); if (propertyEntranceComponentID > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_PROPERTY_ENTRANCE, + m_Components.insert(std::make_pair(eReplicaComponentType::PROPERTY_ENTRANCE, new PropertyEntranceComponent(propertyEntranceComponentID, this))); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_CONTROLLABLE_PHYSICS) > 0) { + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::CONTROLLABLE_PHYSICS) > 0) { ControllablePhysicsComponent* controllablePhysics = new ControllablePhysicsComponent(this); if (m_Character) { @@ -268,61 +269,61 @@ void Entity::Initialize() { controllablePhysics->SetRotation(m_DefaultRotation); } - m_Components.insert(std::make_pair(COMPONENT_TYPE_CONTROLLABLE_PHYSICS, controllablePhysics)); + m_Components.insert(std::make_pair(eReplicaComponentType::CONTROLLABLE_PHYSICS, controllablePhysics)); } // If an entity is marked a phantom, simple physics is made into phantom phyics. bool markedAsPhantom = GetVar<bool>(u"markedAsPhantom"); - const auto simplePhysicsComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SIMPLE_PHYSICS); + const auto simplePhysicsComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::SIMPLE_PHYSICS); if (!markedAsPhantom && simplePhysicsComponentID > 0) { SimplePhysicsComponent* comp = new SimplePhysicsComponent(simplePhysicsComponentID, this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_SIMPLE_PHYSICS, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::SIMPLE_PHYSICS, comp)); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS) > 0) { + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::RIGID_BODY_PHANTOM_PHYSICS) > 0) { RigidbodyPhantomPhysicsComponent* comp = new RigidbodyPhantomPhysicsComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::RIGID_BODY_PHANTOM_PHYSICS, comp)); } - if (markedAsPhantom || compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PHANTOM_PHYSICS) > 0) { + if (markedAsPhantom || compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PHANTOM_PHYSICS) > 0) { PhantomPhysicsComponent* phantomPhysics = new PhantomPhysicsComponent(this); phantomPhysics->SetPhysicsEffectActive(false); - m_Components.insert(std::make_pair(COMPONENT_TYPE_PHANTOM_PHYSICS, phantomPhysics)); + m_Components.insert(std::make_pair(eReplicaComponentType::PHANTOM_PHYSICS, phantomPhysics)); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_VEHICLE_PHYSICS) > 0) { + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::VEHICLE_PHYSICS) > 0) { VehiclePhysicsComponent* vehiclePhysicsComponent = new VehiclePhysicsComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_VEHICLE_PHYSICS, vehiclePhysicsComponent)); + m_Components.insert(std::make_pair(eReplicaComponentType::VEHICLE_PHYSICS, vehiclePhysicsComponent)); vehiclePhysicsComponent->SetPosition(m_DefaultPosition); vehiclePhysicsComponent->SetRotation(m_DefaultRotation); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SOUND_TRIGGER, -1) != -1) { + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::SOUND_TRIGGER, -1) != -1) { auto* comp = new SoundTriggerComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_SOUND_TRIGGER, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::SOUND_TRIGGER, comp)); } //Also check for the collectible id: m_CollectibleID = GetVarAs<int32_t>(u"collectible_id"); - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_BUFF) > 0) { + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::BUFF) > 0) { BuffComponent* comp = new BuffComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_BUFF, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::BUFF, comp)); } - int collectibleComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_COLLECTIBLE); + int collectibleComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::COLLECTIBLE); if (collectibleComponentID > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_COLLECTIBLE, nullptr)); + m_Components.insert(std::make_pair(eReplicaComponentType::COLLECTIBLE, nullptr)); } /** * Multiple components require the destructible component. */ - int buffComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_BUFF); - int rebuildComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_REBUILD); + int buffComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::BUFF); + int rebuildComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::QUICK_BUILD); int componentID = 0; if (collectibleComponentID > 0) componentID = collectibleComponentID; @@ -341,7 +342,7 @@ void Entity::Initialize() { std::vector<CDDestructibleComponent> destCompData = destCompTable->Query([=](CDDestructibleComponent entry) { return (entry.id == componentID); }); if (destCompData.size() > 0) { - if (HasComponent(COMPONENT_TYPE_RACING_STATS)) { + if (HasComponent(eReplicaComponentType::RACING_STATS)) { destCompData[0].imagination = 60; } @@ -385,8 +386,8 @@ void Entity::Initialize() { comp->AddFaction(6); //Smashables // A race car has 60 imagination, other entities defaults to 0. - comp->SetImagination(HasComponent(COMPONENT_TYPE_RACING_STATS) ? 60 : 0); - comp->SetMaxImagination(HasComponent(COMPONENT_TYPE_RACING_STATS) ? 60 : 0); + comp->SetImagination(HasComponent(eReplicaComponentType::RACING_STATS) ? 60 : 0); + comp->SetMaxImagination(HasComponent(eReplicaComponentType::RACING_STATS) ? 60 : 0); } } @@ -404,35 +405,35 @@ void Entity::Initialize() { } } - m_Components.insert(std::make_pair(COMPONENT_TYPE_DESTROYABLE, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::DESTROYABLE, comp)); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_CHARACTER) > 0 || m_Character) { + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::CHARACTER) > 0 || m_Character) { // Character Component always has a possessor, level, and forced movement components - m_Components.insert(std::make_pair(COMPONENT_TYPE_POSSESSOR, new PossessorComponent(this))); + m_Components.insert(std::make_pair(eReplicaComponentType::POSSESSOR, new PossessorComponent(this))); // load in the xml for the level auto* levelComp = new LevelProgressionComponent(this); levelComp->LoadFromXml(m_Character->GetXMLDoc()); - m_Components.insert(std::make_pair(COMPONENT_TYPE_LEVEL_PROGRESSION, levelComp)); + m_Components.insert(std::make_pair(eReplicaComponentType::LEVEL_PROGRESSION, levelComp)); - m_Components.insert(std::make_pair(COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT, new PlayerForcedMovementComponent(this))); + m_Components.insert(std::make_pair(eReplicaComponentType::PLAYER_FORCED_MOVEMENT, new PlayerForcedMovementComponent(this))); CharacterComponent* charComp = new CharacterComponent(this, m_Character); charComp->LoadFromXml(m_Character->GetXMLDoc()); - m_Components.insert(std::make_pair(COMPONENT_TYPE_CHARACTER, charComp)); + m_Components.insert(std::make_pair(eReplicaComponentType::CHARACTER, charComp)); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_INVENTORY) > 0 || m_Character) { + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::INVENTORY) > 0 || m_Character) { InventoryComponent* comp = nullptr; if (m_Character) comp = new InventoryComponent(this, m_Character->GetXMLDoc()); else comp = new InventoryComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_INVENTORY, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::INVENTORY, comp)); } // if this component exists, then we initialize it. it's value is always 0 - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_ROCKET_LAUNCH_LUP, -1) != -1) { + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::ROCKET_LAUNCH_LUP, -1) != -1) { auto comp = new RocketLaunchLupComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_ROCKET_LAUNCH_LUP, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::ROCKET_LAUNCH_LUP, comp)); } /** @@ -440,7 +441,7 @@ void Entity::Initialize() { */ CDScriptComponentTable* scriptCompTable = CDClientManager::Instance()->GetTable<CDScriptComponentTable>("ScriptComponent"); - int32_t scriptComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SCRIPT, -1); + int32_t scriptComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::SCRIPT, -1); std::string scriptName = ""; bool client = false; @@ -483,7 +484,7 @@ void Entity::Initialize() { } if (!scriptName.empty() || client || m_Character || scriptComponentID >= 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_SCRIPT, new ScriptComponent(this, scriptName, true, client && scriptName.empty()))); + m_Components.insert(std::make_pair(eReplicaComponentType::SCRIPT, new ScriptComponent(this, scriptName, true, client && scriptName.empty()))); } // ZoneControl script @@ -497,24 +498,24 @@ void Entity::Initialize() { CDScriptComponent zoneScriptData = scriptCompTable->GetByID(zoneScriptID); ScriptComponent* comp = new ScriptComponent(this, zoneScriptData.script_name, true); - m_Components.insert(std::make_pair(COMPONENT_TYPE_SCRIPT, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::SCRIPT, comp)); } } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SKILL, -1) != -1 || m_Character) { + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::SKILL, -1) != -1 || m_Character) { SkillComponent* comp = new SkillComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_SKILL, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::SKILL, comp)); } - const auto combatAiId = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_BASE_COMBAT_AI); + const auto combatAiId = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::BASE_COMBAT_AI); if (combatAiId > 0) { BaseCombatAIComponent* comp = new BaseCombatAIComponent(this, combatAiId); - m_Components.insert(std::make_pair(COMPONENT_TYPE_BASE_COMBAT_AI, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::BASE_COMBAT_AI, comp)); } - if (int componentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_REBUILD) > 0) { + if (int componentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::QUICK_BUILD) > 0) { RebuildComponent* comp = new RebuildComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_REBUILD, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::QUICK_BUILD, comp)); CDRebuildComponentTable* rebCompTable = CDClientManager::Instance()->GetTable<CDRebuildComponentTable>("RebuildComponent"); std::vector<CDRebuildComponent> rebCompData = rebCompTable->Query([=](CDRebuildComponent entry) { return (entry.id == rebuildComponentID); }); @@ -554,87 +555,87 @@ void Entity::Initialize() { } } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SWITCH, -1) != -1) { + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::SWITCH, -1) != -1) { SwitchComponent* comp = new SwitchComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_SWITCH, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::SWITCH, comp)); } - if ((compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_VENDOR) > 0)) { + if ((compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::VENDOR) > 0)) { VendorComponent* comp = new VendorComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_VENDOR, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::VENDOR, comp)); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY_VENDOR, -1) != -1) { + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROPERTY_VENDOR, -1) != -1) { auto* component = new PropertyVendorComponent(this); - m_Components.insert_or_assign(COMPONENT_TYPE_PROPERTY_VENDOR, component); + m_Components.insert_or_assign(eReplicaComponentType::PROPERTY_VENDOR, component); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY_MANAGEMENT, -1) != -1) { + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROPERTY_MANAGEMENT, -1) != -1) { auto* component = new PropertyManagementComponent(this); - m_Components.insert_or_assign(COMPONENT_TYPE_PROPERTY_MANAGEMENT, component); + m_Components.insert_or_assign(eReplicaComponentType::PROPERTY_MANAGEMENT, component); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_BOUNCER, -1) != -1) { // you have to determine it like this because all bouncers have a componentID of 0 + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::BOUNCER, -1) != -1) { // you have to determine it like this because all bouncers have a componentID of 0 BouncerComponent* comp = new BouncerComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_BOUNCER, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::BOUNCER, comp)); } - if ((compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_RENDER) > 0 && m_TemplateID != 2365) || m_Character) { + if ((compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::RENDER) > 0 && m_TemplateID != 2365) || m_Character) { RenderComponent* render = new RenderComponent(this); - m_Components.insert(std::make_pair(COMPONENT_TYPE_RENDER, render)); + m_Components.insert(std::make_pair(eReplicaComponentType::RENDER, render)); } - if ((compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MISSION_OFFER) > 0) || m_Character) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_MISSION_OFFER, new MissionOfferComponent(this, m_TemplateID))); + if ((compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::MISSION_OFFER) > 0) || m_Character) { + m_Components.insert(std::make_pair(eReplicaComponentType::MISSION_OFFER, new MissionOfferComponent(this, m_TemplateID))); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_BUILD_BORDER, -1) != -1) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_BUILD_BORDER, new BuildBorderComponent(this))); + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::BUILD_BORDER, -1) != -1) { + m_Components.insert(std::make_pair(eReplicaComponentType::BUILD_BORDER, new BuildBorderComponent(this))); } // Scripted activity component - int scriptedActivityID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SCRIPTED_ACTIVITY); + int scriptedActivityID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::SCRIPTED_ACTIVITY); if ((scriptedActivityID > 0)) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_SCRIPTED_ACTIVITY, new ScriptedActivityComponent(this, scriptedActivityID))); + m_Components.insert(std::make_pair(eReplicaComponentType::SCRIPTED_ACTIVITY, new ScriptedActivityComponent(this, scriptedActivityID))); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MODEL, -1) != -1 && !GetComponent<PetComponent>()) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_MODEL, new ModelComponent(this))); - if (m_Components.find(COMPONENT_TYPE_DESTROYABLE) == m_Components.end()) { + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::MODEL, -1) != -1 && !GetComponent<PetComponent>()) { + m_Components.insert(std::make_pair(eReplicaComponentType::MODEL, new ModelComponent(this))); + if (m_Components.find(eReplicaComponentType::DESTROYABLE) == m_Components.end()) { auto destroyableComponent = new DestroyableComponent(this); destroyableComponent->SetHealth(1); destroyableComponent->SetMaxHealth(1.0f); destroyableComponent->SetFaction(-1, true); destroyableComponent->SetIsSmashable(true); - m_Components.insert(std::make_pair(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)); + m_Components.insert(std::make_pair(eReplicaComponentType::DESTROYABLE, destroyableComponent)); } } PetComponent* petComponent; - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_ITEM) > 0 && !TryGetComponent(COMPONENT_TYPE_PET, petComponent) && !HasComponent(COMPONENT_TYPE_MODEL)) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_ITEM, nullptr)); + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::ITEM) > 0 && !TryGetComponent(eReplicaComponentType::PET, petComponent) && !HasComponent(eReplicaComponentType::MODEL)) { + m_Components.insert(std::make_pair(eReplicaComponentType::ITEM, nullptr)); } // Shooting gallery component - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_SHOOTING_GALLERY) > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_SHOOTING_GALLERY, new ShootingGalleryComponent(this))); + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::SHOOTING_GALLERY) > 0) { + m_Components.insert(std::make_pair(eReplicaComponentType::SHOOTING_GALLERY, new ShootingGalleryComponent(this))); } - if (compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROPERTY, -1) != -1) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_PROPERTY, new PropertyComponent(this))); + if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROPERTY, -1) != -1) { + m_Components.insert(std::make_pair(eReplicaComponentType::PROPERTY, new PropertyComponent(this))); } - const int rocketId = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_ROCKET_LAUNCH); + const int rocketId = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::ROCKET_LAUNCH); if ((rocketId > 0)) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_ROCKET_LAUNCH, new RocketLaunchpadControlComponent(this, rocketId))); + m_Components.insert(std::make_pair(eReplicaComponentType::ROCKET_LAUNCH, new RocketLaunchpadControlComponent(this, rocketId))); } - const int32_t railComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_RAIL_ACTIVATOR); + const int32_t railComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::RAIL_ACTIVATOR); if (railComponentID > 0) { - m_Components.insert(std::make_pair(COMPONENT_TYPE_RAIL_ACTIVATOR, new RailActivatorComponent(this, railComponentID))); + m_Components.insert(std::make_pair(eReplicaComponentType::RAIL_ACTIVATOR, new RailActivatorComponent(this, railComponentID))); } - int movementAIID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_MOVEMENT_AI); + int movementAIID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::MOVEMENT_AI); if (movementAIID > 0) { CDMovementAIComponentTable* moveAITable = CDClientManager::Instance()->GetTable<CDMovementAIComponentTable>("MovementAIComponent"); std::vector<CDMovementAIComponent> moveAIComp = moveAITable->Query([=](CDMovementAIComponent entry) {return (entry.id == movementAIID); }); @@ -659,7 +660,7 @@ void Entity::Initialize() { } } - m_Components.insert(std::make_pair(COMPONENT_TYPE_MOVEMENT_AI, new MovementAIComponent(this, moveInfo))); + m_Components.insert(std::make_pair(eReplicaComponentType::MOVEMENT_AI, new MovementAIComponent(this, moveInfo))); } } else if (petComponentId > 0 || combatAiId > 0 && GetComponent<BaseCombatAIComponent>()->GetTetherSpeed() > 0) { MovementAIInfo moveInfo = MovementAIInfo(); @@ -670,7 +671,7 @@ void Entity::Initialize() { moveInfo.wanderDelayMax = 5; moveInfo.wanderDelayMin = 2; - m_Components.insert(std::make_pair(COMPONENT_TYPE_MOVEMENT_AI, new MovementAIComponent(this, moveInfo))); + m_Components.insert(std::make_pair(eReplicaComponentType::MOVEMENT_AI, new MovementAIComponent(this, moveInfo))); } std::string pathName = GetVarAsString(u"attached_path"); @@ -681,7 +682,7 @@ void Entity::Initialize() { // if we have a moving platform path, then we need a moving platform component if (path->pathType == PathType::MovingPlatform) { MovingPlatformComponent* plat = new MovingPlatformComponent(this, pathName); - m_Components.insert(std::make_pair(COMPONENT_TYPE_MOVING_PLATFORM, plat)); + m_Components.insert(std::make_pair(eReplicaComponentType::MOVING_PLATFORM, plat)); // else if we are a movement path } /*else if (path->pathType == PathType::Movement) { auto movementAIcomp = GetComponent<MovementAIComponent>(); @@ -693,14 +694,14 @@ void Entity::Initialize() { }*/ } - int proximityMonitorID = compRegistryTable->GetByIDAndType(m_TemplateID, COMPONENT_TYPE_PROXIMITY_MONITOR); + int proximityMonitorID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROXIMITY_MONITOR); if (proximityMonitorID > 0) { CDProximityMonitorComponentTable* proxCompTable = CDClientManager::Instance()->GetTable<CDProximityMonitorComponentTable>("ProximityMonitorComponent"); std::vector<CDProximityMonitorComponent> proxCompData = proxCompTable->Query([=](CDProximityMonitorComponent entry) { return (entry.id == proximityMonitorID); }); if (proxCompData.size() > 0) { std::vector<std::string> proximityStr = GeneralUtils::SplitString(proxCompData[0].Proximities, ','); ProximityMonitorComponent* comp = new ProximityMonitorComponent(this, std::stoi(proximityStr[0]), std::stoi(proximityStr[1])); - m_Components.insert(std::make_pair(COMPONENT_TYPE_PROXIMITY_MONITOR, comp)); + m_Components.insert(std::make_pair(eReplicaComponentType::PROXIMITY_MONITOR, comp)); } } @@ -713,7 +714,7 @@ void Entity::Initialize() { if (!m_Character && EntityManager::Instance()->GetGhostingEnabled()) { // Don't ghost what is likely large scene elements - if (m_Components.size() == 2 && HasComponent(COMPONENT_TYPE_SIMPLE_PHYSICS) && HasComponent(COMPONENT_TYPE_RENDER)) { + if (m_Components.size() == 2 && HasComponent(eReplicaComponentType::SIMPLE_PHYSICS) && HasComponent(eReplicaComponentType::RENDER)) { goto no_ghosting; } @@ -725,14 +726,14 @@ void Entity::Initialize() { */ if ( !EntityManager::IsExcludedFromGhosting(GetLOT()) && - !HasComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY) && - !HasComponent(COMPONENT_TYPE_MOVING_PLATFORM) && - !HasComponent(COMPONENT_TYPE_PHANTOM_PHYSICS) && - !HasComponent(COMPONENT_TYPE_PROPERTY) && - !HasComponent(COMPONENT_TYPE_RACING_CONTROL) && - !HasComponent(COMPONENT_TYPE_VEHICLE_PHYSICS) + !HasComponent(eReplicaComponentType::SCRIPTED_ACTIVITY) && + !HasComponent(eReplicaComponentType::MOVING_PLATFORM) && + !HasComponent(eReplicaComponentType::PHANTOM_PHYSICS) && + !HasComponent(eReplicaComponentType::PROPERTY) && + !HasComponent(eReplicaComponentType::RACING_CONTROL) && + !HasComponent(eReplicaComponentType::VEHICLE_PHYSICS) ) - //if (HasComponent(COMPONENT_TYPE_BASE_COMBAT_AI)) + //if (HasComponent(eReplicaComponentType::BASE_COMBAT_AI)) { m_IsGhostingCandidate = true; } @@ -742,7 +743,7 @@ void Entity::Initialize() { } // Special case for collectibles in Ninjago - if (HasComponent(COMPONENT_TYPE_COLLECTIBLE) && Game::server->GetZoneID() == 2000) { + if (HasComponent(eReplicaComponentType::COLLECTIBLE) && Game::server->GetZoneID() == 2000) { m_IsGhostingCandidate = true; } } @@ -777,7 +778,7 @@ User* Entity::GetParentUser() const { return static_cast<const Player*>(this)->GetParentUser(); } -Component* Entity::GetComponent(int32_t componentID) const { +Component* Entity::GetComponent(eReplicaComponentType componentID) const { const auto& index = m_Components.find(componentID); if (index == m_Components.end()) { @@ -787,11 +788,11 @@ Component* Entity::GetComponent(int32_t componentID) const { return index->second; } -bool Entity::HasComponent(const int32_t componentId) const { +bool Entity::HasComponent(const eReplicaComponentType componentId) const { return m_Components.find(componentId) != m_Components.end(); } -void Entity::AddComponent(const int32_t componentId, Component* component) { +void Entity::AddComponent(const eReplicaComponentType componentId, Component* component) { if (HasComponent(componentId)) { return; } @@ -801,8 +802,8 @@ void Entity::AddComponent(const int32_t componentId, Component* component) { std::vector<ScriptComponent*> Entity::GetScriptComponents() { std::vector<ScriptComponent*> comps; - for (std::pair<int32_t, void*> p : m_Components) { - if (p.first == COMPONENT_TYPE_SCRIPT) { + for (std::pair<eReplicaComponentType, void*> p : m_Components) { + if (p.first == eReplicaComponentType::SCRIPT) { comps.push_back(static_cast<ScriptComponent*>(p.second)); } } @@ -830,7 +831,7 @@ void Entity::SetProximityRadius(float proxRadius, std::string name) { ProximityMonitorComponent* proxMon = GetComponent<ProximityMonitorComponent>(); if (!proxMon) { proxMon = new ProximityMonitorComponent(this); - m_Components.insert_or_assign(COMPONENT_TYPE_PROXIMITY_MONITOR, proxMon); + m_Components.insert_or_assign(eReplicaComponentType::PROXIMITY_MONITOR, proxMon); } proxMon->SetProximityRadius(proxRadius, name); } @@ -839,7 +840,7 @@ void Entity::SetProximityRadius(dpEntity* entity, std::string name) { ProximityMonitorComponent* proxMon = GetComponent<ProximityMonitorComponent>(); if (!proxMon) { proxMon = new ProximityMonitorComponent(this); - m_Components.insert_or_assign(COMPONENT_TYPE_PROXIMITY_MONITOR, proxMon); + m_Components.insert_or_assign(eReplicaComponentType::PROXIMITY_MONITOR, proxMon); } proxMon->SetProximityRadius(entity, name); } @@ -927,7 +928,7 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke } TriggerComponent* triggerComponent; - if (TryGetComponent(COMPONENT_TYPE_TRIGGER, triggerComponent)) { + if (TryGetComponent(eReplicaComponentType::TRIGGER, triggerComponent)) { // has trigger component, check to see if we have events to handle auto* trigger = triggerComponent->GetTrigger(); outBitStream->Write<bool>(trigger && trigger->events.size() > 0); @@ -993,59 +994,59 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType unsigned int flags = 0; PossessableComponent* possessableComponent; - if (TryGetComponent(COMPONENT_TYPE_POSSESSABLE, possessableComponent)) { + if (TryGetComponent(eReplicaComponentType::POSSESSABLE, possessableComponent)) { possessableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } ModuleAssemblyComponent* moduleAssemblyComponent; - if (TryGetComponent(COMPONENT_TYPE_MODULE_ASSEMBLY, moduleAssemblyComponent)) { + if (TryGetComponent(eReplicaComponentType::MODULE_ASSEMBLY, moduleAssemblyComponent)) { moduleAssemblyComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } ControllablePhysicsComponent* controllablePhysicsComponent; - if (TryGetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS, controllablePhysicsComponent)) { + if (TryGetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS, controllablePhysicsComponent)) { controllablePhysicsComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } SimplePhysicsComponent* simplePhysicsComponent; - if (TryGetComponent(COMPONENT_TYPE_SIMPLE_PHYSICS, simplePhysicsComponent)) { + if (TryGetComponent(eReplicaComponentType::SIMPLE_PHYSICS, simplePhysicsComponent)) { simplePhysicsComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } RigidbodyPhantomPhysicsComponent* rigidbodyPhantomPhysics; - if (TryGetComponent(COMPONENT_TYPE_RIGID_BODY_PHANTOM_PHYSICS, rigidbodyPhantomPhysics)) { + if (TryGetComponent(eReplicaComponentType::RIGID_BODY_PHANTOM_PHYSICS, rigidbodyPhantomPhysics)) { rigidbodyPhantomPhysics->Serialize(outBitStream, bIsInitialUpdate, flags); } VehiclePhysicsComponent* vehiclePhysicsComponent; - if (TryGetComponent(COMPONENT_TYPE_VEHICLE_PHYSICS, vehiclePhysicsComponent)) { + if (TryGetComponent(eReplicaComponentType::VEHICLE_PHYSICS, vehiclePhysicsComponent)) { vehiclePhysicsComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } PhantomPhysicsComponent* phantomPhysicsComponent; - if (TryGetComponent(COMPONENT_TYPE_PHANTOM_PHYSICS, phantomPhysicsComponent)) { + if (TryGetComponent(eReplicaComponentType::PHANTOM_PHYSICS, phantomPhysicsComponent)) { phantomPhysicsComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } SoundTriggerComponent* soundTriggerComponent; - if (TryGetComponent(COMPONENT_TYPE_SOUND_TRIGGER, soundTriggerComponent)) { + if (TryGetComponent(eReplicaComponentType::SOUND_TRIGGER, soundTriggerComponent)) { soundTriggerComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } BuffComponent* buffComponent; - if (TryGetComponent(COMPONENT_TYPE_BUFF, buffComponent)) { + if (TryGetComponent(eReplicaComponentType::BUFF, buffComponent)) { buffComponent->Serialize(outBitStream, bIsInitialUpdate, flags); DestroyableComponent* destroyableComponent; - if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) { + if (TryGetComponent(eReplicaComponentType::DESTROYABLE, destroyableComponent)) { destroyableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } destroyableSerialized = true; } - if (HasComponent(COMPONENT_TYPE_COLLECTIBLE)) { + if (HasComponent(eReplicaComponentType::COLLECTIBLE)) { DestroyableComponent* destroyableComponent; - if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent) && !destroyableSerialized) { + if (TryGetComponent(eReplicaComponentType::DESTROYABLE, destroyableComponent) && !destroyableSerialized) { destroyableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } destroyableSerialized = true; @@ -1053,15 +1054,15 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } PetComponent* petComponent; - if (TryGetComponent(COMPONENT_TYPE_PET, petComponent)) { + if (TryGetComponent(eReplicaComponentType::PET, petComponent)) { petComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } CharacterComponent* characterComponent; - if (TryGetComponent(COMPONENT_TYPE_CHARACTER, characterComponent)) { + if (TryGetComponent(eReplicaComponentType::CHARACTER, characterComponent)) { PossessorComponent* possessorComponent; - if (TryGetComponent(COMPONENT_TYPE_POSSESSOR, possessorComponent)) { + if (TryGetComponent(eReplicaComponentType::POSSESSOR, possessorComponent)) { possessorComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } else { // Should never happen, but just to be safe @@ -1069,7 +1070,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } LevelProgressionComponent* levelProgressionComponent; - if (TryGetComponent(COMPONENT_TYPE_LEVEL_PROGRESSION, levelProgressionComponent)) { + if (TryGetComponent(eReplicaComponentType::LEVEL_PROGRESSION, levelProgressionComponent)) { levelProgressionComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } else { // Should never happen, but just to be safe @@ -1077,7 +1078,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } PlayerForcedMovementComponent* playerForcedMovementComponent; - if (TryGetComponent(COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT, playerForcedMovementComponent)) { + if (TryGetComponent(eReplicaComponentType::PLAYER_FORCED_MOVEMENT, playerForcedMovementComponent)) { playerForcedMovementComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } else { // Should never happen, but just to be safe @@ -1087,34 +1088,34 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType characterComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } - if (HasComponent(COMPONENT_TYPE_ITEM)) { + if (HasComponent(eReplicaComponentType::ITEM)) { outBitStream->Write0(); } InventoryComponent* inventoryComponent; - if (TryGetComponent(COMPONENT_TYPE_INVENTORY, inventoryComponent)) { + if (TryGetComponent(eReplicaComponentType::INVENTORY, inventoryComponent)) { inventoryComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } ScriptComponent* scriptComponent; - if (TryGetComponent(COMPONENT_TYPE_SCRIPT, scriptComponent)) { + if (TryGetComponent(eReplicaComponentType::SCRIPT, scriptComponent)) { scriptComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } SkillComponent* skillComponent; - if (TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) { + if (TryGetComponent(eReplicaComponentType::SKILL, skillComponent)) { skillComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } BaseCombatAIComponent* baseCombatAiComponent; - if (TryGetComponent(COMPONENT_TYPE_BASE_COMBAT_AI, baseCombatAiComponent)) { + if (TryGetComponent(eReplicaComponentType::BASE_COMBAT_AI, baseCombatAiComponent)) { baseCombatAiComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } RebuildComponent* rebuildComponent; - if (TryGetComponent(COMPONENT_TYPE_REBUILD, rebuildComponent)) { + if (TryGetComponent(eReplicaComponentType::QUICK_BUILD, rebuildComponent)) { DestroyableComponent* destroyableComponent; - if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent) && !destroyableSerialized) { + if (TryGetComponent(eReplicaComponentType::DESTROYABLE, destroyableComponent) && !destroyableSerialized) { destroyableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } destroyableSerialized = true; @@ -1122,64 +1123,64 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType } MovingPlatformComponent* movingPlatformComponent; - if (TryGetComponent(COMPONENT_TYPE_MOVING_PLATFORM, movingPlatformComponent)) { + if (TryGetComponent(eReplicaComponentType::MOVING_PLATFORM, movingPlatformComponent)) { movingPlatformComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } SwitchComponent* switchComponent; - if (TryGetComponent(COMPONENT_TYPE_SWITCH, switchComponent)) { + if (TryGetComponent(eReplicaComponentType::SWITCH, switchComponent)) { switchComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } VendorComponent* vendorComponent; - if (TryGetComponent(COMPONENT_TYPE_VENDOR, vendorComponent)) { + if (TryGetComponent(eReplicaComponentType::VENDOR, vendorComponent)) { vendorComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } BouncerComponent* bouncerComponent; - if (TryGetComponent(COMPONENT_TYPE_BOUNCER, bouncerComponent)) { + if (TryGetComponent(eReplicaComponentType::BOUNCER, bouncerComponent)) { bouncerComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } ScriptedActivityComponent* scriptedActivityComponent; - if (TryGetComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY, scriptedActivityComponent)) { + if (TryGetComponent(eReplicaComponentType::SCRIPTED_ACTIVITY, scriptedActivityComponent)) { scriptedActivityComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } ShootingGalleryComponent* shootingGalleryComponent; - if (TryGetComponent(COMPONENT_TYPE_SHOOTING_GALLERY, shootingGalleryComponent)) { + if (TryGetComponent(eReplicaComponentType::SHOOTING_GALLERY, shootingGalleryComponent)) { shootingGalleryComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } RacingControlComponent* racingControlComponent; - if (TryGetComponent(COMPONENT_TYPE_RACING_CONTROL, racingControlComponent)) { + if (TryGetComponent(eReplicaComponentType::RACING_CONTROL, racingControlComponent)) { racingControlComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } LUPExhibitComponent* lupExhibitComponent; - if (TryGetComponent(COMPONENT_TYPE_EXHIBIT, lupExhibitComponent)) { + if (TryGetComponent(eReplicaComponentType::LUP_EXHIBIT, lupExhibitComponent)) { lupExhibitComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } ModelComponent* modelComponent; - if (TryGetComponent(COMPONENT_TYPE_MODEL, modelComponent)) { + if (TryGetComponent(eReplicaComponentType::MODEL, modelComponent)) { modelComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } RenderComponent* renderComponent; - if (TryGetComponent(COMPONENT_TYPE_RENDER, renderComponent)) { + if (TryGetComponent(eReplicaComponentType::RENDER, renderComponent)) { renderComponent->Serialize(outBitStream, bIsInitialUpdate, flags); } if (modelComponent) { DestroyableComponent* destroyableComponent; - if (TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent) && !destroyableSerialized) { + if (TryGetComponent(eReplicaComponentType::DESTROYABLE, destroyableComponent) && !destroyableSerialized) { destroyableComponent->Serialize(outBitStream, bIsInitialUpdate, flags); destroyableSerialized = true; } } - if (HasComponent(COMPONENT_TYPE_ZONE_CONTROL)) { + if (HasComponent(eReplicaComponentType::ZONE_CONTROL)) { outBitStream->Write<uint32_t>(0x40000000); } diff --git a/dGame/Entity.h b/dGame/Entity.h index 0bde01e2..ae16fb82 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -31,6 +31,7 @@ class Item; class Character; class EntityCallbackTimer; enum class eTriggerEventType; +enum class eReplicaComponentType : uint32_t; namespace CppScripts { class Script; @@ -131,17 +132,17 @@ public: * Component management */ - Component* GetComponent(int32_t componentID) const; + Component* GetComponent(eReplicaComponentType componentID) const; template<typename T> T* GetComponent() const; template<typename T> - bool TryGetComponent(int32_t componentId, T*& component) const; + bool TryGetComponent(eReplicaComponentType componentId, T*& component) const; - bool HasComponent(int32_t componentId) const; + bool HasComponent(eReplicaComponentType componentId) const; - void AddComponent(int32_t componentId, Component* component); + void AddComponent(eReplicaComponentType componentId, Component* component); std::vector<ScriptComponent*> GetScriptComponents(); @@ -164,7 +165,7 @@ public: void AddToGroup(const std::string& group); bool IsPlayer() const; - std::unordered_map<int32_t, Component*>& GetComponents() { return m_Components; } // TODO: Remove + std::unordered_map<eReplicaComponentType, Component*>& GetComponents() { return m_Components; } // TODO: Remove void WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacketType packetType); void WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType packetType); @@ -314,7 +315,7 @@ protected: std::vector<std::function<void()>> m_DieCallbacks; std::vector<std::function<void(Entity* target)>> m_PhantomCollisionCallbacks; - std::unordered_map<int32_t, Component*> m_Components; //The int is the ID of the component + std::unordered_map<eReplicaComponentType, Component*> m_Components; std::vector<EntityTimer*> m_Timers; std::vector<EntityTimer*> m_PendingTimers; std::vector<EntityCallbackTimer*> m_CallbackTimers; @@ -344,7 +345,7 @@ protected: */ template<typename T> -bool Entity::TryGetComponent(const int32_t componentId, T*& component) const { +bool Entity::TryGetComponent(const eReplicaComponentType componentId, T*& component) const { const auto& index = m_Components.find(componentId); if (index == m_Components.end()) { diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index dae27af6..e79ada25 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -20,6 +20,7 @@ #include "MessageIdentifiers.h" #include "dConfig.h" #include "eTriggerEventType.h" +#include "eReplicaComponentType.h" EntityManager* EntityManager::m_Address = nullptr; @@ -268,10 +269,10 @@ std::vector<Entity*> EntityManager::GetEntitiesInGroup(const std::string& group) return entitiesInGroup; } -std::vector<Entity*> EntityManager::GetEntitiesByComponent(const int componentType) const { +std::vector<Entity*> EntityManager::GetEntitiesByComponent(const eReplicaComponentType componentType) const { std::vector<Entity*> withComp; for (const auto& entity : m_Entities) { - if (componentType != -1 && !entity.second->HasComponent(componentType)) continue; + if (componentType != eReplicaComponentType::INVALID && !entity.second->HasComponent(componentType)) continue; withComp.push_back(entity.second); } diff --git a/dGame/EntityManager.h b/dGame/EntityManager.h index 8a930de3..0314cc09 100644 --- a/dGame/EntityManager.h +++ b/dGame/EntityManager.h @@ -11,6 +11,7 @@ class Entity; class EntityInfo; class Player; class User; +enum class eReplicaComponentType : uint32_t; struct SystemAddress; @@ -35,7 +36,7 @@ public: void DestroyEntity(Entity* entity); Entity* GetEntity(const LWOOBJID& objectId) const; std::vector<Entity*> GetEntitiesInGroup(const std::string& group); - std::vector<Entity*> GetEntitiesByComponent(int componentType) const; + std::vector<Entity*> GetEntitiesByComponent(eReplicaComponentType componentType) const; std::vector<Entity*> GetEntitiesByLOT(const LOT& lot) const; Entity* GetZoneControlEntity() const; diff --git a/dGame/Player.cpp b/dGame/Player.cpp index 4f4bc951..2e194e6a 100644 --- a/dGame/Player.cpp +++ b/dGame/Player.cpp @@ -16,6 +16,7 @@ #include "User.h" #include "CppScripts.h" #include "Loot.h" +#include "eReplicaComponentType.h" std::vector<Player*> Player::m_Players = {}; @@ -223,7 +224,7 @@ Player* Player::GetPlayer(const SystemAddress& sysAddr) { } Player* Player::GetPlayer(const std::string& name) { - const auto characters = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER); + const auto characters = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::CHARACTER); for (auto* character : characters) { if (!character->IsPlayer()) continue; @@ -289,7 +290,7 @@ Player::~Player() { script->OnPlayerExit(zoneControl, this); } - std::vector<Entity*> scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY); + std::vector<Entity*> scriptedActs = EntityManager::Instance()->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)) { diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index 26d1e9e6..397e0c72 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -15,6 +15,7 @@ #include "EchoSyncSkill.h" #include "PhantomPhysicsComponent.h" #include "RebuildComponent.h" +#include "eReplicaComponentType.h" BehaviorSyncEntry::BehaviorSyncEntry() { } @@ -311,13 +312,13 @@ std::vector<LWOOBJID> BehaviorContext::GetValidTargets(int32_t ignoreFaction, in } } - if (ignoreFaction || includeFaction || (!entity->HasComponent(COMPONENT_TYPE_PHANTOM_PHYSICS) && targets.empty())) { + if (ignoreFaction || includeFaction || (!entity->HasComponent(eReplicaComponentType::PHANTOM_PHYSICS) && targets.empty())) { DestroyableComponent* destroyableComponent; - if (!entity->TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) { + if (!entity->TryGetComponent(eReplicaComponentType::DESTROYABLE, destroyableComponent)) { return targets; } - auto entities = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS); + auto entities = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS); for (auto* candidate : entities) { const auto id = candidate->GetObjectID(); diff --git a/dGame/dBehaviors/HealBehavior.cpp b/dGame/dBehaviors/HealBehavior.cpp index 2799d2e2..66fe2c79 100644 --- a/dGame/dBehaviors/HealBehavior.cpp +++ b/dGame/dBehaviors/HealBehavior.cpp @@ -4,6 +4,7 @@ #include "dLogger.h" #include "EntityManager.h" #include "DestroyableComponent.h" +#include "eReplicaComponentType.h" void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { @@ -15,7 +16,7 @@ void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_strea return; } - auto* destroyable = static_cast<DestroyableComponent*>(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); + auto* destroyable = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); if (destroyable == nullptr) { Game::logger->Log("HealBehavior", "Failed to find destroyable component for %(llu)!", branch.target); diff --git a/dGame/dBehaviors/RepairBehavior.cpp b/dGame/dBehaviors/RepairBehavior.cpp index a48141d3..ce2e5fd2 100644 --- a/dGame/dBehaviors/RepairBehavior.cpp +++ b/dGame/dBehaviors/RepairBehavior.cpp @@ -5,6 +5,7 @@ #include "EntityManager.h" #include "dLogger.h" #include "Game.h" +#include "eReplicaComponentType.h" void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { auto* entity = EntityManager::Instance()->GetEntity(branch.target); @@ -15,7 +16,7 @@ void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_str return; } - auto* destroyable = static_cast<DestroyableComponent*>(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); + auto* destroyable = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); if (destroyable == nullptr) { Game::logger->Log("RepairBehavior", "Failed to find destroyable component for %(llu)!", branch.target); diff --git a/dGame/dBehaviors/SpawnBehavior.cpp b/dGame/dBehaviors/SpawnBehavior.cpp index 8b2020b1..75c84f6c 100644 --- a/dGame/dBehaviors/SpawnBehavior.cpp +++ b/dGame/dBehaviors/SpawnBehavior.cpp @@ -9,6 +9,7 @@ #include "RebuildComponent.h" #include "Entity.h" #include "EntityInfo.h" +#include "eReplicaComponentType.h" void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { auto* origin = EntityManager::Instance()->GetEntity(context->originator); @@ -86,7 +87,7 @@ void SpawnBehavior::Timer(BehaviorContext* context, const BehaviorBranchContext return; } - auto* destroyable = static_cast<DestroyableComponent*>(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); + auto* destroyable = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); if (destroyable == nullptr) { entity->Smash(context->originator); diff --git a/dGame/dBehaviors/StunBehavior.cpp b/dGame/dBehaviors/StunBehavior.cpp index 065b7220..4e34d3a2 100644 --- a/dGame/dBehaviors/StunBehavior.cpp +++ b/dGame/dBehaviors/StunBehavior.cpp @@ -7,6 +7,7 @@ #include "Game.h" #include "dLogger.h" #include "DestroyableComponent.h" +#include "eReplicaComponentType.h" void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { @@ -32,7 +33,7 @@ void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream * If our target is an enemy we can go ahead and stun it. */ - auto* combatAiComponent = static_cast<BaseCombatAIComponent*>(target->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); + auto* combatAiComponent = static_cast<BaseCombatAIComponent*>(target->GetComponent(eReplicaComponentType::BASE_COMBAT_AI)); if (combatAiComponent == nullptr) { return; @@ -55,7 +56,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr * See if we can stun ourselves */ - auto* combatAiComponent = static_cast<BaseCombatAIComponent*>(self->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); + auto* combatAiComponent = static_cast<BaseCombatAIComponent*>(self->GetComponent(eReplicaComponentType::BASE_COMBAT_AI)); if (combatAiComponent == nullptr) { return; @@ -90,7 +91,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr * If our target is an enemy we can go ahead and stun it. */ - auto* combatAiComponent = static_cast<BaseCombatAIComponent*>(target->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); + auto* combatAiComponent = static_cast<BaseCombatAIComponent*>(target->GetComponent(eReplicaComponentType::BASE_COMBAT_AI)); if (combatAiComponent == nullptr) { return; diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 8e778d1d..a5255b07 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -106,7 +106,7 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id): int32_t collisionGroup = (COLLISION_GROUP_DYNAMIC | COLLISION_GROUP_ENEMY); CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - auto componentID = componentRegistryTable->GetByIDAndType(parent->GetLOT(), COMPONENT_TYPE_CONTROLLABLE_PHYSICS); + auto componentID = componentRegistryTable->GetByIDAndType(parent->GetLOT(), eReplicaComponentType::CONTROLLABLE_PHYSICS); CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance()->GetTable<CDPhysicsComponentTable>("PhysicsComponent"); diff --git a/dGame/dComponents/BaseCombatAIComponent.h b/dGame/dComponents/BaseCombatAIComponent.h index 6e55a4b1..8bf6140a 100644 --- a/dGame/dComponents/BaseCombatAIComponent.h +++ b/dGame/dComponents/BaseCombatAIComponent.h @@ -8,6 +8,7 @@ #include "dpWorld.h" #include "dpEntity.h" #include "Component.h" +#include "eReplicaComponentType.h" #include <vector> #include <map> @@ -46,7 +47,7 @@ struct AiSkillEntry */ class BaseCombatAIComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_BASE_COMBAT_AI; + static const eReplicaComponentType ComponentType = eReplicaComponentType::BASE_COMBAT_AI; BaseCombatAIComponent(Entity* parentEntity, uint32_t id); ~BaseCombatAIComponent() override; @@ -245,7 +246,7 @@ private: /** * @brief Sets the AiState and prepares the entity for serialization next frame. - * + * */ void SetAiState(AiState newState); @@ -377,7 +378,7 @@ private: /** * Whether or not the Component has dirty information and should update next frame - * + * */ bool m_DirtyStateOrTarget = false; diff --git a/dGame/dComponents/BouncerComponent.h b/dGame/dComponents/BouncerComponent.h index f179998b..15665cc1 100644 --- a/dGame/dComponents/BouncerComponent.h +++ b/dGame/dComponents/BouncerComponent.h @@ -5,13 +5,14 @@ #include "RakNetTypes.h" #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Attached to bouncer entities, allowing other entities to bounce off of it */ class BouncerComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_BOUNCER; + static const eReplicaComponentType ComponentType = eReplicaComponentType::BOUNCER; BouncerComponent(Entity* parentEntity); ~BouncerComponent() override; diff --git a/dGame/dComponents/BuffComponent.h b/dGame/dComponents/BuffComponent.h index 7f7c6b0f..d9175883 100644 --- a/dGame/dComponents/BuffComponent.h +++ b/dGame/dComponents/BuffComponent.h @@ -7,6 +7,7 @@ #include <unordered_map> #include <map> #include "Component.h" +#include "eReplicaComponentType.h" class Entity; @@ -41,7 +42,7 @@ struct Buff */ class BuffComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_BUFF; + static const eReplicaComponentType ComponentType = eReplicaComponentType::BUFF; explicit BuffComponent(Entity* parent); diff --git a/dGame/dComponents/BuildBorderComponent.h b/dGame/dComponents/BuildBorderComponent.h index ba677e37..dc5afc8a 100644 --- a/dGame/dComponents/BuildBorderComponent.h +++ b/dGame/dComponents/BuildBorderComponent.h @@ -9,13 +9,14 @@ #include "BitStream.h" #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Component for the build border, allowing the user to start building when interacting with it */ class BuildBorderComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_BUILD_BORDER; + static const eReplicaComponentType ComponentType = eReplicaComponentType::BUILD_BORDER; BuildBorderComponent(Entity* parent); ~BuildBorderComponent() override; diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index 196dfa01..613f2322 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -9,6 +9,7 @@ #include <string> #include "CDMissionsTable.h" #include "tinyxml2.h" +#include "eReplicaComponentType.h" /** * The statistics that can be achieved per zone @@ -59,7 +60,7 @@ enum StatisticID { */ class CharacterComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_CHARACTER; + static const eReplicaComponentType ComponentType = eReplicaComponentType::CHARACTER; CharacterComponent(Entity* parent, Character* character); ~CharacterComponent() override; diff --git a/dGame/dComponents/ControllablePhysicsComponent.h b/dGame/dComponents/ControllablePhysicsComponent.h index a05a11fd..a7359a26 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.h +++ b/dGame/dComponents/ControllablePhysicsComponent.h @@ -10,6 +10,7 @@ #include "dpCollisionChecks.h" #include "PhantomPhysicsComponent.h" #include "eBubbleType.h" +#include "eReplicaComponentType.h" class Entity; class dpEntity; @@ -19,7 +20,7 @@ class dpEntity; */ class ControllablePhysicsComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_CONTROLLABLE_PHYSICS; + static const eReplicaComponentType ComponentType = eReplicaComponentType::CONTROLLABLE_PHYSICS; ControllablePhysicsComponent(Entity* entity); ~ControllablePhysicsComponent() override; diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 4763c863..51d68a12 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -76,9 +76,9 @@ DestroyableComponent::~DestroyableComponent() { void DestroyableComponent::Reinitialize(LOT templateID) { CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - int32_t buffComponentID = compRegistryTable->GetByIDAndType(templateID, COMPONENT_TYPE_BUFF); - int32_t collectibleComponentID = compRegistryTable->GetByIDAndType(templateID, COMPONENT_TYPE_COLLECTIBLE); - int32_t rebuildComponentID = compRegistryTable->GetByIDAndType(templateID, COMPONENT_TYPE_REBUILD); + int32_t buffComponentID = compRegistryTable->GetByIDAndType(templateID, eReplicaComponentType::BUFF); + int32_t collectibleComponentID = compRegistryTable->GetByIDAndType(templateID, eReplicaComponentType::COLLECTIBLE); + int32_t rebuildComponentID = compRegistryTable->GetByIDAndType(templateID, eReplicaComponentType::QUICK_BUILD); int32_t componentID = 0; if (collectibleComponentID > 0) componentID = collectibleComponentID; @@ -810,7 +810,7 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType script->OnPlayerDied(zoneControl, m_Parent); } - std::vector<Entity*> scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY); + std::vector<Entity*> scriptedActs = EntityManager::Instance()->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)) { diff --git a/dGame/dComponents/DestroyableComponent.h b/dGame/dComponents/DestroyableComponent.h index 854144d9..47be96a0 100644 --- a/dGame/dComponents/DestroyableComponent.h +++ b/dGame/dComponents/DestroyableComponent.h @@ -6,6 +6,7 @@ #include "tinyxml2.h" #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" namespace CppScripts { class Script; @@ -17,7 +18,7 @@ namespace CppScripts { */ class DestroyableComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_DESTROYABLE; + static const eReplicaComponentType ComponentType = eReplicaComponentType::DESTROYABLE; DestroyableComponent(Entity* parentEntity); ~DestroyableComponent() override; diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 8925554e..df292e2a 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -48,7 +48,7 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do } auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - const auto componentId = compRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_INVENTORY); + const auto componentId = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::INVENTORY); auto* inventoryComponentTable = CDClientManager::Instance()->GetTable<CDInventoryComponentTable>("InventoryComponent"); auto items = inventoryComponentTable->Query([=](const CDInventoryComponent entry) { return entry.id == componentId; }); @@ -181,7 +181,7 @@ void InventoryComponent::AddItem( inventoryType = Inventory::FindInventoryTypeForLot(lot); } - auto* missions = static_cast<MissionComponent*>(this->m_Parent->GetComponent(COMPONENT_TYPE_MISSION)); + auto* missions = static_cast<MissionComponent*>(this->m_Parent->GetComponent(eReplicaComponentType::MISSION)); auto* inventory = GetInventory(inventoryType); @@ -818,7 +818,7 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) { if (character != nullptr && !skipChecks) { // Hacky proximity rocket if (item->GetLot() == 6416) { - const auto rocketLauchPads = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_ROCKET_LAUNCH); + const auto rocketLauchPads = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::ROCKET_LAUNCH); const auto position = m_Parent->GetPosition(); @@ -914,7 +914,7 @@ void InventoryComponent::UnEquipItem(Item* item) { void InventoryComponent::EquipScripts(Item* equippedItem) { CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); if (!compRegistryTable) return; - int32_t scriptComponentID = compRegistryTable->GetByIDAndType(equippedItem->GetLot(), COMPONENT_TYPE_SCRIPT, -1); + int32_t scriptComponentID = compRegistryTable->GetByIDAndType(equippedItem->GetLot(), eReplicaComponentType::SCRIPT, -1); if (scriptComponentID > -1) { CDScriptComponentTable* scriptCompTable = CDClientManager::Instance()->GetTable<CDScriptComponentTable>("ScriptComponent"); CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); @@ -929,7 +929,7 @@ void InventoryComponent::EquipScripts(Item* equippedItem) { void InventoryComponent::UnequipScripts(Item* unequippedItem) { CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); if (!compRegistryTable) return; - int32_t scriptComponentID = compRegistryTable->GetByIDAndType(unequippedItem->GetLot(), COMPONENT_TYPE_SCRIPT, -1); + int32_t scriptComponentID = compRegistryTable->GetByIDAndType(unequippedItem->GetLot(), eReplicaComponentType::SCRIPT, -1); if (scriptComponentID > -1) { CDScriptComponentTable* scriptCompTable = CDClientManager::Instance()->GetTable<CDScriptComponentTable>("ScriptComponent"); CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); @@ -1331,7 +1331,7 @@ std::vector<uint32_t> InventoryComponent::FindBuffs(Item* item, bool castOnEquip return entry.objectTemplate == static_cast<unsigned int>(item->GetLot()); }); - auto* missions = static_cast<MissionComponent*>(m_Parent->GetComponent(COMPONENT_TYPE_MISSION)); + auto* missions = static_cast<MissionComponent*>(m_Parent->GetComponent(eReplicaComponentType::MISSION)); for (const auto& result : results) { if (result.castOnType == 1) { diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index b660de15..d695737c 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -20,6 +20,7 @@ #include "eItemSetPassiveAbilityID.h" #include "PossessorComponent.h" #include "eInventoryType.h" +#include "eReplicaComponentType.h" class Entity; class ItemSet; @@ -36,7 +37,7 @@ enum class eItemType : int32_t; class InventoryComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_INVENTORY; + static const eReplicaComponentType ComponentType = eReplicaComponentType::INVENTORY; explicit InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document = nullptr); void Update(float deltaTime) override; diff --git a/dGame/dComponents/LUPExhibitComponent.h b/dGame/dComponents/LUPExhibitComponent.h index 2d128f6c..587d1b2f 100644 --- a/dGame/dComponents/LUPExhibitComponent.h +++ b/dGame/dComponents/LUPExhibitComponent.h @@ -2,6 +2,7 @@ #include "Component.h" #include "Entity.h" +#include "eReplicaComponentType.h" /** * Component that handles the LOT that is shown in the LUP exhibit in the LUP world. Works by setting a timer and @@ -10,7 +11,7 @@ class LUPExhibitComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_EXHIBIT; + static const eReplicaComponentType ComponentType = eReplicaComponentType::EXHIBIT; LUPExhibitComponent(Entity* parent); ~LUPExhibitComponent(); diff --git a/dGame/dComponents/LevelProgressionComponent.h b/dGame/dComponents/LevelProgressionComponent.h index dd3fbfbb..06908a81 100644 --- a/dGame/dComponents/LevelProgressionComponent.h +++ b/dGame/dComponents/LevelProgressionComponent.h @@ -4,6 +4,7 @@ #include "GameMessages.h" #include "Component.h" #include "eCharacterVersion.h" +#include "eReplicaComponentType.h" /** * Component that handles level progression and serilization. @@ -12,7 +13,7 @@ class LevelProgressionComponent : public Component { public: - static const uint32_t ComponentType = eReplicaComponentType::COMPONENT_TYPE_LEVEL_PROGRESSION; + static const eReplicaComponentType ComponentType = eReplicaComponentType::LEVEL_PROGRESSION; /** * Constructor for this component diff --git a/dGame/dComponents/MissionComponent.h b/dGame/dComponents/MissionComponent.h index 231b3321..eeaaa726 100644 --- a/dGame/dComponents/MissionComponent.h +++ b/dGame/dComponents/MissionComponent.h @@ -16,6 +16,7 @@ #include "CDClientManager.h" #include "CDMissionsTable.h" #include "Component.h" +#include "eReplicaComponentType.h" class AchievementCacheKey; @@ -26,7 +27,7 @@ class AchievementCacheKey; class MissionComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MISSION; + static const eReplicaComponentType ComponentType = eReplicaComponentType::MISSION; explicit MissionComponent(Entity* parent); ~MissionComponent() override; diff --git a/dGame/dComponents/MissionOfferComponent.cpp b/dGame/dComponents/MissionOfferComponent.cpp index f8446868..ad315314 100644 --- a/dGame/dComponents/MissionOfferComponent.cpp +++ b/dGame/dComponents/MissionOfferComponent.cpp @@ -40,7 +40,7 @@ bool OfferedMission::GetAcceptMission() const { MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot) : Component(parent) { auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - auto value = compRegistryTable->GetByIDAndType(parentLot, COMPONENT_TYPE_MISSION_OFFER, -1); + auto value = compRegistryTable->GetByIDAndType(parentLot, eReplicaComponentType::MISSION_OFFER, -1); if (value != -1) { const uint32_t componentId = value; @@ -77,7 +77,7 @@ void MissionOfferComponent::OnUse(Entity* originator) { void MissionOfferComponent::OfferMissions(Entity* entity, const uint32_t specifiedMissionId) { // First, get the entity's MissionComponent. If there is not one, then we cannot offer missions to this entity. - auto* missionComponent = static_cast<MissionComponent*>(entity->GetComponent(COMPONENT_TYPE_MISSION)); + auto* missionComponent = static_cast<MissionComponent*>(entity->GetComponent(eReplicaComponentType::MISSION)); if (!missionComponent) { Game::logger->Log("MissionOfferComponent", "Unable to get mission component for Entity %llu", entity->GetObjectID()); diff --git a/dGame/dComponents/MissionOfferComponent.h b/dGame/dComponents/MissionOfferComponent.h index 42aad3c4..6e22ca05 100644 --- a/dGame/dComponents/MissionOfferComponent.h +++ b/dGame/dComponents/MissionOfferComponent.h @@ -10,6 +10,7 @@ #include "Component.h" #include <vector> #include <stdint.h> +#include "eReplicaComponentType.h" class Entity; @@ -60,7 +61,7 @@ private: */ class MissionOfferComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MISSION_OFFER; + static const eReplicaComponentType ComponentType = eReplicaComponentType::MISSION_OFFER; MissionOfferComponent(Entity* parent, LOT parentLot); ~MissionOfferComponent() override; diff --git a/dGame/dComponents/ModelComponent.cpp b/dGame/dComponents/ModelComponent.cpp index 8fa085f2..74f614d1 100644 --- a/dGame/dComponents/ModelComponent.cpp +++ b/dGame/dComponents/ModelComponent.cpp @@ -10,7 +10,7 @@ ModelComponent::ModelComponent(Entity* parent) : Component(parent) { void ModelComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { // ItemComponent Serialization. Pets do not get this serialization. - if (!m_Parent->HasComponent(COMPONENT_TYPE_PET)) { + if (!m_Parent->HasComponent(eReplicaComponentType::PET)) { outBitStream->Write1(); outBitStream->Write<LWOOBJID>(m_userModelID != LWOOBJID_EMPTY ? m_userModelID : m_Parent->GetObjectID()); outBitStream->Write<int>(0); diff --git a/dGame/dComponents/ModelComponent.h b/dGame/dComponents/ModelComponent.h index 81342059..b5224869 100644 --- a/dGame/dComponents/ModelComponent.h +++ b/dGame/dComponents/ModelComponent.h @@ -4,6 +4,7 @@ #include "NiPoint3.h" #include "NiQuaternion.h" #include "Component.h" +#include "eReplicaComponentType.h" class Entity; @@ -12,7 +13,7 @@ class Entity; */ class ModelComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MODEL; + static const eReplicaComponentType ComponentType = eReplicaComponentType::MODEL; ModelComponent(Entity* parent); diff --git a/dGame/dComponents/ModuleAssemblyComponent.h b/dGame/dComponents/ModuleAssemblyComponent.h index 24e1c1ee..c6e217ed 100644 --- a/dGame/dComponents/ModuleAssemblyComponent.h +++ b/dGame/dComponents/ModuleAssemblyComponent.h @@ -3,6 +3,7 @@ #include "BitStream.h" #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Component that belongs to an object that may be modularly built, like cars and rockets. Note that this is not the @@ -11,7 +12,7 @@ */ class ModuleAssemblyComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MODULE_ASSEMBLY; + static const eReplicaComponentType ComponentType = eReplicaComponentType::MODULE_ASSEMBLY; ModuleAssemblyComponent(Entity* MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); ~ModuleAssemblyComponent() override; diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index 92397a55..fa54eb6d 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -19,7 +19,7 @@ MovementAIComponent::MovementAIComponent(Entity* parent, MovementAIInfo info) : m_BaseCombatAI = nullptr; - m_BaseCombatAI = reinterpret_cast<BaseCombatAIComponent*>(m_Parent->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); + m_BaseCombatAI = reinterpret_cast<BaseCombatAIComponent*>(m_Parent->GetComponent(eReplicaComponentType::BASE_COMBAT_AI)); //Try and fix the insane values: if (m_Info.wanderRadius > 5.0f) m_Info.wanderRadius = m_Info.wanderRadius * 0.5f; @@ -286,7 +286,7 @@ float MovementAIComponent::GetBaseSpeed(LOT lot) { int32_t componentID; CDPhysicsComponent* physicsComponent = nullptr; - componentID = componentRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_CONTROLLABLE_PHYSICS, -1); + componentID = componentRegistryTable->GetByIDAndType(lot, eReplicaComponentType::CONTROLLABLE_PHYSICS, -1); if (componentID != -1) { physicsComponent = physicsComponentTable->GetByID(componentID); @@ -294,7 +294,7 @@ float MovementAIComponent::GetBaseSpeed(LOT lot) { goto foundComponent; } - componentID = componentRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_SIMPLE_PHYSICS, -1); + componentID = componentRegistryTable->GetByIDAndType(lot, eReplicaComponentType::SIMPLE_PHYSICS, -1); if (componentID != -1) { physicsComponent = physicsComponentTable->GetByID(componentID); diff --git a/dGame/dComponents/MovementAIComponent.h b/dGame/dComponents/MovementAIComponent.h index 82cd48a0..3c9044aa 100644 --- a/dGame/dComponents/MovementAIComponent.h +++ b/dGame/dComponents/MovementAIComponent.h @@ -13,6 +13,7 @@ #include "Game.h" #include "dLogger.h" #include "Component.h" +#include "eReplicaComponentType.h" #include <vector> class ControllablePhysicsComponent; @@ -56,7 +57,7 @@ struct MovementAIInfo { */ class MovementAIComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MOVEMENT_AI; + static const eReplicaComponentType ComponentType = eReplicaComponentType::MOVEMENT_AI; MovementAIComponent(Entity* parentEntity, MovementAIInfo info); ~MovementAIComponent() override; diff --git a/dGame/dComponents/MovingPlatformComponent.h b/dGame/dComponents/MovingPlatformComponent.h index 38b15143..9e4c1ecf 100644 --- a/dGame/dComponents/MovingPlatformComponent.h +++ b/dGame/dComponents/MovingPlatformComponent.h @@ -14,6 +14,7 @@ #include "EntityManager.h" #include "Component.h" #include "eMovementPlatformState.h" +#include "eReplicaComponentType.h" class Path; @@ -105,7 +106,7 @@ public: */ class MovingPlatformComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_MOVING_PLATFORM; + static const eReplicaComponentType ComponentType = eReplicaComponentType::MOVING_PLATFORM; MovingPlatformComponent(Entity* parent, const std::string& pathName); ~MovingPlatformComponent() override; diff --git a/dGame/dComponents/PetComponent.h b/dGame/dComponents/PetComponent.h index efde0e8a..e3c1556b 100644 --- a/dGame/dComponents/PetComponent.h +++ b/dGame/dComponents/PetComponent.h @@ -4,6 +4,7 @@ #include "MovementAIComponent.h" #include "Component.h" #include "Preconditions.h" +#include "eReplicaComponentType.h" enum class PetAbilityType { @@ -20,7 +21,7 @@ enum class PetAbilityType class PetComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PET; + static const eReplicaComponentType ComponentType = eReplicaComponentType::PET; explicit PetComponent(Entity* parentEntity, uint32_t componentId); ~PetComponent() override; diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index aa3ced46..b95b7cdd 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -144,7 +144,7 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par if (!m_HasCreatedPhysics) { CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), COMPONENT_TYPE_PHANTOM_PHYSICS); + auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::PHANTOM_PHYSICS); CDPhysicsComponentTable* physComp = CDClientManager::Instance()->GetTable<CDPhysicsComponentTable>("PhysicsComponent"); @@ -254,7 +254,7 @@ void PhantomPhysicsComponent::CreatePhysics() { z = m_Parent->GetVar<float>(u"primitiveModelValueZ"); } else { CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), COMPONENT_TYPE_PHANTOM_PHYSICS); + auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::PHANTOM_PHYSICS); CDPhysicsComponentTable* physComp = CDClientManager::Instance()->GetTable<CDPhysicsComponentTable>("PhysicsComponent"); diff --git a/dGame/dComponents/PhantomPhysicsComponent.h b/dGame/dComponents/PhantomPhysicsComponent.h index 1e9a7b60..0b27db05 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.h +++ b/dGame/dComponents/PhantomPhysicsComponent.h @@ -12,6 +12,7 @@ #include "CppScripts.h" #include "InvalidScript.h" #include "Component.h" +#include "eReplicaComponentType.h" class LDFBaseData; class Entity; @@ -25,7 +26,7 @@ class dpEntity; */ class PhantomPhysicsComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PHANTOM_PHYSICS; + static const eReplicaComponentType ComponentType = eReplicaComponentType::PHANTOM_PHYSICS; PhantomPhysicsComponent(Entity* parent); ~PhantomPhysicsComponent() override; diff --git a/dGame/dComponents/PlayerForcedMovementComponent.h b/dGame/dComponents/PlayerForcedMovementComponent.h index 43b99997..90708c9a 100644 --- a/dGame/dComponents/PlayerForcedMovementComponent.h +++ b/dGame/dComponents/PlayerForcedMovementComponent.h @@ -2,6 +2,7 @@ #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Component that handles player forced movement @@ -9,7 +10,7 @@ */ class PlayerForcedMovementComponent : public Component { public: - static const uint32_t ComponentType = eReplicaComponentType::COMPONENT_TYPE_PLAYER_FORCED_MOVEMENT; + static const eReplicaComponentType ComponentType = eReplicaComponentType::PLAYER_FORCED_MOVEMENT; /** * Constructor for this component diff --git a/dGame/dComponents/PossessableComponent.h b/dGame/dComponents/PossessableComponent.h index e1dc5ccd..2026c11e 100644 --- a/dGame/dComponents/PossessableComponent.h +++ b/dGame/dComponents/PossessableComponent.h @@ -6,6 +6,7 @@ #include "Item.h" #include "PossessorComponent.h" #include "eAninmationFlags.h" +#include "eReplicaComponentType.h" /** * Represents an entity that can be controlled by some other entity, generally used by cars to indicate that some @@ -13,7 +14,7 @@ */ class PossessableComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_POSSESSABLE; + static const eReplicaComponentType ComponentType = eReplicaComponentType::POSSESSABLE; PossessableComponent(Entity* parentEntity, uint32_t componentId); diff --git a/dGame/dComponents/PossessorComponent.h b/dGame/dComponents/PossessorComponent.h index 00b24445..4456af27 100644 --- a/dGame/dComponents/PossessorComponent.h +++ b/dGame/dComponents/PossessorComponent.h @@ -3,6 +3,7 @@ #include "BitStream.h" #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" // possession types enum class ePossessionType : uint8_t { @@ -17,7 +18,7 @@ enum class ePossessionType : uint8_t { */ class PossessorComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_POSSESSOR; + static const eReplicaComponentType ComponentType = eReplicaComponentType::POSSESSOR; PossessorComponent(Entity* parent); ~PossessorComponent() override; diff --git a/dGame/dComponents/PropertyComponent.h b/dGame/dComponents/PropertyComponent.h index 2096a475..41f93677 100644 --- a/dGame/dComponents/PropertyComponent.h +++ b/dGame/dComponents/PropertyComponent.h @@ -9,6 +9,7 @@ #include "BitStream.h" #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" struct PropertyState { LWOOBJID ownerID; @@ -21,7 +22,7 @@ struct PropertyState { */ class PropertyComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PROPERTY; + static const eReplicaComponentType ComponentType = eReplicaComponentType::PROPERTY; explicit PropertyComponent(Entity* parentEntity); ~PropertyComponent() override; [[nodiscard]] PropertyState* GetPropertyState() const { return m_PropertyState; }; diff --git a/dGame/dComponents/PropertyEntranceComponent.h b/dGame/dComponents/PropertyEntranceComponent.h index 4110e7d9..e37d1daa 100644 --- a/dGame/dComponents/PropertyEntranceComponent.h +++ b/dGame/dComponents/PropertyEntranceComponent.h @@ -6,13 +6,14 @@ #include "Entity.h" #include "EntityManager.h" #include "GameMessages.h" +#include "eReplicaComponentType.h" /** * Represents the launch pad that's used to select and browse properties */ class PropertyEntranceComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PROPERTY_ENTRANCE; + static const eReplicaComponentType ComponentType = eReplicaComponentType::PROPERTY_ENTRANCE; explicit PropertyEntranceComponent(uint32_t componentID, Entity* parent); /** diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index ce2c8e5e..0b05b10e 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -255,7 +255,7 @@ void PropertyManagementComponent::OnStartBuilding() { LWOMAPID zoneId = 1100; - const auto entrance = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_PROPERTY_ENTRANCE); + const auto entrance = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::PROPERTY_ENTRANCE); originalPrivacyOption = privacyOption; diff --git a/dGame/dComponents/PropertyManagementComponent.h b/dGame/dComponents/PropertyManagementComponent.h index d9526015..2ee010a8 100644 --- a/dGame/dComponents/PropertyManagementComponent.h +++ b/dGame/dComponents/PropertyManagementComponent.h @@ -3,6 +3,7 @@ #include <chrono> #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Information regarding which players may visit this property @@ -31,7 +32,7 @@ enum class PropertyPrivacyOption class PropertyManagementComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PROPERTY_MANAGEMENT; + static const eReplicaComponentType ComponentType = eReplicaComponentType::PROPERTY_MANAGEMENT; PropertyManagementComponent(Entity* parent); static PropertyManagementComponent* Instance(); diff --git a/dGame/dComponents/PropertyVendorComponent.h b/dGame/dComponents/PropertyVendorComponent.h index f947d745..5055b445 100644 --- a/dGame/dComponents/PropertyVendorComponent.h +++ b/dGame/dComponents/PropertyVendorComponent.h @@ -2,6 +2,7 @@ #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * The property guard that stands on a property before it's claimed, allows entities to attempt claiming this property. @@ -9,7 +10,7 @@ class PropertyVendorComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PROPERTY_VENDOR; + static const eReplicaComponentType ComponentType = eReplicaComponentType::PROPERTY_VENDOR; explicit PropertyVendorComponent(Entity* parent); /** diff --git a/dGame/dComponents/ProximityMonitorComponent.h b/dGame/dComponents/ProximityMonitorComponent.h index a98397a2..2f51917d 100644 --- a/dGame/dComponents/ProximityMonitorComponent.h +++ b/dGame/dComponents/ProximityMonitorComponent.h @@ -11,6 +11,7 @@ #include "dpWorld.h" #include "dpEntity.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Utility component for detecting how close entities are to named proximities for this entity. Allows you to store @@ -18,7 +19,7 @@ */ class ProximityMonitorComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PROXIMITY_MONITOR; + static const eReplicaComponentType ComponentType = eReplicaComponentType::PROXIMITY_MONITOR; ProximityMonitorComponent(Entity* parentEntity, int smallRadius = -1, int largeRadius = -1); ~ProximityMonitorComponent() override; diff --git a/dGame/dComponents/RacingControlComponent.h b/dGame/dComponents/RacingControlComponent.h index 933178cc..91ab2fd4 100644 --- a/dGame/dComponents/RacingControlComponent.h +++ b/dGame/dComponents/RacingControlComponent.h @@ -7,6 +7,7 @@ #include "BitStream.h" #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Information for each player in the race @@ -104,7 +105,7 @@ struct RacingPlayerInfo { */ class RacingControlComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_RACING_CONTROL; + static const eReplicaComponentType ComponentType = eReplicaComponentType::RACING_CONTROL; RacingControlComponent(Entity* parentEntity); ~RacingControlComponent(); diff --git a/dGame/dComponents/RailActivatorComponent.h b/dGame/dComponents/RailActivatorComponent.h index 8f67e7e3..5d625d2a 100644 --- a/dGame/dComponents/RailActivatorComponent.h +++ b/dGame/dComponents/RailActivatorComponent.h @@ -4,6 +4,7 @@ #include <string> #include "dCommonVars.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Component that handles the traveling using rails, e.g. the ninjago posts that can be used to travel using Spinjitzu. @@ -14,7 +15,7 @@ public: explicit RailActivatorComponent(Entity* parent, int32_t componentID); ~RailActivatorComponent() override; - static const uint32_t ComponentType = COMPONENT_TYPE_RAIL_ACTIVATOR; + static const eReplicaComponentType ComponentType = eReplicaComponentType::RAIL_ACTIVATOR; /** * Handles the OnUse event from some entity, initiates the rail movement diff --git a/dGame/dComponents/RebuildComponent.cpp b/dGame/dComponents/RebuildComponent.cpp index bf7bd3e5..abd21873 100644 --- a/dGame/dComponents/RebuildComponent.cpp +++ b/dGame/dComponents/RebuildComponent.cpp @@ -53,7 +53,7 @@ RebuildComponent::~RebuildComponent() { } void RebuildComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { - if (m_Parent->GetComponent(COMPONENT_TYPE_DESTROYABLE) == nullptr) { + if (m_Parent->GetComponent(eReplicaComponentType::DESTROYABLE) == nullptr) { if (bIsInitialUpdate) { outBitStream->Write(false); } diff --git a/dGame/dComponents/RebuildComponent.h b/dGame/dComponents/RebuildComponent.h index bd3edd7d..a8e11e4c 100644 --- a/dGame/dComponents/RebuildComponent.h +++ b/dGame/dComponents/RebuildComponent.h @@ -9,6 +9,7 @@ #include "ScriptedActivityComponent.h" #include "Preconditions.h" #include "Component.h" +#include "eReplicaComponentType.h" class Entity; @@ -19,7 +20,7 @@ class Entity; */ class RebuildComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_REBUILD; + static const eReplicaComponentType ComponentType = eReplicaComponentType::QUICK_BUILD; RebuildComponent(Entity* entity); ~RebuildComponent() override; diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index 3002ae33..f188859d 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -22,7 +22,7 @@ RenderComponent::RenderComponent(Entity* parent) : Component(parent) { /* auto* table = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - const auto entry = table->GetByIDAndType(parent->GetLOT(), COMPONENT_TYPE_RENDER); + const auto entry = table->GetByIDAndType(parent->GetLOT(), eReplicaComponentType::RENDER); std::stringstream query; diff --git a/dGame/dComponents/RenderComponent.h b/dGame/dComponents/RenderComponent.h index e6184564..de8b2907 100644 --- a/dGame/dComponents/RenderComponent.h +++ b/dGame/dComponents/RenderComponent.h @@ -8,6 +8,7 @@ #include "AMFFormat.h" #include "Component.h" +#include "eReplicaComponentType.h" class Entity; @@ -55,7 +56,7 @@ struct Effect { */ class RenderComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_RENDER; + static const eReplicaComponentType ComponentType = eReplicaComponentType::RENDER; RenderComponent(Entity* entity); ~RenderComponent() override; diff --git a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h index c8faa930..480f9b81 100644 --- a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h +++ b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h @@ -11,6 +11,7 @@ #include "NiPoint3.h" #include "NiQuaternion.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Component that handles rigid bodies that can be interacted with, mostly client-side rendered. An example is the @@ -18,7 +19,7 @@ */ class RigidbodyPhantomPhysicsComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_PHANTOM_PHYSICS; + static const eReplicaComponentType ComponentType = eReplicaComponentType::PHANTOM_PHYSICS; RigidbodyPhantomPhysicsComponent(Entity* parent); ~RigidbodyPhantomPhysicsComponent() override; diff --git a/dGame/dComponents/RocketLaunchLupComponent.h b/dGame/dComponents/RocketLaunchLupComponent.h index 3fc0b444..226fa1b2 100644 --- a/dGame/dComponents/RocketLaunchLupComponent.h +++ b/dGame/dComponents/RocketLaunchLupComponent.h @@ -3,6 +3,7 @@ #include "Entity.h" #include "GameMessages.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Component that handles the LUP/WBL rocket launchpad that can be interacted with to travel to WBL worlds. @@ -10,7 +11,7 @@ */ class RocketLaunchLupComponent : public Component { public: - static const uint32_t ComponentType = eReplicaComponentType::COMPONENT_TYPE_ROCKET_LAUNCH_LUP; + static const eReplicaComponentType ComponentType = eReplicaComponentType::ROCKET_LAUNCH_LUP; /** * Constructor for this component, builds the m_LUPWorlds vector diff --git a/dGame/dComponents/RocketLaunchpadControlComponent.h b/dGame/dComponents/RocketLaunchpadControlComponent.h index 8a10f0f7..84cff22d 100644 --- a/dGame/dComponents/RocketLaunchpadControlComponent.h +++ b/dGame/dComponents/RocketLaunchpadControlComponent.h @@ -9,6 +9,7 @@ #include "BitStream.h" #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" class PreconditionExpression; @@ -17,7 +18,7 @@ class PreconditionExpression; */ class RocketLaunchpadControlComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_ROCKET_LAUNCH; + static const eReplicaComponentType ComponentType = eReplicaComponentType::ROCKET_LAUNCH; RocketLaunchpadControlComponent(Entity* parent, int rocketId); ~RocketLaunchpadControlComponent() override; diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index 067446e7..4a034187 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -137,7 +137,7 @@ void ScriptedActivityComponent::PlayerJoin(Entity* player) { } void ScriptedActivityComponent::PlayerJoinLobby(Entity* player) { - if (!m_Parent->HasComponent(COMPONENT_TYPE_REBUILD)) + if (!m_Parent->HasComponent(eReplicaComponentType::QUICK_BUILD)) GameMessages::SendMatchResponse(player, player->GetSystemAddress(), 0); // tell the client they joined a lobby LobbyPlayer* newLobbyPlayer = new LobbyPlayer(); newLobbyPlayer->entityID = player->GetObjectID(); diff --git a/dGame/dComponents/ScriptedActivityComponent.h b/dGame/dComponents/ScriptedActivityComponent.h index 8bb17093..a4aad048 100644 --- a/dGame/dComponents/ScriptedActivityComponent.h +++ b/dGame/dComponents/ScriptedActivityComponent.h @@ -11,6 +11,7 @@ #include "BitStream.h" #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Represents an instance of an activity, having participants and score @@ -153,7 +154,7 @@ struct ActivityPlayer { */ class ScriptedActivityComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SCRIPTED_ACTIVITY; + static const eReplicaComponentType ComponentType = eReplicaComponentType::SCRIPTED_ACTIVITY; ScriptedActivityComponent(Entity* parent, int activityID); ~ScriptedActivityComponent() override; diff --git a/dGame/dComponents/ShootingGalleryComponent.h b/dGame/dComponents/ShootingGalleryComponent.h index c43f20c2..c31575f1 100644 --- a/dGame/dComponents/ShootingGalleryComponent.h +++ b/dGame/dComponents/ShootingGalleryComponent.h @@ -3,6 +3,7 @@ #include "NiPoint3.h" #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Parameters for the shooting gallery that change during playtime @@ -72,7 +73,7 @@ struct StaticShootingGalleryParams { */ class ShootingGalleryComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SHOOTING_GALLERY; + static const eReplicaComponentType ComponentType = eReplicaComponentType::SHOOTING_GALLERY; explicit ShootingGalleryComponent(Entity* parent); ~ShootingGalleryComponent(); diff --git a/dGame/dComponents/SimplePhysicsComponent.h b/dGame/dComponents/SimplePhysicsComponent.h index ebb8b124..51356710 100644 --- a/dGame/dComponents/SimplePhysicsComponent.h +++ b/dGame/dComponents/SimplePhysicsComponent.h @@ -11,6 +11,7 @@ #include "NiPoint3.h" #include "NiQuaternion.h" #include "Component.h" +#include "eReplicaComponentType.h" class Entity; @@ -27,7 +28,7 @@ enum class eClimbableType : int32_t { */ class SimplePhysicsComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SIMPLE_PHYSICS; + static const eReplicaComponentType ComponentType = eReplicaComponentType::SIMPLE_PHYSICS; SimplePhysicsComponent(uint32_t componentID, Entity* parent); ~SimplePhysicsComponent() override; diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index 2391dc3b..625f1f30 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -128,7 +128,7 @@ void SkillComponent::RegisterPlayerProjectile(const LWOOBJID projectileId, Behav } void SkillComponent::Update(const float deltaTime) { - if (!m_Parent->HasComponent(COMPONENT_TYPE_BASE_COMBAT_AI) && m_Parent->GetLOT() != 1) { + if (!m_Parent->HasComponent(eReplicaComponentType::BASE_COMBAT_AI) && m_Parent->GetLOT() != 1) { CalculateUpdate(deltaTime); } diff --git a/dGame/dComponents/SkillComponent.h b/dGame/dComponents/SkillComponent.h index 2bdcb88f..034e65ce 100644 --- a/dGame/dComponents/SkillComponent.h +++ b/dGame/dComponents/SkillComponent.h @@ -13,6 +13,7 @@ #include "Component.h" #include "Entity.h" #include "dLogger.h" +#include "eReplicaComponentType.h" struct ProjectileSyncEntry { LWOOBJID id = LWOOBJID_EMPTY; @@ -58,7 +59,7 @@ struct SkillExecutionResult { */ class SkillComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SKILL; + static const eReplicaComponentType ComponentType = eReplicaComponentType::SKILL; explicit SkillComponent(Entity* parent); ~SkillComponent() override; diff --git a/dGame/dComponents/SoundTriggerComponent.h b/dGame/dComponents/SoundTriggerComponent.h index e1178150..954d8495 100644 --- a/dGame/dComponents/SoundTriggerComponent.h +++ b/dGame/dComponents/SoundTriggerComponent.h @@ -3,6 +3,7 @@ #include "Entity.h" #include "GUID.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Music that should be played by the client @@ -19,7 +20,7 @@ struct MusicCue { */ class SoundTriggerComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SOUND_TRIGGER; + static const eReplicaComponentType ComponentType = eReplicaComponentType::SOUND_TRIGGER; explicit SoundTriggerComponent(Entity* parent); ~SoundTriggerComponent() override; diff --git a/dGame/dComponents/SwitchComponent.h b/dGame/dComponents/SwitchComponent.h index ea5955d8..fde3cfc0 100644 --- a/dGame/dComponents/SwitchComponent.h +++ b/dGame/dComponents/SwitchComponent.h @@ -9,13 +9,14 @@ #include "BouncerComponent.h" #include <algorithm> #include "Component.h" +#include "eReplicaComponentType.h" /** * A component for switches in game, including pet triggered switches. */ class SwitchComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SWITCH; + static const eReplicaComponentType ComponentType = eReplicaComponentType::SWITCH; SwitchComponent(Entity* parent); ~SwitchComponent() override; diff --git a/dGame/dComponents/TriggerComponent.h b/dGame/dComponents/TriggerComponent.h index d7711696..492b0449 100644 --- a/dGame/dComponents/TriggerComponent.h +++ b/dGame/dComponents/TriggerComponent.h @@ -2,6 +2,7 @@ #define __TRIGGERCOMPONENT__H__ #include "Component.h" +#include "eReplicaComponentType.h" namespace LUTriggers { struct Trigger; @@ -10,7 +11,7 @@ namespace LUTriggers { class TriggerComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_TRIGGER; + static const eReplicaComponentType ComponentType = eReplicaComponentType::TRIGGER; explicit TriggerComponent(Entity* parent, const std::string triggerInfo); diff --git a/dGame/dComponents/VehiclePhysicsComponent.h b/dGame/dComponents/VehiclePhysicsComponent.h index f5ab1917..551cce42 100644 --- a/dGame/dComponents/VehiclePhysicsComponent.h +++ b/dGame/dComponents/VehiclePhysicsComponent.h @@ -3,13 +3,14 @@ #include "BitStream.h" #include "Entity.h" #include "Component.h" +#include "eReplicaComponentType.h" /** * Physics component for vehicles. */ class VehiclePhysicsComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_VEHICLE_PHYSICS; + static const eReplicaComponentType ComponentType = eReplicaComponentType::VEHICLE_PHYSICS; VehiclePhysicsComponent(Entity* parentEntity); ~VehiclePhysicsComponent() override; diff --git a/dGame/dComponents/VendorComponent.cpp b/dGame/dComponents/VendorComponent.cpp index 96dfb2c0..e9599b71 100644 --- a/dGame/dComponents/VendorComponent.cpp +++ b/dGame/dComponents/VendorComponent.cpp @@ -119,7 +119,7 @@ void VendorComponent::RefreshInventory(bool isCreation) { void VendorComponent::SetupConstants() { auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - int componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), COMPONENT_TYPE_VENDOR); + int componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::VENDOR); auto* vendorComponentTable = CDClientManager::Instance()->GetTable<CDVendorComponentTable>("VendorComponent"); std::vector<CDVendorComponent> vendorComps = vendorComponentTable->Query([=](CDVendorComponent entry) { return (entry.id == componentID); }); diff --git a/dGame/dComponents/VendorComponent.h b/dGame/dComponents/VendorComponent.h index 72a5816d..bf372bf2 100644 --- a/dGame/dComponents/VendorComponent.h +++ b/dGame/dComponents/VendorComponent.h @@ -7,13 +7,14 @@ #include "Entity.h" #include "GameMessages.h" #include "RakNetTypes.h" +#include "eReplicaComponentType.h" /** * A component for vendor NPCs. A vendor sells items to the player. */ class VendorComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_VENDOR; + static const eReplicaComponentType ComponentType = eReplicaComponentType::VENDOR; VendorComponent(Entity* parent); ~VendorComponent() override; diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 16942ecc..b63f1c6d 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -32,6 +32,7 @@ #include "EchoStartSkill.h" #include "EchoSyncSkill.h" #include "eMissionTaskType.h" +#include "eReplicaComponentType.h" using namespace std; @@ -122,7 +123,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System destroyable->SetImagination(destroyable->GetImagination()); EntityManager::Instance()->SerializeEntity(entity); - std::vector<Entity*> racingControllers = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RACING_CONTROL); + std::vector<Entity*> racingControllers = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::RACING_CONTROL); for (Entity* racingController : racingControllers) { auto* racingComponent = racingController->GetComponent<RacingControlComponent>(); if (racingComponent != nullptr) { @@ -135,7 +136,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System script->OnPlayerLoaded(zoneControl, player); } - std::vector<Entity*> scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); + std::vector<Entity*> scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::SCRIPT); 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)) { @@ -241,7 +242,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_REQUEST_RESURRECT: { GameMessages::SendResurrect(entity); - /*auto* dest = static_cast<DestroyableComponent*>(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); + /*auto* dest = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); if (dest) { dest->SetHealth(4); dest->SetArmor(0); diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 1d897727..9dcd2d74 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -80,6 +80,7 @@ #include "eBlueprintSaveResponseType.h" #include "eAninmationFlags.h" #include "AMFFormat_BitStream.h" +#include "eReplicaComponentType.h" void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender) { CBITSTREAM; @@ -914,7 +915,7 @@ void GameMessages::SendSetJetPackMode(Entity* entity, bool use, bool bypassCheck } void GameMessages::SendResurrect(Entity* entity) { - DestroyableComponent* dest = static_cast<DestroyableComponent*>(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); + DestroyableComponent* dest = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); if (dest != nullptr && entity->GetLOT() == 1) { auto* levelComponent = entity->GetComponent<LevelProgressionComponent>(); @@ -924,7 +925,7 @@ void GameMessages::SendResurrect(Entity* entity) { } } - auto cont = static_cast<ControllablePhysicsComponent*>(entity->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); + auto cont = static_cast<ControllablePhysicsComponent*>(entity->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (cont && entity->GetLOT() == 1) { cont->SetPosition(entity->GetRespawnPosition()); cont->SetRotation(entity->GetRespawnRotation()); @@ -1121,7 +1122,7 @@ void GameMessages::SendPlayerReachedRespawnCheckpoint(Entity* entity, const NiPo bitStream.Write(position.y); bitStream.Write(position.z); - auto con = static_cast<ControllablePhysicsComponent*>(entity->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); + auto con = static_cast<ControllablePhysicsComponent*>(entity->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (con) { auto rot = con->GetRotation(); bitStream.Write(rot.x); @@ -1256,7 +1257,7 @@ void GameMessages::SendVendorStatusUpdate(Entity* entity, const SystemAddress& s CBITSTREAM; CMSGHEADER; - VendorComponent* vendor = static_cast<VendorComponent*>(entity->GetComponent(COMPONENT_TYPE_VENDOR)); + VendorComponent* vendor = static_cast<VendorComponent*>(entity->GetComponent(eReplicaComponentType::VENDOR)); if (!vendor) return; std::map<LOT, int> vendorItems = vendor->GetInventory(); @@ -1378,7 +1379,7 @@ void GameMessages::SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, i CBITSTREAM; CMSGHEADER; - InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; Item* itemStack = inv->FindItemById(iObjID); @@ -1682,7 +1683,7 @@ void GameMessages::HandleActivityStateChangeRequest(RakNet::BitStream* inStream, Game::logger->Log("Activity State Change", "%s [%i, %i] from %i to %i", GeneralUtils::UTF16ToWTF8(stringValue).c_str(), value1, value2, entity->GetLOT(), assosiate != nullptr ? assosiate->GetLOT() : 0); - std::vector<Entity*> scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SHOOTING_GALLERY); + std::vector<Entity*> scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::SHOOTING_GALLERY); for (Entity* scriptEntity : scriptedActs) { scriptEntity->OnActivityStateChangeRequest(objectID, value1, value2, stringValue); } @@ -2211,24 +2212,24 @@ void GameMessages::HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* Game::logger->Log("HandleQueryPropertyData", "Entity (%i) requesting data", entity->GetLOT()); /* - auto entites = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_PROPERTY_VENDOR); + auto entites = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::PROPERTY_VENDOR); entity = entites[0]; */ - auto* propertyVendorComponent = static_cast<PropertyVendorComponent*>(entity->GetComponent(COMPONENT_TYPE_PROPERTY_VENDOR)); + auto* propertyVendorComponent = static_cast<PropertyVendorComponent*>(entity->GetComponent(eReplicaComponentType::PROPERTY_VENDOR)); if (propertyVendorComponent != nullptr) { propertyVendorComponent->OnQueryPropertyData(entity, sysAddr); } /* - entites = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_PROPERTY_MANAGEMENT); + entites = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::PROPERTY_MANAGEMENT); entity = entites[0]; */ - auto* propertyManagerComponent = static_cast<PropertyManagementComponent*>(entity->GetComponent(COMPONENT_TYPE_PROPERTY_MANAGEMENT)); + auto* propertyManagerComponent = static_cast<PropertyManagementComponent*>(entity->GetComponent(eReplicaComponentType::PROPERTY_MANAGEMENT)); if (propertyManagerComponent != nullptr) { propertyManagerComponent->OnQueryPropertyData(entity, sysAddr); @@ -2272,7 +2273,7 @@ void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entit } void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - if (!entity->HasComponent(COMPONENT_TYPE_PROPERTY_MANAGEMENT)) { + if (!entity->HasComponent(eReplicaComponentType::PROPERTY_MANAGEMENT)) { return; } @@ -2901,7 +2902,7 @@ void GameMessages::HandleCinematicUpdate(RakNet::BitStream* inStream, Entity* en inStream->Read<int32_t>(waypoint); } - std::vector<Entity*> scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); + std::vector<Entity*> scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::SCRIPT); for (Entity* scriptEntity : scriptedActs) { scriptEntity->OnCinematicUpdate(scriptEntity, entity, event, pathName, pathTime, overallTime, waypoint); } @@ -3868,7 +3869,7 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* racingControlComponent->HandleMessageBoxResponse(userEntity, GeneralUtils::UTF16ToWTF8(identifier)); } - for (auto* shootingGallery : EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SHOOTING_GALLERY)) { + for (auto* shootingGallery : EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::SHOOTING_GALLERY)) { shootingGallery->OnMessageBoxResponse(userEntity, iButton, identifier, userData); } } @@ -4665,7 +4666,7 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti Entity* player = EntityManager::Instance()->GetEntity(user->GetLoggedInChar()); if (!player) return; - auto* propertyVendorComponent = static_cast<PropertyVendorComponent*>(entity->GetComponent(COMPONENT_TYPE_PROPERTY_VENDOR)); + auto* propertyVendorComponent = static_cast<PropertyVendorComponent*>(entity->GetComponent(eReplicaComponentType::PROPERTY_VENDOR)); if (propertyVendorComponent != nullptr) { propertyVendorComponent->OnBuyFromVendor(player, bConfirmed, item, count); @@ -4675,16 +4676,16 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti const auto isCommendationVendor = entity->GetLOT() == 13806; - VendorComponent* vend = static_cast<VendorComponent*>(entity->GetComponent(COMPONENT_TYPE_VENDOR)); + VendorComponent* vend = static_cast<VendorComponent*>(entity->GetComponent(eReplicaComponentType::VENDOR)); if (!vend && !isCommendationVendor) return; - InventoryComponent* inv = static_cast<InventoryComponent*>(player->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(player->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); CDItemComponentTable* itemComponentTable = CDClientManager::Instance()->GetTable<CDItemComponentTable>("ItemComponent"); - int itemCompID = compRegistryTable->GetByIDAndType(item, COMPONENT_TYPE_ITEM); + int itemCompID = compRegistryTable->GetByIDAndType(item, eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); Character* character = player->GetCharacter(); @@ -4764,10 +4765,10 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit if (!player) return; Character* character = player->GetCharacter(); if (!character) return; - InventoryComponent* inv = static_cast<InventoryComponent*>(player->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(player->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; - VendorComponent* vend = static_cast<VendorComponent*>(entity->GetComponent(COMPONENT_TYPE_VENDOR)); + VendorComponent* vend = static_cast<VendorComponent*>(entity->GetComponent(eReplicaComponentType::VENDOR)); if (!vend) return; Item* item = inv->FindItemById(iObjID); @@ -4776,7 +4777,7 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); CDItemComponentTable* itemComponentTable = CDClientManager::Instance()->GetTable<CDItemComponentTable>("ItemComponent"); - int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), COMPONENT_TYPE_ITEM); + int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM); 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 @@ -4814,10 +4815,10 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* if (!player) return; Character* character = player->GetCharacter(); if (!character) return; - InventoryComponent* inv = static_cast<InventoryComponent*>(player->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(player->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; - VendorComponent* vend = static_cast<VendorComponent*>(entity->GetComponent(COMPONENT_TYPE_VENDOR)); + VendorComponent* vend = static_cast<VendorComponent*>(entity->GetComponent(eReplicaComponentType::VENDOR)); if (!vend) return; Item* item = inv->FindItemById(iObjID); @@ -4826,7 +4827,7 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); CDItemComponentTable* itemComponentTable = CDClientManager::Instance()->GetTable<CDItemComponentTable>("ItemComponent"); - int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), COMPONENT_TYPE_ITEM); + int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); float sellScalar = vend->GetSellScalar(); @@ -4968,7 +4969,7 @@ void GameMessages::HandleRebuildCancel(RakNet::BitStream* inStream, Entity* enti inStream->Read(bEarlyRelease); inStream->Read(userID); - RebuildComponent* rebComp = static_cast<RebuildComponent*>(entity->GetComponent(COMPONENT_TYPE_REBUILD)); + RebuildComponent* rebComp = static_cast<RebuildComponent*>(entity->GetComponent(eReplicaComponentType::QUICK_BUILD)); if (!rebComp) return; rebComp->CancelRebuild(EntityManager::Instance()->GetEntity(userID), eFailReason::REASON_CANCELED_EARLY); @@ -5001,7 +5002,7 @@ void GameMessages::HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, if (bIsMultiInteractUse) { if (multiInteractType == 0) { - auto* missionOfferComponent = static_cast<MissionOfferComponent*>(interactedObject->GetComponent(COMPONENT_TYPE_MISSION_OFFER)); + auto* missionOfferComponent = static_cast<MissionOfferComponent*>(interactedObject->GetComponent(eReplicaComponentType::MISSION_OFFER)); if (missionOfferComponent != nullptr) { missionOfferComponent->OfferMissions(entity, multiInteractID); @@ -5014,7 +5015,7 @@ void GameMessages::HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, } //Perform use task if possible: - auto missionComponent = static_cast<MissionComponent*>(entity->GetComponent(COMPONENT_TYPE_MISSION)); + auto missionComponent = static_cast<MissionComponent*>(entity->GetComponent(eReplicaComponentType::MISSION)); if (missionComponent == nullptr) return; @@ -5050,7 +5051,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) } } else { Game::logger->LogDebug("GameMessages", "Target ID is empty, using backup"); - const auto scriptedEntities = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT); + const auto scriptedEntities = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::SCRIPT); const auto& referencePoint = entity->GetPosition(); @@ -5080,7 +5081,7 @@ void GameMessages::HandleModularBuildConvertModel(RakNet::BitStream* inStream, E if (!user) return; Entity* character = EntityManager::Instance()->GetEntity(user->GetLoggedInChar()); if (!character) return; - InventoryComponent* inv = static_cast<InventoryComponent*>(character->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(character->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; auto* item = inv->FindItemById(modelID); @@ -5123,7 +5124,7 @@ void GameMessages::HandleRespondToMission(RakNet::BitStream* inStream, Entity* e inStream->Read(isDefaultReward); if (isDefaultReward) inStream->Read(reward); - MissionComponent* missionComponent = static_cast<MissionComponent*>(entity->GetComponent(COMPONENT_TYPE_MISSION)); + MissionComponent* missionComponent = static_cast<MissionComponent*>(entity->GetComponent(eReplicaComponentType::MISSION)); if (!missionComponent) { Game::logger->Log("GameMessages", "Unable to get mission component for entity %llu to handle RespondToMission", playerID); return; @@ -5166,7 +5167,7 @@ void GameMessages::HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* en } // Get the player's mission component - MissionComponent* missionComponent = static_cast<MissionComponent*>(player->GetComponent(COMPONENT_TYPE_MISSION)); + MissionComponent* missionComponent = static_cast<MissionComponent*>(player->GetComponent(eReplicaComponentType::MISSION)); if (!missionComponent) { Game::logger->Log("GameMessages", "Unable to get mission component for entity %llu to handle MissionDialogueOK", player->GetObjectID()); return; @@ -5190,7 +5191,7 @@ void GameMessages::HandleRequestLinkedMission(RakNet::BitStream* inStream, Entit auto* player = EntityManager::Instance()->GetEntity(playerId); - auto* missionOfferComponent = static_cast<MissionOfferComponent*>(entity->GetComponent(COMPONENT_TYPE_MISSION_OFFER)); + auto* missionOfferComponent = static_cast<MissionOfferComponent*>(entity->GetComponent(eReplicaComponentType::MISSION_OFFER)); if (missionOfferComponent != nullptr) { missionOfferComponent->OfferMissions(player, 0); @@ -5204,7 +5205,7 @@ void GameMessages::HandleHasBeenCollected(RakNet::BitStream* inStream, Entity* e Entity* player = EntityManager::Instance()->GetEntity(playerID); if (!player || !entity || entity->GetCollectibleID() == 0) return; - MissionComponent* missionComponent = static_cast<MissionComponent*>(player->GetComponent(COMPONENT_TYPE_MISSION)); + MissionComponent* missionComponent = static_cast<MissionComponent*>(player->GetComponent(eReplicaComponentType::MISSION)); if (missionComponent) { missionComponent->Progress(eMissionTaskType::COLLECTION, entity->GetLOT(), entity->GetObjectID()); } @@ -5307,7 +5308,7 @@ void GameMessages::HandleEquipItem(RakNet::BitStream* inStream, Entity* entity) inStream->Read(immediate); //twice? inStream->Read(objectID); - InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; Item* item = inv->FindItemById(objectID); @@ -5326,7 +5327,7 @@ void GameMessages::HandleUnequipItem(RakNet::BitStream* inStream, Entity* entity inStream->Read(immediate); inStream->Read(objectID); - InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; auto* item = inv->FindItemById(objectID); @@ -5401,7 +5402,7 @@ void GameMessages::HandleRemoveItemFromInventory(RakNet::BitStream* inStream, En inStream->Read(iTradeIDIsDefault); if (iTradeIDIsDefault) inStream->Read(iTradeID); - InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; auto* item = inv->FindItemById(iObjID); @@ -5444,7 +5445,7 @@ void GameMessages::HandleMoveItemInInventory(RakNet::BitStream* inStream, Entity inStream->Read(responseCode); inStream->Read(slot); - InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; auto* item = inv->FindItemById(iObjID); @@ -5521,7 +5522,7 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* if (!user) return; Entity* character = EntityManager::Instance()->GetEntity(user->GetLoggedInChar()); if (!character) return; - InventoryComponent* inv = static_cast<InventoryComponent*>(character->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(character->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; Game::logger->Log("GameMessages", "Build finished"); @@ -5586,7 +5587,7 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* } } - ScriptComponent* script = static_cast<ScriptComponent*>(entity->GetComponent(COMPONENT_TYPE_SCRIPT)); + ScriptComponent* script = static_cast<ScriptComponent*>(entity->GetComponent(eReplicaComponentType::SCRIPT)); for (CppScripts::Script* script : CppScripts::GetEntityScripts(entity)) { script->OnModularBuildExit(entity, character, count >= 3, modList); @@ -5609,7 +5610,7 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti if (!user) return; Entity* character = EntityManager::Instance()->GetEntity(user->GetLoggedInChar()); if (!character) return; - InventoryComponent* inv = static_cast<InventoryComponent*>(character->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(character->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; /** @@ -5660,7 +5661,7 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti */ if (PropertyManagementComponent::Instance() != nullptr) { - const auto& buildAreas = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_BUILD_BORDER); + const auto& buildAreas = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::BUILD_BORDER); const auto& entities = EntityManager::Instance()->GetEntitiesInGroup("PropertyPlaque"); @@ -5727,7 +5728,7 @@ void GameMessages::HandleModularBuildMoveAndEquip(RakNet::BitStream* inStream, E inStream->Read(templateID); - InventoryComponent* inv = static_cast<InventoryComponent*>(character->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(character->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; auto* item = inv->FindItemByLot(templateID, TEMP_MODELS); @@ -5768,7 +5769,7 @@ void GameMessages::HandleResurrect(RakNet::BitStream* inStream, Entity* entity) script->OnPlayerResurrected(zoneControl, entity); } - std::vector<Entity*> scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY); + std::vector<Entity*> scriptedActs = EntityManager::Instance()->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)) { @@ -5779,13 +5780,13 @@ void GameMessages::HandleResurrect(RakNet::BitStream* inStream, Entity* entity) } void GameMessages::HandlePushEquippedItemsState(RakNet::BitStream* inStream, Entity* entity) { - InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; inv->PushEquippedItems(); } void GameMessages::HandlePopEquippedItemsState(RakNet::BitStream* inStream, Entity* entity) { - InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inv = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; inv->PopEquippedItems(); EntityManager::Instance()->SerializeEntity(entity); // so it updates on client side @@ -5797,7 +5798,7 @@ void GameMessages::HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* inStream->Read(itemConsumed); - auto* inventory = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + auto* inventory = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (inventory == nullptr) { return; @@ -5811,7 +5812,7 @@ void GameMessages::HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* item->Consume(); - auto* missions = static_cast<MissionComponent*>(entity->GetComponent(COMPONENT_TYPE_MISSION)); + auto* missions = static_cast<MissionComponent*>(entity->GetComponent(eReplicaComponentType::MISSION)); if (missions != nullptr) { missions->Progress(eMissionTaskType::USE_ITEM, itemLot); } @@ -5823,7 +5824,7 @@ void GameMessages::HandleUseNonEquipmentItem(RakNet::BitStream* inStream, Entity inStream->Read(itemConsumed); - auto* inv = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + auto* inv = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; @@ -5854,11 +5855,11 @@ void GameMessages::HandleMatchRequest(RakNet::BitStream* inStream, Entity* entit inStream->Read(type); inStream->Read(value); - std::vector<Entity*> scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY); + std::vector<Entity*> scriptedActs = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); if (type == 0) { // join if (value != 0) { for (Entity* scriptedAct : scriptedActs) { - ScriptedActivityComponent* comp = static_cast<ScriptedActivityComponent*>(scriptedAct->GetComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY)); + ScriptedActivityComponent* comp = static_cast<ScriptedActivityComponent*>(scriptedAct->GetComponent(eReplicaComponentType::SCRIPTED_ACTIVITY)); if (!comp) continue; if (comp->GetActivityID() == value) { comp->PlayerJoin(entity); @@ -5869,7 +5870,7 @@ void GameMessages::HandleMatchRequest(RakNet::BitStream* inStream, Entity* entit } } else if (type == 1) { // ready/unready for (Entity* scriptedAct : scriptedActs) { - ScriptedActivityComponent* comp = static_cast<ScriptedActivityComponent*>(scriptedAct->GetComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY)); + ScriptedActivityComponent* comp = static_cast<ScriptedActivityComponent*>(scriptedAct->GetComponent(eReplicaComponentType::SCRIPTED_ACTIVITY)); if (!comp) continue; if (comp->PlayerIsInQueue(entity)) { comp->PlayerReady(entity, value); @@ -5987,7 +5988,7 @@ void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) void GameMessages::HandleClientRailMovementReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); + const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::RAIL_ACTIVATOR); for (const auto* possibleRail : possibleRails) { const auto* rail = possibleRail->GetComponent<RailActivatorComponent>(); if (rail != nullptr) { @@ -5999,7 +6000,7 @@ GameMessages::HandleClientRailMovementReady(RakNet::BitStream* inStream, Entity* void GameMessages::HandleCancelRailMovement(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { const auto immediate = inStream->ReadBit(); - const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); + const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::RAIL_ACTIVATOR); for (const auto* possibleRail : possibleRails) { auto* rail = possibleRail->GetComponent<RailActivatorComponent>(); if (rail != nullptr) { @@ -6023,7 +6024,7 @@ void GameMessages::HandlePlayerRailArrivedNotification(RakNet::BitStream* inStre int32_t waypointNumber; inStream->Read(waypointNumber); - const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_RAIL_ACTIVATOR); + const auto possibleRails = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::RAIL_ACTIVATOR); for (auto* possibleRail : possibleRails) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(possibleRail)) { script->OnPlayerRailArrived(possibleRail, entity, pathName, waypointNumber); diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index 69a643ae..b35281eb 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -4,6 +4,7 @@ #include "Item.h" #include "InventoryComponent.h" #include "eItemType.h" +#include "eReplicaComponentType.h" std::vector<LOT> Inventory::m_GameMasterRestrictedItems = { 1727, // GM Only - JetPack @@ -277,7 +278,7 @@ const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { auto* itemComponents = CDClientManager::Instance()->GetTable<CDItemComponentTable>("ItemComponent"); - const auto componentId = registry->GetByIDAndType(lot, COMPONENT_TYPE_ITEM); + const auto componentId = registry->GetByIDAndType(lot, eReplicaComponentType::ITEM); if (componentId == 0) { Game::logger->Log("Inventory", "Failed to find item component for (%i)!", lot); @@ -293,7 +294,7 @@ const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { bool Inventory::IsValidItem(const LOT lot) { auto* registry = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - const auto componentId = registry->GetByIDAndType(lot, COMPONENT_TYPE_ITEM); + const auto componentId = registry->GetByIDAndType(lot, eReplicaComponentType::ITEM); return componentId != 0; } diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 2a054ae8..0df1723d 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -16,6 +16,7 @@ #include "AssetManager.h" #include "InventoryComponent.h" #include "Loot.h" +#include "eReplicaComponentType.h" Item::Item(const LWOOBJID id, const LOT lot, Inventory* inventory, const uint32_t slot, const uint32_t count, const bool bound, const std::vector<LDFBaseData*>& config, const LWOOBJID parent, LWOOBJID subKey, eLootSourceType lootSourceType) { if (!Inventory::IsValidItem(lot)) { @@ -297,7 +298,7 @@ void Item::UseNonEquip(Item* item) { auto inventory = item->GetInventory(); if (inventory && inventory->GetType() == eInventoryType::ITEMS) { auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, COMPONENT_TYPE_PACKAGE); + const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::PACKAGE); if (packageComponentId == 0) return; @@ -381,7 +382,7 @@ void Item::Disassemble(const eInventoryType inventoryType) { void Item::DisassembleModel() { auto* table = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - const auto componentId = table->GetByIDAndType(GetLot(), COMPONENT_TYPE_RENDER); + const auto componentId = table->GetByIDAndType(GetLot(), eReplicaComponentType::RENDER); auto query = CDClientDatabase::CreatePreppedStmt( "SELECT render_asset FROM RenderComponent WHERE id = ?;"); diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index 0e1acdac..68384652 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -23,7 +23,7 @@ #include "eMissionState.h" #include "eMissionTaskType.h" #include "eMissionLockState.h" - +#include "eReplicaComponentType.h" Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { m_MissionComponent = missionComponent; @@ -370,7 +370,7 @@ void Mission::CheckCompletion() { void Mission::Catchup() { auto* entity = GetAssociate(); - auto* inventory = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + auto* inventory = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); for (auto* task : m_Tasks) { const auto type = task->GetType(); diff --git a/dGame/dMission/MissionTask.cpp b/dGame/dMission/MissionTask.cpp index e339d232..344427c6 100644 --- a/dGame/dMission/MissionTask.cpp +++ b/dGame/dMission/MissionTask.cpp @@ -14,6 +14,7 @@ #include "InventoryComponent.h" #include "MissionComponent.h" #include "eMissionTaskType.h" +#include "eReplicaComponentType.h" MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) { this->info = info; @@ -237,7 +238,7 @@ void MissionTask::Progress(int32_t value, LWOOBJID associate, const std::string& break; } - activity = static_cast<ScriptedActivityComponent*>(entity->GetComponent(COMPONENT_TYPE_REBUILD)); + activity = static_cast<ScriptedActivityComponent*>(entity->GetComponent(eReplicaComponentType::QUICK_BUILD)); if (activity == nullptr) { break; } diff --git a/dGame/dUtilities/Loot.cpp b/dGame/dUtilities/Loot.cpp index 44e35a91..415c976c 100644 --- a/dGame/dUtilities/Loot.cpp +++ b/dGame/dUtilities/Loot.cpp @@ -14,7 +14,7 @@ #include "InventoryComponent.h" #include "MissionComponent.h" #include "eMissionState.h" - +#include "eReplicaComponentType.h" LootGenerator::LootGenerator() { CDLootTableTable* lootTableTable = CDClientManager::Instance()->GetTable<CDLootTableTable>("LootTable"); @@ -38,7 +38,7 @@ LootGenerator::LootGenerator() { uniqueItems.erase(std::unique(uniqueItems.begin(), uniqueItems.end()), uniqueItems.end()); for (const uint32_t itemID : uniqueItems) { - uint32_t itemComponentID = componentsRegistryTable->GetByIDAndType(itemID, COMPONENT_TYPE_ITEM); + uint32_t itemComponentID = componentsRegistryTable->GetByIDAndType(itemID, eReplicaComponentType::ITEM); const CDItemComponent& item = itemComponentTable->GetItemComponentByID(itemComponentID); m_ItemRarities.insert({ itemID, item.rarity }); diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index 48f21a5d..9490f748 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -25,6 +25,7 @@ #include "dZoneManager.h" #include "WorldConfig.h" #include "eMissionTaskType.h" +#include "eReplicaComponentType.h" void Mail::SendMail(const Entity* recipient, const std::string& subject, const std::string& body, const LOT attachment, const uint16_t attachmentCount) { @@ -196,7 +197,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd //Inventory::InventoryType itemType; int mailCost = dZoneManager::Instance()->GetWorldConfig()->mailBaseFee; int stackSize = 0; - auto inv = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + auto inv = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); Item* item = nullptr; if (itemID > 0 && attachmentCount > 0 && inv) { @@ -355,7 +356,7 @@ void Mail::HandleAttachmentCollect(RakNet::BitStream* packet, const SystemAddres attachmentCount = res->getInt(2); } - auto inv = static_cast<InventoryComponent*>(player->GetComponent(COMPONENT_TYPE_INVENTORY)); + auto inv = static_cast<InventoryComponent*>(player->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; inv->AddItem(attachmentLOT, attachmentCount, eLootSourceType::LOOT_SOURCE_MAIL); diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 8ae0b441..443ba41d 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -75,6 +75,7 @@ #include "eMissionState.h" #include "TriggerComponent.h" #include "eServerDisconnectIdentifiers.h" +#include "eReplicaComponentType.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { std::string chatCommand; @@ -561,7 +562,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - InventoryComponent* inventory = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inventory = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (inventory) { auto* items = inventory->GetInventory(ITEMS); @@ -611,7 +612,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - auto comp = static_cast<MissionComponent*>(entity->GetComponent(COMPONENT_TYPE_MISSION)); + auto comp = static_cast<MissionComponent*>(entity->GetComponent(eReplicaComponentType::MISSION)); if (comp) comp->AcceptMission(missionID, true); return; } @@ -626,7 +627,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - auto comp = static_cast<MissionComponent*>(entity->GetComponent(COMPONENT_TYPE_MISSION)); + auto comp = static_cast<MissionComponent*>(entity->GetComponent(eReplicaComponentType::MISSION)); if (comp) comp->CompleteMission(missionID, true); return; } @@ -676,7 +677,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - auto* comp = static_cast<MissionComponent*>(entity->GetComponent(COMPONENT_TYPE_MISSION)); + auto* comp = static_cast<MissionComponent*>(entity->GetComponent(eReplicaComponentType::MISSION)); if (comp == nullptr) { return; @@ -753,7 +754,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "getnavmeshheight" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { - auto control = static_cast<ControllablePhysicsComponent*>(entity->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); + auto control = static_cast<ControllablePhysicsComponent*>(entity->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (!control) return; float y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(control->GetPosition()); @@ -770,7 +771,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - InventoryComponent* inventory = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inventory = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); inventory->AddItem(itemLOT, 1, eLootSourceType::LOOT_SOURCE_MODERATION); } else if (args.size() == 2) { @@ -788,7 +789,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - InventoryComponent* inventory = static_cast<InventoryComponent*>(entity->GetComponent(COMPONENT_TYPE_INVENTORY)); + InventoryComponent* inventory = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); inventory->AddItem(itemLOT, count, eLootSourceType::LOOT_SOURCE_MODERATION); } else { @@ -934,7 +935,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "tpall" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { const auto pos = entity->GetPosition(); - const auto characters = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER); + const auto characters = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::CHARACTER); for (auto* character : characters) { GameMessages::SendTeleport(character->GetObjectID(), pos, NiQuaternion(), character->GetSystemAddress()); @@ -1153,7 +1154,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit //------------------------------------------------- if (chatCommand == "buffme" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { - auto dest = static_cast<DestroyableComponent*>(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); + auto dest = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); if (dest) { dest->SetHealth(999); dest->SetMaxHealth(999.0f); @@ -1177,7 +1178,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "buffmed" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { - auto dest = static_cast<DestroyableComponent*>(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); + auto dest = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); if (dest) { dest->SetHealth(9); dest->SetMaxHealth(9.0f); @@ -1191,7 +1192,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "refillstats" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { - auto dest = static_cast<DestroyableComponent*>(entity->GetComponent(COMPONENT_TYPE_DESTROYABLE)); + auto dest = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); if (dest) { dest->SetHealth((int)dest->GetMaxHealth()); dest->SetArmor((int)dest->GetMaxArmor()); @@ -1224,7 +1225,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "spawn" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { - ControllablePhysicsComponent* comp = static_cast<ControllablePhysicsComponent*>(entity->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); + ControllablePhysicsComponent* comp = static_cast<ControllablePhysicsComponent*>(entity->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (!comp) return; uint32_t lot; @@ -1655,18 +1656,18 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "spawnphysicsverts" && entity->GetGMLevel() >= 6) { //Go tell physics to spawn all the vertices: - auto entities = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_PHANTOM_PHYSICS); + auto entities = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::PHANTOM_PHYSICS); for (auto en : entities) { - auto phys = static_cast<PhantomPhysicsComponent*>(en->GetComponent(COMPONENT_TYPE_PHANTOM_PHYSICS)); + auto phys = static_cast<PhantomPhysicsComponent*>(en->GetComponent(eReplicaComponentType::PHANTOM_PHYSICS)); if (phys) phys->SpawnVertices(); } } if (chatCommand == "reportproxphys" && entity->GetGMLevel() >= 6) { - auto entities = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_PROXIMITY_MONITOR); + auto entities = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::PROXIMITY_MONITOR); for (auto en : entities) { - auto phys = static_cast<ProximityMonitorComponent*>(en->GetComponent(COMPONENT_TYPE_PROXIMITY_MONITOR)); + auto phys = static_cast<ProximityMonitorComponent*>(en->GetComponent(eReplicaComponentType::PROXIMITY_MONITOR)); if (phys) { for (auto prox : phys->GetProximitiesData()) { if (!prox.second) continue; @@ -1760,7 +1761,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit Game::config->ReloadConfig(); VanityUtilities::SpawnVanity(); dpWorld::Instance().Reload(); - auto entities = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPTED_ACTIVITY); + auto entities = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); for (auto entity : entities) { auto* scriptedActivityComponent = entity->GetComponent<ScriptedActivityComponent>(); if (!scriptedActivityComponent) continue; @@ -1839,14 +1840,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "inspect" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { Entity* closest = nullptr; - int32_t component; + eReplicaComponentType component; std::u16string ldf; bool isLDF = false; if (!GeneralUtils::TryParse(args[0], component)) { - component = -1; + component = eReplicaComponentType::INVALID; ldf = GeneralUtils::UTF8ToUTF16(args[0]); @@ -1906,7 +1907,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit std::stringstream stream; - stream << "Component [" << std::to_string(id) << "]"; + stream << "Component [" << std::to_string(static_cast<uint32_t>(id)) << "]"; ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(stream.str())); } diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index 9e8153cc..100efac5 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -32,7 +32,7 @@ #include "CharacterComponent.h" #include "Database.h" #include "dMessageIdentifiers.h" - +#include "eReplicaComponentType.h" void ClientPackets::HandleChatMessage(const SystemAddress& sysAddr, Packet* packet) { User* user = UserManager::Instance()->GetUser(sysAddr); @@ -89,7 +89,7 @@ void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Pac Entity* entity = EntityManager::Instance()->GetEntity(user->GetLastUsedChar()->GetObjectID()); if (!entity) return; - ControllablePhysicsComponent* comp = static_cast<ControllablePhysicsComponent*>(entity->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); + ControllablePhysicsComponent* comp = static_cast<ControllablePhysicsComponent*>(entity->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (!comp) return; /* diff --git a/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp b/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp index ef81c888..c584f05b 100644 --- a/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp +++ b/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp @@ -13,6 +13,7 @@ #include "GameMessages.h" #include "SkillComponent.h" +#include "eReplicaComponentType.h" #include <vector> @@ -27,9 +28,9 @@ void BossSpiderQueenEnemyServer::OnStartup(Entity* self) { //self:SetStatusImmunity{ StateChangeType = "PUSH", bImmuneToPullToPoint = true, bImmuneToKnockback = true, bImmuneToInterrupt = true } //Get our components: - destroyable = static_cast<DestroyableComponent*>(self->GetComponent(COMPONENT_TYPE_DESTROYABLE)); - controllable = static_cast<ControllablePhysicsComponent*>(self->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); - combat = static_cast<BaseCombatAIComponent*>(self->GetComponent(COMPONENT_TYPE_BASE_COMBAT_AI)); + destroyable = static_cast<DestroyableComponent*>(self->GetComponent(eReplicaComponentType::DESTROYABLE)); + controllable = static_cast<ControllablePhysicsComponent*>(self->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); + combat = static_cast<BaseCombatAIComponent*>(self->GetComponent(eReplicaComponentType::BASE_COMBAT_AI)); if (!destroyable || !controllable) return; @@ -397,7 +398,7 @@ void BossSpiderQueenEnemyServer::RapidFireShooterManager(Entity* self) { void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) { /* - const auto targets = EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER); + const auto targets = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::CHARACTER); */ const auto targets = self->GetTargetsInPhantom(); diff --git a/dScripts/02_server/Enemy/General/BaseEnemyMech.cpp b/dScripts/02_server/Enemy/General/BaseEnemyMech.cpp index 8c200566..ce42585c 100644 --- a/dScripts/02_server/Enemy/General/BaseEnemyMech.cpp +++ b/dScripts/02_server/Enemy/General/BaseEnemyMech.cpp @@ -6,6 +6,7 @@ #include "EntityInfo.h" #include "GeneralUtils.h" #include "DestroyableComponent.h" +#include "eReplicaComponentType.h" void BaseEnemyMech::OnStartup(Entity* self) { auto* destroyableComponent = self->GetComponent<DestroyableComponent>(); @@ -15,7 +16,7 @@ void BaseEnemyMech::OnStartup(Entity* self) { } void BaseEnemyMech::OnDie(Entity* self, Entity* killer) { - ControllablePhysicsComponent* controlPhys = static_cast<ControllablePhysicsComponent*>(self->GetComponent(COMPONENT_TYPE_CONTROLLABLE_PHYSICS)); + ControllablePhysicsComponent* controlPhys = static_cast<ControllablePhysicsComponent*>(self->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (!controlPhys) return; NiPoint3 newLoc = { controlPhys->GetPosition().x, dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(controlPhys->GetPosition()), controlPhys->GetPosition().z }; diff --git a/dScripts/02_server/Map/AG/AgCagedBricksServer.cpp b/dScripts/02_server/Map/AG/AgCagedBricksServer.cpp index 6d1360de..3c400e5d 100644 --- a/dScripts/02_server/Map/AG/AgCagedBricksServer.cpp +++ b/dScripts/02_server/Map/AG/AgCagedBricksServer.cpp @@ -3,6 +3,7 @@ #include "GameMessages.h" #include "Character.h" #include "EntityManager.h" +#include "eReplicaComponentType.h" void AgCagedBricksServer::OnUse(Entity* self, Entity* user) { //Tell the client to spawn the baby spiderling: @@ -19,7 +20,7 @@ void AgCagedBricksServer::OnUse(Entity* self, Entity* user) { character->SetPlayerFlag(74, true); //Remove the maelstrom cube: - auto inv = static_cast<InventoryComponent*>(user->GetComponent(COMPONENT_TYPE_INVENTORY)); + auto inv = static_cast<InventoryComponent*>(user->GetComponent(eReplicaComponentType::INVENTORY)); if (inv) { inv->RemoveItem(14553, 1); diff --git a/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp b/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp index 9efae1ca..c09000be 100644 --- a/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp +++ b/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp @@ -5,10 +5,11 @@ #include "EntityManager.h" #include "AgMonumentLaserServer.h" #include "EntityManager.h" +#include "eReplicaComponentType.h" void AgLaserSensorServer::OnStartup(Entity* self) { - PhantomPhysicsComponent* physComp = static_cast<PhantomPhysicsComponent*>(self->GetComponent(COMPONENT_TYPE_PHANTOM_PHYSICS)); + PhantomPhysicsComponent* physComp = static_cast<PhantomPhysicsComponent*>(self->GetComponent(eReplicaComponentType::PHANTOM_PHYSICS)); physComp->SetPhysicsEffectActive(true); physComp->SetEffectType(2); // repulse (prolly should make definitions of these are in Entity.cpp) physComp->SetDirectionalMultiplier(static_cast<float>(m_RepelForce)); @@ -25,7 +26,7 @@ void AgLaserSensorServer::OnCollisionPhantom(Entity* self, Entity* target) { Entity* laser = nullptr; - for (auto script : EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_SCRIPT)) { + for (auto script : EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::SCRIPT)) { AgMonumentLaserServer* hasLaser = (AgMonumentLaserServer*)script; diff --git a/dScripts/02_server/Map/AG/NpcNjAssistantServer.cpp b/dScripts/02_server/Map/AG/NpcNjAssistantServer.cpp index 183765d7..8ee2e988 100644 --- a/dScripts/02_server/Map/AG/NpcNjAssistantServer.cpp +++ b/dScripts/02_server/Map/AG/NpcNjAssistantServer.cpp @@ -4,6 +4,7 @@ #include "MissionComponent.h" #include "Item.h" #include "eMissionState.h" +#include "eReplicaComponentType.h" void NpcNjAssistantServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { if (missionID != mailMission) return; @@ -11,7 +12,7 @@ void NpcNjAssistantServer::OnMissionDialogueOK(Entity* self, Entity* target, int if (missionState == eMissionState::COMPLETE || missionState == eMissionState::READY_TO_COMPLETE) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"switch", 0, 0, LWOOBJID_EMPTY, "", target->GetSystemAddress()); - auto* inv = static_cast<InventoryComponent*>(target->GetComponent(COMPONENT_TYPE_INVENTORY)); + auto* inv = static_cast<InventoryComponent*>(target->GetComponent(eReplicaComponentType::INVENTORY)); // If we are ready to complete our missions, we take the kit from you: if (inv && missionState == eMissionState::READY_TO_COMPLETE) { @@ -22,7 +23,7 @@ void NpcNjAssistantServer::OnMissionDialogueOK(Entity* self, Entity* target, int } } } else if (missionState == eMissionState::AVAILABLE) { - auto* missionComponent = static_cast<MissionComponent*>(target->GetComponent(COMPONENT_TYPE_MISSION)); + auto* missionComponent = static_cast<MissionComponent*>(target->GetComponent(eReplicaComponentType::MISSION)); missionComponent->CompleteMission(mailAchievement, true); } } diff --git a/dScripts/02_server/Map/AG/RemoveRentalGear.cpp b/dScripts/02_server/Map/AG/RemoveRentalGear.cpp index 6e7bd4de..18177e57 100644 --- a/dScripts/02_server/Map/AG/RemoveRentalGear.cpp +++ b/dScripts/02_server/Map/AG/RemoveRentalGear.cpp @@ -3,6 +3,7 @@ #include "Item.h" #include "eMissionState.h" #include "Character.h" +#include "eReplicaComponentType.h" /* -------------------------------------------------------------- @@ -21,7 +22,7 @@ void RemoveRentalGear::OnMissionDialogueOK(Entity* self, Entity* target, int mis if (missionID != defaultMission && missionID != 313) return; if (missionState == eMissionState::COMPLETE || missionState == eMissionState::READY_TO_COMPLETE) { - auto inv = static_cast<InventoryComponent*>(target->GetComponent(COMPONENT_TYPE_INVENTORY)); + auto inv = static_cast<InventoryComponent*>(target->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; //remove the inventory items diff --git a/dScripts/02_server/Map/FV/FvCandle.cpp b/dScripts/02_server/Map/FV/FvCandle.cpp index efd717ee..0c4344d0 100644 --- a/dScripts/02_server/Map/FV/FvCandle.cpp +++ b/dScripts/02_server/Map/FV/FvCandle.cpp @@ -1,11 +1,12 @@ #include "FvCandle.h" #include "MissionComponent.h" #include "RenderComponent.h" +#include "eReplicaComponentType.h" std::vector<int32_t> FvCandle::m_Missions = { 850, 1431, 1529, 1566, 1603 }; void FvCandle::OnStartup(Entity* self) { - auto* render = static_cast<RenderComponent*>(self->GetComponent(COMPONENT_TYPE_RENDER)); + auto* render = static_cast<RenderComponent*>(self->GetComponent(eReplicaComponentType::RENDER)); if (render == nullptr) return; @@ -22,7 +23,7 @@ void FvCandle::BlowOutCandle(Entity* self, Entity* blower) { if (self->GetBoolean(u"AmHit")) return; - auto* render = static_cast<RenderComponent*>(self->GetComponent(COMPONENT_TYPE_RENDER)); + auto* render = static_cast<RenderComponent*>(self->GetComponent(eReplicaComponentType::RENDER)); if (render == nullptr) return; @@ -46,7 +47,7 @@ void FvCandle::BlowOutCandle(Entity* self, Entity* blower) { void FvCandle::OnTimerDone(Entity* self, std::string timerName) { self->SetBoolean(u"AmHit", false); - auto* render = static_cast<RenderComponent*>(self->GetComponent(COMPONENT_TYPE_RENDER)); + auto* render = static_cast<RenderComponent*>(self->GetComponent(eReplicaComponentType::RENDER)); if (render == nullptr) return; diff --git a/dScripts/02_server/Map/GF/GfTikiTorch.cpp b/dScripts/02_server/Map/GF/GfTikiTorch.cpp index db7ee6b5..22420679 100644 --- a/dScripts/02_server/Map/GF/GfTikiTorch.cpp +++ b/dScripts/02_server/Map/GF/GfTikiTorch.cpp @@ -4,6 +4,7 @@ #include "MissionComponent.h" #include "RenderComponent.h" #include "eMissionTaskType.h" +#include "eReplicaComponentType.h" void GfTikiTorch::OnStartup(Entity* self) { LightTorch(self); @@ -42,7 +43,7 @@ void GfTikiTorch::OnTimerDone(Entity* self, std::string timerName) { } void GfTikiTorch::LightTorch(Entity* self) { - auto* renderComponent = static_cast<RenderComponent*>(self->GetComponent(COMPONENT_TYPE_RENDER)); + auto* renderComponent = static_cast<RenderComponent*>(self->GetComponent(eReplicaComponentType::RENDER)); if (renderComponent == nullptr) return; diff --git a/dScripts/02_server/Map/General/TokenConsoleServer.cpp b/dScripts/02_server/Map/General/TokenConsoleServer.cpp index f21938d1..5212a9b5 100644 --- a/dScripts/02_server/Map/General/TokenConsoleServer.cpp +++ b/dScripts/02_server/Map/General/TokenConsoleServer.cpp @@ -2,11 +2,12 @@ #include "InventoryComponent.h" #include "GameMessages.h" #include "Character.h" +#include "eReplicaComponentType.h" //2021-05-03 - max - added script, omitted some parts related to inheritance in lua which we don't need void TokenConsoleServer::OnUse(Entity* self, Entity* user) { - auto* inv = static_cast<InventoryComponent*>(user->GetComponent(COMPONENT_TYPE_INVENTORY)); + auto* inv = static_cast<InventoryComponent*>(user->GetComponent(eReplicaComponentType::INVENTORY)); //make sure the user has the required amount of infected bricks if (inv && inv->GetLotCount(6194) >= bricksToTake) { diff --git a/dScripts/02_server/Map/General/TouchMissionUpdateServer.cpp b/dScripts/02_server/Map/General/TouchMissionUpdateServer.cpp index 00c1b900..7b2495d0 100644 --- a/dScripts/02_server/Map/General/TouchMissionUpdateServer.cpp +++ b/dScripts/02_server/Map/General/TouchMissionUpdateServer.cpp @@ -4,6 +4,7 @@ #include "GameMessages.h" #include "MissionComponent.h" #include "eMissionState.h" +#include "eReplicaComponentType.h" void TouchMissionUpdateServer::OnStartup(Entity* self) { self->SetProximityRadius(20, "touchCheck"); // Those does not have a collider for some reason? @@ -16,7 +17,7 @@ void TouchMissionUpdateServer::OnCollisionPhantom(Entity* self, Entity* target) return; } - auto* missionComponent = static_cast<MissionComponent*>(target->GetComponent(COMPONENT_TYPE_MISSION)); + auto* missionComponent = static_cast<MissionComponent*>(target->GetComponent(eReplicaComponentType::MISSION)); if (missionComponent == nullptr) { return; diff --git a/dScripts/02_server/Map/Property/AG_Small/EnemySpiderSpawner.cpp b/dScripts/02_server/Map/Property/AG_Small/EnemySpiderSpawner.cpp index 695bd92f..0d4f568e 100644 --- a/dScripts/02_server/Map/Property/AG_Small/EnemySpiderSpawner.cpp +++ b/dScripts/02_server/Map/Property/AG_Small/EnemySpiderSpawner.cpp @@ -3,6 +3,7 @@ #include "EntityManager.h" #include "EntityInfo.h" #include "DestroyableComponent.h" +#include "eReplicaComponentType.h" //---------------------------------------------- //--Initiate egg hatching on call @@ -14,7 +15,7 @@ void EnemySpiderSpawner::OnFireEventServerSide(Entity* self, Entity* sender, std GameMessages::SendPlayFXEffect(self->GetObjectID(), 2856, u"maelstrom", "test", LWOOBJID_EMPTY, 1.0f, 1.0f, true); // Make indestructible - auto dest = static_cast<DestroyableComponent*>(self->GetComponent(COMPONENT_TYPE_DESTROYABLE)); + auto dest = static_cast<DestroyableComponent*>(self->GetComponent(eReplicaComponentType::DESTROYABLE)); if (dest) { dest->SetFaction(-1); } diff --git a/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp b/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp index b6172df1..215e22c2 100644 --- a/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp +++ b/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp @@ -7,6 +7,7 @@ #include "RenderComponent.h" #include "MissionComponent.h" #include "eMissionState.h" +#include "eReplicaComponentType.h" void ZoneAgProperty::SetGameVariables(Entity* self) { self->SetVar<std::string>(GuardGroup, "Guard"); @@ -256,7 +257,7 @@ void ZoneAgProperty::BaseTimerDone(Entity* self, const std::string& timerName) { DeactivateSpawner(self->GetVar<std::string>(SpiderScreamSpawner)); DestroySpawner(self->GetVar<std::string>(SpiderScreamSpawner)); - for (auto* player : EntityManager::Instance()->GetEntitiesByComponent(COMPONENT_TYPE_CHARACTER)) { + for (auto* player : EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::CHARACTER)) { GameMessages::SendStop2DAmbientSound(player, true, GUIDMaelstrom); GameMessages::SendPlay2DAmbientSound(player, GUIDPeaceful); } diff --git a/dScripts/02_server/Map/SS/SsModularBuildServer.cpp b/dScripts/02_server/Map/SS/SsModularBuildServer.cpp index 82c802cc..dfb29168 100644 --- a/dScripts/02_server/Map/SS/SsModularBuildServer.cpp +++ b/dScripts/02_server/Map/SS/SsModularBuildServer.cpp @@ -1,12 +1,13 @@ #include "SsModularBuildServer.h" #include "MissionComponent.h" #include "eMissionState.h" +#include "eReplicaComponentType.h" void SsModularBuildServer::OnModularBuildExit(Entity* self, Entity* player, bool bCompleted, std::vector<LOT> modules) { int missionNum = 1732; if (bCompleted) { - MissionComponent* mission = static_cast<MissionComponent*>(player->GetComponent(COMPONENT_TYPE_MISSION)); + MissionComponent* mission = static_cast<MissionComponent*>(player->GetComponent(eReplicaComponentType::MISSION)); Mission* rocketMission = mission->GetMission(missionNum); if (rocketMission->GetMissionState() == eMissionState::ACTIVE) { diff --git a/dScripts/NtFactionSpyServer.cpp b/dScripts/NtFactionSpyServer.cpp index 684e6a0e..dc62855a 100644 --- a/dScripts/NtFactionSpyServer.cpp +++ b/dScripts/NtFactionSpyServer.cpp @@ -5,6 +5,7 @@ #include "GameMessages.h" #include "MissionComponent.h" #include "eMissionState.h" +#include "eReplicaComponentType.h" void NtFactionSpyServer::OnStartup(Entity* self) { SetVariables(self); @@ -13,7 +14,7 @@ void NtFactionSpyServer::OnStartup(Entity* self) { auto* proximityMonitor = self->GetComponent<ProximityMonitorComponent>(); if (proximityMonitor == nullptr) { proximityMonitor = new ProximityMonitorComponent(self, -1, -1); - self->AddComponent(COMPONENT_TYPE_PROXIMITY_MONITOR, proximityMonitor); + self->AddComponent(eReplicaComponentType::PROXIMITY_MONITOR, proximityMonitor); } proximityMonitor->SetProximityRadius(self->GetVar<float_t>(m_SpyProximityVariable), m_ProximityName); diff --git a/dScripts/ScriptComponent.h b/dScripts/ScriptComponent.h index 94226627..77dff5bf 100644 --- a/dScripts/ScriptComponent.h +++ b/dScripts/ScriptComponent.h @@ -9,6 +9,7 @@ #include "CppScripts.h" #include "Component.h" #include <string> +#include "eReplicaComponentType.h" class Entity; @@ -18,7 +19,7 @@ class Entity; */ class ScriptComponent : public Component { public: - static const uint32_t ComponentType = COMPONENT_TYPE_SCRIPT; + static const eReplicaComponentType ComponentType = eReplicaComponentType::SCRIPT; ScriptComponent(Entity* parent, std::string scriptName, bool serialized, bool client = false); ~ScriptComponent() override; diff --git a/dScripts/ai/AG/AgFans.cpp b/dScripts/ai/AG/AgFans.cpp index 27d3b940..e05fe68d 100644 --- a/dScripts/ai/AG/AgFans.cpp +++ b/dScripts/ai/AG/AgFans.cpp @@ -4,6 +4,7 @@ #include "GameMessages.h" #include "PhantomPhysicsComponent.h" #include "RenderComponent.h" +#include "eReplicaComponentType.h" void AgFans::OnStartup(Entity* self) { self->SetVar<bool>(u"alive", true); @@ -11,7 +12,7 @@ void AgFans::OnStartup(Entity* self) { ToggleFX(self, false); - auto* renderComponent = static_cast<RenderComponent*>(self->GetComponent(COMPONENT_TYPE_RENDER)); + auto* renderComponent = static_cast<RenderComponent*>(self->GetComponent(eReplicaComponentType::RENDER)); if (renderComponent == nullptr) { return; @@ -24,7 +25,7 @@ void AgFans::ToggleFX(Entity* self, bool hit) { std::string fanGroup = self->GetGroups()[0]; std::vector<Entity*> fanVolumes = EntityManager::Instance()->GetEntitiesInGroup(fanGroup); - auto* renderComponent = static_cast<RenderComponent*>(self->GetComponent(COMPONENT_TYPE_RENDER)); + auto* renderComponent = static_cast<RenderComponent*>(self->GetComponent(eReplicaComponentType::RENDER)); if (renderComponent == nullptr) { return; @@ -39,7 +40,7 @@ void AgFans::ToggleFX(Entity* self, bool hit) { self->SetVar<bool>(u"on", false); for (Entity* volume : fanVolumes) { - PhantomPhysicsComponent* volumePhys = static_cast<PhantomPhysicsComponent*>(volume->GetComponent(COMPONENT_TYPE_PHANTOM_PHYSICS)); + PhantomPhysicsComponent* volumePhys = static_cast<PhantomPhysicsComponent*>(volume->GetComponent(eReplicaComponentType::PHANTOM_PHYSICS)); if (!volumePhys) continue; volumePhys->SetPhysicsEffectActive(false); EntityManager::Instance()->SerializeEntity(volume); @@ -55,7 +56,7 @@ void AgFans::ToggleFX(Entity* self, bool hit) { self->SetVar<bool>(u"on", true); for (Entity* volume : fanVolumes) { - PhantomPhysicsComponent* volumePhys = static_cast<PhantomPhysicsComponent*>(volume->GetComponent(COMPONENT_TYPE_PHANTOM_PHYSICS)); + PhantomPhysicsComponent* volumePhys = static_cast<PhantomPhysicsComponent*>(volume->GetComponent(eReplicaComponentType::PHANTOM_PHYSICS)); if (!volumePhys) continue; volumePhys->SetPhysicsEffectActive(true); EntityManager::Instance()->SerializeEntity(volume); diff --git a/dScripts/ai/AG/AgImagSmashable.cpp b/dScripts/ai/AG/AgImagSmashable.cpp index 195f7b9a..5e8331b1 100644 --- a/dScripts/ai/AG/AgImagSmashable.cpp +++ b/dScripts/ai/AG/AgImagSmashable.cpp @@ -4,12 +4,13 @@ #include "GameMessages.h" #include "EntityInfo.h" #include "DestroyableComponent.h" +#include "eReplicaComponentType.h" void AgImagSmashable::OnDie(Entity* self, Entity* killer) { bool maxImagGreaterThanZero = false; if (killer) { - DestroyableComponent* dest = static_cast<DestroyableComponent*>(killer->GetComponent(COMPONENT_TYPE_DESTROYABLE)); + DestroyableComponent* dest = static_cast<DestroyableComponent*>(killer->GetComponent(eReplicaComponentType::DESTROYABLE)); if (dest) { maxImagGreaterThanZero = dest->GetMaxImagination() > 0; } diff --git a/dScripts/ai/AG/AgJetEffectServer.cpp b/dScripts/ai/AG/AgJetEffectServer.cpp index 8c7eca3b..9546bc4d 100644 --- a/dScripts/ai/AG/AgJetEffectServer.cpp +++ b/dScripts/ai/AG/AgJetEffectServer.cpp @@ -2,6 +2,7 @@ #include "GameMessages.h" #include "EntityManager.h" #include "SkillComponent.h" +#include "eReplicaComponentType.h" void AgJetEffectServer::OnUse(Entity* self, Entity* user) { if (inUse) { @@ -86,12 +87,12 @@ void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) { auto* mortar = entities[selected]; - Game::logger->Log("AgJetEffectServer", "Mortar (%i) (&d)", mortar->GetLOT(), mortar->HasComponent(COMPONENT_TYPE_SKILL)); + Game::logger->Log("AgJetEffectServer", "Mortar (%i) (&d)", mortar->GetLOT(), mortar->HasComponent(eReplicaComponentType::SKILL)); mortar->SetOwnerOverride(builder); SkillComponent* skillComponent; - if (!mortar->TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) { + if (!mortar->TryGetComponent(eReplicaComponentType::SKILL, skillComponent)) { return; } diff --git a/dScripts/ai/AG/AgStromlingProperty.cpp b/dScripts/ai/AG/AgStromlingProperty.cpp index 36d8d378..9a9ae33b 100644 --- a/dScripts/ai/AG/AgStromlingProperty.cpp +++ b/dScripts/ai/AG/AgStromlingProperty.cpp @@ -1,5 +1,6 @@ #include "AgStromlingProperty.h" #include "MovementAIComponent.h" +#include "eReplicaComponentType.h" void AgStromlingProperty::OnStartup(Entity* self) { auto movementInfo = MovementAIInfo{ @@ -12,5 +13,5 @@ void AgStromlingProperty::OnStartup(Entity* self) { }; auto* movementAIComponent = new MovementAIComponent(self, movementInfo); - self->AddComponent(COMPONENT_TYPE_MOVEMENT_AI, movementAIComponent); + self->AddComponent(eReplicaComponentType::MOVEMENT_AI, movementAIComponent); } diff --git a/dScripts/ai/GF/GfCampfire.cpp b/dScripts/ai/GF/GfCampfire.cpp index 95e29a9a..6a10b39e 100644 --- a/dScripts/ai/GF/GfCampfire.cpp +++ b/dScripts/ai/GF/GfCampfire.cpp @@ -4,13 +4,14 @@ #include "MissionComponent.h" #include "RenderComponent.h" #include "EntityManager.h" +#include "eReplicaComponentType.h" void GfCampfire::OnStartup(Entity* self) { self->SetI32(u"counter", static_cast<int32_t>(0)); self->SetProximityRadius(2.0f, "placeholder"); self->SetBoolean(u"isBurning", true); - auto* render = static_cast<RenderComponent*>(self->GetComponent(COMPONENT_TYPE_RENDER)); + auto* render = static_cast<RenderComponent*>(self->GetComponent(eReplicaComponentType::RENDER)); if (render == nullptr) return; @@ -20,7 +21,7 @@ void GfCampfire::OnStartup(Entity* self) { void GfCampfire::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { if (args == "physicsReady") { - auto* render = static_cast<RenderComponent*>(self->GetComponent(COMPONENT_TYPE_RENDER)); + auto* render = static_cast<RenderComponent*>(self->GetComponent(eReplicaComponentType::RENDER)); render->PlayEffect(295, u"running", "Burn"); } diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp index 2948ae3d..703c6bbd 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp @@ -14,6 +14,7 @@ #include "Loot.h" #include "InventoryComponent.h" #include "eMissionTaskType.h" +#include "eReplicaComponentType.h" void SGCannon::OnStartup(Entity* self) { Game::logger->Log("SGCannon", "OnStartup"); @@ -295,7 +296,7 @@ void SGCannon::OnActivityTimerDone(Entity* self, const std::string& name) { if (true) { auto* movementAI = new MovementAIComponent(enemy, {}); - enemy->AddComponent(COMPONENT_TYPE_MOVEMENT_AI, movementAI); + enemy->AddComponent(eReplicaComponentType::MOVEMENT_AI, movementAI); movementAI->SetSpeed(toSpawn.initialSpeed); movementAI->SetCurrentSpeed(toSpawn.initialSpeed); diff --git a/dScripts/ai/NP/NpcNpSpacemanBob.cpp b/dScripts/ai/NP/NpcNpSpacemanBob.cpp index d242d08f..2195f4b4 100644 --- a/dScripts/ai/NP/NpcNpSpacemanBob.cpp +++ b/dScripts/ai/NP/NpcNpSpacemanBob.cpp @@ -2,12 +2,13 @@ #include "DestroyableComponent.h" #include "MissionComponent.h" #include "eMissionState.h" +#include "eReplicaComponentType.h" void NpcNpSpacemanBob::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { if (missionState == eMissionState::READY_TO_COMPLETE && missionID == 173) { - DestroyableComponent* destroyable = static_cast<DestroyableComponent*>(target->GetComponent(COMPONENT_TYPE_DESTROYABLE)); + DestroyableComponent* destroyable = static_cast<DestroyableComponent*>(target->GetComponent(eReplicaComponentType::DESTROYABLE)); destroyable->SetImagination(6); - MissionComponent* mission = static_cast<MissionComponent*>(target->GetComponent(COMPONENT_TYPE_MISSION)); + MissionComponent* mission = static_cast<MissionComponent*>(target->GetComponent(eReplicaComponentType::MISSION)); mission->CompleteMission(664); } diff --git a/dScripts/ai/NS/NsGetFactionMissionServer.cpp b/dScripts/ai/NS/NsGetFactionMissionServer.cpp index d759e3ad..cfecb249 100644 --- a/dScripts/ai/NS/NsGetFactionMissionServer.cpp +++ b/dScripts/ai/NS/NsGetFactionMissionServer.cpp @@ -2,6 +2,7 @@ #include "GameMessages.h" #include "MissionComponent.h" #include "Character.h" +#include "eReplicaComponentType.h" void NsGetFactionMissionServer::OnRespondToMission(Entity* self, int missionID, Entity* player, int reward) { if (missionID != 474) return; @@ -44,7 +45,7 @@ void NsGetFactionMissionServer::OnRespondToMission(Entity* self, int missionID, player->GetCharacter()->SetPlayerFlag(flagID, true); } - MissionComponent* mis = static_cast<MissionComponent*>(player->GetComponent(COMPONENT_TYPE_MISSION)); + MissionComponent* mis = static_cast<MissionComponent*>(player->GetComponent(eReplicaComponentType::MISSION)); for (int mission : factionMissions) { mis->AcceptMission(mission); diff --git a/dScripts/ai/NS/NsModularBuild.cpp b/dScripts/ai/NS/NsModularBuild.cpp index 2e00aa19..1922eb17 100644 --- a/dScripts/ai/NS/NsModularBuild.cpp +++ b/dScripts/ai/NS/NsModularBuild.cpp @@ -1,10 +1,11 @@ #include "NsModularBuild.h" #include "MissionComponent.h" #include "eMissionState.h" +#include "eReplicaComponentType.h" void NsModularBuild::OnModularBuildExit(Entity* self, Entity* player, bool bCompleted, std::vector<LOT> modules) { if (bCompleted) { - MissionComponent* mission = static_cast<MissionComponent*>(player->GetComponent(COMPONENT_TYPE_MISSION)); + MissionComponent* mission = static_cast<MissionComponent*>(player->GetComponent(eReplicaComponentType::MISSION)); if (mission->GetMissionState(m_MissionNum) == eMissionState::ACTIVE) { for (LOT mod : modules) { diff --git a/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.cpp b/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.cpp index c6cab294..43ae9e89 100644 --- a/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.cpp +++ b/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.cpp @@ -4,6 +4,7 @@ #include "SkillComponent.h" #include "DestroyableComponent.h" #include "EntityManager.h" +#include "eReplicaComponentType.h" void SpecialImaginePowerupSpawner::OnStartup(Entity* self) { self->SetProximityRadius(1.5f, "powerupEnter"); @@ -26,7 +27,7 @@ void SpecialImaginePowerupSpawner::OnProximityUpdate(Entity* self, Entity* enter GameMessages::SendPlayFXEffect(self, -1, u"pickup", "", LWOOBJID_EMPTY, 1, 1, true); SkillComponent* skillComponent; - if (!self->TryGetComponent(COMPONENT_TYPE_SKILL, skillComponent)) { + if (!self->TryGetComponent(eReplicaComponentType::SKILL, skillComponent)) { return; } @@ -35,7 +36,7 @@ void SpecialImaginePowerupSpawner::OnProximityUpdate(Entity* self, Entity* enter skillComponent->CalculateBehavior(13, 20, source); DestroyableComponent* destroyableComponent; - if (!self->TryGetComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent)) { + if (!self->TryGetComponent(eReplicaComponentType::DESTROYABLE, destroyableComponent)) { return; } diff --git a/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp index 5448a4c2..7399456d 100644 --- a/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp +++ b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp @@ -4,6 +4,7 @@ #include "BitStream.h" #include "DestroyableComponent.h" #include "Entity.h" +#include "eReplicaComponentType.h" class DestroyableTest : public GameDependenciesTest { protected: @@ -15,7 +16,7 @@ protected: SetUpDependencies(); baseEntity = new Entity(15, GameDependenciesTest::info); destroyableComponent = new DestroyableComponent(baseEntity); - baseEntity->AddComponent(COMPONENT_TYPE_DESTROYABLE, destroyableComponent); + baseEntity->AddComponent(eReplicaComponentType::DESTROYABLE, destroyableComponent); // Initialize some values to be not default destroyableComponent->SetMaxHealth(12345.0f); destroyableComponent->SetHealth(23); @@ -317,7 +318,7 @@ TEST_F(DestroyableTest, DestroyableComponentFactionTest) { TEST_F(DestroyableTest, DestroyableComponentValiditiyTest) { auto* enemyEntity = new Entity(19, info); auto* enemyDestroyableComponent = new DestroyableComponent(enemyEntity); - enemyEntity->AddComponent(COMPONENT_TYPE_DESTROYABLE, enemyDestroyableComponent); + enemyEntity->AddComponent(eReplicaComponentType::DESTROYABLE, enemyDestroyableComponent); enemyDestroyableComponent->AddFactionNoLookup(16); destroyableComponent->AddEnemyFaction(16); EXPECT_TRUE(destroyableComponent->IsEnemy(enemyEntity)); From 9d65d871d0b0096804523be35c098feeea7c9bb0 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sun, 5 Mar 2023 13:11:32 -0600 Subject: [PATCH 261/322] fix compatibility with nexus dash (#1011) * add some more utility to the masterserver -a command fix compatability with nexus dash * cleanup code some more user logger where it makes sense only take in password if it is needed log a better error if account cannot be created * update message * return before success statement if catching error --- dMasterServer/MasterServer.cpp | 88 +++++++++++++++++++-------- migrations/dlu/8_foreign_play_key.sql | 1 + 2 files changed, 64 insertions(+), 25 deletions(-) create mode 100644 migrations/dlu/8_foreign_play_key.sql diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 77571e22..bcf1a540 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -212,43 +212,81 @@ int main(int argc, char** argv) { std::cout << "Enter a username: "; std::cin >> username; + std::unique_ptr<sql::PreparedStatement> userLookupStatement(Database::CreatePreppedStmt("SELECT id FROM accounts WHERE name=? LIMIT 1;")); + userLookupStatement->setString(1, username.c_str()); + std::unique_ptr<sql::ResultSet> res(userLookupStatement->executeQuery()); + if (res->rowsCount() > 0) { + Game::logger->Log("MasterServer", "Account with name \"%s\" already exists", username.c_str()); + std::cout << "Do you want to change the password of that account? [y/n]?"; + std::string prompt = ""; + std::cin >> prompt; + if (prompt == "y" || prompt == "yes"){ + uint32_t accountId = 0; + res->next(); + accountId = res->getUInt(1); + if (accountId == 0) return EXIT_FAILURE; + + //Read the password from the console without echoing it. + #ifdef __linux__ + //This function is obsolete, but it only meant to be used by the + //sysadmin to create their first account. + password = getpass("Enter a password: "); + #else + std::cout << "Enter a password: "; + std::cin >> password; + #endif + + // Regenerate hash based on new password + char salt[BCRYPT_HASHSIZE]; + char hash[BCRYPT_HASHSIZE]; + int32_t bcryptState = ::bcrypt_gensalt(12, salt); + assert(bcryptState == 0); + bcryptState = ::bcrypt_hashpw(password.c_str(), salt, hash); + assert(bcryptState == 0); + + std::unique_ptr<sql::PreparedStatement> userUpdateStatement(Database::CreatePreppedStmt("UPDATE accounts SET password = ? WHERE id = ?;")); + userUpdateStatement->setString(1, std::string(hash, BCRYPT_HASHSIZE).c_str()); + userUpdateStatement->setUInt(2, accountId); + userUpdateStatement->execute(); + + Game::logger->Log("MasterServer", "Account \"%s\" password updated successfully!", username.c_str()); + } else { + Game::logger->Log("MasterServer", "Account \"%s\" was not updated.", username.c_str()); + } + return EXIT_SUCCESS; + } + //Read the password from the console without echoing it. -#ifdef __linux__ - //This function is obsolete, but it only meant to be used by the - //sysadmin to create their first account. - password = getpass("Enter a password: "); -#else - std::cout << "Enter a password: "; - std::cin >> password; -#endif + #ifdef __linux__ + //This function is obsolete, but it only meant to be used by the + //sysadmin to create their first account. + password = getpass("Enter a password: "); + #else + std::cout << "Enter a password: "; + std::cin >> password; + #endif //Generate new hash for bcrypt - char salt[BCRYPT_HASHSIZE]; char hash[BCRYPT_HASHSIZE]; - int32_t bcryptState = ::bcrypt_gensalt(12, salt); - assert(bcryptState == 0); - bcryptState = ::bcrypt_hashpw(password.c_str(), salt, hash); - assert(bcryptState == 0); //Create account + try { + std::unique_ptr<sql::PreparedStatement> statement(Database::CreatePreppedStmt("INSERT INTO accounts (name, password, gm_level) VALUES (?, ?, ?);")); + statement->setString(1, username.c_str()); + statement->setString(2, std::string(hash, BCRYPT_HASHSIZE).c_str()); + statement->setInt(3, 9); + statement->execute(); + } catch(sql::SQLException& e) { + Game::logger->Log("MasterServer", "A SQL error occurred!:\n %s", e.what()); + return EXIT_FAILURE; + } - auto* statement = Database::CreatePreppedStmt("INSERT INTO accounts (name, password, ""gm_level) VALUES (?, ?, ?);"); - statement->setString(1, username.c_str()); - statement->setString(2, std::string(hash, BCRYPT_HASHSIZE).c_str()); - statement->setInt(3, 9); - - statement->execute(); - - delete statement; - - std::cout << "Account created successfully!\n"; - - + Game::logger->Log("MasterServer", "Account created successfully!"); return EXIT_SUCCESS; } diff --git a/migrations/dlu/8_foreign_play_key.sql b/migrations/dlu/8_foreign_play_key.sql new file mode 100644 index 00000000..6f171bb5 --- /dev/null +++ b/migrations/dlu/8_foreign_play_key.sql @@ -0,0 +1 @@ +ALTER TABLE accounts MODIFY play_key_id INT DEFAULT NULL; From 49047a267b9f78af4a814b262ae0908dd5828b6a Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 5 Mar 2023 12:34:59 -0800 Subject: [PATCH 262/322] Fix racing imagination loss on death (#1006) * Fix imagination on death * Fix defaults * Fix visuals --- dCommon/dEnums/dMessageIdentifiers.h | 2 + dGame/dComponents/RacingControlComponent.cpp | 81 ++++++++++++-------- dGame/dGameMessages/GameMessages.cpp | 30 ++++++++ dGame/dGameMessages/GameMessages.h | 6 +- 4 files changed, 85 insertions(+), 34 deletions(-) diff --git a/dCommon/dEnums/dMessageIdentifiers.h b/dCommon/dEnums/dMessageIdentifiers.h index c1afc497..e11f9e7f 100644 --- a/dCommon/dEnums/dMessageIdentifiers.h +++ b/dCommon/dEnums/dMessageIdentifiers.h @@ -546,6 +546,8 @@ enum GAME_MSG : unsigned short { GAME_MSG_REMOVE_RUN_SPEED_MODIFIER = 1506, GAME_MSG_UPDATE_PROPERTY_PERFORMANCE_COST = 1547, GAME_MSG_PROPERTY_ENTRANCE_BEGIN = 1553, + GAME_MSG_SET_RESURRECT_RESTORE_VALUES = 1591, + GAME_MSG_VEHICLE_STOP_BOOST = 1617, GAME_MSG_REMOVE_BUFF = 1648, GAME_MSG_REQUEST_MOVE_ITEM_BETWEEN_INVENTORY_TYPES = 1666, GAME_MSG_RESPONSE_MOVE_ITEM_BETWEEN_INVENTORY_TYPES = 1667, diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 4b27ac0f..fe4f1faf 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -306,30 +306,58 @@ void RacingControlComponent::OnRequestDie(Entity* player) { auto* vehicle = EntityManager::Instance()->GetEntity(racingPlayer.vehicleID); - if (vehicle == nullptr) { - return; - } + if (!vehicle) return; if (!racingPlayer.noSmashOnReload) { racingPlayer.smashedTimes++; + GameMessages::SendDie(vehicle, vehicle->GetObjectID(), LWOOBJID_EMPTY, true, + VIOLENT, u"", 0, 0, 90.0f, false, true, 0); + + auto* destroyableComponent = vehicle->GetComponent<DestroyableComponent>(); + uint32_t respawnImagination = 0; + // Reset imagination to half its current value, rounded up to the nearest value divisible by 10, as it was done in live. + // Do not actually change the value yet. Do that on respawn. + if (destroyableComponent) { + respawnImagination = static_cast<int32_t>(ceil(destroyableComponent->GetImagination() / 2.0f / 10.0f)) * 10.0f; + GameMessages::SendSetResurrectRestoreValues(vehicle, -1, -1, respawnImagination); + } + + // Respawn the player in 2 seconds, as was done in live. Not sure if this value is in a setting somewhere else... + vehicle->AddCallbackTimer(2.0f, [=]() { + if (!vehicle || !this->m_Parent) return; + GameMessages::SendRacingResetPlayerToLastReset( + m_Parent->GetObjectID(), racingPlayer.playerID, + UNASSIGNED_SYSTEM_ADDRESS); + + GameMessages::SendVehicleStopBoost(vehicle, player->GetSystemAddress(), true); + + GameMessages::SendRacingSetPlayerResetInfo( + m_Parent->GetObjectID(), racingPlayer.lap, + racingPlayer.respawnIndex, player->GetObjectID(), + racingPlayer.respawnPosition, racingPlayer.respawnIndex + 1, + UNASSIGNED_SYSTEM_ADDRESS); + + GameMessages::SendResurrect(vehicle); + auto* destroyableComponent = vehicle->GetComponent<DestroyableComponent>(); + // Reset imagination to half its current value, rounded up to the nearest value divisible by 10, as it was done in live. + if (destroyableComponent) destroyableComponent->SetImagination(respawnImagination); + EntityManager::Instance()->SerializeEntity(vehicle); + }); + + auto* characterComponent = player->GetComponent<CharacterComponent>(); + if (characterComponent != nullptr) { + characterComponent->UpdatePlayerStatistic(RacingTimesWrecked); + } + } else { + GameMessages::SendRacingSetPlayerResetInfo( + m_Parent->GetObjectID(), racingPlayer.lap, + racingPlayer.respawnIndex, player->GetObjectID(), + racingPlayer.respawnPosition, racingPlayer.respawnIndex + 1, + UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendRacingResetPlayerToLastReset( + m_Parent->GetObjectID(), racingPlayer.playerID, + UNASSIGNED_SYSTEM_ADDRESS); } - - // Reset player to last checkpoint - GameMessages::SendRacingSetPlayerResetInfo( - m_Parent->GetObjectID(), racingPlayer.lap, - racingPlayer.respawnIndex, player->GetObjectID(), - racingPlayer.respawnPosition, racingPlayer.respawnIndex + 1, - UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendRacingResetPlayerToLastReset( - m_Parent->GetObjectID(), racingPlayer.playerID, - UNASSIGNED_SYSTEM_ADDRESS); - - auto* characterComponent = player->GetComponent<CharacterComponent>(); - if (characterComponent != nullptr) { - characterComponent->UpdatePlayerStatistic(RacingTimesWrecked); - } - - return; } } @@ -348,19 +376,6 @@ void RacingControlComponent::OnRacingPlayerInfoResetFinished(Entity* player) { return; } - if (!racingPlayer.noSmashOnReload) { - GameMessages::SendDie(vehicle, LWOOBJID_EMPTY, LWOOBJID_EMPTY, true, - VIOLENT, u"", 0, 0, 0, true, false, 0); - - GameMessages::SendVehicleUnlockInput(racingPlayer.vehicleID, false, - UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendVehicleSetWheelLockState( - racingPlayer.vehicleID, false, false, - UNASSIGNED_SYSTEM_ADDRESS); - - GameMessages::SendResurrect(vehicle); - } - racingPlayer.noSmashOnReload = false; return; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 9dcd2d74..c8860283 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -4396,6 +4396,36 @@ void GameMessages::SendRacingResetPlayerToLastReset(LWOOBJID objectId, LWOOBJID SEND_PACKET; } +void GameMessages::SendVehicleStopBoost(Entity* targetEntity, const SystemAddress& playerSysAddr, bool affectPassive) { + CBITSTREAM; + CMSGHEADER; + + bitStream.Write(targetEntity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_VEHICLE_STOP_BOOST); + + bitStream.Write(affectPassive); + + SEND_PACKET_BROADCAST; +} + +void GameMessages::SendSetResurrectRestoreValues(Entity* targetEntity, int32_t armorRestore, int32_t healthRestore, int32_t imaginationRestore) { + CBITSTREAM; + CMSGHEADER; + + bitStream.Write(targetEntity->GetObjectID()); + bitStream.Write(GAME_MSG::GAME_MSG_SET_RESURRECT_RESTORE_VALUES); + + bitStream.Write(armorRestore != -1); + if (armorRestore != -1) bitStream.Write(armorRestore); + + bitStream.Write(healthRestore != -1); + if (healthRestore != -1) bitStream.Write(healthRestore); + + bitStream.Write(imaginationRestore != -1); + if (imaginationRestore != -1) bitStream.Write(imaginationRestore); + + SEND_PACKET_BROADCAST; +} void GameMessages::SendNotifyRacingClient(LWOOBJID objectId, int32_t eventType, int32_t param1, LWOOBJID paramObj, std::u16string paramStr, LWOOBJID singleClient, const SystemAddress& sysAddr) { CBITSTREAM; diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 0675ae76..5d199995 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -31,7 +31,8 @@ namespace GameMessages { void SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptRespawn, const SystemAddress& systemAddress); void SendInvalidZoneTransferList(Entity* entity, const SystemAddress& sysAddr, const std::u16string& feedbackURL, const std::u16string& invalidMapTransferList, bool feedbackOnExit, bool feedbackOnInvalidTransfer); void SendKnockback(const LWOOBJID& objectID, const LWOOBJID& caster, const LWOOBJID& originator, int knockBackTimeMS, const NiPoint3& vector); - + // https://lcdruniverse.org/lu_packets/lu_packets/world/gm/client/struct.VehicleStopBoost.html + void SendVehicleStopBoost(Entity* targetEntity, const SystemAddress& playerSysAddr, bool affectPassive); void SendStartArrangingWithItem( Entity* entity, const SystemAddress& sysAddr, @@ -125,6 +126,9 @@ namespace GameMessages { void HandleUnUseModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void SendStartCelebrationEffect(Entity* entity, const SystemAddress& sysAddr, int celebrationID); + // https://lcdruniverse.org/lu_packets/lu_packets/world/gm/client/struct.SetResurrectRestoreValues.html + void SendSetResurrectRestoreValues(Entity* targetEntity, int32_t armorRestore, int32_t healthRestore, int32_t imaginationRestore); + /** * Sends a message to an Entity to smash itself, but not delete or destroy itself from the world * From ff0336793cfd051adf70a4cdddadb5894c6b374f Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Wed, 8 Mar 2023 07:31:45 -0600 Subject: [PATCH 263/322] add stun immunity script (#1015) several summons use this script to be immune to stuns --- dScripts/CppScripts.cpp | 3 +++ dScripts/EquipmentScripts/CMakeLists.txt | 3 ++- dScripts/EquipmentScripts/StunImmunity.cpp | 19 +++++++++++++++++++ dScripts/EquipmentScripts/StunImmunity.h | 6 ++++++ 4 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 dScripts/EquipmentScripts/StunImmunity.cpp create mode 100644 dScripts/EquipmentScripts/StunImmunity.h diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 745a74ae..24b30dee 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -281,6 +281,7 @@ #include "GemPack.h" #include "ShardArmor.h" #include "TeslaPack.h" +#include "StunImmunity.h" // Survival scripts #include "AgSurvivalStromling.h" @@ -846,6 +847,8 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new ShardArmor(); else if (scriptName == "scripts\\equipmenttriggers\\coilbackpack.lua") script = new TeslaPack(); + else if (scriptName == "scripts\\EquipmentScripts\\stunImmunity.lua") + script = new StunImmunity(); // FB else if (scriptName == "scripts\\ai\\NS\\WH\\L_ROCKHYDRANT_BROKEN.lua") diff --git a/dScripts/EquipmentScripts/CMakeLists.txt b/dScripts/EquipmentScripts/CMakeLists.txt index c870ae31..696be03d 100644 --- a/dScripts/EquipmentScripts/CMakeLists.txt +++ b/dScripts/EquipmentScripts/CMakeLists.txt @@ -1,4 +1,4 @@ -set(DSCRIPTS_SOURCES_EQUIPMENTSCRIPTS +set(DSCRIPTS_SOURCES_EQUIPMENTSCRIPTS "Sunflower.cpp" "AnvilOfArmor.cpp" "FountainOfImagination.cpp" @@ -6,4 +6,5 @@ set(DSCRIPTS_SOURCES_EQUIPMENTSCRIPTS "PersonalFortress.cpp" "BuccaneerValiantShip.cpp" "FireFirstSkillonStartup.cpp" + "StunImmunity.cpp" PARENT_SCOPE) diff --git a/dScripts/EquipmentScripts/StunImmunity.cpp b/dScripts/EquipmentScripts/StunImmunity.cpp new file mode 100644 index 00000000..f35fe261 --- /dev/null +++ b/dScripts/EquipmentScripts/StunImmunity.cpp @@ -0,0 +1,19 @@ +#include "StunImmunity.h" +#include "DestroyableComponent.h" +#include "ControllablePhysicsComponent.h" + +void StunImmunity::OnStartup(Entity* self) { + auto* destroyableComponent = self->GetComponent<DestroyableComponent>(); + if (destroyableComponent) { + destroyableComponent->SetStatusImmunity( + eStateChangeType::PUSH, false, false, true, true, false, false, false, false, true + ); + } + + auto* controllablePhysicsComponent = self->GetComponent<ControllablePhysicsComponent>(); + if (controllablePhysicsComponent) { + controllablePhysicsComponent->SetStunImmunity( + eStateChangeType::PUSH, self->GetObjectID(), true + ); + } +} diff --git a/dScripts/EquipmentScripts/StunImmunity.h b/dScripts/EquipmentScripts/StunImmunity.h new file mode 100644 index 00000000..0faaf061 --- /dev/null +++ b/dScripts/EquipmentScripts/StunImmunity.h @@ -0,0 +1,6 @@ +#pragma once +#include "CppScripts.h" + +class StunImmunity : public CppScripts::Script { + void OnStartup(Entity* self) override; +}; From a532bc15d8cc2d0bb5b22d3bb6b64f7847d7d66e Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 8 Mar 2023 05:32:03 -0800 Subject: [PATCH 264/322] Fix zombie bug (#1014) --- dGame/dGameMessages/GameMessages.cpp | 22 +++++++++++++++------- dScripts/ai/ACT/ActPlayerDeathTrigger.cpp | 2 ++ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index c8860283..8da37bf5 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -915,15 +915,23 @@ void GameMessages::SendSetJetPackMode(Entity* entity, bool use, bool bypassCheck } void GameMessages::SendResurrect(Entity* entity) { - DestroyableComponent* dest = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); + // Restore the players health after the animation for respawning has finished. + // This is when the health appered back in live, not immediately upon requesting respawn + // Add a half second in case someone decides to cheat and move during the death animation + // and just make sure the client has time to be ready. + constexpr float respawnTime = 3.66700005531311f + 0.5f; + entity->AddCallbackTimer(respawnTime, [=]() { + auto* destroyableComponent = entity->GetComponent<DestroyableComponent>(); - if (dest != nullptr && entity->GetLOT() == 1) { - auto* levelComponent = entity->GetComponent<LevelProgressionComponent>(); - if (levelComponent) { - dest->SetHealth(levelComponent->GetLevel() >= 45 ? 8 : 4); - dest->SetImagination(levelComponent->GetLevel() >= 45 ? 20 : 6); + if (destroyableComponent != nullptr && entity->GetLOT() == 1) { + auto* levelComponent = entity->GetComponent<LevelProgressionComponent>(); + if (levelComponent) { + destroyableComponent->SetHealth(levelComponent->GetLevel() >= 45 ? 8 : 4); + destroyableComponent->SetImagination(levelComponent->GetLevel() >= 45 ? 20 : 6); + } } - } + }); + auto cont = static_cast<ControllablePhysicsComponent*>(entity->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (cont && entity->GetLOT() == 1) { diff --git a/dScripts/ai/ACT/ActPlayerDeathTrigger.cpp b/dScripts/ai/ACT/ActPlayerDeathTrigger.cpp index 28f1ef43..0674f0dd 100644 --- a/dScripts/ai/ACT/ActPlayerDeathTrigger.cpp +++ b/dScripts/ai/ACT/ActPlayerDeathTrigger.cpp @@ -1,5 +1,7 @@ #include "ActPlayerDeathTrigger.h" +#include "Entity.h" + void ActPlayerDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) { if (!target->IsPlayer() || target->GetIsDead() || !target->GetPlayerReadyForUpdates()) return; //Don't kill already dead players or players not ready From 137a5e5c3d5d443883b95bdedde55be2528a6f53 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 12 Mar 2023 07:21:27 -0700 Subject: [PATCH 265/322] Players no longer respawn if they were alive at the end of Battle of Nimbus Station (#1017) --- dScripts/02_server/Map/NS/Waves/ZoneNsWaves.h | 2 ++ dScripts/BaseWavesServer.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/dScripts/02_server/Map/NS/Waves/ZoneNsWaves.h b/dScripts/02_server/Map/NS/Waves/ZoneNsWaves.h index 06503d19..637aceb7 100644 --- a/dScripts/02_server/Map/NS/Waves/ZoneNsWaves.h +++ b/dScripts/02_server/Map/NS/Waves/ZoneNsWaves.h @@ -1,6 +1,8 @@ #pragma once #include "BaseWavesServer.h" +#include "dCommonVars.h" + enum SpawnerName { interior_A, interior_B, diff --git a/dScripts/BaseWavesServer.cpp b/dScripts/BaseWavesServer.cpp index ad40a77d..00340bd0 100644 --- a/dScripts/BaseWavesServer.cpp +++ b/dScripts/BaseWavesServer.cpp @@ -430,7 +430,7 @@ void BaseWavesServer::SpawnWave(Entity* self) { for (const auto& playerID : state.players) { auto* player = EntityManager::Instance()->GetEntity(playerID); - if (player != nullptr) { + if (player && player->GetIsDead()) { player->Resurrect(); } } From f0451616a417c81a5a5acabe411600aca8392988 Mon Sep 17 00:00:00 2001 From: David Markowitz <EmosewaMC@gmail.com> Date: Mon, 13 Mar 2023 03:16:14 -0700 Subject: [PATCH 266/322] Correct incorrect inventory types --- dGame/dInventory/Inventory.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index b35281eb..2970160d 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -242,9 +242,9 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) { return PROPERTY_DEEDS; case eItemType::MODEL: - case eItemType::VEHICLE: + case eItemType::PET_INVENTORY_ITEM: case eItemType::LOOT_MODEL: - case eItemType::LUP_MODEL: + case eItemType::VEHICLE: case eItemType::MOUNT: return MODELS; @@ -261,9 +261,8 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) { case eItemType::CHEST: case eItemType::EGG: case eItemType::PET_FOOD: - case eItemType::PET_INVENTORY_ITEM: case eItemType::PACKAGE: - + case eItemType::LUP_MODEL: return ITEMS; case eItemType::QUEST_OBJECT: From c3723371cf27775e12ed071e263332d1e31762ec Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 14 Mar 2023 04:12:26 -0700 Subject: [PATCH 267/322] Patch divide by zero when advancing waypoints (#1020) --- dGame/dComponents/MovementAIComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index fa54eb6d..1f774690 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -93,7 +93,7 @@ void MovementAIComponent::Update(const float deltaTime) { NiPoint3 velocity = NiPoint3::ZERO; - if (AdvanceWaypointIndex()) // Do we have another waypoint to seek? + if (m_Acceleration > 0 && m_BaseSpeed > 0 && AdvanceWaypointIndex()) // Do we have another waypoint to seek? { m_NextWaypoint = GetCurrentWaypoint(); From 2bcf862f9308215a4184d8565a46bdaeaa65a43c Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 14 Mar 2023 05:50:12 -0700 Subject: [PATCH 268/322] Development inventory command improvements (#1022) --- dGame/dUtilities/SlashCommandHandler.cpp | 50 +++++++++++++++++------- docs/Commands.md | 2 +- 2 files changed, 36 insertions(+), 16 deletions(-) diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 443ba41d..fb9485b8 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -552,21 +552,42 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if ((chatCommand == "setinventorysize" || chatCommand == "setinvsize") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { - if (args.size() != 1) return; - + if ((chatCommand == "setinventorysize" || chatCommand == "setinvsize") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { uint32_t size; - if (!GeneralUtils::TryParse(args[0], size)) { + if (!GeneralUtils::TryParse(args.at(0), size)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid size."); return; } - InventoryComponent* inventory = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); - if (inventory) { - auto* items = inventory->GetInventory(ITEMS); + eInventoryType selectedInventory = eInventoryType::ITEMS; - items->SetSize(size); + // 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)) { + // 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<eInventoryType>(index)))) selectedInventory = static_cast<eInventoryType>(index); + } + } + if (selectedInventory == eInventoryType::INVALID) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid inventory."); + return; + } + + ChatPackets::SendSystemMessage(sysAddr, u"Setting inventory " + + GeneralUtils::ASCIIToUTF16(args.at(1)) + + u" to size " + + GeneralUtils::to_u16string(size)); + } else ChatPackets::SendSystemMessage(sysAddr, u"Setting inventory ITEMS to size " + GeneralUtils::to_u16string(size)); + + auto* inventoryComponent = entity->GetComponent<InventoryComponent>(); + if (inventoryComponent) { + auto* inventory = inventoryComponent->GetInventory(selectedInventory); + + inventory->SetSize(size); } return; @@ -581,10 +602,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto buf = Game::assetManager->GetFileAsBuffer(("macros/" + args[0] + ".scm").c_str()); - if (!buf.m_Success){ + if (!buf.m_Success) { ChatPackets::SendSystemMessage(sysAddr, u"Unknown macro! Is the filename right?"); return; - } + } std::istream infile(&buf); @@ -1331,9 +1352,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit eLootSourceType lootType = eLootSourceType::LOOT_SOURCE_MODERATION; int32_t type; - if (args.size() >= 2 && GeneralUtils::TryParse(args[1], type)) - { - lootType = (eLootSourceType) type; + if (args.size() >= 2 && GeneralUtils::TryParse(args[1], type)) { + lootType = (eLootSourceType)type; } GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), uscore, lootType); @@ -1814,7 +1834,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit eInventoryType inventoryType = eInventoryType::INVALID; if (!GeneralUtils::TryParse(args[0], inventoryType)) { // 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); + std::transform(args[0].begin(), args[0].end(), args[0].begin(), ::toupper); Game::logger->Log("SlashCommandHandler", "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<eInventoryType>(index)))) inventoryType = static_cast<eInventoryType>(index); @@ -1988,7 +2008,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } auto* triggerComponent = closest->GetComponent<TriggerComponent>(); - if (triggerComponent){ + if (triggerComponent) { auto trigger = triggerComponent->GetTrigger(); if (trigger) { ChatPackets::SendSystemMessage(sysAddr, u"Trigger: " + (GeneralUtils::to_u16string(trigger->id))); diff --git a/docs/Commands.md b/docs/Commands.md index 7dc11ff1..a9cd3e7c 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -92,7 +92,7 @@ These commands are primarily for development and testing. The usage of many of t |setcontrolscheme|`/setcontrolscheme <scheme number>`|Sets the character control scheme to the specified number.|8| |setcurrency|`/setcurrency <coins>`|Sets your coins.|8| |setflag|`/setflag (value) <flag id>`|Sets the given inventory or health flag to the given value, where value can be one of "on" or "off". If no value is given, by default this adds the flag to your character (equivalent of calling `/setflag on <flag id>`).|8| -|setinventorysize|`/setinventorysize <size>`|Sets your inventory size to the given size. Alias: `/setinvsize`|8| +|setinventorysize|`/setinventorysize <size> (inventory)`|Sets your inventory size to the given size. If `inventory` is provided, the number or string will be used to set that inventory to the requested size. Alias: `/setinvsize`|8| |setuistate|`/setuistate <ui state>`|Changes UI state.|8| |spawn|`/spawn <id>`|Spawns an object at your location by id.|8| |speedboost|`/speedboost <amount>`|Sets the speed multiplier to the given amount. `/speedboost 1.5` will set the speed multiplier to 1.5x the normal speed.|8| From bd79e9433c27e4c51721e62278efd30de25fb55f Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 17 Mar 2023 02:48:47 -0700 Subject: [PATCH 269/322] Increase Battle of Nimbus Station end of match timer to 60 seconds (#1018) as per the live script This is now the third time this has been updated lol --- dScripts/02_server/Map/NS/Waves/ZoneNsWaves.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dScripts/02_server/Map/NS/Waves/ZoneNsWaves.cpp b/dScripts/02_server/Map/NS/Waves/ZoneNsWaves.cpp index 6f78acb6..184132fe 100644 --- a/dScripts/02_server/Map/NS/Waves/ZoneNsWaves.cpp +++ b/dScripts/02_server/Map/NS/Waves/ZoneNsWaves.cpp @@ -439,7 +439,7 @@ std::vector<Wave> ZoneNsWaves::GetWaves() { 5.0f, (uint32_t)-1, true, - 30, + 60, }, }; } From 7671cc6865222cd8d191a50dc8856b7166d42fde Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 17 Mar 2023 07:36:21 -0700 Subject: [PATCH 270/322] CDClient cleanup and optimization (#1023) * CDClient cleanup and optimization - Use static function to get table name - Remove unused GetName function - Replace above function with a static GetTableName function - Remove verbose comments - Remove verbose initializers - Remove need to specify table name when getting a table by name - Remove unused typedef for mac and linux * Re-add unused table Convert tables to singletons - Convert all CDClient tables to singletons - Move Singleton.h to dCommon - Reduce header clutter in CDClientManager --- {dPhysics => dCommon}/Singleton.h | 0 dCommon/dEnums/dCommonVars.h | 5 - dDatabase/CDClientManager.cpp | 120 +++++++++++------- dDatabase/CDClientManager.h | 96 ++------------ dDatabase/Tables/CDActivitiesTable.cpp | 11 -- dDatabase/Tables/CDActivitiesTable.h | 34 +---- dDatabase/Tables/CDActivityRewardsTable.cpp | 11 -- dDatabase/Tables/CDActivityRewardsTable.h | 33 +---- dDatabase/Tables/CDAnimationsTable.cpp | 11 -- dDatabase/Tables/CDAnimationsTable.h | 33 +---- dDatabase/Tables/CDBehaviorParameterTable.cpp | 9 -- dDatabase/Tables/CDBehaviorParameterTable.h | 23 +--- dDatabase/Tables/CDBehaviorTemplateTable.cpp | 11 -- dDatabase/Tables/CDBehaviorTemplateTable.h | 32 +---- dDatabase/Tables/CDBrickIDTableTable.cpp | 11 -- dDatabase/Tables/CDBrickIDTableTable.h | 26 +--- .../Tables/CDComponentsRegistryTable.cpp | 37 ------ dDatabase/Tables/CDComponentsRegistryTable.h | 23 +--- dDatabase/Tables/CDCurrencyTableTable.cpp | 10 -- dDatabase/Tables/CDCurrencyTableTable.h | 26 +--- .../Tables/CDDestructibleComponentTable.cpp | 10 -- .../Tables/CDDestructibleComponentTable.h | 33 +---- dDatabase/Tables/CDEmoteTable.cpp | 5 - dDatabase/Tables/CDEmoteTable.h | 26 +--- dDatabase/Tables/CDFeatureGatingTable.cpp | 10 -- dDatabase/Tables/CDFeatureGatingTable.h | 32 +---- .../Tables/CDInventoryComponentTable.cpp | 10 -- dDatabase/Tables/CDInventoryComponentTable.h | 33 +---- dDatabase/Tables/CDItemComponentTable.cpp | 8 -- dDatabase/Tables/CDItemComponentTable.h | 25 +--- dDatabase/Tables/CDItemSetSkillsTable.cpp | 11 -- dDatabase/Tables/CDItemSetSkillsTable.h | 34 +---- dDatabase/Tables/CDItemSetsTable.cpp | 10 -- dDatabase/Tables/CDItemSetsTable.h | 33 +---- .../Tables/CDLevelProgressionLookupTable.cpp | 8 -- .../Tables/CDLevelProgressionLookupTable.h | 34 +---- dDatabase/Tables/CDLootMatrixTable.cpp | 10 -- dDatabase/Tables/CDLootMatrixTable.h | 33 +---- dDatabase/Tables/CDLootTableTable.cpp | 8 -- dDatabase/Tables/CDLootTableTable.h | 33 +---- dDatabase/Tables/CDMissionEmailTable.cpp | 8 -- dDatabase/Tables/CDMissionEmailTable.h | 33 +---- .../Tables/CDMissionNPCComponentTable.cpp | 8 -- dDatabase/Tables/CDMissionNPCComponentTable.h | 33 +---- dDatabase/Tables/CDMissionTasksTable.cpp | 10 -- dDatabase/Tables/CDMissionTasksTable.h | 32 +---- dDatabase/Tables/CDMissionsTable.cpp | 10 -- dDatabase/Tables/CDMissionsTable.h | 33 +---- .../Tables/CDMovementAIComponentTable.cpp | 8 -- dDatabase/Tables/CDMovementAIComponentTable.h | 35 +---- dDatabase/Tables/CDObjectSkillsTable.cpp | 9 -- dDatabase/Tables/CDObjectSkillsTable.h | 33 +---- dDatabase/Tables/CDObjectsTable.cpp | 8 -- dDatabase/Tables/CDObjectsTable.h | 27 +--- dDatabase/Tables/CDPackageComponentTable.cpp | 8 -- dDatabase/Tables/CDPackageComponentTable.h | 32 +---- dDatabase/Tables/CDPhysicsComponentTable.cpp | 6 +- dDatabase/Tables/CDPhysicsComponentTable.h | 8 +- .../CDPropertyEntranceComponentTable.cpp | 6 - .../Tables/CDPropertyEntranceComponentTable.h | 24 +--- dDatabase/Tables/CDPropertyTemplateTable.cpp | 6 - dDatabase/Tables/CDPropertyTemplateTable.h | 5 +- .../CDProximityMonitorComponentTable.cpp | 8 -- .../Tables/CDProximityMonitorComponentTable.h | 30 +---- dDatabase/Tables/CDRailActivatorComponent.cpp | 6 - dDatabase/Tables/CDRailActivatorComponent.h | 6 +- dDatabase/Tables/CDRarityTableTable.cpp | 8 -- dDatabase/Tables/CDRarityTableTable.h | 36 +----- dDatabase/Tables/CDRebuildComponentTable.cpp | 8 -- dDatabase/Tables/CDRebuildComponentTable.h | 35 +---- dDatabase/Tables/CDRewardsTable.cpp | 4 - dDatabase/Tables/CDRewardsTable.h | 8 +- dDatabase/Tables/CDScriptComponentTable.cpp | 8 -- dDatabase/Tables/CDScriptComponentTable.h | 30 +---- dDatabase/Tables/CDSkillBehaviorTable.cpp | 16 --- dDatabase/Tables/CDSkillBehaviorTable.h | 30 +---- dDatabase/Tables/CDTable.h | 28 +--- dDatabase/Tables/CDVendorComponentTable.cpp | 8 -- dDatabase/Tables/CDVendorComponentTable.h | 33 +---- dDatabase/Tables/CDZoneTableTable.cpp | 8 -- dDatabase/Tables/CDZoneTableTable.h | 27 +--- dGame/Entity.cpp | 34 +++-- dGame/LeaderboardManager.cpp | 6 +- dGame/dBehaviors/Behavior.cpp | 11 +- dGame/dBehaviors/OverTimeBehavior.cpp | 4 +- dGame/dComponents/BaseCombatAIComponent.cpp | 6 +- dGame/dComponents/BuffComponent.cpp | 3 +- dGame/dComponents/DestroyableComponent.cpp | 6 +- dGame/dComponents/InventoryComponent.cpp | 24 ++-- .../dComponents/LevelProgressionComponent.cpp | 4 +- dGame/dComponents/MissionComponent.cpp | 10 +- dGame/dComponents/MissionOfferComponent.cpp | 6 +- dGame/dComponents/MovementAIComponent.cpp | 7 +- dGame/dComponents/PhantomPhysicsComponent.cpp | 8 +- .../dComponents/PropertyEntranceComponent.cpp | 2 +- dGame/dComponents/RailActivatorComponent.cpp | 3 +- dGame/dComponents/RenderComponent.cpp | 2 +- .../dComponents/ScriptedActivityComponent.cpp | 14 +- dGame/dComponents/ScriptedActivityComponent.h | 2 + dGame/dComponents/SkillComponent.cpp | 4 +- dGame/dComponents/TriggerComponent.cpp | 2 +- dGame/dComponents/VendorComponent.cpp | 13 +- dGame/dGameMessages/GameMessageHandler.cpp | 2 +- dGame/dGameMessages/GameMessages.cpp | 19 +-- dGame/dGameMessages/PropertyDataMessage.cpp | 5 +- dGame/dInventory/Inventory.cpp | 8 +- dGame/dInventory/Inventory.h | 2 +- dGame/dInventory/Item.cpp | 15 ++- dGame/dInventory/ItemSet.cpp | 6 +- dGame/dMission/Mission.cpp | 12 +- dGame/dMission/MissionPrerequisites.cpp | 2 +- dGame/dUtilities/Loot.cpp | 20 +-- dGame/dUtilities/SlashCommandHandler.cpp | 7 +- dMasterServer/InstanceManager.cpp | 4 +- dMasterServer/MasterServer.cpp | 2 +- .../02_server/Map/General/QbEnemyStunner.cpp | 7 +- .../FireFirstSkillonStartup.cpp | 5 +- dWorldServer/WorldServer.cpp | 2 +- dZoneManager/Level.cpp | 2 +- dZoneManager/Zone.cpp | 2 +- dZoneManager/dZoneManager.cpp | 3 +- 121 files changed, 399 insertions(+), 1584 deletions(-) rename {dPhysics => dCommon}/Singleton.h (100%) diff --git a/dPhysics/Singleton.h b/dCommon/Singleton.h similarity index 100% rename from dPhysics/Singleton.h rename to dCommon/Singleton.h diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index da8a2e18..2b7f63dc 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -64,11 +64,6 @@ typedef std::set<LWOOBJID> TSetObjID; const float PI = 3.14159f; -#if defined(__unix) || defined(__APPLE__) -//For Linux: -typedef __int64_t __int64; -#endif - //============ STRUCTS ============== struct LWOSCENEID { diff --git a/dDatabase/CDClientManager.cpp b/dDatabase/CDClientManager.cpp index 4b32e749..eeea686f 100644 --- a/dDatabase/CDClientManager.cpp +++ b/dDatabase/CDClientManager.cpp @@ -1,46 +1,80 @@ #include "CDClientManager.h" +#include "CDActivityRewardsTable.h" +#include "CDAnimationsTable.h" +#include "CDBehaviorParameterTable.h" +#include "CDBehaviorTemplateTable.h" +#include "CDComponentsRegistryTable.h" +#include "CDCurrencyTableTable.h" +#include "CDDestructibleComponentTable.h" +#include "CDEmoteTable.h" +#include "CDInventoryComponentTable.h" +#include "CDItemComponentTable.h" +#include "CDItemSetsTable.h" +#include "CDItemSetSkillsTable.h" +#include "CDLevelProgressionLookupTable.h" +#include "CDLootMatrixTable.h" +#include "CDLootTableTable.h" +#include "CDMissionNPCComponentTable.h" +#include "CDMissionTasksTable.h" +#include "CDMissionsTable.h" +#include "CDObjectSkillsTable.h" +#include "CDObjectsTable.h" +#include "CDPhysicsComponentTable.h" +#include "CDRebuildComponentTable.h" +#include "CDScriptComponentTable.h" +#include "CDSkillBehaviorTable.h" +#include "CDZoneTableTable.h" +#include "CDVendorComponentTable.h" +#include "CDActivitiesTable.h" +#include "CDPackageComponentTable.h" +#include "CDProximityMonitorComponentTable.h" +#include "CDMovementAIComponentTable.h" +#include "CDBrickIDTableTable.h" +#include "CDRarityTableTable.h" +#include "CDMissionEmailTable.h" +#include "CDRewardsTable.h" +#include "CDPropertyEntranceComponentTable.h" +#include "CDPropertyTemplateTable.h" +#include "CDFeatureGatingTable.h" +#include "CDRailActivatorComponent.h" -// Static Variables -CDClientManager* CDClientManager::m_Address = nullptr; - -//! Initializes the manager -void CDClientManager::Initialize(void) { - tables.insert(std::make_pair("ActivityRewards", new CDActivityRewardsTable())); - UNUSED(tables.insert(std::make_pair("Animations", new CDAnimationsTable()))); - tables.insert(std::make_pair("BehaviorParameter", new CDBehaviorParameterTable())); - tables.insert(std::make_pair("BehaviorTemplate", new CDBehaviorTemplateTable())); - tables.insert(std::make_pair("ComponentsRegistry", new CDComponentsRegistryTable())); - tables.insert(std::make_pair("CurrencyTable", new CDCurrencyTableTable())); - tables.insert(std::make_pair("DestructibleComponent", new CDDestructibleComponentTable())); - tables.insert(std::make_pair("EmoteTable", new CDEmoteTableTable())); - tables.insert(std::make_pair("InventoryComponent", new CDInventoryComponentTable())); - tables.insert(std::make_pair("ItemComponent", new CDItemComponentTable())); - tables.insert(std::make_pair("ItemSets", new CDItemSetsTable())); - tables.insert(std::make_pair("ItemSetSkills", new CDItemSetSkillsTable())); - tables.insert(std::make_pair("LevelProgressionLookup", new CDLevelProgressionLookupTable())); - tables.insert(std::make_pair("LootMatrix", new CDLootMatrixTable())); - tables.insert(std::make_pair("LootTable", new CDLootTableTable())); - tables.insert(std::make_pair("MissionNPCComponent", new CDMissionNPCComponentTable())); - tables.insert(std::make_pair("MissionTasks", new CDMissionTasksTable())); - tables.insert(std::make_pair("Missions", new CDMissionsTable())); - tables.insert(std::make_pair("ObjectSkills", new CDObjectSkillsTable())); - tables.insert(std::make_pair("Objects", new CDObjectsTable())); - tables.insert(std::make_pair("PhysicsComponent", new CDPhysicsComponentTable())); - tables.insert(std::make_pair("RebuildComponent", new CDRebuildComponentTable())); - tables.insert(std::make_pair("ScriptComponent", new CDScriptComponentTable())); - tables.insert(std::make_pair("SkillBehavior", new CDSkillBehaviorTable())); - tables.insert(std::make_pair("ZoneTable", new CDZoneTableTable())); - tables.insert(std::make_pair("VendorComponent", new CDVendorComponentTable())); - tables.insert(std::make_pair("Activities", new CDActivitiesTable())); - tables.insert(std::make_pair("PackageComponent", new CDPackageComponentTable())); - tables.insert(std::make_pair("ProximityMonitorComponent", new CDProximityMonitorComponentTable())); - tables.insert(std::make_pair("MovementAIComponent", new CDMovementAIComponentTable())); - tables.insert(std::make_pair("BrickIDTable", new CDBrickIDTableTable())); - tables.insert(std::make_pair("RarityTable", new CDRarityTableTable())); - tables.insert(std::make_pair("MissionEmail", new CDMissionEmailTable())); - tables.insert(std::make_pair("Rewards", new CDRewardsTable())); - tables.insert(std::make_pair("PropertyEntranceComponent", new CDPropertyEntranceComponentTable())); - tables.insert(std::make_pair("PropertyTemplate", new CDPropertyTemplateTable())); - tables.insert(std::make_pair("FeatureGating", new CDFeatureGatingTable())); - tables.insert(std::make_pair("RailActivatorComponent", new CDRailActivatorComponentTable())); +CDClientManager::CDClientManager() { + CDActivityRewardsTable::Instance(); + UNUSED(CDAnimationsTable::Instance()); + CDBehaviorParameterTable::Instance(); + CDBehaviorTemplateTable::Instance(); + CDComponentsRegistryTable::Instance(); + CDCurrencyTableTable::Instance(); + CDDestructibleComponentTable::Instance(); + CDEmoteTableTable::Instance(); + CDInventoryComponentTable::Instance(); + CDItemComponentTable::Instance(); + CDItemSetsTable::Instance(); + CDItemSetSkillsTable::Instance(); + CDLevelProgressionLookupTable::Instance(); + CDLootMatrixTable::Instance(); + CDLootTableTable::Instance(); + CDMissionNPCComponentTable::Instance(); + CDMissionTasksTable::Instance(); + CDMissionsTable::Instance(); + CDObjectSkillsTable::Instance(); + CDObjectsTable::Instance(); + CDPhysicsComponentTable::Instance(); + CDRebuildComponentTable::Instance(); + CDScriptComponentTable::Instance(); + CDSkillBehaviorTable::Instance(); + CDZoneTableTable::Instance(); + CDVendorComponentTable::Instance(); + CDActivitiesTable::Instance(); + CDPackageComponentTable::Instance(); + CDProximityMonitorComponentTable::Instance(); + CDMovementAIComponentTable::Instance(); + CDBrickIDTableTable::Instance(); + CDRarityTableTable::Instance(); + CDMissionEmailTable::Instance(); + CDRewardsTable::Instance(); + CDPropertyEntranceComponentTable::Instance(); + CDPropertyTemplateTable::Instance(); + CDFeatureGatingTable::Instance(); + CDRailActivatorComponentTable::Instance(); } diff --git a/dDatabase/CDClientManager.h b/dDatabase/CDClientManager.h index ea24a373..1754fe99 100644 --- a/dDatabase/CDClientManager.h +++ b/dDatabase/CDClientManager.h @@ -1,96 +1,24 @@ #pragma once -// Custom Classes #include "CDTable.h" -// Tables -#include "CDActivityRewardsTable.h" -#include "CDAnimationsTable.h" -#include "CDBehaviorParameterTable.h" -#include "CDBehaviorTemplateTable.h" -#include "CDComponentsRegistryTable.h" -#include "CDCurrencyTableTable.h" -#include "CDDestructibleComponentTable.h" -#include "CDEmoteTable.h" -#include "CDInventoryComponentTable.h" -#include "CDItemComponentTable.h" -#include "CDItemSetsTable.h" -#include "CDItemSetSkillsTable.h" -#include "CDLevelProgressionLookupTable.h" -#include "CDLootMatrixTable.h" -#include "CDLootTableTable.h" -#include "CDMissionNPCComponentTable.h" -#include "CDMissionTasksTable.h" -#include "CDMissionsTable.h" -#include "CDObjectSkillsTable.h" -#include "CDObjectsTable.h" -#include "CDPhysicsComponentTable.h" -#include "CDRebuildComponentTable.h" -#include "CDScriptComponentTable.h" -#include "CDSkillBehaviorTable.h" -#include "CDZoneTableTable.h" -#include "CDVendorComponentTable.h" -#include "CDActivitiesTable.h" -#include "CDPackageComponentTable.h" -#include "CDProximityMonitorComponentTable.h" -#include "CDMovementAIComponentTable.h" -#include "CDBrickIDTableTable.h" -#include "CDRarityTableTable.h" -#include "CDMissionEmailTable.h" -#include "CDRewardsTable.h" -#include "CDPropertyEntranceComponentTable.h" -#include "CDPropertyTemplateTable.h" -#include "CDFeatureGatingTable.h" -#include "CDRailActivatorComponent.h" +#include "Singleton.h" -// C++ -#include <type_traits> -#include <unordered_map> - -/*! - \file CDClientManager.hpp - \brief A manager for the CDClient tables +/** + * Initialize the CDClient tables so they are all loaded into memory. */ - - //! Manages all data from the CDClient -class CDClientManager { -private: - static CDClientManager* m_Address; //!< The singleton address - - std::unordered_map<std::string, CDTable*> tables; //!< The tables - +class CDClientManager : public Singleton<CDClientManager> { public: + CDClientManager(); - //! The singleton method - static CDClientManager* Instance() { - if (m_Address == 0) { - m_Address = new CDClientManager; - } - - return m_Address; - } - - //! Initializes the manager - void Initialize(void); - - //! Fetches a CDClient table - /*! - This function uses typename T which must be a subclass of CDTable. - It returns the class that conforms to the class name - - \param tableName The table name - \return The class or nullptr + /** + * Fetch a table from CDClient + * + * @tparam Table type to fetch + * @return A pointer to the requested table. */ template<typename T> - T* GetTable(const std::string& tableName) { - static_assert(std::is_base_of<CDTable, T>::value, "T should inherit from CDTable!"); - - for (auto itr = this->tables.begin(); itr != this->tables.end(); ++itr) { - if (itr->first == tableName) { - return dynamic_cast<T*>(itr->second); - } - } - - return nullptr; + T* GetTable() { + return &T::Instance(); } }; diff --git a/dDatabase/Tables/CDActivitiesTable.cpp b/dDatabase/Tables/CDActivitiesTable.cpp index d6fa354e..e1660d66 100644 --- a/dDatabase/Tables/CDActivitiesTable.cpp +++ b/dDatabase/Tables/CDActivitiesTable.cpp @@ -1,6 +1,5 @@ #include "CDActivitiesTable.h" -//! Constructor CDActivitiesTable::CDActivitiesTable(void) { // First, get the size of the table @@ -48,15 +47,6 @@ CDActivitiesTable::CDActivitiesTable(void) { tableData.finalize(); } -//! Destructor -CDActivitiesTable::~CDActivitiesTable(void) {} - -//! Returns the table's name -std::string CDActivitiesTable::GetName(void) const { - return "Activities"; -} - -//! Queries the table with a custom "where" clause std::vector<CDActivities> CDActivitiesTable::Query(std::function<bool(CDActivities)> predicate) { std::vector<CDActivities> data = cpplinq::from(this->entries) @@ -66,7 +56,6 @@ std::vector<CDActivities> CDActivitiesTable::Query(std::function<bool(CDActiviti return data; } -//! Gets all the entries in the table std::vector<CDActivities> CDActivitiesTable::GetEntries(void) const { return this->entries; } diff --git a/dDatabase/Tables/CDActivitiesTable.h b/dDatabase/Tables/CDActivitiesTable.h index 51c560cf..4b60afbd 100644 --- a/dDatabase/Tables/CDActivitiesTable.h +++ b/dDatabase/Tables/CDActivitiesTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDActivitiesTable.hpp - \brief Contains data for the Activities table - */ - - //! Activities Entry Struct struct CDActivities { unsigned int ActivityID; unsigned int locStatus; @@ -31,36 +25,14 @@ struct CDActivities { float optionalPercentage; }; - -//! Activities table -class CDActivitiesTable : public CDTable { +class CDActivitiesTable : public CDTable<CDActivitiesTable> { private: std::vector<CDActivities> entries; public: - - //! Constructor - CDActivitiesTable(void); - - //! Destructor - ~CDActivitiesTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDActivitiesTable(); + // Queries the table with a custom "where" clause std::vector<CDActivities> Query(std::function<bool(CDActivities)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDActivities> GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDActivityRewardsTable.cpp b/dDatabase/Tables/CDActivityRewardsTable.cpp index 3922d9fb..65ef1101 100644 --- a/dDatabase/Tables/CDActivityRewardsTable.cpp +++ b/dDatabase/Tables/CDActivityRewardsTable.cpp @@ -1,6 +1,5 @@ #include "CDActivityRewardsTable.h" -//! Constructor CDActivityRewardsTable::CDActivityRewardsTable(void) { // First, get the size of the table @@ -36,15 +35,6 @@ CDActivityRewardsTable::CDActivityRewardsTable(void) { tableData.finalize(); } -//! Destructor -CDActivityRewardsTable::~CDActivityRewardsTable(void) {} - -//! Returns the table's name -std::string CDActivityRewardsTable::GetName(void) const { - return "ActivityRewards"; -} - -//! Queries the table with a custom "where" clause std::vector<CDActivityRewards> CDActivityRewardsTable::Query(std::function<bool(CDActivityRewards)> predicate) { std::vector<CDActivityRewards> data = cpplinq::from(this->entries) @@ -54,7 +44,6 @@ std::vector<CDActivityRewards> CDActivityRewardsTable::Query(std::function<bool( return data; } -//! Gets all the entries in the table std::vector<CDActivityRewards> CDActivityRewardsTable::GetEntries(void) const { return this->entries; } diff --git a/dDatabase/Tables/CDActivityRewardsTable.h b/dDatabase/Tables/CDActivityRewardsTable.h index 7f1e81a0..b5503fb6 100644 --- a/dDatabase/Tables/CDActivityRewardsTable.h +++ b/dDatabase/Tables/CDActivityRewardsTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDActivityRewardsTable.hpp - \brief Contains data for the ActivityRewards table - */ - - //! ActivityRewards Entry Struct struct CDActivityRewards { unsigned int objectTemplate; //!< The object template (?) unsigned int ActivityRewardIndex; //!< The activity reward index @@ -19,36 +13,15 @@ struct CDActivityRewards { std::string description; //!< The description }; - -//! ActivityRewards table -class CDActivityRewardsTable : public CDTable { +class CDActivityRewardsTable : public CDTable<CDActivityRewardsTable> { private: std::vector<CDActivityRewards> entries; public: - - //! Constructor - CDActivityRewardsTable(void); - - //! Destructor - ~CDActivityRewardsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDActivityRewardsTable(); + // Queries the table with a custom "where" clause std::vector<CDActivityRewards> Query(std::function<bool(CDActivityRewards)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDActivityRewards> GetEntries(void) const; }; diff --git a/dDatabase/Tables/CDAnimationsTable.cpp b/dDatabase/Tables/CDAnimationsTable.cpp index e21d44c5..e1227f39 100644 --- a/dDatabase/Tables/CDAnimationsTable.cpp +++ b/dDatabase/Tables/CDAnimationsTable.cpp @@ -1,6 +1,5 @@ #include "CDAnimationsTable.h" -//! Constructor CDAnimationsTable::CDAnimationsTable(void) { // First, get the size of the table @@ -42,15 +41,6 @@ CDAnimationsTable::CDAnimationsTable(void) { tableData.finalize(); } -//! Destructor -CDAnimationsTable::~CDAnimationsTable(void) {} - -//! Returns the table's name -std::string CDAnimationsTable::GetName(void) const { - return "Animations"; -} - -//! Queries the table with a custom "where" clause std::vector<CDAnimations> CDAnimationsTable::Query(std::function<bool(CDAnimations)> predicate) { std::vector<CDAnimations> data = cpplinq::from(this->entries) @@ -60,7 +50,6 @@ std::vector<CDAnimations> CDAnimationsTable::Query(std::function<bool(CDAnimatio return data; } -//! Gets all the entries in the table std::vector<CDAnimations> CDAnimationsTable::GetEntries(void) const { return this->entries; } diff --git a/dDatabase/Tables/CDAnimationsTable.h b/dDatabase/Tables/CDAnimationsTable.h index 24112985..43400abf 100644 --- a/dDatabase/Tables/CDAnimationsTable.h +++ b/dDatabase/Tables/CDAnimationsTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDAnimationsTable.hpp - \brief Contains data for the Animations table - */ - - //! Animations Entry Struct struct CDAnimations { unsigned int animationGroupID; //!< The animation group ID std::string animation_type; //!< The animation type @@ -26,35 +20,14 @@ struct CDAnimations { }; -//! Animations table -class CDAnimationsTable : public CDTable { +class CDAnimationsTable : public CDTable<CDAnimationsTable> { private: std::vector<CDAnimations> entries; public: - - //! Constructor - CDAnimationsTable(void); - - //! Destructor - ~CDAnimationsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDAnimationsTable(); + // Queries the table with a custom "where" clause std::vector<CDAnimations> Query(std::function<bool(CDAnimations)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDAnimations> GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDBehaviorParameterTable.cpp b/dDatabase/Tables/CDBehaviorParameterTable.cpp index b894688b..0713e740 100644 --- a/dDatabase/Tables/CDBehaviorParameterTable.cpp +++ b/dDatabase/Tables/CDBehaviorParameterTable.cpp @@ -1,7 +1,6 @@ #include "CDBehaviorParameterTable.h" #include "GeneralUtils.h" -//! Constructor CDBehaviorParameterTable::CDBehaviorParameterTable(void) { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorParameter"); uint32_t uniqueParameterId = 0; @@ -28,14 +27,6 @@ CDBehaviorParameterTable::CDBehaviorParameterTable(void) { tableData.finalize(); } -//! Destructor -CDBehaviorParameterTable::~CDBehaviorParameterTable(void) {} - -//! Returns the table's name -std::string CDBehaviorParameterTable::GetName(void) const { - return "BehaviorParameter"; -} - 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; diff --git a/dDatabase/Tables/CDBehaviorParameterTable.h b/dDatabase/Tables/CDBehaviorParameterTable.h index 5d0d8b72..b0715684 100644 --- a/dDatabase/Tables/CDBehaviorParameterTable.h +++ b/dDatabase/Tables/CDBehaviorParameterTable.h @@ -5,37 +5,18 @@ #include <unordered_map> #include <unordered_set> -/*! - \file CDBehaviorParameterTable.hpp - \brief Contains data for the BehaviorParameter table - */ - - //! BehaviorParameter Entry Struct struct CDBehaviorParameter { unsigned int behaviorID; //!< The Behavior ID std::unordered_map<std::string, uint32_t>::iterator parameterID; //!< The Parameter ID float value; //!< The value of the behavior template }; -//! BehaviorParameter table -class CDBehaviorParameterTable : public CDTable { +class CDBehaviorParameterTable : public CDTable<CDBehaviorParameterTable> { private: std::unordered_map<uint64_t, CDBehaviorParameter> m_Entries; std::unordered_map<std::string, uint32_t> m_ParametersList; public: - - //! Constructor - CDBehaviorParameterTable(void); - - //! Destructor - ~CDBehaviorParameterTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - + CDBehaviorParameterTable(); float GetValue(const uint32_t behaviorID, const std::string& name, const float defaultValue = 0); std::map<std::string, float> GetParametersByBehaviorID(uint32_t behaviorID); diff --git a/dDatabase/Tables/CDBehaviorTemplateTable.cpp b/dDatabase/Tables/CDBehaviorTemplateTable.cpp index 4adb9bce..08bc86d1 100644 --- a/dDatabase/Tables/CDBehaviorTemplateTable.cpp +++ b/dDatabase/Tables/CDBehaviorTemplateTable.cpp @@ -1,6 +1,5 @@ #include "CDBehaviorTemplateTable.h" -//! Constructor CDBehaviorTemplateTable::CDBehaviorTemplateTable(void) { // First, get the size of the table @@ -40,15 +39,6 @@ CDBehaviorTemplateTable::CDBehaviorTemplateTable(void) { tableData.finalize(); } -//! Destructor -CDBehaviorTemplateTable::~CDBehaviorTemplateTable(void) {} - -//! Returns the table's name -std::string CDBehaviorTemplateTable::GetName(void) const { - return "BehaviorTemplate"; -} - -//! Queries the table with a custom "where" clause std::vector<CDBehaviorTemplate> CDBehaviorTemplateTable::Query(std::function<bool(CDBehaviorTemplate)> predicate) { std::vector<CDBehaviorTemplate> data = cpplinq::from(this->entries) @@ -58,7 +48,6 @@ std::vector<CDBehaviorTemplate> CDBehaviorTemplateTable::Query(std::function<boo return data; } -//! Gets all the entries in the table std::vector<CDBehaviorTemplate> CDBehaviorTemplateTable::GetEntries(void) const { return this->entries; } diff --git a/dDatabase/Tables/CDBehaviorTemplateTable.h b/dDatabase/Tables/CDBehaviorTemplateTable.h index b2bd2521..f9ac9a09 100644 --- a/dDatabase/Tables/CDBehaviorTemplateTable.h +++ b/dDatabase/Tables/CDBehaviorTemplateTable.h @@ -5,12 +5,6 @@ #include <unordered_map> #include <unordered_set> -/*! - \file CDBehaviorTemplateTable.hpp - \brief Contains data for the BehaviorTemplate table - */ - - //! BehaviorTemplate Entry Struct struct CDBehaviorTemplate { unsigned int behaviorID; //!< The Behavior ID unsigned int templateID; //!< The Template ID (LOT) @@ -19,36 +13,16 @@ struct CDBehaviorTemplate { }; -//! BehaviorTemplate table -class CDBehaviorTemplateTable : public CDTable { +class CDBehaviorTemplateTable : public CDTable<CDBehaviorTemplateTable> { private: std::vector<CDBehaviorTemplate> entries; std::unordered_map<uint32_t, CDBehaviorTemplate> entriesMappedByBehaviorID; std::unordered_set<std::string> m_EffectHandles; public: - - //! Constructor - CDBehaviorTemplateTable(void); - - //! Destructor - ~CDBehaviorTemplateTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDBehaviorTemplateTable(); + // Queries the table with a custom "where" clause std::vector<CDBehaviorTemplate> Query(std::function<bool(CDBehaviorTemplate)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDBehaviorTemplate> GetEntries(void) const; const CDBehaviorTemplate GetByBehaviorID(uint32_t behaviorID); diff --git a/dDatabase/Tables/CDBrickIDTableTable.cpp b/dDatabase/Tables/CDBrickIDTableTable.cpp index 7cd3e86f..9ad24d39 100644 --- a/dDatabase/Tables/CDBrickIDTableTable.cpp +++ b/dDatabase/Tables/CDBrickIDTableTable.cpp @@ -1,6 +1,5 @@ #include "CDBrickIDTableTable.h" -//! Constructor CDBrickIDTableTable::CDBrickIDTableTable(void) { // First, get the size of the table @@ -31,15 +30,6 @@ CDBrickIDTableTable::CDBrickIDTableTable(void) { tableData.finalize(); } -//! Destructor -CDBrickIDTableTable::~CDBrickIDTableTable(void) {} - -//! Returns the table's name -std::string CDBrickIDTableTable::GetName(void) const { - return "BrickIDTable"; -} - -//! Queries the table with a custom "where" clause std::vector<CDBrickIDTable> CDBrickIDTableTable::Query(std::function<bool(CDBrickIDTable)> predicate) { std::vector<CDBrickIDTable> data = cpplinq::from(this->entries) @@ -49,7 +39,6 @@ std::vector<CDBrickIDTable> CDBrickIDTableTable::Query(std::function<bool(CDBric return data; } -//! Gets all the entries in the table std::vector<CDBrickIDTable> CDBrickIDTableTable::GetEntries(void) const { return this->entries; } diff --git a/dDatabase/Tables/CDBrickIDTableTable.h b/dDatabase/Tables/CDBrickIDTableTable.h index aefe332c..e2084caf 100644 --- a/dDatabase/Tables/CDBrickIDTableTable.h +++ b/dDatabase/Tables/CDBrickIDTableTable.h @@ -16,34 +16,14 @@ struct CDBrickIDTable { //! BrickIDTable table -class CDBrickIDTableTable : public CDTable { +class CDBrickIDTableTable : public CDTable<CDBrickIDTableTable> { private: std::vector<CDBrickIDTable> entries; public: - - //! Constructor - CDBrickIDTableTable(void); - - //! Destructor - ~CDBrickIDTableTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDBrickIDTableTable(); + // Queries the table with a custom "where" clause std::vector<CDBrickIDTable> Query(std::function<bool(CDBrickIDTable)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDBrickIDTable> GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDComponentsRegistryTable.cpp b/dDatabase/Tables/CDComponentsRegistryTable.cpp index 88bb04cc..32012f6c 100644 --- a/dDatabase/Tables/CDComponentsRegistryTable.cpp +++ b/dDatabase/Tables/CDComponentsRegistryTable.cpp @@ -3,7 +3,6 @@ #define CDCLIENT_CACHE_ALL -//! Constructor CDComponentsRegistryTable::CDComponentsRegistryTable(void) { #ifdef CDCLIENT_CACHE_ALL @@ -31,24 +30,6 @@ CDComponentsRegistryTable::CDComponentsRegistryTable(void) { this->mappedEntries.insert_or_assign(((uint64_t)entry.component_type) << 32 | ((uint64_t)entry.id), entry.component_id); - //this->entries.push_back(entry); - - /* - //Darwin's stuff: - const auto& it = this->mappedEntries.find(entry.id); - if (it != mappedEntries.end()) { - const auto& iter = it->second.find(entry.component_type); - if (iter == it->second.end()) { - it->second.insert(std::make_pair(entry.component_type, entry.component_id)); - } - } - else { - std::map<unsigned int, unsigned int> map; - map.insert(std::make_pair(entry.component_type, entry.component_id)); - this->mappedEntries.insert(std::make_pair(entry.id, map)); - } - */ - tableData.nextRow(); } @@ -56,14 +37,6 @@ CDComponentsRegistryTable::CDComponentsRegistryTable(void) { #endif } -//! Destructor -CDComponentsRegistryTable::~CDComponentsRegistryTable(void) {} - -//! Returns the table's name -std::string CDComponentsRegistryTable::GetName(void) const { - return "ComponentsRegistry"; -} - int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, eReplicaComponentType componentType, int32_t defaultValue) { const auto& iter = this->mappedEntries.find(((uint64_t)componentType) << 32 | ((uint64_t)id)); @@ -73,16 +46,6 @@ int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, eReplicaComponent return iter->second; - /* - const auto& it = this->mappedEntries.find(id); - if (it != mappedEntries.end()) { - const auto& iter = it->second.find(componentType); - if (iter != it->second.end()) { - return iter->second; - } - } - */ - #ifndef CDCLIENT_CACHE_ALL // Now get the data std::stringstream query; diff --git a/dDatabase/Tables/CDComponentsRegistryTable.h b/dDatabase/Tables/CDComponentsRegistryTable.h index 91e3800c..990072c9 100644 --- a/dDatabase/Tables/CDComponentsRegistryTable.h +++ b/dDatabase/Tables/CDComponentsRegistryTable.h @@ -3,12 +3,7 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDComponentsRegistryTable.hpp - \brief Contains data for the ComponentsRegistry table - */ enum class eReplicaComponentType : uint32_t; - //! ComponentsRegistry Entry Struct struct CDComponentsRegistry { unsigned int id; //!< The LOT is used as the ID eReplicaComponentType component_type; //!< See ComponentTypes enum for values @@ -16,25 +11,11 @@ struct CDComponentsRegistry { }; -//! ComponentsRegistry table -class CDComponentsRegistryTable : public CDTable { +class CDComponentsRegistryTable : public CDTable<CDComponentsRegistryTable> { private: - //std::vector<CDComponentsRegistry> entries; std::map<uint64_t, uint32_t> mappedEntries; //id, component_type, component_id public: - - //! Constructor - CDComponentsRegistryTable(void); - - //! Destructor - ~CDComponentsRegistryTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - + CDComponentsRegistryTable(); int32_t GetByIDAndType(uint32_t id, eReplicaComponentType componentType, int32_t defaultValue = 0); }; diff --git a/dDatabase/Tables/CDCurrencyTableTable.cpp b/dDatabase/Tables/CDCurrencyTableTable.cpp index 21870f00..78a716f9 100644 --- a/dDatabase/Tables/CDCurrencyTableTable.cpp +++ b/dDatabase/Tables/CDCurrencyTableTable.cpp @@ -34,15 +34,6 @@ CDCurrencyTableTable::CDCurrencyTableTable(void) { tableData.finalize(); } -//! Destructor -CDCurrencyTableTable::~CDCurrencyTableTable(void) {} - -//! Returns the table's name -std::string CDCurrencyTableTable::GetName(void) const { - return "CurrencyTable"; -} - -//! Queries the table with a custom "where" clause std::vector<CDCurrencyTable> CDCurrencyTableTable::Query(std::function<bool(CDCurrencyTable)> predicate) { std::vector<CDCurrencyTable> data = cpplinq::from(this->entries) @@ -52,7 +43,6 @@ std::vector<CDCurrencyTable> CDCurrencyTableTable::Query(std::function<bool(CDCu return data; } -//! Gets all the entries in the table std::vector<CDCurrencyTable> CDCurrencyTableTable::GetEntries(void) const { return this->entries; } diff --git a/dDatabase/Tables/CDCurrencyTableTable.h b/dDatabase/Tables/CDCurrencyTableTable.h index 5a856395..ec700320 100644 --- a/dDatabase/Tables/CDCurrencyTableTable.h +++ b/dDatabase/Tables/CDCurrencyTableTable.h @@ -18,34 +18,14 @@ struct CDCurrencyTable { }; //! CurrencyTable table -class CDCurrencyTableTable : public CDTable { +class CDCurrencyTableTable : public CDTable<CDCurrencyTableTable> { private: std::vector<CDCurrencyTable> entries; public: - - //! Constructor - CDCurrencyTableTable(void); - - //! Destructor - ~CDCurrencyTableTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDCurrencyTableTable(); + // Queries the table with a custom "where" clause std::vector<CDCurrencyTable> Query(std::function<bool(CDCurrencyTable)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDCurrencyTable> GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDDestructibleComponentTable.cpp b/dDatabase/Tables/CDDestructibleComponentTable.cpp index 2480fc24..4bbc8242 100644 --- a/dDatabase/Tables/CDDestructibleComponentTable.cpp +++ b/dDatabase/Tables/CDDestructibleComponentTable.cpp @@ -43,15 +43,6 @@ CDDestructibleComponentTable::CDDestructibleComponentTable(void) { tableData.finalize(); } -//! Destructor -CDDestructibleComponentTable::~CDDestructibleComponentTable(void) {} - -//! Returns the table's name -std::string CDDestructibleComponentTable::GetName(void) const { - return "DestructibleComponent"; -} - -//! Queries the table with a custom "where" clause std::vector<CDDestructibleComponent> CDDestructibleComponentTable::Query(std::function<bool(CDDestructibleComponent)> predicate) { std::vector<CDDestructibleComponent> data = cpplinq::from(this->entries) @@ -61,7 +52,6 @@ std::vector<CDDestructibleComponent> CDDestructibleComponentTable::Query(std::fu return data; } -//! Gets all the entries in the table std::vector<CDDestructibleComponent> CDDestructibleComponentTable::GetEntries(void) const { return this->entries; } diff --git a/dDatabase/Tables/CDDestructibleComponentTable.h b/dDatabase/Tables/CDDestructibleComponentTable.h index e89bbff8..e42cf486 100644 --- a/dDatabase/Tables/CDDestructibleComponentTable.h +++ b/dDatabase/Tables/CDDestructibleComponentTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDDestructibleComponentTable.hpp - \brief Contains data for the DestructibleComponent table - */ - - //! ItemComponent Struct struct CDDestructibleComponent { unsigned int id; //!< The component ID from the ComponentsRegistry Table int faction; //!< The Faction ID of the object @@ -26,35 +20,14 @@ struct CDDestructibleComponent { int difficultyLevel; //!< ??? }; -//! ItemComponent table -class CDDestructibleComponentTable : public CDTable { +class CDDestructibleComponentTable : public CDTable<CDDestructibleComponentTable> { private: std::vector<CDDestructibleComponent> entries; public: - - //! Constructor - CDDestructibleComponentTable(void); - - //! Destructor - ~CDDestructibleComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDDestructibleComponentTable(); + // Queries the table with a custom "where" clause std::vector<CDDestructibleComponent> Query(std::function<bool(CDDestructibleComponent)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDDestructibleComponent> GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDEmoteTable.cpp b/dDatabase/Tables/CDEmoteTable.cpp index b97e02e8..aacbdd55 100644 --- a/dDatabase/Tables/CDEmoteTable.cpp +++ b/dDatabase/Tables/CDEmoteTable.cpp @@ -30,11 +30,6 @@ CDEmoteTableTable::~CDEmoteTableTable(void) { entries.clear(); } -//! Returns the table's name -std::string CDEmoteTableTable::GetName(void) const { - return "Emotes"; -} - CDEmoteTable* CDEmoteTableTable::GetEmote(int id) { for (auto e : entries) { if (e.first == id) return e.second; diff --git a/dDatabase/Tables/CDEmoteTable.h b/dDatabase/Tables/CDEmoteTable.h index 1f4fb246..be40c86f 100644 --- a/dDatabase/Tables/CDEmoteTable.h +++ b/dDatabase/Tables/CDEmoteTable.h @@ -4,12 +4,6 @@ #include "CDTable.h" #include <map> -/*! - \file CDEmoteTable.hpp - \brief Contains data for the CDEmoteTable table - */ - - //! CDEmoteEntry Struct struct CDEmoteTable { CDEmoteTable() { ID = -1; @@ -32,25 +26,13 @@ struct CDEmoteTable { std::string gateVersion; }; -//! CDEmoteTable table -class CDEmoteTableTable : public CDTable { +class CDEmoteTableTable : public CDTable<CDEmoteTableTable> { private: std::map<int, CDEmoteTable*> entries; public: - - //! Constructor - CDEmoteTableTable(void); - - //! Destructor - ~CDEmoteTableTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Returns an emote by ID + CDEmoteTableTable(); + ~CDEmoteTableTable(); + // Returns an emote by ID CDEmoteTable* GetEmote(int id); }; diff --git a/dDatabase/Tables/CDFeatureGatingTable.cpp b/dDatabase/Tables/CDFeatureGatingTable.cpp index 0abcdb25..05fe69bf 100644 --- a/dDatabase/Tables/CDFeatureGatingTable.cpp +++ b/dDatabase/Tables/CDFeatureGatingTable.cpp @@ -34,15 +34,6 @@ CDFeatureGatingTable::CDFeatureGatingTable(void) { tableData.finalize(); } -//! Destructor -CDFeatureGatingTable::~CDFeatureGatingTable(void) {} - -//! Returns the table's name -std::string CDFeatureGatingTable::GetName(void) const { - return "FeatureGating"; -} - -//! Queries the table with a custom "where" clause std::vector<CDFeatureGating> CDFeatureGatingTable::Query(std::function<bool(CDFeatureGating)> predicate) { std::vector<CDFeatureGating> data = cpplinq::from(this->entries) @@ -62,7 +53,6 @@ bool CDFeatureGatingTable::FeatureUnlocked(const std::string& feature) const { return false; } -//! Gets all the entries in the table std::vector<CDFeatureGating> CDFeatureGatingTable::GetEntries(void) const { return this->entries; } diff --git a/dDatabase/Tables/CDFeatureGatingTable.h b/dDatabase/Tables/CDFeatureGatingTable.h index 54e6d21b..7f536db5 100644 --- a/dDatabase/Tables/CDFeatureGatingTable.h +++ b/dDatabase/Tables/CDFeatureGatingTable.h @@ -3,11 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDFeatureGatingTable.hpp - */ - - //! ItemComponent Struct struct CDFeatureGating { std::string featureName; int32_t major; @@ -16,37 +11,16 @@ struct CDFeatureGating { std::string description; }; -//! ItemComponent table -class CDFeatureGatingTable : public CDTable { +class CDFeatureGatingTable : public CDTable<CDFeatureGatingTable> { private: std::vector<CDFeatureGating> entries; public: - - //! Constructor - CDFeatureGatingTable(void); - - //! Destructor - ~CDFeatureGatingTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDFeatureGatingTable(); + // Queries the table with a custom "where" clause std::vector<CDFeatureGating> Query(std::function<bool(CDFeatureGating)> predicate); bool FeatureUnlocked(const std::string& feature) const; - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDFeatureGating> GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDInventoryComponentTable.cpp b/dDatabase/Tables/CDInventoryComponentTable.cpp index cf956775..2dc375ab 100644 --- a/dDatabase/Tables/CDInventoryComponentTable.cpp +++ b/dDatabase/Tables/CDInventoryComponentTable.cpp @@ -33,15 +33,6 @@ CDInventoryComponentTable::CDInventoryComponentTable(void) { tableData.finalize(); } -//! Destructor -CDInventoryComponentTable::~CDInventoryComponentTable(void) {} - -//! Returns the table's name -std::string CDInventoryComponentTable::GetName(void) const { - return "InventoryComponent"; -} - -//! Queries the table with a custom "where" clause std::vector<CDInventoryComponent> CDInventoryComponentTable::Query(std::function<bool(CDInventoryComponent)> predicate) { std::vector<CDInventoryComponent> data = cpplinq::from(this->entries) @@ -51,7 +42,6 @@ std::vector<CDInventoryComponent> CDInventoryComponentTable::Query(std::function return data; } -//! Gets all the entries in the table std::vector<CDInventoryComponent> CDInventoryComponentTable::GetEntries(void) const { return this->entries; } diff --git a/dDatabase/Tables/CDInventoryComponentTable.h b/dDatabase/Tables/CDInventoryComponentTable.h index c6117907..cbc04d99 100644 --- a/dDatabase/Tables/CDInventoryComponentTable.h +++ b/dDatabase/Tables/CDInventoryComponentTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDInventoryComponentTable.hpp - \brief Contains data for the InventoryComponent table - */ - - //! ItemComponent Struct struct CDInventoryComponent { unsigned int id; //!< The component ID for this object unsigned int itemid; //!< The LOT of the object @@ -16,35 +10,14 @@ struct CDInventoryComponent { bool equip; //!< Whether or not to equip the item }; -//! ItemComponent table -class CDInventoryComponentTable : public CDTable { +class CDInventoryComponentTable : public CDTable<CDInventoryComponentTable> { private: std::vector<CDInventoryComponent> entries; public: - - //! Constructor - CDInventoryComponentTable(void); - - //! Destructor - ~CDInventoryComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDInventoryComponentTable(); + // Queries the table with a custom "where" clause std::vector<CDInventoryComponent> Query(std::function<bool(CDInventoryComponent)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDInventoryComponent> GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDItemComponentTable.cpp b/dDatabase/Tables/CDItemComponentTable.cpp index a3cb4159..54afc417 100644 --- a/dDatabase/Tables/CDItemComponentTable.cpp +++ b/dDatabase/Tables/CDItemComponentTable.cpp @@ -74,14 +74,6 @@ CDItemComponentTable::CDItemComponentTable(void) { #endif } -//! Destructor -CDItemComponentTable::~CDItemComponentTable(void) {} - -//! Returns the table's name -std::string CDItemComponentTable::GetName(void) const { - return "ItemComponent"; -} - const CDItemComponent& CDItemComponentTable::GetItemComponentByID(unsigned int skillID) { const auto& it = this->entries.find(skillID); if (it != this->entries.end()) { diff --git a/dDatabase/Tables/CDItemComponentTable.h b/dDatabase/Tables/CDItemComponentTable.h index b3a2a5f4..11c34dd6 100644 --- a/dDatabase/Tables/CDItemComponentTable.h +++ b/dDatabase/Tables/CDItemComponentTable.h @@ -4,12 +4,6 @@ #include "CDTable.h" #include "dCommonVars.h" -/*! - \file CDItemComponentTable.hpp - \brief Contains data for the ItemComponent table - */ - - //! ItemComponent Struct struct CDItemComponent { unsigned int id; //!< The Component ID std::string equipLocation; //!< The equip location @@ -55,28 +49,15 @@ struct CDItemComponent { float SellMultiplier; //!< Something to do with early vendors perhaps (but replaced) }; -//! ItemComponent table -class CDItemComponentTable : public CDTable { +class CDItemComponentTable : public CDTable<CDItemComponentTable> { private: std::map<unsigned int, CDItemComponent> entries; public: - - //! Constructor - CDItemComponentTable(void); - - //! Destructor - ~CDItemComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - + CDItemComponentTable(); static std::map<LOT, uint32_t> ParseCraftingCurrencies(const CDItemComponent& itemComponent); - //! Gets an entry by ID + // Gets an entry by ID const CDItemComponent& GetItemComponentByID(unsigned int skillID); static CDItemComponent Default; diff --git a/dDatabase/Tables/CDItemSetSkillsTable.cpp b/dDatabase/Tables/CDItemSetSkillsTable.cpp index 107e25d9..f6b412ff 100644 --- a/dDatabase/Tables/CDItemSetSkillsTable.cpp +++ b/dDatabase/Tables/CDItemSetSkillsTable.cpp @@ -32,15 +32,6 @@ CDItemSetSkillsTable::CDItemSetSkillsTable(void) { tableData.finalize(); } -//! Destructor -CDItemSetSkillsTable::~CDItemSetSkillsTable(void) {} - -//! Returns the table's name -std::string CDItemSetSkillsTable::GetName(void) const { - return "ItemSetSkills"; -} - -//! Queries the table with a custom "where" clause std::vector<CDItemSetSkills> CDItemSetSkillsTable::Query(std::function<bool(CDItemSetSkills)> predicate) { std::vector<CDItemSetSkills> data = cpplinq::from(this->entries) @@ -50,7 +41,6 @@ std::vector<CDItemSetSkills> CDItemSetSkillsTable::Query(std::function<bool(CDIt return data; } -//! Gets all the entries in the table std::vector<CDItemSetSkills> CDItemSetSkillsTable::GetEntries(void) const { return this->entries; } @@ -65,4 +55,3 @@ std::vector<CDItemSetSkills> CDItemSetSkillsTable::GetBySkillID(unsigned int Ski return toReturn; } - diff --git a/dDatabase/Tables/CDItemSetSkillsTable.h b/dDatabase/Tables/CDItemSetSkillsTable.h index bf05eea9..8328c66b 100644 --- a/dDatabase/Tables/CDItemSetSkillsTable.h +++ b/dDatabase/Tables/CDItemSetSkillsTable.h @@ -3,50 +3,22 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDItemSetSkillsTable.hpp - \brief Contains data for the ItemSetSkills table - */ - - //! ZoneTable Struct struct CDItemSetSkills { unsigned int SkillSetID; //!< The skill set ID unsigned int SkillID; //!< The skill ID unsigned int SkillCastType; //!< The skill cast type }; -//! ItemSets table -class CDItemSetSkillsTable : public CDTable { +class CDItemSetSkillsTable : public CDTable<CDItemSetSkillsTable> { private: std::vector<CDItemSetSkills> entries; public: - - //! Constructor - CDItemSetSkillsTable(void); - - //! Destructor - ~CDItemSetSkillsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDItemSetSkillsTable(); + // Queries the table with a custom "where" clause std::vector<CDItemSetSkills> Query(std::function<bool(CDItemSetSkills)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDItemSetSkills> GetEntries(void) const; std::vector<CDItemSetSkills> GetBySkillID(unsigned int SkillSetID); - }; - diff --git a/dDatabase/Tables/CDItemSetsTable.cpp b/dDatabase/Tables/CDItemSetsTable.cpp index 1f9d7409..0632ef13 100644 --- a/dDatabase/Tables/CDItemSetsTable.cpp +++ b/dDatabase/Tables/CDItemSetsTable.cpp @@ -44,15 +44,6 @@ CDItemSetsTable::CDItemSetsTable(void) { tableData.finalize(); } -//! Destructor -CDItemSetsTable::~CDItemSetsTable(void) {} - -//! Returns the table's name -std::string CDItemSetsTable::GetName(void) const { - return "ItemSets"; -} - -//! Queries the table with a custom "where" clause std::vector<CDItemSets> CDItemSetsTable::Query(std::function<bool(CDItemSets)> predicate) { std::vector<CDItemSets> data = cpplinq::from(this->entries) @@ -62,7 +53,6 @@ std::vector<CDItemSets> CDItemSetsTable::Query(std::function<bool(CDItemSets)> p return data; } -//! Gets all the entries in the table std::vector<CDItemSets> CDItemSetsTable::GetEntries(void) const { return this->entries; } diff --git a/dDatabase/Tables/CDItemSetsTable.h b/dDatabase/Tables/CDItemSetsTable.h index ef12c7b4..6756e7fa 100644 --- a/dDatabase/Tables/CDItemSetsTable.h +++ b/dDatabase/Tables/CDItemSetsTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDItemSetsTable.hpp - \brief Contains data for the ItemSets table - */ - - //! ZoneTable Struct struct CDItemSets { unsigned int setID; //!< The item set ID unsigned int locStatus; //!< The loc status @@ -27,36 +21,15 @@ struct CDItemSets { float priority; //!< The priority }; -//! ItemSets table -class CDItemSetsTable : public CDTable { +class CDItemSetsTable : public CDTable<CDItemSetsTable> { private: std::vector<CDItemSets> entries; public: - - //! Constructor - CDItemSetsTable(void); - - //! Destructor - ~CDItemSetsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDItemSetsTable(); + // Queries the table with a custom "where" clause std::vector<CDItemSets> Query(std::function<bool(CDItemSets)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDItemSets> GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDLevelProgressionLookupTable.cpp b/dDatabase/Tables/CDLevelProgressionLookupTable.cpp index b3231308..47a8fc0e 100644 --- a/dDatabase/Tables/CDLevelProgressionLookupTable.cpp +++ b/dDatabase/Tables/CDLevelProgressionLookupTable.cpp @@ -32,14 +32,6 @@ CDLevelProgressionLookupTable::CDLevelProgressionLookupTable(void) { tableData.finalize(); } -//! Destructor -CDLevelProgressionLookupTable::~CDLevelProgressionLookupTable(void) {} - -//! Returns the table's name -std::string CDLevelProgressionLookupTable::GetName(void) const { - return "LevelProgressionLookup"; -} - //! Queries the table with a custom "where" clause std::vector<CDLevelProgressionLookup> CDLevelProgressionLookupTable::Query(std::function<bool(CDLevelProgressionLookup)> predicate) { diff --git a/dDatabase/Tables/CDLevelProgressionLookupTable.h b/dDatabase/Tables/CDLevelProgressionLookupTable.h index 391c9b37..070b2e0c 100644 --- a/dDatabase/Tables/CDLevelProgressionLookupTable.h +++ b/dDatabase/Tables/CDLevelProgressionLookupTable.h @@ -3,47 +3,21 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDLevelProgressionLookupTable.hpp - \brief Contains data for the LevelProgressionLookup table - */ - - //! LevelProgressionLookup Entry Struct struct CDLevelProgressionLookup { unsigned int id; //!< The Level ID unsigned int requiredUScore; //!< The required LEGO Score std::string BehaviorEffect; //!< The behavior effect attached to this }; -//! LevelProgressionLookup table -class CDLevelProgressionLookupTable : public CDTable { +class CDLevelProgressionLookupTable : public CDTable<CDLevelProgressionLookupTable> { private: std::vector<CDLevelProgressionLookup> entries; public: - - //! Constructor - CDLevelProgressionLookupTable(void); - - //! Destructor - ~CDLevelProgressionLookupTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDLevelProgressionLookupTable(); + // Queries the table with a custom "where" clause std::vector<CDLevelProgressionLookup> Query(std::function<bool(CDLevelProgressionLookup)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ + // Gets all the entries in the table std::vector<CDLevelProgressionLookup> GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDLootMatrixTable.cpp b/dDatabase/Tables/CDLootMatrixTable.cpp index 93a2fda1..8f25e8a3 100644 --- a/dDatabase/Tables/CDLootMatrixTable.cpp +++ b/dDatabase/Tables/CDLootMatrixTable.cpp @@ -38,15 +38,6 @@ CDLootMatrixTable::CDLootMatrixTable(void) { tableData.finalize(); } -//! Destructor -CDLootMatrixTable::~CDLootMatrixTable(void) {} - -//! Returns the table's name -std::string CDLootMatrixTable::GetName(void) const { - return "LootMatrix"; -} - -//! Queries the table with a custom "where" clause std::vector<CDLootMatrix> CDLootMatrixTable::Query(std::function<bool(CDLootMatrix)> predicate) { std::vector<CDLootMatrix> data = cpplinq::from(this->entries) @@ -56,7 +47,6 @@ std::vector<CDLootMatrix> CDLootMatrixTable::Query(std::function<bool(CDLootMatr return data; } -//! Gets all the entries in the table const std::vector<CDLootMatrix>& CDLootMatrixTable::GetEntries(void) const { return this->entries; } diff --git a/dDatabase/Tables/CDLootMatrixTable.h b/dDatabase/Tables/CDLootMatrixTable.h index 7d311b3b..c6035841 100644 --- a/dDatabase/Tables/CDLootMatrixTable.h +++ b/dDatabase/Tables/CDLootMatrixTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDLootMatrixTable.hpp - \brief Contains data for the ObjectSkills table - */ - - //! LootMatrix Struct struct CDLootMatrix { unsigned int LootMatrixIndex; //!< The Loot Matrix Index unsigned int LootTableIndex; //!< The Loot Table Index @@ -21,36 +15,15 @@ struct CDLootMatrix { UNUSED(std::string gate_version); //!< The Gate Version }; -//! MissionNPCComponent table -class CDLootMatrixTable : public CDTable { +class CDLootMatrixTable : public CDTable<CDLootMatrixTable> { private: std::vector<CDLootMatrix> entries; public: - - //! Constructor - CDLootMatrixTable(void); - - //! Destructor - ~CDLootMatrixTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDLootMatrixTable(); + // Queries the table with a custom "where" clause std::vector<CDLootMatrix> Query(std::function<bool(CDLootMatrix)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ const std::vector<CDLootMatrix>& GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDLootTableTable.cpp b/dDatabase/Tables/CDLootTableTable.cpp index 91cced47..0a46784a 100644 --- a/dDatabase/Tables/CDLootTableTable.cpp +++ b/dDatabase/Tables/CDLootTableTable.cpp @@ -35,14 +35,6 @@ CDLootTableTable::CDLootTableTable(void) { tableData.finalize(); } -//! Destructor -CDLootTableTable::~CDLootTableTable(void) {} - -//! Returns the table's name -std::string CDLootTableTable::GetName(void) const { - return "LootTable"; -} - //! Queries the table with a custom "where" clause std::vector<CDLootTable> CDLootTableTable::Query(std::function<bool(CDLootTable)> predicate) { diff --git a/dDatabase/Tables/CDLootTableTable.h b/dDatabase/Tables/CDLootTableTable.h index 3f1baf60..ba6f207e 100644 --- a/dDatabase/Tables/CDLootTableTable.h +++ b/dDatabase/Tables/CDLootTableTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDLootTableTable.hpp - \brief Contains data for the LootTable table - */ - - //! LootTable Struct struct CDLootTable { unsigned int itemid; //!< The LOT of the item unsigned int LootTableIndex; //!< The Loot Table Index @@ -17,36 +11,15 @@ struct CDLootTable { unsigned int sortPriority; //!< The sorting priority }; -//! LootTable table -class CDLootTableTable : public CDTable { +class CDLootTableTable : public CDTable<CDLootTableTable> { private: std::vector<CDLootTable> entries; public: - - //! Constructor - CDLootTableTable(void); - - //! Destructor - ~CDLootTableTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDLootTableTable(); + // Queries the table with a custom "where" clause std::vector<CDLootTable> Query(std::function<bool(CDLootTable)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ const std::vector<CDLootTable>& GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDMissionEmailTable.cpp b/dDatabase/Tables/CDMissionEmailTable.cpp index 4fac7be2..ed855d8a 100644 --- a/dDatabase/Tables/CDMissionEmailTable.cpp +++ b/dDatabase/Tables/CDMissionEmailTable.cpp @@ -37,14 +37,6 @@ CDMissionEmailTable::CDMissionEmailTable(void) { tableData.finalize(); } -//! Destructor -CDMissionEmailTable::~CDMissionEmailTable(void) {} - -//! Returns the table's name -std::string CDMissionEmailTable::GetName(void) const { - return "MissionEmail"; -} - //! Queries the table with a custom "where" clause std::vector<CDMissionEmail> CDMissionEmailTable::Query(std::function<bool(CDMissionEmail)> predicate) { diff --git a/dDatabase/Tables/CDMissionEmailTable.h b/dDatabase/Tables/CDMissionEmailTable.h index 81a7a793..db2310d4 100644 --- a/dDatabase/Tables/CDMissionEmailTable.h +++ b/dDatabase/Tables/CDMissionEmailTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDMissionEmailTable.hpp - \brief Contains data for the MissionEmail table - */ - - //! MissionEmail Entry Struct struct CDMissionEmail { unsigned int ID; unsigned int messageType; @@ -21,35 +15,14 @@ struct CDMissionEmail { }; -//! MissionEmail table -class CDMissionEmailTable : public CDTable { +class CDMissionEmailTable : public CDTable<CDMissionEmailTable> { private: std::vector<CDMissionEmail> entries; public: - - //! Constructor - CDMissionEmailTable(void); - - //! Destructor - ~CDMissionEmailTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDMissionEmailTable(); + // Queries the table with a custom "where" clause std::vector<CDMissionEmail> Query(std::function<bool(CDMissionEmail)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDMissionEmail> GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDMissionNPCComponentTable.cpp b/dDatabase/Tables/CDMissionNPCComponentTable.cpp index 461cc909..5672ed67 100644 --- a/dDatabase/Tables/CDMissionNPCComponentTable.cpp +++ b/dDatabase/Tables/CDMissionNPCComponentTable.cpp @@ -34,14 +34,6 @@ CDMissionNPCComponentTable::CDMissionNPCComponentTable(void) { tableData.finalize(); } -//! Destructor -CDMissionNPCComponentTable::~CDMissionNPCComponentTable(void) {} - -//! Returns the table's name -std::string CDMissionNPCComponentTable::GetName(void) const { - return "MissionNPCComponent"; -} - //! Queries the table with a custom "where" clause std::vector<CDMissionNPCComponent> CDMissionNPCComponentTable::Query(std::function<bool(CDMissionNPCComponent)> predicate) { diff --git a/dDatabase/Tables/CDMissionNPCComponentTable.h b/dDatabase/Tables/CDMissionNPCComponentTable.h index 68c94ef0..a7aeb145 100644 --- a/dDatabase/Tables/CDMissionNPCComponentTable.h +++ b/dDatabase/Tables/CDMissionNPCComponentTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDMissionNPCComponentTable.hpp - \brief Contains data for the ObjectSkills table - */ - - //! MissionNPCComponent Struct struct CDMissionNPCComponent { unsigned int id; //!< The ID unsigned int missionID; //!< The Mission ID @@ -17,35 +11,16 @@ struct CDMissionNPCComponent { std::string gate_version; //!< The gate version }; -//! MissionNPCComponent table -class CDMissionNPCComponentTable : public CDTable { +class CDMissionNPCComponentTable : public CDTable<CDMissionNPCComponentTable> { private: std::vector<CDMissionNPCComponent> entries; public: - - //! Constructor - CDMissionNPCComponentTable(void); - - //! Destructor - ~CDMissionNPCComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDMissionNPCComponentTable(); + // Queries the table with a custom "where" clause std::vector<CDMissionNPCComponent> Query(std::function<bool(CDMissionNPCComponent)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ + // Gets all the entries in the table std::vector<CDMissionNPCComponent> GetEntries(void) const; }; diff --git a/dDatabase/Tables/CDMissionTasksTable.cpp b/dDatabase/Tables/CDMissionTasksTable.cpp index c22da1ef..f32dca1b 100644 --- a/dDatabase/Tables/CDMissionTasksTable.cpp +++ b/dDatabase/Tables/CDMissionTasksTable.cpp @@ -42,15 +42,6 @@ CDMissionTasksTable::CDMissionTasksTable(void) { tableData.finalize(); } -//! Destructor -CDMissionTasksTable::~CDMissionTasksTable(void) {} - -//! Returns the table's name -std::string CDMissionTasksTable::GetName(void) const { - return "MissionTasks"; -} - -//! Queries the table with a custom "where" clause std::vector<CDMissionTasks> CDMissionTasksTable::Query(std::function<bool(CDMissionTasks)> predicate) { std::vector<CDMissionTasks> data = cpplinq::from(this->entries) @@ -74,7 +65,6 @@ std::vector<CDMissionTasks*> CDMissionTasksTable::GetByMissionID(uint32_t missio return tasks; } -//! Gets all the entries in the table const std::vector<CDMissionTasks>& CDMissionTasksTable::GetEntries(void) const { return this->entries; } diff --git a/dDatabase/Tables/CDMissionTasksTable.h b/dDatabase/Tables/CDMissionTasksTable.h index 1a4bd361..fa213faf 100644 --- a/dDatabase/Tables/CDMissionTasksTable.h +++ b/dDatabase/Tables/CDMissionTasksTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDMissionTasksTable.hpp - \brief Contains data for the MissionTasks table - */ - - //! ObjectSkills Struct struct CDMissionTasks { unsigned int id; //!< The Mission ID that the task belongs to UNUSED(unsigned int locStatus); //!< ??? @@ -25,37 +19,17 @@ struct CDMissionTasks { UNUSED(std::string gate_version); //!< ??? }; -//! ObjectSkills table -class CDMissionTasksTable : public CDTable { +class CDMissionTasksTable : public CDTable<CDMissionTasksTable> { private: std::vector<CDMissionTasks> entries; public: - - //! Constructor - CDMissionTasksTable(void); - - //! Destructor - ~CDMissionTasksTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDMissionTasksTable(); + // Queries the table with a custom "where" clause std::vector<CDMissionTasks> Query(std::function<bool(CDMissionTasks)> predicate); std::vector<CDMissionTasks*> GetByMissionID(uint32_t missionID); - //! Gets all the entries in the table - /*! - \return The entries - */ const std::vector<CDMissionTasks>& GetEntries(void) const; }; diff --git a/dDatabase/Tables/CDMissionsTable.cpp b/dDatabase/Tables/CDMissionsTable.cpp index a87b4327..d4ee40ae 100644 --- a/dDatabase/Tables/CDMissionsTable.cpp +++ b/dDatabase/Tables/CDMissionsTable.cpp @@ -85,15 +85,6 @@ CDMissionsTable::CDMissionsTable(void) { Default.id = -1; } -//! Destructor -CDMissionsTable::~CDMissionsTable(void) {} - -//! Returns the table's name -std::string CDMissionsTable::GetName(void) const { - return "Missions"; -} - -//! Queries the table with a custom "where" clause std::vector<CDMissions> CDMissionsTable::Query(std::function<bool(CDMissions)> predicate) { std::vector<CDMissions> data = cpplinq::from(this->entries) @@ -103,7 +94,6 @@ std::vector<CDMissions> CDMissionsTable::Query(std::function<bool(CDMissions)> p return data; } -//! Gets all the entries in the table const std::vector<CDMissions>& CDMissionsTable::GetEntries(void) const { return this->entries; } diff --git a/dDatabase/Tables/CDMissionsTable.h b/dDatabase/Tables/CDMissionsTable.h index 6d1c4a8f..e6a44b02 100644 --- a/dDatabase/Tables/CDMissionsTable.h +++ b/dDatabase/Tables/CDMissionsTable.h @@ -5,12 +5,6 @@ #include <map> #include <cstdint> -/*! - \file CDMissionsTable.hpp - \brief Contains data for the Missions table - */ - - //! Missions Struct struct CDMissions { int id; //!< The Mission ID std::string defined_type; //!< The type of mission @@ -66,35 +60,16 @@ struct CDMissions { int reward_bankinventory; //!< The amount of bank space this mission rewards }; -//! Missions table -class CDMissionsTable : public CDTable { +class CDMissionsTable : public CDTable<CDMissionsTable> { private: std::vector<CDMissions> entries; public: - - //! Constructor - CDMissionsTable(void); - - //! Destructor - ~CDMissionsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDMissionsTable(); + // Queries the table with a custom "where" clause std::vector<CDMissions> Query(std::function<bool(CDMissions)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ + // Gets all the entries in the table const std::vector<CDMissions>& GetEntries(void) const; const CDMissions* GetPtrByMissionID(uint32_t missionID) const; diff --git a/dDatabase/Tables/CDMovementAIComponentTable.cpp b/dDatabase/Tables/CDMovementAIComponentTable.cpp index 333ec202..3b9cc4f4 100644 --- a/dDatabase/Tables/CDMovementAIComponentTable.cpp +++ b/dDatabase/Tables/CDMovementAIComponentTable.cpp @@ -37,14 +37,6 @@ CDMovementAIComponentTable::CDMovementAIComponentTable(void) { tableData.finalize(); } -//! Destructor -CDMovementAIComponentTable::~CDMovementAIComponentTable(void) {} - -//! Returns the table's name -std::string CDMovementAIComponentTable::GetName(void) const { - return "MovementAIComponent"; -} - //! Queries the table with a custom "where" clause std::vector<CDMovementAIComponent> CDMovementAIComponentTable::Query(std::function<bool(CDMovementAIComponent)> predicate) { diff --git a/dDatabase/Tables/CDMovementAIComponentTable.h b/dDatabase/Tables/CDMovementAIComponentTable.h index 0064a98b..84896e2c 100644 --- a/dDatabase/Tables/CDMovementAIComponentTable.h +++ b/dDatabase/Tables/CDMovementAIComponentTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDMovementAIComponentTable.hpp - \brief Contains data for the MovementAIComponent table - */ - - //! MovementAIComponent Struct struct CDMovementAIComponent { unsigned int id; std::string MovementType; @@ -20,36 +14,15 @@ struct CDMovementAIComponent { std::string attachedPath; }; -//! MovementAIComponent table -class CDMovementAIComponentTable : public CDTable { +class CDMovementAIComponentTable : public CDTable<CDMovementAIComponentTable> { private: std::vector<CDMovementAIComponent> entries; public: - - //! Constructor - CDMovementAIComponentTable(void); - - //! Destructor - ~CDMovementAIComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDMovementAIComponentTable(); + // Queries the table with a custom "where" clause std::vector<CDMovementAIComponent> Query(std::function<bool(CDMovementAIComponent)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ + // Gets all the entries in the table std::vector<CDMovementAIComponent> GetEntries(void) const; - }; - diff --git a/dDatabase/Tables/CDObjectSkillsTable.cpp b/dDatabase/Tables/CDObjectSkillsTable.cpp index dc797529..2e8b3fb2 100644 --- a/dDatabase/Tables/CDObjectSkillsTable.cpp +++ b/dDatabase/Tables/CDObjectSkillsTable.cpp @@ -33,14 +33,6 @@ CDObjectSkillsTable::CDObjectSkillsTable(void) { tableData.finalize(); } -//! Destructor -CDObjectSkillsTable::~CDObjectSkillsTable(void) {} - -//! Returns the table's name -std::string CDObjectSkillsTable::GetName(void) const { - return "ObjectSkills"; -} - //! Queries the table with a custom "where" clause std::vector<CDObjectSkills> CDObjectSkillsTable::Query(std::function<bool(CDObjectSkills)> predicate) { @@ -55,4 +47,3 @@ std::vector<CDObjectSkills> CDObjectSkillsTable::Query(std::function<bool(CDObje std::vector<CDObjectSkills> CDObjectSkillsTable::GetEntries(void) const { return this->entries; } - diff --git a/dDatabase/Tables/CDObjectSkillsTable.h b/dDatabase/Tables/CDObjectSkillsTable.h index c2caf71b..4ceaa447 100644 --- a/dDatabase/Tables/CDObjectSkillsTable.h +++ b/dDatabase/Tables/CDObjectSkillsTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDObjectSkillsTable.hpp - \brief Contains data for the ObjectSkills table - */ - - //! ObjectSkills Struct struct CDObjectSkills { unsigned int objectTemplate; //!< The LOT of the item unsigned int skillID; //!< The Skill ID of the object @@ -16,35 +10,16 @@ struct CDObjectSkills { unsigned int AICombatWeight; //!< ??? }; -//! ObjectSkills table -class CDObjectSkillsTable : public CDTable { +class CDObjectSkillsTable : public CDTable<CDObjectSkillsTable> { private: std::vector<CDObjectSkills> entries; public: - - //! Constructor - CDObjectSkillsTable(void); - - //! Destructor - ~CDObjectSkillsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDObjectSkillsTable(); + // Queries the table with a custom "where" clause std::vector<CDObjectSkills> Query(std::function<bool(CDObjectSkills)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ + // Gets all the entries in the table std::vector<CDObjectSkills> GetEntries(void) const; }; diff --git a/dDatabase/Tables/CDObjectsTable.cpp b/dDatabase/Tables/CDObjectsTable.cpp index 5133becc..c68c3e6a 100644 --- a/dDatabase/Tables/CDObjectsTable.cpp +++ b/dDatabase/Tables/CDObjectsTable.cpp @@ -43,14 +43,6 @@ CDObjectsTable::CDObjectsTable(void) { m_default.id = 0; } -//! Destructor -CDObjectsTable::~CDObjectsTable(void) {} - -//! Returns the table's name -std::string CDObjectsTable::GetName(void) const { - return "Objects"; -} - const CDObjects& CDObjectsTable::GetByID(unsigned int LOT) { const auto& it = this->entries.find(LOT); if (it != this->entries.end()) { diff --git a/dDatabase/Tables/CDObjectsTable.h b/dDatabase/Tables/CDObjectsTable.h index 333477bd..171eddef 100644 --- a/dDatabase/Tables/CDObjectsTable.h +++ b/dDatabase/Tables/CDObjectsTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDObjectsTable.hpp - \brief Contains data for the Objects table - */ - - //! RebuildComponent Struct struct CDObjects { unsigned int id; //!< The LOT of the object std::string name; //!< The internal name of the object @@ -26,29 +20,14 @@ struct CDObjects { UNUSED(unsigned int HQ_valid); //!< Probably used for the Nexus HQ database on LEGOUniverse.com }; -//! ObjectSkills table -class CDObjectsTable : public CDTable { +class CDObjectsTable : public CDTable<CDObjectsTable> { private: - //std::vector<CDObjects> entries; std::map<unsigned int, CDObjects> entries; CDObjects m_default; public: - - //! Constructor - CDObjectsTable(void); - - //! Destructor - ~CDObjectsTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Gets an entry by ID + CDObjectsTable(); + // Gets an entry by ID const CDObjects& GetByID(unsigned int LOT); - }; diff --git a/dDatabase/Tables/CDPackageComponentTable.cpp b/dDatabase/Tables/CDPackageComponentTable.cpp index eabe68da..efb85eeb 100644 --- a/dDatabase/Tables/CDPackageComponentTable.cpp +++ b/dDatabase/Tables/CDPackageComponentTable.cpp @@ -32,14 +32,6 @@ CDPackageComponentTable::CDPackageComponentTable(void) { tableData.finalize(); } -//! Destructor -CDPackageComponentTable::~CDPackageComponentTable(void) {} - -//! Returns the table's name -std::string CDPackageComponentTable::GetName(void) const { - return "PackageComponent"; -} - //! Queries the table with a custom "where" clause std::vector<CDPackageComponent> CDPackageComponentTable::Query(std::function<bool(CDPackageComponent)> predicate) { diff --git a/dDatabase/Tables/CDPackageComponentTable.h b/dDatabase/Tables/CDPackageComponentTable.h index 763acf8c..6c11ab39 100644 --- a/dDatabase/Tables/CDPackageComponentTable.h +++ b/dDatabase/Tables/CDPackageComponentTable.h @@ -3,48 +3,20 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDPackageComponentTable.hpp - \brief Contains data for the PackageComponent table - */ - - //! PackageComponent Entry Struct struct CDPackageComponent { unsigned int id; unsigned int LootMatrixIndex; unsigned int packageType; }; - -//! PackageComponent table -class CDPackageComponentTable : public CDTable { +class CDPackageComponentTable : public CDTable<CDPackageComponentTable> { private: std::vector<CDPackageComponent> entries; public: - - //! Constructor CDPackageComponentTable(void); - - //! Destructor - ~CDPackageComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + // Queries the table with a custom "where" clause std::vector<CDPackageComponent> Query(std::function<bool(CDPackageComponent)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDPackageComponent> GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDPhysicsComponentTable.cpp b/dDatabase/Tables/CDPhysicsComponentTable.cpp index f85d83c4..bb21ed7f 100644 --- a/dDatabase/Tables/CDPhysicsComponentTable.cpp +++ b/dDatabase/Tables/CDPhysicsComponentTable.cpp @@ -28,7 +28,7 @@ CDPhysicsComponentTable::CDPhysicsComponentTable(void) { tableData.finalize(); } -CDPhysicsComponentTable::~CDPhysicsComponentTable(void) { +CDPhysicsComponentTable::~CDPhysicsComponentTable() { for (auto e : m_entries) { if (e.second) delete e.second; } @@ -36,10 +36,6 @@ CDPhysicsComponentTable::~CDPhysicsComponentTable(void) { m_entries.clear(); } -std::string CDPhysicsComponentTable::GetName(void) const { - return "PhysicsComponent"; -} - CDPhysicsComponent* CDPhysicsComponentTable::GetByID(unsigned int componentID) { for (auto e : m_entries) { if (e.first == componentID) return e.second; diff --git a/dDatabase/Tables/CDPhysicsComponentTable.h b/dDatabase/Tables/CDPhysicsComponentTable.h index c5805da3..e63d337d 100644 --- a/dDatabase/Tables/CDPhysicsComponentTable.h +++ b/dDatabase/Tables/CDPhysicsComponentTable.h @@ -21,12 +21,12 @@ struct CDPhysicsComponent { UNUSED(std::string gravityVolumeAsset); }; -class CDPhysicsComponentTable : public CDTable { +class CDPhysicsComponentTable : public CDTable<CDPhysicsComponentTable> { public: - CDPhysicsComponentTable(void); - ~CDPhysicsComponentTable(void); + CDPhysicsComponentTable(); + ~CDPhysicsComponentTable(); - std::string GetName(void) const override; + static const std::string GetTableName() { return "PhysicsComponent"; }; CDPhysicsComponent* GetByID(unsigned int componentID); private: diff --git a/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp b/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp index 127ebc9d..1fead45e 100644 --- a/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp +++ b/dDatabase/Tables/CDPropertyEntranceComponentTable.cpp @@ -32,12 +32,6 @@ CDPropertyEntranceComponentTable::CDPropertyEntranceComponentTable() { tableData.finalize(); } -CDPropertyEntranceComponentTable::~CDPropertyEntranceComponentTable(void) = default; - -std::string CDPropertyEntranceComponentTable::GetName() const { - return "PropertyEntranceComponent"; -} - CDPropertyEntranceComponent CDPropertyEntranceComponentTable::GetByID(uint32_t id) { for (const auto& entry : entries) { if (entry.id == id) diff --git a/dDatabase/Tables/CDPropertyEntranceComponentTable.h b/dDatabase/Tables/CDPropertyEntranceComponentTable.h index fa0603c0..925fd1be 100644 --- a/dDatabase/Tables/CDPropertyEntranceComponentTable.h +++ b/dDatabase/Tables/CDPropertyEntranceComponentTable.h @@ -9,31 +9,13 @@ struct CDPropertyEntranceComponent { std::string groupType; }; -class CDPropertyEntranceComponentTable : public CDTable { +class CDPropertyEntranceComponentTable : public CDTable<CDPropertyEntranceComponentTable> { public: - //! Constructor CDPropertyEntranceComponentTable(); - - //! Destructor - ~CDPropertyEntranceComponentTable(); - - //! Returns the table's name - /*! - \return The table name - */ - [[nodiscard]] std::string GetName() const override; - - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + // Queries the table with a custom "where" clause CDPropertyEntranceComponent GetByID(uint32_t id); - //! Gets all the entries in the table - /*! - \return The entries - */ + // Gets all the entries in the table [[nodiscard]] std::vector<CDPropertyEntranceComponent> GetEntries() const { return entries; } private: std::vector<CDPropertyEntranceComponent> entries{}; diff --git a/dDatabase/Tables/CDPropertyTemplateTable.cpp b/dDatabase/Tables/CDPropertyTemplateTable.cpp index bf56da7b..4caa6dc5 100644 --- a/dDatabase/Tables/CDPropertyTemplateTable.cpp +++ b/dDatabase/Tables/CDPropertyTemplateTable.cpp @@ -30,12 +30,6 @@ CDPropertyTemplateTable::CDPropertyTemplateTable() { tableData.finalize(); } -CDPropertyTemplateTable::~CDPropertyTemplateTable() = default; - -std::string CDPropertyTemplateTable::GetName() const { - return "PropertyTemplate"; -} - CDPropertyTemplate CDPropertyTemplateTable::GetByMapID(uint32_t mapID) { for (const auto& entry : entries) { if (entry.mapID == mapID) diff --git a/dDatabase/Tables/CDPropertyTemplateTable.h b/dDatabase/Tables/CDPropertyTemplateTable.h index a266932b..cb075dbf 100644 --- a/dDatabase/Tables/CDPropertyTemplateTable.h +++ b/dDatabase/Tables/CDPropertyTemplateTable.h @@ -8,12 +8,11 @@ struct CDPropertyTemplate { std::string spawnName; }; -class CDPropertyTemplateTable : public CDTable { +class CDPropertyTemplateTable : public CDTable<CDPropertyTemplateTable> { public: CDPropertyTemplateTable(); - ~CDPropertyTemplateTable(); - [[nodiscard]] std::string GetName() const override; + static const std::string GetTableName() { return "PropertyTemplate"; }; CDPropertyTemplate GetByMapID(uint32_t mapID); private: std::vector<CDPropertyTemplate> entries{}; diff --git a/dDatabase/Tables/CDProximityMonitorComponentTable.cpp b/dDatabase/Tables/CDProximityMonitorComponentTable.cpp index 98cde098..688de056 100644 --- a/dDatabase/Tables/CDProximityMonitorComponentTable.cpp +++ b/dDatabase/Tables/CDProximityMonitorComponentTable.cpp @@ -33,14 +33,6 @@ CDProximityMonitorComponentTable::CDProximityMonitorComponentTable(void) { tableData.finalize(); } -//! Destructor -CDProximityMonitorComponentTable::~CDProximityMonitorComponentTable(void) {} - -//! Returns the table's name -std::string CDProximityMonitorComponentTable::GetName(void) const { - return "ProximityMonitorComponent"; -} - //! Queries the table with a custom "where" clause std::vector<CDProximityMonitorComponent> CDProximityMonitorComponentTable::Query(std::function<bool(CDProximityMonitorComponent)> predicate) { diff --git a/dDatabase/Tables/CDProximityMonitorComponentTable.h b/dDatabase/Tables/CDProximityMonitorComponentTable.h index 007bb916..38b7d43b 100644 --- a/dDatabase/Tables/CDProximityMonitorComponentTable.h +++ b/dDatabase/Tables/CDProximityMonitorComponentTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDProximityMonitorComponentTable.hpp - \brief Contains data for the ProximityMonitorComponent table - */ - - //! ProximityMonitorComponent Entry Struct struct CDProximityMonitorComponent { unsigned int id; std::string Proximities; @@ -16,36 +10,14 @@ struct CDProximityMonitorComponent { bool LoadOnServer; }; - -//! ProximityMonitorComponent table -class CDProximityMonitorComponentTable : public CDTable { +class CDProximityMonitorComponentTable : public CDTable<CDProximityMonitorComponentTable> { private: std::vector<CDProximityMonitorComponent> entries; public: - - //! Constructor CDProximityMonitorComponentTable(void); - - //! Destructor - ~CDProximityMonitorComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ std::vector<CDProximityMonitorComponent> Query(std::function<bool(CDProximityMonitorComponent)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDProximityMonitorComponent> GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDRailActivatorComponent.cpp b/dDatabase/Tables/CDRailActivatorComponent.cpp index 4d1b5e7e..2ff8990d 100644 --- a/dDatabase/Tables/CDRailActivatorComponent.cpp +++ b/dDatabase/Tables/CDRailActivatorComponent.cpp @@ -43,12 +43,6 @@ CDRailActivatorComponentTable::CDRailActivatorComponentTable() { tableData.finalize(); } -CDRailActivatorComponentTable::~CDRailActivatorComponentTable() = default; - -std::string CDRailActivatorComponentTable::GetName() const { - return "RailActivatorComponent"; -} - CDRailActivatorComponent CDRailActivatorComponentTable::GetEntryByID(int32_t id) const { for (const auto& entry : m_Entries) { if (entry.id == id) diff --git a/dDatabase/Tables/CDRailActivatorComponent.h b/dDatabase/Tables/CDRailActivatorComponent.h index b8313e96..03dd0525 100644 --- a/dDatabase/Tables/CDRailActivatorComponent.h +++ b/dDatabase/Tables/CDRailActivatorComponent.h @@ -20,12 +20,10 @@ struct CDRailActivatorComponent { bool showNameBillboard; }; -class CDRailActivatorComponentTable : public CDTable { +class CDRailActivatorComponentTable : public CDTable<CDRailActivatorComponentTable> { public: CDRailActivatorComponentTable(); - ~CDRailActivatorComponentTable(); - - std::string GetName() const override; + static const std::string GetTableName() { return "RailActivatorComponent"; }; [[nodiscard]] CDRailActivatorComponent GetEntryByID(int32_t id) const; [[nodiscard]] std::vector<CDRailActivatorComponent> GetEntries() const; private: diff --git a/dDatabase/Tables/CDRarityTableTable.cpp b/dDatabase/Tables/CDRarityTableTable.cpp index cfa8d01c..0b1212c0 100644 --- a/dDatabase/Tables/CDRarityTableTable.cpp +++ b/dDatabase/Tables/CDRarityTableTable.cpp @@ -33,14 +33,6 @@ CDRarityTableTable::CDRarityTableTable(void) { tableData.finalize(); } -//! Destructor -CDRarityTableTable::~CDRarityTableTable(void) {} - -//! Returns the table's name -std::string CDRarityTableTable::GetName(void) const { - return "RarityTable"; -} - //! Queries the table with a custom "where" clause std::vector<CDRarityTable> CDRarityTableTable::Query(std::function<bool(CDRarityTable)> predicate) { diff --git a/dDatabase/Tables/CDRarityTableTable.h b/dDatabase/Tables/CDRarityTableTable.h index 55cfec4b..592346ed 100644 --- a/dDatabase/Tables/CDRarityTableTable.h +++ b/dDatabase/Tables/CDRarityTableTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDRarityTableTable.hpp - \brief Contains data for the RarityTable table - */ - - //! RarityTable Entry Struct struct CDRarityTable { unsigned int id; float randmax; @@ -32,37 +26,15 @@ struct CDRarityTable { } }; - -//! RarityTable table -class CDRarityTableTable : public CDTable { +class CDRarityTableTable : public CDTable<CDRarityTableTable> { private: std::vector<CDRarityTable> entries; public: - - //! Constructor - CDRarityTableTable(void); - - //! Destructor - ~CDRarityTableTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDRarityTableTable(); + // Queries the table with a custom "where" clause std::vector<CDRarityTable> Query(std::function<bool(CDRarityTable)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ - const std::vector<CDRarityTable>& GetEntries(void) const; - + const std::vector<CDRarityTable>& GetEntries() const; }; diff --git a/dDatabase/Tables/CDRebuildComponentTable.cpp b/dDatabase/Tables/CDRebuildComponentTable.cpp index 111592d4..d5c386d1 100644 --- a/dDatabase/Tables/CDRebuildComponentTable.cpp +++ b/dDatabase/Tables/CDRebuildComponentTable.cpp @@ -39,14 +39,6 @@ CDRebuildComponentTable::CDRebuildComponentTable(void) { tableData.finalize(); } -//! Destructor -CDRebuildComponentTable::~CDRebuildComponentTable(void) {} - -//! Returns the table's name -std::string CDRebuildComponentTable::GetName(void) const { - return "RebuildComponent"; -} - //! Queries the table with a custom "where" clause std::vector<CDRebuildComponent> CDRebuildComponentTable::Query(std::function<bool(CDRebuildComponent)> predicate) { diff --git a/dDatabase/Tables/CDRebuildComponentTable.h b/dDatabase/Tables/CDRebuildComponentTable.h index bdc2da8a..db70a47d 100644 --- a/dDatabase/Tables/CDRebuildComponentTable.h +++ b/dDatabase/Tables/CDRebuildComponentTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDRebuildComponentTable.hpp - \brief Contains data for the RebuildComponent table - */ - - //! RebuildComponent Struct struct CDRebuildComponent { unsigned int id; //!< The component Id float reset_time; //!< The reset time @@ -22,36 +16,15 @@ struct CDRebuildComponent { float time_before_smash; //!< The time before smash }; -//! ObjectSkills table -class CDRebuildComponentTable : public CDTable { +class CDRebuildComponentTable : public CDTable<CDRebuildComponentTable> { private: std::vector<CDRebuildComponent> entries; public: - - //! Constructor - CDRebuildComponentTable(void); - - //! Destructor - ~CDRebuildComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDRebuildComponentTable(); + // Queries the table with a custom "where" clause std::vector<CDRebuildComponent> Query(std::function<bool(CDRebuildComponent)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ - std::vector<CDRebuildComponent> GetEntries(void) const; - + std::vector<CDRebuildComponent> GetEntries() const; }; diff --git a/dDatabase/Tables/CDRewardsTable.cpp b/dDatabase/Tables/CDRewardsTable.cpp index a53e02b5..55672add 100644 --- a/dDatabase/Tables/CDRewardsTable.cpp +++ b/dDatabase/Tables/CDRewardsTable.cpp @@ -26,10 +26,6 @@ CDRewardsTable::~CDRewardsTable(void) { m_entries.clear(); } -std::string CDRewardsTable::GetName(void) const { - return "Rewards"; -} - std::vector<CDRewards*> CDRewardsTable::GetByLevelID(uint32_t levelID) { std::vector<CDRewards*> result{}; for (const auto& e : m_entries) { diff --git a/dDatabase/Tables/CDRewardsTable.h b/dDatabase/Tables/CDRewardsTable.h index 2edfd2b3..2e079a83 100644 --- a/dDatabase/Tables/CDRewardsTable.h +++ b/dDatabase/Tables/CDRewardsTable.h @@ -11,12 +11,12 @@ struct CDRewards { int32_t count; }; -class CDRewardsTable : public CDTable { +class CDRewardsTable : public CDTable<CDRewardsTable> { public: - CDRewardsTable(void); - ~CDRewardsTable(void); + CDRewardsTable(); + ~CDRewardsTable(); - std::string GetName(void) const override; + static const std::string GetTableName() { return "Rewards"; }; std::vector<CDRewards*> GetByLevelID(uint32_t levelID); private: diff --git a/dDatabase/Tables/CDScriptComponentTable.cpp b/dDatabase/Tables/CDScriptComponentTable.cpp index d91dcee9..8050c139 100644 --- a/dDatabase/Tables/CDScriptComponentTable.cpp +++ b/dDatabase/Tables/CDScriptComponentTable.cpp @@ -29,14 +29,6 @@ CDScriptComponentTable::CDScriptComponentTable(void) { tableData.finalize(); } -//! Destructor -CDScriptComponentTable::~CDScriptComponentTable(void) {} - -//! Returns the table's name -std::string CDScriptComponentTable::GetName(void) const { - return "ScriptComponent"; -} - const CDScriptComponent& CDScriptComponentTable::GetByID(unsigned int id) { std::map<unsigned int, CDScriptComponent>::iterator it = this->entries.find(id); if (it != this->entries.end()) { diff --git a/dDatabase/Tables/CDScriptComponentTable.h b/dDatabase/Tables/CDScriptComponentTable.h index 92534cc0..77453939 100644 --- a/dDatabase/Tables/CDScriptComponentTable.h +++ b/dDatabase/Tables/CDScriptComponentTable.h @@ -3,44 +3,20 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDScriptComponentTable.hpp - \brief Contains data for the ScriptComponent table - */ - - //! ScriptComponent Struct struct CDScriptComponent { unsigned int id; //!< The component ID std::string script_name; //!< The script name std::string client_script_name; //!< The client script name }; -//! ObjectSkills table -class CDScriptComponentTable : public CDTable { +class CDScriptComponentTable : public CDTable<CDScriptComponentTable> { private: std::map<unsigned int, CDScriptComponent> entries; CDScriptComponent m_ToReturnWhenNoneFound; public: - //! Gets an entry by ID + CDScriptComponentTable(); + // Gets an entry by scriptID const CDScriptComponent& GetByID(unsigned int id); - - //! Constructor - CDScriptComponentTable(void); - - //! Destructor - ~CDScriptComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ - }; diff --git a/dDatabase/Tables/CDSkillBehaviorTable.cpp b/dDatabase/Tables/CDSkillBehaviorTable.cpp index b6b601a1..c5df78ef 100644 --- a/dDatabase/Tables/CDSkillBehaviorTable.cpp +++ b/dDatabase/Tables/CDSkillBehaviorTable.cpp @@ -51,24 +51,8 @@ CDSkillBehaviorTable::CDSkillBehaviorTable(void) { tableData.finalize(); } -//! Destructor -CDSkillBehaviorTable::~CDSkillBehaviorTable(void) {} - -//! Returns the table's name -std::string CDSkillBehaviorTable::GetName(void) const { - return "SkillBehavior"; -} - //! Queries the table with a custom "where" clause std::vector<CDSkillBehavior> CDSkillBehaviorTable::Query(std::function<bool(CDSkillBehavior)> predicate) { - - /*std::vector<CDSkillBehavior> data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data;*/ - - //Logger::LogDebug("CDSkillBehaviorTable", "The 'Query' function is no longer working! Please use GetSkillByID instead!"); std::vector<CDSkillBehavior> data; //So MSVC shuts up return data; } diff --git a/dDatabase/Tables/CDSkillBehaviorTable.h b/dDatabase/Tables/CDSkillBehaviorTable.h index da8676db..eb3094e0 100644 --- a/dDatabase/Tables/CDSkillBehaviorTable.h +++ b/dDatabase/Tables/CDSkillBehaviorTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDSkillBehaviorTable.hpp - \brief Contains data for the SkillBehavior table - */ - - //! ZoneTable Struct struct CDSkillBehavior { unsigned int skillID; //!< The Skill ID of the skill UNUSED(unsigned int locStatus); //!< ?? @@ -31,33 +25,17 @@ struct CDSkillBehavior { UNUSED(unsigned int cancelType); //!< The cancel type (?) }; -//! SkillBehavior table -class CDSkillBehaviorTable : public CDTable { +class CDSkillBehaviorTable : public CDTable<CDSkillBehaviorTable> { private: std::map<unsigned int, CDSkillBehavior> entries; CDSkillBehavior m_empty; public: - - //! Constructor - CDSkillBehaviorTable(void); - - //! Destructor - ~CDSkillBehaviorTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDSkillBehaviorTable(); + // Queries the table with a custom "where" clause std::vector<CDSkillBehavior> Query(std::function<bool(CDSkillBehavior)> predicate); - //! Gets an entry by ID + // Gets an entry by skillID const CDSkillBehavior& GetSkillByID(unsigned int skillID); }; diff --git a/dDatabase/Tables/CDTable.h b/dDatabase/Tables/CDTable.h index cd05782d..fca16eb8 100644 --- a/dDatabase/Tables/CDTable.h +++ b/dDatabase/Tables/CDTable.h @@ -1,9 +1,8 @@ #pragma once -// Custom Classes -#include "../CDClientDatabase.h" +#include "CDClientDatabase.h" +#include "Singleton.h" -// C++ #include <functional> #include <string> #include <vector> @@ -19,23 +18,8 @@ #pragma warning (disable : 4244) //Disable double to float conversion warnings #pragma warning (disable : 4715) //Disable "not all control paths return a value" -#if defined(__unix) || defined(__APPLE__) -//For Linux: -typedef __int64_t __int64; -#endif - -/*! - \file CDTable.hpp - \brief A virtual class for CDClient Tables - */ - - //! The base class for all CD tables -class CDTable { -public: - - //! Returns the table's name - /*! - \return The table name - */ - virtual std::string GetName() const = 0; +template<class Table> +class CDTable : public Singleton<Table> { +protected: + virtual ~CDTable() = default; }; diff --git a/dDatabase/Tables/CDVendorComponentTable.cpp b/dDatabase/Tables/CDVendorComponentTable.cpp index 86d87d4b..dfff2e20 100644 --- a/dDatabase/Tables/CDVendorComponentTable.cpp +++ b/dDatabase/Tables/CDVendorComponentTable.cpp @@ -34,14 +34,6 @@ CDVendorComponentTable::CDVendorComponentTable(void) { tableData.finalize(); } -//! Destructor -CDVendorComponentTable::~CDVendorComponentTable(void) {} - -//! Returns the table's name -std::string CDVendorComponentTable::GetName(void) const { - return "VendorComponent"; -} - //! Queries the table with a custom "where" clause std::vector<CDVendorComponent> CDVendorComponentTable::Query(std::function<bool(CDVendorComponent)> predicate) { diff --git a/dDatabase/Tables/CDVendorComponentTable.h b/dDatabase/Tables/CDVendorComponentTable.h index 2e0fb9e4..f2666d7e 100644 --- a/dDatabase/Tables/CDVendorComponentTable.h +++ b/dDatabase/Tables/CDVendorComponentTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDVendorComponentTable.hpp - \brief Contains data for the VendorComponent table - */ - - //! VendorComponent Struct struct CDVendorComponent { unsigned int id; //!< The Component ID float buyScalar; //!< Buy Scalar (what does that mean?) @@ -17,36 +11,15 @@ struct CDVendorComponent { unsigned int LootMatrixIndex; //!< LootMatrixIndex of the vendor's items }; -//! VendorComponent table -class CDVendorComponentTable : public CDTable { +class CDVendorComponentTable : public CDTable<CDVendorComponentTable> { private: std::vector<CDVendorComponent> entries; public: - - //! Constructor - CDVendorComponentTable(void); - - //! Destructor - ~CDVendorComponentTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a custom "where" clause - /*! - \param predicate The predicate - */ + CDVendorComponentTable(); + // Queries the table with a custom "where" clause std::vector<CDVendorComponent> Query(std::function<bool(CDVendorComponent)> predicate); - //! Gets all the entries in the table - /*! - \return The entries - */ std::vector<CDVendorComponent> GetEntries(void) const; - }; diff --git a/dDatabase/Tables/CDZoneTableTable.cpp b/dDatabase/Tables/CDZoneTableTable.cpp index 04f7d102..bafbf8fe 100644 --- a/dDatabase/Tables/CDZoneTableTable.cpp +++ b/dDatabase/Tables/CDZoneTableTable.cpp @@ -53,14 +53,6 @@ CDZoneTableTable::CDZoneTableTable(void) { tableData.finalize(); } -//! Destructor -CDZoneTableTable::~CDZoneTableTable(void) {} - -//! Returns the table's name -std::string CDZoneTableTable::GetName(void) const { - return "ZoneTable"; -} - //! Queries the table with a zoneID to find. const CDZoneTable* CDZoneTableTable::Query(unsigned int zoneID) { const auto& iter = m_Entries.find(zoneID); diff --git a/dDatabase/Tables/CDZoneTableTable.h b/dDatabase/Tables/CDZoneTableTable.h index c115a38a..f844fd25 100644 --- a/dDatabase/Tables/CDZoneTableTable.h +++ b/dDatabase/Tables/CDZoneTableTable.h @@ -3,12 +3,6 @@ // Custom Classes #include "CDTable.h" -/*! - \file CDZoneTableTable.hpp - \brief Contains data for the ZoneTable table - */ - - //! ZoneTable Struct struct CDZoneTable { unsigned int zoneID; //!< The Zone ID of the object unsigned int locStatus; //!< The Locale Status(?) @@ -39,28 +33,13 @@ struct CDZoneTable { UNUSED(bool mountsAllowed); //!< Whether or not mounts are allowed }; -//! ZoneTable table -class CDZoneTableTable : public CDTable { +class CDZoneTableTable : public CDTable<CDZoneTableTable> { private: std::map<unsigned int, CDZoneTable> m_Entries; public: + CDZoneTableTable(); - //! Constructor - CDZoneTableTable(void); - - //! Destructor - ~CDZoneTableTable(void); - - //! Returns the table's name - /*! - \return The table name - */ - std::string GetName(void) const override; - - //! Queries the table with a zoneID to find. - /*! - \param id The zoneID - */ + // Queries the table with a zoneID to find. const CDZoneTable* Query(unsigned int zoneID); }; diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 77692966..13507527 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -72,6 +72,18 @@ #include "TriggerComponent.h" #include "eReplicaComponentType.h" +// Table includes +#include "CDComponentsRegistryTable.h" +#include "CDCurrencyTableTable.h" +#include "CDMovementAIComponentTable.h" +#include "CDProximityMonitorComponentTable.h" +#include "CDRebuildComponentTable.h" +#include "CDObjectSkillsTable.h" +#include "CDObjectsTable.h" +#include "CDScriptComponentTable.h" +#include "CDSkillBehaviorTable.h" +#include "CDZoneTableTable.h" + Entity::Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity) { m_ObjectID = objectID; m_TemplateID = info.lot; @@ -158,7 +170,7 @@ void Entity::Initialize() { } // Get the registry table - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); /** * Special case for BBB models. They have components not corresponding to the registry. @@ -330,7 +342,7 @@ void Entity::Initialize() { if (rebuildComponentID > 0) componentID = rebuildComponentID; if (buffComponentID > 0) componentID = buffComponentID; - CDDestructibleComponentTable* destCompTable = CDClientManager::Instance()->GetTable<CDDestructibleComponentTable>("DestructibleComponent"); + CDDestructibleComponentTable* destCompTable = CDClientManager::Instance().GetTable<CDDestructibleComponentTable>(); std::vector<CDDestructibleComponent> destCompData = destCompTable->Query([=](CDDestructibleComponent entry) { return (entry.id == componentID); }); if (buffComponentID > 0 || collectibleComponentID > 0) { @@ -362,7 +374,7 @@ void Entity::Initialize() { uint32_t npcMinLevel = destCompData[0].level; uint32_t currencyIndex = destCompData[0].CurrencyIndex; - CDCurrencyTableTable* currencyTable = CDClientManager::Instance()->GetTable<CDCurrencyTableTable>("CurrencyTable"); + CDCurrencyTableTable* currencyTable = CDClientManager::Instance().GetTable<CDCurrencyTableTable>(); std::vector<CDCurrencyTable> currencyValues = currencyTable->Query([=](CDCurrencyTable entry) { return (entry.currencyIndex == currencyIndex && entry.npcminlevel == npcMinLevel); }); if (currencyValues.size() > 0) { @@ -440,7 +452,7 @@ void Entity::Initialize() { * This is a bit of a mess */ - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance()->GetTable<CDScriptComponentTable>("ScriptComponent"); + CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable<CDScriptComponentTable>(); int32_t scriptComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::SCRIPT, -1); std::string scriptName = ""; @@ -489,7 +501,7 @@ void Entity::Initialize() { // ZoneControl script if (m_TemplateID == 2365) { - CDZoneTableTable* zoneTable = CDClientManager::Instance()->GetTable<CDZoneTableTable>("ZoneTable"); + CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable<CDZoneTableTable>(); const auto zoneID = dZoneManager::Instance()->GetZoneID(); const CDZoneTable* zoneData = zoneTable->Query(zoneID.GetMapID()); @@ -517,7 +529,7 @@ void Entity::Initialize() { RebuildComponent* comp = new RebuildComponent(this); m_Components.insert(std::make_pair(eReplicaComponentType::QUICK_BUILD, comp)); - CDRebuildComponentTable* rebCompTable = CDClientManager::Instance()->GetTable<CDRebuildComponentTable>("RebuildComponent"); + CDRebuildComponentTable* rebCompTable = CDClientManager::Instance().GetTable<CDRebuildComponentTable>(); std::vector<CDRebuildComponent> rebCompData = rebCompTable->Query([=](CDRebuildComponent entry) { return (entry.id == rebuildComponentID); }); if (rebCompData.size() > 0) { @@ -637,7 +649,7 @@ void Entity::Initialize() { int movementAIID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::MOVEMENT_AI); if (movementAIID > 0) { - CDMovementAIComponentTable* moveAITable = CDClientManager::Instance()->GetTable<CDMovementAIComponentTable>("MovementAIComponent"); + CDMovementAIComponentTable* moveAITable = CDClientManager::Instance().GetTable<CDMovementAIComponentTable>(); std::vector<CDMovementAIComponent> moveAIComp = moveAITable->Query([=](CDMovementAIComponent entry) {return (entry.id == movementAIID); }); if (moveAIComp.size() > 0) { @@ -696,7 +708,7 @@ void Entity::Initialize() { int proximityMonitorID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROXIMITY_MONITOR); if (proximityMonitorID > 0) { - CDProximityMonitorComponentTable* proxCompTable = CDClientManager::Instance()->GetTable<CDProximityMonitorComponentTable>("ProximityMonitorComponent"); + CDProximityMonitorComponentTable* proxCompTable = CDClientManager::Instance().GetTable<CDProximityMonitorComponentTable>(); std::vector<CDProximityMonitorComponent> proxCompData = proxCompTable->Query([=](CDProximityMonitorComponent entry) { return (entry.id == proximityMonitorID); }); if (proxCompData.size() > 0) { std::vector<std::string> proximityStr = GeneralUtils::SplitString(proxCompData[0].Proximities, ','); @@ -1576,7 +1588,7 @@ void Entity::PickupItem(const LWOOBJID& objectID) { InventoryComponent* inv = GetComponent<InventoryComponent>(); if (!inv) return; - CDObjectsTable* objectsTable = CDClientManager::Instance()->GetTable<CDObjectsTable>("Objects"); + CDObjectsTable* objectsTable = CDClientManager::Instance().GetTable<CDObjectsTable>(); auto& droppedLoot = static_cast<Player*>(this)->GetDroppedLoot(); @@ -1589,10 +1601,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>("ObjectSkills"); + CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable<CDObjectSkillsTable>(); std::vector<CDObjectSkills> skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == p.second.lot); }); for (CDObjectSkills skill : skills) { - CDSkillBehaviorTable* skillBehTable = CDClientManager::Instance()->GetTable<CDSkillBehaviorTable>("SkillBehavior"); + CDSkillBehaviorTable* skillBehTable = CDClientManager::Instance().GetTable<CDSkillBehaviorTable>(); CDSkillBehavior behaviorData = skillBehTable->GetSkillByID(skill.skillID); SkillComponent::HandleUnmanaged(behaviorData.behaviorID, GetObjectID()); diff --git a/dGame/LeaderboardManager.cpp b/dGame/LeaderboardManager.cpp index a0df940f..d85a95d4 100644 --- a/dGame/LeaderboardManager.cpp +++ b/dGame/LeaderboardManager.cpp @@ -8,6 +8,10 @@ #include "dLogger.h" #include "dConfig.h" #include "CDClientManager.h" +#include "GeneralUtils.h" +#include "Entity.h" + +#include "CDActivitiesTable.h" Leaderboard::Leaderboard(uint32_t gameID, uint32_t infoType, bool weekly, std::vector<LeaderboardEntry> entries, LWOOBJID relatedPlayer, LeaderboardType leaderboardType) { @@ -273,7 +277,7 @@ void LeaderboardManager::SendLeaderboard(uint32_t gameID, InfoType infoType, boo } LeaderboardType LeaderboardManager::GetLeaderboardType(uint32_t gameID) { - auto* activitiesTable = CDClientManager::Instance()->GetTable<CDActivitiesTable>("Activities"); + auto* activitiesTable = CDClientManager::Instance().GetTable<CDActivitiesTable>(); std::vector<CDActivities> activities = activitiesTable->Query([=](const CDActivities& entry) { return (entry.ActivityID == gameID); }); diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index c8c1a1de..2a269ddc 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -73,13 +73,14 @@ #include "EntityManager.h" #include "RenderComponent.h" #include "DestroyableComponent.h" +#include "CDBehaviorTemplateTable.h" std::unordered_map<uint32_t, Behavior*> Behavior::Cache = {}; CDBehaviorParameterTable* Behavior::BehaviorParameterTable = nullptr; Behavior* Behavior::GetBehavior(const uint32_t behaviorId) { if (BehaviorParameterTable == nullptr) { - BehaviorParameterTable = CDClientManager::Instance()->GetTable<CDBehaviorParameterTable>("BehaviorParameter"); + BehaviorParameterTable = CDClientManager::Instance().GetTable<CDBehaviorParameterTable>(); } const auto pair = Cache.find(behaviorId); @@ -290,7 +291,7 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) { } BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) { - auto behaviorTemplateTable = CDClientManager::Instance()->GetTable<CDBehaviorTemplateTable>("BehaviorTemplate"); + auto behaviorTemplateTable = CDClientManager::Instance().GetTable<CDBehaviorTemplateTable>(); BehaviorTemplates templateID = BehaviorTemplates::BEHAVIOR_EMPTY; // Find behavior template by its behavior id. Default to 0. @@ -398,7 +399,7 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID } Behavior::Behavior(const uint32_t behaviorId) { - auto behaviorTemplateTable = CDClientManager::Instance()->GetTable<CDBehaviorTemplateTable>("BehaviorTemplate"); + auto behaviorTemplateTable = CDClientManager::Instance().GetTable<CDBehaviorTemplateTable>(); CDBehaviorTemplate templateInDatabase{}; @@ -441,7 +442,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<CDBehaviorParameterTable>("BehaviorParameter"); + if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance().GetTable<CDBehaviorParameterTable>(); return BehaviorParameterTable->GetValue(this->m_behaviorId, name, defaultValue); } @@ -469,7 +470,7 @@ Behavior* Behavior::GetAction(float value) const { std::map<std::string, float> Behavior::GetParameterNames() const { std::map<std::string, float> templatesInDatabase; // Find behavior template by its behavior id. - if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance()->GetTable<CDBehaviorParameterTable>("BehaviorParameter"); + if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance().GetTable<CDBehaviorParameterTable>(); if (BehaviorParameterTable) { templatesInDatabase = BehaviorParameterTable->GetParametersByBehaviorID(this->m_behaviorId); } diff --git a/dGame/dBehaviors/OverTimeBehavior.cpp b/dGame/dBehaviors/OverTimeBehavior.cpp index 20dd89af..5afbbd26 100644 --- a/dGame/dBehaviors/OverTimeBehavior.cpp +++ b/dGame/dBehaviors/OverTimeBehavior.cpp @@ -9,6 +9,8 @@ #include "CDClientDatabase.h" #include "CDClientManager.h" +#include "CDSkillBehaviorTable.h" + void OverTimeBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { const auto originator = context->originator; @@ -39,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>("SkillBehavior"); + CDSkillBehaviorTable* skillTable = CDClientManager::Instance().GetTable<CDSkillBehaviorTable>(); m_ActionBehaviorId = skillTable->GetSkillByID(m_Action).behaviorID; m_Delay = GetFloat("delay"); diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index a5255b07..64c739f5 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -23,6 +23,8 @@ #include "RebuildComponent.h" #include "DestroyableComponent.h" #include "Metrics.hpp" +#include "CDComponentsRegistryTable.h" +#include "CDPhysicsComponentTable.h" BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id): Component(parent) { m_Target = LWOOBJID_EMPTY; @@ -105,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>("ComponentsRegistry"); + CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); auto componentID = componentRegistryTable->GetByIDAndType(parent->GetLOT(), eReplicaComponentType::CONTROLLABLE_PHYSICS); - CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance()->GetTable<CDPhysicsComponentTable>("PhysicsComponent"); + CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance().GetTable<CDPhysicsComponentTable>(); if (physicsComponentTable != nullptr) { auto* info = physicsComponentTable->GetByID(componentID); diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index 974d0bd2..68b5182c 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -10,6 +10,7 @@ #include "ControllablePhysicsComponent.h" #include "EntityManager.h" #include "CDClientManager.h" +#include "CDSkillBehaviorTable.h" std::unordered_map<int32_t, std::vector<BuffParameter>> BuffComponent::m_Cache{}; @@ -101,7 +102,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<CDSkillBehaviorTable>("SkillBehavior"); + auto* behaviorTemplateTable = CDClientManager::Instance().GetTable<CDSkillBehaviorTable>(); behaviorID = behaviorTemplateTable->GetSkillByID(parameter.values[0]).behaviorID; stacks = static_cast<int32_t>(parameter.values[1]); diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 51d68a12..c2d72941 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -34,6 +34,8 @@ #include "WorldConfig.h" #include "eMissionTaskType.h" +#include "CDComponentsRegistryTable.h" + DestroyableComponent::DestroyableComponent(Entity* parent) : Component(parent) { m_iArmor = 0; m_fMaxArmor = 0.0f; @@ -74,7 +76,7 @@ DestroyableComponent::~DestroyableComponent() { } void DestroyableComponent::Reinitialize(LOT templateID) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); int32_t buffComponentID = compRegistryTable->GetByIDAndType(templateID, eReplicaComponentType::BUFF); int32_t collectibleComponentID = compRegistryTable->GetByIDAndType(templateID, eReplicaComponentType::COLLECTIBLE); @@ -85,7 +87,7 @@ void DestroyableComponent::Reinitialize(LOT templateID) { if (rebuildComponentID > 0) componentID = rebuildComponentID; if (buffComponentID > 0) componentID = buffComponentID; - CDDestructibleComponentTable* destCompTable = CDClientManager::Instance()->GetTable<CDDestructibleComponentTable>("DestructibleComponent"); + CDDestructibleComponentTable* destCompTable = CDClientManager::Instance().GetTable<CDDestructibleComponentTable>(); std::vector<CDDestructibleComponent> 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 df292e2a..dc8fdbdc 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -30,6 +30,12 @@ #include "CppScripts.h" #include "eMissionTaskType.h" +#include "CDComponentsRegistryTable.h" +#include "CDInventoryComponentTable.h" +#include "CDScriptComponentTable.h" +#include "CDObjectSkillsTable.h" +#include "CDSkillBehaviorTable.h" + InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document): Component(parent) { this->m_Dirty = true; this->m_Equipped = {}; @@ -47,10 +53,10 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do return; } - auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + auto* compRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); const auto componentId = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::INVENTORY); - auto* inventoryComponentTable = CDClientManager::Instance()->GetTable<CDInventoryComponentTable>("InventoryComponent"); + auto* inventoryComponentTable = CDClientManager::Instance().GetTable<CDInventoryComponentTable>(); auto items = inventoryComponentTable->Query([=](const CDInventoryComponent entry) { return entry.id == componentId; }); auto slot = 0u; @@ -912,11 +918,11 @@ void InventoryComponent::UnEquipItem(Item* item) { void InventoryComponent::EquipScripts(Item* equippedItem) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); if (!compRegistryTable) return; int32_t scriptComponentID = compRegistryTable->GetByIDAndType(equippedItem->GetLot(), eReplicaComponentType::SCRIPT, -1); if (scriptComponentID > -1) { - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance()->GetTable<CDScriptComponentTable>("ScriptComponent"); + CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable<CDScriptComponentTable>(); CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name); if (!itemScript) { @@ -927,11 +933,11 @@ void InventoryComponent::EquipScripts(Item* equippedItem) { } void InventoryComponent::UnequipScripts(Item* unequippedItem) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); if (!compRegistryTable) return; int32_t scriptComponentID = compRegistryTable->GetByIDAndType(unequippedItem->GetLot(), eReplicaComponentType::SCRIPT, -1); if (scriptComponentID > -1) { - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance()->GetTable<CDScriptComponentTable>("ScriptComponent"); + CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable<CDScriptComponentTable>(); CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name); if (!itemScript) { @@ -1306,7 +1312,7 @@ bool InventoryComponent::IsTransferInventory(eInventoryType type) { } uint32_t InventoryComponent::FindSkill(const LOT lot) { - auto* table = CDClientManager::Instance()->GetTable<CDObjectSkillsTable>("ObjectSkills"); + auto* table = CDClientManager::Instance().GetTable<CDObjectSkillsTable>(); const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast<unsigned int>(lot); @@ -1324,8 +1330,8 @@ uint32_t InventoryComponent::FindSkill(const LOT lot) { std::vector<uint32_t> InventoryComponent::FindBuffs(Item* item, bool castOnEquip) const { std::vector<uint32_t> buffs; if (item == nullptr) return buffs; - auto* table = CDClientManager::Instance()->GetTable<CDObjectSkillsTable>("ObjectSkills"); - auto* behaviors = CDClientManager::Instance()->GetTable<CDSkillBehaviorTable>("SkillBehavior"); + auto* table = CDClientManager::Instance().GetTable<CDObjectSkillsTable>(); + auto* behaviors = CDClientManager::Instance().GetTable<CDSkillBehaviorTable>(); const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast<unsigned int>(item->GetLot()); diff --git a/dGame/dComponents/LevelProgressionComponent.cpp b/dGame/dComponents/LevelProgressionComponent.cpp index 6e6b823e..814a7a86 100644 --- a/dGame/dComponents/LevelProgressionComponent.cpp +++ b/dGame/dComponents/LevelProgressionComponent.cpp @@ -4,6 +4,8 @@ #include "CharacterComponent.h" #include "tinyxml2.h" +#include "CDRewardsTable.h" + LevelProgressionComponent::LevelProgressionComponent(Entity* parent) : Component(parent) { m_Parent = parent; m_Level = 1; @@ -42,7 +44,7 @@ void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool } void LevelProgressionComponent::HandleLevelUp() { - auto* rewardsTable = CDClientManager::Instance()->GetTable<CDRewardsTable>("Rewards"); + auto* rewardsTable = CDClientManager::Instance().GetTable<CDRewardsTable>(); 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 cbae7f9f..0ae0f07e 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -265,7 +265,7 @@ void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, } bool MissionComponent::GetMissionInfo(uint32_t missionId, CDMissions& result) { - auto* missionsTable = CDClientManager::Instance()->GetTable<CDMissionsTable>("Missions"); + auto* missionsTable = CDClientManager::Instance().GetTable<CDMissionsTable>(); const auto missions = missionsTable->Query([=](const CDMissions& entry) { return entry.id == static_cast<int>(missionId); @@ -319,8 +319,8 @@ bool MissionComponent::LookForAchievements(eMissionTaskType type, int32_t value, return any; #else - auto* missionTasksTable = CDClientManager::Instance()->GetTable<CDMissionTasksTable>("MissionTasks"); - auto* missionsTable = CDClientManager::Instance()->GetTable<CDMissionsTable>("Missions"); + auto* missionTasksTable = CDClientManager::Instance().GetTable<CDMissionTasksTable>(); + auto* missionsTable = CDClientManager::Instance().GetTable<CDMissionsTable>(); auto tasks = missionTasksTable->Query([=](const CDMissionTasks& entry) { return entry.taskType == static_cast<unsigned>(type); @@ -406,8 +406,8 @@ const std::vector<uint32_t>& MissionComponent::QueryAchievements(eMissionTaskTyp } // Find relevent tables - auto* missionTasksTable = CDClientManager::Instance()->GetTable<CDMissionTasksTable>("MissionTasks"); - auto* missionsTable = CDClientManager::Instance()->GetTable<CDMissionsTable>("Missions"); + auto* missionTasksTable = CDClientManager::Instance().GetTable<CDMissionTasksTable>(); + auto* missionsTable = CDClientManager::Instance().GetTable<CDMissionsTable>(); std::vector<uint32_t> result; diff --git a/dGame/dComponents/MissionOfferComponent.cpp b/dGame/dComponents/MissionOfferComponent.cpp index ad315314..e4c94ebd 100644 --- a/dGame/dComponents/MissionOfferComponent.cpp +++ b/dGame/dComponents/MissionOfferComponent.cpp @@ -16,6 +16,8 @@ #include "MissionPrerequisites.h" #include "eMissionState.h" +#include "CDComponentsRegistryTable.h" + OfferedMission::OfferedMission(const uint32_t missionId, const bool offersMission, const bool acceptsMission) { this->missionId = missionId; this->offersMission = offersMission; @@ -38,7 +40,7 @@ bool OfferedMission::GetAcceptMission() const { //------------------------ MissionOfferComponent below ------------------------ MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot) : Component(parent) { - auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + auto* compRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); auto value = compRegistryTable->GetByIDAndType(parentLot, eReplicaComponentType::MISSION_OFFER, -1); @@ -46,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<CDMissionNPCComponentTable>("MissionNPCComponent"); + auto* missionNpcComponentTable = CDClientManager::Instance().GetTable<CDMissionNPCComponentTable>(); auto missions = missionNpcComponentTable->Query([=](const CDMissionNPCComponent& entry) { return entry.id == static_cast<unsigned>(componentId); diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index 1f774690..278e9106 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -11,6 +11,9 @@ #include "SimplePhysicsComponent.h" #include "CDClientManager.h" +#include "CDComponentsRegistryTable.h" +#include "CDPhysicsComponentTable.h" + std::map<LOT, float> MovementAIComponent::m_PhysicsSpeedCache = {}; MovementAIComponent::MovementAIComponent(Entity* parent, MovementAIInfo info) : Component(parent) { @@ -280,8 +283,8 @@ float MovementAIComponent::GetBaseSpeed(LOT lot) { return it->second; } - CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance()->GetTable<CDPhysicsComponentTable>("PhysicsComponent"); + CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); + CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance().GetTable<CDPhysicsComponentTable>(); int32_t componentID; CDPhysicsComponent* physicsComponent = nullptr; diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index b95b7cdd..75cef4fb 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -143,10 +143,10 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par */ if (!m_HasCreatedPhysics) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::PHANTOM_PHYSICS); - CDPhysicsComponentTable* physComp = CDClientManager::Instance()->GetTable<CDPhysicsComponentTable>("PhysicsComponent"); + CDPhysicsComponentTable* physComp = CDClientManager::Instance().GetTable<CDPhysicsComponentTable>(); if (physComp == nullptr) return; @@ -253,10 +253,10 @@ void PhantomPhysicsComponent::CreatePhysics() { y = m_Parent->GetVar<float>(u"primitiveModelValueY"); z = m_Parent->GetVar<float>(u"primitiveModelValueZ"); } else { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::PHANTOM_PHYSICS); - CDPhysicsComponentTable* physComp = CDClientManager::Instance()->GetTable<CDPhysicsComponentTable>("PhysicsComponent"); + CDPhysicsComponentTable* physComp = CDClientManager::Instance().GetTable<CDPhysicsComponentTable>(); if (physComp == nullptr) return; diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index 9498a903..fa838ed7 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -16,7 +16,7 @@ PropertyEntranceComponent::PropertyEntranceComponent(uint32_t componentID, Entity* parent) : Component(parent) { this->propertyQueries = {}; - auto table = CDClientManager::Instance()->GetTable<CDPropertyEntranceComponentTable>("PropertyEntranceComponent"); + auto table = CDClientManager::Instance().GetTable<CDPropertyEntranceComponentTable>(); const auto& entry = table->GetByID(componentID); this->m_MapID = entry.mapID; diff --git a/dGame/dComponents/RailActivatorComponent.cpp b/dGame/dComponents/RailActivatorComponent.cpp index 25fad26e..49fc105d 100644 --- a/dGame/dComponents/RailActivatorComponent.cpp +++ b/dGame/dComponents/RailActivatorComponent.cpp @@ -10,8 +10,7 @@ RailActivatorComponent::RailActivatorComponent(Entity* parent, int32_t componentID) : Component(parent) { m_ComponentID = componentID; - const auto tableData = CDClientManager::Instance() - ->GetTable<CDRailActivatorComponentTable>("RailActivatorComponent")->GetEntryByID(componentID); + const auto tableData = CDClientManager::Instance().GetTable<CDRailActivatorComponentTable>()->GetEntryByID(componentID);; m_Path = parent->GetVar<std::u16string>(u"rail_path"); m_PathDirection = parent->GetVar<bool>(u"rail_path_direction"); diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index f188859d..ee42acba 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -20,7 +20,7 @@ RenderComponent::RenderComponent(Entity* parent) : Component(parent) { return; /* - auto* table = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + auto* table = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); const auto entry = table->GetByIDAndType(parent->GetLOT(), eReplicaComponentType::RENDER); diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index 4a034187..bafa1faa 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -22,9 +22,13 @@ #include "Loot.h" #include "eMissionTaskType.h" +#include "CDCurrencyTableTable.h" +#include "CDActivityRewardsTable.h" +#include "CDActivitiesTable.h" + ScriptedActivityComponent::ScriptedActivityComponent(Entity* parent, int activityID) : Component(parent) { m_ActivityID = activityID; - CDActivitiesTable* activitiesTable = CDClientManager::Instance()->GetTable<CDActivitiesTable>("Activities"); + CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable<CDActivitiesTable>(); std::vector<CDActivities> activities = activitiesTable->Query([=](CDActivities entry) {return (entry.ActivityID == m_ActivityID); }); for (CDActivities activity : activities) { @@ -53,7 +57,7 @@ ScriptedActivityComponent::ScriptedActivityComponent(Entity* parent, int activit if (destroyableComponent) { // check for LMIs and set the loot LMIs - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable<CDActivityRewardsTable>("ActivityRewards"); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance().GetTable<CDActivityRewardsTable>(); std::vector<CDActivityRewards> activityRewards = activityRewardsTable->Query([=](CDActivityRewards entry) {return (entry.LootMatrixIndex == destroyableComponent->GetLootMatrixID()); }); uint32_t startingLMI = 0; @@ -94,7 +98,7 @@ void ScriptedActivityComponent::Serialize(RakNet::BitStream* outBitStream, bool } void ScriptedActivityComponent::ReloadConfig() { - CDActivitiesTable* activitiesTable = CDClientManager::Instance()->GetTable<CDActivitiesTable>("Activities"); + CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable<CDActivitiesTable>(); std::vector<CDActivities> activities = activitiesTable->Query([=](CDActivities entry) {return (entry.ActivityID == m_ActivityID); }); for (auto activity : activities) { auto mapID = m_ActivityInfo.instanceMapID; @@ -557,14 +561,14 @@ void ActivityInstance::RewardParticipant(Entity* participant) { } // First, get the activity data - auto* activityRewardsTable = CDClientManager::Instance()->GetTable<CDActivityRewardsTable>("ActivityRewards"); + auto* activityRewardsTable = CDClientManager::Instance().GetTable<CDActivityRewardsTable>(); std::vector<CDActivityRewards> activityRewards = activityRewardsTable->Query([=](CDActivityRewards entry) { return (entry.objectTemplate == m_ActivityInfo.ActivityID); }); if (!activityRewards.empty()) { uint32_t minCoins = 0; uint32_t maxCoins = 0; - auto* currencyTableTable = CDClientManager::Instance()->GetTable<CDCurrencyTableTable>("CurrencyTable"); + auto* currencyTableTable = CDClientManager::Instance().GetTable<CDCurrencyTableTable>(); std::vector<CDCurrencyTable> currencyTable = currencyTableTable->Query([=](CDCurrencyTable entry) { return (entry.currencyIndex == activityRewards[0].CurrencyIndex && entry.npcminlevel == 1); }); if (!currencyTable.empty()) { diff --git a/dGame/dComponents/ScriptedActivityComponent.h b/dGame/dComponents/ScriptedActivityComponent.h index a4aad048..1d49a62d 100644 --- a/dGame/dComponents/ScriptedActivityComponent.h +++ b/dGame/dComponents/ScriptedActivityComponent.h @@ -13,6 +13,8 @@ #include "Component.h" #include "eReplicaComponentType.h" +#include "CDActivitiesTable.h" + /** * Represents an instance of an activity, having participants and score */ diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index 625f1f30..23ef1bee 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -24,6 +24,8 @@ #include "DoClientProjectileImpact.h" #include "CDClientManager.h" +#include "CDSkillBehaviorTable.h" + ProjectileSyncEntry::ProjectileSyncEntry() { } @@ -220,7 +222,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<CDSkillBehaviorTable>("SkillBehavior"); + auto skillTable = CDClientManager::Instance().GetTable<CDSkillBehaviorTable>(); behaviorId = skillTable->GetSkillByID(skillId).behaviorID; m_skillBehaviorCache.insert_or_assign(skillId, behaviorId); } else { diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp index fe3c7792..d98b2eea 100644 --- a/dGame/dComponents/TriggerComponent.cpp +++ b/dGame/dComponents/TriggerComponent.cpp @@ -161,7 +161,7 @@ void TriggerComponent::HandleSetPhysicsVolume(Entity* targetEntity, std::vector< } void TriggerComponent::HandleUpdateMission(Entity* targetEntity, std::vector<std::string> argArray) { - CDMissionTasksTable* missionTasksTable = CDClientManager::Instance()->GetTable<CDMissionTasksTable>("MissionTasks"); + CDMissionTasksTable* missionTasksTable = CDClientManager::Instance().GetTable<CDMissionTasksTable>(); std::vector<CDMissionTasks> missionTasks = missionTasksTable->Query([=](CDMissionTasks entry) { return (entry.targetGroup == argArray.at(4)); }); diff --git a/dGame/dComponents/VendorComponent.cpp b/dGame/dComponents/VendorComponent.cpp index e9599b71..c9178785 100644 --- a/dGame/dComponents/VendorComponent.cpp +++ b/dGame/dComponents/VendorComponent.cpp @@ -5,6 +5,11 @@ #include "Game.h" #include "dServer.h" +#include "CDComponentsRegistryTable.h" +#include "CDVendorComponentTable.h" +#include "CDLootMatrixTable.h" +#include "CDLootTableTable.h" + VendorComponent::VendorComponent(Entity* parent) : Component(parent) { SetupConstants(); RefreshInventory(true); @@ -59,13 +64,13 @@ void VendorComponent::RefreshInventory(bool isCreation) { return; } m_Inventory.clear(); - auto* lootMatrixTable = CDClientManager::Instance()->GetTable<CDLootMatrixTable>("LootMatrix"); + auto* lootMatrixTable = CDClientManager::Instance().GetTable<CDLootMatrixTable>(); std::vector<CDLootMatrix> lootMatrices = lootMatrixTable->Query([=](CDLootMatrix entry) { return (entry.LootMatrixIndex == m_LootMatrixID); }); if (lootMatrices.empty()) return; // Done with lootMatrix table - auto* lootTableTable = CDClientManager::Instance()->GetTable<CDLootTableTable>("LootTable"); + auto* lootTableTable = CDClientManager::Instance().GetTable<CDLootTableTable>(); for (const auto& lootMatrix : lootMatrices) { int lootTableID = lootMatrix.LootTableIndex; @@ -118,10 +123,10 @@ void VendorComponent::RefreshInventory(bool isCreation) { } void VendorComponent::SetupConstants() { - auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + auto* compRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); int componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::VENDOR); - auto* vendorComponentTable = CDClientManager::Instance()->GetTable<CDVendorComponentTable>("VendorComponent"); + auto* vendorComponentTable = CDClientManager::Instance().GetTable<CDVendorComponentTable>(); std::vector<CDVendorComponent> vendorComps = vendorComponentTable->Query([=](CDVendorComponent entry) { return (entry.id == componentID); }); if (vendorComps.empty()) return; m_BuyScalar = vendorComps[0].buyScalar; diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index b63f1c6d..5c05c28d 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -286,7 +286,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System comp->Progress(eMissionTaskType::USE_SKILL, startSkill.skillID); } - CDSkillBehaviorTable* skillTable = CDClientManager::Instance()->GetTable<CDSkillBehaviorTable>("SkillBehavior"); + CDSkillBehaviorTable* skillTable = CDClientManager::Instance().GetTable<CDSkillBehaviorTable>(); unsigned int behaviorId = skillTable->GetSkillByID(startSkill.skillID).behaviorID; bool success = false; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 8da37bf5..33a7f104 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -82,6 +82,9 @@ #include "AMFFormat_BitStream.h" #include "eReplicaComponentType.h" +#include "CDComponentsRegistryTable.h" +#include "CDObjectsTable.h" + void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const SystemAddress& sysAddr, std::u16string args, const LWOOBJID& object, int64_t param1, int param2, const LWOOBJID& sender) { CBITSTREAM; CMSGHEADER; @@ -1077,7 +1080,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>("Objects"); + CDObjectsTable* objectsTable = CDClientManager::Instance().GetTable<CDObjectsTable>(); const CDObjects& object = objectsTable->GetByID(item); @@ -4720,8 +4723,8 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti InventoryComponent* inv = static_cast<InventoryComponent*>(player->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance()->GetTable<CDItemComponentTable>("ItemComponent"); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); + CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable<CDItemComponentTable>(); int itemCompID = compRegistryTable->GetByIDAndType(item, eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); @@ -4812,8 +4815,8 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit Item* item = inv->FindItemById(iObjID); if (!item) return; - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance()->GetTable<CDItemComponentTable>("ItemComponent"); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); + CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable<CDItemComponentTable>(); int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); @@ -4862,8 +4865,8 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* Item* item = inv->FindItemById(iObjID); if (!item) return; - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance()->GetTable<CDItemComponentTable>("ItemComponent"); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); + CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable<CDItemComponentTable>(); int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); @@ -5101,7 +5104,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) } } - CDEmoteTableTable* emotes = CDClientManager::Instance()->GetTable<CDEmoteTableTable>("EmoteTable"); + CDEmoteTableTable* emotes = CDClientManager::Instance().GetTable<CDEmoteTableTable>(); 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 e0b792ad..c3443f31 100644 --- a/dGame/dGameMessages/PropertyDataMessage.cpp +++ b/dGame/dGameMessages/PropertyDataMessage.cpp @@ -6,6 +6,8 @@ #include "dLogger.h" #include "CDClientManager.h" +#include "CDPropertyTemplateTable.h" + void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) const { stream.Write<int64_t>(0); // - property id @@ -101,8 +103,7 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con } GameMessages::PropertyDataMessage::PropertyDataMessage(uint32_t mapID) { - const auto propertyTemplate = CDClientManager::Instance()-> - GetTable<CDPropertyTemplateTable>("PropertyTemplate")->GetByMapID(mapID); + const auto propertyTemplate = CDClientManager::Instance().GetTable<CDPropertyTemplateTable>()->GetByMapID(mapID); TemplateID = propertyTemplate.id; ZoneId = propertyTemplate.mapID; diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index b35281eb..d752f87d 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -6,6 +6,8 @@ #include "eItemType.h" #include "eReplicaComponentType.h" +#include "CDComponentsRegistryTable.h" + std::vector<LOT> Inventory::m_GameMasterRestrictedItems = { 1727, // GM Only - JetPack 2243, // GM Only - Hammer of Doom @@ -274,9 +276,9 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) { } const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { - auto* registry = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + auto* registry = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); - auto* itemComponents = CDClientManager::Instance()->GetTable<CDItemComponentTable>("ItemComponent"); + auto* itemComponents = CDClientManager::Instance().GetTable<CDItemComponentTable>(); const auto componentId = registry->GetByIDAndType(lot, eReplicaComponentType::ITEM); @@ -292,7 +294,7 @@ const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { } bool Inventory::IsValidItem(const LOT lot) { - auto* registry = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + auto* registry = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); const auto componentId = registry->GetByIDAndType(lot, eReplicaComponentType::ITEM); diff --git a/dGame/dInventory/Inventory.h b/dGame/dInventory/Inventory.h index cd381db3..5e0ac8d6 100644 --- a/dGame/dInventory/Inventory.h +++ b/dGame/dInventory/Inventory.h @@ -6,7 +6,7 @@ #include <map> #include <vector> - +#include "CDItemComponentTable.h" #include "CDClientManager.h" #include "dCommonVars.h" diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 0df1723d..acaecbf7 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -18,6 +18,11 @@ #include "Loot.h" #include "eReplicaComponentType.h" +#include "CDBrickIDTableTable.h" +#include "CDObjectSkillsTable.h" +#include "CDComponentsRegistryTable.h" +#include "CDPackageComponentTable.h" + Item::Item(const LWOOBJID id, const LOT lot, Inventory* inventory, const uint32_t slot, const uint32_t count, const bool bound, const std::vector<LDFBaseData*>& config, const LWOOBJID parent, LWOOBJID subKey, eLootSourceType lootSourceType) { if (!Inventory::IsValidItem(lot)) { return; @@ -238,7 +243,7 @@ bool Item::IsEquipped() const { } bool Item::Consume() { - auto* skillsTable = CDClientManager::Instance()->GetTable<CDObjectSkillsTable>("ObjectSkills"); + auto* skillsTable = CDClientManager::Instance().GetTable<CDObjectSkillsTable>(); auto skills = skillsTable->Query([=](const CDObjectSkills entry) { return entry.objectTemplate == static_cast<uint32_t>(lot); @@ -297,12 +302,12 @@ void Item::UseNonEquip(Item* item) { bool success = false; auto inventory = item->GetInventory(); if (inventory && inventory->GetType() == eInventoryType::ITEMS) { - auto* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + auto* compRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::PACKAGE); if (packageComponentId == 0) return; - auto* packCompTable = CDClientManager::Instance()->GetTable<CDPackageComponentTable>("PackageComponent"); + auto* packCompTable = CDClientManager::Instance().GetTable<CDPackageComponentTable>(); auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast<uint32_t>(packageComponentId); }); auto success = !packages.empty(); @@ -380,7 +385,7 @@ void Item::Disassemble(const eInventoryType inventoryType) { } void Item::DisassembleModel() { - auto* table = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); + auto* table = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); const auto componentId = table->GetByIDAndType(GetLot(), eReplicaComponentType::RENDER); @@ -457,7 +462,7 @@ void Item::DisassembleModel() { currentBrick = currentBrick->NextSiblingElement(searchTerm.c_str()); } - auto* brickIDTable = CDClientManager::Instance()->GetTable<CDBrickIDTableTable>("BrickIDTable"); + auto* brickIDTable = CDClientManager::Instance().GetTable<CDBrickIDTableTable>(); for (unsigned int part : parts) { const auto brickID = brickIDTable->Query([=](const CDBrickIDTable& entry) { diff --git a/dGame/dInventory/ItemSet.cpp b/dGame/dInventory/ItemSet.cpp index e246f9f7..a8e58739 100644 --- a/dGame/dInventory/ItemSet.cpp +++ b/dGame/dInventory/ItemSet.cpp @@ -9,6 +9,8 @@ #include "eMissionTaskType.h" #include <algorithm> +#include "CDSkillBehaviorTable.h" + ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) { this->m_ID = id; this->m_InventoryComponent = inventoryComponent; @@ -127,7 +129,7 @@ void ItemSet::OnEquip(const LOT lot) { auto* missionComponent = m_InventoryComponent->GetParent()->GetComponent<MissionComponent>(); for (const auto skill : skillSet) { - auto* skillTable = CDClientManager::Instance()->GetTable<CDSkillBehaviorTable>("SkillBehavior"); + auto* skillTable = CDClientManager::Instance().GetTable<CDSkillBehaviorTable>(); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; @@ -159,7 +161,7 @@ void ItemSet::OnUnEquip(const LOT lot) { const auto& skillComponent = m_InventoryComponent->GetParent()->GetComponent<SkillComponent>(); for (const auto skill : skillSet) { - auto* skillTable = CDClientManager::Instance()->GetTable<CDSkillBehaviorTable>("SkillBehavior"); + auto* skillTable = CDClientManager::Instance().GetTable<CDSkillBehaviorTable>(); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index 68384652..9cfdaaa7 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -25,6 +25,8 @@ #include "eMissionLockState.h" #include "eReplicaComponentType.h" +#include "CDMissionEmailTable.h" + Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { m_MissionComponent = missionComponent; @@ -38,7 +40,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { m_State = eMissionState::UNKNOWN; - auto* missionsTable = CDClientManager::Instance()->GetTable<CDMissionsTable>("Missions"); + auto* missionsTable = CDClientManager::Instance().GetTable<CDMissionsTable>(); info = missionsTable->GetPtrByMissionID(missionId); @@ -48,7 +50,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { return; } - auto* tasksTable = CDClientManager::Instance()->GetTable<CDMissionTasksTable>("MissionTasks"); + auto* tasksTable = CDClientManager::Instance().GetTable<CDMissionTasksTable>(); auto tasks = tasksTable->GetByMissionID(missionId); @@ -176,7 +178,7 @@ void Mission::UpdateXml(tinyxml2::XMLElement* element) { } bool Mission::IsValidMission(const uint32_t missionId) { - auto* table = CDClientManager::Instance()->GetTable<CDMissionsTable>("Missions"); + auto* table = CDClientManager::Instance().GetTable<CDMissionsTable>(); const auto missions = table->Query([=](const CDMissions& entry) { return entry.id == static_cast<int>(missionId); @@ -186,7 +188,7 @@ bool Mission::IsValidMission(const uint32_t missionId) { } bool Mission::IsValidMission(const uint32_t missionId, CDMissions& info) { - auto* table = CDClientManager::Instance()->GetTable<CDMissionsTable>("Missions"); + auto* table = CDClientManager::Instance().GetTable<CDMissionsTable>(); const auto missions = table->Query([=](const CDMissions& entry) { return entry.id == static_cast<int>(missionId); @@ -330,7 +332,7 @@ void Mission::Complete(const bool yieldRewards) { missionComponent->Progress(eMissionTaskType::RACING, info->id, (LWOOBJID)eRacingTaskParam::COMPLETE_TRACK_TASKS); - auto* missionEmailTable = CDClientManager::Instance()->GetTable<CDMissionEmailTable>("MissionEmail"); + auto* missionEmailTable = CDClientManager::Instance().GetTable<CDMissionEmailTable>(); const auto missionId = GetMissionId(); diff --git a/dGame/dMission/MissionPrerequisites.cpp b/dGame/dMission/MissionPrerequisites.cpp index 6b55151c..ec4522b9 100644 --- a/dGame/dMission/MissionPrerequisites.cpp +++ b/dGame/dMission/MissionPrerequisites.cpp @@ -163,7 +163,7 @@ bool MissionPrerequisites::CheckPrerequisites(uint32_t missionId, const std::uno return index->second->Execute(missions); } - auto* missionsTable = CDClientManager::Instance()->GetTable<CDMissionsTable>("Missions"); + auto* missionsTable = CDClientManager::Instance().GetTable<CDMissionsTable>(); const auto missionEntries = missionsTable->Query([=](const CDMissions& entry) { return entry.id == static_cast<int>(missionId); }); diff --git a/dGame/dUtilities/Loot.cpp b/dGame/dUtilities/Loot.cpp index 415c976c..da0f2487 100644 --- a/dGame/dUtilities/Loot.cpp +++ b/dGame/dUtilities/Loot.cpp @@ -7,6 +7,8 @@ #include "CDLootMatrixTable.h" #include "CDLootTableTable.h" #include "CDRarityTableTable.h" +#include "CDActivityRewardsTable.h" +#include "CDCurrencyTableTable.h" #include "Character.h" #include "Entity.h" #include "GameMessages.h" @@ -17,11 +19,11 @@ #include "eReplicaComponentType.h" LootGenerator::LootGenerator() { - CDLootTableTable* lootTableTable = CDClientManager::Instance()->GetTable<CDLootTableTable>("LootTable"); - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry"); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance()->GetTable<CDItemComponentTable>("ItemComponent"); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance()->GetTable<CDLootMatrixTable>("LootMatrix"); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance()->GetTable<CDRarityTableTable>("RarityTable"); + CDLootTableTable* lootTableTable = CDClientManager::Instance().GetTable<CDLootTableTable>(); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance().GetTable<CDComponentsRegistryTable>(); + CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable<CDItemComponentTable>(); + CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance().GetTable<CDLootMatrixTable>(); + CDRarityTableTable* rarityTableTable = CDClientManager::Instance().GetTable<CDRarityTableTable>(); // ============================== // Cache Item Rarities @@ -292,7 +294,7 @@ void LootGenerator::GiveLoot(Entity* player, std::unordered_map<LOT, int32_t>& r } void LootGenerator::GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating) { - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable<CDActivityRewardsTable>("ActivityRewards"); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance().GetTable<CDActivityRewardsTable>(); std::vector<CDActivityRewards> activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); const CDActivityRewards* selectedReward = nullptr; @@ -308,7 +310,7 @@ void LootGenerator::GiveActivityLoot(Entity* player, Entity* source, uint32_t ac uint32_t minCoins = 0; uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable<CDCurrencyTableTable>("CurrencyTable"); + CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance().GetTable<CDCurrencyTableTable>(); std::vector<CDCurrencyTable> currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); if (currencyTable.size() > 0) { @@ -362,7 +364,7 @@ void LootGenerator::DropLoot(Entity* player, Entity* killedObject, std::unordere } void LootGenerator::DropActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating) { - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance()->GetTable<CDActivityRewardsTable>("ActivityRewards"); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance().GetTable<CDActivityRewardsTable>(); std::vector<CDActivityRewards> activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); const CDActivityRewards* selectedReward = nullptr; @@ -379,7 +381,7 @@ void LootGenerator::DropActivityLoot(Entity* player, Entity* source, uint32_t ac uint32_t minCoins = 0; uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance()->GetTable<CDCurrencyTableTable>("CurrencyTable"); + CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance().GetTable<CDCurrencyTableTable>(); std::vector<CDCurrencyTable> 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 fb9485b8..0278136b 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -77,6 +77,9 @@ #include "eServerDisconnectIdentifiers.h" #include "eReplicaComponentType.h" +#include "CDObjectsTable.h" +#include "CDZoneTableTable.h" + void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { std::string chatCommand; std::vector<std::string> args; @@ -1912,7 +1915,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit EntityManager::Instance()->SerializeEntity(closest); - auto* table = CDClientManager::Instance()->GetTable<CDObjectsTable>("Objects"); + auto* table = CDClientManager::Instance().GetTable<CDObjectsTable>(); const auto& info = table->GetByID(closest->GetLOT()); @@ -2021,7 +2024,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit bool SlashCommandHandler::CheckIfAccessibleZone(const unsigned int zoneID) { //We're gonna go ahead and presume we've got the db loaded already: - CDZoneTableTable* zoneTable = CDClientManager::Instance()->GetTable<CDZoneTableTable>("ZoneTable"); + CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable<CDZoneTableTable>(); const CDZoneTable* zone = zoneTable->Query(zoneID); if (zone != nullptr) { return Game::assetManager->HasFile(("maps/" + zone->zoneName).c_str()); diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index b277adbf..fe62a5e5 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -369,7 +369,7 @@ Instance* InstanceManager::FindPrivateInstance(const std::string& password) { } int InstanceManager::GetSoftCap(LWOMAPID mapID) { - CDZoneTableTable* zoneTable = CDClientManager::Instance()->GetTable<CDZoneTableTable>("ZoneTable"); + CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable<CDZoneTableTable>(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); @@ -382,7 +382,7 @@ int InstanceManager::GetSoftCap(LWOMAPID mapID) { } int InstanceManager::GetHardCap(LWOMAPID mapID) { - CDZoneTableTable* zoneTable = CDClientManager::Instance()->GetTable<CDZoneTableTable>("ZoneTable"); + CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable<CDZoneTableTable>(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index bcf1a540..cc2bdd90 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -193,7 +193,7 @@ int main(int argc, char** argv) { //Get CDClient initial information try { - CDClientManager::Instance()->Initialize(); + CDClientManager::Instance(); } catch (CppSQLite3Exception& e) { Game::logger->Log("WorldServer", "Failed to initialize CDServer SQLite Database"); Game::logger->Log("WorldServer", "May be caused by corrupted file: %s", (Game::assetManager->GetResPath() / "CDServer.sqlite").string().c_str()); diff --git a/dScripts/02_server/Map/General/QbEnemyStunner.cpp b/dScripts/02_server/Map/General/QbEnemyStunner.cpp index 2b15a056..441d743c 100644 --- a/dScripts/02_server/Map/General/QbEnemyStunner.cpp +++ b/dScripts/02_server/Map/General/QbEnemyStunner.cpp @@ -3,6 +3,9 @@ #include "CDClientManager.h" #include "DestroyableComponent.h" +#include "CDObjectSkillsTable.h" +#include "CDSkillBehaviorTable.h" + void QbEnemyStunner::OnRebuildComplete(Entity* self, Entity* target) { auto* destroyable = self->GetComponent<DestroyableComponent>(); @@ -14,12 +17,12 @@ void QbEnemyStunner::OnRebuildComplete(Entity* self, Entity* target) { if (!skillComponent) return; // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance()->GetTable<CDObjectSkillsTable>("ObjectSkills"); + CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable<CDObjectSkillsTable>(); auto skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); std::map<uint32_t, uint32_t> skillBehaviorMap; // For each skill, cast it with the associated behavior ID. for (auto skill : skills) { - CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance()->GetTable<CDSkillBehaviorTable>("SkillBehavior"); + CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance().GetTable<CDSkillBehaviorTable>(); 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 dcccc337..389f3621 100644 --- a/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp +++ b/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp @@ -3,6 +3,7 @@ #include "SkillComponent.h" #include "CDClientDatabase.h" #include "CDObjectSkillsTable.h" +#include "CDSkillBehaviorTable.h" #include "CDClientManager.h" void FireFirstSkillonStartup::OnStartup(Entity* self) { @@ -10,12 +11,12 @@ void FireFirstSkillonStartup::OnStartup(Entity* self) { if (!skillComponent) return; // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance()->GetTable<CDObjectSkillsTable>("ObjectSkills"); + CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable<CDObjectSkillsTable>(); std::vector<CDObjectSkills> 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>("SkillBehavior"); + CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance().GetTable<CDSkillBehaviorTable>(); CDSkillBehavior behaviorData = skillBehaviorTable->GetSkillByID(skill.skillID); // Should parent entity be null, make the originator self. diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index f8d50f5b..8a603878 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -168,7 +168,7 @@ int main(int argc, char** argv) { return EXIT_FAILURE; } - CDClientManager::Instance()->Initialize(); + CDClientManager::Instance(); //Connect to the MySQL Database std::string mysql_host = Game::config->GetValue("mysql_host"); diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index dd38d208..55790592 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -162,7 +162,7 @@ void Level::ReadSceneObjectDataChunk(std::istream& file, Header& header) { uint32_t objectsCount = 0; BinaryIO::BinaryRead(file, objectsCount); - CDFeatureGatingTable* featureGatingTable = CDClientManager::Instance()->GetTable<CDFeatureGatingTable>("FeatureGating"); + CDFeatureGatingTable* featureGatingTable = CDClientManager::Instance().GetTable<CDFeatureGatingTable>(); for (uint32_t i = 0; i < objectsCount; ++i) { SceneObject obj; diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index c32f8447..28d3f0c8 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -164,7 +164,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"); + CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable<CDZoneTableTable>(); 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 0b7844a3..52008b5d 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -9,6 +9,7 @@ #include "GameMessages.h" #include "VanityUtilities.h" #include "WorldConfig.h" +#include "CDZoneTableTable.h" #include <chrono> #include "../dWorldServer/ObjectIDManager.h" @@ -27,7 +28,7 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { LOT zoneControlTemplate = 2365; - CDZoneTableTable* zoneTable = CDClientManager::Instance()->GetTable<CDZoneTableTable>("ZoneTable"); + CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable<CDZoneTableTable>(); if (zoneTable != nullptr) { const CDZoneTable* zone = zoneTable->Query(zoneID.GetMapID()); From b967cc57d17c47bc35374a004bbcdb133e55399c Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 23 Mar 2023 07:49:31 -0700 Subject: [PATCH 271/322] Allow name billboards to be toggled (#1026) * Allow name billboards to be toggled * Allow name billboards to be toggled * Add comments * Move logic to Character * Use Entity in Character instead --- dCommon/dEnums/dMessageIdentifiers.h | 2 ++ dGame/Character.cpp | 18 +++++++++++++++ dGame/Character.h | 9 ++++++++ dGame/dGameMessages/GameMessages.cpp | 29 ++++++++++++++++++++++++ dGame/dGameMessages/GameMessages.h | 2 ++ dGame/dUtilities/SlashCommandHandler.cpp | 13 +++++++++++ docs/Commands.md | 1 + resources/worldconfig.ini | 3 +++ 8 files changed, 77 insertions(+) diff --git a/dCommon/dEnums/dMessageIdentifiers.h b/dCommon/dEnums/dMessageIdentifiers.h index e11f9e7f..63d7044e 100644 --- a/dCommon/dEnums/dMessageIdentifiers.h +++ b/dCommon/dEnums/dMessageIdentifiers.h @@ -484,6 +484,7 @@ enum GAME_MSG : unsigned short { GAME_MSG_LOCK_NODE_ROTATION = 1260, GAME_MSG_VEHICLE_SET_WHEEL_LOCK_STATE = 1273, GAME_MSG_NOTIFY_VEHICLE_OF_RACING_OBJECT = 1276, + GAME_MSG_SET_NAME_BILLBOARD_STATE = 1284, GAME_MSG_PLAYER_REACHED_RESPAWN_CHECKPOINT = 1296, GAME_MSG_HANDLE_UGC_EQUIP_POST_DELETE_BASED_ON_EDIT_MODE = 1300, GAME_MSG_HANDLE_UGC_EQUIP_PRE_CREATE_BASED_ON_EDIT_MODE = 1301, @@ -494,6 +495,7 @@ enum GAME_MSG : unsigned short { GAME_MSG_MATCH_UPDATE = 1310, GAME_MSG_MODULE_ASSEMBLY_DB_DATA_FOR_CLIENT = 1131, GAME_MSG_MODULE_ASSEMBLY_QUERY_DATA = 1132, + GAME_MSG_SHOW_BILLBOARD_INTERACT_ICON = 1337, GAME_MSG_CHANGE_IDLE_FLAGS = 1338, GAME_MSG_VEHICLE_ADD_PASSIVE_BOOST_ACTION = 1340, GAME_MSG_VEHICLE_REMOVE_PASSIVE_BOOST_ACTION = 1341, diff --git a/dGame/Character.cpp b/dGame/Character.cpp index 572a3e9e..16497fc3 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -621,3 +621,21 @@ void Character::SendMuteNotice() const { ChatPackets::SendSystemMessage(GetEntity()->GetSystemAddress(), u"You are muted until " + timeStr); } + +void Character::SetBillboardVisible(bool visible) { + if (m_BillboardVisible == visible) return; + m_BillboardVisible = visible; + + GameMessages::SendSetNamebillboardState(UNASSIGNED_SYSTEM_ADDRESS, m_OurEntity->GetObjectID()); + + if (!visible) return; + + // The GameMessage we send for turning the nameplate off just deletes the BillboardSubcomponent from the parent component. + // Because that same message does not allow for custom parameters, we need to create the BillboardSubcomponent a different way + // This workaround involves sending an unrelated GameMessage that does not apply to player entites, + // but forces the client to create the necessary SubComponent that controls the billboard. + GameMessages::SendShowBillboardInteractIcon(UNASSIGNED_SYSTEM_ADDRESS, m_OurEntity->GetObjectID()); + + // Now turn off the billboard for the owner. + GameMessages::SendSetNamebillboardState(m_OurEntity->GetSystemAddress(), m_OurEntity->GetObjectID()); +} diff --git a/dGame/Character.h b/dGame/Character.h index abded1b3..d77dd022 100644 --- a/dGame/Character.h +++ b/dGame/Character.h @@ -451,6 +451,10 @@ public: */ void SetIsFlying(bool isFlying) { m_IsFlying = isFlying; } + bool GetBillboardVisible() { return m_BillboardVisible; } + + void SetBillboardVisible(bool visible); + private: /** * The ID of this character. First 32 bits of the ObjectID. @@ -652,6 +656,11 @@ private: */ bool m_IsFlying = false; + /** + * True if billboard (referred to as nameplate for end users) is visible, false otherwise + */ + bool m_BillboardVisible = true; + /** * Queries the character XML and updates all the fields of this object * NOTE: quick as there's no DB lookups diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 33a7f104..8604d136 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -6154,3 +6154,32 @@ void GameMessages::SendDeactivateBubbleBuffFromServer(LWOOBJID objectId, const S if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; } + +void GameMessages::SendSetNamebillboardState(const SystemAddress& sysAddr, LWOOBJID objectId) { + CBITSTREAM; + CMSGHEADER; + + bitStream.Write(objectId); + bitStream.Write(GAME_MSG::GAME_MSG_SET_NAME_BILLBOARD_STATE); + + // Technically these bits would be written, however the client does not + // contain a deserialize method to actually deserialize, so we are leaving it out. + // As such this GM only turns the billboard off. + + // bitStream.Write(overrideDefault); + // bitStream.Write(state); + + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST + else SEND_PACKET +} + +void GameMessages::SendShowBillboardInteractIcon(const SystemAddress& sysAddr, LWOOBJID objectId) { + CBITSTREAM; + CMSGHEADER; + + bitStream.Write(objectId); + bitStream.Write(GAME_MSG::GAME_MSG_SHOW_BILLBOARD_INTERACT_ICON); + + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST + else SEND_PACKET +} diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 5d199995..7305e429 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -574,6 +574,8 @@ namespace GameMessages { void HandleToggleGhostReferenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleSetGhostReferencePosition(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void SendSetNamebillboardState(const SystemAddress& sysAddr, LWOOBJID objectId); + void SendShowBillboardInteractIcon(const SystemAddress& sysAddr, LWOOBJID objectId); void HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleSellToVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 0278136b..1f3da6c7 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -171,6 +171,19 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } #endif + if (chatCommand == "togglenameplate" && (Game::config->GetValue("allownameplateoff") == "1" || entity->GetGMLevel() > GAME_MASTER_LEVEL_DEVELOPER)) { + auto* character = entity->GetCharacter(); + + if (character && character->GetBillboardVisible()) { + character->SetBillboardVisible(false); + ChatPackets::SendSystemMessage(sysAddr, u"Your nameplate has been turned off and is not visible to players currently in this zone."); + } else { + character->SetBillboardVisible(true); + ChatPackets::SendSystemMessage(sysAddr, u"Your nameplate is now on and visible to all players."); + } + return; + } + //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //HANDLE ALL NON GM SLASH COMMANDS RIGHT HERE! //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! diff --git a/docs/Commands.md b/docs/Commands.md index a9cd3e7c..725a03a0 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -48,6 +48,7 @@ These commands are primarily for development and testing. The usage of many of t |Command|Usage|Description|Admin Level Requirement| |--- |--- |--- |--- | +|togglenameplate|`/togglenameplate`|Turns the nameplate above your head that is visible to other players off and on.|8 or if `allow_nameplate_off` is set to exactly `1` in the settings| |fix-stats|`/fix-stats`|Resets skills, buffs, and destroyables.|| |join|`/join <password>`|Joins a private zone with given password.|| |leave-zone|`/leave-zone`|If you are in an instanced zone, transfers you to the closest main world. For example, if you are in an instance of Avant Gardens Survival or the Spider Queen Battle, you are sent to Avant Gardens. If you are in the Battle of Nimbus Station, you are sent to Nimbus Station.|| diff --git a/resources/worldconfig.ini b/resources/worldconfig.ini index 64b4fb40..b05614b4 100644 --- a/resources/worldconfig.ini +++ b/resources/worldconfig.ini @@ -58,3 +58,6 @@ hardcore_uscore_enemies_multiplier=2 # Percentage of u-score to lose on player death hardcore_lose_uscore_on_death_percent=10 + +# Allow civilian players the ability to turn the nameplate above their head off. Must be exactly 1 to be enabled for civilians. +allow_nameplate_off=0 From 72ca0f13ff0f09137a05784ea1fe062d19e4e58f Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Fri, 24 Mar 2023 18:16:45 -0500 Subject: [PATCH 272/322] breakout gmlevel into a scoped enum (#996) * breakout gmlevel enum and make it a class tested that things still work slash command, chat restrictions, packets and serializations * fix GM level for some slash commands * fix new use of this enum --- dChatFilter/dChatFilter.cpp | 5 +- dChatFilter/dChatFilter.h | 3 +- dCommon/dEnums/dCommonVars.h | 15 -- dCommon/dEnums/eGameMasterLevel.h | 20 ++ dGame/Character.cpp | 9 +- dGame/Character.h | 7 +- dGame/Entity.cpp | 7 +- dGame/Entity.h | 7 +- dGame/EntityManager.cpp | 3 +- dGame/User.cpp | 5 +- dGame/User.h | 5 +- dGame/UserManager.cpp | 3 +- dGame/dComponents/CharacterComponent.cpp | 7 +- dGame/dComponents/CharacterComponent.h | 6 +- dGame/dComponents/PetComponent.cpp | 6 +- .../dComponents/PropertyEntranceComponent.cpp | 3 +- .../dComponents/ScriptedActivityComponent.cpp | 2 +- dGame/dGameMessages/GameMessages.cpp | 4 +- dGame/dGameMessages/GameMessages.h | 7 +- dGame/dUtilities/SlashCommandHandler.cpp | 176 +++++++++--------- dNet/ClientPackets.cpp | 3 +- dNet/WorldPackets.cpp | 15 +- dNet/WorldPackets.h | 5 +- docs/Commands.md | 20 +- 24 files changed, 184 insertions(+), 159 deletions(-) create mode 100644 dCommon/dEnums/eGameMasterLevel.h diff --git a/dChatFilter/dChatFilter.cpp b/dChatFilter/dChatFilter.cpp index ea38f8cd..92da9556 100644 --- a/dChatFilter/dChatFilter.cpp +++ b/dChatFilter/dChatFilter.cpp @@ -12,6 +12,7 @@ #include "dConfig.h" #include "Database.h" #include "Game.h" +#include "eGameMasterLevel.h" using namespace dChatFilterDCF; @@ -108,8 +109,8 @@ void dChatFilter::ExportWordlistToDCF(const std::string& filepath, bool whiteLis } } -std::vector<std::pair<uint8_t, uint8_t>> dChatFilter::IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList) { - if (gmLevel > GAME_MASTER_LEVEL_FORUM_MODERATOR) return { }; //If anything but a forum mod, return true. +std::vector<std::pair<uint8_t, uint8_t>> dChatFilter::IsSentenceOkay(const std::string& message, eGameMasterLevel gmLevel, bool whiteList) { + if (gmLevel > eGameMasterLevel::FORUM_MODERATOR) return { }; //If anything but a forum mod, return true. if (message.empty()) return { }; if (!whiteList && m_DeniedWords.empty()) return { { 0, message.length() } }; diff --git a/dChatFilter/dChatFilter.h b/dChatFilter/dChatFilter.h index 7e7dd859..d00525ce 100644 --- a/dChatFilter/dChatFilter.h +++ b/dChatFilter/dChatFilter.h @@ -4,6 +4,7 @@ #include "dCommonVars.h" +enum class eGameMasterLevel : uint8_t; namespace dChatFilterDCF { static const uint32_t header = ('D' + ('C' << 8) + ('F' << 16) + ('B' << 24)); static const uint32_t formatVersion = 2; @@ -23,7 +24,7 @@ public: void ReadWordlistPlaintext(const std::string& filepath, bool whiteList); bool ReadWordlistDCF(const std::string& filepath, bool whiteList); void ExportWordlistToDCF(const std::string& filepath, bool whiteList); - std::vector<std::pair<uint8_t, uint8_t>> IsSentenceOkay(const std::string& message, int gmLevel, bool whiteList = true); + std::vector<std::pair<uint8_t, uint8_t>> IsSentenceOkay(const std::string& message, eGameMasterLevel gmLevel, bool whiteList = true); private: bool m_DontGenerateDCF; diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index 2b7f63dc..16cae3c9 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -175,21 +175,6 @@ union suchar { char svalue; }; -//=========== DLU ENUMS ============ - -enum eGameMasterLevel : int32_t { - GAME_MASTER_LEVEL_CIVILIAN = 0, // Normal player. - GAME_MASTER_LEVEL_FORUM_MODERATOR = 1, // No permissions on live servers. - GAME_MASTER_LEVEL_JUNIOR_MODERATOR = 2, // Can kick/mute and pull chat logs. - GAME_MASTER_LEVEL_MODERATOR = 3, // Can return lost items. - GAME_MASTER_LEVEL_SENIOR_MODERATOR = 4, // Can ban. - GAME_MASTER_LEVEL_LEAD_MODERATOR = 5, // Can approve properties. - GAME_MASTER_LEVEL_JUNIOR_DEVELOPER = 6, // Junior developer & future content team. Civilan on live. - GAME_MASTER_LEVEL_INACTIVE_DEVELOPER = 7, // Inactive developer, limited permissions. - GAME_MASTER_LEVEL_DEVELOPER = 8, // Active developer, full permissions on live. - GAME_MASTER_LEVEL_OPERATOR = 9 // Can shutdown server for restarts & updates. -}; - //=========== LU ENUMS ============ //! An enum for object ID bits diff --git a/dCommon/dEnums/eGameMasterLevel.h b/dCommon/dEnums/eGameMasterLevel.h new file mode 100644 index 00000000..a63c1caf --- /dev/null +++ b/dCommon/dEnums/eGameMasterLevel.h @@ -0,0 +1,20 @@ +#ifndef __EGAMEMASTERLEVEL__H__ +#define __EGAMEMASTERLEVEL__H__ + +#include <cstdint> + +enum class eGameMasterLevel : uint8_t { + CIVILIAN = 0, // Normal player. + FORUM_MODERATOR = 1, // No permissions on live servers. + JUNIOR_MODERATOR = 2, // Can kick/mute and pull chat logs. + MODERATOR = 3, // Can return lost items. + SENIOR_MODERATOR = 4, // Can ban. + LEAD_MODERATOR = 5, // Can approve properties. + JUNIOR_DEVELOPER = 6, // Junior developer & future content team. Civilan on live. + INACTIVE_DEVELOPER = 7, // Inactive developer, limited permissions. + DEVELOPER = 8, // Active developer, full permissions on live. + OPERATOR = 9 // Can shutdown server for restarts & updates. +}; + + +#endif //!__EGAMEMASTERLEVEL__H__ diff --git a/dGame/Character.cpp b/dGame/Character.cpp index 16497fc3..b8d08854 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -18,6 +18,7 @@ #include "InventoryComponent.h" #include "eMissionTaskType.h" #include "eMissionState.h" +#include "eGameMasterLevel.h" Character::Character(uint32_t id, User* parentUser) { //First load the name, etc: @@ -204,7 +205,9 @@ void Character::DoQuickXMLDataParse() { tinyxml2::XMLElement* character = m_Doc->FirstChildElement("obj")->FirstChildElement("char"); if (character) { character->QueryAttribute("cc", &m_Coins); - character->QueryAttribute("gm", &m_GMLevel); + int32_t gm_level = 0; + character->QueryAttribute("gm", &gm_level); + m_GMLevel = static_cast<eGameMasterLevel>(gm_level); uint64_t lzidConcat = 0; if (character->FindAttribute("lzid")) { @@ -304,7 +307,7 @@ void Character::SaveXMLToDatabase() { tinyxml2::XMLElement* character = m_Doc->FirstChildElement("obj")->FirstChildElement("char"); if (character) { - character->SetAttribute("gm", m_GMLevel); + character->SetAttribute("gm", static_cast<uint32_t>(m_GMLevel)); character->SetAttribute("cc", m_Coins); auto zoneInfo = dZoneManager::Instance()->GetZone()->GetZoneID(); @@ -545,7 +548,7 @@ void Character::OnZoneLoad() { const auto maxGMLevel = m_ParentUser->GetMaxGMLevel(); // This does not apply to the GMs - if (maxGMLevel > GAME_MASTER_LEVEL_CIVILIAN) { + if (maxGMLevel > eGameMasterLevel::CIVILIAN) { return; } diff --git a/dGame/Character.h b/dGame/Character.h index d77dd022..2f0abba5 100644 --- a/dGame/Character.h +++ b/dGame/Character.h @@ -15,6 +15,7 @@ class User; struct Packet; class Entity; enum class ePermissionMap : uint64_t; +enum class eGameMasterLevel : uint8_t; /** * Meta information about a character, like their name and style @@ -308,13 +309,13 @@ public: * Gets the GM level of the character * @return the GM level */ - int32_t GetGMLevel() const { return m_GMLevel; } + eGameMasterLevel GetGMLevel() const { return m_GMLevel; } /** * Sets the GM level of the character * @param value the GM level to set */ - void SetGMLevel(uint8_t value) { m_GMLevel = value; } + void SetGMLevel(eGameMasterLevel value) { m_GMLevel = value; } /** * Gets the current amount of coins of the character @@ -481,7 +482,7 @@ private: * * @see eGameMasterLevel */ - int32_t m_GMLevel; + eGameMasterLevel m_GMLevel; /** * Bitmap of permission attributes this character has. diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 13507527..c33a7247 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -70,6 +70,7 @@ #include "RailActivatorComponent.h" #include "LUPExhibitComponent.h" #include "TriggerComponent.h" +#include "eGameMasterLevel.h" #include "eReplicaComponentType.h" // Table includes @@ -89,7 +90,7 @@ Entity::Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity) m_TemplateID = info.lot; m_ParentEntity = parentEntity; m_Character = nullptr; - m_GMLevel = 0; + m_GMLevel = eGameMasterLevel::CIVILIAN; m_CollectibleID = 0; m_NetworkID = 0; m_Groups = {}; @@ -857,7 +858,7 @@ void Entity::SetProximityRadius(dpEntity* entity, std::string name) { proxMon->SetProximityRadius(entity, name); } -void Entity::SetGMLevel(uint8_t value) { +void Entity::SetGMLevel(eGameMasterLevel value) { m_GMLevel = value; if (GetParentUser()) { Character* character = GetParentUser()->GetLastUsedChar(); @@ -969,7 +970,7 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke outBitStream->Write0(); //ObjectWorldState - if (m_GMLevel != 0) { + if (m_GMLevel != eGameMasterLevel::CIVILIAN) { outBitStream->Write1(); outBitStream->Write(m_GMLevel); } else outBitStream->Write0(); //No GM Level diff --git a/dGame/Entity.h b/dGame/Entity.h index ae16fb82..f8abff31 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -31,6 +31,7 @@ class Item; class Character; class EntityCallbackTimer; enum class eTriggerEventType; +enum class eGameMasterLevel : uint8_t; enum class eReplicaComponentType : uint32_t; namespace CppScripts { @@ -60,7 +61,7 @@ public: Character* GetCharacter() const { return m_Character; } - uint8_t GetGMLevel() const { return m_GMLevel; } + eGameMasterLevel GetGMLevel() const { return m_GMLevel; } uint8_t GetCollectibleID() const { return uint8_t(m_CollectibleID); } @@ -108,7 +109,7 @@ public: void SetCharacter(Character* value) { m_Character = value; } - void SetGMLevel(uint8_t value); + void SetGMLevel(eGameMasterLevel value); void SetOwnerOverride(LWOOBJID value); @@ -308,7 +309,7 @@ protected: Entity* m_ParentEntity; //For spawners and the like std::vector<Entity*> m_ChildEntities; - uint8_t m_GMLevel; + eGameMasterLevel m_GMLevel; uint16_t m_CollectibleID; std::vector<std::string> m_Groups; uint16_t m_NetworkID; diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index e79ada25..31b755fe 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -20,6 +20,7 @@ #include "MessageIdentifiers.h" #include "dConfig.h" #include "eTriggerEventType.h" +#include "eGameMasterLevel.h" #include "eReplicaComponentType.h" EntityManager* EntityManager::m_Address = nullptr; @@ -370,7 +371,7 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr // PacketUtils::SavePacket("[24]_"+std::to_string(entity->GetObjectID()) + "_" + std::to_string(m_SerializationCounter) + ".bin", (char*)stream.GetData(), stream.GetNumberOfBytesUsed()); if (entity->IsPlayer()) { - if (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN) { + if (entity->GetGMLevel() > eGameMasterLevel::CIVILIAN) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), true, sysAddr); } } diff --git a/dGame/User.cpp b/dGame/User.cpp index dc607cd0..55bbcc09 100644 --- a/dGame/User.cpp +++ b/dGame/User.cpp @@ -6,13 +6,14 @@ #include "Game.h" #include "dZoneManager.h" #include "eServerDisconnectIdentifiers.h" +#include "eGameMasterLevel.h" User::User(const SystemAddress& sysAddr, const std::string& username, const std::string& sessionKey) { m_AccountID = 0; m_Username = ""; m_SessionKey = ""; - m_MaxGMLevel = 0; //The max GM level this account can assign to it's characters + m_MaxGMLevel = eGameMasterLevel::CIVILIAN; //The max GM level this account can assign to it's characters m_LastCharID = 0; m_SessionKey = sessionKey; @@ -33,7 +34,7 @@ User::User(const SystemAddress& sysAddr, const std::string& username, const std: sql::ResultSet* res = stmt->executeQuery(); while (res->next()) { m_AccountID = res->getUInt(1); - m_MaxGMLevel = res->getInt(2); + m_MaxGMLevel = static_cast<eGameMasterLevel>(res->getInt(2)); m_MuteExpire = 0; //res->getUInt64(3); } diff --git a/dGame/User.h b/dGame/User.h index 59416c4c..3201538e 100644 --- a/dGame/User.h +++ b/dGame/User.h @@ -9,6 +9,7 @@ #include <unordered_map> class Character; +enum class eGameMasterLevel : uint8_t; struct BehaviorParams { uint32_t behavior; @@ -29,7 +30,7 @@ public: std::string& GetSessionKey() { return m_SessionKey; } SystemAddress& GetSystemAddress() { return m_SystemAddress; } - uint32_t GetMaxGMLevel() { return m_MaxGMLevel; } + eGameMasterLevel GetMaxGMLevel() { return m_MaxGMLevel; } uint32_t GetLastCharID() { return m_LastCharID; } void SetLastCharID(uint32_t newCharID) { m_LastCharID = newCharID; } @@ -61,7 +62,7 @@ private: std::string m_SessionKey; SystemAddress m_SystemAddress; - uint32_t m_MaxGMLevel; //The max GM level this account can assign to it's characters + eGameMasterLevel m_MaxGMLevel; //The max GM level this account can assign to it's characters uint32_t m_LastCharID; std::vector<Character*> m_Characters; LWOOBJID m_LoggedInCharID; diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index 93469daa..4f0c456d 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -23,6 +23,7 @@ #include "AssetManager.h" #include "CDClientDatabase.h" #include "dMessageIdentifiers.h" +#include "eGameMasterLevel.h" UserManager* UserManager::m_Address = nullptr; @@ -330,7 +331,7 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) //Check to see if our name was pre-approved: bool nameOk = IsNamePreapproved(name); - if (!nameOk && u->GetMaxGMLevel() > 1) nameOk = true; + if (!nameOk && u->GetMaxGMLevel() > eGameMasterLevel::FORUM_MODERATOR) nameOk = true; if (name != "") { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("INSERT INTO `charinfo`(`id`, `account_id`, `name`, `pending_name`, `needs_rename`, `last_login`) VALUES (?,?,?,?,?,?)"); diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 98540bd0..6394cc32 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -14,6 +14,7 @@ #include "GameMessages.h" #include "Item.h" #include "AMFFormat.h" +#include "eGameMasterLevel.h" CharacterComponent::CharacterComponent(Entity* parent, Character* character) : Component(parent) { m_Character = character; @@ -165,9 +166,9 @@ void CharacterComponent::SetPvpEnabled(const bool value) { m_PvpEnabled = value; } -void CharacterComponent::SetGMLevel(int gmlevel) { +void CharacterComponent::SetGMLevel(eGameMasterLevel gmlevel) { m_DirtyGMInfo = true; - if (gmlevel > 0) m_IsGM = true; + if (gmlevel > eGameMasterLevel::CIVILIAN) m_IsGM = true; else m_IsGM = false; m_GMLevel = gmlevel; } @@ -239,7 +240,7 @@ void CharacterComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { // End custom attributes // - if (m_GMLevel > 0) { + if (m_GMLevel > eGameMasterLevel::CIVILIAN) { m_IsGM = true; m_DirtyGMInfo = true; m_EditorLevel = m_GMLevel; diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index 613f2322..0e047494 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -178,7 +178,7 @@ public: * Sets the GM level of the character, should be called in the entity. Here it's set for serialization * @param gmlevel the gm level to set */ - void SetGMLevel(int gmlevel); + void SetGMLevel(eGameMasterLevel gmlevel); /** * Initializes the player statistics from the string stored in the XML @@ -333,7 +333,7 @@ private: /** * The current GM level of this character (anything > 0 counts as a GM) */ - unsigned char m_GMLevel; + eGameMasterLevel m_GMLevel; /** * Whether the character has HF enabled @@ -343,7 +343,7 @@ private: /** * The level of the character in HF */ - unsigned char m_EditorLevel; + eGameMasterLevel m_EditorLevel; /** * Whether the currently active activity has been changed diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 5549f952..090e5791 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -22,7 +22,7 @@ #include "Database.h" #include "EntityInfo.h" #include "eMissionTaskType.h" - +#include "eGameMasterLevel.h" std::unordered_map<LOT, PetComponent::PetPuzzleData> PetComponent::buildCache{}; std::unordered_map<LWOOBJID, LWOOBJID> PetComponent::currentActivities{}; @@ -988,7 +988,7 @@ void PetComponent::Command(NiPoint3 position, LWOOBJID source, int32_t commandTy // TODO: Go to player } - if (owner->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (owner->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { ChatPackets::SendSystemMessage(owner->GetSystemAddress(), u"Commmand Type: " + (GeneralUtils::to_u16string(commandType)) + u" - Type Id: " + (GeneralUtils::to_u16string(typeId))); } } @@ -1080,7 +1080,7 @@ void PetComponent::SetPetNameForModeration(const std::string& petName) { int approved = 1; //default, in mod //Make sure that the name isn't already auto-approved: - if (Game::chatFilter->IsSentenceOkay(petName, 0).empty()) { + if (Game::chatFilter->IsSentenceOkay(petName, eGameMasterLevel::CIVILIAN).empty()) { approved = 2; //approved } diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index fa838ed7..c251dc96 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -12,6 +12,7 @@ #include "UserManager.h" #include "dLogger.h" #include "AMFFormat.h" +#include "eGameMasterLevel.h" PropertyEntranceComponent::PropertyEntranceComponent(uint32_t componentID, Entity* parent) : Component(parent) { this->propertyQueries = {}; @@ -271,7 +272,7 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl bool isModeratorApproved = propertyEntry->getBoolean(10); - if (!isModeratorApproved && entity->GetGMLevel() >= GAME_MASTER_LEVEL_LEAD_MODERATOR) { + if (!isModeratorApproved && entity->GetGMLevel() >= eGameMasterLevel::LEAD_MODERATOR) { propertyName = "[AWAITING APPROVAL]"; propertyDescription = "[AWAITING APPROVAL]"; isModeratorApproved = true; diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index bafa1faa..1bc8c01f 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -303,7 +303,7 @@ bool ScriptedActivityComponent::HasLobby() const { bool ScriptedActivityComponent::IsValidActivity(Entity* player) { // Makes it so that scripted activities with an unimplemented map cannot be joined - /*if (player->GetGMLevel() < GAME_MASTER_LEVEL_DEVELOPER && (m_ActivityInfo.instanceMapID == 1302 || m_ActivityInfo.instanceMapID == 1301)) { + /*if (player->GetGMLevel() < eGameMasterLevel::DEVELOPER && (m_ActivityInfo.instanceMapID == 1302 || m_ActivityInfo.instanceMapID == 1301)) { if (m_Parent->GetLOT() == 4860) { auto* missionComponent = player->GetComponent<MissionComponent>(); missionComponent->CompleteMission(229); diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 8604d136..2941a0f9 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -409,7 +409,7 @@ void GameMessages::SendServerDoneLoadingAllObjects(Entity* entity, const SystemA SEND_PACKET; } -void GameMessages::SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level) { +void GameMessages::SendChatModeUpdate(const LWOOBJID& objectID, eGameMasterLevel level) { CBITSTREAM; CMSGHEADER; bitStream.Write(objectID); @@ -418,7 +418,7 @@ void GameMessages::SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level) { SEND_PACKET_BROADCAST; } -void GameMessages::SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level) { +void GameMessages::SendGMLevelBroadcast(const LWOOBJID& objectID, eGameMasterLevel level) { CBITSTREAM; CMSGHEADER; bitStream.Write(objectID); diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 7305e429..1372003e 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -21,6 +21,7 @@ enum class eAnimationFlags : uint32_t; enum class eUnequippableActiveType; enum eInventoryType : uint32_t; +enum class eGameMasterLevel : uint8_t; namespace GameMessages { class PropertyDataMessage; @@ -61,8 +62,8 @@ namespace GameMessages { void SendRestoreToPostLoadStats(Entity* entity, const SystemAddress& sysAddr); void SendServerDoneLoadingAllObjects(Entity* entity, const SystemAddress& sysAddr); - void SendGMLevelBroadcast(const LWOOBJID& objectID, uint8_t level); - void SendChatModeUpdate(const LWOOBJID& objectID, uint8_t level); + void SendGMLevelBroadcast(const LWOOBJID& objectID, eGameMasterLevel level); + void SendChatModeUpdate(const LWOOBJID& objectID, eGameMasterLevel level); void SendAddItemToInventoryClientSync(Entity* entity, const SystemAddress& sysAddr, Item* item, const LWOOBJID& objectID, bool showFlyingLoot, int itemCount, LWOOBJID subKey = LWOOBJID_EMPTY, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); void SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFlagID, bool bFlag, const SystemAddress& sysAddr); @@ -623,7 +624,7 @@ namespace GameMessages { void HandleReportBug(RakNet::BitStream* inStream, Entity* entity); void SendRemoveBuff(Entity* entity, bool fromUnEquip, bool removeImmunity, uint32_t buffId); - + // bubble void HandleDeactivateBubbleBuff(RakNet::BitStream* inStream, Entity* entity); diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 1f3da6c7..f9bf4884 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -75,6 +75,7 @@ #include "eMissionState.h" #include "TriggerComponent.h" #include "eServerDisconnectIdentifiers.h" +#include "eGameMasterLevel.h" #include "eReplicaComponentType.h" #include "CDObjectsTable.h" @@ -121,19 +122,20 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit //Game::logger->Log("SlashCommandHandler", "Received chat command \"%s\"", GeneralUtils::UTF16ToWTF8(command).c_str()); User* user = UserManager::Instance()->GetUser(sysAddr); - if ((chatCommand == "setgmlevel" || chatCommand == "makegm" || chatCommand == "gmlevel") && user->GetMaxGMLevel() > GAME_MASTER_LEVEL_CIVILIAN) { + if ((chatCommand == "setgmlevel" || chatCommand == "makegm" || chatCommand == "gmlevel") && user->GetMaxGMLevel() > eGameMasterLevel::CIVILIAN) { if (args.size() != 1) return; - uint32_t level; + uint32_t level_intermed = 0; - if (!GeneralUtils::TryParse(args[0], level)) { + if (!GeneralUtils::TryParse(args[0], level_intermed)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid gm level."); return; } + eGameMasterLevel level = static_cast<eGameMasterLevel>(level_intermed); #ifndef DEVELOPER_SERVER - if (user->GetMaxGMLevel() == GAME_MASTER_LEVEL_JUNIOR_DEVELOPER) { - level = GAME_MASTER_LEVEL_CIVILIAN; + if (user->GetMaxGMLevel() == eGameMasterLevel::JUNIOR_DEVELOPER) { + level = eGameMasterLevel::CIVILIAN; } #endif @@ -146,9 +148,9 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (success) { - if (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN && level == GAME_MASTER_LEVEL_CIVILIAN) { + if (entity->GetGMLevel() > eGameMasterLevel::CIVILIAN && level == eGameMasterLevel::CIVILIAN) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); - } else if (entity->GetGMLevel() == GAME_MASTER_LEVEL_CIVILIAN && level > GAME_MASTER_LEVEL_CIVILIAN) { + } else if (entity->GetGMLevel() == eGameMasterLevel::CIVILIAN && level > eGameMasterLevel::CIVILIAN) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); } @@ -160,10 +162,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } #ifndef DEVELOPER_SERVER - if ((entity->GetGMLevel() > user->GetMaxGMLevel()) || (entity->GetGMLevel() > GAME_MASTER_LEVEL_CIVILIAN && user->GetMaxGMLevel() == GAME_MASTER_LEVEL_JUNIOR_DEVELOPER)) { - WorldPackets::SendGMLevelChange(sysAddr, true, user->GetMaxGMLevel(), entity->GetGMLevel(), GAME_MASTER_LEVEL_CIVILIAN); - GameMessages::SendChatModeUpdate(entity->GetObjectID(), GAME_MASTER_LEVEL_CIVILIAN); - entity->SetGMLevel(GAME_MASTER_LEVEL_CIVILIAN); + if ((entity->GetGMLevel() > user->GetMaxGMLevel()) || (entity->GetGMLevel() > eGameMasterLevel::CIVILIAN && user->GetMaxGMLevel() == eGameMasterLevel::JUNIOR_DEVELOPER)) { + WorldPackets::SendGMLevelChange(sysAddr, true, user->GetMaxGMLevel(), entity->GetGMLevel(), eGameMasterLevel::CIVILIAN); + GameMessages::SendChatModeUpdate(entity->GetObjectID(), eGameMasterLevel::CIVILIAN); + entity->SetGMLevel(eGameMasterLevel::CIVILIAN); GameMessages::SendToggleGMInvis(entity->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); @@ -171,7 +173,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } #endif - if (chatCommand == "togglenameplate" && (Game::config->GetValue("allownameplateoff") == "1" || entity->GetGMLevel() > GAME_MASTER_LEVEL_DEVELOPER)) { + if (chatCommand == "togglenameplate" && (Game::config->GetValue("allownameplateoff") == "1" || entity->GetGMLevel() > eGameMasterLevel::DEVELOPER)) { auto* character = entity->GetCharacter(); if (character && character->GetBillboardVisible()) { @@ -349,7 +351,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit }); } - if (user->GetMaxGMLevel() == 0 || entity->GetGMLevel() >= 0) { + if (user->GetMaxGMLevel() == eGameMasterLevel::CIVILIAN || entity->GetGMLevel() >= eGameMasterLevel::CIVILIAN) { if (chatCommand == "die") { entity->Smash(entity->GetObjectID()); } @@ -375,7 +377,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Map: " + (GeneralUtils::to_u16string(zoneId.GetMapID())) + u"\nClone: " + (GeneralUtils::to_u16string(zoneId.GetCloneID())) + u"\nInstance: " + (GeneralUtils::to_u16string(zoneId.GetInstanceID()))); } - if (entity->GetGMLevel() == 0) return; + if (entity->GetGMLevel() == eGameMasterLevel::CIVILIAN) return; } // Log command to database @@ -385,7 +387,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit stmt->execute(); delete stmt; - if (chatCommand == "setminifig" && args.size() == 2 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_FORUM_MODERATOR) { // could break characters so only allow if GM > 0 + 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)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid Minifig Item Id ID."); @@ -429,7 +431,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameMessages::SendToggleGMInvis(entity->GetObjectID(), false, UNASSIGNED_SYSTEM_ADDRESS); // need to retoggle because it gets reenabled on creation of new character } - if ((chatCommand == "playanimation" || chatCommand == "playanim") && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if ((chatCommand == "playanimation" || chatCommand == "playanim") && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { std::u16string anim = GeneralUtils::ASCIIToUTF16(args[0], args[0].size()); GameMessages::SendPlayAnimation(entity, anim); auto* possessorComponent = entity->GetComponent<PossessorComponent>(); @@ -439,7 +441,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "list-spawns" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "list-spawns" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { for (const auto& pair : EntityManager::Instance()->GetSpawnPointEntities()) { ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16(pair.first)); } @@ -449,7 +451,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "unlock-emote" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "unlock-emote" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { int32_t emoteID; if (!GeneralUtils::TryParse(args[0], emoteID)) { @@ -460,11 +462,11 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit entity->GetCharacter()->UnlockEmote(emoteID); } - if (chatCommand == "force-save" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "force-save" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { entity->GetCharacter()->SaveXMLToDatabase(); } - if (chatCommand == "kill" && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "kill" && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { ChatPackets::SendSystemMessage(sysAddr, u"Brutally murdering that player, if online on this server."); auto* user = UserManager::Instance()->GetUser(args[0]); @@ -479,7 +481,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "speedboost" && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "speedboost" && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { float boost; if (!GeneralUtils::TryParse(args[0], boost)) { @@ -510,7 +512,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit EntityManager::Instance()->SerializeEntity(entity); } - if (chatCommand == "freecam" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "freecam" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { const auto state = !entity->GetVar<bool>(u"freecam"); entity->SetVar<bool>(u"freecam", state); @@ -520,7 +522,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "setcontrolscheme" && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "setcontrolscheme" && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { uint32_t scheme; if (!GeneralUtils::TryParse(args[0], scheme)) { @@ -534,7 +536,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "approveproperty" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_LEAD_MODERATOR) { + if (chatCommand == "approveproperty" && entity->GetGMLevel() >= eGameMasterLevel::LEAD_MODERATOR) { if (PropertyManagementComponent::Instance() != nullptr) { PropertyManagementComponent::Instance()->UpdateApprovedStatus(true); @@ -543,7 +545,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "setuistate" && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "setuistate" && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { AMFStringValue* value = new AMFStringValue(); value->SetStringValue(args[0]); @@ -556,7 +558,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "toggle" && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "toggle" && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { AMFTrueValue* value = new AMFTrueValue(); AMFArrayValue amfArgs; @@ -568,7 +570,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if ((chatCommand == "setinventorysize" || chatCommand == "setinvsize") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { + if ((chatCommand == "setinventorysize" || chatCommand == "setinvsize") && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { uint32_t size; if (!GeneralUtils::TryParse(args.at(0), size)) { @@ -609,7 +611,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "runmacro" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "runmacro" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() != 1) return; // Only process if input does not contain separator charaters @@ -639,7 +641,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "addmission" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "addmission" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 0) return; uint32_t missionID; @@ -654,7 +656,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "completemission" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "completemission" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 0) return; uint32_t missionID; @@ -669,7 +671,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "setflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) { + if (chatCommand == "setflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { uint32_t flagId; if (!GeneralUtils::TryParse(args[0], flagId)) { @@ -680,7 +682,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit entity->GetCharacter()->SetPlayerFlag(flagId, true); } - if (chatCommand == "setflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 2) { + if (chatCommand == "setflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 2) { uint32_t flagId; std::string onOffFlag = args[0]; if (!GeneralUtils::TryParse(args[1], flagId)) { @@ -693,7 +695,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } entity->GetCharacter()->SetPlayerFlag(flagId, onOffFlag == "on"); } - if (chatCommand == "clearflag" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) { + if (chatCommand == "clearflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { uint32_t flagId; if (!GeneralUtils::TryParse(args[0], flagId)) { @@ -704,7 +706,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit entity->GetCharacter()->SetPlayerFlag(flagId, false); } - if (chatCommand == "resetmission" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "resetmission" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 0) return; uint32_t missionID; @@ -731,7 +733,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "playeffect" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 3) { + if (chatCommand == "playeffect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 3) { int32_t effectID = 0; if (!GeneralUtils::TryParse(args[0], effectID)) { @@ -742,11 +744,11 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameMessages::SendPlayFXEffect(entity->GetObjectID(), effectID, GeneralUtils::ASCIIToUTF16(args[1]), args[2]); } - if (chatCommand == "stopeffect" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { + if (chatCommand == "stopeffect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { GameMessages::SendStopFXEffect(entity, true, args[0]); } - if (chatCommand == "setanntitle" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "setanntitle" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() < 0) return; std::stringstream ss; @@ -757,7 +759,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "setannmsg" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "setannmsg" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() < 0) return; std::stringstream ss; @@ -768,7 +770,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "announce" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "announce" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (entity->GetCharacter()->GetAnnouncementTitle().size() == 0 || entity->GetCharacter()->GetAnnouncementMessage().size() == 0) { ChatPackets::SendSystemMessage(sysAddr, u"Use /setanntitle <title> & /setannmsg <msg> first!"); return; @@ -778,7 +780,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "shutdownuniverse" && entity->GetGMLevel() == GAME_MASTER_LEVEL_OPERATOR) { + if (chatCommand == "shutdownuniverse" && entity->GetGMLevel() == eGameMasterLevel::OPERATOR) { //Tell the master server that we're going to be shutting down whole "universe": CBITSTREAM; PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SHUTDOWN_UNIVERSE); @@ -790,7 +792,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "getnavmeshheight" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "getnavmeshheight" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto control = static_cast<ControllablePhysicsComponent*>(entity->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (!control) return; @@ -799,7 +801,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, msg); } - if (chatCommand == "gmadditem" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "gmadditem" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 1) { uint32_t itemLOT; @@ -834,7 +836,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "mailitem" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_MODERATOR && args.size() >= 2) { + if (chatCommand == "mailitem" && entity->GetGMLevel() >= eGameMasterLevel::MODERATOR && args.size() >= 2) { const auto& playerName = args[0]; sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id from charinfo WHERE name=? LIMIT 1;"); @@ -883,7 +885,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "setname" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "setname" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { std::string name = ""; for (const auto& arg : args) { @@ -893,7 +895,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameMessages::SendSetName(entity->GetObjectID(), GeneralUtils::UTF8ToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); } - if (chatCommand == "title" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "title" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { std::string name = entity->GetCharacter()->GetName() + " - "; for (const auto& arg : args) { @@ -903,7 +905,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameMessages::SendSetName(entity->GetObjectID(), GeneralUtils::UTF8ToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); } - if ((chatCommand == "teleport" || chatCommand == "tele") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_JUNIOR_MODERATOR) { + if ((chatCommand == "teleport" || chatCommand == "tele") && entity->GetGMLevel() >= eGameMasterLevel::JUNIOR_MODERATOR) { NiPoint3 pos{}; if (args.size() == 3) { @@ -969,7 +971,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "tpall" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "tpall" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { const auto pos = entity->GetPosition(); const auto characters = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::CHARACTER); @@ -981,7 +983,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "dismount" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "dismount" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* possessorComponent = entity->GetComponent<PossessorComponent>(); if (possessorComponent) { auto possessableId = possessorComponent->GetPossessable(); @@ -992,7 +994,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "fly" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_JUNIOR_DEVELOPER) { + if (chatCommand == "fly" && entity->GetGMLevel() >= eGameMasterLevel::JUNIOR_DEVELOPER) { auto* character = entity->GetCharacter(); if (character) { @@ -1028,7 +1030,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit //------- GM COMMANDS TO ACTUALLY MODERATE -------- - if (chatCommand == "mute" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_JUNIOR_DEVELOPER) { + if (chatCommand == "mute" && entity->GetGMLevel() >= eGameMasterLevel::JUNIOR_DEVELOPER) { if (args.size() >= 1) { auto* player = Player::GetPlayer(args[0]); @@ -1123,7 +1125,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "kick" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_JUNIOR_MODERATOR) { + if (chatCommand == "kick" && entity->GetGMLevel() >= eGameMasterLevel::JUNIOR_MODERATOR) { if (args.size() == 1) { auto* player = Player::GetPlayer(args[0]); @@ -1141,7 +1143,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "ban" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_SENIOR_MODERATOR) { + if (chatCommand == "ban" && entity->GetGMLevel() >= eGameMasterLevel::SENIOR_MODERATOR) { if (args.size() == 1) { auto* player = Player::GetPlayer(args[0]); @@ -1190,7 +1192,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit //------------------------------------------------- - if (chatCommand == "buffme" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "buffme" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto dest = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); if (dest) { dest->SetHealth(999); @@ -1203,7 +1205,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit EntityManager::Instance()->SerializeEntity(entity); } - if (chatCommand == "startcelebration" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() == 1) { + if (chatCommand == "startcelebration" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { int32_t celebration; if (!GeneralUtils::TryParse(args[0], celebration)) { @@ -1214,7 +1216,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameMessages::SendStartCelebrationEffect(entity, entity->GetSystemAddress(), celebration); } - if (chatCommand == "buffmed" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "buffmed" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto dest = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); if (dest) { dest->SetHealth(9); @@ -1227,7 +1229,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit EntityManager::Instance()->SerializeEntity(entity); } - if (chatCommand == "refillstats" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "refillstats" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto dest = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); if (dest) { @@ -1239,7 +1241,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit EntityManager::Instance()->SerializeEntity(entity); } - if (chatCommand == "lookup" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { + if (chatCommand == "lookup" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto query = CDClientDatabase::CreatePreppedStmt( "SELECT `id`, `name` FROM `Objects` WHERE `displayName` LIKE ?1 OR `name` LIKE ?1 OR `description` LIKE ?1 LIMIT 50"); // Concatenate all of the arguments into a single query so a multi word query can be used properly. @@ -1261,7 +1263,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "spawn" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { + if (chatCommand == "spawn" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { ControllablePhysicsComponent* comp = static_cast<ControllablePhysicsComponent*>(entity->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (!comp) return; @@ -1302,7 +1304,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit EntityManager::Instance()->ConstructEntity(newEntity); } - if (chatCommand == "spawngroup" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 3) { + if (chatCommand == "spawngroup" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 3) { auto controllablePhysicsComponent = entity->GetComponent<ControllablePhysicsComponent>(); if (!controllablePhysicsComponent) return; @@ -1353,7 +1355,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if ((chatCommand == "giveuscore") && args.size() >= 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if ((chatCommand == "giveuscore") && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { int32_t uscore; if (!GeneralUtils::TryParse(args[0], uscore)) { @@ -1375,7 +1377,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), uscore, lootType); } - if ((chatCommand == "setlevel") && args.size() >= 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if ((chatCommand == "setlevel") && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { // We may be trying to set a specific players level to a level. If so override the entity with the requested players. std::string requestedPlayerToSetLevelOf = ""; if (args.size() > 1) { @@ -1443,7 +1445,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "pos" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "pos" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { const auto position = entity->GetPosition(); ChatPackets::SendSystemMessage(sysAddr, u"<" + (GeneralUtils::to_u16string(position.x)) + u", " + (GeneralUtils::to_u16string(position.y)) + u", " + (GeneralUtils::to_u16string(position.z)) + u">"); @@ -1451,7 +1453,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit std::cout << position.x << ", " << position.y << ", " << position.z << std::endl; } - if (chatCommand == "rot" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "rot" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { const auto rotation = entity->GetRotation(); ChatPackets::SendSystemMessage(sysAddr, u"<" + (GeneralUtils::to_u16string(rotation.w)) + u", " + (GeneralUtils::to_u16string(rotation.x)) + u", " + (GeneralUtils::to_u16string(rotation.y)) + u", " + (GeneralUtils::to_u16string(rotation.z)) + u">"); @@ -1459,22 +1461,22 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit std::cout << rotation.w << ", " << rotation.x << ", " << rotation.y << ", " << rotation.z << std::endl; } - if (chatCommand == "locrow" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "locrow" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { const auto position = entity->GetPosition(); const auto rotation = entity->GetRotation(); std::cout << "<location x=\"" << position.x << "\" y=\"" << position.y << "\" z=\"" << position.z << "\" rw=\"" << rotation.w << "\" rx=\"" << rotation.x << "\" ry=\"" << rotation.y << "\" rz=\"" << rotation.z << "\" />" << std::endl; } - if (chatCommand == "playlvlfx" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "playlvlfx" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { GameMessages::SendPlayFXEffect(entity, 7074, u"create", "7074", LWOOBJID_EMPTY, 1.0f, 1.0f, true); } - if (chatCommand == "playrebuildfx" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "playrebuildfx" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { GameMessages::SendPlayFXEffect(entity, 230, u"rebuild", "230", LWOOBJID_EMPTY, 1.0f, 1.0f, true); } - if ((chatCommand == "freemoney" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) && args.size() == 1) { + if ((chatCommand == "freemoney" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) && args.size() == 1) { int32_t money; if (!GeneralUtils::TryParse(args[0], money)) { @@ -1486,7 +1488,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ch->SetCoins(ch->GetCoins() + money, eLootSourceType::LOOT_SOURCE_MODERATION); } - if ((chatCommand == "setcurrency") && args.size() == 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if ((chatCommand == "setcurrency") && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { int32_t money; if (!GeneralUtils::TryParse(args[0], money)) { @@ -1499,13 +1501,13 @@ 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() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "gminvis" && entity->GetParentUser()->GetMaxGMLevel() >= eGameMasterLevel::DEVELOPER) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); return; } - if (chatCommand == "gmimmune" && args.size() >= 1 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "gmimmune" && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* destroyableComponent = entity->GetComponent<DestroyableComponent>(); int32_t state = false; @@ -1522,7 +1524,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "buff" && args.size() >= 2 && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "buff" && args.size() >= 2 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* buffComponent = entity->GetComponent<BuffComponent>(); int32_t id = 0; @@ -1545,7 +1547,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if ((chatCommand == "testmap" && args.size() >= 1) && entity->GetGMLevel() >= GAME_MASTER_LEVEL_FORUM_MODERATOR) { + if ((chatCommand == "testmap" && args.size() >= 1) && entity->GetGMLevel() >= eGameMasterLevel::FORUM_MODERATOR) { ChatPackets::SendSystemMessage(sysAddr, u"Requesting map change..."); uint32_t reqZone; LWOCLONEID cloneId = 0; @@ -1604,7 +1606,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "createprivate" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 3) { + if (chatCommand == "createprivate" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 3) { uint32_t zone; if (!GeneralUtils::TryParse(args[0], zone)) { @@ -1628,13 +1630,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if ((chatCommand == "debugui") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if ((chatCommand == "debugui") && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { ChatPackets::SendSystemMessage(sysAddr, u"Opening UIDebugger..."); AMFArrayValue args; GameMessages::SendUIMessageServerToSingleClient(entity, sysAddr, "ToggleUIDebugger;", nullptr); } - if ((chatCommand == "boost") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if ((chatCommand == "boost") && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* possessorComponent = entity->GetComponent<PossessorComponent>(); if (possessorComponent == nullptr) { @@ -1666,7 +1668,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } - if ((chatCommand == "unboost") && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if ((chatCommand == "unboost") && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* possessorComponent = entity->GetComponent<PossessorComponent>(); if (possessorComponent == nullptr) return; @@ -1676,7 +1678,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit GameMessages::SendVehicleRemovePassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); } - if (chatCommand == "activatespawner" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { + if (chatCommand == "activatespawner" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto spawners = dZoneManager::Instance()->GetSpawnersByName(args[0]); for (auto* spawner : spawners) { @@ -1690,7 +1692,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "spawnphysicsverts" && entity->GetGMLevel() >= 6) { + if (chatCommand == "spawnphysicsverts" && entity->GetGMLevel() >= eGameMasterLevel::JUNIOR_DEVELOPER) { //Go tell physics to spawn all the vertices: auto entities = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::PHANTOM_PHYSICS); for (auto en : entities) { @@ -1700,7 +1702,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "reportproxphys" && entity->GetGMLevel() >= 6) { + if (chatCommand == "reportproxphys" && entity->GetGMLevel() >= eGameMasterLevel::JUNIOR_DEVELOPER) { auto entities = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::PROXIMITY_MONITOR); for (auto en : entities) { auto phys = static_cast<ProximityMonitorComponent*>(en->GetComponent(eReplicaComponentType::PROXIMITY_MONITOR)); @@ -1716,7 +1718,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "triggerspawner" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { + if (chatCommand == "triggerspawner" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto spawners = dZoneManager::Instance()->GetSpawnersByName(args[0]); for (auto* spawner : spawners) { @@ -1730,7 +1732,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (chatCommand == "reforge" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 2) { + if (chatCommand == "reforge" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 2) { LOT baseItem; LOT reforgedItem; @@ -1747,7 +1749,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit inventoryComponent->AddItem(baseItem, 1, eLootSourceType::LOOT_SOURCE_MODERATION, eInventoryType::INVALID, data); } - if (chatCommand == "crash" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR) { + if (chatCommand == "crash" && entity->GetGMLevel() >= eGameMasterLevel::OPERATOR) { ChatPackets::SendSystemMessage(sysAddr, u"Crashing..."); int* badPtr = nullptr; @@ -1756,7 +1758,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "metrics" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "metrics" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { for (const auto variable : Metrics::GetAllMetrics()) { auto* metric = Metrics::GetMetric(variable); @@ -1793,7 +1795,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - if (chatCommand == "reloadconfig" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER) { + if (chatCommand == "reloadconfig" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { Game::config->ReloadConfig(); VanityUtilities::SpawnVanity(); dpWorld::Instance().Reload(); @@ -1809,7 +1811,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Successfully reloaded config for world!"); } - if (chatCommand == "rollloot" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_OPERATOR && args.size() >= 3) { + if (chatCommand == "rollloot" && entity->GetGMLevel() >= eGameMasterLevel::OPERATOR && args.size() >= 3) { uint32_t lootMatrixIndex = 0; uint32_t targetLot = 0; uint32_t loops = 1; @@ -1846,7 +1848,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, message); } - if (chatCommand == "deleteinven" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { + if (chatCommand == "deleteinven" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { eInventoryType inventoryType = eInventoryType::INVALID; if (!GeneralUtils::TryParse(args[0], inventoryType)) { // In this case, we treat the input as a string and try to find it in the reflection list @@ -1873,7 +1875,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Deleted inventory " + GeneralUtils::UTF8ToUTF16(args[0])); } - if (chatCommand == "inspect" && entity->GetGMLevel() >= GAME_MASTER_LEVEL_DEVELOPER && args.size() >= 1) { + if (chatCommand == "inspect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { Entity* closest = nullptr; eReplicaComponentType component; diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index 100efac5..a1c08938 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -32,6 +32,7 @@ #include "CharacterComponent.h" #include "Database.h" #include "dMessageIdentifiers.h" +#include "eGameMasterLevel.h" #include "eReplicaComponentType.h" void ClientPackets::HandleChatMessage(const SystemAddress& sysAddr, Packet* packet) { @@ -66,7 +67,7 @@ void ClientPackets::HandleChatMessage(const SystemAddress& sysAddr, Packet* pack } std::string playerName = user->GetLastUsedChar()->GetName(); - bool isMythran = user->GetLastUsedChar()->GetGMLevel() > 0; + bool isMythran = user->GetLastUsedChar()->GetGMLevel() > eGameMasterLevel::CIVILIAN; if (!user->GetLastChatMessageApproved() && !isMythran) return; diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index f6a8f558..febb6bc1 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -15,6 +15,7 @@ #include "CharacterComponent.h" #include "ZCompression.h" + void WorldPackets::SendLoadStaticZone(const SystemAddress& sysAddr, float x, float y, float z, uint32_t checksum) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_LOAD_STATIC_ZONE); @@ -127,7 +128,7 @@ void WorldPackets::SendServerState(const SystemAddress& sysAddr) { SEND_PACKET; } -void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm) { +void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, eGameMasterLevel gm) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CREATE_CHARACTER); @@ -144,8 +145,8 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent LDFData<LOT>* lot = new LDFData<LOT>(u"template", 1); LDFData<std::string>* xmlConfigData = new LDFData<std::string>(u"xmlData", xmlData); LDFData<std::u16string>* name = new LDFData<std::u16string>(u"name", username); - LDFData<int32_t>* gmlevel = new LDFData<int32_t>(u"gmlevel", gm); - LDFData<int32_t>* chatmode = new LDFData<int32_t>(u"chatmode", gm); + LDFData<int32_t>* gmlevel = new LDFData<int32_t>(u"gmlevel", static_cast<int32_t>(gm)); + LDFData<int32_t>* chatmode = new LDFData<int32_t>(u"chatmode", static_cast<int32_t>(gm)); LDFData<int64_t>* reputation = new LDFData<int64_t>(u"reputation", character->GetReputation()); objid->WriteToPacket(&data); @@ -220,14 +221,14 @@ void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool SEND_PACKET; } -void WorldPackets::SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel) { +void WorldPackets::SendGMLevelChange(const SystemAddress& sysAddr, bool success, eGameMasterLevel highestLevel, eGameMasterLevel prevLevel, eGameMasterLevel newLevel) { CBITSTREAM; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAKE_GM_RESPONSE); bitStream.Write<uint8_t>(success); - bitStream.Write<uint16_t>(highestLevel); - bitStream.Write<uint16_t>(prevLevel); - bitStream.Write<uint16_t>(newLevel); + bitStream.Write(static_cast<uint16_t>(highestLevel)); + bitStream.Write(static_cast<uint16_t>(prevLevel)); + bitStream.Write(static_cast<uint16_t>(newLevel)); SEND_PACKET; } diff --git a/dNet/WorldPackets.h b/dNet/WorldPackets.h index d9951941..ec20ac22 100644 --- a/dNet/WorldPackets.h +++ b/dNet/WorldPackets.h @@ -8,6 +8,7 @@ class User; struct SystemAddress; +enum class eGameMasterLevel : uint8_t; namespace WorldPackets { void SendLoadStaticZone(const SystemAddress& sysAddr, float x, float y, float z, uint32_t checksum); @@ -17,9 +18,9 @@ namespace WorldPackets { void SendCharacterDeleteResponse(const SystemAddress& sysAddr, bool response); void SendTransferToWorld(const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift); void SendServerState(const SystemAddress& sysAddr); - void SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, int32_t gm); + void SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, eGameMasterLevel gm); void SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector<std::pair<uint8_t, uint8_t>> unacceptedItems); - void SendGMLevelChange(const SystemAddress& sysAddr, bool success, uint8_t highestLevel, uint8_t prevLevel, uint8_t newLevel); + void SendGMLevelChange(const SystemAddress& sysAddr, bool success, eGameMasterLevel highestLevel, eGameMasterLevel prevLevel, eGameMasterLevel newLevel); } #endif // WORLDPACKETS_H diff --git a/docs/Commands.md b/docs/Commands.md index 725a03a0..c997c3c4 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -128,13 +128,13 @@ There are 9 Game master levels |Level|Variable Name|Description| |--- |--- |--- | -|0|GAME_MASTER_LEVEL_CIVILIAN|Normal player| -|1|GAME_MASTER_LEVEL_FORUM_MODERATOR|Forum moderator. No permissions on live servers.| -|2|GAME_MASTER_LEVEL_JUNIOR_MODERATOR|Can kick/mute and pull chat logs| -|3|GAME_MASTER_LEVEL_MODERATOR|Can return lost items| -|4|GAME_MASTER_LEVEL_SENIOR_MODERATOR|Can ban| -|5|GAME_MASTER_LEVEL_LEAD_MODERATOR|Can approve properties| -|6|GAME_MASTER_LEVEL_JUNIOR_DEVELOPER|Junior developer & future content team. Civilan on live.| -|7|GAME_MASTER_LEVEL_INACTIVE_DEVELOPER|Inactive developer, limited permissions.| -|8|GAME_MASTER_LEVEL_DEVELOPER|Active developer, full permissions on live.| -|9|GAME_MASTER_LEVEL_OPERATOR|Can shutdown server for restarts & updates.| +|0|CIVILIAN|Normal player| +|1|FORUM_MODERATOR|Forum moderator. No permissions on live servers.| +|2|JUNIOR_MODERATOR|Can kick/mute and pull chat logs| +|3|MODERATOR|Can return lost items| +|4|SENIOR_MODERATOR|Can ban| +|5|LEAD_MODERATOR|Can approve properties| +|6|JUNIOR_DEVELOPER|Junior developer & future content team. Civilan on live.| +|7|INACTIVE_DEVELOPER|Inactive developer, limited permissions.| +|8|DEVELOPER|Active developer, full permissions on live.| +|9|OPERATOR|Can shutdown server for restarts & updates.| From c415d0520afe442827046ce53ae538703e58f0e0 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 25 Mar 2023 05:26:39 -0500 Subject: [PATCH 273/322] Implement some more trigger event calls and command handlers (#989) * Implement some trigger event calls and command handlers * add zone summary dimissed GM * break and remove log * some cleanup in Gather Targets and blocking out * fix default value of unlock for play cinematic * Log on errors add enum for physics effect type simplify nipoint3 logic check arg count add enum for End behavior * tryparse for nipoint3 * totally didn't forget to include it * bleh c++ is blah * ??? * address feedback * Fix for #1028 --- dCommon/GeneralUtils.cpp | 4 + dCommon/GeneralUtils.h | 3 + dCommon/NiPoint3.cpp | 6 + dCommon/NiPoint3.h | 3 + dCommon/dEnums/dMessageIdentifiers.h | 1 + dCommon/dEnums/eEndBehavior.h | 11 + dCommon/dEnums/ePhysicsEffectType.h | 15 + dCommon/dEnums/eTriggerEventType.h | 2 +- dGame/Entity.cpp | 5 +- dGame/EntityManager.cpp | 4 +- dGame/dComponents/BouncerComponent.cpp | 3 + dGame/dComponents/PhantomPhysicsComponent.cpp | 5 +- dGame/dComponents/PhantomPhysicsComponent.h | 7 +- dGame/dComponents/RebuildComponent.cpp | 3 + dGame/dComponents/SwitchComponent.cpp | 4 +- dGame/dComponents/TriggerComponent.cpp | 409 ++++++++++++++---- dGame/dComponents/TriggerComponent.h | 31 +- dGame/dGameMessages/GameMessageHandler.cpp | 3 + dGame/dGameMessages/GameMessages.cpp | 14 +- dGame/dGameMessages/GameMessages.h | 5 +- dGame/dUtilities/SlashCommandHandler.cpp | 2 +- .../02_server/Map/AG/AgLaserSensorServer.cpp | 3 +- dScripts/02_server/Map/GF/MastTeleport.cpp | 3 +- .../Map/General/ForceVolumeServer.cpp | 3 +- .../02_server/Map/NT/NtAssemblyTubeServer.cpp | 3 +- .../Map/NT/NtSentinelWalkwayServer.cpp | 3 +- .../Map/NT/NtVentureCannonServer.cpp | 3 +- dScripts/BasePropertyServer.cpp | 14 +- dScripts/ai/FV/ActParadoxPipeFix.cpp | 3 +- dZoneManager/Spawner.cpp | 25 +- dZoneManager/Spawner.h | 1 + dZoneManager/dZoneManager.cpp | 12 +- 32 files changed, 461 insertions(+), 152 deletions(-) create mode 100644 dCommon/dEnums/eEndBehavior.h create mode 100644 dCommon/dEnums/ePhysicsEffectType.h diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index 54ef5661..df641a1b 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -319,3 +319,7 @@ std::vector<std::string> 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<float>(x.c_str(), dst.x) && TryParse<float>(y.c_str(), dst.y) && TryParse<float>(z.c_str(), dst.z); +} diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index a2a52b45..25aac783 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -10,6 +10,7 @@ #include <type_traits> #include <stdexcept> #include <BitStream.h> +#include "NiPoint3.h" #include "Game.h" #include "dLogger.h" @@ -208,6 +209,8 @@ namespace GeneralUtils { return TryParse<T>(value.c_str(), dst); } + bool TryParse(const std::string& x, const std::string& y, const std::string& z, NiPoint3& dst); + template<typename T> std::u16string to_u16string(T value) { return GeneralUtils::ASCIIToUTF16(std::to_string(value)); diff --git a/dCommon/NiPoint3.cpp b/dCommon/NiPoint3.cpp index a539c4df..b2ffa0d1 100644 --- a/dCommon/NiPoint3.cpp +++ b/dCommon/NiPoint3.cpp @@ -128,6 +128,12 @@ 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) const { + return NiPoint3(this->x + point.x, this->y + point.y, this->z + point.z); +} + + //! 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); diff --git a/dCommon/NiPoint3.h b/dCommon/NiPoint3.h index 6c0b9d3d..f76b9269 100644 --- a/dCommon/NiPoint3.h +++ b/dCommon/NiPoint3.h @@ -135,6 +135,9 @@ public: //! Operator for addition of vectors NiPoint3 operator+(const NiPoint3& point) const; + //! Operator for addition of vectors + NiPoint3 operator+=(const NiPoint3& point) const; + //! Operator for subtraction of vectors NiPoint3 operator-(const NiPoint3& point) const; diff --git a/dCommon/dEnums/dMessageIdentifiers.h b/dCommon/dEnums/dMessageIdentifiers.h index 63d7044e..7c810a2d 100644 --- a/dCommon/dEnums/dMessageIdentifiers.h +++ b/dCommon/dEnums/dMessageIdentifiers.h @@ -445,6 +445,7 @@ enum GAME_MSG : unsigned short { GAME_MSG_BBB_SAVE_RESPONSE = 1006, GAME_MSG_NOTIFY_CLIENT_OBJECT = 1042, GAME_MSG_DISPLAY_ZONE_SUMMARY = 1043, + GAME_MSG_ZONE_SUMMARY_DISMISSED = 1044, GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST = 1053, GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC = 1046, GAME_MSG_START_BUILDING_WITH_ITEM = 1057, diff --git a/dCommon/dEnums/eEndBehavior.h b/dCommon/dEnums/eEndBehavior.h new file mode 100644 index 00000000..77afaab4 --- /dev/null +++ b/dCommon/dEnums/eEndBehavior.h @@ -0,0 +1,11 @@ +#ifndef __EENDBEHAVIOR__H__ +#define __EENDBEHAVIOR__H__ + +#include <cstdint> + +enum class eEndBehavior : uint32_t { + RETURN, + WAIT +}; + +#endif //!__EENDBEHAVIOR__H__ diff --git a/dCommon/dEnums/ePhysicsEffectType.h b/dCommon/dEnums/ePhysicsEffectType.h new file mode 100644 index 00000000..1aa68b34 --- /dev/null +++ b/dCommon/dEnums/ePhysicsEffectType.h @@ -0,0 +1,15 @@ +#ifndef __EPHYSICSEFFECTTYPE__H__ +#define __EPHYSICSEFFECTTYPE__H__ + + +#include <cstdint> + +enum class ePhysicsEffectType : uint32_t { + PUSH, + ATTRACT, + REPULSE, + GRAVITY_SCALE, + FRICTION +}; + +#endif //!__EPHYSICSEFFECTTYPE__H__ diff --git a/dCommon/dEnums/eTriggerEventType.h b/dCommon/dEnums/eTriggerEventType.h index 1705ce22..a2daa256 100644 --- a/dCommon/dEnums/eTriggerEventType.h +++ b/dCommon/dEnums/eTriggerEventType.h @@ -35,7 +35,7 @@ public: {"OnTimerDone", eTriggerEventType::TIMER_DONE}, {"OnRebuildComplete", eTriggerEventType::REBUILD_COMPLETE}, {"OnActivated", eTriggerEventType::ACTIVATED}, - {"OnDeactivated", eTriggerEventType::DEACTIVATED}, + {"OnDectivated", eTriggerEventType::DEACTIVATED}, // Dectivated vs Deactivated {"OnArrived", eTriggerEventType::ARRIVED}, {"OnArrivedAtEndOfPath", eTriggerEventType::ARRIVED_AT_END_OF_PATH}, {"OnZoneSummaryDismissed", eTriggerEventType::ZONE_SUMMARY_DISMISSED}, diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index c33a7247..95a550a6 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -763,7 +763,7 @@ void Entity::Initialize() { no_ghosting: - TriggerEvent(eTriggerEventType::CREATE); + TriggerEvent(eTriggerEventType::CREATE, this); if (m_Character) { auto* controllablePhysicsComponent = GetComponent<ControllablePhysicsComponent>(); @@ -1390,7 +1390,7 @@ void Entity::OnEmoteReceived(const int32_t emote, Entity* target) { } void Entity::OnUse(Entity* originator) { - TriggerEvent(eTriggerEventType::INTERACT); + TriggerEvent(eTriggerEventType::INTERACT, originator); for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnUse(this, originator); @@ -1412,6 +1412,7 @@ void Entity::OnHitOrHealResult(Entity* attacker, int32_t damage) { } void Entity::OnHit(Entity* attacker) { + TriggerEvent(eTriggerEventType::HIT, attacker); for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnHit(this, attacker); } diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index 31b755fe..d547cdb1 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -163,6 +163,8 @@ void EntityManager::DestroyEntity(Entity* entity) { return; } + entity->TriggerEvent(eTriggerEventType::DESTROY, entity); + const auto id = entity->GetObjectID(); if (std::count(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), id)) { @@ -588,7 +590,7 @@ void EntityManager::ScheduleForKill(Entity* entity) { SwitchComponent* switchComp = entity->GetComponent<SwitchComponent>(); if (switchComp) { - entity->TriggerEvent(eTriggerEventType::DEACTIVATED); + entity->TriggerEvent(eTriggerEventType::DEACTIVATED, entity); } const auto objectId = entity->GetObjectID(); diff --git a/dGame/dComponents/BouncerComponent.cpp b/dGame/dComponents/BouncerComponent.cpp index 1f32d6e5..f6a53261 100644 --- a/dGame/dComponents/BouncerComponent.cpp +++ b/dGame/dComponents/BouncerComponent.cpp @@ -7,6 +7,7 @@ #include "dLogger.h" #include "GameMessages.h" #include <BitStream.h> +#include "eTriggerEventType.h" BouncerComponent::BouncerComponent(Entity* parent) : Component(parent) { m_PetEnabled = false; @@ -46,8 +47,10 @@ void BouncerComponent::SetPetBouncerEnabled(bool value) { EntityManager::Instance()->SerializeEntity(m_Parent); if (value) { + m_Parent->TriggerEvent(eTriggerEventType::PET_ON_SWITCH, m_Parent); GameMessages::SendPlayFXEffect(m_Parent->GetObjectID(), 1513, u"create", "PetOnSwitch", LWOOBJID_EMPTY, 1, 1, true); } else { + m_Parent->TriggerEvent(eTriggerEventType::PET_OFF_SWITCH, m_Parent); GameMessages::SendStopFXEffect(m_Parent, true, "PetOnSwitch"); } diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index 75cef4fb..ce205826 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -14,6 +14,7 @@ #include "EntityManager.h" #include "ControllablePhysicsComponent.h" #include "GameMessages.h" +#include "ePhysicsEffectType.h" #include "CDClientManager.h" #include "CDComponentsRegistryTable.h" @@ -36,7 +37,7 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par m_PositionInfoDirty = false; m_IsPhysicsEffectActive = false; - m_EffectType = 0; + m_EffectType = ePhysicsEffectType::PUSH; m_DirectionalMultiplier = 0.0f; m_MinMax = false; @@ -405,7 +406,7 @@ void PhantomPhysicsComponent::SetDirectionalMultiplier(float mul) { m_EffectInfoDirty = true; } -void PhantomPhysicsComponent::SetEffectType(uint32_t type) { +void PhantomPhysicsComponent::SetEffectType(ePhysicsEffectType type) { m_EffectType = type; m_EffectInfoDirty = true; } diff --git a/dGame/dComponents/PhantomPhysicsComponent.h b/dGame/dComponents/PhantomPhysicsComponent.h index 0b27db05..cc0d1844 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.h +++ b/dGame/dComponents/PhantomPhysicsComponent.h @@ -17,6 +17,7 @@ class LDFBaseData; class Entity; class dpEntity; +enum class ePhysicsEffectType : uint32_t ; /** * Allows the creation of phantom physics for an entity: a physics object that is generally invisible but can be @@ -103,13 +104,13 @@ public: * Returns the effect that's currently active, defaults to 0 * @return the effect that's currently active */ - uint32_t GetEffectType() const { return m_EffectType; } + ePhysicsEffectType GetEffectType() const { return m_EffectType; } /** * Sets the effect that's currently active * @param type the effect to set */ - void SetEffectType(uint32_t type); + void SetEffectType(ePhysicsEffectType type); /** * Returns the Physics entity for the component @@ -168,7 +169,7 @@ private: /** * The physics effect that's currently active, defaults to 0 */ - uint32_t m_EffectType; + ePhysicsEffectType m_EffectType; /** * A scaling multiplier to add to the directional vector diff --git a/dGame/dComponents/RebuildComponent.cpp b/dGame/dComponents/RebuildComponent.cpp index abd21873..2562b313 100644 --- a/dGame/dComponents/RebuildComponent.cpp +++ b/dGame/dComponents/RebuildComponent.cpp @@ -8,6 +8,7 @@ #include "CharacterComponent.h" #include "MissionComponent.h" #include "eMissionTaskType.h" +#include "eTriggerEventType.h" #include "dServer.h" #include "PacketUtils.h" @@ -495,6 +496,8 @@ void RebuildComponent::CompleteRebuild(Entity* user) { for (const auto& callback : m_RebuildCompleteCallbacks) callback(user); + m_Parent->TriggerEvent(eTriggerEventType::REBUILD_COMPLETE, user); + auto* movingPlatform = m_Parent->GetComponent<MovingPlatformComponent>(); if (movingPlatform != nullptr) { movingPlatform->OnCompleteRebuild(); diff --git a/dGame/dComponents/SwitchComponent.cpp b/dGame/dComponents/SwitchComponent.cpp index dbdf37a9..392d885a 100644 --- a/dGame/dComponents/SwitchComponent.cpp +++ b/dGame/dComponents/SwitchComponent.cpp @@ -43,7 +43,7 @@ void SwitchComponent::EntityEnter(Entity* entity) { } m_Active = true; if (!m_Parent) return; - m_Parent->TriggerEvent(eTriggerEventType::ACTIVATED); + m_Parent->TriggerEvent(eTriggerEventType::ACTIVATED, entity); const auto grpName = m_Parent->GetVarAsString(u"grp_name"); @@ -79,7 +79,7 @@ void SwitchComponent::Update(float deltaTime) { if (m_Timer <= 0.0f) { m_Active = false; if (!m_Parent) return; - m_Parent->TriggerEvent(eTriggerEventType::DEACTIVATED); + m_Parent->TriggerEvent(eTriggerEventType::DEACTIVATED, m_Parent); const auto grpName = m_Parent->GetVarAsString(u"grp_name"); diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp index d98b2eea..0f241116 100644 --- a/dGame/dComponents/TriggerComponent.cpp +++ b/dGame/dComponents/TriggerComponent.cpp @@ -1,10 +1,19 @@ #include "TriggerComponent.h" #include "dZoneManager.h" -#include "LUTriggers.h" +#include "TeamManager.h" #include "eTriggerCommandType.h" +#include "eMissionTaskType.h" +#include "ePhysicsEffectType.h" + +#include "CharacterComponent.h" +#include "ControllablePhysicsComponent.h" #include "MissionComponent.h" #include "PhantomPhysicsComponent.h" -#include "CDMissionTasksTable.h" +#include "Player.h" +#include "RebuildComponent.h" +#include "SkillComponent.h" +#include "eEndBehavior.h" + TriggerComponent::TriggerComponent(Entity* parent, const std::string triggerInfo): Component(parent) { m_Parent = parent; @@ -51,19 +60,37 @@ void TriggerComponent::HandleTriggerCommand(LUTriggers::Command* command, Entity case eTriggerCommandType::FIRE_EVENT: HandleFireEvent(targetEntity, command->args); break; - case eTriggerCommandType::DESTROY_OBJ: break; - case eTriggerCommandType::TOGGLE_TRIGGER: break; - case eTriggerCommandType::RESET_REBUILD: break; + case eTriggerCommandType::DESTROY_OBJ: + HandleDestroyObject(targetEntity, command->args); + break; + case eTriggerCommandType::TOGGLE_TRIGGER: + HandleToggleTrigger(targetEntity, command->args); + break; + case eTriggerCommandType::RESET_REBUILD: + HandleResetRebuild(targetEntity, command->args); + break; case eTriggerCommandType::SET_PATH: break; case eTriggerCommandType::SET_PICK_TYPE: break; - case eTriggerCommandType::MOVE_OBJECT: break; - case eTriggerCommandType::ROTATE_OBJECT: break; - case eTriggerCommandType::PUSH_OBJECT: break; - case eTriggerCommandType::REPEL_OBJECT: break; + case eTriggerCommandType::MOVE_OBJECT: + HandleMoveObject(targetEntity, argArray); + break; + case eTriggerCommandType::ROTATE_OBJECT: + HandleRotateObject(targetEntity, argArray); + break; + case eTriggerCommandType::PUSH_OBJECT: + HandlePushObject(targetEntity, argArray); + break; + case eTriggerCommandType::REPEL_OBJECT: + HandleRepelObject(targetEntity, command->args); + break; case eTriggerCommandType::SET_TIMER: break; case eTriggerCommandType::CANCEL_TIMER: break; - case eTriggerCommandType::PLAY_CINEMATIC: break; - case eTriggerCommandType::TOGGLE_BBB: break; + case eTriggerCommandType::PLAY_CINEMATIC: + HandlePlayCinematic(targetEntity, argArray); + break; + case eTriggerCommandType::TOGGLE_BBB: + HandleToggleBBB(targetEntity, command->args); + break; case eTriggerCommandType::UPDATE_MISSION: HandleUpdateMission(targetEntity, argArray); break; @@ -75,8 +102,43 @@ void TriggerComponent::HandleTriggerCommand(LUTriggers::Command* command, Entity case eTriggerCommandType::STOP_PATHING: break; case eTriggerCommandType::START_PATHING: break; case eTriggerCommandType::LOCK_OR_UNLOCK_CONTROLS: break; - case eTriggerCommandType::PLAY_EFFECT: break; - case eTriggerCommandType::STOP_EFFECT: break; + case eTriggerCommandType::PLAY_EFFECT: + HandlePlayEffect(targetEntity, argArray); + break; + case eTriggerCommandType::STOP_EFFECT: + GameMessages::SendStopFXEffect(targetEntity, true, command->args); + break; + case eTriggerCommandType::CAST_SKILL: + HandleCastSkill(targetEntity, command->args); + break; + case eTriggerCommandType::DISPLAY_ZONE_SUMMARY: + GameMessages::SendDisplayZoneSummary(targetEntity->GetObjectID(), targetEntity->GetSystemAddress(), false, command->args == "1", m_Parent->GetObjectID()); + break; + case eTriggerCommandType::SET_PHYSICS_VOLUME_EFFECT: + HandleSetPhysicsVolumeEffect(targetEntity, argArray); + break; + case eTriggerCommandType::SET_PHYSICS_VOLUME_STATUS: + HandleSetPhysicsVolumeStatus(targetEntity, command->args); + break; + case eTriggerCommandType::SET_MODEL_TO_BUILD: break; + case eTriggerCommandType::SPAWN_MODEL_BRICKS: break; + case eTriggerCommandType::ACTIVATE_SPAWNER_NETWORK: + HandleActivateSpawnerNetwork(command->args); + break; + case eTriggerCommandType::DEACTIVATE_SPAWNER_NETWORK: + HandleDeactivateSpawnerNetwork(command->args); + break; + case eTriggerCommandType::RESET_SPAWNER_NETWORK: + HandleResetSpawnerNetwork(command->args); + break; + case eTriggerCommandType::DESTROY_SPAWNER_NETWORK_OBJECTS: + HandleDestroySpawnerNetworkObjects(command->args); + break; + case eTriggerCommandType::GO_TO_WAYPOINT: break; + case eTriggerCommandType::ACTIVATE_PHYSICS: + HandleActivatePhysics(targetEntity, command->args); + break; + // DEPRECATED BLOCK START case eTriggerCommandType::ACTIVATE_MUSIC_CUE: break; case eTriggerCommandType::DEACTIVATE_MUSIC_CUE: break; case eTriggerCommandType::FLASH_MUSIC_CUE: break; @@ -87,20 +149,7 @@ void TriggerComponent::HandleTriggerCommand(LUTriggers::Command* command, Entity case eTriggerCommandType::STOP_3D_AMBIENT_SOUND: break; case eTriggerCommandType::ACTIVATE_MIXER_PROGRAM: break; case eTriggerCommandType::DEACTIVATE_MIXER_PROGRAM: break; - case eTriggerCommandType::CAST_SKILL: break; - case eTriggerCommandType::DISPLAY_ZONE_SUMMARY: break; - case eTriggerCommandType::SET_PHYSICS_VOLUME_EFFECT: - HandleSetPhysicsVolume(targetEntity, argArray, command->target); - break; - case eTriggerCommandType::SET_PHYSICS_VOLUME_STATUS: break; - case eTriggerCommandType::SET_MODEL_TO_BUILD: break; - case eTriggerCommandType::SPAWN_MODEL_BRICKS: break; - case eTriggerCommandType::ACTIVATE_SPAWNER_NETWORK: break; - case eTriggerCommandType::DEACTIVATE_SPAWNER_NETWORK: break; - case eTriggerCommandType::RESET_SPAWNER_NETWORK: break; - case eTriggerCommandType::DESTROY_SPAWNER_NETWORK_OBJECTS: break; - case eTriggerCommandType::GO_TO_WAYPOINT: break; - case eTriggerCommandType::ACTIVATE_PHYSICS: break; + // DEPRECATED BLOCK END default: Game::logger->LogDebug("TriggerComponent", "Event %i was not handled!", command->id); break; @@ -113,70 +162,262 @@ std::vector<Entity*> TriggerComponent::GatherTargets(LUTriggers::Command* comman if (command->target == "self") entities.push_back(m_Parent); else if (command->target == "zone") { /*TODO*/ } - else if (command->target == "target") { /*TODO*/ } - else if (command->target == "targetTeam") { /*TODO*/ } - else if (command->target == "objGroup") entities = EntityManager::Instance()->GetEntitiesInGroup(command->targetName); - else if (command->target == "allPlayers") { /*TODO*/ } - else if (command->target == "allNPCs") { /*TODO*/ } - - if (optionalTarget) entities.push_back(optionalTarget); + else if (command->target == "target" && optionalTarget) entities.push_back(optionalTarget); + else if (command->target == "targetTeam" && optionalTarget) { + auto* team = TeamManager::Instance()->GetTeam(optionalTarget->GetObjectID()); + for (const auto memberId : team->members) { + auto* member = EntityManager::Instance()->GetEntity(memberId); + if (member) entities.push_back(member); + } + } else if (command->target == "objGroup") entities = EntityManager::Instance()->GetEntitiesInGroup(command->targetName); + else if (command->target == "allPlayers") { + for (auto* player : Player::GetAllPlayers()) { + entities.push_back(player); + } + } else if (command->target == "allNPCs") { /*UNUSED*/ } return entities; } -void TriggerComponent::HandleSetPhysicsVolume(Entity* targetEntity, std::vector<std::string> argArray, std::string target) { - PhantomPhysicsComponent* phanPhys = m_Parent->GetComponent<PhantomPhysicsComponent>(); - if (!phanPhys) return; - - phanPhys->SetPhysicsEffectActive(true); - uint32_t effectType = 0; - std::transform(argArray.at(0).begin(), argArray.at(0).end(), argArray.at(0).begin(), ::tolower); //Transform to lowercase - if (argArray.at(0) == "push") effectType = 0; - else if (argArray.at(0) == "attract") effectType = 1; - else if (argArray.at(0) == "repulse") effectType = 2; - else if (argArray.at(0) == "gravity") effectType = 3; - else if (argArray.at(0) == "friction") effectType = 4; - - phanPhys->SetEffectType(effectType); - phanPhys->SetDirectionalMultiplier(std::stof(argArray.at(1))); - if (argArray.size() > 4) { - NiPoint3 direction = NiPoint3::ZERO; - GeneralUtils::TryParse<float>(argArray.at(2), direction.x); - GeneralUtils::TryParse<float>(argArray.at(3), direction.y); - GeneralUtils::TryParse<float>(argArray.at(4), direction.z); - phanPhys->SetDirection(direction); - } - if (argArray.size() > 5) { - uint32_t min; - GeneralUtils::TryParse<uint32_t>(argArray.at(6), min); - phanPhys->SetMin(min); - - uint32_t max; - GeneralUtils::TryParse<uint32_t>(argArray.at(7), max); - phanPhys->SetMax(max); - } - - // TODO: why is this contruct and not serialize? - if (target == "self") EntityManager::Instance()->ConstructEntity(m_Parent); -} - -void TriggerComponent::HandleUpdateMission(Entity* targetEntity, std::vector<std::string> argArray) { - CDMissionTasksTable* missionTasksTable = CDClientManager::Instance().GetTable<CDMissionTasksTable>(); - std::vector<CDMissionTasks> missionTasks = missionTasksTable->Query([=](CDMissionTasks entry) { - return (entry.targetGroup == argArray.at(4)); - }); - - for (const CDMissionTasks& task : missionTasks) { - MissionComponent* missionComponent = targetEntity->GetComponent<MissionComponent>(); - if (!missionComponent) continue; - - missionComponent->ForceProgress(task.id, task.uid, std::stoi(argArray.at(2))); - } -} - void TriggerComponent::HandleFireEvent(Entity* targetEntity, std::string args) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(targetEntity)) { script->OnFireEventServerSide(targetEntity, m_Parent, args, 0, 0, 0); } } +void TriggerComponent::HandleDestroyObject(Entity* targetEntity, std::string args){ + uint32_t killType; + GeneralUtils::TryParse<uint32_t>(args, killType); + targetEntity->Smash(m_Parent->GetObjectID(), static_cast<eKillType>(killType)); +} + +void TriggerComponent::HandleToggleTrigger(Entity* targetEntity, std::string args){ + auto* triggerComponent = targetEntity->GetComponent<TriggerComponent>(); + if (!triggerComponent) { + Game::logger->Log("TriggerComponent::HandleToggleTrigger", "Trigger component not found!"); + return; + } + triggerComponent->SetTriggerEnabled(args == "1"); +} + +void TriggerComponent::HandleResetRebuild(Entity* targetEntity, std::string args){ + auto* rebuildComponent = targetEntity->GetComponent<RebuildComponent>(); + if (!rebuildComponent) { + Game::logger->Log("TriggerComponent::HandleResetRebuild", "Rebuild component not found!"); + return; + } + rebuildComponent->ResetRebuild(args == "1"); +} + +void TriggerComponent::HandleMoveObject(Entity* targetEntity, std::vector<std::string> argArray){ + if (argArray.size() <= 2) return; + + auto position = targetEntity->GetPosition(); + NiPoint3 offset = NiPoint3::ZERO; + GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), offset); + + position += offset; + targetEntity->SetPosition(position); +} + +void TriggerComponent::HandleRotateObject(Entity* targetEntity, std::vector<std::string> argArray){ + if (argArray.size() <= 2) return; + + NiPoint3 vector = NiPoint3::ZERO; + GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), vector); + + NiQuaternion rotation = NiQuaternion::FromEulerAngles(vector); + targetEntity->SetRotation(rotation); +} + +void TriggerComponent::HandlePushObject(Entity* targetEntity, std::vector<std::string> argArray){ + auto* phantomPhysicsComponent = m_Parent->GetComponent<PhantomPhysicsComponent>(); + if (!phantomPhysicsComponent) { + Game::logger->Log("TriggerComponent::HandlePushObject", "Phantom Physics component not found!"); + return; + } + phantomPhysicsComponent->SetPhysicsEffectActive(true); + phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::PUSH); + phantomPhysicsComponent->SetDirectionalMultiplier(1); + NiPoint3 direction = NiPoint3::ZERO; + GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), direction); + phantomPhysicsComponent->SetDirection(direction); + + EntityManager::Instance()->SerializeEntity(m_Parent); +} + + +void TriggerComponent::HandleRepelObject(Entity* targetEntity, std::string args){ + auto* phantomPhysicsComponent = m_Parent->GetComponent<PhantomPhysicsComponent>(); + if (!phantomPhysicsComponent) { + Game::logger->Log("TriggerComponent::HandleRepelObject", "Phantom Physics component not found!"); + return; + } + float forceMultiplier; + GeneralUtils::TryParse<float>(args, forceMultiplier); + phantomPhysicsComponent->SetPhysicsEffectActive(true); + phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::REPULSE); + phantomPhysicsComponent->SetDirectionalMultiplier(forceMultiplier); + + auto triggerPos = m_Parent->GetPosition(); + auto targetPos = targetEntity->GetPosition(); + + // normalize the vectors to get the direction + auto delta = targetPos - triggerPos; + auto length = delta.Length(); + NiPoint3 direction = delta / length; + phantomPhysicsComponent->SetDirection(direction); + + EntityManager::Instance()->SerializeEntity(m_Parent); +} + +void TriggerComponent::HandlePlayCinematic(Entity* targetEntity, std::vector<std::string> argArray) { + float leadIn = -1.0; + auto wait = eEndBehavior::RETURN; + bool unlock = true; + bool leaveLocked = false; + bool hidePlayer = false; + + if (argArray.size() >= 2) { + GeneralUtils::TryParse<float>(argArray.at(1), leadIn); + if (argArray.size() >= 3 && argArray.at(2) == "wait") { + wait = eEndBehavior::WAIT; + if (argArray.size() >= 4 && argArray.at(3) == "unlock") { + unlock = false; + if (argArray.size() >= 5 && argArray.at(4) == "leavelocked") { + leaveLocked = true; + if (argArray.size() >= 6 && argArray.at(5) == "hideplayer") { + hidePlayer = true; + } + } + } + } + } + + GameMessages::SendPlayCinematic(targetEntity->GetObjectID(), GeneralUtils::UTF8ToUTF16(argArray.at(0)), targetEntity->GetSystemAddress(), true, true, false, false, wait, hidePlayer, leadIn, leaveLocked, unlock); +} + +void TriggerComponent::HandleToggleBBB(Entity* targetEntity, std::string args) { + auto* character = targetEntity->GetCharacter(); + if (!character) { + Game::logger->Log("TriggerComponent::HandleToggleBBB", "Character was not found!"); + return; + } + bool buildMode = !(character->GetBuildMode()); + if (args == "enter") buildMode = true; + else if (args == "exit") buildMode = false; + character->SetBuildMode(buildMode); +} + +void TriggerComponent::HandleUpdateMission(Entity* targetEntity, std::vector<std::string> argArray) { + // there are only explore tasks used + // If others need to be implemented for modding + // then we need a good way to convert this from a string to that enum + if (argArray.at(0) != "exploretask") return; + MissionComponent* missionComponent = targetEntity->GetComponent<MissionComponent>(); + if (!missionComponent){ + Game::logger->Log("TriggerComponent::HandleUpdateMission", "Mission component not found!"); + return; + } + missionComponent->Progress(eMissionTaskType::EXPLORE, 0, 0, argArray.at(4)); +} + +void TriggerComponent::HandlePlayEffect(Entity* targetEntity, std::vector<std::string> argArray) { + if (argArray.size() < 3) return; + int32_t effectID = 0; + if (!GeneralUtils::TryParse<int32_t>(argArray.at(1), effectID)) return; + std::u16string effectType = GeneralUtils::UTF8ToUTF16(argArray.at(2)); + float priority = 1; + if (argArray.size() == 4) GeneralUtils::TryParse<float>(argArray.at(3), priority); + GameMessages::SendPlayFXEffect(targetEntity, effectID, effectType, argArray.at(0), LWOOBJID_EMPTY, priority); +} + +void TriggerComponent::HandleCastSkill(Entity* targetEntity, std::string args){ + auto* skillComponent = targetEntity->GetComponent<SkillComponent>(); + if (!skillComponent) { + Game::logger->Log("TriggerComponent::HandleCastSkill", "Skill component not found!"); + return; + } + uint32_t skillId; + GeneralUtils::TryParse<uint32_t>(args, skillId); + skillComponent->CastSkill(skillId, targetEntity->GetObjectID()); +} + +void TriggerComponent::HandleSetPhysicsVolumeEffect(Entity* targetEntity, std::vector<std::string> argArray) { + auto* phantomPhysicsComponent = targetEntity->GetComponent<PhantomPhysicsComponent>(); + if (!phantomPhysicsComponent) { + Game::logger->Log("TriggerComponent::HandleSetPhysicsVolumeEffect", "Phantom Physics component not found!"); + return; + } + phantomPhysicsComponent->SetPhysicsEffectActive(true); + ePhysicsEffectType effectType = ePhysicsEffectType::PUSH; + std::transform(argArray.at(0).begin(), argArray.at(0).end(), argArray.at(0).begin(), ::tolower); //Transform to lowercase + if (argArray.at(0) == "push") effectType = ePhysicsEffectType::PUSH; + else if (argArray.at(0) == "attract") effectType = ePhysicsEffectType::ATTRACT; + else if (argArray.at(0) == "repulse") effectType = ePhysicsEffectType::REPULSE; + else if (argArray.at(0) == "gravity") effectType = ePhysicsEffectType::GRAVITY_SCALE; + else if (argArray.at(0) == "friction") effectType = ePhysicsEffectType::FRICTION; + + phantomPhysicsComponent->SetEffectType(effectType); + phantomPhysicsComponent->SetDirectionalMultiplier(std::stof(argArray.at(1))); + if (argArray.size() > 4) { + NiPoint3 direction = NiPoint3::ZERO; + GeneralUtils::TryParse(argArray.at(2), argArray.at(3), argArray.at(4), direction); + phantomPhysicsComponent->SetDirection(direction); + } + if (argArray.size() > 5) { + uint32_t min; + GeneralUtils::TryParse<uint32_t>(argArray.at(6), min); + phantomPhysicsComponent->SetMin(min); + + uint32_t max; + GeneralUtils::TryParse<uint32_t>(argArray.at(7), max); + phantomPhysicsComponent->SetMax(max); + } + + EntityManager::Instance()->SerializeEntity(targetEntity); +} + +void TriggerComponent::HandleSetPhysicsVolumeStatus(Entity* targetEntity, std::string args) { + auto* phantomPhysicsComponent = targetEntity->GetComponent<PhantomPhysicsComponent>(); + if (!phantomPhysicsComponent) { + Game::logger->Log("TriggerComponent::HandleSetPhysicsVolumeEffect", "Phantom Physics component not found!"); + return; + } + phantomPhysicsComponent->SetPhysicsEffectActive(args == "On"); + EntityManager::Instance()->SerializeEntity(targetEntity); +} + +void TriggerComponent::HandleActivateSpawnerNetwork(std::string args){ + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(args)) { + if (spawner) spawner->Activate(); + } +} + +void TriggerComponent::HandleDeactivateSpawnerNetwork(std::string args){ + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(args)) { + if (spawner) spawner->Deactivate(); + } +} + +void TriggerComponent::HandleResetSpawnerNetwork(std::string args){ + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(args)) { + if (spawner) spawner->Reset(); + } +} + +void TriggerComponent::HandleDestroySpawnerNetworkObjects(std::string args){ + for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(args)) { + if (spawner) spawner->DestroyAllEntities(); + } +} + +void TriggerComponent::HandleActivatePhysics(Entity* targetEntity, std::string args) { + if (args == "true") { + // TODO add physics entity if there isn't one + } else if (args == "false"){ + // TODO remove Phsyics entity if there is one + } else { + Game::logger->LogDebug("TriggerComponent", "Invalid argument for ActivatePhysics Trigger: %s", args.c_str()); + } +} diff --git a/dGame/dComponents/TriggerComponent.h b/dGame/dComponents/TriggerComponent.h index 492b0449..317da00e 100644 --- a/dGame/dComponents/TriggerComponent.h +++ b/dGame/dComponents/TriggerComponent.h @@ -2,13 +2,9 @@ #define __TRIGGERCOMPONENT__H__ #include "Component.h" +#include "LUTriggers.h" #include "eReplicaComponentType.h" -namespace LUTriggers { - struct Trigger; - struct Command; -}; - class TriggerComponent : public Component { public: static const eReplicaComponentType ComponentType = eReplicaComponentType::TRIGGER; @@ -17,18 +13,35 @@ public: void TriggerEvent(eTriggerEventType event, Entity* optionalTarget = nullptr); LUTriggers::Trigger* GetTrigger() const { return m_Trigger; } + void SetTriggerEnabled(bool enabled){ m_Trigger->enabled = enabled; }; + private: void HandleTriggerCommand(LUTriggers::Command* command, Entity* optionalTarget); - std::vector<std::string> ParseArgs(std::string args); std::vector<Entity*> GatherTargets(LUTriggers::Command* command, Entity* optionalTarget); // Trigger Event Handlers - void HandleSetPhysicsVolume(Entity* targetEntity, std::vector<std::string> argArray, std::string target); - void HandleUpdateMission(Entity* targetEntity, std::vector<std::string> argArray); void HandleFireEvent(Entity* targetEntity, std::string args); - void HandleCastSkill(Entity* targetEntity, uint32_t skillID); + void HandleDestroyObject(Entity* targetEntity, std::string args); + void HandleToggleTrigger(Entity* targetEntity, std::string args); + void HandleResetRebuild(Entity* targetEntity, std::string args); + void HandleMoveObject(Entity* targetEntity, std::vector<std::string> argArray); + void HandleRotateObject(Entity* targetEntity, std::vector<std::string> argArray); + void HandlePushObject(Entity* targetEntity, std::vector<std::string> argArray); + void HandleRepelObject(Entity* targetEntity, std::string args); + void HandlePlayCinematic(Entity* targetEntity, std::vector<std::string> argArray); + void HandleToggleBBB(Entity* targetEntity, std::string args); + void HandleUpdateMission(Entity* targetEntity, std::vector<std::string> argArray); + void HandlePlayEffect(Entity* targetEntity, std::vector<std::string> argArray); + void HandleCastSkill(Entity* targetEntity, std::string args); + void HandleSetPhysicsVolumeEffect(Entity* targetEntity, std::vector<std::string> argArray); + void HandleSetPhysicsVolumeStatus(Entity* targetEntity, std::string args); + void HandleActivateSpawnerNetwork(std::string args); + void HandleDeactivateSpawnerNetwork(std::string args); + void HandleResetSpawnerNetwork(std::string args); + void HandleDestroySpawnerNetworkObjects(std::string args); + void HandleActivatePhysics(Entity* targetEntity, std::string args); LUTriggers::Trigger* m_Trigger; }; diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index 5c05c28d..c0893a09 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -673,6 +673,9 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System case GAME_MSG_ACTIVATE_BUBBLE_BUFF: GameMessages::HandleActivateBubbleBuff(inStream, entity); break; + case GAME_MSG_ZONE_SUMMARY_DISMISSED: + GameMessages::HandleZoneSummaryDismissed(inStream, entity); + break; default: // Game::logger->Log("GameMessageHandler", "Unknown game message ID: %i", messageID); break; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 2941a0f9..bf7476e9 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -34,6 +34,7 @@ #include "eRacingTaskParam.h" #include "eMissionTaskType.h" #include "eMissionState.h" +#include "eTriggerEventType.h" #include <sstream> #include <future> @@ -2813,7 +2814,7 @@ void GameMessages::HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* void GameMessages::SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, bool allowGhostUpdates, bool bCloseMultiInteract, bool bSendServerNotify, bool bUseControlledObjectForAudioListener, - int endBehavior, bool hidePlayerDuringCine, float leadIn, bool leavePlayerLockedWhenFinished, + eEndBehavior endBehavior, bool hidePlayerDuringCine, float leadIn, bool leavePlayerLockedWhenFinished, bool lockPlayer, bool result, bool skipIfSamePath, float startTimeAdvance) { CBITSTREAM; CMSGHEADER; @@ -2826,8 +2827,8 @@ void GameMessages::SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, bitStream.Write(bSendServerNotify); bitStream.Write(bUseControlledObjectForAudioListener); - bitStream.Write(endBehavior != 0); - if (endBehavior != 0) bitStream.Write(endBehavior); + bitStream.Write(endBehavior != eEndBehavior::RETURN); + if (endBehavior != eEndBehavior::RETURN) bitStream.Write(endBehavior); bitStream.Write(hidePlayerDuringCine); @@ -6155,6 +6156,13 @@ void GameMessages::SendDeactivateBubbleBuffFromServer(LWOOBJID objectId, const S SEND_PACKET; } +void GameMessages::HandleZoneSummaryDismissed(RakNet::BitStream* inStream, Entity* entity) { + LWOOBJID player_id; + inStream->Read<LWOOBJID>(player_id); + auto target = EntityManager::Instance()->GetEntity(player_id); + entity->TriggerEvent(eTriggerEventType::ZONE_SUMMARY_DISMISSED, target); +}; + void GameMessages::SendSetNamebillboardState(const SystemAddress& sysAddr, LWOOBJID objectId) { CBITSTREAM; CMSGHEADER; diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 1372003e..68f4542f 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -7,6 +7,7 @@ #include <vector> #include "eMovementPlatformState.h" #include "NiPoint3.h" +#include "eEndBehavior.h" class AMFValue; class Entity; @@ -266,7 +267,7 @@ namespace GameMessages { void SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, bool allowGhostUpdates = true, bool bCloseMultiInteract = true, bool bSendServerNotify = false, bool bUseControlledObjectForAudioListener = false, - int endBehavior = 0, bool hidePlayerDuringCine = false, float leadIn = -1, bool leavePlayerLockedWhenFinished = false, + eEndBehavior endBehavior = eEndBehavior::RETURN, bool hidePlayerDuringCine = false, float leadIn = -1, bool leavePlayerLockedWhenFinished = false, bool lockPlayer = true, bool result = false, bool skipIfSamePath = false, float startTimeAdvance = 0); void SendEndCinematic(LWOOBJID objectID, std::u16string pathName, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, @@ -633,6 +634,8 @@ namespace GameMessages { void SendActivateBubbleBuffFromServer(LWOOBJID objectId, const SystemAddress& sysAddr); void SendDeactivateBubbleBuffFromServer(LWOOBJID objectId, const SystemAddress& sysAddr); + + void HandleZoneSummaryDismissed(RakNet::BitStream* inStream, Entity* entity); }; #endif // GAMEMESSAGES_H diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index f9bf4884..7383d51c 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -2018,7 +2018,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto* phantomPhysicsComponent = closest->GetComponent<PhantomPhysicsComponent>(); if (phantomPhysicsComponent != nullptr) { - ChatPackets::SendSystemMessage(sysAddr, u"Type: " + (GeneralUtils::to_u16string(phantomPhysicsComponent->GetEffectType()))); + ChatPackets::SendSystemMessage(sysAddr, u"Type: " + (GeneralUtils::to_u16string(static_cast<uint32_t>(phantomPhysicsComponent->GetEffectType())))); const auto dir = phantomPhysicsComponent->GetDirection(); ChatPackets::SendSystemMessage(sysAddr, u"Direction: <" + (GeneralUtils::to_u16string(dir.x)) + u", " + (GeneralUtils::to_u16string(dir.y)) + u", " + (GeneralUtils::to_u16string(dir.z)) + u">"); ChatPackets::SendSystemMessage(sysAddr, u"Multiplier: " + (GeneralUtils::to_u16string(phantomPhysicsComponent->GetDirectionalMultiplier()))); diff --git a/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp b/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp index c09000be..703625d2 100644 --- a/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp +++ b/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp @@ -5,13 +5,14 @@ #include "EntityManager.h" #include "AgMonumentLaserServer.h" #include "EntityManager.h" +#include "ePhysicsEffectType.h" #include "eReplicaComponentType.h" void AgLaserSensorServer::OnStartup(Entity* self) { PhantomPhysicsComponent* physComp = static_cast<PhantomPhysicsComponent*>(self->GetComponent(eReplicaComponentType::PHANTOM_PHYSICS)); physComp->SetPhysicsEffectActive(true); - physComp->SetEffectType(2); // repulse (prolly should make definitions of these are in Entity.cpp) + physComp->SetEffectType(ePhysicsEffectType::REPULSE); physComp->SetDirectionalMultiplier(static_cast<float>(m_RepelForce)); physComp->SetDirection(NiPoint3::UNIT_Y); diff --git a/dScripts/02_server/Map/GF/MastTeleport.cpp b/dScripts/02_server/Map/GF/MastTeleport.cpp index 6e50c6ec..8b8453b9 100644 --- a/dScripts/02_server/Map/GF/MastTeleport.cpp +++ b/dScripts/02_server/Map/GF/MastTeleport.cpp @@ -2,6 +2,7 @@ #include "EntityManager.h" #include "GameMessages.h" #include "Preconditions.h" +#include "eEndBehavior.h" #include "DestroyableComponent.h" #ifdef _WIN32 @@ -52,7 +53,7 @@ void MastTeleport::OnTimerDone(Entity* self, std::string timerName) { if (!cinematic.empty()) { GameMessages::SendPlayCinematic(playerId, GeneralUtils::ASCIIToUTF16(cinematic), player->GetSystemAddress(), - true, true, false, false, 0, false, leanIn + true, true, false, false, eEndBehavior::RETURN, false, leanIn ); } diff --git a/dScripts/02_server/Map/General/ForceVolumeServer.cpp b/dScripts/02_server/Map/General/ForceVolumeServer.cpp index fbaad6ee..ed9024c1 100644 --- a/dScripts/02_server/Map/General/ForceVolumeServer.cpp +++ b/dScripts/02_server/Map/General/ForceVolumeServer.cpp @@ -1,6 +1,7 @@ #include "ForceVolumeServer.h" #include "PhantomPhysicsComponent.h" #include "EntityManager.h" +#include "ePhysicsEffectType.h" void ForceVolumeServer::OnStartup(Entity* self) { auto* phantomPhysicsComponent = self->GetComponent<PhantomPhysicsComponent>(); @@ -12,7 +13,7 @@ void ForceVolumeServer::OnStartup(Entity* self) { const auto forceY = self->GetVar<float>(u"ForceY"); const auto forceZ = self->GetVar<float>(u"ForceZ"); - phantomPhysicsComponent->SetEffectType(0); // PUSH + phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::PUSH); phantomPhysicsComponent->SetDirectionalMultiplier(forceAmount); phantomPhysicsComponent->SetDirection({ forceX, forceY, forceZ }); phantomPhysicsComponent->SetPhysicsEffectActive(true); diff --git a/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp b/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp index b4d75296..74f9bd16 100644 --- a/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp +++ b/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp @@ -4,6 +4,7 @@ #include "MissionComponent.h" #include "eMissionTaskType.h" #include "eMissionState.h" +#include "eEndBehavior.h" void NtAssemblyTubeServer::OnStartup(Entity* self) { self->SetProximityRadius(5, "teleport"); @@ -45,7 +46,7 @@ void NtAssemblyTubeServer::RunAssemblyTube(Entity* self, Entity* player) { if (!teleCinematic.empty()) { const auto teleCinematicUname = teleCinematic; GameMessages::SendPlayCinematic(player->GetObjectID(), teleCinematicUname, player->GetSystemAddress(), - true, true, true, false, 0, false, -1, false, true + true, true, true, false, eEndBehavior::RETURN, false, -1, false, true ); } diff --git a/dScripts/02_server/Map/NT/NtSentinelWalkwayServer.cpp b/dScripts/02_server/Map/NT/NtSentinelWalkwayServer.cpp index 66bfe46f..257bf6da 100644 --- a/dScripts/02_server/Map/NT/NtSentinelWalkwayServer.cpp +++ b/dScripts/02_server/Map/NT/NtSentinelWalkwayServer.cpp @@ -3,6 +3,7 @@ #include "EntityManager.h" #include "MissionComponent.h" #include "eMissionTaskType.h" +#include "ePhysicsEffectType.h" void NtSentinelWalkwayServer::OnStartup(Entity* self) { auto* phantomPhysicsComponent = self->GetComponent<PhantomPhysicsComponent>(); @@ -19,7 +20,7 @@ void NtSentinelWalkwayServer::OnStartup(Entity* self) { const auto forward = self->GetRotation().GetRightVector() * -1; - phantomPhysicsComponent->SetEffectType(0); // PUSH + phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::PUSH); phantomPhysicsComponent->SetDirectionalMultiplier(force); phantomPhysicsComponent->SetDirection(forward); phantomPhysicsComponent->SetPhysicsEffectActive(true); diff --git a/dScripts/02_server/Map/NT/NtVentureCannonServer.cpp b/dScripts/02_server/Map/NT/NtVentureCannonServer.cpp index e6cd2df6..874d8aa1 100644 --- a/dScripts/02_server/Map/NT/NtVentureCannonServer.cpp +++ b/dScripts/02_server/Map/NT/NtVentureCannonServer.cpp @@ -1,6 +1,7 @@ #include "NtVentureCannonServer.h" #include "GameMessages.h" #include "EntityManager.h" +#include "eEndBehavior.h" void NtVentureCannonServer::OnUse(Entity* self, Entity* user) { auto* player = user; @@ -73,7 +74,7 @@ void NtVentureCannonServer::EnterCannonEnded(Entity* self, Entity* player) { const auto exitCinematicUname = exitCinematic; GameMessages::SendPlayCinematic(player->GetObjectID(), exitCinematicUname, player->GetSystemAddress(), - true, true, true, false, 0, false, 0, false, false + true, true, true, false, eEndBehavior::RETURN, false, 0, false, false ); self->AddCallbackTimer(1.5f, [this, self, playerID]() { diff --git a/dScripts/BasePropertyServer.cpp b/dScripts/BasePropertyServer.cpp index 7552eeca..a9f35e25 100644 --- a/dScripts/BasePropertyServer.cpp +++ b/dScripts/BasePropertyServer.cpp @@ -303,18 +303,8 @@ void BasePropertyServer::ResetSpawner(const std::string& spawnerName) { void BasePropertyServer::DestroySpawner(const std::string& spawnerName) { for (auto* spawner : dZoneManager::Instance()->GetSpawnersByName(spawnerName)) { - for (auto* node : spawner->m_Info.nodes) { - for (const auto& element : node->entities) { - auto* entity = EntityManager::Instance()->GetEntity(element); - if (entity == nullptr) - continue; - - entity->Kill(); - } - - node->entities.clear(); - } - + if (!spawner) return; + spawner->DestroyAllEntities(); spawner->Deactivate(); } } diff --git a/dScripts/ai/FV/ActParadoxPipeFix.cpp b/dScripts/ai/FV/ActParadoxPipeFix.cpp index 1dddde64..517474a9 100644 --- a/dScripts/ai/FV/ActParadoxPipeFix.cpp +++ b/dScripts/ai/FV/ActParadoxPipeFix.cpp @@ -3,6 +3,7 @@ #include "RebuildComponent.h" #include "GameMessages.h" #include "MissionComponent.h" +#include "eEndBehavior.h" void ActParadoxPipeFix::OnRebuildComplete(Entity* self, Entity* target) { const auto myGroup = "AllPipes"; @@ -42,7 +43,7 @@ void ActParadoxPipeFix::OnRebuildComplete(Entity* self, Entity* target) { missionComponent->ForceProgressTaskType(769, 1, 1, false); } - GameMessages::SendPlayCinematic(player->GetObjectID(), u"ParadoxPipeFinish", player->GetSystemAddress(), true, true, false, false, 0, false, 2.0f); + GameMessages::SendPlayCinematic(player->GetObjectID(), u"ParadoxPipeFinish", player->GetSystemAddress(), true, true, false, false, eEndBehavior::RETURN, false, 2.0f); } object->SetVar(u"PlayerID", LWOOBJID_EMPTY); diff --git a/dZoneManager/Spawner.cpp b/dZoneManager/Spawner.cpp index 57b4e988..28f77fea 100644 --- a/dZoneManager/Spawner.cpp +++ b/dZoneManager/Spawner.cpp @@ -134,24 +134,23 @@ void Spawner::AddEntitySpawnedCallback(std::function<void(Entity*)> callback) { void Spawner::Reset() { m_Start = true; - - for (auto* node : m_Info.nodes) { - for (const auto& spawned : node->entities) { - auto* entity = EntityManager::Instance()->GetEntity(spawned); - - if (entity == nullptr) continue; - - entity->Kill(); - } - - node->entities.clear(); - } - + DestroyAllEntities(); m_Entities.clear(); m_AmountSpawned = 0; m_NeedsUpdate = true; } +void Spawner::DestroyAllEntities(){ + for (auto* node : m_Info.nodes) { + for (const auto& element : node->entities) { + auto* entity = EntityManager::Instance()->GetEntity(element); + if (entity == nullptr) continue; + entity->Kill(); + } + node->entities.clear(); + } +} + void Spawner::SoftReset() { m_Start = true; m_AmountSpawned = 0; diff --git a/dZoneManager/Spawner.h b/dZoneManager/Spawner.h index a42c8a65..1f610b71 100644 --- a/dZoneManager/Spawner.h +++ b/dZoneManager/Spawner.h @@ -61,6 +61,7 @@ public: void AddEntitySpawnedCallback(std::function<void(Entity*)> callback); void SetSpawnLot(LOT lot); void Reset(); + void DestroyAllEntities(); void SoftReset(); void SetRespawnTime(float time); void SetNumToMaintain(int32_t value); diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index 52008b5d..ac3a7008 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -182,17 +182,7 @@ void dZoneManager::RemoveSpawner(const LWOOBJID id) { Game::logger->Log("dZoneManager", "Failed to find spawner entity (%llu)", id); } - for (auto* node : spawner->m_Info.nodes) { - for (const auto& element : node->entities) { - auto* nodeEntity = EntityManager::Instance()->GetEntity(element); - - if (nodeEntity == nullptr) continue; - - nodeEntity->Kill(); - } - - node->entities.clear(); - } + spawner->DestroyAllEntities(); spawner->Deactivate(); From cbef4a140efaac328b46cff65598983cf78dc42b Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Thu, 30 Mar 2023 06:01:15 -0700 Subject: [PATCH 274/322] Fix Spider Queen boss battle crash (#1034) --- .../Enemy/AG/BossSpiderQueenEnemyServer.cpp | 139 ++++-------------- 1 file changed, 30 insertions(+), 109 deletions(-) diff --git a/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp b/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp index c584f05b..a3b9cc3f 100644 --- a/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp +++ b/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp @@ -48,8 +48,6 @@ void BossSpiderQueenEnemyServer::OnStartup(Entity* self) { m_CurrentBossStage = 1; // Obtain faction and collision group to save for subsequent resets - //self : SetVar("SBFactionList", self:GetFaction().factionList) - //self : SetVar("SBCollisionGroup", self:GetCollisionGroup().colGroup) } void BossSpiderQueenEnemyServer::OnDie(Entity* self, Entity* killer) { @@ -61,8 +59,6 @@ void BossSpiderQueenEnemyServer::OnDie(Entity* self, Entity* killer) { missionComponent->CompleteMission(instanceMissionID); } - Game::logger->Log("BossSpiderQueenEnemyServer", "Starting timer..."); - // There is suppose to be a 0.1 second delay here but that may be admitted? auto* controller = EntityManager::Instance()->GetZoneControlEntity(); @@ -165,9 +161,6 @@ void BossSpiderQueenEnemyServer::SpawnSpiderWave(Entity* self, int spiderCount) // The Spider Queen Boss is withdrawing and requesting the spawn // of a hatchling wave - /*auto SpiderEggNetworkID = self->GetI64(u"SpiderEggNetworkID"); - if (SpiderEggNetworkID == 0) return;*/ - // Clamp invalid Spiderling number requests to the maximum amount of eggs available if ((spiderCount > maxSpiderEggCnt) || (spiderCount < 0)) spiderCount = maxSpiderEggCnt; @@ -176,44 +169,13 @@ void BossSpiderQueenEnemyServer::SpawnSpiderWave(Entity* self, int spiderCount) hatchCounter = spiderCount; hatchList = {}; - Game::logger->Log("SpiderQueen", "Trying to spawn %i spiders", hatchCounter); - - // Run the wave manager SpiderWaveManager(self); - } void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { auto SpiderEggNetworkID = self->GetI64(u"SpiderEggNetworkID"); - // Reset the spider egg spawner network to ensure a maximum number of eggs - //SpiderEggNetworkID:SpawnerReset() - - // Obtain a list of all the eggs on the egg spawner network - - //auto spiderEggList = SpiderEggNetworkID:SpawnerGetAllObjectIDsSpawned().objects; - - //if (table.maxn(spiderEggList) <= 0) { - // self->AddTimer("PollSpiderWaveManager", 1.0f); - // return; - //} - // - //// A check for (wave mangement across multiple spawn iterations - //if(hatchCounter < spiderWaveCnt) { - // // We have already prepped some objects for (hatching, - // // remove them from our list for (random egg pulls - // for (i, sVal in ipairs(spiderEggList) { - // if(hatchList[sVal:GetID()]) { - // // We have found a prepped egg, remove it from the spiderEggList - // spiderEggList[i] = nil - // } - // } - - //} - - - std::vector<LWOOBJID> spiderEggs{}; auto spooders = EntityManager::Instance()->GetEntitiesInGroup("EGG"); @@ -223,44 +185,43 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { // Select a number of random spider eggs from the list equal to the // current number needed to complete the current wave - for (int i = 0; i < hatchCounter; i++) { - // Select a random spider egg - auto randomEggLoc = GeneralUtils::GenerateRandomNumber<int>(0, spiderEggs.size() - 1); - auto randomEgg = spiderEggs[randomEggLoc]; + if (!spiderEggs.empty()) { + for (int i = 0; i < hatchCounter; i++) { + // Select a random spider egg + auto randomEggLoc = GeneralUtils::GenerateRandomNumber<int>(0, spiderEggs.size() - 1); + auto randomEgg = spiderEggs[randomEggLoc]; - //Just a quick check to try and prevent dupes: - for (auto en : hatchList) { - if (en == randomEgg) { - randomEggLoc++; - randomEgg = spiderEggs[randomEggLoc]; - } - } - - if (randomEgg) { - auto* eggEntity = EntityManager::Instance()->GetEntity(randomEgg); - - if (eggEntity == nullptr) { - continue; + //Just a quick check to try and prevent dupes: + for (auto en : hatchList) { + if (en == randomEgg) { + randomEggLoc++; + randomEgg = spiderEggs[randomEggLoc]; + } } - // Prep the selected spider egg - //randomEgg:FireEvent{s}erID=self, args="prepEgg"} - eggEntity->OnFireEventServerSide(self, "prepEgg"); - Game::logger->Log("SpiderQueen", "Prepping egg %llu", eggEntity->GetObjectID()); + if (randomEgg) { + auto* eggEntity = EntityManager::Instance()->GetEntity(randomEgg); - // Add the prepped egg to our hatchList - hatchList.push_back(eggEntity->GetObjectID()); + if (eggEntity == nullptr) { + continue; + } - // Decrement the hatchCounter - hatchCounter = hatchCounter - 1; - } + // Prep the selected spider egg + eggEntity->OnFireEventServerSide(self, "prepEgg"); - // Remove it from our spider egg list - //table.remove(spiderEggList, randomEggLoc); - spiderEggs[randomEggLoc] = LWOOBJID_EMPTY; + // Add the prepped egg to our hatchList + hatchList.push_back(eggEntity->GetObjectID()); - if (spiderEggs.size() <= 0 || (hatchCounter <= 0)) { - break; + // Decrement the hatchCounter + hatchCounter = hatchCounter - 1; + } + + // Remove it from our spider egg list + spiderEggs[randomEggLoc] = LWOOBJID_EMPTY; + + if (spiderEggs.size() <= 0 || (hatchCounter <= 0)) { + break; + } } } @@ -279,14 +240,12 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { } eggEntity->OnFireEventServerSide(self, "hatchEgg"); - Game::logger->Log("SpiderQueen", "hatching egg %llu", eggEntity->GetObjectID()); auto time = PlayAnimAndReturnTime(self, spiderWithdrawIdle); combat->SetStunImmune(false); combat->Stun(time += 6.0f); combat->SetStunImmune(true); - //self->AddTimer("disableWaitForIdle", defaultAnimPause); self->AddTimer("checkForSpiders", 6.0f); } @@ -397,10 +356,6 @@ void BossSpiderQueenEnemyServer::RapidFireShooterManager(Entity* self) { } void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) { - /* - const auto targets = EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::CHARACTER); - */ - const auto targets = self->GetTargetsInPhantom(); if (self->GetBoolean(u"stoppedFlag")) { @@ -433,8 +388,6 @@ void BossSpiderQueenEnemyServer::RunRapidFireShooter(Entity* self) { PlayAnimAndReturnTime(self, spiderSingleShot); - Game::logger->Log("BossSpiderQueenEnemyServer", "Ran RFS"); - self->AddTimer("RFS", GeneralUtils::GenerateRandomNumber<float>(10, 15)); } @@ -556,26 +509,6 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(self, u"camshake-bridge", self->GetObjectID(), 100.0f); } else if (timerName == "AdvanceComplete") { - //Reset faction and collision - /*local SBFactionList = self:GetVar("SBFactionList") - local SBCollisionGroup = self:GetVar("SBCollisionGroup") - - for i, fVal in ipairs(SBFactionList) { - if(i == 1) { - //Our first faction - flush and add - self:SetFaction{faction = fVal} - else - //Add - self:ModifyFaction{factionID = fVal, bAddFaction = true} - } - }*/ - - /* - auto SBCollisionGroup = self->GetI32(u"SBCollisionGroup"); - - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SetColGroup", SBCollisionGroup, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); - */ - GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SetColGroup", 11, 0, 0, "", UNASSIGNED_SYSTEM_ADDRESS); //Wind up, telegraphing next round @@ -625,7 +558,6 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim //Did we queue a spcial attack? if (self->GetBoolean(u"bSpecialQueued")) { self->SetBoolean(u"bSpecialQueued", false); - //SpiderSkillManager(self, true); } } } @@ -673,17 +605,6 @@ void BossSpiderQueenEnemyServer::OnUpdate(Entity* self) { controllable->SetStatic(true); EntityManager::Instance()->SerializeEntity(self); - - //if (waitForIdle) return; - - ////Play the Spider Boss' mountain idle anim - //PlayAnimAndReturnTime(self, spiderWithdrawIdle); - - ////If there are still baby spiders, don't do anyhting either - //auto spooders = EntityManager::Instance()->GetEntitiesInGroup("BabySpider"); - //if (spooders.size() > 0) return; - //else - // WithdrawSpider(self, false); } //---------------------------------------------- From 152c8ea71218b2d210005684bd45843df71defe5 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Fri, 31 Mar 2023 14:50:17 -0700 Subject: [PATCH 275/322] Add npc (#1038) --- vanity/NPC.xml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/vanity/NPC.xml b/vanity/NPC.xml index 3bb5ae9f..dfe324c3 100644 --- a/vanity/NPC.xml +++ b/vanity/NPC.xml @@ -17,6 +17,18 @@ </locations> </zone> </npc> + <npc name="EmosewaMC - Quickbuilder" lot="6738"> + <equipment>12947, 12949, 12962, 12963</equipment> + <phrases> + <phrase>I hope quickbulds are still working!</phrase> + <phrase>Be careful crossing the gap!</phrase> + </phrases> + <zone id="1800"> + <locations> + <location x="745.756" y="75.262" z="-207.989" rw="0.838565" rx="0.0" ry="0.544801" rz="0.0" /> + </locations> + </zone> + </npc> <npc name="Neal - Paradox Scout" lot="6738"> <equipment>9950, 9944, 14102, 14092</equipment> <phrases> From 49d695a153aeb6537458dd642ca9bde17765612b Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 1 Apr 2023 02:45:29 -0700 Subject: [PATCH 276/322] Remove extra bit in BasicAttackBehavior write (#1039) --- dGame/dBehaviors/BasicAttackBehavior.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/dBehaviors/BasicAttackBehavior.cpp b/dGame/dBehaviors/BasicAttackBehavior.cpp index 97068d91..f8693795 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.cpp +++ b/dGame/dBehaviors/BasicAttackBehavior.cpp @@ -147,7 +147,7 @@ void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* DoBehaviorCalculation(context, bitStream, branch); const auto endAddress = bitStream->GetWriteOffset(); - const uint16_t allocate = endAddress - startAddress + 1; + const uint16_t allocate = endAddress - startAddress; bitStream->SetWriteOffset(allocatedAddress); bitStream->Write(allocate); From 801ca69778c9a073f70ded93cee13382a2a72e16 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 1 Apr 2023 18:30:08 -0700 Subject: [PATCH 277/322] Fix nameplate command (#1040) --- dGame/dUtilities/SlashCommandHandler.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 7383d51c..6f346d88 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -173,7 +173,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } #endif - if (chatCommand == "togglenameplate" && (Game::config->GetValue("allownameplateoff") == "1" || entity->GetGMLevel() > eGameMasterLevel::DEVELOPER)) { + if (chatCommand == "togglenameplate" && (Game::config->GetValue("allow_nameplate_off") == "1" || entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER)) { auto* character = entity->GetCharacter(); if (character && character->GetBillboardVisible()) { From 54d8c45b52e1506e21ee8bb2825f66b978cbd239 Mon Sep 17 00:00:00 2001 From: David Markowitz <EmosewaMC@gmail.com> Date: Sun, 2 Apr 2023 11:54:34 -0700 Subject: [PATCH 278/322] Don't interrupt players --- dGame/dBehaviors/InterruptBehavior.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/dGame/dBehaviors/InterruptBehavior.cpp b/dGame/dBehaviors/InterruptBehavior.cpp index 9035c092..96cba1b1 100644 --- a/dGame/dBehaviors/InterruptBehavior.cpp +++ b/dGame/dBehaviors/InterruptBehavior.cpp @@ -46,6 +46,8 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS if (target == nullptr) return; + if (target->GetLOT() == 1) return; + auto* skillComponent = target->GetComponent<SkillComponent>(); if (skillComponent == nullptr) return; @@ -71,6 +73,8 @@ void InterruptBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* b if (target == nullptr) return; + if (target->GetLOT() == 1) return; + auto* skillComponent = target->GetComponent<SkillComponent>(); if (skillComponent == nullptr) return; From 595afe42e5a0764672d5473396a48790a0be2201 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Sun, 2 Apr 2023 22:37:24 -0500 Subject: [PATCH 279/322] fix the lookat --- dGame/dBehaviors/ChangeOrientationBehavior.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/dBehaviors/ChangeOrientationBehavior.cpp b/dGame/dBehaviors/ChangeOrientationBehavior.cpp index a60be62f..d07e7429 100644 --- a/dGame/dBehaviors/ChangeOrientationBehavior.cpp +++ b/dGame/dBehaviors/ChangeOrientationBehavior.cpp @@ -16,7 +16,7 @@ void ChangeOrientationBehavior::Calculate(BehaviorContext* context, RakNet::BitS if (self == nullptr || other == nullptr) return; const auto source = self->GetPosition(); - const auto destination = self->GetPosition(); + const auto destination = other->GetPosition(); if (m_OrientCaster) { auto* baseCombatAIComponent = self->GetComponent<BaseCombatAIComponent>(); From a26f29baf696735112fc6b7ac4c7e319d9138d37 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sun, 2 Apr 2023 23:26:44 -0700 Subject: [PATCH 280/322] Fix some models not disassembling into bricks (#1041) --- dGame/dInventory/Item.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index acaecbf7..5795ab12 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -390,19 +390,22 @@ void Item::DisassembleModel() { const auto componentId = table->GetByIDAndType(GetLot(), eReplicaComponentType::RENDER); auto query = CDClientDatabase::CreatePreppedStmt( - "SELECT render_asset FROM RenderComponent WHERE id = ?;"); + "SELECT render_asset, LXFMLFolder FROM RenderComponent WHERE id = ?;"); query.bind(1, (int)componentId); auto result = query.execQuery(); - if (result.eof()) { + if (result.eof() || result.fieldIsNull(0)) { return; } - std::string renderAsset = result.fieldIsNull(0) ? "" : std::string(result.getStringField(0)); - std::vector<std::string> renderAssetSplit = GeneralUtils::SplitString(renderAsset, '\\'); + std::string renderAsset = std::string(result.getStringField(0)); + std::string lxfmlFolderName = std::string(result.getStringField(1)); - std::string lxfmlPath = "BrickModels/" + GeneralUtils::SplitString(renderAssetSplit.back(), '.').at(0) + ".lxfml"; + std::vector<std::string> renderAssetSplit = GeneralUtils::SplitString(renderAsset, '\\'); + if (renderAssetSplit.size() == 0) return; + + std::string lxfmlPath = "BrickModels/" + lxfmlFolderName + "/" + GeneralUtils::SplitString(renderAssetSplit.back(), '.').at(0) + ".lxfml"; auto buffer = Game::assetManager->GetFileAsBuffer(lxfmlPath.c_str()); if (!buffer.m_Success) { From b8251c06b8dbdbc215b86d64c3ac6a8293fdc86f Mon Sep 17 00:00:00 2001 From: David Markowitz <EmosewaMC@gmail.com> Date: Mon, 3 Apr 2023 04:11:02 -0700 Subject: [PATCH 281/322] Fix incorrect SwitchMultiple handling --- dGame/dBehaviors/SwitchMultipleBehavior.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/dGame/dBehaviors/SwitchMultipleBehavior.cpp b/dGame/dBehaviors/SwitchMultipleBehavior.cpp index 078464bb..23411429 100644 --- a/dGame/dBehaviors/SwitchMultipleBehavior.cpp +++ b/dGame/dBehaviors/SwitchMultipleBehavior.cpp @@ -22,13 +22,9 @@ void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* for (unsigned int i = 0; i < this->m_behaviors.size(); i++) { const double data = this->m_behaviors.at(i).first; + trigger = i; - if (value <= data) { - - trigger = i; - - break; - } + if (value <= data) break; } auto* behavior = this->m_behaviors.at(trigger).second; From 1fb086ccbdb146caa4423191fc9e1d57dd996684 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Mon, 3 Apr 2023 08:21:23 -0500 Subject: [PATCH 282/322] Fully implement Change orientation fix bug where you would always look at self added to_angle handline --- .../dBehaviors/ChangeOrientationBehavior.cpp | 57 +++++++++---------- dGame/dBehaviors/ChangeOrientationBehavior.h | 24 +++----- 2 files changed, 35 insertions(+), 46 deletions(-) diff --git a/dGame/dBehaviors/ChangeOrientationBehavior.cpp b/dGame/dBehaviors/ChangeOrientationBehavior.cpp index d07e7429..a7dc838f 100644 --- a/dGame/dBehaviors/ChangeOrientationBehavior.cpp +++ b/dGame/dBehaviors/ChangeOrientationBehavior.cpp @@ -2,43 +2,40 @@ #include "BehaviorBranchContext.h" #include "BehaviorContext.h" #include "EntityManager.h" -#include "BaseCombatAIComponent.h" - -void ChangeOrientationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { -} void ChangeOrientationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - if (!m_ToTarget) return; // TODO: Add the other arguments to this behavior + Entity* sourceEntity; + if (this->m_orientCaster) sourceEntity = EntityManager::Instance()->GetEntity(context->originator); + else sourceEntity = EntityManager::Instance()->GetEntity(branch.target); + if (!sourceEntity) return; - auto* self = EntityManager::Instance()->GetEntity(context->originator); - auto* other = EntityManager::Instance()->GetEntity(branch.target); - if (self == nullptr || other == nullptr) return; + if (this->m_toTarget) { + Entity* destinationEntity; + if (this->m_orientCaster) destinationEntity = EntityManager::Instance()->GetEntity(branch.target); + else destinationEntity = EntityManager::Instance()->GetEntity(context->originator); + if (!destinationEntity) return; - const auto source = self->GetPosition(); - const auto destination = other->GetPosition(); - - if (m_OrientCaster) { - auto* baseCombatAIComponent = self->GetComponent<BaseCombatAIComponent>(); - - /*if (baseCombatAIComponent != nullptr) - { - baseCombatAIComponent->LookAt(destination); + const auto source = sourceEntity->GetPosition(); + const auto destination = destinationEntity->GetPosition(); + sourceEntity->SetRotation(NiQuaternion::LookAt(source, destination)); + } else if (this->m_toAngle){ + auto baseAngle = NiPoint3(this->m_angle, 0, 0); + if (this->m_relative){ + auto sourceAngle = sourceEntity->GetRotation().GetEulerAngles(); + baseAngle += sourceAngle; } - else*/ - { - self->SetRotation(NiQuaternion::LookAt(source, destination)); - } - - EntityManager::Instance()->SerializeEntity(self); - } else { - other->SetRotation(NiQuaternion::LookAt(destination, source)); - - EntityManager::Instance()->SerializeEntity(other); - } + auto newRotation = NiQuaternion::FromEulerAngles(baseAngle); + sourceEntity->SetRotation(newRotation); + } else return; + EntityManager::Instance()->SerializeEntity(sourceEntity); + return; } void ChangeOrientationBehavior::Load() { - m_OrientCaster = GetBoolean("orient_caster"); - m_ToTarget = GetBoolean("to_target"); + this->m_orientCaster = GetBoolean("orient_caster", true); + this->m_toTarget = GetBoolean("to_target", false); + this->m_toAngle = GetBoolean("to_angle", false); + this->m_angle = GetFloat("angle", 0.0f); + this->m_relative = GetBoolean("relative", false); } diff --git a/dGame/dBehaviors/ChangeOrientationBehavior.h b/dGame/dBehaviors/ChangeOrientationBehavior.h index eb038ffb..46d471ad 100644 --- a/dGame/dBehaviors/ChangeOrientationBehavior.h +++ b/dGame/dBehaviors/ChangeOrientationBehavior.h @@ -1,25 +1,17 @@ #pragma once #include "Behavior.h" - #include <vector> -class ChangeOrientationBehavior final : public Behavior -{ +class ChangeOrientationBehavior final : public Behavior { public: - bool m_OrientCaster; - bool m_ToTarget; - - /* - * Inherited - */ - - explicit ChangeOrientationBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { - } - - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - + explicit ChangeOrientationBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void Load() override; +private: + bool m_orientCaster; + bool m_toTarget; + bool m_toAngle; + float m_angle; + bool m_relative; }; From a5ff93351dea4e19c0c4121db0c532f22719690a Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Mon, 3 Apr 2023 08:25:47 -0500 Subject: [PATCH 283/322] remove empty line remove undeeded header --- dGame/dBehaviors/ChangeOrientationBehavior.cpp | 1 - dGame/dBehaviors/ChangeOrientationBehavior.h | 1 - 2 files changed, 2 deletions(-) diff --git a/dGame/dBehaviors/ChangeOrientationBehavior.cpp b/dGame/dBehaviors/ChangeOrientationBehavior.cpp index a7dc838f..398e9e33 100644 --- a/dGame/dBehaviors/ChangeOrientationBehavior.cpp +++ b/dGame/dBehaviors/ChangeOrientationBehavior.cpp @@ -9,7 +9,6 @@ void ChangeOrientationBehavior::Calculate(BehaviorContext* context, RakNet::BitS else sourceEntity = EntityManager::Instance()->GetEntity(branch.target); if (!sourceEntity) return; - if (this->m_toTarget) { Entity* destinationEntity; if (this->m_orientCaster) destinationEntity = EntityManager::Instance()->GetEntity(branch.target); diff --git a/dGame/dBehaviors/ChangeOrientationBehavior.h b/dGame/dBehaviors/ChangeOrientationBehavior.h index 46d471ad..22c92bb8 100644 --- a/dGame/dBehaviors/ChangeOrientationBehavior.h +++ b/dGame/dBehaviors/ChangeOrientationBehavior.h @@ -1,7 +1,6 @@ #pragma once #include "Behavior.h" -#include <vector> class ChangeOrientationBehavior final : public Behavior { public: From dffcbcd4d4970927a3137dd4ad85c830df9aeb8a Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Mon, 3 Apr 2023 08:29:39 -0500 Subject: [PATCH 284/322] cleanup --- dGame/dBehaviors/ChangeOrientationBehavior.cpp | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/dGame/dBehaviors/ChangeOrientationBehavior.cpp b/dGame/dBehaviors/ChangeOrientationBehavior.cpp index 398e9e33..ee9e2009 100644 --- a/dGame/dBehaviors/ChangeOrientationBehavior.cpp +++ b/dGame/dBehaviors/ChangeOrientationBehavior.cpp @@ -15,17 +15,13 @@ void ChangeOrientationBehavior::Calculate(BehaviorContext* context, RakNet::BitS else destinationEntity = EntityManager::Instance()->GetEntity(context->originator); if (!destinationEntity) return; - const auto source = sourceEntity->GetPosition(); - const auto destination = destinationEntity->GetPosition(); - sourceEntity->SetRotation(NiQuaternion::LookAt(source, destination)); + sourceEntity->SetRotation( + NiQuaternion::LookAt(sourceEntity->GetPosition(), destinationEntity->GetPosition()) + ); } else if (this->m_toAngle){ auto baseAngle = NiPoint3(this->m_angle, 0, 0); - if (this->m_relative){ - auto sourceAngle = sourceEntity->GetRotation().GetEulerAngles(); - baseAngle += sourceAngle; - } - auto newRotation = NiQuaternion::FromEulerAngles(baseAngle); - sourceEntity->SetRotation(newRotation); + if (this->m_relative) baseAngle += sourceEntity->GetRotation().GetEulerAngles(); + sourceEntity->SetRotation(NiQuaternion::FromEulerAngles(baseAngle)); } else return; EntityManager::Instance()->SerializeEntity(sourceEntity); return; From 426a84daf98e2edf4657b8b9c43536a65ff91795 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 3 Apr 2023 09:37:29 -0700 Subject: [PATCH 285/322] Update InterruptBehavior.cpp --- dGame/dBehaviors/InterruptBehavior.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/dGame/dBehaviors/InterruptBehavior.cpp b/dGame/dBehaviors/InterruptBehavior.cpp index 96cba1b1..9035c092 100644 --- a/dGame/dBehaviors/InterruptBehavior.cpp +++ b/dGame/dBehaviors/InterruptBehavior.cpp @@ -46,8 +46,6 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS if (target == nullptr) return; - if (target->GetLOT() == 1) return; - auto* skillComponent = target->GetComponent<SkillComponent>(); if (skillComponent == nullptr) return; @@ -73,8 +71,6 @@ void InterruptBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* b if (target == nullptr) return; - if (target->GetLOT() == 1) return; - auto* skillComponent = target->GetComponent<SkillComponent>(); if (skillComponent == nullptr) return; From 930735860b05a23bee25eb7f78946546359ad7be Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Mon, 3 Apr 2023 13:10:51 -0500 Subject: [PATCH 286/322] use z axis --- dGame/dBehaviors/ChangeOrientationBehavior.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dGame/dBehaviors/ChangeOrientationBehavior.cpp b/dGame/dBehaviors/ChangeOrientationBehavior.cpp index ee9e2009..36a2e6a8 100644 --- a/dGame/dBehaviors/ChangeOrientationBehavior.cpp +++ b/dGame/dBehaviors/ChangeOrientationBehavior.cpp @@ -19,8 +19,8 @@ void ChangeOrientationBehavior::Calculate(BehaviorContext* context, RakNet::BitS NiQuaternion::LookAt(sourceEntity->GetPosition(), destinationEntity->GetPosition()) ); } else if (this->m_toAngle){ - auto baseAngle = NiPoint3(this->m_angle, 0, 0); - if (this->m_relative) baseAngle += sourceEntity->GetRotation().GetEulerAngles(); + auto baseAngle = NiPoint3(0, 0, this->m_angle); + if (this->m_relative) baseAngle += sourceEntity->GetRotation().GetForwardVector(); sourceEntity->SetRotation(NiQuaternion::FromEulerAngles(baseAngle)); } else return; EntityManager::Instance()->SerializeEntity(sourceEntity); From 541250176c8c5d203480e53de4e58ea598740656 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 5 Apr 2023 06:57:47 -0700 Subject: [PATCH 287/322] Resolve many issues with invisible enemies and End Behavior nodes not firing (#1044) * Finall fix invisible enemies * Add garbage collection * Add comment * Add constexpr for lagFrames --- dGame/dBehaviors/AirMovementBehavior.cpp | 3 ++- dGame/dBehaviors/AirMovementBehavior.h | 10 +++------- dGame/dBehaviors/AttackDelayBehavior.cpp | 2 +- dGame/dBehaviors/BehaviorContext.cpp | 20 +++++++++++++++++++- dGame/dBehaviors/BehaviorContext.h | 4 +++- dGame/dBehaviors/ChargeUpBehavior.cpp | 3 ++- dGame/dBehaviors/ChargeUpBehavior.h | 12 ++++-------- dGame/dBehaviors/ForceMovementBehavior.cpp | 2 +- dGame/dComponents/SkillComponent.cpp | 18 +++++++++++++++--- vanity/NPC.xml | 1 + 10 files changed, 51 insertions(+), 24 deletions(-) diff --git a/dGame/dBehaviors/AirMovementBehavior.cpp b/dGame/dBehaviors/AirMovementBehavior.cpp index 932297b9..dbfde465 100644 --- a/dGame/dBehaviors/AirMovementBehavior.cpp +++ b/dGame/dBehaviors/AirMovementBehavior.cpp @@ -13,7 +13,7 @@ void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi return; } - context->RegisterSyncBehavior(handle, this, branch); + context->RegisterSyncBehavior(handle, this, branch, this->m_Timeout); } void AirMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { @@ -47,4 +47,5 @@ void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitS } void AirMovementBehavior::Load() { + this->m_Timeout = (GetFloat("timeout_ms") / 1000.0f); } diff --git a/dGame/dBehaviors/AirMovementBehavior.h b/dGame/dBehaviors/AirMovementBehavior.h index 89dc1e05..9d51ef03 100644 --- a/dGame/dBehaviors/AirMovementBehavior.h +++ b/dGame/dBehaviors/AirMovementBehavior.h @@ -4,13 +4,7 @@ class AirMovementBehavior final : public Behavior { public: - - /* - * Inherited - */ - - explicit AirMovementBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { - } + explicit AirMovementBehavior(const uint32_t behavior_id) : Behavior(behavior_id) {} void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; @@ -19,4 +13,6 @@ public: void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; +private: + float m_Timeout; }; diff --git a/dGame/dBehaviors/AttackDelayBehavior.cpp b/dGame/dBehaviors/AttackDelayBehavior.cpp index ccea5fd9..af33aadd 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.cpp +++ b/dGame/dBehaviors/AttackDelayBehavior.cpp @@ -13,7 +13,7 @@ void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi }; for (auto i = 0u; i < this->m_numIntervals; ++i) { - context->RegisterSyncBehavior(handle, this, branch, m_ignoreInterrupts); + context->RegisterSyncBehavior(handle, this, branch, m_ignoreInterrupts, this->m_delay * i); } } diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index 397e0c72..d0cb68e4 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -47,7 +47,7 @@ uint32_t BehaviorContext::GetUniqueSkillId() const { } -void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext, bool ignoreInterrupts) { +void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext, const float duration, bool ignoreInterrupts) { auto entry = BehaviorSyncEntry(); entry.handle = syncId; @@ -55,6 +55,9 @@ void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* beha entry.branchContext = branchContext; entry.branchContext.isSync = true; entry.ignoreInterrupts = ignoreInterrupts; + // Add 10 seconds + duration time to account for lag and give clients time to send their syncs to the server. + constexpr float lagTime = 10.0f; + entry.time = lagTime + duration; this->syncEntries.push_back(entry); } @@ -183,6 +186,21 @@ void BehaviorContext::SyncCalculation(const uint32_t syncId, const float time, B this->syncEntries.push_back(entry); } +void BehaviorContext::UpdatePlayerSyncs(float deltaTime) { + uint32_t i = 0; + while (i < this->syncEntries.size()) { + auto& entry = this->syncEntries.at(i); + + entry.time -= deltaTime; + + if (entry.time >= 0.0f) { + i++; + continue; + } + this->syncEntries.erase(this->syncEntries.begin() + i); + } +} + void BehaviorContext::InvokeEnd(const uint32_t id) { std::vector<BehaviorEndEntry> entries; diff --git a/dGame/dBehaviors/BehaviorContext.h b/dGame/dBehaviors/BehaviorContext.h index dbba4d91..117f328d 100644 --- a/dGame/dBehaviors/BehaviorContext.h +++ b/dGame/dBehaviors/BehaviorContext.h @@ -80,7 +80,9 @@ struct BehaviorContext uint32_t GetUniqueSkillId() const; - void RegisterSyncBehavior(uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext, bool ignoreInterrupts = false); + void UpdatePlayerSyncs(float deltaTime); + + void RegisterSyncBehavior(uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext, const float duration, bool ignoreInterrupts = false); void RegisterTimerBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, LWOOBJID second = LWOOBJID_EMPTY); diff --git a/dGame/dBehaviors/ChargeUpBehavior.cpp b/dGame/dBehaviors/ChargeUpBehavior.cpp index 1b9ba433..4c7c3dac 100644 --- a/dGame/dBehaviors/ChargeUpBehavior.cpp +++ b/dGame/dBehaviors/ChargeUpBehavior.cpp @@ -12,7 +12,7 @@ void ChargeUpBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt return; }; - context->RegisterSyncBehavior(handle, this, branch); + context->RegisterSyncBehavior(handle, this, branch, this->m_MaxDuration); } void ChargeUpBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { @@ -24,4 +24,5 @@ void ChargeUpBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStre void ChargeUpBehavior::Load() { this->m_action = GetAction("action"); + this->m_MaxDuration = GetFloat("max_duration"); } diff --git a/dGame/dBehaviors/ChargeUpBehavior.h b/dGame/dBehaviors/ChargeUpBehavior.h index d753895e..ceb40f6c 100644 --- a/dGame/dBehaviors/ChargeUpBehavior.h +++ b/dGame/dBehaviors/ChargeUpBehavior.h @@ -4,14 +4,7 @@ class ChargeUpBehavior final : public Behavior { public: - Behavior* m_action; - - /* - * Inherited - */ - - explicit ChargeUpBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { - } + explicit ChargeUpBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; @@ -20,4 +13,7 @@ public: void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Load() override; +private: + Behavior* m_action; + float m_MaxDuration; }; diff --git a/dGame/dBehaviors/ForceMovementBehavior.cpp b/dGame/dBehaviors/ForceMovementBehavior.cpp index e095447c..52359cf7 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.cpp +++ b/dGame/dBehaviors/ForceMovementBehavior.cpp @@ -16,7 +16,7 @@ void ForceMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* Game::logger->Log("ForceMovementBehavior", "Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); return; } - context->RegisterSyncBehavior(handle, this, branch); + context->RegisterSyncBehavior(handle, this, branch, this->m_Duration); } void ForceMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index 23ef1bee..ae0e82f0 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -134,6 +134,10 @@ void SkillComponent::Update(const float deltaTime) { CalculateUpdate(deltaTime); } + if (m_Parent->IsPlayer()) { + for (const auto& pair : this->m_managedBehaviors) pair.second->UpdatePlayerSyncs(deltaTime); + } + std::map<uint32_t, BehaviorContext*> keep{}; for (const auto& pair : this->m_managedBehaviors) { @@ -192,7 +196,15 @@ void SkillComponent::Interrupt() { auto* combat = m_Parent->GetComponent<BaseCombatAIComponent>(); if (combat != nullptr && combat->GetStunImmune()) return; - for (const auto& behavior : this->m_managedBehaviors) behavior.second->Interrupt(); + for (const auto& behavior : this->m_managedBehaviors) { + for (const auto& behaviorEndEntry : behavior.second->endEntries) { + behaviorEndEntry.behavior->End(behavior.second, behaviorEndEntry.branchContext, behaviorEndEntry.second); + } + behavior.second->endEntries.clear(); + if (m_Parent->IsPlayer()) continue; + behavior.second->Interrupt(); + } + } void SkillComponent::RegisterCalculatedProjectile(const LWOOBJID projectileId, BehaviorContext* context, const BehaviorBranchContext& branch, const LOT lot, const float maxTime, @@ -215,7 +227,7 @@ void SkillComponent::RegisterCalculatedProjectile(const LWOOBJID projectileId, B this->m_managedProjectiles.push_back(entry); } -bool SkillComponent::CastSkill(const uint32_t skillId, LWOOBJID target, const LWOOBJID optionalOriginatorID){ +bool SkillComponent::CastSkill(const uint32_t skillId, LWOOBJID target, const LWOOBJID optionalOriginatorID) { uint32_t behaviorId = -1; // try to find it via the cache const auto& pair = m_skillBehaviorCache.find(skillId); @@ -463,7 +475,7 @@ void SkillComponent::HandleUnCast(const uint32_t behaviorId, const LWOOBJID targ delete context; } -SkillComponent::SkillComponent(Entity* parent) : Component(parent) { +SkillComponent::SkillComponent(Entity* parent): Component(parent) { this->m_skillUid = 0; } diff --git a/vanity/NPC.xml b/vanity/NPC.xml index dfe324c3..2311ab46 100644 --- a/vanity/NPC.xml +++ b/vanity/NPC.xml @@ -22,6 +22,7 @@ <phrases> <phrase>I hope quickbulds are still working!</phrase> <phrase>Be careful crossing the gap!</phrase> + <phrase>Have The Maelstrom stopped going invisible?</phrase> </phrases> <zone id="1800"> <locations> From 33f9e9c8cb687cb5a278c1f29d2572fe908689a0 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 8 Apr 2023 13:45:45 -0700 Subject: [PATCH 288/322] Allow case insensitive commands (#1047) --- dCommon/GeneralUtils.cpp | 2 +- dCommon/GeneralUtils.h | 2 +- dGame/dUtilities/SlashCommandHandler.cpp | 48 +++++++----------------- 3 files changed, 16 insertions(+), 36 deletions(-) diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index df641a1b..99ca687a 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -241,7 +241,7 @@ std::vector<std::wstring> GeneralUtils::SplitString(std::wstring& str, wchar_t d return vector; } -std::vector<std::u16string> GeneralUtils::SplitString(std::u16string& str, char16_t delimiter) { +std::vector<std::u16string> GeneralUtils::SplitString(const std::u16string& str, char16_t delimiter) { std::vector<std::u16string> vector = std::vector<std::u16string>(); std::u16string current; diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index 25aac783..0555a45e 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -139,7 +139,7 @@ namespace GeneralUtils { std::vector<std::wstring> SplitString(std::wstring& str, wchar_t delimiter); - std::vector<std::u16string> SplitString(std::u16string& str, char16_t delimiter); + std::vector<std::u16string> SplitString(const std::u16string& str, char16_t delimiter); std::vector<std::string> SplitString(const std::string& str, char delimiter); diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 6f346d88..8693abe9 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -82,44 +82,24 @@ #include "CDZoneTableTable.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { + auto commandCopy = command; + // Sanity check that a command was given + if (command.empty() || command.front() != u'/') return; + commandCopy.erase(commandCopy.begin()); + + // Split the command by spaces std::string chatCommand; std::vector<std::string> args; + auto wideCommand = GeneralUtils::SplitString(commandCopy, u' '); + if (wideCommand.empty()) return; - uint32_t breakIndex = 0; - for (uint32_t i = 1; i < command.size(); ++i) { - if (command[i] == L' ') { - breakIndex = i; - break; - } + // Convert the command to lowercase + chatCommand = GeneralUtils::UTF16ToWTF8(wideCommand.front()); + std::transform(chatCommand.begin(), chatCommand.end(), chatCommand.begin(), ::tolower); + wideCommand.erase(wideCommand.begin()); - chatCommand.push_back(static_cast<unsigned char>(command[i])); - breakIndex++; - } - - uint32_t index = ++breakIndex; - while (true) { - std::string arg; - - while (index < command.size()) { - if (command[index] == L' ') { - args.push_back(arg); - arg = ""; - index++; - continue; - } - - arg.push_back(static_cast<char>(command[index])); - index++; - } - - if (arg != "") { - args.push_back(arg); - } - - break; - } - - //Game::logger->Log("SlashCommandHandler", "Received chat command \"%s\"", GeneralUtils::UTF16ToWTF8(command).c_str()); + // Convert the arguements to not u16strings + for (auto wideArg : wideCommand) args.push_back(GeneralUtils::UTF16ToWTF8(wideArg)); User* user = UserManager::Instance()->GetUser(sysAddr); if ((chatCommand == "setgmlevel" || chatCommand == "makegm" || chatCommand == "gmlevel") && user->GetMaxGMLevel() > eGameMasterLevel::CIVILIAN) { From 37fe935a3a54c52ed45b6661e512cf81cd5c9806 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Sat, 8 Apr 2023 22:07:25 -0500 Subject: [PATCH 289/322] Implements all the old pickup scripts Testsed to make sure they work Tested to make sure existing script works still killing it immedialtely is live accurate, the timer was not accurate --- dScripts/CppScripts.cpp | 46 +++++++++++++++++-- dScripts/ai/SPEC/CMakeLists.txt | 5 +- dScripts/ai/SPEC/Special10BronzeCoinSpawner.h | 13 ++++++ dScripts/ai/SPEC/Special10GoldCoinSpawner.h | 13 ++++++ dScripts/ai/SPEC/Special10SilverCoinSpawner.h | 13 ++++++ dScripts/ai/SPEC/Special1BronzeCoinSpawner.h | 15 ++++++ dScripts/ai/SPEC/Special1GoldCoinSpawner.h | 13 ++++++ dScripts/ai/SPEC/Special1SilverCoinSpawner.h | 13 ++++++ dScripts/ai/SPEC/Special25BronzeCoinSpawner.h | 13 ++++++ dScripts/ai/SPEC/Special25GoldCoinSpawner.h | 13 ++++++ dScripts/ai/SPEC/Special25SilverCoinSpawner.h | 13 ++++++ dScripts/ai/SPEC/SpecialArmorPowerupSpawner.h | 14 ++++++ dScripts/ai/SPEC/SpecialCoinSpawner.cpp | 16 +++++++ dScripts/ai/SPEC/SpecialCoinSpawner.h | 13 ++++++ .../ai/SPEC/SpecialImaginePowerupSpawner.h | 16 ++++--- .../ai/SPEC/SpecialImaginePowerupSpawner2pt.h | 13 ++++++ dScripts/ai/SPEC/SpecialLifePowerupSpawner.h | 13 ++++++ ...pSpawner.cpp => SpecialPowerupSpawner.cpp} | 34 +++----------- dScripts/ai/SPEC/SpecialPowerupSpawner.h | 13 ++++++ 19 files changed, 263 insertions(+), 39 deletions(-) create mode 100644 dScripts/ai/SPEC/Special10BronzeCoinSpawner.h create mode 100644 dScripts/ai/SPEC/Special10GoldCoinSpawner.h create mode 100644 dScripts/ai/SPEC/Special10SilverCoinSpawner.h create mode 100644 dScripts/ai/SPEC/Special1BronzeCoinSpawner.h create mode 100644 dScripts/ai/SPEC/Special1GoldCoinSpawner.h create mode 100644 dScripts/ai/SPEC/Special1SilverCoinSpawner.h create mode 100644 dScripts/ai/SPEC/Special25BronzeCoinSpawner.h create mode 100644 dScripts/ai/SPEC/Special25GoldCoinSpawner.h create mode 100644 dScripts/ai/SPEC/Special25SilverCoinSpawner.h create mode 100644 dScripts/ai/SPEC/SpecialArmorPowerupSpawner.h create mode 100644 dScripts/ai/SPEC/SpecialCoinSpawner.cpp create mode 100644 dScripts/ai/SPEC/SpecialCoinSpawner.h create mode 100644 dScripts/ai/SPEC/SpecialImaginePowerupSpawner2pt.h create mode 100644 dScripts/ai/SPEC/SpecialLifePowerupSpawner.h rename dScripts/ai/SPEC/{SpecialImaginePowerupSpawner.cpp => SpecialPowerupSpawner.cpp} (53%) create mode 100644 dScripts/ai/SPEC/SpecialPowerupSpawner.h diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 24b30dee..6b57b0f9 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -160,7 +160,6 @@ #include "AgSalutingNpcs.h" #include "BossSpiderQueenEnemyServer.h" #include "RockHydrantSmashable.h" -#include "SpecialImaginePowerupSpawner.h" // Misc Scripts #include "ExplodingAsset.h" @@ -295,6 +294,21 @@ // WBL scripts #include "WblGenericZone.h" +// pickups +#include "Special1BronzeCoinSpawner.h" +#include "Special1SilverCoinSpawner.h" +#include "Special10BronzeCoinSpawner.h" +#include "Special25BronzeCoinSpawner.h" +#include "Special10SilverCoinSpawner.h" +#include "Special25SilverCoinSpawner.h" +#include "Special1GoldCoinSpawner.h" +#include "Special10GoldCoinSpawner.h" +#include "Special25GoldCoinSpawner.h" +#include "SpecialImaginePowerupSpawner.h" +#include "SpecialImaginePowerupSpawner2pt.h" +#include "SpecialLifePowerupSpawner.h" +#include "SpecialArmorPowerupSpawner.h" + //Big bad global bc this is a namespace and not a class: InvalidScript* invalidToReturn = new InvalidScript(); std::map<std::string, CppScripts::Script*> m_Scripts; @@ -371,8 +385,6 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new RemoveRentalGear(); else if (scriptName == "scripts\\02_server\\Map\\AG\\L_NPC_NJ_ASSISTANT_SERVER.lua") script = new NpcNjAssistantServer(); - else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_IMAGINE-POWERUP-SPAWNER.lua") - script = new SpecialImaginePowerupSpawner(); else if (scriptName == "scripts\\ai\\AG\\L_AG_SALUTING_NPCS.lua") script = new AgSalutingNpcs(); else if (scriptName == "scripts\\ai\\AG\\L_AG_JET_EFFECT_SERVER.lua") @@ -860,6 +872,34 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\zone\\LUPs\\WBL_generic_zone.lua") script = new WblGenericZone(); + // pickups + if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_1_BRONZE-COIN-SPAWNER.lua") + script = new Special1BronzeCoinSpawner(); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_1_SILVER-COIN-SPAWNER.lua") + script = new Special1SilverCoinSpawner(); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_10_BRONZE-COIN-SPAWNER.lua") + script = new Special10BronzeCoinSpawner(); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_25_BRONZE-COIN-SPAWNER.lua") + script = new Special25BronzeCoinSpawner(); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_10_SILVER-COIN-SPAWNER.lua") + script = new Special10SilverCoinSpawner(); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_25_SILVER-COIN-SPAWNER.lua") + script = new Special25SilverCoinSpawner(); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_1_GOLD-COIN-SPAWNER.lua") + script = new Special1GoldCoinSpawner(); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_10_GOLD-COIN-SPAWNER.lua") + script = new Special10GoldCoinSpawner(); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_25_GOLD-COIN-SPAWNER.lua") + script = new Special25GoldCoinSpawner(); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_IMAGINE-POWERUP-SPAWNER.lua") + script = new SpecialImaginePowerupSpawner(); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_IMAGINE-POWERUP-SPAWNER-2PT.lua") + script = new SpecialImaginePowerupSpawner2pt(); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_LIFE-POWERUP-SPAWNER.lua") + script = new SpecialLifePowerupSpawner(); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_ARMOR-POWERUP-SPAWNER.lua") + script = new SpecialArmorPowerupSpawner(); + // handle invalid script reporting if the path is greater than zero and it's not an ignored script // information not really needed for sys admins but is for developers else if (script == invalidToReturn) { diff --git a/dScripts/ai/SPEC/CMakeLists.txt b/dScripts/ai/SPEC/CMakeLists.txt index c4c5b809..d7496e9f 100644 --- a/dScripts/ai/SPEC/CMakeLists.txt +++ b/dScripts/ai/SPEC/CMakeLists.txt @@ -1,3 +1,4 @@ -set(DSCRIPTS_SOURCES_AI_SPEC - "SpecialImaginePowerupSpawner.cpp" +set(DSCRIPTS_SOURCES_AI_SPEC + "SpecialCoinSpawner.cpp" + "SpecialPowerupSpawner.cpp" PARENT_SCOPE) diff --git a/dScripts/ai/SPEC/Special10BronzeCoinSpawner.h b/dScripts/ai/SPEC/Special10BronzeCoinSpawner.h new file mode 100644 index 00000000..bbc4ecbe --- /dev/null +++ b/dScripts/ai/SPEC/Special10BronzeCoinSpawner.h @@ -0,0 +1,13 @@ +#ifndef __SPECIAL10BRONZECOINSPAWNER__H__ +#define __SPECIAL10BRONZECOINSPAWNER__H__ + +#include "SpecialCoinSpawner.h" + +class Special10BronzeCoinSpawner : public SpecialCoinSpawner { +public: + Special10BronzeCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; +private: + static const uint32_t m_currencyDenomination = 10; +}; + +#endif //!__SPECIAL10BRONZECOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special10GoldCoinSpawner.h b/dScripts/ai/SPEC/Special10GoldCoinSpawner.h new file mode 100644 index 00000000..0f45832b --- /dev/null +++ b/dScripts/ai/SPEC/Special10GoldCoinSpawner.h @@ -0,0 +1,13 @@ +#ifndef __SPECIAL10GOLDCOINSPAWNER__H__ +#define __SPECIAL10GOLDCOINSPAWNER__H__ + +#include "SpecialCoinSpawner.h" + +class Special10GoldCoinSpawner : public SpecialCoinSpawner { +public: + Special10GoldCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; +private: + static const uint32_t m_currencyDenomination = 100000; +}; + +#endif //!__SPECIAL10GOLDCOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special10SilverCoinSpawner.h b/dScripts/ai/SPEC/Special10SilverCoinSpawner.h new file mode 100644 index 00000000..55aa8c2b --- /dev/null +++ b/dScripts/ai/SPEC/Special10SilverCoinSpawner.h @@ -0,0 +1,13 @@ +#ifndef __SPECIAL10SILVERCOINSPAWNER__H__ +#define __SPECIAL10SILVERCOINSPAWNER__H__ + +#include "SpecialCoinSpawner.h" + +class Special10SilverCoinSpawner : public SpecialCoinSpawner { +public: + Special10SilverCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; +private: + static const uint32_t m_currencyDenomination = 1000; +}; + +#endif //!__SPECIAL10SILVERCOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special1BronzeCoinSpawner.h b/dScripts/ai/SPEC/Special1BronzeCoinSpawner.h new file mode 100644 index 00000000..1577b95c --- /dev/null +++ b/dScripts/ai/SPEC/Special1BronzeCoinSpawner.h @@ -0,0 +1,15 @@ +#ifndef __SPECIAL1BRONZECOINSPAWNER__H__ +#define __SPECIAL1BRONZECOINSPAWNER__H__ + +#include "SpecialCoinSpawner.h" + +class Special1BronzeCoinSpawner : public SpecialCoinSpawner { +public: + Special1BronzeCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; +private: + static const uint32_t m_currencyDenomination = 1; +}; + +#endif //!__SPECIAL1BRONZECOINSPAWNER__H__ + + diff --git a/dScripts/ai/SPEC/Special1GoldCoinSpawner.h b/dScripts/ai/SPEC/Special1GoldCoinSpawner.h new file mode 100644 index 00000000..a1fd2737 --- /dev/null +++ b/dScripts/ai/SPEC/Special1GoldCoinSpawner.h @@ -0,0 +1,13 @@ +#ifndef __SPECIAL1GOLDCOINSPAWNER__H__ +#define __SPECIAL1GOLDCOINSPAWNER__H__ + +#include "SpecialCoinSpawner.h" + +class Special1GoldCoinSpawner : public SpecialCoinSpawner { +public: + Special1GoldCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; +private: + static const uint32_t m_currencyDenomination = 10000; +}; + +#endif //!__SPECIAL1GOLDCOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special1SilverCoinSpawner.h b/dScripts/ai/SPEC/Special1SilverCoinSpawner.h new file mode 100644 index 00000000..558f9a63 --- /dev/null +++ b/dScripts/ai/SPEC/Special1SilverCoinSpawner.h @@ -0,0 +1,13 @@ +#ifndef __SPECIAL1SILVERCOINSPAWNER__H__ +#define __SPECIAL1SILVERCOINSPAWNER__H__ + +#include "SpecialCoinSpawner.h" + +class Special1SilverCoinSpawner : public SpecialCoinSpawner { +public: + Special1SilverCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; +private: + static const uint32_t m_currencyDenomination = 100; +}; + +#endif //!__SPECIAL1SILVERCOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special25BronzeCoinSpawner.h b/dScripts/ai/SPEC/Special25BronzeCoinSpawner.h new file mode 100644 index 00000000..6be32fb1 --- /dev/null +++ b/dScripts/ai/SPEC/Special25BronzeCoinSpawner.h @@ -0,0 +1,13 @@ +#ifndef __SPECIAL25BRONZECOINSPAWNER__H__ +#define __SPECIAL25BRONZECOINSPAWNER__H__ + +#include "SpecialCoinSpawner.h" + +class Special25BronzeCoinSpawner : public SpecialCoinSpawner { +public: + Special25BronzeCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; +private: + static const uint32_t m_currencyDenomination = 25; +}; + +#endif //!__SPECIAL25BRONZECOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special25GoldCoinSpawner.h b/dScripts/ai/SPEC/Special25GoldCoinSpawner.h new file mode 100644 index 00000000..30eb8688 --- /dev/null +++ b/dScripts/ai/SPEC/Special25GoldCoinSpawner.h @@ -0,0 +1,13 @@ +#ifndef __SPECIAL25GOLDCOINSPAWNER__H__ +#define __SPECIAL25GOLDCOINSPAWNER__H__ + +#include "SpecialCoinSpawner.h" + +class Special25GoldCoinSpawner : public SpecialCoinSpawner { +public: + Special25GoldCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; +private: + static const uint32_t m_currencyDenomination = 250000; +}; + +#endif //!__SPECIAL25GOLDCOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special25SilverCoinSpawner.h b/dScripts/ai/SPEC/Special25SilverCoinSpawner.h new file mode 100644 index 00000000..c07ae2d6 --- /dev/null +++ b/dScripts/ai/SPEC/Special25SilverCoinSpawner.h @@ -0,0 +1,13 @@ +#ifndef __SPECIAL25SILVERCOINSPAWNER__H__ +#define __SPECIAL25SILVERCOINSPAWNER__H__ + +#include "SpecialCoinSpawner.h" + +class Special25SilverCoinSpawner : public SpecialCoinSpawner { +public: + Special25SilverCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; +private: + static const uint32_t m_currencyDenomination = 2500; +}; + +#endif //!__SPECIAL25SILVERCOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/SpecialArmorPowerupSpawner.h b/dScripts/ai/SPEC/SpecialArmorPowerupSpawner.h new file mode 100644 index 00000000..d6599c7f --- /dev/null +++ b/dScripts/ai/SPEC/SpecialArmorPowerupSpawner.h @@ -0,0 +1,14 @@ +#ifndef __SPECIALARMORPOWERUPSPAWNER__H__ +#define __SPECIALARMORPOWERUPSPAWNER__H__ + +#include "SpecialPowerupSpawner.h" + +class SpecialArmorPowerupSpawner : public SpecialPowerupSpawner { +public: + SpecialArmorPowerupSpawner() : SpecialPowerupSpawner(m_SkillId) {}; +private: + uint32_t m_SkillId = 80; +}; + + +#endif //!__SPECIALARMORPOWERUPSPAWNER__H__ diff --git a/dScripts/ai/SPEC/SpecialCoinSpawner.cpp b/dScripts/ai/SPEC/SpecialCoinSpawner.cpp new file mode 100644 index 00000000..447230de --- /dev/null +++ b/dScripts/ai/SPEC/SpecialCoinSpawner.cpp @@ -0,0 +1,16 @@ +#include "SpecialCoinSpawner.h" +#include "CharacterComponent.h" + +void SpecialCoinSpawner::OnStartup(Entity* self) { + self->SetProximityRadius(1.5f, "powerupEnter"); +} + +void SpecialCoinSpawner::OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) { + if (name != "powerupEnter" && status != "ENTER") return; + if (!entering->IsPlayer()) return; + auto character = entering->GetCharacter(); + if (!character) return; + GameMessages::SendPlayFXEffect(self, -1, u"pickup", "", LWOOBJID_EMPTY, 1, 1, true); + character->SetCoins(character->GetCoins() + this->m_currencyDenomination, eLootSourceType::LOOT_SOURCE_CURRENCY); + self->Smash(entering->GetObjectID(), eKillType::SILENT); +} diff --git a/dScripts/ai/SPEC/SpecialCoinSpawner.h b/dScripts/ai/SPEC/SpecialCoinSpawner.h new file mode 100644 index 00000000..6d73f6f0 --- /dev/null +++ b/dScripts/ai/SPEC/SpecialCoinSpawner.h @@ -0,0 +1,13 @@ +#pragma once +#include "CppScripts.h" + +class SpecialCoinSpawner : public CppScripts::Script { +public: + SpecialCoinSpawner(uint32_t CurrencyDenomination) { + m_currencyDenomination = CurrencyDenomination; + }; + void OnStartup(Entity* self) override; + void OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) override; +private: + int32_t m_currencyDenomination = 0; +}; diff --git a/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.h b/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.h index eb628951..ec13e253 100644 --- a/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.h +++ b/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.h @@ -1,9 +1,13 @@ -#pragma once -#include "CppScripts.h" +#ifndef __SPECIALIMAGINEPOWERUPSPAWNER__H__ +#define __SPECIALIMAGINEPOWERUPSPAWNER__H__ -class SpecialImaginePowerupSpawner final : public CppScripts::Script -{ +#include "SpecialPowerupSpawner.h" + +class SpecialImaginePowerupSpawner : public SpecialPowerupSpawner { public: - void OnStartup(Entity* self) override; - void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + SpecialImaginePowerupSpawner() : SpecialPowerupSpawner(m_SkillId) {}; +private: + uint32_t m_SkillId = 13; }; + +#endif //!__SPECIALIMAGINEPOWERUPSPAWNER__H__ diff --git a/dScripts/ai/SPEC/SpecialImaginePowerupSpawner2pt.h b/dScripts/ai/SPEC/SpecialImaginePowerupSpawner2pt.h new file mode 100644 index 00000000..d7e4428c --- /dev/null +++ b/dScripts/ai/SPEC/SpecialImaginePowerupSpawner2pt.h @@ -0,0 +1,13 @@ +#ifndef __SPECIALIMAGINEPOWERUPSPAWNER2PT__H__ +#define __SPECIALIMAGINEPOWERUPSPAWNER2PT__H__ + +#include "SpecialPowerupSpawner.h" + +class SpecialImaginePowerupSpawner2pt : public SpecialPowerupSpawner { +public: + SpecialImaginePowerupSpawner2pt() : SpecialPowerupSpawner(m_SkillId) {}; +private: + uint32_t m_SkillId = 129; +}; + +#endif //!__SPECIALIMAGINEPOWERUPSPAWNER2PT__H__ diff --git a/dScripts/ai/SPEC/SpecialLifePowerupSpawner.h b/dScripts/ai/SPEC/SpecialLifePowerupSpawner.h new file mode 100644 index 00000000..2b5ce687 --- /dev/null +++ b/dScripts/ai/SPEC/SpecialLifePowerupSpawner.h @@ -0,0 +1,13 @@ +#ifndef __SPECIALLIFEPOWERUPSPAWNER__H__ +#define __SPECIALLIFEPOWERUPSPAWNER__H__ + +#include "SpecialPowerupSpawner.h" + +class SpecialLifePowerupSpawner : public SpecialPowerupSpawner { +public: + SpecialLifePowerupSpawner() : SpecialPowerupSpawner(m_SkillId) {}; +private: + uint32_t m_SkillId = 5; +}; + +#endif //!__SPECIALLIFEPOWERUPSPAWNER__H__ diff --git a/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.cpp b/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp similarity index 53% rename from dScripts/ai/SPEC/SpecialImaginePowerupSpawner.cpp rename to dScripts/ai/SPEC/SpecialPowerupSpawner.cpp index 43ae9e89..43834943 100644 --- a/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.cpp +++ b/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp @@ -2,7 +2,6 @@ #include "GameMessages.h" #include "SkillComponent.h" -#include "DestroyableComponent.h" #include "EntityManager.h" #include "eReplicaComponentType.h" @@ -12,37 +11,16 @@ void SpecialImaginePowerupSpawner::OnStartup(Entity* self) { } void SpecialImaginePowerupSpawner::OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) { - if (name != "powerupEnter" && status != "ENTER") { - return; - } - - if (entering->GetLOT() != 1) { - return; - } - - if (self->GetVar<bool>(u"bIsDead")) { - return; - } + if (name != "powerupEnter" && status != "ENTER") return; + if (!entering->IsPlayer()) return; + if (self->GetVar<bool>(u"bIsDead")) return; GameMessages::SendPlayFXEffect(self, -1, u"pickup", "", LWOOBJID_EMPTY, 1, 1, true); SkillComponent* skillComponent; - if (!self->TryGetComponent(eReplicaComponentType::SKILL, skillComponent)) { - return; - } - - const auto source = entering->GetObjectID(); - - skillComponent->CalculateBehavior(13, 20, source); - - DestroyableComponent* destroyableComponent; - if (!self->TryGetComponent(eReplicaComponentType::DESTROYABLE, destroyableComponent)) { - return; - } + if (!self->TryGetComponent(eReplicaComponentType::SKILL, skillComponent)) return; + skillComponent->CastSkill(13, entering->GetObjectID()); self->SetVar(u"bIsDead", true); - - self->AddCallbackTimer(1.0f, [self]() { - EntityManager::Instance()->ScheduleForKill(self); - }); + self->Smash(entering->GetObjectID(), eKillType::SILENT); } diff --git a/dScripts/ai/SPEC/SpecialPowerupSpawner.h b/dScripts/ai/SPEC/SpecialPowerupSpawner.h new file mode 100644 index 00000000..b27e9789 --- /dev/null +++ b/dScripts/ai/SPEC/SpecialPowerupSpawner.h @@ -0,0 +1,13 @@ +#pragma once +#include "CppScripts.h" + +class SpecialPowerupSpawner : public CppScripts::Script { +public: + SpecialPowerupSpawner(uint32_t skillId) { + m_SkillId = skillId; + }; + void OnStartup(Entity* self) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; +private: + uint32_t m_SkillId = 0; +}; From 9e4de544a64cf4c0b8d340d14b306f3adb6398bd Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Sun, 9 Apr 2023 01:10:23 -0500 Subject: [PATCH 290/322] fix --- dScripts/ai/SPEC/SpecialPowerupSpawner.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp b/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp index 43834943..a3797af7 100644 --- a/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp +++ b/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp @@ -1,16 +1,16 @@ -#include "SpecialImaginePowerupSpawner.h" +#include "SpecialPowerupSpawner.h" #include "GameMessages.h" #include "SkillComponent.h" #include "EntityManager.h" #include "eReplicaComponentType.h" -void SpecialImaginePowerupSpawner::OnStartup(Entity* self) { +void SpecialPowerupSpawner::OnStartup(Entity* self) { self->SetProximityRadius(1.5f, "powerupEnter"); self->SetVar(u"bIsDead", false); } -void SpecialImaginePowerupSpawner::OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) { +void SpecialPowerupSpawner::OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) { if (name != "powerupEnter" && status != "ENTER") return; if (!entering->IsPlayer()) return; if (self->GetVar<bool>(u"bIsDead")) return; From 5cdff8bcaf916b9345148cdf0f6c309dbb09cca4 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Sun, 9 Apr 2023 08:54:14 -0500 Subject: [PATCH 291/322] Simplify tested that things still work as intended --- dScripts/CppScripts.cpp | 51 ++++++++----------- dScripts/ai/SPEC/Special10BronzeCoinSpawner.h | 13 ----- dScripts/ai/SPEC/Special10GoldCoinSpawner.h | 13 ----- dScripts/ai/SPEC/Special10SilverCoinSpawner.h | 13 ----- dScripts/ai/SPEC/Special1BronzeCoinSpawner.h | 15 ------ dScripts/ai/SPEC/Special1GoldCoinSpawner.h | 13 ----- dScripts/ai/SPEC/Special1SilverCoinSpawner.h | 13 ----- dScripts/ai/SPEC/Special25BronzeCoinSpawner.h | 13 ----- dScripts/ai/SPEC/Special25GoldCoinSpawner.h | 13 ----- dScripts/ai/SPEC/Special25SilverCoinSpawner.h | 13 ----- dScripts/ai/SPEC/SpecialArmorPowerupSpawner.h | 14 ----- dScripts/ai/SPEC/SpecialCoinSpawner.cpp | 2 +- dScripts/ai/SPEC/SpecialCoinSpawner.h | 4 +- .../ai/SPEC/SpecialImaginePowerupSpawner.h | 13 ----- .../ai/SPEC/SpecialImaginePowerupSpawner2pt.h | 13 ----- dScripts/ai/SPEC/SpecialLifePowerupSpawner.h | 13 ----- 16 files changed, 23 insertions(+), 206 deletions(-) delete mode 100644 dScripts/ai/SPEC/Special10BronzeCoinSpawner.h delete mode 100644 dScripts/ai/SPEC/Special10GoldCoinSpawner.h delete mode 100644 dScripts/ai/SPEC/Special10SilverCoinSpawner.h delete mode 100644 dScripts/ai/SPEC/Special1BronzeCoinSpawner.h delete mode 100644 dScripts/ai/SPEC/Special1GoldCoinSpawner.h delete mode 100644 dScripts/ai/SPEC/Special1SilverCoinSpawner.h delete mode 100644 dScripts/ai/SPEC/Special25BronzeCoinSpawner.h delete mode 100644 dScripts/ai/SPEC/Special25GoldCoinSpawner.h delete mode 100644 dScripts/ai/SPEC/Special25SilverCoinSpawner.h delete mode 100644 dScripts/ai/SPEC/SpecialArmorPowerupSpawner.h delete mode 100644 dScripts/ai/SPEC/SpecialImaginePowerupSpawner.h delete mode 100644 dScripts/ai/SPEC/SpecialImaginePowerupSpawner2pt.h delete mode 100644 dScripts/ai/SPEC/SpecialLifePowerupSpawner.h diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 6b57b0f9..f7faa9aa 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -295,19 +295,8 @@ #include "WblGenericZone.h" // pickups -#include "Special1BronzeCoinSpawner.h" -#include "Special1SilverCoinSpawner.h" -#include "Special10BronzeCoinSpawner.h" -#include "Special25BronzeCoinSpawner.h" -#include "Special10SilverCoinSpawner.h" -#include "Special25SilverCoinSpawner.h" -#include "Special1GoldCoinSpawner.h" -#include "Special10GoldCoinSpawner.h" -#include "Special25GoldCoinSpawner.h" -#include "SpecialImaginePowerupSpawner.h" -#include "SpecialImaginePowerupSpawner2pt.h" -#include "SpecialLifePowerupSpawner.h" -#include "SpecialArmorPowerupSpawner.h" +#include "SpecialCoinSpawner.h" +#include "SpecialPowerupSpawner.h" //Big bad global bc this is a namespace and not a class: InvalidScript* invalidToReturn = new InvalidScript(); @@ -874,31 +863,31 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr // pickups if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_1_BRONZE-COIN-SPAWNER.lua") - script = new Special1BronzeCoinSpawner(); - else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_1_SILVER-COIN-SPAWNER.lua") - script = new Special1SilverCoinSpawner(); - else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_10_BRONZE-COIN-SPAWNER.lua") - script = new Special10BronzeCoinSpawner(); - else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_25_BRONZE-COIN-SPAWNER.lua") - script = new Special25BronzeCoinSpawner(); - else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_10_SILVER-COIN-SPAWNER.lua") - script = new Special10SilverCoinSpawner(); - else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_25_SILVER-COIN-SPAWNER.lua") - script = new Special25SilverCoinSpawner(); + script = new SpecialCoinSpawner(1); else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_1_GOLD-COIN-SPAWNER.lua") - script = new Special1GoldCoinSpawner(); + script = new SpecialCoinSpawner(10000); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_1_SILVER-COIN-SPAWNER.lua") + script = new SpecialCoinSpawner(100); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_10_BRONZE-COIN-SPAWNER.lua") + script = new SpecialCoinSpawner(10); else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_10_GOLD-COIN-SPAWNER.lua") - script = new Special10GoldCoinSpawner(); + script = new SpecialCoinSpawner(100000); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_10_SILVER-COIN-SPAWNER.lua") + script = new SpecialCoinSpawner(1000); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_25_BRONZE-COIN-SPAWNER.lua") + script = new SpecialCoinSpawner(25); else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_25_GOLD-COIN-SPAWNER.lua") - script = new Special25GoldCoinSpawner(); + script = new SpecialCoinSpawner(250000); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_25_SILVER-COIN-SPAWNER.lua") + script = new SpecialCoinSpawner(2500); else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_IMAGINE-POWERUP-SPAWNER.lua") - script = new SpecialImaginePowerupSpawner(); + script = new SpecialPowerupSpawner(13); else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_IMAGINE-POWERUP-SPAWNER-2PT.lua") - script = new SpecialImaginePowerupSpawner2pt(); + script = new SpecialPowerupSpawner(129); else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_LIFE-POWERUP-SPAWNER.lua") - script = new SpecialLifePowerupSpawner(); + script = new SpecialPowerupSpawner(5); else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_ARMOR-POWERUP-SPAWNER.lua") - script = new SpecialArmorPowerupSpawner(); + script = new SpecialPowerupSpawner(80); // handle invalid script reporting if the path is greater than zero and it's not an ignored script // information not really needed for sys admins but is for developers diff --git a/dScripts/ai/SPEC/Special10BronzeCoinSpawner.h b/dScripts/ai/SPEC/Special10BronzeCoinSpawner.h deleted file mode 100644 index bbc4ecbe..00000000 --- a/dScripts/ai/SPEC/Special10BronzeCoinSpawner.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __SPECIAL10BRONZECOINSPAWNER__H__ -#define __SPECIAL10BRONZECOINSPAWNER__H__ - -#include "SpecialCoinSpawner.h" - -class Special10BronzeCoinSpawner : public SpecialCoinSpawner { -public: - Special10BronzeCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; -private: - static const uint32_t m_currencyDenomination = 10; -}; - -#endif //!__SPECIAL10BRONZECOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special10GoldCoinSpawner.h b/dScripts/ai/SPEC/Special10GoldCoinSpawner.h deleted file mode 100644 index 0f45832b..00000000 --- a/dScripts/ai/SPEC/Special10GoldCoinSpawner.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __SPECIAL10GOLDCOINSPAWNER__H__ -#define __SPECIAL10GOLDCOINSPAWNER__H__ - -#include "SpecialCoinSpawner.h" - -class Special10GoldCoinSpawner : public SpecialCoinSpawner { -public: - Special10GoldCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; -private: - static const uint32_t m_currencyDenomination = 100000; -}; - -#endif //!__SPECIAL10GOLDCOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special10SilverCoinSpawner.h b/dScripts/ai/SPEC/Special10SilverCoinSpawner.h deleted file mode 100644 index 55aa8c2b..00000000 --- a/dScripts/ai/SPEC/Special10SilverCoinSpawner.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __SPECIAL10SILVERCOINSPAWNER__H__ -#define __SPECIAL10SILVERCOINSPAWNER__H__ - -#include "SpecialCoinSpawner.h" - -class Special10SilverCoinSpawner : public SpecialCoinSpawner { -public: - Special10SilverCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; -private: - static const uint32_t m_currencyDenomination = 1000; -}; - -#endif //!__SPECIAL10SILVERCOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special1BronzeCoinSpawner.h b/dScripts/ai/SPEC/Special1BronzeCoinSpawner.h deleted file mode 100644 index 1577b95c..00000000 --- a/dScripts/ai/SPEC/Special1BronzeCoinSpawner.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef __SPECIAL1BRONZECOINSPAWNER__H__ -#define __SPECIAL1BRONZECOINSPAWNER__H__ - -#include "SpecialCoinSpawner.h" - -class Special1BronzeCoinSpawner : public SpecialCoinSpawner { -public: - Special1BronzeCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; -private: - static const uint32_t m_currencyDenomination = 1; -}; - -#endif //!__SPECIAL1BRONZECOINSPAWNER__H__ - - diff --git a/dScripts/ai/SPEC/Special1GoldCoinSpawner.h b/dScripts/ai/SPEC/Special1GoldCoinSpawner.h deleted file mode 100644 index a1fd2737..00000000 --- a/dScripts/ai/SPEC/Special1GoldCoinSpawner.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __SPECIAL1GOLDCOINSPAWNER__H__ -#define __SPECIAL1GOLDCOINSPAWNER__H__ - -#include "SpecialCoinSpawner.h" - -class Special1GoldCoinSpawner : public SpecialCoinSpawner { -public: - Special1GoldCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; -private: - static const uint32_t m_currencyDenomination = 10000; -}; - -#endif //!__SPECIAL1GOLDCOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special1SilverCoinSpawner.h b/dScripts/ai/SPEC/Special1SilverCoinSpawner.h deleted file mode 100644 index 558f9a63..00000000 --- a/dScripts/ai/SPEC/Special1SilverCoinSpawner.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __SPECIAL1SILVERCOINSPAWNER__H__ -#define __SPECIAL1SILVERCOINSPAWNER__H__ - -#include "SpecialCoinSpawner.h" - -class Special1SilverCoinSpawner : public SpecialCoinSpawner { -public: - Special1SilverCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; -private: - static const uint32_t m_currencyDenomination = 100; -}; - -#endif //!__SPECIAL1SILVERCOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special25BronzeCoinSpawner.h b/dScripts/ai/SPEC/Special25BronzeCoinSpawner.h deleted file mode 100644 index 6be32fb1..00000000 --- a/dScripts/ai/SPEC/Special25BronzeCoinSpawner.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __SPECIAL25BRONZECOINSPAWNER__H__ -#define __SPECIAL25BRONZECOINSPAWNER__H__ - -#include "SpecialCoinSpawner.h" - -class Special25BronzeCoinSpawner : public SpecialCoinSpawner { -public: - Special25BronzeCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; -private: - static const uint32_t m_currencyDenomination = 25; -}; - -#endif //!__SPECIAL25BRONZECOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special25GoldCoinSpawner.h b/dScripts/ai/SPEC/Special25GoldCoinSpawner.h deleted file mode 100644 index 30eb8688..00000000 --- a/dScripts/ai/SPEC/Special25GoldCoinSpawner.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __SPECIAL25GOLDCOINSPAWNER__H__ -#define __SPECIAL25GOLDCOINSPAWNER__H__ - -#include "SpecialCoinSpawner.h" - -class Special25GoldCoinSpawner : public SpecialCoinSpawner { -public: - Special25GoldCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; -private: - static const uint32_t m_currencyDenomination = 250000; -}; - -#endif //!__SPECIAL25GOLDCOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/Special25SilverCoinSpawner.h b/dScripts/ai/SPEC/Special25SilverCoinSpawner.h deleted file mode 100644 index c07ae2d6..00000000 --- a/dScripts/ai/SPEC/Special25SilverCoinSpawner.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __SPECIAL25SILVERCOINSPAWNER__H__ -#define __SPECIAL25SILVERCOINSPAWNER__H__ - -#include "SpecialCoinSpawner.h" - -class Special25SilverCoinSpawner : public SpecialCoinSpawner { -public: - Special25SilverCoinSpawner() : SpecialCoinSpawner(m_currencyDenomination) {}; -private: - static const uint32_t m_currencyDenomination = 2500; -}; - -#endif //!__SPECIAL25SILVERCOINSPAWNER__H__ diff --git a/dScripts/ai/SPEC/SpecialArmorPowerupSpawner.h b/dScripts/ai/SPEC/SpecialArmorPowerupSpawner.h deleted file mode 100644 index d6599c7f..00000000 --- a/dScripts/ai/SPEC/SpecialArmorPowerupSpawner.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef __SPECIALARMORPOWERUPSPAWNER__H__ -#define __SPECIALARMORPOWERUPSPAWNER__H__ - -#include "SpecialPowerupSpawner.h" - -class SpecialArmorPowerupSpawner : public SpecialPowerupSpawner { -public: - SpecialArmorPowerupSpawner() : SpecialPowerupSpawner(m_SkillId) {}; -private: - uint32_t m_SkillId = 80; -}; - - -#endif //!__SPECIALARMORPOWERUPSPAWNER__H__ diff --git a/dScripts/ai/SPEC/SpecialCoinSpawner.cpp b/dScripts/ai/SPEC/SpecialCoinSpawner.cpp index 447230de..aed9e817 100644 --- a/dScripts/ai/SPEC/SpecialCoinSpawner.cpp +++ b/dScripts/ai/SPEC/SpecialCoinSpawner.cpp @@ -11,6 +11,6 @@ void SpecialCoinSpawner::OnProximityUpdate(Entity* self, Entity* entering, const auto character = entering->GetCharacter(); if (!character) return; GameMessages::SendPlayFXEffect(self, -1, u"pickup", "", LWOOBJID_EMPTY, 1, 1, true); - character->SetCoins(character->GetCoins() + this->m_currencyDenomination, eLootSourceType::LOOT_SOURCE_CURRENCY); + character->SetCoins(character->GetCoins() + this->m_CurrencyDenomination, eLootSourceType::LOOT_SOURCE_CURRENCY); self->Smash(entering->GetObjectID(), eKillType::SILENT); } diff --git a/dScripts/ai/SPEC/SpecialCoinSpawner.h b/dScripts/ai/SPEC/SpecialCoinSpawner.h index 6d73f6f0..5af6f24a 100644 --- a/dScripts/ai/SPEC/SpecialCoinSpawner.h +++ b/dScripts/ai/SPEC/SpecialCoinSpawner.h @@ -4,10 +4,10 @@ class SpecialCoinSpawner : public CppScripts::Script { public: SpecialCoinSpawner(uint32_t CurrencyDenomination) { - m_currencyDenomination = CurrencyDenomination; + m_CurrencyDenomination = CurrencyDenomination; }; void OnStartup(Entity* self) override; void OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) override; private: - int32_t m_currencyDenomination = 0; + int32_t m_CurrencyDenomination = 0; }; diff --git a/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.h b/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.h deleted file mode 100644 index ec13e253..00000000 --- a/dScripts/ai/SPEC/SpecialImaginePowerupSpawner.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __SPECIALIMAGINEPOWERUPSPAWNER__H__ -#define __SPECIALIMAGINEPOWERUPSPAWNER__H__ - -#include "SpecialPowerupSpawner.h" - -class SpecialImaginePowerupSpawner : public SpecialPowerupSpawner { -public: - SpecialImaginePowerupSpawner() : SpecialPowerupSpawner(m_SkillId) {}; -private: - uint32_t m_SkillId = 13; -}; - -#endif //!__SPECIALIMAGINEPOWERUPSPAWNER__H__ diff --git a/dScripts/ai/SPEC/SpecialImaginePowerupSpawner2pt.h b/dScripts/ai/SPEC/SpecialImaginePowerupSpawner2pt.h deleted file mode 100644 index d7e4428c..00000000 --- a/dScripts/ai/SPEC/SpecialImaginePowerupSpawner2pt.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __SPECIALIMAGINEPOWERUPSPAWNER2PT__H__ -#define __SPECIALIMAGINEPOWERUPSPAWNER2PT__H__ - -#include "SpecialPowerupSpawner.h" - -class SpecialImaginePowerupSpawner2pt : public SpecialPowerupSpawner { -public: - SpecialImaginePowerupSpawner2pt() : SpecialPowerupSpawner(m_SkillId) {}; -private: - uint32_t m_SkillId = 129; -}; - -#endif //!__SPECIALIMAGINEPOWERUPSPAWNER2PT__H__ diff --git a/dScripts/ai/SPEC/SpecialLifePowerupSpawner.h b/dScripts/ai/SPEC/SpecialLifePowerupSpawner.h deleted file mode 100644 index 2b5ce687..00000000 --- a/dScripts/ai/SPEC/SpecialLifePowerupSpawner.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef __SPECIALLIFEPOWERUPSPAWNER__H__ -#define __SPECIALLIFEPOWERUPSPAWNER__H__ - -#include "SpecialPowerupSpawner.h" - -class SpecialLifePowerupSpawner : public SpecialPowerupSpawner { -public: - SpecialLifePowerupSpawner() : SpecialPowerupSpawner(m_SkillId) {}; -private: - uint32_t m_SkillId = 5; -}; - -#endif //!__SPECIALLIFEPOWERUPSPAWNER__H__ From 172b398b7bf0bb41d0aa7b847551f1c908e061a7 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Sun, 9 Apr 2023 09:38:56 -0500 Subject: [PATCH 292/322] fix consolidation add speed buff --- dScripts/CppScripts.cpp | 2 ++ dScripts/ai/SPEC/SpecialPowerupSpawner.cpp | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index f7faa9aa..5f5f4373 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -888,6 +888,8 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new SpecialPowerupSpawner(5); else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_ARMOR-POWERUP-SPAWNER.lua") script = new SpecialPowerupSpawner(80); + else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_SPEED_BUFF_SPAWNER.lua") + script = new SpecialPowerupSpawner(500); // handle invalid script reporting if the path is greater than zero and it's not an ignored script // information not really needed for sys admins but is for developers diff --git a/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp b/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp index a3797af7..5abf9219 100644 --- a/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp +++ b/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp @@ -19,7 +19,8 @@ void SpecialPowerupSpawner::OnProximityUpdate(Entity* self, Entity* entering, co SkillComponent* skillComponent; if (!self->TryGetComponent(eReplicaComponentType::SKILL, skillComponent)) return; - skillComponent->CastSkill(13, entering->GetObjectID()); + Game::logger->Log("SpecialPowerupSpawner", "casting skill %i", this->m_SkillId); + skillComponent->CastSkill(this->m_SkillId, entering->GetObjectID()); self->SetVar(u"bIsDead", true); self->Smash(entering->GetObjectID(), eKillType::SILENT); From 87e36aaf72a0c79462f5cee205fdb68ac570a27e Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Sun, 9 Apr 2023 09:40:57 -0500 Subject: [PATCH 293/322] remove log --- dScripts/ai/SPEC/SpecialPowerupSpawner.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp b/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp index 5abf9219..d2a8f648 100644 --- a/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp +++ b/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp @@ -19,7 +19,6 @@ void SpecialPowerupSpawner::OnProximityUpdate(Entity* self, Entity* entering, co SkillComponent* skillComponent; if (!self->TryGetComponent(eReplicaComponentType::SKILL, skillComponent)) return; - Game::logger->Log("SpecialPowerupSpawner", "casting skill %i", this->m_SkillId); skillComponent->CastSkill(this->m_SkillId, entering->GetObjectID()); self->SetVar(u"bIsDead", true); From 2cf92a16d2d4c6b9713f7d36b3d725c2cf2c5107 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sun, 9 Apr 2023 10:17:05 -0500 Subject: [PATCH 294/322] Add scripts for a few wild creatures (#1051) ignore frog script --- dScripts/CppScripts.cpp | 17 +++++++++++++++++ dScripts/ai/WILD/CMakeLists.txt | 6 +++++- dScripts/ai/WILD/WildAmbientCrab.cpp | 27 +++++++++++++++++++++++++++ dScripts/ai/WILD/WildAmbientCrab.h | 9 +++++++++ dScripts/ai/WILD/WildAndScared.cpp | 6 ++++++ dScripts/ai/WILD/WildAndScared.h | 7 +++++++ dScripts/ai/WILD/WildGfGlowbug.cpp | 28 ++++++++++++++++++++++++++++ dScripts/ai/WILD/WildGfGlowbug.h | 9 +++++++++ dScripts/ai/WILD/WildPants.cpp | 10 ++++++++++ dScripts/ai/WILD/WildPants.h | 9 +++++++++ 10 files changed, 127 insertions(+), 1 deletion(-) create mode 100644 dScripts/ai/WILD/WildAmbientCrab.cpp create mode 100644 dScripts/ai/WILD/WildAmbientCrab.h create mode 100644 dScripts/ai/WILD/WildAndScared.cpp create mode 100644 dScripts/ai/WILD/WildAndScared.h create mode 100644 dScripts/ai/WILD/WildGfGlowbug.cpp create mode 100644 dScripts/ai/WILD/WildGfGlowbug.h create mode 100644 dScripts/ai/WILD/WildPants.cpp create mode 100644 dScripts/ai/WILD/WildPants.h diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 24b30dee..7ed7373f 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -295,6 +295,12 @@ // WBL scripts #include "WblGenericZone.h" +// Wild Scripts +#include "WildAndScared.h" +#include "WildGfGlowbug.h" +#include "WildAmbientCrab.h" +#include "WildPants.h" + //Big bad global bc this is a namespace and not a class: InvalidScript* invalidToReturn = new InvalidScript(); std::map<std::string, CppScripts::Script*> m_Scripts; @@ -860,11 +866,22 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\zone\\LUPs\\WBL_generic_zone.lua") script = new WblGenericZone(); + // Wild + if (scriptName == "scripts\\ai\\WILD\\L_WILD_GF_RAT.lua" || scriptName == "scripts\\ai\\WILD\\L_WILD_GF_SNAIL.lua") + script = new WildAndScared(); + else if (scriptName == "scripts\\ai\\WILD\\L_WILD_GF_GLOWBUG.lua") + script = new WildGfGlowbug(); + else if (scriptName == "scripts\\ai\\WILD\\L_WILD_AMBIENT_CRAB.lua") + script = new WildAmbientCrab(); + else if (scriptName == "scripts\\ai\\WILD\\L_WILD_PANTS.lua") + script = new WildPants(); + // handle invalid script reporting if the path is greater than zero and it's not an ignored script // information not really needed for sys admins but is for developers else if (script == invalidToReturn) { if ((scriptName.length() > 0) && !((scriptName == "scripts\\02_server\\Enemy\\General\\L_SUSPEND_LUA_AI.lua") || (scriptName == "scripts\\02_server\\Enemy\\General\\L_BASE_ENEMY_SPIDERLING.lua") || + (scriptName == "scripts\\ai\\WILD\\L_WILD_GF_FROG.lua") || (scriptName == "scripts\\empty.lua") )) Game::logger->LogDebug("CppScripts", "LOT %i attempted to load CppScript for '%s', but returned InvalidScript.", parent->GetLOT(), scriptName.c_str()); } diff --git a/dScripts/ai/WILD/CMakeLists.txt b/dScripts/ai/WILD/CMakeLists.txt index 57470f72..d3e499db 100644 --- a/dScripts/ai/WILD/CMakeLists.txt +++ b/dScripts/ai/WILD/CMakeLists.txt @@ -1,4 +1,8 @@ -set(DSCRIPTS_SOURCES_AI_WILD +set(DSCRIPTS_SOURCES_AI_WILD "AllCrateChicken.cpp" "WildAmbients.cpp" + "WildAmbientCrab.cpp" + "WildAndScared.cpp" + "WildGfGlowbug.cpp" + "WildPants.cpp" PARENT_SCOPE) diff --git a/dScripts/ai/WILD/WildAmbientCrab.cpp b/dScripts/ai/WILD/WildAmbientCrab.cpp new file mode 100644 index 00000000..7b5b3d45 --- /dev/null +++ b/dScripts/ai/WILD/WildAmbientCrab.cpp @@ -0,0 +1,27 @@ +#include "WildAmbientCrab.h" +#include "GameMessages.h" + +void WildAmbientCrab::OnStartup(Entity* self){ + self->SetVar(u"flipped", true); + GameMessages::SendPlayAnimation(self, u"idle"); +} + +void WildAmbientCrab::OnUse(Entity* self, Entity* user) { + auto flipped = self->GetVar<bool>(u"flipped"); + if (flipped) { + self->AddTimer("Flipping", 0.6f); + GameMessages::SendPlayAnimation(self, u"flip-over"); + self->SetVar(u"flipped", false); + } else if (!flipped) { + self->AddTimer("Flipback", 0.8f); + GameMessages::SendPlayAnimation(self, u"flip-back"); + self->SetVar(u"flipped", true); + } +} + +void WildAmbientCrab::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "Flipping") GameMessages::SendPlayAnimation(self, u"over-idle"); + else if (timerName == "Flipback") GameMessages::SendPlayAnimation(self, u"idle"); +} + + diff --git a/dScripts/ai/WILD/WildAmbientCrab.h b/dScripts/ai/WILD/WildAmbientCrab.h new file mode 100644 index 00000000..0e1b3877 --- /dev/null +++ b/dScripts/ai/WILD/WildAmbientCrab.h @@ -0,0 +1,9 @@ +#pragma once +#include "CppScripts.h" + +class WildAmbientCrab final : public CppScripts::Script { +public: + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; + void OnUse(Entity* self, Entity* user) override; +}; diff --git a/dScripts/ai/WILD/WildAndScared.cpp b/dScripts/ai/WILD/WildAndScared.cpp new file mode 100644 index 00000000..d2e89c40 --- /dev/null +++ b/dScripts/ai/WILD/WildAndScared.cpp @@ -0,0 +1,6 @@ +#include "WildAndScared.h" +#include "GameMessages.h" + +void WildAndScared::OnUse(Entity* self, Entity* user) { + GameMessages::SendPlayAnimation(self, u"scared"); +} diff --git a/dScripts/ai/WILD/WildAndScared.h b/dScripts/ai/WILD/WildAndScared.h new file mode 100644 index 00000000..c94fb06d --- /dev/null +++ b/dScripts/ai/WILD/WildAndScared.h @@ -0,0 +1,7 @@ +#pragma once +#include "CppScripts.h" + +class WildAndScared : public CppScripts::Script { +public: + void OnUse(Entity* self, Entity* user) override; +}; diff --git a/dScripts/ai/WILD/WildGfGlowbug.cpp b/dScripts/ai/WILD/WildGfGlowbug.cpp new file mode 100644 index 00000000..d834f5b5 --- /dev/null +++ b/dScripts/ai/WILD/WildGfGlowbug.cpp @@ -0,0 +1,28 @@ +#include "WildGfGlowbug.h" +#include "GameMessages.h" + +void WildGfGlowbug::OnStartup(Entity* self){ + self->SetVar(u"switch", false); +} + +void WildGfGlowbug::OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { + if (args == "physicsReady") { + auto switchState = self->GetVar<bool>(u"switch"); + if (!switchState) { + GameMessages::SendStopFXEffect(self, true, "glowlight"); + } else if (switchState) { + GameMessages::SendPlayFXEffect(self, -1, u"light", "glowlight", LWOOBJID_EMPTY); + } + } +} + +void WildGfGlowbug::OnUse(Entity* self, Entity* user) { + auto switchState = self->GetVar<bool>(u"switch"); + if (switchState) { + GameMessages::SendStopFXEffect(self, true, "glowlight"); + self->SetVar(u"switch", false); + } else if (!switchState) { + GameMessages::SendPlayFXEffect(self, -1, u"light", "glowlight", LWOOBJID_EMPTY); + self->SetVar(u"switch", true); + } +} diff --git a/dScripts/ai/WILD/WildGfGlowbug.h b/dScripts/ai/WILD/WildGfGlowbug.h new file mode 100644 index 00000000..03242372 --- /dev/null +++ b/dScripts/ai/WILD/WildGfGlowbug.h @@ -0,0 +1,9 @@ +#pragma once +#include "CppScripts.h" + +class WildGfGlowbug : public CppScripts::Script { +public: + void OnStartup(Entity* self) override; + void OnFireEventServerSide(Entity* self, Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) override; + void OnUse(Entity* self, Entity* user) override; +}; diff --git a/dScripts/ai/WILD/WildPants.cpp b/dScripts/ai/WILD/WildPants.cpp new file mode 100644 index 00000000..7c5e1cd2 --- /dev/null +++ b/dScripts/ai/WILD/WildPants.cpp @@ -0,0 +1,10 @@ +#include "WildPants.h" +#include "GameMessages.h" + +void WildPants::OnStartup(Entity* self) { + self->SetProximityRadius(5, "scardyPants"); +} + +void WildPants::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (status == "ENTER") GameMessages::SendPlayAnimation(self, u"scared"); +} diff --git a/dScripts/ai/WILD/WildPants.h b/dScripts/ai/WILD/WildPants.h new file mode 100644 index 00000000..c6968045 --- /dev/null +++ b/dScripts/ai/WILD/WildPants.h @@ -0,0 +1,9 @@ +#pragma once +#include "CppScripts.h" + +class WildPants : public CppScripts::Script +{ +public: + void OnStartup(Entity* self) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; +}; From 09e9bb2c15bd29261c66c45bb749e8750b98232f Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Sun, 9 Apr 2023 13:21:57 -0500 Subject: [PATCH 295/322] fix scripts split speed out to use target as caster fix armor skill --- dScripts/CppScripts.cpp | 5 ++-- dScripts/ai/SPEC/CMakeLists.txt | 1 + dScripts/ai/SPEC/SpecialPowerupSpawner.cpp | 5 ++-- dScripts/ai/SPEC/SpecialSpeedBuffSpawner.cpp | 26 ++++++++++++++++++++ dScripts/ai/SPEC/SpecialSpeedBuffSpawner.h | 10 ++++++++ 5 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 dScripts/ai/SPEC/SpecialSpeedBuffSpawner.cpp create mode 100644 dScripts/ai/SPEC/SpecialSpeedBuffSpawner.h diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 9aea8ef9..b9b481f3 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -297,6 +297,7 @@ // pickups #include "SpecialCoinSpawner.h" #include "SpecialPowerupSpawner.h" +#include "SpecialSpeedBuffSpawner.h" // Wild Scripts #include "WildAndScared.h" @@ -893,9 +894,9 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_LIFE-POWERUP-SPAWNER.lua") script = new SpecialPowerupSpawner(5); else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_ARMOR-POWERUP-SPAWNER.lua") - script = new SpecialPowerupSpawner(80); + script = new SpecialPowerupSpawner(747); else if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_SPEED_BUFF_SPAWNER.lua") - script = new SpecialPowerupSpawner(500); + script = new SpecialSpeedBuffSpawner(); // Wild if (scriptName == "scripts\\ai\\WILD\\L_WILD_GF_RAT.lua" || scriptName == "scripts\\ai\\WILD\\L_WILD_GF_SNAIL.lua") diff --git a/dScripts/ai/SPEC/CMakeLists.txt b/dScripts/ai/SPEC/CMakeLists.txt index d7496e9f..42dbf8f8 100644 --- a/dScripts/ai/SPEC/CMakeLists.txt +++ b/dScripts/ai/SPEC/CMakeLists.txt @@ -1,4 +1,5 @@ set(DSCRIPTS_SOURCES_AI_SPEC "SpecialCoinSpawner.cpp" "SpecialPowerupSpawner.cpp" + "SpecialSpeedBuffSpawner.cpp" PARENT_SCOPE) diff --git a/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp b/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp index d2a8f648..ea2e1044 100644 --- a/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp +++ b/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp @@ -17,8 +17,9 @@ void SpecialPowerupSpawner::OnProximityUpdate(Entity* self, Entity* entering, co GameMessages::SendPlayFXEffect(self, -1, u"pickup", "", LWOOBJID_EMPTY, 1, 1, true); - SkillComponent* skillComponent; - if (!self->TryGetComponent(eReplicaComponentType::SKILL, skillComponent)) return; + auto skillComponent = self->GetComponent<SkillComponent>(); + if (!skillComponent) return; + Game::logger->Log("SpecialPowerupSpawner", "cast skill %i on %llu", this->m_SkillId, entering->GetObjectID()); skillComponent->CastSkill(this->m_SkillId, entering->GetObjectID()); self->SetVar(u"bIsDead", true); diff --git a/dScripts/ai/SPEC/SpecialSpeedBuffSpawner.cpp b/dScripts/ai/SPEC/SpecialSpeedBuffSpawner.cpp new file mode 100644 index 00000000..d3109806 --- /dev/null +++ b/dScripts/ai/SPEC/SpecialSpeedBuffSpawner.cpp @@ -0,0 +1,26 @@ +#include "SpecialSpeedBuffSpawner.h" + +#include "GameMessages.h" +#include "SkillComponent.h" +#include "EntityManager.h" +#include "eReplicaComponentType.h" + +void SpecialSpeedBuffSpawner::OnStartup(Entity* self) { + self->SetProximityRadius(1.5f, "powerupEnter"); + self->SetVar(u"bIsDead", false); +} + +void SpecialSpeedBuffSpawner::OnProximityUpdate(Entity* self, Entity* entering, const std::string name, const std::string status) { + if (name != "powerupEnter" && status != "ENTER") return; + if (!entering->IsPlayer()) return; + if (self->GetVar<bool>(u"bIsDead")) return; + + GameMessages::SendPlayFXEffect(self, -1, u"pickup", "", LWOOBJID_EMPTY, 1, 1, true); + + auto skillComponent = entering->GetComponent<SkillComponent>(); + if (!skillComponent) return; + skillComponent->CastSkill(this->m_SkillId, entering->GetObjectID()); + + self->SetVar(u"bIsDead", true); + self->Smash(entering->GetObjectID(), eKillType::SILENT); +} diff --git a/dScripts/ai/SPEC/SpecialSpeedBuffSpawner.h b/dScripts/ai/SPEC/SpecialSpeedBuffSpawner.h new file mode 100644 index 00000000..e1741691 --- /dev/null +++ b/dScripts/ai/SPEC/SpecialSpeedBuffSpawner.h @@ -0,0 +1,10 @@ +#pragma once +#include "CppScripts.h" + +class SpecialSpeedBuffSpawner : public CppScripts::Script { +public: + void OnStartup(Entity* self) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; +private: + uint32_t m_SkillId = 500; +}; From d2d075ef52881ef11aba0b2968ffa3501a11ac70 Mon Sep 17 00:00:00 2001 From: Aaron Kimbre <aronwk.aaron@gmail.com> Date: Sun, 9 Apr 2023 13:50:26 -0500 Subject: [PATCH 296/322] remove debug log --- dScripts/ai/SPEC/SpecialPowerupSpawner.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp b/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp index ea2e1044..72565923 100644 --- a/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp +++ b/dScripts/ai/SPEC/SpecialPowerupSpawner.cpp @@ -19,7 +19,6 @@ void SpecialPowerupSpawner::OnProximityUpdate(Entity* self, Entity* entering, co auto skillComponent = self->GetComponent<SkillComponent>(); if (!skillComponent) return; - Game::logger->Log("SpecialPowerupSpawner", "cast skill %i on %llu", this->m_SkillId, entering->GetObjectID()); skillComponent->CastSkill(this->m_SkillId, entering->GetObjectID()); self->SetVar(u"bIsDead", true); From 268155fc98d05a0ed7012b4ad6dbacbf8805a620 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 11 Apr 2023 00:42:12 -0700 Subject: [PATCH 297/322] Fix more invisible enemy issues (#1052) --- dGame/dBehaviors/AttackDelayBehavior.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/dBehaviors/AttackDelayBehavior.cpp b/dGame/dBehaviors/AttackDelayBehavior.cpp index af33aadd..3f12f662 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.cpp +++ b/dGame/dBehaviors/AttackDelayBehavior.cpp @@ -13,7 +13,7 @@ void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi }; for (auto i = 0u; i < this->m_numIntervals; ++i) { - context->RegisterSyncBehavior(handle, this, branch, m_ignoreInterrupts, this->m_delay * i); + context->RegisterSyncBehavior(handle, this, branch, this->m_delay * i, m_ignoreInterrupts); } } From ce51438bc83aff912203d3e14e17685561d2b138 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Wed, 12 Apr 2023 11:46:31 -0500 Subject: [PATCH 298/322] Implement some scripts for alpha FV (#1049) * Implement maelstrom fog for alpha FV add OnOffCollisionPhantom call to cppscripts Add physics shape for gas blocking volume * Add Ninja Sensie Script for alpha FV and migration * Fix private var casing * And ninja wild scripts they keep making me add more things * address feedback --------- Co-authored-by: Gie "Max" Vanommeslaeghe <gievanom@hotmail.com> --- dGame/Entity.cpp | 4 + dGame/dComponents/PhantomPhysicsComponent.cpp | 7 ++ dScripts/CppScripts.cpp | 20 +++++ dScripts/CppScripts.h | 7 ++ dScripts/ai/FV/ActNinjaSensei.cpp | 78 +++++++++++++++++++ dScripts/ai/FV/ActNinjaSensei.h | 10 +++ dScripts/ai/FV/CMakeLists.txt | 4 +- dScripts/ai/FV/TriggerGas.cpp | 49 ++++++++++++ dScripts/ai/FV/TriggerGas.h | 14 ++++ dScripts/ai/WILD/CMakeLists.txt | 3 + dScripts/ai/WILD/WildNinjaBricks.cpp | 13 ++++ dScripts/ai/WILD/WildNinjaBricks.h | 9 +++ dScripts/ai/WILD/WildNinjaSensei.cpp | 36 +++++++++ dScripts/ai/WILD/WildNinjaSensei.h | 9 +++ dScripts/ai/WILD/WildNinjaStudent.cpp | 14 ++++ dScripts/ai/WILD/WildNinjaStudent.h | 9 +++ migrations/cdserver/6_ninja_sensei.sql | 2 + 17 files changed, 287 insertions(+), 1 deletion(-) create mode 100644 dScripts/ai/FV/ActNinjaSensei.cpp create mode 100644 dScripts/ai/FV/ActNinjaSensei.h create mode 100644 dScripts/ai/FV/TriggerGas.cpp create mode 100644 dScripts/ai/FV/TriggerGas.h create mode 100644 dScripts/ai/WILD/WildNinjaBricks.cpp create mode 100644 dScripts/ai/WILD/WildNinjaBricks.h create mode 100644 dScripts/ai/WILD/WildNinjaSensei.cpp create mode 100644 dScripts/ai/WILD/WildNinjaSensei.h create mode 100644 dScripts/ai/WILD/WildNinjaStudent.cpp create mode 100644 dScripts/ai/WILD/WildNinjaStudent.h create mode 100644 migrations/cdserver/6_ninja_sensei.sql diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 95a550a6..bb78af29 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -1342,6 +1342,10 @@ void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) { auto* other = EntityManager::Instance()->GetEntity(otherEntity); if (!other) return; + for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { + script->OnOffCollisionPhantom(this, other); + } + TriggerEvent(eTriggerEventType::EXIT, other); SwitchComponent* switchComp = GetComponent<SwitchComponent>(); diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index ce205826..e6272aa4 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -216,6 +216,13 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : Component(par m_dpEntity->SetRotation(m_Rotation); m_dpEntity->SetPosition(m_Position); dpWorld::Instance().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::Instance().AddEntity(m_dpEntity); } else { //Game::logger->Log("PhantomPhysicsComponent", "This one is supposed to have %s", info->physicsAsset.c_str()); diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index b9b481f3..5459fd37 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -294,6 +294,10 @@ // WBL scripts #include "WblGenericZone.h" +// Alpha Scripts +#include "TriggerGas.h" +#include "ActNinjaSensei.h" + // pickups #include "SpecialCoinSpawner.h" #include "SpecialPowerupSpawner.h" @@ -304,6 +308,9 @@ #include "WildGfGlowbug.h" #include "WildAmbientCrab.h" #include "WildPants.h" +#include "WildNinjaStudent.h" +#include "WildNinjaSensei.h" +#include "WildNinjaBricks.h" //Big bad global bc this is a namespace and not a class: InvalidScript* invalidToReturn = new InvalidScript(); @@ -868,6 +875,12 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr else if (scriptName == "scripts\\zone\\LUPs\\WBL_generic_zone.lua") script = new WblGenericZone(); + // Alpha + if (scriptName == "scripts\\ai\\FV\\L_TRIGGER_GAS.lua") + script = new TriggerGas(); + else if (scriptName == "scripts\\ai\\FV\\L_ACT_NINJA_SENSEI.lua") + script = new ActNinjaSensei(); + // pickups if (scriptName == "scripts\\ai\\SPEC\\L_SPECIAL_1_BRONZE-COIN-SPAWNER.lua") script = new SpecialCoinSpawner(1); @@ -907,12 +920,19 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new WildAmbientCrab(); else if (scriptName == "scripts\\ai\\WILD\\L_WILD_PANTS.lua") script = new WildPants(); + else if (scriptName == "scripts\\ai\\WILD\\L_WILD_NINJA_BRICKS.lua") + script = new WildNinjaBricks(); + else if (scriptName == "scripts\\ai\\WILD\\L_WILD_NINJA_STUDENT.lua") + script = new WildNinjaStudent(); + else if (scriptName == "scripts\\ai\\WILD\\L_WILD_NINJA_SENSEI.lua") + script = new WildNinjaSensei(); // handle invalid script reporting if the path is greater than zero and it's not an ignored script // information not really needed for sys admins but is for developers else if (script == invalidToReturn) { if ((scriptName.length() > 0) && !((scriptName == "scripts\\02_server\\Enemy\\General\\L_SUSPEND_LUA_AI.lua") || (scriptName == "scripts\\02_server\\Enemy\\General\\L_BASE_ENEMY_SPIDERLING.lua") || + (scriptName =="scripts\\ai\\FV\\L_ACT_NINJA_STUDENT.lua") || (scriptName == "scripts\\ai\\WILD\\L_WILD_GF_FROG.lua") || (scriptName == "scripts\\empty.lua") )) Game::logger->LogDebug("CppScripts", "LOT %i attempted to load CppScript for '%s', but returned InvalidScript.", parent->GetLOT(), scriptName.c_str()); diff --git a/dScripts/CppScripts.h b/dScripts/CppScripts.h index 21ff8427..5c702a70 100644 --- a/dScripts/CppScripts.h +++ b/dScripts/CppScripts.h @@ -44,6 +44,13 @@ namespace CppScripts { */ virtual void OnCollisionPhantom(Entity* self, Entity* target) {}; + /** + * Invoked upon an entity leaving the phantom collider on self. + * + * Equivalent to 'function onOffCollisionPhantom(self, msg)' + */ + virtual void OnOffCollisionPhantom(Entity* self, Entity* target) {}; + /** * Invoked when a player accepted a mission. * diff --git a/dScripts/ai/FV/ActNinjaSensei.cpp b/dScripts/ai/FV/ActNinjaSensei.cpp new file mode 100644 index 00000000..27e42219 --- /dev/null +++ b/dScripts/ai/FV/ActNinjaSensei.cpp @@ -0,0 +1,78 @@ +#include "ActNinjaSensei.h" +#include "Entity.h" +#include "EntityManager.h" +#include "GameMessages.h" + +void ActNinjaSensei::OnStartup(Entity* self) { + auto students = EntityManager::Instance()->GetEntitiesInGroup(this->m_StudentGroup); + std::vector<Entity*> validStudents = {}; + for (auto* student : students) { + if (student && student->GetLOT() == this->m_StudentLOT) validStudents.push_back(student); + } + self->SetVar(u"students", validStudents); + self->AddTimer("crane", 5); +} + +void ActNinjaSensei::OnTimerDone(Entity* self, std::string timerName) { + auto students = self->GetVar<std::vector<Entity*>>(u"students"); + if (students.empty()) return; + + if (timerName == "crane") { + for (auto student : students) { + if (student) GameMessages::SendPlayAnimation(student, u"crane"); + } + GameMessages::SendPlayAnimation(self, u"crane"); + self->AddTimer("bow", 15.33); + } + + if (timerName == "bow") { + GameMessages::SendPlayAnimation(self, u"bow"); + for (auto student : students) { + if (student) GameMessages::SendPlayAnimation(student, u"bow"); + } + GameMessages::SendPlayAnimation(self, u"bow"); + self->AddTimer("tiger", 5); + } + + if (timerName == "tiger") { + GameMessages::SendPlayAnimation(self, u"tiger"); + for (auto student : students) { + if (student) GameMessages::SendPlayAnimation(student, u"tiger"); + } + GameMessages::SendPlayAnimation(self, u"tiger"); + self->AddTimer("bow2", 15.33); + } + + if (timerName == "bow2") { + GameMessages::SendPlayAnimation(self, u"bow"); + for (auto student : students) { + if (student) GameMessages::SendPlayAnimation(student, u"bow"); + } + GameMessages::SendPlayAnimation(self, u"bow"); + self->AddTimer("mantis", 5); + } + + if (timerName == "mantis") { + GameMessages::SendPlayAnimation(self, u"mantis"); + for (auto student : students) { + if (student) GameMessages::SendPlayAnimation(student, u"mantis"); + } + GameMessages::SendPlayAnimation(self, u"mantis"); + self->AddTimer("bow3", 15.3); + } + + if (timerName == "bow3") { + GameMessages::SendPlayAnimation(self, u"bow"); + for (auto student : students) { + if (student) GameMessages::SendPlayAnimation(student, u"bow"); + } + GameMessages::SendPlayAnimation(self, u"bow"); + self->AddTimer("repeat", 5); + } + + if (timerName == "repeat") { + self->CancelAllTimers(); + self->AddTimer("crane", 5); + } +} + diff --git a/dScripts/ai/FV/ActNinjaSensei.h b/dScripts/ai/FV/ActNinjaSensei.h new file mode 100644 index 00000000..c35ede12 --- /dev/null +++ b/dScripts/ai/FV/ActNinjaSensei.h @@ -0,0 +1,10 @@ +#pragma once +#include "CppScripts.h" + +class ActNinjaSensei : public CppScripts::Script { + void OnStartup(Entity* self) override; + void OnTimerDone(Entity* self, std::string timerName) override; +private: + std::string m_StudentGroup = "Sensei_kids"; + LOT m_StudentLOT = 2497; +}; diff --git a/dScripts/ai/FV/CMakeLists.txt b/dScripts/ai/FV/CMakeLists.txt index 2a8a3367..56418706 100644 --- a/dScripts/ai/FV/CMakeLists.txt +++ b/dScripts/ai/FV/CMakeLists.txt @@ -1,4 +1,5 @@ -set(DSCRIPTS_SOURCES_AI_FV +set(DSCRIPTS_SOURCES_AI_FV + "ActNinjaSensei.cpp" "ActNinjaTurret.cpp" "FvFlyingCreviceDragon.cpp" "FvDragonSmashingGolemQb.cpp" @@ -15,4 +16,5 @@ set(DSCRIPTS_SOURCES_AI_FV "FvPassThroughWall.cpp" "FvBounceOverWall.cpp" "FvMaelstromGeyser.cpp" + "TriggerGas.cpp" PARENT_SCOPE) diff --git a/dScripts/ai/FV/TriggerGas.cpp b/dScripts/ai/FV/TriggerGas.cpp new file mode 100644 index 00000000..7e9762e3 --- /dev/null +++ b/dScripts/ai/FV/TriggerGas.cpp @@ -0,0 +1,49 @@ +#include "TriggerGas.h" +#include "InventoryComponent.h" +#include "SkillComponent.h" +#include "Entity.h" +#include "dLogger.h" + + +void TriggerGas::OnStartup(Entity* self) { + self->AddTimer(this->m_TimerName, this->m_Time); +} + +void TriggerGas::OnCollisionPhantom(Entity* self, Entity* target) { + if (!target->IsPlayer()) return; + auto players = self->GetVar<std::vector<Entity*>>(u"players"); + players.push_back(target); + self->SetVar(u"players", players); +} + +void TriggerGas::OnOffCollisionPhantom(Entity* self, Entity* target) { + auto players = self->GetVar<std::vector<Entity*>>(u"players"); + if (!target->IsPlayer() || players.empty()) return; + auto position = std::find(players.begin(), players.end(), target); + if (position != players.end()) players.erase(position); + self->SetVar(u"players", players); +} + +void TriggerGas::OnTimerDone(Entity* self, std::string timerName) { + if (timerName != this->m_TimerName) return; + auto players = self->GetVar<std::vector<Entity*>>(u"players"); + for (auto player : players) { + if (player->GetIsDead() || !player){ + auto position = std::find(players.begin(), players.end(), player); + if (position != players.end()) players.erase(position); + continue; + } + auto inventoryComponent = player->GetComponent<InventoryComponent>(); + if (inventoryComponent) { + if (!inventoryComponent->IsEquipped(this->m_MaelstromHelmet)) { + auto* skillComponent = self->GetComponent<SkillComponent>(); + if (skillComponent) { + skillComponent->CastSkill(this->m_FogDamageSkill, player->GetObjectID()); + } + } + } + } + self->SetVar(u"players", players); + self->AddTimer(this->m_TimerName, this->m_Time); +} + diff --git a/dScripts/ai/FV/TriggerGas.h b/dScripts/ai/FV/TriggerGas.h new file mode 100644 index 00000000..284f2485 --- /dev/null +++ b/dScripts/ai/FV/TriggerGas.h @@ -0,0 +1,14 @@ +#pragma once +#include "CppScripts.h" + +class TriggerGas : public CppScripts::Script { + void OnStartup(Entity* self) override; + void OnCollisionPhantom(Entity* self, Entity* target) override; + void OnOffCollisionPhantom(Entity* self, Entity* target) override; + void OnTimerDone(Entity* self, std::string timerName) override; +private: + std::string m_TimerName = "gasTriggerDamage"; + float m_Time = 3.0f; + uint32_t m_MaelstromHelmet = 3068; + uint32_t m_FogDamageSkill = 103; +}; diff --git a/dScripts/ai/WILD/CMakeLists.txt b/dScripts/ai/WILD/CMakeLists.txt index d3e499db..446ce0d4 100644 --- a/dScripts/ai/WILD/CMakeLists.txt +++ b/dScripts/ai/WILD/CMakeLists.txt @@ -4,5 +4,8 @@ set(DSCRIPTS_SOURCES_AI_WILD "WildAmbientCrab.cpp" "WildAndScared.cpp" "WildGfGlowbug.cpp" + "WildNinjaBricks.cpp" + "WildNinjaStudent.cpp" + "WildNinjaSensei.cpp" "WildPants.cpp" PARENT_SCOPE) diff --git a/dScripts/ai/WILD/WildNinjaBricks.cpp b/dScripts/ai/WILD/WildNinjaBricks.cpp new file mode 100644 index 00000000..4fa65b01 --- /dev/null +++ b/dScripts/ai/WILD/WildNinjaBricks.cpp @@ -0,0 +1,13 @@ +#include "WildNinjaBricks.h" +#include "Entity.h" + +void WildNinjaBricks::OnStartup(Entity* self) { + self->AddToGroup("Ninjastuff"); +} + +void WildNinjaBricks::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) { + if (name == "Crane") GameMessages::SendPlayAnimation(self, u"crane"); + else if (name == "Tiger") GameMessages::SendPlayAnimation(self, u"tiger"); + else if (name == "Mantis") GameMessages::SendPlayAnimation(self, u"mantis"); +} + diff --git a/dScripts/ai/WILD/WildNinjaBricks.h b/dScripts/ai/WILD/WildNinjaBricks.h new file mode 100644 index 00000000..a1f470a3 --- /dev/null +++ b/dScripts/ai/WILD/WildNinjaBricks.h @@ -0,0 +1,9 @@ +#pragma once +#include "CppScripts.h" + +class WildNinjaBricks : public CppScripts::Script { +public: + void OnStartup(Entity* self); + void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; +}; + diff --git a/dScripts/ai/WILD/WildNinjaSensei.cpp b/dScripts/ai/WILD/WildNinjaSensei.cpp new file mode 100644 index 00000000..42ddfa21 --- /dev/null +++ b/dScripts/ai/WILD/WildNinjaSensei.cpp @@ -0,0 +1,36 @@ +#include "WildNinjaSensei.h" +#include "Entity.h" + +void WildNinjaSensei::OnStartup(Entity* self) { + GameMessages::SendPlayAnimation(self, u"bow"); + self->AddTimer("CraneStart", 5); +} + +void WildNinjaSensei::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "CraneStart") { + auto ninjas = EntityManager::Instance()->GetEntitiesInGroup("Ninjastuff"); + for (auto ninja : ninjas) ninja->NotifyObject(self, "Crane"); + self->AddTimer("Bow", 15.5f); + self->AddTimer("TigerStart", 25); + GameMessages::SendPlayAnimation(self, u"crane"); + } else if (timerName == "TigerStart") { + auto ninjas = EntityManager::Instance()->GetEntitiesInGroup("Ninjastuff"); + GameMessages::SendPlayAnimation(self, u"bow"); + for (auto ninja : ninjas) ninja->NotifyObject(self, "Tiger"); + self->AddTimer("Bow", 15.5f); + self->AddTimer("MantisStart", 25); + GameMessages::SendPlayAnimation(self, u"tiger"); + } else if (timerName == "MantisStart") { + auto ninjas = EntityManager::Instance()->GetEntitiesInGroup("Ninjastuff"); + GameMessages::SendPlayAnimation(self, u"tiger"); + for (auto ninja : ninjas) ninja->NotifyObject(self, "Mantis"); + self->AddTimer("Bow", 15.5f); + self->AddTimer("CraneStart", 25); + GameMessages::SendPlayAnimation(self, u"mantis"); + } else if (timerName == "Bow") { + auto ninjas = EntityManager::Instance()->GetEntitiesInGroup("Ninjastuff"); + for (auto ninja : ninjas) ninja->NotifyObject(self, "Bow"); + GameMessages::SendPlayAnimation(self, u"bow"); + } +} + diff --git a/dScripts/ai/WILD/WildNinjaSensei.h b/dScripts/ai/WILD/WildNinjaSensei.h new file mode 100644 index 00000000..c14b6f08 --- /dev/null +++ b/dScripts/ai/WILD/WildNinjaSensei.h @@ -0,0 +1,9 @@ +#pragma once +#include "CppScripts.h" + +class WildNinjaSensei : public CppScripts::Script { +public: + void OnStartup(Entity* self); + void OnTimerDone(Entity* self, std::string timerName); +}; + diff --git a/dScripts/ai/WILD/WildNinjaStudent.cpp b/dScripts/ai/WILD/WildNinjaStudent.cpp new file mode 100644 index 00000000..b7e2f585 --- /dev/null +++ b/dScripts/ai/WILD/WildNinjaStudent.cpp @@ -0,0 +1,14 @@ +#include "WildNinjaStudent.h" +#include "GameMessages.h" + +void WildNinjaStudent::OnStartup(Entity* self) { + self->AddToGroup("Ninjastuff"); + GameMessages::SendPlayAnimation(self, u"bow"); +} + +void WildNinjaStudent::OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1, int32_t param2) { + if (name == "Crane") GameMessages::SendPlayAnimation(self, u"crane"); + else if (name == "Tiger") GameMessages::SendPlayAnimation(self, u"tiger"); + else if (name == "Mantis") GameMessages::SendPlayAnimation(self, u"mantis"); + else if (name == "Bow") GameMessages::SendPlayAnimation(self, u"bow"); +} diff --git a/dScripts/ai/WILD/WildNinjaStudent.h b/dScripts/ai/WILD/WildNinjaStudent.h new file mode 100644 index 00000000..2948ee3c --- /dev/null +++ b/dScripts/ai/WILD/WildNinjaStudent.h @@ -0,0 +1,9 @@ +#pragma once +#include "CppScripts.h" + +class WildNinjaStudent : public CppScripts::Script { +public: + void OnStartup(Entity* self); + void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; +}; + diff --git a/migrations/cdserver/6_ninja_sensei.sql b/migrations/cdserver/6_ninja_sensei.sql new file mode 100644 index 00000000..f3828b07 --- /dev/null +++ b/migrations/cdserver/6_ninja_sensei.sql @@ -0,0 +1,2 @@ +INSERT INTO ScriptComponent (id, script_name, client_script_name) VALUES (228, 'scripts\ai\FV\L_ACT_NINJA_SENSEI.lua', null); +UPDATE ComponentsRegistry SET component_id = 228 WHERE id = 2489 AND component_type = 5; From 4734996c7c2e7c850e9fb11fa8c8a7f879323428 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Wed, 12 Apr 2023 09:48:20 -0700 Subject: [PATCH 299/322] Resolve most compiler warnings (#1053) --- dCommon/AMFFormat_BitStream.cpp | 9 +++++++++ dCommon/Diagnostics.cpp | 2 +- dCommon/dClient/AssetManager.cpp | 6 +++++- dCommon/dClient/Pack.cpp | 6 +++--- dGame/dComponents/RebuildComponent.cpp | 1 + dGame/dGameMessages/GameMessages.cpp | 2 +- dGame/dUtilities/Mail.cpp | 4 ++-- tests/dCommonTests/AMFDeserializeTests.cpp | 3 +-- 8 files changed, 23 insertions(+), 10 deletions(-) diff --git a/dCommon/AMFFormat_BitStream.cpp b/dCommon/AMFFormat_BitStream.cpp index b603ba31..dcb9197d 100644 --- a/dCommon/AMFFormat_BitStream.cpp +++ b/dCommon/AMFFormat_BitStream.cpp @@ -65,6 +65,15 @@ void RakNet::BitStream::Write<AMFValue*>(AMFValue* value) { this->Write((AMFArrayValue*)value); break; } + case AMFObject: + case AMFXML: + case AMFByteArray: + case AMFVectorInt: + case AMFVectorUInt: + case AMFVectorDouble: + case AMFVectorObject: + case AMFDictionary: + break; } } } diff --git a/dCommon/Diagnostics.cpp b/dCommon/Diagnostics.cpp index 3025f083..58d558de 100644 --- a/dCommon/Diagnostics.cpp +++ b/dCommon/Diagnostics.cpp @@ -111,7 +111,7 @@ static void ErrorCallback(void* data, const char* msg, int errnum) { void GenerateDump() { std::string cmd = "sudo gcore " + std::to_string(getpid()); - system(cmd.c_str()); + int ret = system(cmd.c_str()); // Saving a return just to prevent warning } void CatchUnhandled(int sig) { diff --git a/dCommon/dClient/AssetManager.cpp b/dCommon/dClient/AssetManager.cpp index ed86d719..00cedba9 100644 --- a/dCommon/dClient/AssetManager.cpp +++ b/dCommon/dClient/AssetManager.cpp @@ -47,6 +47,10 @@ AssetManager::AssetManager(const std::filesystem::path& path) { this->LoadPackIndex(); break; } + case eAssetBundleType::None: + case eAssetBundleType::Unpacked: { + break; + } } } @@ -111,7 +115,7 @@ bool AssetManager::GetFile(const char* name, char** data, uint32_t* len) { *len = ftell(file); *data = (char*)malloc(*len); fseek(file, 0, SEEK_SET); - fread(*data, sizeof(uint8_t), *len, file); + int32_t readInData = fread(*data, sizeof(uint8_t), *len, file); fclose(file); return true; diff --git a/dCommon/dClient/Pack.cpp b/dCommon/dClient/Pack.cpp index 1c1a643a..11345fc9 100644 --- a/dCommon/dClient/Pack.cpp +++ b/dCommon/dClient/Pack.cpp @@ -77,7 +77,7 @@ bool Pack::ReadFileFromPack(uint32_t crc, char** data, uint32_t* len) { if (!isCompressed) { char* tempData = (char*)malloc(pkRecord.m_UncompressedSize); - fread(tempData, sizeof(uint8_t), pkRecord.m_UncompressedSize, file); + int32_t readInData = fread(tempData, sizeof(uint8_t), pkRecord.m_UncompressedSize, file); *data = tempData; *len = pkRecord.m_UncompressedSize; @@ -97,11 +97,11 @@ bool Pack::ReadFileFromPack(uint32_t crc, char** data, uint32_t* len) { if (currentReadPos >= pkRecord.m_UncompressedSize) break; uint32_t size; - fread(&size, sizeof(uint32_t), 1, file); + int32_t readInData = fread(&size, sizeof(uint32_t), 1, file); pos += 4; // Move pointer position 4 to the right char* chunk = (char*)malloc(size); - fread(chunk, sizeof(int8_t), size, file); + int32_t readInData2 = fread(chunk, sizeof(int8_t), size, file); pos += size; // Move pointer position the amount of bytes read to the right int32_t err; diff --git a/dGame/dComponents/RebuildComponent.cpp b/dGame/dComponents/RebuildComponent.cpp index 2562b313..e3c885dd 100644 --- a/dGame/dComponents/RebuildComponent.cpp +++ b/dGame/dComponents/RebuildComponent.cpp @@ -234,6 +234,7 @@ void RebuildComponent::Update(float deltaTime) { } break; } + case REBUILD_RESETTING: break; } } diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index bf7476e9..0fc32e2e 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -2570,7 +2570,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //We runs this in async because the http library here is blocking, meaning it'll halt the thread. //But we don't want the server to go unresponsive, because then the client would disconnect. - std::async(std::launch::async, [&]() { + auto returnVal = std::async(std::launch::async, [&]() { //We need to get a new ID for our model first: ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t newID) { diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index 9490f748..5cd11ea4 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -130,7 +130,7 @@ void Mail::HandleMailStuff(RakNet::BitStream* packet, const SystemAddress& sysAd int mailStuffID = 0; packet->Read(mailStuffID); - std::async(std::launch::async, [packet, &sysAddr, entity, mailStuffID]() { + auto returnVal = std::async(std::launch::async, [packet, &sysAddr, entity, mailStuffID]() { Mail::MailMessageID stuffID = MailMessageID(mailStuffID); switch (stuffID) { case MailMessageID::AttachmentCollect: @@ -393,7 +393,7 @@ void Mail::HandleMailRead(RakNet::BitStream* packet, const SystemAddress& sysAdd } void Mail::HandleNotificationRequest(const SystemAddress& sysAddr, uint32_t objectID) { - std::async(std::launch::async, [&]() { + auto returnVal = std::async(std::launch::async, [&]() { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT id FROM mail WHERE receiver_id=? AND was_read=0"); stmt->setUInt(1, objectID); sql::ResultSet* res = stmt->executeQuery(); diff --git a/tests/dCommonTests/AMFDeserializeTests.cpp b/tests/dCommonTests/AMFDeserializeTests.cpp index 3811a706..b679ea78 100644 --- a/tests/dCommonTests/AMFDeserializeTests.cpp +++ b/tests/dCommonTests/AMFDeserializeTests.cpp @@ -173,9 +173,8 @@ TEST(dCommonTests, AMFDeserializeAMFArrayTest) { /** * @brief This test checks that if we recieve an unimplemented AMFValueType * we correctly throw an error and can actch it. - * + * Yes this leaks memory. */ -#pragma message("-- The AMFDeserializeUnimplementedValuesTest causes a known memory leak of 880 bytes since it throws errors! --") TEST(dCommonTests, AMFDeserializeUnimplementedValuesTest) { std::vector<AMFValueType> unimplementedValues = { AMFValueType::AMFXMLDoc, From fbfa778d3d89527053f00c668287c07e3f40e6f1 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 17 Apr 2023 12:19:26 -0700 Subject: [PATCH 300/322] Patch ghosting exclusions (#1059) --- dGame/Entity.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index bb78af29..683baaa2 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -727,7 +727,7 @@ void Entity::Initialize() { if (!m_Character && EntityManager::Instance()->GetGhostingEnabled()) { // Don't ghost what is likely large scene elements - if (m_Components.size() == 2 && HasComponent(eReplicaComponentType::SIMPLE_PHYSICS) && HasComponent(eReplicaComponentType::RENDER)) { + if (HasComponent(eReplicaComponentType::SIMPLE_PHYSICS) && HasComponent(eReplicaComponentType::RENDER) && (m_Components.size() == 2 || (HasComponent(eReplicaComponentType::TRIGGER) && m_Components.size() == 3))) { goto no_ghosting; } From f60ea40acc6775498becaf27d3f5026abcc84fd3 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Tue, 18 Apr 2023 01:40:20 -0500 Subject: [PATCH 301/322] Add random end of race behavior (#1056) * randominze between 0 and 7 inclusive for the different animation types * Make the end behavior deterministic unpon loading So that all players see the same animations for each other --- dGame/dComponents/VehiclePhysicsComponent.cpp | 3 ++- dGame/dComponents/VehiclePhysicsComponent.h | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/dGame/dComponents/VehiclePhysicsComponent.cpp b/dGame/dComponents/VehiclePhysicsComponent.cpp index bf6a3bb7..d981acf7 100644 --- a/dGame/dComponents/VehiclePhysicsComponent.cpp +++ b/dGame/dComponents/VehiclePhysicsComponent.cpp @@ -11,6 +11,7 @@ VehiclePhysicsComponent::VehiclePhysicsComponent(Entity* parent) : Component(par m_DirtyPosition = true; m_DirtyVelocity = true; m_DirtyAngularVelocity = true; + m_EndBehavior = GeneralUtils::GenerateRandomNumber<uint32_t>(0, 7); } VehiclePhysicsComponent::~VehiclePhysicsComponent() { @@ -93,7 +94,7 @@ void VehiclePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bI } if (bIsInitialUpdate) { - outBitStream->Write<uint8_t>(5); + outBitStream->Write<uint8_t>(m_EndBehavior); outBitStream->Write1(); } diff --git a/dGame/dComponents/VehiclePhysicsComponent.h b/dGame/dComponents/VehiclePhysicsComponent.h index 551cce42..64609edf 100644 --- a/dGame/dComponents/VehiclePhysicsComponent.h +++ b/dGame/dComponents/VehiclePhysicsComponent.h @@ -109,4 +109,5 @@ private: bool m_IsOnRail; float m_SoftUpdate = 0; + uint32_t m_EndBehavior; }; From da6ca82ae23388606993a67112a17595bffe2dcd Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 17 Apr 2023 23:40:33 -0700 Subject: [PATCH 302/322] add missing overrides (#1060) --- dScripts/ai/WILD/WildNinjaBricks.h | 2 +- dScripts/ai/WILD/WildNinjaStudent.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dScripts/ai/WILD/WildNinjaBricks.h b/dScripts/ai/WILD/WildNinjaBricks.h index a1f470a3..9578e37a 100644 --- a/dScripts/ai/WILD/WildNinjaBricks.h +++ b/dScripts/ai/WILD/WildNinjaBricks.h @@ -3,7 +3,7 @@ class WildNinjaBricks : public CppScripts::Script { public: - void OnStartup(Entity* self); + void OnStartup(Entity* self) override; void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; }; diff --git a/dScripts/ai/WILD/WildNinjaStudent.h b/dScripts/ai/WILD/WildNinjaStudent.h index 2948ee3c..b76e5fa5 100644 --- a/dScripts/ai/WILD/WildNinjaStudent.h +++ b/dScripts/ai/WILD/WildNinjaStudent.h @@ -3,7 +3,7 @@ class WildNinjaStudent : public CppScripts::Script { public: - void OnStartup(Entity* self); + void OnStartup(Entity* self) override; void OnNotifyObject(Entity* self, Entity* sender, const std::string& name, int32_t param1 = 0, int32_t param2 = 0) override; }; From 2e284eb2ce9d1f5a1f01746a8d1f50152f958238 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Tue, 18 Apr 2023 12:48:03 -0500 Subject: [PATCH 303/322] Implement Timer handlers in triggers and ontimerdone trigger event (#1031) * Works, but AOE is broken * Address Feedback * fix typo --- dGame/Entity.cpp | 1 + dGame/dComponents/SkillComponent.cpp | 2 + dGame/dComponents/TriggerComponent.cpp | 40 +++++++--- dGame/dComponents/TriggerComponent.h | 2 + dScripts/ai/AG/AgJetEffectServer.cpp | 106 ++++++------------------- 5 files changed, 58 insertions(+), 93 deletions(-) diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 683baaa2..595ab090 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -1232,6 +1232,7 @@ void Entity::Update(const float deltaTime) { for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { script->OnTimerDone(this, timerName); } + TriggerEvent(eTriggerEventType::TIMER_DONE, this); } else { timerPosition++; } diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index ae0e82f0..dc7c16bd 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -260,6 +260,8 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c context->caster = m_Parent->GetObjectID(); + context->skillID = skillId; + context->clientInitalized = clientInitalized; context->foundTarget = target != LWOOBJID_EMPTY || ignoreTarget || clientInitalized; diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp index 0f241116..3f05d805 100644 --- a/dGame/dComponents/TriggerComponent.cpp +++ b/dGame/dComponents/TriggerComponent.cpp @@ -83,8 +83,12 @@ void TriggerComponent::HandleTriggerCommand(LUTriggers::Command* command, Entity case eTriggerCommandType::REPEL_OBJECT: HandleRepelObject(targetEntity, command->args); break; - case eTriggerCommandType::SET_TIMER: break; - case eTriggerCommandType::CANCEL_TIMER: break; + case eTriggerCommandType::SET_TIMER: + HandleSetTimer(targetEntity, argArray); + break; + case eTriggerCommandType::CANCEL_TIMER: + HandleCancelTimer(targetEntity, command->args); + break; case eTriggerCommandType::PLAY_CINEMATIC: HandlePlayCinematic(targetEntity, argArray); break; @@ -194,7 +198,7 @@ void TriggerComponent::HandleDestroyObject(Entity* targetEntity, std::string arg void TriggerComponent::HandleToggleTrigger(Entity* targetEntity, std::string args){ auto* triggerComponent = targetEntity->GetComponent<TriggerComponent>(); if (!triggerComponent) { - Game::logger->Log("TriggerComponent::HandleToggleTrigger", "Trigger component not found!"); + Game::logger->LogDebug("TriggerComponent::HandleToggleTrigger", "Trigger component not found!"); return; } triggerComponent->SetTriggerEnabled(args == "1"); @@ -203,7 +207,7 @@ void TriggerComponent::HandleToggleTrigger(Entity* targetEntity, std::string arg void TriggerComponent::HandleResetRebuild(Entity* targetEntity, std::string args){ auto* rebuildComponent = targetEntity->GetComponent<RebuildComponent>(); if (!rebuildComponent) { - Game::logger->Log("TriggerComponent::HandleResetRebuild", "Rebuild component not found!"); + Game::logger->LogDebug("TriggerComponent::HandleResetRebuild", "Rebuild component not found!"); return; } rebuildComponent->ResetRebuild(args == "1"); @@ -233,7 +237,7 @@ void TriggerComponent::HandleRotateObject(Entity* targetEntity, std::vector<std: void TriggerComponent::HandlePushObject(Entity* targetEntity, std::vector<std::string> argArray){ auto* phantomPhysicsComponent = m_Parent->GetComponent<PhantomPhysicsComponent>(); if (!phantomPhysicsComponent) { - Game::logger->Log("TriggerComponent::HandlePushObject", "Phantom Physics component not found!"); + Game::logger->LogDebug("TriggerComponent::HandlePushObject", "Phantom Physics component not found!"); return; } phantomPhysicsComponent->SetPhysicsEffectActive(true); @@ -250,7 +254,7 @@ void TriggerComponent::HandlePushObject(Entity* targetEntity, std::vector<std::s void TriggerComponent::HandleRepelObject(Entity* targetEntity, std::string args){ auto* phantomPhysicsComponent = m_Parent->GetComponent<PhantomPhysicsComponent>(); if (!phantomPhysicsComponent) { - Game::logger->Log("TriggerComponent::HandleRepelObject", "Phantom Physics component not found!"); + Game::logger->LogDebug("TriggerComponent::HandleRepelObject", "Phantom Physics component not found!"); return; } float forceMultiplier; @@ -271,6 +275,20 @@ void TriggerComponent::HandleRepelObject(Entity* targetEntity, std::string args) EntityManager::Instance()->SerializeEntity(m_Parent); } +void TriggerComponent::HandleSetTimer(Entity* targetEntity, std::vector<std::string> argArray){ + if (argArray.size() != 2) { + Game::logger->LogDebug("TriggerComponent::HandleSetTimer", "Not ehought variables!"); + return; + } + float time = 0.0; + GeneralUtils::TryParse<float>(argArray.at(1), time); + m_Parent->AddTimer(argArray.at(0), time); +} + +void TriggerComponent::HandleCancelTimer(Entity* targetEntity, std::string args){ + m_Parent->CancelTimer(args); +} + void TriggerComponent::HandlePlayCinematic(Entity* targetEntity, std::vector<std::string> argArray) { float leadIn = -1.0; auto wait = eEndBehavior::RETURN; @@ -300,7 +318,7 @@ void TriggerComponent::HandlePlayCinematic(Entity* targetEntity, std::vector<std void TriggerComponent::HandleToggleBBB(Entity* targetEntity, std::string args) { auto* character = targetEntity->GetCharacter(); if (!character) { - Game::logger->Log("TriggerComponent::HandleToggleBBB", "Character was not found!"); + Game::logger->LogDebug("TriggerComponent::HandleToggleBBB", "Character was not found!"); return; } bool buildMode = !(character->GetBuildMode()); @@ -316,7 +334,7 @@ void TriggerComponent::HandleUpdateMission(Entity* targetEntity, std::vector<std if (argArray.at(0) != "exploretask") return; MissionComponent* missionComponent = targetEntity->GetComponent<MissionComponent>(); if (!missionComponent){ - Game::logger->Log("TriggerComponent::HandleUpdateMission", "Mission component not found!"); + Game::logger->LogDebug("TriggerComponent::HandleUpdateMission", "Mission component not found!"); return; } missionComponent->Progress(eMissionTaskType::EXPLORE, 0, 0, argArray.at(4)); @@ -335,7 +353,7 @@ void TriggerComponent::HandlePlayEffect(Entity* targetEntity, std::vector<std::s void TriggerComponent::HandleCastSkill(Entity* targetEntity, std::string args){ auto* skillComponent = targetEntity->GetComponent<SkillComponent>(); if (!skillComponent) { - Game::logger->Log("TriggerComponent::HandleCastSkill", "Skill component not found!"); + Game::logger->LogDebug("TriggerComponent::HandleCastSkill", "Skill component not found!"); return; } uint32_t skillId; @@ -346,7 +364,7 @@ void TriggerComponent::HandleCastSkill(Entity* targetEntity, std::string args){ void TriggerComponent::HandleSetPhysicsVolumeEffect(Entity* targetEntity, std::vector<std::string> argArray) { auto* phantomPhysicsComponent = targetEntity->GetComponent<PhantomPhysicsComponent>(); if (!phantomPhysicsComponent) { - Game::logger->Log("TriggerComponent::HandleSetPhysicsVolumeEffect", "Phantom Physics component not found!"); + Game::logger->LogDebug("TriggerComponent::HandleSetPhysicsVolumeEffect", "Phantom Physics component not found!"); return; } phantomPhysicsComponent->SetPhysicsEffectActive(true); @@ -381,7 +399,7 @@ void TriggerComponent::HandleSetPhysicsVolumeEffect(Entity* targetEntity, std::v void TriggerComponent::HandleSetPhysicsVolumeStatus(Entity* targetEntity, std::string args) { auto* phantomPhysicsComponent = targetEntity->GetComponent<PhantomPhysicsComponent>(); if (!phantomPhysicsComponent) { - Game::logger->Log("TriggerComponent::HandleSetPhysicsVolumeEffect", "Phantom Physics component not found!"); + Game::logger->LogDebug("TriggerComponent::HandleSetPhysicsVolumeEffect", "Phantom Physics component not found!"); return; } phantomPhysicsComponent->SetPhysicsEffectActive(args == "On"); diff --git a/dGame/dComponents/TriggerComponent.h b/dGame/dComponents/TriggerComponent.h index 317da00e..df65707f 100644 --- a/dGame/dComponents/TriggerComponent.h +++ b/dGame/dComponents/TriggerComponent.h @@ -30,6 +30,8 @@ private: void HandleRotateObject(Entity* targetEntity, std::vector<std::string> argArray); void HandlePushObject(Entity* targetEntity, std::vector<std::string> argArray); void HandleRepelObject(Entity* targetEntity, std::string args); + void HandleSetTimer(Entity* targetEntity, std::vector<std::string> argArray); + void HandleCancelTimer(Entity* targetEntity, std::string args); void HandlePlayCinematic(Entity* targetEntity, std::vector<std::string> argArray); void HandleToggleBBB(Entity* targetEntity, std::string args); void HandleUpdateMission(Entity* targetEntity, std::vector<std::string> argArray); diff --git a/dScripts/ai/AG/AgJetEffectServer.cpp b/dScripts/ai/AG/AgJetEffectServer.cpp index 9546bc4d..1811d491 100644 --- a/dScripts/ai/AG/AgJetEffectServer.cpp +++ b/dScripts/ai/AG/AgJetEffectServer.cpp @@ -5,113 +5,55 @@ #include "eReplicaComponentType.h" void AgJetEffectServer::OnUse(Entity* self, Entity* user) { - if (inUse) { - return; - } - + if (inUse || !self->GetLOT() == 6859) return; GameMessages::SendNotifyClientObject( - self->GetObjectID(), - u"isInUse", - 0, - 0, - LWOOBJID_EMPTY, - "", - UNASSIGNED_SYSTEM_ADDRESS + self->GetObjectID(), u"toggleInUse", 1, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS ); - inUse = true; auto entities = EntityManager::Instance()->GetEntitiesInGroup("Jet_FX"); - - if (entities.empty()) { - return; - } - - auto* effect = entities[0]; - - GameMessages::SendPlayFXEffect(effect, 641, u"create", "radarDish", LWOOBJID_EMPTY, 1, 1, true); - - self->AddTimer("radarDish", 2); - self->AddTimer("CineDone", 9); + if (entities.empty()) return; + GameMessages::SendPlayFXEffect(entities.at(0), 641, u"create", "radarDish", LWOOBJID_EMPTY, 1, 1, true); + self->AddTimer("radarDish", 2.0f); + self->AddTimer("PlayEffect", 2.5f); + self->AddTimer("CineDone", 7.5f + 5.0f); // 7.5f is time the cinematic takes to play } void AgJetEffectServer::OnRebuildComplete(Entity* self, Entity* target) { + if (self->GetLOT() != 6209) return; auto entities = EntityManager::Instance()->GetEntitiesInGroup("Jet_FX"); + if (entities.empty()) return; + GameMessages::SendPlayAnimation(entities.at(0), u"jetFX"); - if (entities.empty()) { - return; - } - - auto* effect = entities[0]; - - auto groups = self->GetGroups(); - - if (groups.empty()) { - return; - } - + // So we can give kill credit to person who build this builder = target->GetObjectID(); - const auto group = groups[0]; - - GameMessages::SendPlayAnimation(effect, u"jetFX"); - - self->AddTimer("PlayEffect", 2.5f); - - if (group == "Base_Radar") { - self->AddTimer("CineDone", 5); + auto groups = self->GetGroups(); + if (!groups.empty() && groups.at(0) == "Base_Radar") { + self->AddTimer("PlayEffect", 2.5f); + self->AddTimer("CineDone", 7.5f + 5.0f); // 7.5f is time the cinematic takes to play } } void AgJetEffectServer::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "radarDish") { GameMessages::SendStopFXEffect(self, true, "radarDish"); - - return; - } - - if (timerName == "PlayEffect") { + } else if (timerName == "PlayEffect") { auto entities = EntityManager::Instance()->GetEntitiesInGroup("mortarMain"); + if (entities.empty()) return; - if (entities.empty()) { - return; - } - - const auto size = entities.size(); - - if (size == 0) { - return; - } - - const auto selected = GeneralUtils::GenerateRandomNumber<int>(0, size - 1); - - auto* mortar = entities[selected]; - - Game::logger->Log("AgJetEffectServer", "Mortar (%i) (&d)", mortar->GetLOT(), mortar->HasComponent(eReplicaComponentType::SKILL)); + const auto selected = GeneralUtils::GenerateRandomNumber<int>(0, entities.size() - 1); + auto* mortar = entities.at(selected); + // so we give proper credit to the builder for the kills from this skill mortar->SetOwnerOverride(builder); - SkillComponent* skillComponent; - if (!mortar->TryGetComponent(eReplicaComponentType::SKILL, skillComponent)) { - return; - } - - skillComponent->CalculateBehavior(318, 3727, LWOOBJID_EMPTY, true); - - return; - } - - if (timerName == "CineDone") { + auto* skillComponent = mortar->GetComponent<SkillComponent>(); + if (skillComponent) skillComponent->CastSkill(318); + } else if (timerName == "CineDone") { GameMessages::SendNotifyClientObject( - self->GetObjectID(), - u"toggleInUse", - -1, - 0, - LWOOBJID_EMPTY, - "", - UNASSIGNED_SYSTEM_ADDRESS + self->GetObjectID(), u"toggleInUse", -1, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS ); - inUse = false; } } From 58951dced0e3b17011f7c654c5134509fc5ac663 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 22 Apr 2023 12:32:32 -0700 Subject: [PATCH 304/322] Remove all need for a local ugc server (#1054) --- README.md | 23 ++--------------------- 1 file changed, 2 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index df782a32..f51b5e2a 100644 --- a/README.md +++ b/README.md @@ -245,30 +245,11 @@ To connect to a server follow these steps: * In the client directory, locate `boot.cfg` * Open it in a text editor and locate where it says `AUTHSERVERIP=0:` * Replace the contents after to `:` and the following `,` with what you configured as the server's public facing IP. For example `AUTHSERVERIP=0:localhost` for locally hosted servers +* Next locate the line `UGCUSE3DSERVICES=7:` +* Ensure the number after the 7 is a `0` * Launch `legouniverse.exe`, through `wine` if on a Unix-like operating system * Note that if you are on WSL2, you will need to configure the public IP in the server and client to be the IP of the WSL2 instance and not localhost, which can be found by running `ifconfig` in the terminal. Windows defaults to WSL1, so this will not apply to most users. -## Brick-By-Brick building -Should you choose to do any brick building, you will want to have some form of a http server that returns a 404 error since we are unable to emulate live User Generated Content at the moment. If you attempt to do any brick building without a 404 server running properly, you will be unable to load into your game. Python is the easiest way to do this, but any thing that returns a 404 should work fine. -* Note: the client hard codes this request on port 80. - -<font size="4">**If you do not plan on doing any Brick Building, then you can skip this step.**</font> - -The easiest way to do this is to install [python](https://www.python.org/downloads/). - -### Allowing a user to build in Brick-by-Brick mode -Brick-By-Brick building requires `PATCHSERVERIP=0:` and `UGCSERVERIP=0:` in the `boot.cfg` to point to a HTTP server which always returns `HTTP 404 - Not Found` for all requests. This can be most easily achieved by pointing both of those variables to `localhost` while having running in the background. -Each client must have their own 404 server running if they are using a locally hosted 404 server. -```bash -# If on linux run this command. Because this is run on a port below 1024, binary network permissions are needed. -sudo python3 -m http.server 80 - -# If on windows one of the following will work when run through Powershell or Command Prompt assuming python is installed -python3 -m http.server 80 -python http.server 80 -py -m http.server 80 -``` - ## Updating your server To update your server to the latest version navigate to your cloned directory ```bash From 4976701f376b28271235a05882d6802542f37578 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Tue, 25 Apr 2023 13:17:40 -0500 Subject: [PATCH 305/322] breakout object bits into scoped enum (#997) * breakout object bits into enum class tested that things still work as expected use the inplace set bits where appropiate * add inline --- dChatServer/ChatPacketHandler.cpp | 17 +++++++++-------- dCommon/GeneralUtils.h | 9 +++++---- dCommon/dEnums/dCommonVars.h | 8 -------- dCommon/dEnums/eObjectBits.h | 13 +++++++++++++ dGame/Character.cpp | 9 +++++---- dGame/Entity.cpp | 5 +++-- dGame/EntityManager.cpp | 5 +++-- dGame/UserManager.cpp | 13 +++++++------ dGame/dBehaviors/ProjectileAttackBehavior.cpp | 3 ++- dGame/dComponents/PetComponent.cpp | 5 +++-- dGame/dComponents/PropertyEntranceComponent.cpp | 5 +++-- .../dComponents/PropertyManagementComponent.cpp | 16 ++++++++-------- dGame/dGameMessages/GameMessages.cpp | 9 +++++---- dGame/dInventory/Item.cpp | 7 ++++--- dGame/dUtilities/SlashCommandHandler.cpp | 5 +++-- dWorldServer/WorldServer.cpp | 9 +++++---- dZoneManager/dZoneManager.cpp | 4 ++-- 17 files changed, 80 insertions(+), 62 deletions(-) create mode 100644 dCommon/dEnums/eObjectBits.h diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index 592c3870..a0d508cb 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -12,6 +12,7 @@ #include "eAddFriendResponseType.h" #include "RakString.h" #include "dConfig.h" +#include "eObjectBits.h" extern PlayerContainer playerContainer; @@ -45,8 +46,8 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { FriendData fd; fd.isFTP = false; // not a thing in DLU fd.friendID = res->getUInt(1); - GeneralUtils::SetBit(fd.friendID, static_cast<size_t>(eObjectBits::OBJECT_BIT_PERSISTENT)); - GeneralUtils::SetBit(fd.friendID, static_cast<size_t>(eObjectBits::OBJECT_BIT_CHARACTER)); + GeneralUtils::SetBit(fd.friendID, eObjectBits::PERSISTENT); + GeneralUtils::SetBit(fd.friendID, eObjectBits::CHARACTER); fd.isBestFriend = res->getInt(2) == 3; //0 = friends, 1 = left_requested, 2 = right_requested, 3 = both_accepted - are now bffs if (fd.isBestFriend) player->countOfBestFriends += 1; @@ -178,10 +179,10 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { bestFriendStatus = oldBestFriendStatus; // Set the bits - GeneralUtils::SetBit(queryPlayerID, static_cast<size_t>(eObjectBits::OBJECT_BIT_CHARACTER)); - GeneralUtils::SetBit(queryPlayerID, static_cast<size_t>(eObjectBits::OBJECT_BIT_PERSISTENT)); - GeneralUtils::SetBit(queryFriendID, static_cast<size_t>(eObjectBits::OBJECT_BIT_CHARACTER)); - GeneralUtils::SetBit(queryFriendID, static_cast<size_t>(eObjectBits::OBJECT_BIT_PERSISTENT)); + GeneralUtils::SetBit(queryPlayerID, eObjectBits::CHARACTER); + GeneralUtils::SetBit(queryPlayerID, eObjectBits::PERSISTENT); + GeneralUtils::SetBit(queryFriendID, eObjectBits::CHARACTER); + GeneralUtils::SetBit(queryFriendID, eObjectBits::PERSISTENT); // Since this player can either be the friend of someone else or be friends with someone else // their column in the database determines what bit gets set. When the value hits 3, they @@ -336,8 +337,8 @@ void ChatPacketHandler::HandleRemoveFriend(Packet* packet) { } // Convert friendID to LWOOBJID - GeneralUtils::SetBit(friendID, static_cast<size_t>(eObjectBits::OBJECT_BIT_PERSISTENT)); - GeneralUtils::SetBit(friendID, static_cast<size_t>(eObjectBits::OBJECT_BIT_CHARACTER)); + GeneralUtils::SetBit(friendID, eObjectBits::PERSISTENT); + GeneralUtils::SetBit(friendID, eObjectBits::CHARACTER); std::unique_ptr<sql::PreparedStatement> deletestmt(Database::CreatePreppedStmt("DELETE FROM friends WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?) LIMIT 1;")); deletestmt->setUInt(1, static_cast<uint32_t>(playerID)); diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index 0555a45e..0a8a0a16 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -16,6 +16,7 @@ #include "dLogger.h" enum eInventoryType : uint32_t; +enum class eObjectBits : size_t; enum class eReplicaComponentType : uint32_t; /*! @@ -66,9 +67,9 @@ namespace GeneralUtils { //! Sets a bit on a numerical value template <typename T> - void SetBit(T& value, size_t index) { + inline void SetBit(T& value, eObjectBits bits) { static_assert(std::is_arithmetic<T>::value, "Not an arithmetic type"); - + auto index = static_cast<size_t>(bits); if (index > (sizeof(T) * 8) - 1) { return; } @@ -78,9 +79,9 @@ namespace GeneralUtils { //! Clears a bit on a numerical value template <typename T> - void ClearBit(T& value, size_t index) { + inline void ClearBit(T& value, eObjectBits bits) { static_assert(std::is_arithmetic<T>::value, "Not an arithmetic type"); - + auto index = static_cast<size_t>(bits); if (index > (sizeof(T) * 8 - 1)) { return; } diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index 16cae3c9..ff8ec836 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -177,14 +177,6 @@ union suchar { //=========== LU ENUMS ============ -//! An enum for object ID bits -enum eObjectBits : int32_t { - OBJECT_BIT_PERSISTENT = 32, //!< The 32 bit index - OBJECT_BIT_CLIENT = 46, //!< The 46 bit index - OBJECT_BIT_SPAWNED = 58, //!< The 58 bit index - OBJECT_BIT_CHARACTER = 60 //!< The 60 bit index -}; - //! An enum for MatchUpdate types enum eMatchUpdate : int { MATCH_UPDATE_PLAYER_JOINED = 0, diff --git a/dCommon/dEnums/eObjectBits.h b/dCommon/dEnums/eObjectBits.h new file mode 100644 index 00000000..b978aad6 --- /dev/null +++ b/dCommon/dEnums/eObjectBits.h @@ -0,0 +1,13 @@ +#ifndef __EOBJECTBITS__H__ +#define __EOBJECTBITS__H__ + +#include <cstdint> + +enum class eObjectBits : size_t { + PERSISTENT = 32, + CLIENT = 46, + SPAWNED = 58, + CHARACTER = 60 +}; + +#endif //!__EOBJECTBITS__H__ diff --git a/dGame/Character.cpp b/dGame/Character.cpp index b8d08854..98d6d0a9 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -18,6 +18,7 @@ #include "InventoryComponent.h" #include "eMissionTaskType.h" #include "eMissionState.h" +#include "eObjectBits.h" #include "eGameMasterLevel.h" Character::Character(uint32_t id, User* parentUser) { @@ -69,8 +70,8 @@ Character::Character(uint32_t id, User* parentUser) { //Set our objectID: m_ObjectID = m_ID; - m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); - m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); + GeneralUtils::SetBit(m_ObjectID, eObjectBits::CHARACTER); + GeneralUtils::SetBit(m_ObjectID, eObjectBits::PERSISTENT); m_ParentUser = parentUser; m_OurEntity = nullptr; @@ -128,8 +129,8 @@ void Character::UpdateFromDatabase() { //Set our objectID: m_ObjectID = m_ID; - m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_CHARACTER); - m_ObjectID = GeneralUtils::SetBit(m_ObjectID, OBJECT_BIT_PERSISTENT); + GeneralUtils::SetBit(m_ObjectID, eObjectBits::CHARACTER); + GeneralUtils::SetBit(m_ObjectID, eObjectBits::PERSISTENT); m_OurEntity = nullptr; m_BuildMode = false; diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 595ab090..55e1b1ca 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -24,6 +24,7 @@ #include "Loot.h" #include "eMissionTaskType.h" #include "eTriggerEventType.h" +#include "eObjectBits.h" //Component includes: #include "Component.h" @@ -952,9 +953,9 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke if (m_ParentEntity != nullptr || m_SpawnerID != 0) { outBitStream->Write1(); - if (m_ParentEntity != nullptr) outBitStream->Write(GeneralUtils::SetBit(m_ParentEntity->GetObjectID(), OBJECT_BIT_CLIENT)); + if (m_ParentEntity != nullptr) outBitStream->Write(GeneralUtils::SetBit(m_ParentEntity->GetObjectID(), static_cast<uint32_t>(eObjectBits::CLIENT))); else if (m_Spawner != nullptr && m_Spawner->m_Info.isNetwork) outBitStream->Write(m_SpawnerID); - else outBitStream->Write(GeneralUtils::SetBit(m_SpawnerID, OBJECT_BIT_CLIENT)); + else outBitStream->Write(GeneralUtils::SetBit(m_SpawnerID, static_cast<uint32_t>(eObjectBits::CLIENT))); } else outBitStream->Write0(); outBitStream->Write(m_HasSpawnerNodeID); diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index d547cdb1..dc9a43f3 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -20,6 +20,7 @@ #include "MessageIdentifiers.h" #include "dConfig.h" #include "eTriggerEventType.h" +#include "eObjectBits.h" #include "eGameMasterLevel.h" #include "eReplicaComponentType.h" @@ -108,11 +109,11 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE if (!controller && info.lot != 14) { // The client flags means the client should render the entity - id = GeneralUtils::SetBit(id, OBJECT_BIT_CLIENT); + GeneralUtils::SetBit(id, eObjectBits::CLIENT); // Spawned entities require the spawned flag to render if (info.spawnerID != 0) { - id = GeneralUtils::SetBit(id, OBJECT_BIT_SPAWNED); + GeneralUtils::SetBit(id, eObjectBits::SPAWNED); } } } diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index 4f0c456d..0e52bc52 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -23,6 +23,7 @@ #include "AssetManager.h" #include "CDClientDatabase.h" #include "dMessageIdentifiers.h" +#include "eObjectBits.h" #include "eGameMasterLevel.h" UserManager* UserManager::m_Address = nullptr; @@ -313,16 +314,16 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) std::stringstream xml2; LWOOBJID lwoidforshirt = idforshirt; - lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_CHARACTER); - lwoidforshirt = GeneralUtils::SetBit(lwoidforshirt, OBJECT_BIT_PERSISTENT); + GeneralUtils::SetBit(lwoidforshirt, eObjectBits::CHARACTER); + GeneralUtils::SetBit(lwoidforshirt, eObjectBits::PERSISTENT); xml2 << xmlSave1 << "<i l=\"" << shirtLOT << "\" id=\"" << lwoidforshirt << "\" s=\"0\" c=\"1\" eq=\"1\" b=\"1\"/>"; std::string xmlSave2 = xml2.str(); ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t idforpants) { LWOOBJID lwoidforpants = idforpants; - lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_CHARACTER); - lwoidforpants = GeneralUtils::SetBit(lwoidforpants, OBJECT_BIT_PERSISTENT); + GeneralUtils::SetBit(lwoidforpants, eObjectBits::CHARACTER); + GeneralUtils::SetBit(lwoidforpants, eObjectBits::PERSISTENT); std::stringstream xml3; xml3 << xmlSave2 << "<i l=\"" << pantsLOT << "\" id=\"" << lwoidforpants << "\" s=\"1\" c=\"1\" eq=\"1\" b=\"1\"/>"; @@ -480,8 +481,8 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) } LWOOBJID objectID = PacketUtils::ReadPacketS64(8, packet); - objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_CHARACTER); - objectID = GeneralUtils::ClearBit(objectID, OBJECT_BIT_PERSISTENT); + GeneralUtils::ClearBit(objectID, eObjectBits::CHARACTER); + GeneralUtils::ClearBit(objectID, eObjectBits::PERSISTENT); uint32_t charID = static_cast<uint32_t>(objectID); Game::logger->Log("UserManager", "Received char rename request for ID: %llu (%u)", objectID, charID); diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.cpp b/dGame/dBehaviors/ProjectileAttackBehavior.cpp index 3ce6c415..f65421cb 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.cpp +++ b/dGame/dBehaviors/ProjectileAttackBehavior.cpp @@ -6,6 +6,7 @@ #include "dLogger.h" #include "SkillComponent.h" #include "../dWorldServer/ObjectIDManager.h" +#include "eObjectBits.h" void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { LWOOBJID target{}; @@ -107,7 +108,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt for (auto i = 0u; i < this->m_projectileCount; ++i) { auto id = static_cast<LWOOBJID>(ObjectIDManager::Instance()->GenerateObjectID()); - id = GeneralUtils::SetBit(id, OBJECT_BIT_SPAWNED); + GeneralUtils::SetBit(id, eObjectBits::SPAWNED); bitStream->Write(id); diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 090e5791..2dfaad27 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -22,6 +22,7 @@ #include "Database.h" #include "EntityInfo.h" #include "eMissionTaskType.h" +#include "eObjectBits.h" #include "eGameMasterLevel.h" std::unordered_map<LOT, PetComponent::PetPuzzleData> PetComponent::buildCache{}; @@ -551,8 +552,8 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { LWOOBJID petSubKey = ObjectIDManager::Instance()->GenerateRandomObjectID(); - petSubKey = GeneralUtils::SetBit(petSubKey, OBJECT_BIT_CHARACTER); - petSubKey = GeneralUtils::SetBit(petSubKey, OBJECT_BIT_PERSISTENT); + GeneralUtils::SetBit(petSubKey, eObjectBits::CHARACTER); + GeneralUtils::SetBit(petSubKey, eObjectBits::PERSISTENT); m_DatabaseId = petSubKey; diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index c251dc96..5da9a3c4 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -12,6 +12,7 @@ #include "UserManager.h" #include "dLogger.h" #include "AMFFormat.h" +#include "eObjectBits.h" #include "eGameMasterLevel.h" PropertyEntranceComponent::PropertyEntranceComponent(uint32_t componentID, Entity* parent) : Component(parent) { @@ -243,8 +244,8 @@ void PropertyEntranceComponent::OnPropertyEntranceSync(Entity* entity, bool incl // Convert owner char id to LWOOBJID LWOOBJID ownerObjId = owner; - ownerObjId = GeneralUtils::SetBit(ownerObjId, OBJECT_BIT_CHARACTER); - ownerObjId = GeneralUtils::SetBit(ownerObjId, OBJECT_BIT_PERSISTENT); + GeneralUtils::SetBit(ownerObjId, eObjectBits::CHARACTER); + GeneralUtils::SetBit(ownerObjId, eObjectBits::PERSISTENT); // Query to get friend and best friend fields auto friendCheck = Database::CreatePreppedStmt("SELECT best_friend FROM friends WHERE (player_id = ? AND friend_id = ?) OR (player_id = ? AND friend_id = ?)"); diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index 0b05b10e..4b9e287f 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -19,6 +19,7 @@ #include "PropertyEntranceComponent.h" #include "InventoryComponent.h" #include "eMissionTaskType.h" +#include "eObjectBits.h" #include <vector> #include "CppScripts.h" @@ -66,8 +67,8 @@ PropertyManagementComponent::PropertyManagementComponent(Entity* parent) : Compo if (propertyEntry->next()) { this->propertyId = propertyEntry->getUInt64(1); this->owner = propertyEntry->getUInt64(2); - this->owner = GeneralUtils::SetBit(this->owner, OBJECT_BIT_CHARACTER); - this->owner = GeneralUtils::SetBit(this->owner, OBJECT_BIT_PERSISTENT); + GeneralUtils::SetBit(this->owner, eObjectBits::CHARACTER); + GeneralUtils::SetBit(this->owner, eObjectBits::PERSISTENT); this->clone_Id = propertyEntry->getInt(2); this->propertyName = propertyEntry->getString(5).c_str(); this->propertyDescription = propertyEntry->getString(6).c_str(); @@ -372,16 +373,15 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N info.emulated = true; info.emulator = EntityManager::Instance()->GetZoneControlEntity()->GetObjectID(); - LWOOBJID id = static_cast<LWOOBJID>(persistentId) | 1ull << OBJECT_BIT_CLIENT; - - info.spawnerID = id; + info.spawnerID = persistentId; + GeneralUtils::SetBit(info.spawnerID, eObjectBits::CLIENT); const auto spawnerId = dZoneManager::Instance()->MakeSpawner(info); auto* spawner = dZoneManager::Instance()->GetSpawner(spawnerId); auto ldfModelBehavior = new LDFData<LWOOBJID>(u"modelBehaviors", 0); - auto userModelID = new LDFData<LWOOBJID>(u"userModelID", id); + auto userModelID = new LDFData<LWOOBJID>(u"userModelID", info.spawnerID); auto modelType = new LDFData<int>(u"modelType", 2); auto propertyObjectID = new LDFData<bool>(u"propertyObjectID", true); auto componentWhitelist = new LDFData<int>(u"componentWhitelist", 1); @@ -622,8 +622,8 @@ void PropertyManagementComponent::Load() { //BBB property models need to have extra stuff set for them: if (lot == 14) { LWOOBJID blueprintID = lookupResult->getUInt(10); - blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_CHARACTER); - blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_PERSISTENT); + GeneralUtils::SetBit(blueprintID, eObjectBits::CHARACTER); + GeneralUtils::SetBit(blueprintID, eObjectBits::PERSISTENT); LDFBaseData* ldfBlueprintID = new LDFData<LWOOBJID>(u"blueprintid", blueprintID); LDFBaseData* componentWhitelist = new LDFData<int>(u"componentWhitelist", 1); diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 0fc32e2e..f5cbc811 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -34,6 +34,7 @@ #include "eRacingTaskParam.h" #include "eMissionTaskType.h" #include "eMissionState.h" +#include "eObjectBits.h" #include "eTriggerEventType.h" #include <sstream> @@ -2575,14 +2576,14 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //We need to get a new ID for our model first: ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t newID) { LWOOBJID newIDL = newID; - newIDL = GeneralUtils::SetBit(newIDL, OBJECT_BIT_CHARACTER); - newIDL = GeneralUtils::SetBit(newIDL, OBJECT_BIT_PERSISTENT); + GeneralUtils::SetBit(newIDL, eObjectBits::CHARACTER); + GeneralUtils::SetBit(newIDL, eObjectBits::PERSISTENT); ObjectIDManager::Instance()->RequestPersistentID([=](uint32_t blueprintIDSmall) { blueprintIDSmall = ObjectIDManager::Instance()->GenerateRandomObjectID(); LWOOBJID blueprintID = blueprintIDSmall; - blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_CHARACTER); - blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_PERSISTENT); + GeneralUtils::SetBit(blueprintID, eObjectBits::CHARACTER); + GeneralUtils::SetBit(blueprintID, eObjectBits::PERSISTENT); //We need to get the propertyID: (stolen from Wincent's propertyManagementComp) const auto& worldId = dZoneManager::Instance()->GetZone()->GetZoneID(); diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 5795ab12..62dffa12 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -16,6 +16,7 @@ #include "AssetManager.h" #include "InventoryComponent.h" #include "Loot.h" +#include "eObjectBits.h" #include "eReplicaComponentType.h" #include "CDBrickIDTableTable.h" @@ -77,13 +78,13 @@ Item::Item( LWOOBJID id = ObjectIDManager::GenerateRandomObjectID(); - id = GeneralUtils::SetBit(id, OBJECT_BIT_CHARACTER); - id = GeneralUtils::SetBit(id, OBJECT_BIT_PERSISTENT); + GeneralUtils::SetBit(id, eObjectBits::CHARACTER); + GeneralUtils::SetBit(id, eObjectBits::PERSISTENT); const auto type = static_cast<eItemType>(info->itemType); if (type == eItemType::MOUNT) { - id = GeneralUtils::SetBit(id, OBJECT_BIT_CLIENT); + GeneralUtils::SetBit(id, eObjectBits::CLIENT); } this->id = id; diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 8693abe9..9c1bc611 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -75,6 +75,7 @@ #include "eMissionState.h" #include "TriggerComponent.h" #include "eServerDisconnectIdentifiers.h" +#include "eObjectBits.h" #include "eGameMasterLevel.h" #include "eReplicaComponentType.h" @@ -1029,8 +1030,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit accountId = result->getUInt(1); characterId = result->getUInt64(2); - characterId = GeneralUtils::SetBit(characterId, OBJECT_BIT_CHARACTER); - characterId = GeneralUtils::SetBit(characterId, OBJECT_BIT_PERSISTENT); + GeneralUtils::SetBit(characterId, eObjectBits::CHARACTER); + GeneralUtils::SetBit(characterId, eObjectBits::PERSISTENT); } } diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 8a603878..71384207 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -64,6 +64,7 @@ #include "AMFFormat.h" #include "NiPoint3.h" #include "eServerDisconnectIdentifiers.h" +#include "eObjectBits.h" #include "ZCompression.h" @@ -968,8 +969,8 @@ void HandlePacket(Packet* packet) { LWOOBJID playerID = 0; inStream.Read(playerID); - playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_CHARACTER); - playerID = GeneralUtils::ClearBit(playerID, OBJECT_BIT_PERSISTENT); + GeneralUtils::ClearBit(playerID, eObjectBits::CHARACTER); + GeneralUtils::ClearBit(playerID, eObjectBits::PERSISTENT); auto user = UserManager::Instance()->GetUser(packet->systemAddress); @@ -1123,8 +1124,8 @@ void HandlePacket(Packet* packet) { //Send message: { LWOOBJID blueprintID = res->getUInt(1); - blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_CHARACTER); - blueprintID = GeneralUtils::SetBit(blueprintID, OBJECT_BIT_PERSISTENT); + GeneralUtils::SetBit(blueprintID, eObjectBits::CHARACTER); + GeneralUtils::SetBit(blueprintID, eObjectBits::PERSISTENT); CBITSTREAM; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index ac3a7008..1a40748d 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -11,6 +11,7 @@ #include "WorldConfig.h" #include "CDZoneTableTable.h" #include <chrono> +#include "eObjectBits.h" #include "../dWorldServer/ObjectIDManager.h" @@ -133,8 +134,7 @@ LWOOBJID dZoneManager::MakeSpawner(SpawnerInfo info) { if (objectId == LWOOBJID_EMPTY) { objectId = ObjectIDManager::Instance()->GenerateObjectID(); - - objectId = GeneralUtils::SetBit(objectId, OBJECT_BIT_CLIENT); + GeneralUtils::SetBit(objectId, eObjectBits::CLIENT); info.spawnerID = objectId; } From 2f919d101f00be8ecfdbeea3bb782b8ca52f24c4 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Tue, 2 May 2023 05:27:16 -0500 Subject: [PATCH 306/322] Fix bad lot comparison in AG Jet Effect Server (#1063) --- dScripts/ai/AG/AgJetEffectServer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dScripts/ai/AG/AgJetEffectServer.cpp b/dScripts/ai/AG/AgJetEffectServer.cpp index 1811d491..3d132991 100644 --- a/dScripts/ai/AG/AgJetEffectServer.cpp +++ b/dScripts/ai/AG/AgJetEffectServer.cpp @@ -5,7 +5,7 @@ #include "eReplicaComponentType.h" void AgJetEffectServer::OnUse(Entity* self, Entity* user) { - if (inUse || !self->GetLOT() == 6859) return; + if (inUse || self->GetLOT() != 6859) return; GameMessages::SendNotifyClientObject( self->GetObjectID(), u"toggleInUse", 1, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS ); From e8590a58539529a95ecd257e5541b36a8cc45a63 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Tue, 2 May 2023 15:19:20 -0700 Subject: [PATCH 307/322] Add tests for LDF parsing and serialization. Cleanup LDF (#1062) * Add tests and cleanup LDF header Also implements a speedup by using overloaded operators to put numbers directly to a stream as opposed to doing to_string first. Stage 2 of re-write Reduce scoping Add further optimizations Fix more edge cases Split out tests to many smaller ones Use EXPECT_NO_THROW Add edge cases to test Added these first with the before to confirm they failed, and now will be adding the remaining fixes needed to make the tests pass. Add edge case testing for LDF strings Add further tests Use characters instead of char* Update AMFDeserializeTests.cpp Add null tests * Add Test Fixture for dCommon * Add speed test * Convert to using string_view * Add explanation on early return * Remove "testing" code --- dCommon/LDFFormat.cpp | 244 +++++++++++-------- dCommon/LDFFormat.h | 86 +++---- tests/dCommonTests/CMakeLists.txt | 1 + tests/dCommonTests/TestLDFFormat.cpp | 263 +++++++++++++++++++-- tests/dCommonTests/dCommonDependencies.cpp | 7 + tests/dCommonTests/dCommonDependencies.h | 26 ++ 6 files changed, 455 insertions(+), 172 deletions(-) create mode 100644 tests/dCommonTests/dCommonDependencies.cpp create mode 100644 tests/dCommonTests/dCommonDependencies.h diff --git a/dCommon/LDFFormat.cpp b/dCommon/LDFFormat.cpp index 767ec81a..cb921842 100644 --- a/dCommon/LDFFormat.cpp +++ b/dCommon/LDFFormat.cpp @@ -3,122 +3,174 @@ // Custom Classes #include "GeneralUtils.h" +#include "Game.h" +#include "dLogger.h" + // C++ -#include <sstream> +#include <string_view> #include <vector> +using LDFKey = std::string_view; +using LDFTypeAndValue = std::string_view; + +using LDFType = std::string_view; +using LDFValue = std::string_view; + //! Returns a pointer to a LDFData value based on string format -LDFBaseData* LDFBaseData::DataFromString(const std::string& format) { +LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { + // A valid LDF must be at least 3 characters long (=0:) is the shortest valid LDF (empty UTF-16 key with no initial value) + if (format.empty() || format.length() <= 2) return nullptr; + auto equalsPosition = format.find('='); + // You can have an empty key, just make sure the type and value might exist + if (equalsPosition == std::string::npos || equalsPosition == (format.size() - 1)) return nullptr; - // First, check the format - std::istringstream ssFormat(format); - std::string token; + std::pair<LDFKey, LDFTypeAndValue> keyValue; + keyValue.first = format.substr(0, equalsPosition); + keyValue.second = format.substr(equalsPosition + 1, format.size()); - std::vector<std::string> keyValueArray; - while (std::getline(ssFormat, token, '=')) { - keyValueArray.push_back(token); + std::u16string key = GeneralUtils::ASCIIToUTF16(keyValue.first); + + auto colonPosition = keyValue.second.find(':'); + + // If : is the first thing after an =, then this is an invalid LDF since + // we dont have a type to use. + if (colonPosition == std::string::npos || colonPosition == 0) return nullptr; + + std::pair<LDFType, LDFValue> ldfTypeAndValue; + ldfTypeAndValue.first = keyValue.second.substr(0, colonPosition); + ldfTypeAndValue.second = keyValue.second.substr(colonPosition + 1, keyValue.second.size()); + + // Only allow empty values for string values. + if (ldfTypeAndValue.second.size() == 0 && !(ldfTypeAndValue.first == "0" || ldfTypeAndValue.first == "13")) return nullptr; + + eLDFType type; + char* storage; + try { + type = static_cast<eLDFType>(strtol(ldfTypeAndValue.first.data(), &storage, 10)); + } catch (std::exception) { + Game::logger->Log("LDFFormat", "Attempted to process invalid ldf type (%s) from string (%s)", ldfTypeAndValue.first.data(), format.data()); + return nullptr; } - if (keyValueArray.size() == 2) { - std::u16string key = GeneralUtils::ASCIIToUTF16(keyValueArray[0]); + LDFBaseData* returnValue = nullptr; + switch (type) { + case LDF_TYPE_UTF_16: { + std::u16string data = GeneralUtils::UTF8ToUTF16(ldfTypeAndValue.second); + returnValue = new LDFData<std::u16string>(key, data); + break; + } - std::vector<std::string> dataArray; - std::istringstream ssData(keyValueArray[1]); - while (std::getline(ssData, token, ':')) { - dataArray.push_back(token); + case LDF_TYPE_S32: { + try { + int32_t data = static_cast<int32_t>(strtoul(ldfTypeAndValue.second.data(), &storage, 10)); + returnValue = new LDFData<int32_t>(key, data); + } catch (std::exception) { + Game::logger->Log("LDFFormat", "Warning: Attempted to process invalid int32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + return nullptr; } + break; + } - if (dataArray.size() > 2) { // hacky fix for strings with colons in them - std::vector<std::string> newDataArray; - newDataArray.push_back(dataArray[0]); - std::string value = ""; - for (size_t i = 1; i < dataArray.size(); ++i) { - value += dataArray[i] + ':'; - } - value.pop_back(); // remove last colon - newDataArray.push_back(value); - dataArray = newDataArray; + case LDF_TYPE_FLOAT: { + try { + float data = strtof(ldfTypeAndValue.second.data(), &storage); + returnValue = new LDFData<float>(key, data); + } catch (std::exception) { + Game::logger->Log("LDFFormat", "Warning: Attempted to process invalid float value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + return nullptr; } + break; + } - if ((dataArray[0] == "0" || dataArray[0] == "13") && dataArray.size() == 1) { - dataArray.push_back(""); + case LDF_TYPE_DOUBLE: { + try { + double data = strtod(ldfTypeAndValue.second.data(), &storage); + returnValue = new LDFData<double>(key, data); + } catch (std::exception) { + Game::logger->Log("LDFFormat", "Warning: Attempted to process invalid double value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + return nullptr; } + break; + } - if (dataArray.size() == 2) { - eLDFType type = static_cast<eLDFType>(stoi(dataArray[0])); + case LDF_TYPE_U32: + { + uint32_t data; - switch (type) { - case LDF_TYPE_UTF_16: { - std::u16string data = GeneralUtils::UTF8ToUTF16(dataArray[1]); - return new LDFData<std::u16string>(key, data); - } - - case LDF_TYPE_S32: { - int32_t data = static_cast<int32_t>(stoull(dataArray[1])); - return new LDFData<int32_t>(key, data); - } - - case LDF_TYPE_FLOAT: { - float data = static_cast<float>(stof(dataArray[1])); - return new LDFData<float>(key, data); - } - - case LDF_TYPE_DOUBLE: { - double data = static_cast<float>(stod(dataArray[1])); - return new LDFData<double>(key, data); - } - - case LDF_TYPE_U32: - { - uint32_t data; - - if (dataArray[1] == "true") { - data = 1; - } else if (dataArray[1] == "false") { - data = 0; - } else { - data = static_cast<uint32_t>(stoul(dataArray[1])); - } - - return new LDFData<uint32_t>(key, data); - } - - case LDF_TYPE_BOOLEAN: { - bool data; - - if (dataArray[1] == "true") { - data = true; - } else if (dataArray[1] == "false") { - data = false; - } else { - data = static_cast<bool>(stoi(dataArray[1])); - } - - return new LDFData<bool>(key, data); - } - - case LDF_TYPE_U64: { - uint64_t data = static_cast<uint64_t>(stoull(dataArray[1])); - return new LDFData<uint64_t>(key, data); - } - - case LDF_TYPE_OBJID: { - LWOOBJID data = static_cast<LWOOBJID>(stoll(dataArray[1])); - return new LDFData<LWOOBJID>(key, data); - } - - case LDF_TYPE_UTF_8: { - std::string data = dataArray[1]; - return new LDFData<std::string>(key, data); - } - - case LDF_TYPE_UNKNOWN: { + if (ldfTypeAndValue.second == "true") { + data = 1; + } else if (ldfTypeAndValue.second == "false") { + data = 0; + } else { + try { + data = static_cast<uint32_t>(strtoul(ldfTypeAndValue.second.data(), &storage, 10)); + } catch (std::exception) { + Game::logger->Log("LDFFormat", "Warning: Attempted to process invalid uint32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - } } + + returnValue = new LDFData<uint32_t>(key, data); + break; } - return nullptr; + case LDF_TYPE_BOOLEAN: { + bool data; + if (ldfTypeAndValue.second == "true") { + data = true; + } else if (ldfTypeAndValue.second == "false") { + data = false; + } else { + try { + data = static_cast<bool>(strtol(ldfTypeAndValue.second.data(), &storage, 10)); + } catch (std::exception) { + Game::logger->Log("LDFFormat", "Warning: Attempted to process invalid bool value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + return nullptr; + } + } + + returnValue = new LDFData<bool>(key, data); + break; + } + + case LDF_TYPE_U64: { + try { + uint64_t data = static_cast<uint64_t>(strtoull(ldfTypeAndValue.second.data(), &storage, 10)); + returnValue = new LDFData<uint64_t>(key, data); + } catch (std::exception) { + Game::logger->Log("LDFFormat", "Warning: Attempted to process invalid uint64 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + return nullptr; + } + break; + } + + case LDF_TYPE_OBJID: { + try { + LWOOBJID data = static_cast<LWOOBJID>(strtoll(ldfTypeAndValue.second.data(), &storage, 10)); + returnValue = new LDFData<LWOOBJID>(key, data); + } catch (std::exception) { + Game::logger->Log("LDFFormat", "Warning: Attempted to process invalid LWOOBJID value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + return nullptr; + } + break; + } + + case LDF_TYPE_UTF_8: { + std::string data = ldfTypeAndValue.second.data(); + returnValue = new LDFData<std::string>(key, data); + break; + } + + case LDF_TYPE_UNKNOWN: { + Game::logger->Log("LDFFormat", "Warning: Attempted to process invalid unknown value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); + break; + } + + default: { + Game::logger->Log("LDFFormat", "Warning: Attempted to process invalid LDF type (%d) from string (%s)", type, format.data()); + break; + } + } + return returnValue; } diff --git a/dCommon/LDFFormat.h b/dCommon/LDFFormat.h index 9b62efa7..0921d04c 100644 --- a/dCommon/LDFFormat.h +++ b/dCommon/LDFFormat.h @@ -1,4 +1,5 @@ -#pragma once +#ifndef __LDFFORMAT__H__ +#define __LDFFORMAT__H__ // Custom Classes #include "dCommonVars.h" @@ -6,18 +7,12 @@ // C++ #include <string> +#include <string_view> #include <sstream> // RakNet +#include "BitStream.h" -#include "../thirdparty/raknet/Source/BitStream.h" - -/*! - \file LDFFormat.hpp - \brief A collection of LDF format classes - */ - - //! An enum for LDF Data Types enum eLDFType { LDF_TYPE_UNKNOWN = -1, //!< Unknown data type LDF_TYPE_UTF_16 = 0, //!< UTF-16 wstring data type @@ -31,36 +26,21 @@ enum eLDFType { LDF_TYPE_UTF_8 = 13, //!< UTF-8 string data type }; -//! A base class for the LDF data class LDFBaseData { public: - //! Destructor - virtual ~LDFBaseData(void) {} + virtual ~LDFBaseData() {} - //! Writes the data to a packet - /*! - \param packet The packet - */ virtual void WriteToPacket(RakNet::BitStream* packet) = 0; - //! Gets the key - /*! - \return The key - */ - virtual const std::u16string& GetKey(void) = 0; + virtual const std::u16string& GetKey() = 0; - //! Gets the value type - /*! - \return The value type - */ - virtual eLDFType GetValueType(void) = 0; + virtual eLDFType GetValueType() = 0; - //! Gets a string from the key/value pair - /*! - \param includeKey Whether or not to include the key in the data - \param includeTypeId Whether or not to include the type id in the data - \return The string representation of the data + /** Gets a string from the key/value pair + * @param includeKey Whether or not to include the key in the data + * @param includeTypeId Whether or not to include the type id in the data + * @return The string representation of the data */ virtual std::string GetString(bool includeKey = true, bool includeTypeId = true) = 0; @@ -68,19 +48,15 @@ public: virtual LDFBaseData* Copy() = 0; - // MARK: Functions - - //! Returns a pointer to a LDFData value based on string format - /*! - \param format The format + /** + * Given an input string, return the data as a LDF key. */ - static LDFBaseData* DataFromString(const std::string& format); + static LDFBaseData* DataFromString(const std::string_view& format); }; -//! A structure for an LDF key-value pair template<typename T> -class LDFData : public LDFBaseData { +class LDFData: public LDFBaseData { private: std::u16string key; T value; @@ -164,15 +140,11 @@ public: if (includeKey) { const std::string& sKey = GeneralUtils::UTF16ToWTF8(this->key, this->key.size()); - - stream << sKey << "="; + stream << sKey << '='; } if (includeTypeId) { - const std::string& sType = std::to_string(this->GetValueType()); - - - stream << sType << ":"; + stream << this->GetValueType() << ':'; } const std::string& sData = this->GetValueString(); @@ -234,20 +206,18 @@ inline void LDFData<std::string>::WriteValue(RakNet::BitStream* packet) { } } -// MARK: String Data -template<> inline std::string LDFData<std::u16string>::GetValueString(void) { - //std::string toReturn(this->value.begin(), this->value.end()); - //return toReturn; - +template<> inline std::string LDFData<std::u16string>::GetValueString() { return GeneralUtils::UTF16ToWTF8(this->value, this->value.size()); } -template<> inline std::string LDFData<int32_t>::GetValueString(void) { return std::to_string(this->value); } -template<> inline std::string LDFData<float>::GetValueString(void) { return std::to_string(this->value); } -template<> inline std::string LDFData<double>::GetValueString(void) { return std::to_string(this->value); } -template<> inline std::string LDFData<uint32_t>::GetValueString(void) { return std::to_string(this->value); } -template<> inline std::string LDFData<bool>::GetValueString(void) { return std::to_string(this->value); } -template<> inline std::string LDFData<uint64_t>::GetValueString(void) { return std::to_string(this->value); } -template<> inline std::string LDFData<LWOOBJID>::GetValueString(void) { return std::to_string(this->value); } +template<> inline std::string LDFData<int32_t>::GetValueString() { return std::to_string(this->value); } +template<> inline std::string LDFData<float>::GetValueString() { return std::to_string(this->value); } +template<> inline std::string LDFData<double>::GetValueString() { return std::to_string(this->value); } +template<> inline std::string LDFData<uint32_t>::GetValueString() { return std::to_string(this->value); } +template<> inline std::string LDFData<bool>::GetValueString() { return std::to_string(this->value); } +template<> inline std::string LDFData<uint64_t>::GetValueString() { return std::to_string(this->value); } +template<> inline std::string LDFData<LWOOBJID>::GetValueString() { return std::to_string(this->value); } -template<> inline std::string LDFData<std::string>::GetValueString(void) { return this->value; } +template<> inline std::string LDFData<std::string>::GetValueString() { return this->value; } + +#endif //!__LDFFORMAT__H__ diff --git a/tests/dCommonTests/CMakeLists.txt b/tests/dCommonTests/CMakeLists.txt index 86c00c58..dd282cb5 100644 --- a/tests/dCommonTests/CMakeLists.txt +++ b/tests/dCommonTests/CMakeLists.txt @@ -3,6 +3,7 @@ set(DCOMMONTEST_SOURCES "TestLDFFormat.cpp" "TestNiPoint3.cpp" "TestEncoding.cpp" + "dCommonDependencies.cpp" ) # Set our executable diff --git a/tests/dCommonTests/TestLDFFormat.cpp b/tests/dCommonTests/TestLDFFormat.cpp index 647c3cbf..36326e38 100644 --- a/tests/dCommonTests/TestLDFFormat.cpp +++ b/tests/dCommonTests/TestLDFFormat.cpp @@ -1,25 +1,252 @@ #include "LDFFormat.h" + #include <gtest/gtest.h> -/** - * @brief Test parsing an LDF value - */ -TEST(dCommonTests, LDFTest) { - // Create - auto* data = LDFBaseData::DataFromString("KEY=0:VALUE"); +#include "Game.h" +#include "dCommonDependencies.h" +#include "dLogger.h" - // Check that the data type is correct +class LDFTests : public dCommonDependenciesTest { +protected: + void SetUp() override { + SetUpDependencies(); + } + + void TearDown() override { + TearDownDependencies(); + } +}; + +#define LdfUniquePtr std::unique_ptr<LDFBaseData> + +// Suite of tests for parsing LDF values + +TEST_F(LDFTests, LDFUTF16Test) { + std::string testWord = "KEY=0:IAmA weird string with :::: and spac,./;'][\\es that I expect to be parsed correctly...; "; + LdfUniquePtr data(LDFBaseData::DataFromString(testWord)); + ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_16); - - // Check that the key is correct ASSERT_EQ(data->GetKey(), u"KEY"); - - // Check that the value is correct - ASSERT_EQ(((LDFData<std::u16string>*)data)->GetValue(), u"VALUE"); - - // Check that the serialization is correct - ASSERT_EQ(data->GetString(), "KEY=0:VALUE"); - - // Cleanup the object - delete data; + ASSERT_EQ(((LDFData<std::u16string>*)data.get())->GetValue(), u"IAmA weird string with :::: and spac,./;'][\\es that I expect to be parsed correctly...; "); + ASSERT_EQ(data->GetString(), testWord); } + +TEST_F(LDFTests, LDFUTF16EmptyTest) { + std::string testWord = "KEY=0:"; + LdfUniquePtr data(LDFBaseData::DataFromString(testWord)); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_16); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<std::u16string>*)data.get())->GetValue(), u""); + ASSERT_EQ(data->GetString(), testWord); +} + +TEST_F(LDFTests, LDFUTF16ColonTest) { + std::string testWord = "KEY=0:::"; + LdfUniquePtr data(LDFBaseData::DataFromString(testWord)); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_16); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<std::u16string>*)data.get())->GetValue(), u"::"); + ASSERT_EQ(data->GetString(), testWord); +} + +TEST_F(LDFTests, LDFUTF16EqualsTest) { + std::string testWord = "KEY=0:=="; + LdfUniquePtr data(LDFBaseData::DataFromString(testWord)); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_16); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<std::u16string>*)data.get())->GetValue(), u"=="); + ASSERT_EQ(data->GetString(), testWord); +} + +TEST_F(LDFTests, LDFS32Test) { + LdfUniquePtr data(LDFBaseData::DataFromString("KEY=1:-15")); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_S32); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<int32_t>*)data.get())->GetValue(), -15); + ASSERT_EQ(data->GetString(), "KEY=1:-15"); +} +TEST_F(LDFTests, LDFU32Test) { + LdfUniquePtr data(LDFBaseData::DataFromString("KEY=5:15")); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_U32); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<uint32_t>*)data.get())->GetValue(), 15); + ASSERT_EQ(data->GetString(), "KEY=5:15"); +} + +TEST_F(LDFTests, LDFU32TrueTest) { + LdfUniquePtr data(LDFBaseData::DataFromString("KEY=5:true")); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_U32); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<uint32_t>*)data.get())->GetValue(), 1); + ASSERT_EQ(data->GetString(), "KEY=5:1"); +} + +TEST_F(LDFTests, LDFU32FalseTest) { + LdfUniquePtr data(LDFBaseData::DataFromString("KEY=5:false")); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_U32); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<uint32_t>*)data.get())->GetValue(), 0); + ASSERT_EQ(data->GetString(), "KEY=5:0"); +} + + +// Use find since floats and doubles generally have appended 0s +TEST_F(LDFTests, LDFFloatTest) { + LdfUniquePtr data(LDFBaseData::DataFromString("KEY=3:15.5")); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_FLOAT); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<float>*)data.get())->GetValue(), 15.5f); + ASSERT_EQ(data->GetString().find("KEY=3:15.5"), 0); +} + +TEST_F(LDFTests, LDFDoubleTest) { + LdfUniquePtr data(LDFBaseData::DataFromString("KEY=4:15.5")); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_DOUBLE); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<double>*)data.get())->GetValue(), 15.5); + ASSERT_EQ(data->GetString().find("KEY=4:15.5"), 0); +} + + +TEST_F(LDFTests, LDFBoolTrueTest) { + LdfUniquePtr data(LDFBaseData::DataFromString("KEY=7:true")); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_BOOLEAN); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<bool>*)data.get())->GetValue(), true); + ASSERT_EQ(data->GetString(), "KEY=7:1"); +} + +TEST_F(LDFTests, LDFBoolFalseTest) { + LdfUniquePtr data(LDFBaseData::DataFromString("KEY=7:false")); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_BOOLEAN); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<bool>*)data.get())->GetValue(), false); + ASSERT_EQ(data->GetString(), "KEY=7:0"); +} + +TEST_F(LDFTests, LDFBoolIntTest) { + LdfUniquePtr data(LDFBaseData::DataFromString("KEY=7:3")); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_BOOLEAN); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<bool>*)data.get())->GetValue(), true); + ASSERT_EQ(data->GetString(), "KEY=7:1"); +} + +TEST_F(LDFTests, LDFU64Test) { + LdfUniquePtr data(LDFBaseData::DataFromString("KEY=8:15")); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_U64); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<uint64_t>*)data.get())->GetValue(), 15); + ASSERT_EQ(data->GetString(), "KEY=8:15"); +} + +TEST_F(LDFTests, LDFLWOOBJIDTest) { + LdfUniquePtr data(LDFBaseData::DataFromString("KEY=9:15")); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_OBJID); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<uint64_t>*)data.get())->GetValue(), 15); + ASSERT_EQ(data->GetString(), "KEY=9:15"); +} + +TEST_F(LDFTests, LDFUTF8Test) { + std::string testWord = "KEY=13:IAmA weird string with :::: and spac,./;'][\\es that I expect to be parsed correctly...; "; + LdfUniquePtr data(LDFBaseData::DataFromString(testWord)); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_8); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<std::string>*)data.get())->GetValue(), "IAmA weird string with :::: and spac,./;'][\\es that I expect to be parsed correctly...; "); + ASSERT_EQ(data->GetString(), testWord); +} + +TEST_F(LDFTests, LDFUTF8EmptyTest) { + std::string testWord = "KEY=13:"; + LdfUniquePtr data(LDFBaseData::DataFromString(testWord)); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_8); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<std::string>*)data.get())->GetValue(), ""); + ASSERT_EQ(data->GetString(), testWord); +} + +TEST_F(LDFTests, LDFUTF8ColonsTest) { + std::string testWord = "KEY=13:::"; + LdfUniquePtr data(LDFBaseData::DataFromString(testWord)); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_8); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<std::string>*)data.get())->GetValue(), "::"); + ASSERT_EQ(data->GetString(), testWord); +} +TEST_F(LDFTests, LDFUTF8EqualsTest) { + std::string testWord = "KEY=13:=="; + LdfUniquePtr data(LDFBaseData::DataFromString(testWord)); + ASSERT_NE(data, nullptr); + ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_8); + ASSERT_EQ(data->GetKey(), u"KEY"); + ASSERT_EQ(((LDFData<std::string>*)data.get())->GetValue(), "=="); + ASSERT_EQ(data->GetString(), testWord); +} + + +TEST_F(LDFTests, LDFParseEdgeCaseTest) { + std::vector<std::string> tests = { + // Test undefined data + "", // Empty + "=", // Only equals sign + ":", // Only colon + "=:", // Only colon and equals sign + + // Test no LDFType + "KEY=:", // No LDF Type + "KEY=:44", // No LDF Type, but has value + + // Test invalid values, but valid types + "key=1:", // no value for int32 + "key=1:banana", // invalid value for int32 + "key=3:", // No value for float + "key=3:banana", // invalid for float + "key=4:", // No value for double + "key=4:banana", // invalid for double + "key=5:", // No value for U32 + "key=5:banana", // invalid for U32 + "key=7:", // No value for bool + "key=7:banana", // invalid for bool + "key=8:", // No value for U64 + "key=8:banana", // invalid for U64 + "key=9:", // No value for LWOOBJID + "key=9:banana", // invalid for LWOOBJID + + // Test invalid LDF types + "key=14:value", // invalid LDF type + "key=-1:value", // invalid LDF type + "key=-2:value", // invalid LDF type (no enum definition) + "key=Garbage:value", // invalid LDF type + }; + for (auto testString : tests) { + Game::logger->Log("LDFTests", "Testing LDF Parsing of invalid string (%s)", testString.c_str()); + EXPECT_NO_THROW(LDFBaseData::DataFromString(testString)); + } +} + +#ifdef PERF_TEST + +TEST_F(LDFTests, LDFSpeedTest) { + std::string keyToTest = "KEY=0:IAmA weird string with :::: and s"; + for (int i = 0; i < 10000; i++) LDFBaseData::DataFromString(keyToTest); +} + +#endif //PERF diff --git a/tests/dCommonTests/dCommonDependencies.cpp b/tests/dCommonTests/dCommonDependencies.cpp new file mode 100644 index 00000000..5b25fd47 --- /dev/null +++ b/tests/dCommonTests/dCommonDependencies.cpp @@ -0,0 +1,7 @@ +#include "Game.h" + +class dLogger; +namespace Game +{ + dLogger* logger; +} // namespace Game diff --git a/tests/dCommonTests/dCommonDependencies.h b/tests/dCommonTests/dCommonDependencies.h new file mode 100644 index 00000000..12aeb938 --- /dev/null +++ b/tests/dCommonTests/dCommonDependencies.h @@ -0,0 +1,26 @@ +#ifndef __DCOMMONDEPENDENCIES__H__ +#define __DCOMMONDEPENDENCIES__H__ + +#include "Game.h" +#include "dLogger.h" +#include "dServer.h" +#include "EntityInfo.h" +#include "EntityManager.h" +#include "dConfig.h" +#include <gtest/gtest.h> + +class dCommonDependenciesTest : public ::testing::Test { +protected: + void SetUpDependencies() { + Game::logger = new dLogger("./testing.log", true, true); + } + + void TearDownDependencies() { + if (Game::logger) { + Game::logger->Flush(); + delete Game::logger; + } + } +}; + +#endif //!__DCOMMONDEPENDENCIES__H__ From 6aa90ad5b2dc536f4ab97814d9532092560747bf Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Tue, 2 May 2023 17:39:21 -0500 Subject: [PATCH 308/322] Breakout rest of the enums from dCommonVars and clean it up (#1061) * Breakout rest of the enums from dcommonvars so we don't have to deal with merge conflicts ePlayerFlags is not a scoped enum, yet, due to it's complexity * address feedback * make player flag types consistent * fix typo --- dCommon/Brick.h | 11 + dCommon/dEnums/dCommonVars.h | 398 ------------------ dCommon/dEnums/eBuildType.h | 12 + dCommon/dEnums/eCharacterCreationResponse.h | 14 + dCommon/dEnums/eCinematicEvent.h | 12 + dCommon/dEnums/eControlScheme.h | 18 + dCommon/dEnums/eCyclingMode.h | 11 + dCommon/dEnums/eGameActivity.h | 15 + dCommon/dEnums/eKillType.h | 11 + dCommon/dEnums/eLoginResponse.h | 24 ++ dCommon/dEnums/eLootSourceType.h | 31 ++ dCommon/dEnums/eMatchUpdate.h | 17 + dCommon/dEnums/eObjectWorldState.h | 12 + dCommon/dEnums/ePetTamingNotifyType.h | 15 + dCommon/dEnums/ePlayerFlag.h | 172 ++++++++ dCommon/dEnums/eQuickBuildFailReason.h | 13 + dCommon/dEnums/eRebuildState.h | 15 + dCommon/dEnums/eRenameResponse.h | 15 + dCommon/dEnums/eReplicaPacketType.h | 12 + dCommon/dEnums/eStateChangeType.h | 11 + dCommon/dEnums/eTerminateType.h | 12 + dCommon/dEnums/eUseItemResponse.h | 12 + dGame/Character.cpp | 19 +- dGame/Character.h | 5 +- dGame/Entity.cpp | 11 +- dGame/Entity.h | 3 + dGame/EntityManager.cpp | 13 +- dGame/TradingManager.cpp | 8 +- dGame/UserManager.cpp | 22 +- dGame/dBehaviors/ImmunityBehavior.cpp | 1 + dGame/dComponents/BaseCombatAIComponent.cpp | 4 +- dGame/dComponents/CharacterComponent.cpp | 3 +- dGame/dComponents/CharacterComponent.h | 8 +- .../ControllablePhysicsComponent.cpp | 1 + .../ControllablePhysicsComponent.h | 1 + dGame/dComponents/DestroyableComponent.cpp | 14 +- dGame/dComponents/DestroyableComponent.h | 1 + dGame/dComponents/InventoryComponent.cpp | 8 +- dGame/dComponents/InventoryComponent.h | 3 +- .../dComponents/LevelProgressionComponent.cpp | 2 +- dGame/dComponents/PetComponent.cpp | 32 +- dGame/dComponents/PetComponent.h | 2 +- dGame/dComponents/PossessorComponent.cpp | 4 +- .../PropertyManagementComponent.cpp | 8 +- dGame/dComponents/RacingControlComponent.cpp | 4 +- dGame/dComponents/RailActivatorComponent.cpp | 3 +- dGame/dComponents/RebuildComponent.cpp | 59 +-- dGame/dComponents/RebuildComponent.h | 6 +- .../RocketLaunchpadControlComponent.cpp | 3 +- .../dComponents/ScriptedActivityComponent.cpp | 17 +- dGame/dComponents/SwitchComponent.cpp | 2 +- dGame/dGameMessages/GameMessages.cpp | 84 ++-- dGame/dGameMessages/GameMessages.h | 34 +- dGame/dInventory/Item.cpp | 9 +- dGame/dInventory/Item.h | 7 +- dGame/dMission/Mission.cpp | 12 +- dGame/dUtilities/Loot.cpp | 4 +- dGame/dUtilities/Loot.h | 4 +- dGame/dUtilities/Mail.cpp | 4 +- dGame/dUtilities/SlashCommandHandler.cpp | 25 +- dNet/AuthPackets.cpp | 21 +- dNet/AuthPackets.h | 1 + dNet/WorldPackets.cpp | 3 +- dNet/WorldPackets.h | 4 +- .../02_server/Enemy/General/BaseEnemyApe.cpp | 3 +- .../02_server/Equipment/BootyDigServer.cpp | 4 +- .../02_server/Map/AG/AgCagedBricksServer.cpp | 3 +- dScripts/02_server/Map/AG/NpcCowboyServer.cpp | 2 +- dScripts/02_server/Map/AG/NpcPirateServer.cpp | 2 +- dScripts/02_server/Map/AG/NpcWispServer.cpp | 2 +- .../02_server/Map/AG/RemoveRentalGear.cpp | 3 +- dScripts/02_server/Map/AG/RemoveRentalGear.h | 1 - dScripts/02_server/Map/AM/AmBlueX.cpp | 2 +- dScripts/02_server/Map/AM/AmBridge.cpp | 2 +- dScripts/02_server/Map/AM/AmDrawBridge.cpp | 3 +- .../02_server/Map/AM/AmDropshipComputer.cpp | 8 +- .../Map/AM/AmShieldGeneratorQuickbuild.cpp | 2 +- dScripts/02_server/Map/AM/AmSkullkinDrill.cpp | 5 +- dScripts/02_server/Map/AM/AmTeapotServer.cpp | 3 +- .../02_server/Map/FV/ImgBrickConsoleQB.cpp | 19 +- .../Map/FV/Racing/RaceMaelstromGeiser.cpp | 2 +- .../02_server/Map/GF/GfCaptainsCannon.cpp | 4 +- dScripts/02_server/Map/GF/GfTikiTorch.cpp | 3 +- dScripts/02_server/Map/GF/MastTeleport.cpp | 1 + .../Ninjago/NjRailActivatorsServer.cpp | 2 +- .../Map/General/Ninjago/NjRailPostServer.cpp | 4 +- .../Ninjago/NjhubLavaPlayerDeathTrigger.cpp | 2 +- .../02_server/Map/General/PetDigServer.cpp | 6 +- .../Map/General/PropertyPlatform.cpp | 2 +- .../Map/General/TokenConsoleServer.cpp | 12 +- .../Map/General/WishingWellServer.cpp | 1 + .../02_server/Map/NS/NsTokenConsoleServer.cpp | 18 +- .../02_server/Map/NT/NtAssemblyTubeServer.cpp | 1 + .../02_server/Map/NT/NtDirtCloudServer.cpp | 2 +- dScripts/02_server/Map/NT/NtDukeServer.cpp | 5 +- dScripts/02_server/Map/NT/NtHaelServer.cpp | 3 +- .../Map/NT/NtImagimeterVisibility.cpp | 3 +- .../02_server/Map/NT/NtOverbuildServer.cpp | 3 +- .../02_server/Map/NT/NtParadoxPanelServer.cpp | 2 + .../02_server/Map/NT/NtParadoxTeleServer.cpp | 1 + .../Map/NT/NtVentureCannonServer.cpp | 4 +- .../02_server/Map/PR/SpawnGryphonServer.cpp | 3 +- .../Map/Property/AG_Small/ZoneAgProperty.cpp | 2 +- .../Map/Property/NS_Med/ZoneNsMedProperty.cpp | 4 +- .../02_server/Map/VE/VeBricksampleServer.cpp | 2 +- dScripts/02_server/Map/VE/VeEpsilonServer.h | 2 +- .../02_server/Map/VE/VeMissionConsole.cpp | 7 +- .../Map/njhub/CatapultBaseServer.cpp | 2 +- .../02_server/Map/njhub/CavePrisonCage.cpp | 2 +- .../Map/njhub/ImaginationShrineServer.cpp | 2 +- dScripts/02_server/Map/njhub/NjColeNPC.cpp | 2 +- .../Map/njhub/NjDragonEmblemChestServer.cpp | 3 +- .../Map/njhub/NjGarmadonCelebration.cpp | 5 +- .../Map/njhub/NjNPCMissionSpinjitzuServer.h | 11 +- .../Map/njhub/NjScrollChestServer.cpp | 2 +- dScripts/02_server/Map/njhub/NjWuNPC.cpp | 5 +- .../boss_instance/NjMonastryBossInstance.cpp | 8 +- dScripts/02_server/Pets/DamagingPets.cpp | 11 +- dScripts/02_server/Pets/DamagingPets.h | 2 +- dScripts/02_server/Pets/PetFromDigServer.cpp | 13 +- dScripts/02_server/Pets/PetFromDigServer.h | 2 +- .../02_server/Pets/PetFromObjectServer.cpp | 15 +- dScripts/02_server/Pets/PetFromObjectServer.h | 2 +- dScripts/BaseConsoleTeleportServer.cpp | 6 +- dScripts/BasePropertyServer.cpp | 6 +- dScripts/ChooseYourDestinationNsToNt.cpp | 3 +- dScripts/CppScripts.h | 4 +- .../EquipmentScripts/PersonalFortress.cpp | 1 + dScripts/EquipmentScripts/StunImmunity.cpp | 1 + dScripts/NPCAddRemoveItem.cpp | 2 +- dScripts/NtFactionSpyServer.cpp | 6 +- dScripts/NtFactionSpyServer.h | 2 +- dScripts/SpawnPetBaseServer.cpp | 3 +- dScripts/ai/ACT/ActMine.cpp | 2 +- dScripts/ai/ACT/ActVehicleDeathTrigger.cpp | 2 +- .../ai/ACT/FootRace/BaseFootRaceManager.cpp | 2 +- dScripts/ai/AG/AgPicnicBlanket.cpp | 3 +- dScripts/ai/AG/AgQbElevator.cpp | 2 +- dScripts/ai/AG/AgShipPlayerShockServer.cpp | 1 + dScripts/ai/FV/ActNinjaTurret.cpp | 5 +- dScripts/ai/FV/ActParadoxPipeFix.cpp | 4 +- dScripts/ai/FV/FvBrickPuzzleServer.cpp | 4 +- dScripts/ai/FV/FvConsoleLeftQuickbuild.cpp | 8 +- dScripts/ai/FV/FvConsoleRightQuickbuild.cpp | 8 +- dScripts/ai/FV/FvDragonSmashingGolemQb.cpp | 3 +- dScripts/ai/FV/FvFacilityBrick.cpp | 2 +- dScripts/ai/FV/FvPandaServer.cpp | 11 +- dScripts/ai/FV/FvPandaServer.h | 2 +- ...nceExitTransferPlayerToLastNonInstance.cpp | 1 + dScripts/ai/GENERAL/LegoDieRoll.cpp | 2 +- dScripts/ai/GF/GfJailWalls.cpp | 3 +- dScripts/ai/GF/PetDigBuild.cpp | 2 +- dScripts/ai/GF/PirateRep.cpp | 3 +- .../ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp | 5 +- dScripts/ai/NS/NsConcertInstrument.cpp | 8 +- dScripts/ai/NS/NsConcertQuickBuild.cpp | 2 +- dScripts/ai/NS/NsGetFactionMissionServer.cpp | 5 +- dScripts/ai/SPEC/SpecialCoinSpawner.cpp | 2 +- dScripts/client/ai/PR/CrabServer.cpp | 13 +- dScripts/client/ai/PR/CrabServer.h | 2 +- .../DestroyableComponentTests.cpp | 1 + 161 files changed, 960 insertions(+), 776 deletions(-) create mode 100644 dCommon/Brick.h create mode 100644 dCommon/dEnums/eBuildType.h create mode 100644 dCommon/dEnums/eCharacterCreationResponse.h create mode 100644 dCommon/dEnums/eCinematicEvent.h create mode 100644 dCommon/dEnums/eControlScheme.h create mode 100644 dCommon/dEnums/eCyclingMode.h create mode 100644 dCommon/dEnums/eGameActivity.h create mode 100644 dCommon/dEnums/eKillType.h create mode 100644 dCommon/dEnums/eLoginResponse.h create mode 100644 dCommon/dEnums/eLootSourceType.h create mode 100644 dCommon/dEnums/eMatchUpdate.h create mode 100644 dCommon/dEnums/eObjectWorldState.h create mode 100644 dCommon/dEnums/ePetTamingNotifyType.h create mode 100644 dCommon/dEnums/ePlayerFlag.h create mode 100644 dCommon/dEnums/eQuickBuildFailReason.h create mode 100644 dCommon/dEnums/eRebuildState.h create mode 100644 dCommon/dEnums/eRenameResponse.h create mode 100644 dCommon/dEnums/eReplicaPacketType.h create mode 100644 dCommon/dEnums/eStateChangeType.h create mode 100644 dCommon/dEnums/eTerminateType.h create mode 100644 dCommon/dEnums/eUseItemResponse.h diff --git a/dCommon/Brick.h b/dCommon/Brick.h new file mode 100644 index 00000000..e8bd747e --- /dev/null +++ b/dCommon/Brick.h @@ -0,0 +1,11 @@ +#ifndef __BRICK__H__ +#define __BRICK__H__ + +#include <cstdint> + +struct Brick { + uint32_t designerID; + uint32_t materialID; +}; + +#endif //!__BRICK__H__ diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index ff8ec836..26201c3d 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -10,8 +10,6 @@ #pragma warning (disable:4251) //Disables SQL warnings -typedef int RESTICKET; - // These are the same define, but they mean two different things in different contexts // so a different define to distinguish what calculation is happening will help clarity. #define FRAMES_TO_MS(x) 1000 / x @@ -45,23 +43,16 @@ typedef uint16_t LWOINSTANCEID; //!< Used for Instance IDs typedef uint32_t PROPERTYCLONELIST; //!< Used for Property Clone IDs typedef uint32_t StripId; -typedef int32_t PetTamingPiece; //!< Pet Taming Pieces - 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_INVALID = -1; //!< Invalid Inventory -const uint32_t INVENTORY_DEFAULT = -1; //!< Default Inventory -const uint32_t StatusChangeInfo = 0; //!< Status Change Info (???) 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 -typedef std::set<LWOOBJID> TSetObjID; - const float PI = 3.14159f; //============ STRUCTS ============== @@ -164,393 +155,4 @@ public: } }; -struct Brick { - uint32_t designerID; - uint32_t materialID; -}; - -//This union is used by the behavior system -union suchar { - unsigned char usigned; - char svalue; -}; - -//=========== LU ENUMS ============ - -//! An enum for MatchUpdate types -enum eMatchUpdate : int { - MATCH_UPDATE_PLAYER_JOINED = 0, - MATCH_UPDATE_PLAYER_LEFT = 1, - MATCH_UPDATE_TIME = 3, - MATCH_UPDATE_TIME_START_DELAY = 4, - MATCH_UPDATE_PLAYER_READY = 5, - MATCH_UPDATE_PLAYER_UNREADY = 6 -}; - -//! An enum for camera cycling modes -enum eCyclingMode : uint32_t { - ALLOW_CYCLE_TEAMMATES, - DISALLOW_CYCLING -}; - -enum eCinematicEvent : uint32_t { - STARTED, - WAYPOINT, - ENDED, -}; - -//! An enum for character creation responses -enum eCreationResponse : uint8_t { - CREATION_RESPONSE_SUCCESS = 0, //!< The creation was successful - CREATION_RESPONSE_OBJECT_ID_UNAVAILABLE, //!< The Object ID can't be used - CREATION_RESPONSE_NAME_NOT_ALLOWED, //!< The name is not allowed - CREATION_RESPONSE_PREDEFINED_NAME_IN_USE, //!< The predefined name is already in use - CREATION_RESPONSE_CUSTOM_NAME_IN_USE //!< The custom name is already in use -}; - -//! An enum for login responses -enum eLoginResponse : uint8_t { - LOGIN_RESPONSE_GENERAL_FAILED = 0, - LOGIN_RESPONSE_SUCCESS = 1, - LOGIN_RESPONSE_BANNED = 2, - LOGIN_RESPONSE_PERMISSIONS_NOT_HIGH_ENOUGH = 5, - LOGIN_RESPONSE_WRONG_PASS_OR_USER = 6, - LOGIN_RESPONSE_ACCOUNT_LOCKED = 7 -}; - -//! An enum for character rename responses -enum eRenameResponse : uint8_t { - RENAME_RESPONSE_SUCCESS = 0, //!< The renaming was successful - RENAME_RESPONSE_UNKNOWN_ERROR, //!< There was an unknown error - RENAME_RESPONSE_NAME_UNAVAILABLE, //!< The name is unavailable - RENAME_RESPONSE_NAME_IN_USE //!< The name is already in use -}; - -//! A replica packet type -enum eReplicaPacketType { - PACKET_TYPE_CONSTRUCTION, //!< A construction packet - PACKET_TYPE_SERIALIZATION, //!< A serialization packet - PACKET_TYPE_DESTRUCTION //!< A destruction packet -}; - -//! The Behavior Types for use with the AI system -enum eCombatBehaviorTypes : uint32_t { - PASSIVE = 0, //!< The object is passive - AGGRESSIVE = 1, //!< The object is aggressive - PASSIVE_TURRET = 2, //!< The object is a passive turret - AGGRESSIVE_TURRET = 3 //!< The object is an aggressive turret -}; - -//! The Combat Role Type for use with the AI system -enum eCombatRoleType : uint32_t { - MELEE = 0, //!< Used for melee attacks - RANGED = 1, //!< Used for range attacks - SUPPORT = 2 //!< Used for support -}; - -//! The kill types for the Die packet -enum eKillType : uint32_t { - VIOLENT, - SILENT -}; - -//! The various world states used throughout the server -enum eObjectWorldState { - WORLDSTATE_INWORLD, //!< Probably used when the object is in the world - WORLDSTATE_ATTACHED, //!< Probably used when the object is attached to another object - WORLDSTATE_INVENTORY //!< Probably used when the object is in an inventory -}; - -//! The trigger stats (???) -enum eTriggerStat { - INVALID_STAT, //!< ??? - HEALTH, //!< Probably used for health - ARMOR, //!< Probably used for armor - IMAGINATION //!< Probably used for imagination -}; - -//! The trigger operations (???) -enum eTriggerOperator { - INVALID_OPER, //!< ??? - EQUAL, //!< ??? - NOT_EQUAL, //!< ??? - GREATER, //!< ??? - GREATER_EQUAL, //!< ??? - LESS, //!< ??? - LESS_EQUAL //!< ??? -}; - -//! The various build types -enum eBuildType { - BUILD_NOWHERE, //!< Used if something can't be built anywhere - BUILD_IN_WORLD, //!< Used if something can be built in the world - BUILD_ON_PROPERTY //!< Used if something can be build on a property -}; - -//! Quickbuild fail reasons -enum eFailReason : uint32_t { - REASON_NOT_GIVEN, - REASON_OUT_OF_IMAGINATION, - REASON_CANCELED_EARLY, - REASON_BUILD_ENDED -}; - -//! Terminate interaction type -enum eTerminateType : uint32_t { - RANGE, - USER, - FROM_INTERACTION -}; - -//! The combat state -enum eCombatState { - IDLE, //!< The AI is in an idle state - AGGRO, //!< The AI is in an aggressive state - TETHER, //!< The AI is being redrawn back to tether point - SPAWN, //!< The AI is spawning - DEAD //!< The AI is dead -}; - -enum eControlSceme { - SCHEME_A, - SCHEME_D, - SCHEME_GAMEPAD, - SCHEME_E, - SCHEME_FPS, - SCHEME_DRIVING, - SCHEME_TAMING, - SCHEME_MODULAR_BUILD, - SCHEME_WEAR_A_ROBOT //== freecam? -}; - -enum class eStateChangeType : uint32_t { - PUSH, - POP -}; - -enum eNotifyType { - NOTIFY_TYPE_SUCCESS, - NOTIFY_TYPE_QUIT, - NOTIFY_TYPE_FAILED, - NOTIFY_TYPE_BEGIN, - NOTIFY_TYPE_READY, - NOTIFY_TYPE_NAMINGPET -}; - - -enum class UseItemResponse : uint32_t { - NoImaginationForPet = 1, - FailedPrecondition, - MountsNotAllowed -}; - -enum eRebuildState : uint32_t { - REBUILD_OPEN, - REBUILD_COMPLETED = 2, - REBUILD_RESETTING = 4, - REBUILD_BUILDING, - REBUILD_INCOMPLETE -}; - -/** - * The loot source's type. - */ -enum eLootSourceType : int32_t { - LOOT_SOURCE_NONE = 0, - LOOT_SOURCE_CHEST, - LOOT_SOURCE_MISSION, - LOOT_SOURCE_MAIL, - LOOT_SOURCE_CURRENCY, - LOOT_SOURCE_ACHIEVEMENT, - LOOT_SOURCE_TRADE, - LOOT_SOURCE_QUICKBUILD, - LOOT_SOURCE_DELETION, - LOOT_SOURCE_VENDOR, - LOOT_SOURCE_ACTIVITY, - LOOT_SOURCE_PICKUP, - LOOT_SOURCE_BRICK, - LOOT_SOURCE_PROPERTY, - LOOT_SOURCE_MODERATION, - LOOT_SOURCE_EXHIBIT, - LOOT_SOURCE_INVENTORY, - LOOT_SOURCE_CLAIMCODE, - LOOT_SOURCE_CONSUMPTION, - LOOT_SOURCE_CRAFTING, - LOOT_SOURCE_LEVEL_REWARD, - LOOT_SOURCE_RELOCATE -}; - -enum eGameActivities : uint32_t { - ACTIVITY_NONE, - ACTIVITY_QUICKBUILDING, - ACTIVITY_SHOOTING_GALLERY, - ACTIVITY_RACING, - ACTIVITY_PINBALL, - ACTIVITY_PET_TAMING -}; - -enum ePlayerFlags { - BTARR_TESTING = 0, - PLAYER_HAS_ENTERED_PET_RANCH = 1, - MINIMAP_UNLOCKED = 2, - ACTIVITY_REBUILDING_FAIL_TIME = 3, - ACTIVITY_REBUILDING_FAIL_RANGE = 4, - ACTIVITY_SHOOTING_GALLERY_HELP = 5, - HELP_WALKING_CONTROLS = 6, - FIRST_SMASHABLE = 7, - FIRST_IMAGINATION_PICKUP = 8, - FIRST_DAMAGE = 9, - FIRST_ITEM = 10, - FIRST_BRICK = 11, - FIRST_CONSUMABLE = 12, - FIRST_EQUIPPABLE = 13, - CHAT_HELP = 14, - FIRST_PET_TAMING_MINIGAME = 15, - FIRST_PET_ON_SWITCH = 16, - FIRST_PET_JUMPED_ON_SWITCH = 17, - FIRST_PET_FOUND_TREASURE = 18, - FIRST_PET_DUG_TREASURE = 19, - FIRST_PET_OWNER_ON_PET_BOUNCER = 20, - FIRST_PET_DESPAWN_NO_IMAGINATION = 21, - FIRST_PET_SELECTED_ENOUGH_BRICKS = 22, - FIRST_EMOTE_UNLOCKED = 23, - GF_PIRATE_REP = 24, - AG_BOB_CINEMATIC_EVENT = 25, - HELP_JUMPING_CONTROLS = 26, - HELP_DOUBLE_JUMP_CONTROLS = 27, - HELP_CAMERA_CONTROLS = 28, - HELP_ROTATE_CONTROLS = 29, - HELP_SMASH = 30, - MONUMENT_INTRO_MUSIC_PLAYED = 31, - BEGINNING_ZONE_SUMMARY_DISPLAYED = 32, - AG_FINISH_LINE_BUILT = 33, - AG_BOSS_AREA_FOUND = 34, - AG_LANDED_IN_BATTLEFIELD = 35, - GF_PLAYER_HAS_BEEN_TO_THE_RAVINE = 36, - MODULAR_BUILD_STARTED = 37, - MODULAR_BUILD_FINISHED_CLICK_BUTTON = 38, - THINKING_HAT_RECEIVED_GO_TO_MODULAR_BUILD_AREA = 39, - BUILD_AREA_ENTERED_MOD_NOT_ACTIVATED_PUT_ON_HAT = 40, - HAT_ON_INSIDE_OF_MOD_BUILD_EQUIP_A_MODULE_FROM_LEG = 41, - MODULE_EQUIPPED_PLACE_ON_GLOWING_BLUE_SPOT = 42, - FIRST_MODULE_PLACED_CORRECTLY_NOW_DO_THE_REST = 43, - ROCKET_COMPLETE_NOW_LAUNCH_FROM_PAD = 44, - JOINED_A_FACTION = 45, - VENTURE_FACTION = 46, - ASSEMBLY_FACTION = 47, - PARADOX_FACTION = 48, - SENTINEL_FACTION = 49, - LUP_WORLD_ACCESS = 50, - AG_FIRST_FLAG_COLLECTED = 51, - TOOLTIP_TALK_TO_SKYLAND_TO_GET_HAT = 52, - MODULAR_BUILD_PLAYER_PLACES_FIRST_MODEL_IN_SCRATCH = 53, - MODULAR_BUILD_FIRST_ARROW_DISPLAY_FOR_MODULE = 54, - AG_BEACON_QB_SO_THE_PLAYER_CAN_ALWAYS_BUILD_THEM = 55, - GF_PET_DIG_FLAG_1 = 56, - GF_PET_DIG_FLAG_2 = 57, - GF_PET_DIG_FLAG_3 = 58, - SUPPRESS_SPACESHIP_CINEMATIC_FLYTHROUGH = 59, - GF_PLAYER_FALL_DEATH = 60, - GF_PLAYER_CAN_GET_FLAG_1 = 61, - GF_PLAYER_CAN_GET_FLAG_2 = 62, - GF_PLAYER_CAN_GET_FLAG_3 = 63, - ENTER_BBB_FROM_PROPERTY_EDIT_CONFIRMATION_DIALOG = 64, - AG_FIRST_COMBAT_COMPLETE = 65, - AG_COMPLETE_BOB_MISSION = 66, - IS_NEWS_SCREEN_VISIBLE = 114, - NJ_GARMADON_CINEMATIC_SEEN = 125, - ELEPHANT_PET_3050 = 801, - CAT_PET_3054 = 802, - TRICERATOPS_PET_3195 = 803, - TERRIER_PET_3254 = 804, - SKUNK_PET_3261 = 805, - LION_PET_3520 = 806, - BUNNY_PET_3672 = 807, - CROCODILE_PET_3994 = 808, - DOBERMAN_PET_5635 = 809, - BUFFALO_PET_5636 = 810, - ROBOT_DOG_PET_5637 = 811, - EUROPEAN_DRAGON_PET_5639 = 812, - TORTOISE_PET_5640 = 813, - ASIAN_DRAGON_PET_5641 = 814, - MANTIS_PET_5642 = 815, - PANDA_PET_5643 = 816, - WARTHOG_PET_6720 = 817, - GOAT_PET_7638 = 818, - CRAB_PET_7694 = 819, - AG_SPACE_SHIP_BINOC_AT_LAUNCH = 1001, - AG_SPACE_SHIP_BINOC_AT_LAUNCH_PLATFORM = 1002, - AG_SPACE_SHIP_BINOC_ON_PLATFORM_TO_LEFT_OF_START = 1003, - AG_SPACE_SHIP_BINOC_ON_PLATFORM_TO_RIGHT_OF_START = 1004, - AG_SPACE_SHIP_BINOC_AT_BOB = 1005, - AG_BATTLE_BINOC_FOR_TRICERETOPS = 1101, - AG_BATTLE_BINOC_AT_PARADOX = 1102, - AG_BATTLE_BINOC_AT_MISSION_GIVER = 1103, - AG_BATTLE_BINOC_AT_BECK = 1104, - AG_MONUMENT_BINOC_INTRO = 1105, - AG_MONUMENT_BINOC_OUTRO = 1106, - AG_LAUNCH_BINOC_INTRO = 1107, - AG_LAUNCH_BINOC_BISON = 1108, - AG_LAUNCH_BINOC_SHARK = 1109, - NS_BINOC_CONCERT_TRANSITION = 1201, - NS_BINOC_RACE_PLACE_TRANSITION = 1202, - NS_BINOC_BRICK_ANNEX_TRANSITION = 1203, - NS_BINOC_GF_LAUNCH = 1204, - NS_BINOC_FV_LAUNCH = 1205, - NS_BINOC_BRICK_ANNEX_WATER = 1206, - NS_BINOC_AG_LAUNCH_AT_RACE_PLACE = 1207, - NS_BINOC_AG_LAUNCH_AT_BRICK_ANNEX = 1208, - NS_BINOC_AG_LAUNCH_AT_PLAZA = 1209, - NS_BINOC_TBA = 1210, - NS_FLAG_COLLECTABLE_1_BY_JONNY_THUNDER = 1211, - NS_FLAG_COLLECTABLE_2_UNDER_CONCERT_BRIDGE = 1212, - NS_FLAG_COLLECTABLE_3_BY_FV_LAUNCH = 1213, - NS_FLAG_COLLECTABLE_4_IN_PLAZA_BEHIND_BUILDING = 1214, - NS_FLAG_COLLECTABLE_5_BY_GF_LAUNCH = 1215, - NS_FLAG_COLLECTABLE_6_BY_DUCK_SG = 1216, - NS_FLAG_COLLECTABLE_7_BY_LUP_LAUNCH = 1217, - NS_FLAG_COLLECTABLE_8_BY_NT_LUANCH = 1218, - NS_FLAG_COLLECTABLE_9_BY_RACE_BUILD = 1219, - NS_FLAG_COLLECTABLE_10_ON_AG_LAUNCH_PATH = 1220, - PR_BINOC_AT_LAUNCH_PAD = 1251, - PR_BINOC_AT_BEGINNING_OF_ISLAND_B = 1252, - PR_BINOC_AT_FIRST_PET_BOUNCER = 1253, - PR_BINOC_ON_BY_CROWS_NEST = 1254, - PR_PET_DIG_AT_BEGINNING_OF_ISLAND_B = 1261, - PR_PET_DIG_AT_THE_LOCATION_OF_OLD_BOUNCE_BACK = 1262, - PR_PET_DIG_UNDER_QB_BRIDGE = 1263, - PR_PET_DIG_BACK_SIDE_BY_PARTNER_BOUNCE = 1264, - PR_PET_DIG_BY_LAUNCH_PAD = 1265, - PR_PET_DIG_BY_FIRST_PET_BOUNCER = 1266, - GF_BINOC_ON_LANDING_PAD = 1301, - GF_BINOC_AT_RAVINE_START = 1302, - GF_BINOC_ON_TOP_OF_RAVINE_HEAD = 1303, - GF_BINOC_AT_TURTLE_AREA = 1304, - GF_BINOC_IN_TUNNEL_TO_ELEPHANTS = 1305, - GF_BINOC_IN_ELEPHANTS_AREA = 1306, - GF_BINOC_IN_RACING_AREA = 1307, - GF_BINOC_IN_CROC_AREA = 1308, - GF_BINOC_IN_JAIL_AREA = 1309, - GF_BINOC_TELESCOPE_NEXT_TO_CAPTAIN_JACK = 1310, - NT_PLINTH_REBUILD = 1919, - NT_FACTION_SPY_DUKE = 1974, - NT_FACTION_SPY_OVERBUILD = 1976, - NT_FACTION_SPY_HAEL = 1977, - NJ_EARTH_SPINJITZU = 2030, - NJ_LIGHTNING_SPINJITZU = 2031, - NJ_ICE_SPINJITZU = 2032, - NJ_FIRE_SPINJITZU = 2033, - NJ_WU_SHOW_DAILY_CHEST = 2099 -}; - -//======== FUNC =========== - -template<typename T> -inline T const& clamp(const T& val, const T& low, const T& high) { - if (val < low) return low; - else if (val > high) return high; - - return val; -} - #endif //!__DCOMMONVARS__H__ diff --git a/dCommon/dEnums/eBuildType.h b/dCommon/dEnums/eBuildType.h new file mode 100644 index 00000000..f28f43cc --- /dev/null +++ b/dCommon/dEnums/eBuildType.h @@ -0,0 +1,12 @@ +#ifndef __EBUILDTYPE__H__ +#define __EBUILDTYPE__H__ + +#include <cstdint> + +enum class eBuildType :uint32_t { + NOWHERE, + IN_WORLD, + ON_PROPERTY +}; + +#endif //!__EBUILDTYPE__H__ diff --git a/dCommon/dEnums/eCharacterCreationResponse.h b/dCommon/dEnums/eCharacterCreationResponse.h new file mode 100644 index 00000000..da1ec0f2 --- /dev/null +++ b/dCommon/dEnums/eCharacterCreationResponse.h @@ -0,0 +1,14 @@ +#ifndef __ECHARACTERCREATIONRESPONSE__H__ +#define __ECHARACTERCREATIONRESPONSE__H__ + +#include <cstdint> + +enum class eCharacterCreationResponse : uint8_t { + SUCCESS = 0, + OBJECT_ID_UNAVAILABLE, + NAME_NOT_ALLOWED, + PREDEFINED_NAME_IN_USE, + CUSTOM_NAME_IN_USE +}; + +#endif //!__ECHARACTERCREATIONRESPONSE__H__ diff --git a/dCommon/dEnums/eCinematicEvent.h b/dCommon/dEnums/eCinematicEvent.h new file mode 100644 index 00000000..7fb82ca7 --- /dev/null +++ b/dCommon/dEnums/eCinematicEvent.h @@ -0,0 +1,12 @@ +#ifndef __ECINEMATICEVENT__H__ +#define __ECINEMATICEVENT__H__ + +#include <cstdint> + +enum class eCinematicEvent : uint32_t { + STARTED, + WAYPOINT, + ENDED, +}; + +#endif //!__ECINEMATICEVENT__H__ diff --git a/dCommon/dEnums/eControlScheme.h b/dCommon/dEnums/eControlScheme.h new file mode 100644 index 00000000..f7585ebb --- /dev/null +++ b/dCommon/dEnums/eControlScheme.h @@ -0,0 +1,18 @@ +#ifndef __ECONTROLSCHEME__H__ +#define __ECONTROLSCHEME__H__ + +#include <cstdint> + +enum class eControlScheme : uint32_t { + SCHEME_A, + SCHEME_D, + SCHEME_GAMEPAD, + SCHEME_E, + SCHEME_FPS, + SCHEME_DRIVING, + SCHEME_TAMING, + SCHEME_MODULAR_BUILD, + SCHEME_WEAR_A_ROBOT //== freecam? +}; + +#endif //!__ECONTROLSCHEME__H__ diff --git a/dCommon/dEnums/eCyclingMode.h b/dCommon/dEnums/eCyclingMode.h new file mode 100644 index 00000000..b5e3248b --- /dev/null +++ b/dCommon/dEnums/eCyclingMode.h @@ -0,0 +1,11 @@ +#ifndef __ECYCLINGMODE__H__ +#define __ECYCLINGMODE__H__ + +#include <cstdint> + +enum class eCyclingMode : uint32_t { + ALLOW_CYCLE_TEAMMATES, + DISALLOW_CYCLING +}; + +#endif //!__ECYCLINGMODE__H__ diff --git a/dCommon/dEnums/eGameActivity.h b/dCommon/dEnums/eGameActivity.h new file mode 100644 index 00000000..16b75380 --- /dev/null +++ b/dCommon/dEnums/eGameActivity.h @@ -0,0 +1,15 @@ +#ifndef __EGAMEACTIVITY__H__ +#define __EGAMEACTIVITY__H__ + +#include <cstdint> + +enum class eGameActivity : uint32_t { + NONE, + QUICKBUILDING, + SHOOTING_GALLERY, + RACING, + PINBALL, + PET_TAMING +}; + +#endif //!__EGAMEACTIVITY__H__ diff --git a/dCommon/dEnums/eKillType.h b/dCommon/dEnums/eKillType.h new file mode 100644 index 00000000..fe3908c8 --- /dev/null +++ b/dCommon/dEnums/eKillType.h @@ -0,0 +1,11 @@ +#ifndef __EKILLTYPE__H__ +#define __EKILLTYPE__H__ + +#include <cstdint> + +enum class eKillType : uint32_t { + VIOLENT, + SILENT +}; + +#endif //!__EKILLTYPE__H__ diff --git a/dCommon/dEnums/eLoginResponse.h b/dCommon/dEnums/eLoginResponse.h new file mode 100644 index 00000000..01bba3d5 --- /dev/null +++ b/dCommon/dEnums/eLoginResponse.h @@ -0,0 +1,24 @@ +#ifndef __ELOGINRESPONSE__H__ +#define __ELOGINRESPONSE__H__ + +#include <cstdint> + +enum class eLoginResponse : uint8_t { + GENERAL_FAILED = 0, + SUCCESS, + BANNED, + // Unused 3 + // Unused 4 + PERMISSIONS_NOT_HIGH_ENOUGH = 5, + INVALID_USER, + ACCOUNT_LOCKED, + WRONG_PASS, + ACCOUNT_ACTIVATION_PENDING, + ACCOUNT_DISABLED, + GAME_TIME_EXPIRED, + FREE_TRIAL_ENDED, + PLAY_SCHEDULE_TIME_UP, + ACCOUNT_NOT_ACTIVATED +}; + +#endif //!__ELOGINRESPONSE__H__ diff --git a/dCommon/dEnums/eLootSourceType.h b/dCommon/dEnums/eLootSourceType.h new file mode 100644 index 00000000..b8ecca4a --- /dev/null +++ b/dCommon/dEnums/eLootSourceType.h @@ -0,0 +1,31 @@ +#ifndef __ELOOTSOURCETYPE__H__ +#define __ELOOTSOURCETYPE__H__ + +#include <cstdint> + +enum class eLootSourceType : uint32_t { + NONE = 0, + CHEST, + MISSION, + MAIL, + CURRENCY, + ACHIEVEMENT, + TRADE, + QUICKBUILD, + DELETION, + VENDOR, + ACTIVITY, + PICKUP, + BRICK, + PROPERTY, + MODERATION, + EXHIBIT, + INVENTORY, + CLAIMCODE, + CONSUMPTION, + CRAFTING, + LEVEL_REWARD, + RELOCATE +}; + +#endif //!__ELOOTSOURCETYPE__H__ diff --git a/dCommon/dEnums/eMatchUpdate.h b/dCommon/dEnums/eMatchUpdate.h new file mode 100644 index 00000000..a42eecd3 --- /dev/null +++ b/dCommon/dEnums/eMatchUpdate.h @@ -0,0 +1,17 @@ +#ifndef __EMATCHUPDATE__H__ +#define __EMATCHUPDATE__H__ + +#include <cstdint> + +enum class eMatchUpdate : int32_t { + PLAYER_ADDED = 0, + PLAYER_REMOVED, + PHASE_CREATED, + PHASE_WAIT_READY, + PHASE_WAIT_START, + PLAYER_READY, + PLAYER_NOT_READY, + PLAYER_UPDATE +}; + +#endif //!__EMATCHUPDATE__H__ diff --git a/dCommon/dEnums/eObjectWorldState.h b/dCommon/dEnums/eObjectWorldState.h new file mode 100644 index 00000000..9735a072 --- /dev/null +++ b/dCommon/dEnums/eObjectWorldState.h @@ -0,0 +1,12 @@ +#ifndef __EOBJECTWORLDSTATE__H__ +#define __EOBJECTWORLDSTATE__H__ + +#include <cstdint> + +enum class eObjectWorldState : uint32_t { + INWORLD, + ATTACHED, + INVENTORY +}; + +#endif //!__EOBJECTWORLDSTATE__H__ diff --git a/dCommon/dEnums/ePetTamingNotifyType.h b/dCommon/dEnums/ePetTamingNotifyType.h new file mode 100644 index 00000000..564e932f --- /dev/null +++ b/dCommon/dEnums/ePetTamingNotifyType.h @@ -0,0 +1,15 @@ +#ifndef __EPETTAMINGNOTIFYTYPE__H__ +#define __EPETTAMINGNOTIFYTYPE__H__ + +#include <cstdint> + +enum class ePetTamingNotifyType : uint32_t { + SUCCESS, + QUIT, + FAILED, + BEGIN, + READY, + NAMINGPET +}; + +#endif //!__EPETTAMINGNOTIFYTYPE__H__ diff --git a/dCommon/dEnums/ePlayerFlag.h b/dCommon/dEnums/ePlayerFlag.h new file mode 100644 index 00000000..fefdfb67 --- /dev/null +++ b/dCommon/dEnums/ePlayerFlag.h @@ -0,0 +1,172 @@ +#ifndef __EPLAYERFLAG__H__ +#define __EPLAYERFLAG__H__ + +#include <cstdint> + +enum ePlayerFlag : int32_t { + BTARR_TESTING = 0, + PLAYER_HAS_ENTERED_PET_RANCH = 1, + MINIMAP_UNLOCKED = 2, + ACTIVITY_REBUILDING_FAIL_TIME = 3, + ACTIVITY_REBUILDING_FAIL_RANGE = 4, + ACTIVITY_SHOOTING_GALLERY_HELP = 5, + HELP_WALKING_CONTROLS = 6, + FIRST_SMASHABLE = 7, + FIRST_IMAGINATION_PICKUP = 8, + FIRST_DAMAGE = 9, + FIRST_ITEM = 10, + FIRST_BRICK = 11, + FIRST_CONSUMABLE = 12, + FIRST_EQUIPPABLE = 13, + CHAT_HELP = 14, + FIRST_PET_TAMING_MINIGAME = 15, + FIRST_PET_ON_SWITCH = 16, + FIRST_PET_JUMPED_ON_SWITCH = 17, + FIRST_PET_FOUND_TREASURE = 18, + FIRST_PET_DUG_TREASURE = 19, + FIRST_PET_OWNER_ON_PET_BOUNCER = 20, + FIRST_PET_DESPAWN_NO_IMAGINATION = 21, + FIRST_PET_SELECTED_ENOUGH_BRICKS = 22, + FIRST_EMOTE_UNLOCKED = 23, + GF_PIRATE_REP = 24, + AG_BOB_CINEMATIC_EVENT = 25, + HELP_JUMPING_CONTROLS = 26, + HELP_DOUBLE_JUMP_CONTROLS = 27, + HELP_CAMERA_CONTROLS = 28, + HELP_ROTATE_CONTROLS = 29, + HELP_SMASH = 30, + MONUMENT_INTRO_MUSIC_PLAYED = 31, + BEGINNING_ZONE_SUMMARY_DISPLAYED = 32, + AG_FINISH_LINE_BUILT = 33, + AG_BOSS_AREA_FOUND = 34, + AG_LANDED_IN_BATTLEFIELD = 35, + GF_PLAYER_HAS_BEEN_TO_THE_RAVINE = 36, + MODULAR_BUILD_STARTED = 37, + MODULAR_BUILD_FINISHED_CLICK_BUTTON = 38, + THINKING_HAT_RECEIVED_GO_TO_MODULAR_BUILD_AREA = 39, + BUILD_AREA_ENTERED_MOD_NOT_ACTIVATED_PUT_ON_HAT = 40, + HAT_ON_INSIDE_OF_MOD_BUILD_EQUIP_A_MODULE_FROM_LEG = 41, + MODULE_EQUIPPED_PLACE_ON_GLOWING_BLUE_SPOT = 42, + FIRST_MODULE_PLACED_CORRECTLY_NOW_DO_THE_REST = 43, + ROCKET_COMPLETE_NOW_LAUNCH_FROM_PAD = 44, + JOINED_A_FACTION = 45, + VENTURE_FACTION = 46, + ASSEMBLY_FACTION = 47, + PARADOX_FACTION = 48, + SENTINEL_FACTION = 49, + LUP_WORLD_ACCESS = 50, + AG_FIRST_FLAG_COLLECTED = 51, + TOOLTIP_TALK_TO_SKYLAND_TO_GET_HAT = 52, + MODULAR_BUILD_PLAYER_PLACES_FIRST_MODEL_IN_SCRATCH = 53, + MODULAR_BUILD_FIRST_ARROW_DISPLAY_FOR_MODULE = 54, + AG_BEACON_QB_SO_THE_PLAYER_CAN_ALWAYS_BUILD_THEM = 55, + GF_PET_DIG_FLAG_1 = 56, + GF_PET_DIG_FLAG_2 = 57, + GF_PET_DIG_FLAG_3 = 58, + SUPPRESS_SPACESHIP_CINEMATIC_FLYTHROUGH = 59, + GF_PLAYER_FALL_DEATH = 60, + GF_PLAYER_CAN_GET_FLAG_1 = 61, + GF_PLAYER_CAN_GET_FLAG_2 = 62, + GF_PLAYER_CAN_GET_FLAG_3 = 63, + ENTER_BBB_FROM_PROPERTY_EDIT_CONFIRMATION_DIALOG = 64, + AG_FIRST_COMBAT_COMPLETE = 65, + AG_COMPLETE_BOB_MISSION = 66, + FIRST_MANUAL_PET_HIBERNATE = 69, + CAGED_SPIDER = 74, + IS_NEWS_SCREEN_VISIBLE = 114, + NJ_GARMADON_CINEMATIC_SEEN = 125, + EQUPPED_TRIAL_FACTION_GEAR = 126, + ELEPHANT_PET_3050 = 801, + CAT_PET_3054 = 803, + TRICERATOPS_PET_3195 = 806, + TERRIER_PET_3254 = 807, + SKUNK_PET_3261 = 811, + BUNNY_PET_3672 = 813, + CROCODILE_PET_3994 = 814, + DOBERMAN_PET_5635 = 815, + BUFFALO_PET_5636 = 816, + ROBOT_DOG_PET_5637 = 818, + RED_DRAGON_PET_5639 = 819, + TORTOISE_PET_5640 = 820, + GREEN_DRAGON_PET_5641 = 821, + PANDA_PET_5643 = 822, + MANTIS_PET_5642 = 823, + WARTHOG_PET_6720 = 824, + LION_PET_3520 = 825, + GOAT_PET_7638 = 818, + CRAB_PET_7694 = 827, + REINDEER_PET_12294 = 829, + STEGOSAURUS_PET_12431 = 830, + SABER_CAT_PET_12432 = 831, + GRYPHON_PET_12433 = 832, + ALINE_PET_12334 = 833, + UNKNOWN_PET = 834, + EARTH_DRAGON_PET_16210 = 836, + SKELETON_DRAGON_PET_13067 = 838, + AG_SPACE_SHIP_BINOC_AT_LAUNCH = 1001, + AG_SPACE_SHIP_BINOC_AT_LAUNCH_PLATFORM = 1002, + AG_SPACE_SHIP_BINOC_ON_PLATFORM_TO_LEFT_OF_START = 1003, + AG_SPACE_SHIP_BINOC_ON_PLATFORM_TO_RIGHT_OF_START = 1004, + AG_SPACE_SHIP_BINOC_AT_BOB = 1005, + AG_BATTLE_BINOC_FOR_TRICERETOPS = 1101, + AG_BATTLE_BINOC_AT_PARADOX = 1102, + AG_BATTLE_BINOC_AT_MISSION_GIVER = 1103, + AG_BATTLE_BINOC_AT_BECK = 1104, + AG_MONUMENT_BINOC_INTRO = 1105, + AG_MONUMENT_BINOC_OUTRO = 1106, + AG_LAUNCH_BINOC_INTRO = 1107, + AG_LAUNCH_BINOC_BISON = 1108, + AG_LAUNCH_BINOC_SHARK = 1109, + NS_BINOC_CONCERT_TRANSITION = 1201, + NS_BINOC_RACE_PLACE_TRANSITION = 1202, + NS_BINOC_BRICK_ANNEX_TRANSITION = 1203, + NS_BINOC_GF_LAUNCH = 1204, + NS_BINOC_FV_LAUNCH = 1205, + NS_BINOC_BRICK_ANNEX_WATER = 1206, + NS_BINOC_AG_LAUNCH_AT_RACE_PLACE = 1207, + NS_BINOC_AG_LAUNCH_AT_BRICK_ANNEX = 1208, + NS_BINOC_AG_LAUNCH_AT_PLAZA = 1209, + NS_BINOC_TBA = 1210, + NS_FLAG_COLLECTABLE_1_BY_JONNY_THUNDER = 1211, + NS_FLAG_COLLECTABLE_2_UNDER_CONCERT_BRIDGE = 1212, + NS_FLAG_COLLECTABLE_3_BY_FV_LAUNCH = 1213, + NS_FLAG_COLLECTABLE_4_IN_PLAZA_BEHIND_BUILDING = 1214, + NS_FLAG_COLLECTABLE_5_BY_GF_LAUNCH = 1215, + NS_FLAG_COLLECTABLE_6_BY_DUCK_SG = 1216, + NS_FLAG_COLLECTABLE_7_BY_LUP_LAUNCH = 1217, + NS_FLAG_COLLECTABLE_8_BY_NT_LUANCH = 1218, + NS_FLAG_COLLECTABLE_9_BY_RACE_BUILD = 1219, + NS_FLAG_COLLECTABLE_10_ON_AG_LAUNCH_PATH = 1220, + PR_BINOC_AT_LAUNCH_PAD = 1251, + PR_BINOC_AT_BEGINNING_OF_ISLAND_B = 1252, + PR_BINOC_AT_FIRST_PET_BOUNCER = 1253, + PR_BINOC_ON_BY_CROWS_NEST = 1254, + PR_PET_DIG_AT_BEGINNING_OF_ISLAND_B = 1261, + PR_PET_DIG_AT_THE_LOCATION_OF_OLD_BOUNCE_BACK = 1262, + PR_PET_DIG_UNDER_QB_BRIDGE = 1263, + PR_PET_DIG_BACK_SIDE_BY_PARTNER_BOUNCE = 1264, + PR_PET_DIG_BY_LAUNCH_PAD = 1265, + PR_PET_DIG_BY_FIRST_PET_BOUNCER = 1266, + GF_BINOC_ON_LANDING_PAD = 1301, + GF_BINOC_AT_RAVINE_START = 1302, + GF_BINOC_ON_TOP_OF_RAVINE_HEAD = 1303, + GF_BINOC_AT_TURTLE_AREA = 1304, + GF_BINOC_IN_TUNNEL_TO_ELEPHANTS = 1305, + GF_BINOC_IN_ELEPHANTS_AREA = 1306, + GF_BINOC_IN_RACING_AREA = 1307, + GF_BINOC_IN_CROC_AREA = 1308, + GF_BINOC_IN_JAIL_AREA = 1309, + GF_BINOC_TELESCOPE_NEXT_TO_CAPTAIN_JACK = 1310, + NT_HEART_OF_DARKNESS = 1911, + NT_PLINTH_REBUILD = 1919, + NT_FACTION_SPY_DUKE = 1974, + NT_FACTION_SPY_OVERBUILD = 1976, + NT_FACTION_SPY_HAEL = 1977, + NJ_EARTH_SPINJITZU = 2030, + NJ_LIGHTNING_SPINJITZU = 2031, + NJ_ICE_SPINJITZU = 2032, + NJ_FIRE_SPINJITZU = 2033, + NJ_WU_SHOW_DAILY_CHEST = 2099 +}; + +#endif //!__EPLAYERFLAG__H__ diff --git a/dCommon/dEnums/eQuickBuildFailReason.h b/dCommon/dEnums/eQuickBuildFailReason.h new file mode 100644 index 00000000..a6144bd5 --- /dev/null +++ b/dCommon/dEnums/eQuickBuildFailReason.h @@ -0,0 +1,13 @@ +#ifndef __EQUICKBUILDFAILREASON__H__ +#define __EQUICKBUILDFAILREASON__H__ + +#include <cstdint> + +enum class eQuickBuildFailReason : uint32_t { + NOT_GIVEN, + OUT_OF_IMAGINATION, + CANCELED_EARLY, + BUILD_ENDED +}; + +#endif //!__EQUICKBUILDFAILREASON__H__ diff --git a/dCommon/dEnums/eRebuildState.h b/dCommon/dEnums/eRebuildState.h new file mode 100644 index 00000000..497bcb77 --- /dev/null +++ b/dCommon/dEnums/eRebuildState.h @@ -0,0 +1,15 @@ +#ifndef __EREBUILDSTATE__H__ +#define __EREBUILDSTATE__H__ + +#include <cstdint> + +enum class eRebuildState : uint32_t { + OPEN, + COMPLETED = 2, + RESETTING = 4, + BUILDING, + INCOMPLETE +}; + + +#endif //!__EREBUILDSTATE__H__ diff --git a/dCommon/dEnums/eRenameResponse.h b/dCommon/dEnums/eRenameResponse.h new file mode 100644 index 00000000..2298e922 --- /dev/null +++ b/dCommon/dEnums/eRenameResponse.h @@ -0,0 +1,15 @@ +#ifndef __ERENAMERESPONSE__H__ +#define __ERENAMERESPONSE__H__ + +#include <cstdint> + +//! An enum for character rename responses +enum class eRenameResponse : uint8_t { + SUCCESS = 0, + UNKNOWN_ERROR, + NAME_UNAVAILABLE, + NAME_IN_USE +}; + + +#endif //!__ERENAMERESPONSE__H__ diff --git a/dCommon/dEnums/eReplicaPacketType.h b/dCommon/dEnums/eReplicaPacketType.h new file mode 100644 index 00000000..2650fb30 --- /dev/null +++ b/dCommon/dEnums/eReplicaPacketType.h @@ -0,0 +1,12 @@ +#ifndef __EREPLICAPACKETTYPE__H__ +#define __EREPLICAPACKETTYPE__H__ + +#include <cstdint> + +enum class eReplicaPacketType : uint8_t { + CONSTRUCTION, + SERIALIZATION, + DESTRUCTION +}; + +#endif //!__EREPLICAPACKETTYPE__H__ diff --git a/dCommon/dEnums/eStateChangeType.h b/dCommon/dEnums/eStateChangeType.h new file mode 100644 index 00000000..e187e265 --- /dev/null +++ b/dCommon/dEnums/eStateChangeType.h @@ -0,0 +1,11 @@ +#ifndef __ESTATECHANGETYPE__H__ +#define __ESTATECHANGETYPE__H__ + +#include <cstdint> + +enum class eStateChangeType : uint32_t { + PUSH, + POP +}; + +#endif //!__ESTATECHANGETYPE__H__ diff --git a/dCommon/dEnums/eTerminateType.h b/dCommon/dEnums/eTerminateType.h new file mode 100644 index 00000000..189734f8 --- /dev/null +++ b/dCommon/dEnums/eTerminateType.h @@ -0,0 +1,12 @@ +#ifndef __ETERMINATETYPE__H__ +#define __ETERMINATETYPE__H__ + +#include <cstdint> + +enum class eTerminateType : uint32_t { + RANGE, + USER, + FROM_INTERACTION +}; + +#endif //!__ETERMINATETYPE__H__ diff --git a/dCommon/dEnums/eUseItemResponse.h b/dCommon/dEnums/eUseItemResponse.h new file mode 100644 index 00000000..ba0ece7f --- /dev/null +++ b/dCommon/dEnums/eUseItemResponse.h @@ -0,0 +1,12 @@ +#ifndef __EUSEITEMRESPONSE__H__ +#define __EUSEITEMRESPONSE__H__ + +#include <cstdint> + +enum class eUseItemResponse : uint32_t { + NoImaginationForPet = 1, + FailedPrecondition, + MountsNotAllowed +}; + +#endif //!__EUSEITEMRESPONSE__H__ diff --git a/dGame/Character.cpp b/dGame/Character.cpp index 98d6d0a9..e565ed4f 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -20,6 +20,7 @@ #include "eMissionState.h" #include "eObjectBits.h" #include "eGameMasterLevel.h" +#include "ePlayerFlag.h" Character::Character(uint32_t id, User* parentUser) { //First load the name, etc: @@ -362,9 +363,9 @@ void Character::SaveXMLToDatabase() { } // Prevents the news feed from showing up on world transfers - if (GetPlayerFlag(ePlayerFlags::IS_NEWS_SCREEN_VISIBLE)) { + if (GetPlayerFlag(ePlayerFlag::IS_NEWS_SCREEN_VISIBLE)) { auto* s = m_Doc->NewElement("s"); - s->SetAttribute("si", ePlayerFlags::IS_NEWS_SCREEN_VISIBLE); + s->SetAttribute("si", ePlayerFlag::IS_NEWS_SCREEN_VISIBLE); flags->LinkEndChild(s); } @@ -417,7 +418,7 @@ void Character::WriteToDatabase() { delete printer; } -void Character::SetPlayerFlag(const uint32_t flagId, const bool value) { +void Character::SetPlayerFlag(const int32_t flagId, const bool value) { // If the flag is already set, we don't have to recalculate it if (GetPlayerFlag(flagId) == value) return; @@ -464,7 +465,7 @@ void Character::SetPlayerFlag(const uint32_t flagId, const bool value) { GameMessages::SendNotifyClientFlagChange(m_ObjectID, flagId, value, m_ParentUser->GetSystemAddress()); } -bool Character::GetPlayerFlag(const uint32_t flagId) const { +bool Character::GetPlayerFlag(const int32_t flagId) const { // Calculate the index first const auto flagIndex = uint32_t(std::floor(flagId / 64)); @@ -481,8 +482,8 @@ bool Character::GetPlayerFlag(const uint32_t flagId) const { void Character::SetRetroactiveFlags() { // Retroactive check for if player has joined a faction to set their 'joined a faction' flag to true. - if (GetPlayerFlag(ePlayerFlags::VENTURE_FACTION) || GetPlayerFlag(ePlayerFlags::ASSEMBLY_FACTION) || GetPlayerFlag(ePlayerFlags::PARADOX_FACTION) || GetPlayerFlag(ePlayerFlags::SENTINEL_FACTION)) { - SetPlayerFlag(ePlayerFlags::JOINED_A_FACTION, true); + if (GetPlayerFlag(ePlayerFlag::VENTURE_FACTION) || GetPlayerFlag(ePlayerFlag::ASSEMBLY_FACTION) || GetPlayerFlag(ePlayerFlag::PARADOX_FACTION) || GetPlayerFlag(ePlayerFlag::SENTINEL_FACTION)) { + SetPlayerFlag(ePlayerFlag::JOINED_A_FACTION, true); } } @@ -542,7 +543,7 @@ void Character::OnZoneLoad() { if (missionComponent != nullptr) { // Fix the monument race flag if (missionComponent->GetMissionState(319) >= eMissionState::READY_TO_COMPLETE) { - SetPlayerFlag(33, true); + SetPlayerFlag(ePlayerFlag::AG_FINISH_LINE_BUILT, true); } } @@ -558,7 +559,7 @@ void Character::OnZoneLoad() { */ if (HasPermission(ePermissionMap::Old)) { if (GetCoins() > 1000000) { - SetCoins(1000000, eLootSourceType::LOOT_SOURCE_NONE); + SetCoins(1000000, eLootSourceType::NONE); } } @@ -636,7 +637,7 @@ void Character::SetBillboardVisible(bool visible) { // The GameMessage we send for turning the nameplate off just deletes the BillboardSubcomponent from the parent component. // Because that same message does not allow for custom parameters, we need to create the BillboardSubcomponent a different way - // This workaround involves sending an unrelated GameMessage that does not apply to player entites, + // This workaround involves sending an unrelated GameMessage that does not apply to player entites, // but forces the client to create the necessary SubComponent that controls the billboard. GameMessages::SendShowBillboardInteractIcon(UNASSIGNED_SYSTEM_ADDRESS, m_OurEntity->GetObjectID()); diff --git a/dGame/Character.h b/dGame/Character.h index 2f0abba5..3759f206 100644 --- a/dGame/Character.h +++ b/dGame/Character.h @@ -16,6 +16,7 @@ struct Packet; class Entity; enum class ePermissionMap : uint64_t; enum class eGameMasterLevel : uint8_t; +enum class eLootSourceType : uint32_t; /** * Meta information about a character, like their name and style @@ -414,14 +415,14 @@ public: * @param flagId the ID of the flag to set * @param value the value to set for the flag */ - void SetPlayerFlag(uint32_t flagId, bool value); + void SetPlayerFlag(int32_t flagId, bool value); /** * Gets the value for a certain character flag * @param flagId the ID of the flag to get a value for * @return the value of the flag given the ID (the default is false, obviously) */ - bool GetPlayerFlag(uint32_t flagId) const; + bool GetPlayerFlag(int32_t flagId) const; /** * Notifies the character that they're now muted diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 55e1b1ca..b9fc79fb 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -73,6 +73,7 @@ #include "TriggerComponent.h" #include "eGameMasterLevel.h" #include "eReplicaComponentType.h" +#include "eReplicaPacketType.h" // Table includes #include "CDComponentsRegistryTable.h" @@ -876,7 +877,7 @@ void Entity::SetGMLevel(eGameMasterLevel value) { } void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacketType packetType) { - if (packetType == PACKET_TYPE_CONSTRUCTION) { + if (packetType == eReplicaPacketType::CONSTRUCTION) { outBitStream->Write(m_ObjectID); outBitStream->Write(m_TemplateID); @@ -978,8 +979,8 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke } // Only serialize parent / child info should the info be dirty (changed) or if this is the construction of the entity. - outBitStream->Write(m_IsParentChildDirty || packetType == PACKET_TYPE_CONSTRUCTION); - if (m_IsParentChildDirty || packetType == PACKET_TYPE_CONSTRUCTION) { + outBitStream->Write(m_IsParentChildDirty || packetType == eReplicaPacketType::CONSTRUCTION); + if (m_IsParentChildDirty || packetType == eReplicaPacketType::CONSTRUCTION) { m_IsParentChildDirty = false; outBitStream->Write(m_ParentEntity != nullptr); if (m_ParentEntity) { @@ -1004,7 +1005,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType bool destroyableSerialized = false; bool bIsInitialUpdate = false; - if (packetType == PACKET_TYPE_CONSTRUCTION) bIsInitialUpdate = true; + if (packetType == eReplicaPacketType::CONSTRUCTION) bIsInitialUpdate = true; unsigned int flags = 0; PossessableComponent* possessableComponent; @@ -1624,7 +1625,7 @@ void Entity::PickupItem(const LWOOBJID& objectID) { } } } else { - inv->AddItem(p.second.lot, p.second.count, eLootSourceType::LOOT_SOURCE_PICKUP, eInventoryType::INVALID, {}, LWOOBJID_EMPTY, true, false, LWOOBJID_EMPTY, eInventoryType::INVALID, 1); + inv->AddItem(p.second.lot, p.second.count, eLootSourceType::PICKUP, eInventoryType::INVALID, {}, LWOOBJID_EMPTY, true, false, LWOOBJID_EMPTY, eInventoryType::INVALID, 1); } } } diff --git a/dGame/Entity.h b/dGame/Entity.h index f8abff31..b980b179 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -10,6 +10,7 @@ #include "NiPoint3.h" #include "NiQuaternion.h" #include "LDFFormat.h" +#include "eKillType.h" namespace Loot { class Info; @@ -33,6 +34,8 @@ class EntityCallbackTimer; enum class eTriggerEventType; enum class eGameMasterLevel : uint8_t; enum class eReplicaComponentType : uint32_t; +enum class eReplicaPacketType : uint8_t; +enum class eCinematicEvent : uint32_t; namespace CppScripts { class Script; diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index dc9a43f3..1a77d365 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -23,6 +23,7 @@ #include "eObjectBits.h" #include "eGameMasterLevel.h" #include "eReplicaComponentType.h" +#include "eReplicaPacketType.h" EntityManager* EntityManager::m_Address = nullptr; @@ -197,8 +198,8 @@ void EntityManager::UpdateEntities(const float deltaTime) { stream.Write(static_cast<char>(ID_REPLICA_MANAGER_SERIALIZE)); stream.Write(static_cast<unsigned short>(entity->GetNetworkId())); - entity->WriteBaseReplicaData(&stream, PACKET_TYPE_SERIALIZATION); - entity->WriteComponents(&stream, PACKET_TYPE_SERIALIZATION); + entity->WriteBaseReplicaData(&stream, eReplicaPacketType::SERIALIZATION); + entity->WriteComponents(&stream, eReplicaPacketType::SERIALIZATION); if (entity->GetIsGhostingCandidate()) { for (auto* player : Player::GetAllPlayers()) { @@ -218,9 +219,9 @@ void EntityManager::UpdateEntities(const float deltaTime) { if (!entity) continue; if (entity->GetScheduledKiller()) { - entity->Smash(entity->GetScheduledKiller()->GetObjectID(), SILENT); + entity->Smash(entity->GetScheduledKiller()->GetObjectID(), eKillType::SILENT); } else { - entity->Smash(LWOOBJID_EMPTY, SILENT); + entity->Smash(LWOOBJID_EMPTY, eKillType::SILENT); } } m_EntitiesToKill.clear(); @@ -352,8 +353,8 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr stream.Write(true); stream.Write(static_cast<unsigned short>(entity->GetNetworkId())); - entity->WriteBaseReplicaData(&stream, PACKET_TYPE_CONSTRUCTION); - entity->WriteComponents(&stream, PACKET_TYPE_CONSTRUCTION); + entity->WriteBaseReplicaData(&stream, eReplicaPacketType::CONSTRUCTION); + entity->WriteComponents(&stream, eReplicaPacketType::CONSTRUCTION); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) { if (skipChecks) { diff --git a/dGame/TradingManager.cpp b/dGame/TradingManager.cpp index e1eac422..281c003d 100644 --- a/dGame/TradingManager.cpp +++ b/dGame/TradingManager.cpp @@ -156,21 +156,21 @@ void Trade::Complete() { } // Now actually do the trade. - characterA->SetCoins(characterA->GetCoins() - m_CoinsA + m_CoinsB, eLootSourceType::LOOT_SOURCE_TRADE); - characterB->SetCoins(characterB->GetCoins() - m_CoinsB + m_CoinsA, eLootSourceType::LOOT_SOURCE_TRADE); + characterA->SetCoins(characterA->GetCoins() - m_CoinsA + m_CoinsB, eLootSourceType::TRADE); + characterB->SetCoins(characterB->GetCoins() - m_CoinsB + m_CoinsA, eLootSourceType::TRADE); for (const auto& tradeItem : m_ItemsA) { auto* itemToRemove = inventoryA->FindItemById(tradeItem.itemId); if (itemToRemove) itemToRemove->SetCount(itemToRemove->GetCount() - tradeItem.itemCount); missionsA->Progress(eMissionTaskType::GATHER, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); - inventoryB->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); + inventoryB->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::TRADE); } for (const auto& tradeItem : m_ItemsB) { auto* itemToRemove = inventoryB->FindItemById(tradeItem.itemId); if (itemToRemove) itemToRemove->SetCount(itemToRemove->GetCount() - tradeItem.itemCount); missionsB->Progress(eMissionTaskType::GATHER, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); - inventoryA->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); + inventoryA->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::TRADE); } characterA->SaveXMLToDatabase(); diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index 0e52bc52..d57caa67 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -25,6 +25,8 @@ #include "dMessageIdentifiers.h" #include "eObjectBits.h" #include "eGameMasterLevel.h" +#include "eCharacterCreationResponse.h" +#include "eRenameResponse.h" UserManager* UserManager::m_Address = nullptr; @@ -269,13 +271,13 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) if (name != "" && !UserManager::IsNameAvailable(name)) { Game::logger->Log("UserManager", "AccountID: %i chose unavailable name: %s", u->GetAccountID(), name.c_str()); - WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_CUSTOM_NAME_IN_USE); + WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::CUSTOM_NAME_IN_USE); return; } if (!IsNameAvailable(predefinedName)) { Game::logger->Log("UserManager", "AccountID: %i chose unavailable predefined name: %s", u->GetAccountID(), predefinedName.c_str()); - WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_PREDEFINED_NAME_IN_USE); + WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::PREDEFINED_NAME_IN_USE); return; } @@ -294,7 +296,7 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) if (overlapResult->next()) { Game::logger->Log("UserManager", "Character object id unavailable, check objectidtracker!"); - WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_OBJECT_ID_UNAVAILABLE); + WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::OBJECT_ID_UNAVAILABLE); return; } @@ -370,7 +372,7 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) stmt->execute(); delete stmt; - WorldPackets::SendCharacterCreationResponse(sysAddr, CREATION_RESPONSE_SUCCESS); + WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::SUCCESS); UserManager::RequestCharacterList(sysAddr); }); }); @@ -500,10 +502,10 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) if (!hasCharacter || !character) { Game::logger->Log("UserManager", "User %i tried to rename a character that it does not own!", u->GetAccountID()); - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); + WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::UNKNOWN_ERROR); } else if (hasCharacter && character) { if (newName == character->GetName()) { - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_UNAVAILABLE); + WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::NAME_UNAVAILABLE); return; } @@ -517,7 +519,7 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) delete stmt; Game::logger->Log("UserManager", "Character %s now known as %s", character->GetName().c_str(), newName.c_str()); - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); + WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::SUCCESS); UserManager::RequestCharacterList(sysAddr); } else { sql::PreparedStatement* stmt = Database::CreatePreppedStmt("UPDATE charinfo SET pending_name=?, needs_rename=0, last_login=? WHERE id=? LIMIT 1"); @@ -528,15 +530,15 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) delete stmt; Game::logger->Log("UserManager", "Character %s has been renamed to %s and is pending approval by a moderator.", character->GetName().c_str(), newName.c_str()); - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_SUCCESS); + WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::SUCCESS); UserManager::RequestCharacterList(sysAddr); } } else { - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_NAME_IN_USE); + WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::NAME_IN_USE); } } else { Game::logger->Log("UserManager", "Unknown error occurred when renaming character, either hasCharacter or character variable != true."); - WorldPackets::SendCharacterRenameResponse(sysAddr, RENAME_RESPONSE_UNKNOWN_ERROR); + WorldPackets::SendCharacterRenameResponse(sysAddr, eRenameResponse::UNKNOWN_ERROR); } } diff --git a/dGame/dBehaviors/ImmunityBehavior.cpp b/dGame/dBehaviors/ImmunityBehavior.cpp index f4a41c52..a5dd4c85 100644 --- a/dGame/dBehaviors/ImmunityBehavior.cpp +++ b/dGame/dBehaviors/ImmunityBehavior.cpp @@ -7,6 +7,7 @@ #include "dLogger.h" #include "DestroyableComponent.h" #include "ControllablePhysicsComponent.h" +#include "eStateChangeType.h" void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { auto* target = EntityManager::Instance()->GetEntity(branch.target); diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 64c739f5..cccaad23 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -248,7 +248,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) { if (rebuild != nullptr) { const auto state = rebuild->GetState(); - if (state != REBUILD_COMPLETED) { + if (state != eRebuildState::COMPLETED) { return; } } @@ -566,7 +566,7 @@ bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const { if (quickbuild != nullptr) { const auto state = quickbuild->GetState(); - if (state != REBUILD_COMPLETED) { + if (state != eRebuildState::COMPLETED) { return false; } } diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 6394cc32..82ad5507 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -15,6 +15,7 @@ #include "Item.h" #include "AMFFormat.h" #include "eGameMasterLevel.h" +#include "eGameActivity.h" CharacterComponent::CharacterComponent(Entity* parent, Character* character) : Component(parent) { m_Character = character; @@ -35,7 +36,7 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C m_EditorLevel = m_GMLevel; m_Reputation = 0; - m_CurrentActivity = 0; + m_CurrentActivity = eGameActivity::NONE; m_CountryCode = 0; m_LastUpdateTimestamp = std::time(nullptr); } diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index 0e047494..e5ca6da5 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -11,6 +11,8 @@ #include "tinyxml2.h" #include "eReplicaComponentType.h" +enum class eGameActivity : uint32_t; + /** * The statistics that can be achieved per zone */ @@ -112,13 +114,13 @@ public: * Gets the current activity that the character is partaking in, see ScriptedActivityComponent for more details * @return the current activity that the character is partaking in */ - const uint32_t GetCurrentActivity() const { return m_CurrentActivity; } + const eGameActivity GetCurrentActivity() const { return m_CurrentActivity; } /** * Set the current activity of the character, see ScriptedActivityComponent for more details * @param currentActivity the activity to set */ - void SetCurrentActivity(uint32_t currentActivity) { m_CurrentActivity = currentActivity; m_DirtyCurrentActivity = true; } + void SetCurrentActivity(eGameActivity currentActivity) { m_CurrentActivity = currentActivity; m_DirtyCurrentActivity = true; } /** * Gets if the entity is currently racing @@ -353,7 +355,7 @@ private: /** * The ID of the curently active activity */ - int m_CurrentActivity; + eGameActivity m_CurrentActivity; /** * Whether the social info has been changed diff --git a/dGame/dComponents/ControllablePhysicsComponent.cpp b/dGame/dComponents/ControllablePhysicsComponent.cpp index 6a6d69ce..1b8627a7 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/ControllablePhysicsComponent.cpp @@ -13,6 +13,7 @@ #include "Character.h" #include "dZoneManager.h" #include "LevelProgressionComponent.h" +#include "eStateChangeType.h" ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Component(entity) { m_Position = {}; diff --git a/dGame/dComponents/ControllablePhysicsComponent.h b/dGame/dComponents/ControllablePhysicsComponent.h index a7359a26..d6088718 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.h +++ b/dGame/dComponents/ControllablePhysicsComponent.h @@ -14,6 +14,7 @@ class Entity; class dpEntity; +enum class eStateChangeType : uint32_t; /** * Handles the movement of controllable Entities, e.g. enemies and players diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index c2d72941..7e7d44aa 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -33,6 +33,8 @@ #include "dZoneManager.h" #include "WorldConfig.h" #include "eMissionTaskType.h" +#include "eStateChangeType.h" +#include "eGameActivity.h" #include "CDComponentsRegistryTable.h" @@ -468,7 +470,7 @@ bool DestroyableComponent::IsKnockbackImmune() const { auto* characterComponent = m_Parent->GetComponent<CharacterComponent>(); auto* inventoryComponent = m_Parent->GetComponent<InventoryComponent>(); - if (characterComponent != nullptr && inventoryComponent != nullptr && characterComponent->GetCurrentActivity() == eGameActivities::ACTIVITY_QUICKBUILDING) { + if (characterComponent != nullptr && inventoryComponent != nullptr && characterComponent->GetCurrentActivity() == eGameActivity::QUICKBUILDING) { const auto hasPassive = inventoryComponent->HasAnyPassive({ eItemSetPassiveAbilityID::EngineerRank2, eItemSetPassiveAbilityID::EngineerRank3, eItemSetPassiveAbilityID::SummonerRank2, eItemSetPassiveAbilityID::SummonerRank3, @@ -514,7 +516,7 @@ bool DestroyableComponent::CheckValidity(const LWOOBJID target, const bool ignor if (targetQuickbuild != nullptr) { const auto state = targetQuickbuild->GetState(); - if (state != REBUILD_COMPLETED) { + if (state != eRebuildState::COMPLETED) { return false; } } @@ -803,7 +805,7 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType coinsTotal -= coinsToLose; LootGenerator::Instance().DropLoot(m_Parent, m_Parent, -1, coinsToLose, coinsToLose); - character->SetCoins(coinsTotal, eLootSourceType::LOOT_SOURCE_PICKUP); + character->SetCoins(coinsTotal, eLootSourceType::PICKUP); } } @@ -992,7 +994,7 @@ void DestroyableComponent::DoHardcoreModeDrops(const LWOOBJID source){ auto uscoreToLose = uscore * (EntityManager::Instance()->GetHardcoreLoseUscoreOnDeathPercent() / 100); character->SetUScore(uscore - uscoreToLose); - GameMessages::SendModifyLEGOScore(m_Parent, m_Parent->GetSystemAddress(), -uscoreToLose, eLootSourceType::LOOT_SOURCE_MISSION); + GameMessages::SendModifyLEGOScore(m_Parent, m_Parent->GetSystemAddress(), -uscoreToLose, eLootSourceType::MISSION); if (EntityManager::Instance()->GetHardcoreDropinventoryOnDeath()) { //drop all items from inventory: @@ -1023,7 +1025,7 @@ void DestroyableComponent::DoHardcoreModeDrops(const LWOOBJID source){ auto coins = chars->GetCoins(); //lose all coins: - chars->SetCoins(0, eLootSourceType::LOOT_SOURCE_NONE); + chars->SetCoins(0, eLootSourceType::NONE); //drop all coins: GameMessages::SendDropClientLoot(m_Parent, source, LOT_NULL, coins, m_Parent->GetPosition()); @@ -1047,7 +1049,7 @@ void DestroyableComponent::DoHardcoreModeDrops(const LWOOBJID source){ int uscore = maxHealth * EntityManager::Instance()->GetHardcoreUscoreEnemiesMultiplier(); playerStats->SetUScore(playerStats->GetUScore() + uscore); - GameMessages::SendModifyLEGOScore(player, player->GetSystemAddress(), uscore, eLootSourceType::LOOT_SOURCE_MISSION); + GameMessages::SendModifyLEGOScore(player, player->GetSystemAddress(), uscore, eLootSourceType::MISSION); EntityManager::Instance()->SerializeEntity(m_Parent); } diff --git a/dGame/dComponents/DestroyableComponent.h b/dGame/dComponents/DestroyableComponent.h index 47be96a0..66c8374d 100644 --- a/dGame/dComponents/DestroyableComponent.h +++ b/dGame/dComponents/DestroyableComponent.h @@ -11,6 +11,7 @@ namespace CppScripts { class Script; }; //! namespace CppScripts +enum class eStateChangeType : uint32_t; /** * Represents the stats of an entity, for example its health, imagination and armor. Also handles factions, which diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index dc8fdbdc..907356ce 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -29,6 +29,8 @@ #include "eUnequippableActiveType.h" #include "CppScripts.h" #include "eMissionTaskType.h" +#include "eStateChangeType.h" +#include "eUseItemResponse.h" #include "CDComponentsRegistryTable.h" #include "CDInventoryComponentTable.h" @@ -356,7 +358,7 @@ void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType in left -= delta; - AddItem(lot, delta, eLootSourceType::LOOT_SOURCE_NONE, inventory, {}, LWOOBJID_EMPTY, showFlyingLot, isModMoveAndEquip, LWOOBJID_EMPTY, origin->GetType(), 0, false, preferredSlot); + AddItem(lot, delta, eLootSourceType::NONE, inventory, {}, LWOOBJID_EMPTY, showFlyingLot, isModMoveAndEquip, LWOOBJID_EMPTY, origin->GetType(), 0, false, preferredSlot); item->SetCount(item->GetCount() - delta, false, false); @@ -371,7 +373,7 @@ void InventoryComponent::MoveItemToInventory(Item* item, const eInventoryType in const auto delta = std::min<uint32_t>(item->GetCount(), count); - AddItem(lot, delta, eLootSourceType::LOOT_SOURCE_NONE, inventory, config, LWOOBJID_EMPTY, showFlyingLot, isModMoveAndEquip, subkey, origin->GetType(), 0, item->GetBound(), preferredSlot); + AddItem(lot, delta, eLootSourceType::NONE, inventory, config, LWOOBJID_EMPTY, showFlyingLot, isModMoveAndEquip, subkey, origin->GetType(), 0, item->GetBound(), preferredSlot); item->SetCount(item->GetCount() - delta, false, false); } @@ -1247,7 +1249,7 @@ void InventoryComponent::SpawnPet(Item* item) { auto destroyableComponent = m_Parent->GetComponent<DestroyableComponent>(); if (Game::config->GetValue("pets_take_imagination") == "1" && destroyableComponent && destroyableComponent->GetImagination() <= 0) { - GameMessages::SendUseItemRequirementsResponse(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), UseItemResponse::NoImaginationForPet); + GameMessages::SendUseItemRequirementsResponse(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), eUseItemResponse::NoImaginationForPet); return; } diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index d695737c..801f9f51 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -21,6 +21,7 @@ #include "PossessorComponent.h" #include "eInventoryType.h" #include "eReplicaComponentType.h" +#include "eLootSourceType.h" class Entity; class ItemSet; @@ -99,7 +100,7 @@ public: void AddItem( LOT lot, uint32_t count, - eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE, + eLootSourceType lootSourceType = eLootSourceType::NONE, eInventoryType inventoryType = INVALID, const std::vector<LDFBaseData*>& config = {}, LWOOBJID parent = LWOOBJID_EMPTY, diff --git a/dGame/dComponents/LevelProgressionComponent.cpp b/dGame/dComponents/LevelProgressionComponent.cpp index 814a7a86..8163e736 100644 --- a/dGame/dComponents/LevelProgressionComponent.cpp +++ b/dGame/dComponents/LevelProgressionComponent.cpp @@ -59,7 +59,7 @@ void LevelProgressionComponent::HandleLevelUp() { for (auto* reward : rewards) { switch (reward->rewardType) { case 0: - inventoryComponent->AddItem(reward->value, reward->count, eLootSourceType::LOOT_SOURCE_LEVEL_REWARD); + inventoryComponent->AddItem(reward->value, reward->count, eLootSourceType::LEVEL_REWARD); break; case 4: { diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 2dfaad27..774aa92b 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -15,6 +15,10 @@ #include "PetDigServer.h" #include "../dWorldServer/ObjectIDManager.h" #include "eUnequippableActiveType.h" +#include "eTerminateType.h" +#include "ePetTamingNotifyType.h" +#include "eUseItemResponse.h" +#include "ePlayerFlag.h" #include "Game.h" #include "dConfig.h" @@ -33,7 +37,7 @@ std::unordered_map<LWOOBJID, LWOOBJID> PetComponent::activePets{}; * Maps all the pet lots to a flag indicating that the player has caught it. All basic pets have been guessed by ObjID * while the faction ones could be checked using their respective missions. */ -std::map<LOT, uint32_t> PetComponent::petFlags = { +std::map<LOT, int32_t> PetComponent::petFlags = { { 3050, 801 }, // Elephant { 3054, 803 }, // Cat { 3195, 806 }, // Triceratops @@ -285,7 +289,7 @@ void PetComponent::OnUse(Entity* originator) { m_Parent->GetObjectID(), LWOOBJID_EMPTY, true, - NOTIFY_TYPE_BEGIN, + ePetTamingNotifyType::BEGIN, petPosition, position, rotation, @@ -297,7 +301,7 @@ void PetComponent::OnUse(Entity* originator) { LWOOBJID_EMPTY, originator->GetObjectID(), true, - NOTIFY_TYPE_BEGIN, + ePetTamingNotifyType::BEGIN, petPosition, position, rotation, @@ -313,7 +317,7 @@ void PetComponent::OnUse(Entity* originator) { // Notify the start of a pet taming minigame for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, originator, NOTIFY_TYPE_BEGIN); + script->OnNotifyPetTamingMinigame(m_Parent, originator, ePetTamingNotifyType::BEGIN); } } @@ -566,7 +570,7 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { GameMessages::SendRegisterPetDBID(m_Tamer, petSubKey, tamer->GetSystemAddress()); - inventoryComponent->AddItem(m_Parent->GetLOT(), 1, eLootSourceType::LOOT_SOURCE_ACTIVITY, eInventoryType::MODELS, {}, LWOOBJID_EMPTY, true, false, petSubKey); + inventoryComponent->AddItem(m_Parent->GetLOT(), 1, eLootSourceType::ACTIVITY, eInventoryType::MODELS, {}, LWOOBJID_EMPTY, true, false, petSubKey); auto* item = inventoryComponent->FindItemBySubKey(petSubKey, MODELS); if (item == nullptr) { @@ -590,7 +594,7 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { LWOOBJID_EMPTY, LWOOBJID_EMPTY, false, - NOTIFY_TYPE_NAMINGPET, + ePetTamingNotifyType::NAMINGPET, NiPoint3::ZERO, NiPoint3::ZERO, NiQuaternion::IDENTITY, @@ -670,7 +674,7 @@ void PetComponent::RequestSetPetName(std::u16string name) { m_Parent->GetObjectID(), m_Tamer, false, - NOTIFY_TYPE_SUCCESS, + ePetTamingNotifyType::SUCCESS, NiPoint3::ZERO, NiPoint3::ZERO, NiQuaternion::IDENTITY, @@ -691,7 +695,7 @@ void PetComponent::RequestSetPetName(std::u16string name) { // Notify the end of a pet taming minigame for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_SUCCESS); + script->OnNotifyPetTamingMinigame(m_Parent, tamer, ePetTamingNotifyType::SUCCESS); } } @@ -711,7 +715,7 @@ void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) { m_Parent->GetObjectID(), m_Tamer, false, - NOTIFY_TYPE_QUIT, + ePetTamingNotifyType::QUIT, NiPoint3::ZERO, NiPoint3::ZERO, NiQuaternion::IDENTITY, @@ -732,7 +736,7 @@ void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) { // Notify the end of a pet taming minigame for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_QUIT); + script->OnNotifyPetTamingMinigame(m_Parent, tamer, ePetTamingNotifyType::QUIT); } } @@ -762,7 +766,7 @@ void PetComponent::ClientFailTamingMinigame() { m_Parent->GetObjectID(), m_Tamer, false, - NOTIFY_TYPE_FAILED, + ePetTamingNotifyType::FAILED, NiPoint3::ZERO, NiPoint3::ZERO, NiQuaternion::IDENTITY, @@ -783,7 +787,7 @@ void PetComponent::ClientFailTamingMinigame() { // Notify the end of a pet taming minigame for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, tamer, NOTIFY_TYPE_FAILED); + script->OnNotifyPetTamingMinigame(m_Parent, tamer, ePetTamingNotifyType::FAILED); } } @@ -884,7 +888,7 @@ void PetComponent::Activate(Item* item, bool registerPet, bool fromTaming) { EntityManager::Instance()->SerializeEntity(m_Parent); - owner->GetCharacter()->SetPlayerFlag(69, true); + owner->GetCharacter()->SetPlayerFlag(ePlayerFlag::FIRST_MANUAL_PET_HIBERNATE, true); if (registerPet) { GameMessages::SendAddPetToPlayer(m_Owner, 0, GeneralUtils::UTF8ToUTF16(m_Name), m_DatabaseId, m_Parent->GetLOT(), owner->GetSystemAddress()); @@ -928,7 +932,7 @@ void PetComponent::AddDrainImaginationTimer(Item* item, bool fromTaming) { auto playerEntity = playerDestroyableComponent->GetParent(); if (!playerEntity) return; - GameMessages::SendUseItemRequirementsResponse(playerEntity->GetObjectID(), playerEntity->GetSystemAddress(), UseItemResponse::NoImaginationForPet); + GameMessages::SendUseItemRequirementsResponse(playerEntity->GetObjectID(), playerEntity->GetSystemAddress(), eUseItemResponse::NoImaginationForPet); } this->AddDrainImaginationTimer(item); diff --git a/dGame/dComponents/PetComponent.h b/dGame/dComponents/PetComponent.h index e3c1556b..b3d089a9 100644 --- a/dGame/dComponents/PetComponent.h +++ b/dGame/dComponents/PetComponent.h @@ -263,7 +263,7 @@ private: /** * Flags that indicate that a player has tamed a pet, indexed by the LOT of the pet */ - static std::map<LOT, uint32_t> petFlags; + static std::map<LOT, int32_t> petFlags; /** * The ID of the component in the pet component table diff --git a/dGame/dComponents/PossessorComponent.cpp b/dGame/dComponents/PossessorComponent.cpp index 69046c3b..387b3479 100644 --- a/dGame/dComponents/PossessorComponent.cpp +++ b/dGame/dComponents/PossessorComponent.cpp @@ -4,6 +4,8 @@ #include "EntityManager.h" #include "GameMessages.h" #include "eUnequippableActiveType.h" +#include "eControlScheme.h" +#include "eStateChangeType.h" PossessorComponent::PossessorComponent(Entity* parent) : Component(parent) { m_Possessable = LWOOBJID_EMPTY; @@ -78,5 +80,5 @@ void PossessorComponent::Dismount(Entity* mount, bool forceDismount) { if (characterComponent) characterComponent->SetIsRacing(false); } // Make sure we don't have wacky controls - GameMessages::SendSetPlayerControlScheme(m_Parent, eControlSceme::SCHEME_A); + GameMessages::SendSetPlayerControlScheme(m_Parent, eControlScheme::SCHEME_A); } diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index 4b9e287f..c87d0744 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -476,7 +476,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet settings.push_back(propertyObjectID); settings.push_back(modelType); - inventoryComponent->AddItem(6662, 1, eLootSourceType::LOOT_SOURCE_DELETION, eInventoryType::MODELS_IN_BBB, settings, LWOOBJID_EMPTY, false, false, spawnerId); + inventoryComponent->AddItem(6662, 1, eLootSourceType::DELETION, eInventoryType::MODELS_IN_BBB, settings, LWOOBJID_EMPTY, false, false, spawnerId); auto* item = inventoryComponent->FindItemBySubKey(spawnerId); if (item == nullptr) { @@ -498,7 +498,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet if (spawner != nullptr) { dZoneManager::Instance()->RemoveSpawner(spawner->m_Info.spawnerID); } else { - model->Smash(SILENT); + model->Smash(LWOOBJID_EMPTY, eKillType::SILENT); } item->SetCount(0, true, false, false); @@ -506,7 +506,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet return; } - inventoryComponent->AddItem(model->GetLOT(), 1, eLootSourceType::LOOT_SOURCE_DELETION, INVALID, {}, LWOOBJID_EMPTY, false); + inventoryComponent->AddItem(model->GetLOT(), 1, eLootSourceType::DELETION, INVALID, {}, LWOOBJID_EMPTY, false); auto* item = inventoryComponent->FindItemByLot(model->GetLOT()); @@ -551,7 +551,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet if (spawner != nullptr) { dZoneManager::Instance()->RemoveSpawner(spawner->m_Info.spawnerID); } else { - model->Smash(SILENT); + model->Smash(LWOOBJID_EMPTY, eKillType::SILENT); } } diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index fe4f1faf..703ec7f3 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -311,7 +311,7 @@ void RacingControlComponent::OnRequestDie(Entity* player) { if (!racingPlayer.noSmashOnReload) { racingPlayer.smashedTimes++; GameMessages::SendDie(vehicle, vehicle->GetObjectID(), LWOOBJID_EMPTY, true, - VIOLENT, u"", 0, 0, 90.0f, false, true, 0); + eKillType::VIOLENT, u"", 0, 0, 90.0f, false, true, 0); auto* destroyableComponent = vehicle->GetComponent<DestroyableComponent>(); uint32_t respawnImagination = 0; @@ -765,7 +765,7 @@ void RacingControlComponent::Update(float deltaTime) { // be smashed by death plane if (vehiclePosition.y < -500) { GameMessages::SendDie(vehicle, m_Parent->GetObjectID(), - LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, + LWOOBJID_EMPTY, true, eKillType::VIOLENT, u"", 0, 0, 0, true, false, 0); OnRequestDie(playerEntity); diff --git a/dGame/dComponents/RailActivatorComponent.cpp b/dGame/dComponents/RailActivatorComponent.cpp index 49fc105d..e4091046 100644 --- a/dGame/dComponents/RailActivatorComponent.cpp +++ b/dGame/dComponents/RailActivatorComponent.cpp @@ -7,6 +7,7 @@ #include "RebuildComponent.h" #include "Game.h" #include "dLogger.h" +#include "eStateChangeType.h" RailActivatorComponent::RailActivatorComponent(Entity* parent, int32_t componentID) : Component(parent) { m_ComponentID = componentID; @@ -41,7 +42,7 @@ RailActivatorComponent::~RailActivatorComponent() = default; void RailActivatorComponent::OnUse(Entity* originator) { auto* rebuildComponent = m_Parent->GetComponent<RebuildComponent>(); - if (rebuildComponent != nullptr && rebuildComponent->GetState() != REBUILD_COMPLETED) + if (rebuildComponent != nullptr && rebuildComponent->GetState() != eRebuildState::COMPLETED) return; if (rebuildComponent != nullptr) { diff --git a/dGame/dComponents/RebuildComponent.cpp b/dGame/dComponents/RebuildComponent.cpp index e3c885dd..fcf2738c 100644 --- a/dGame/dComponents/RebuildComponent.cpp +++ b/dGame/dComponents/RebuildComponent.cpp @@ -9,6 +9,9 @@ #include "MissionComponent.h" #include "eMissionTaskType.h" #include "eTriggerEventType.h" +#include "eQuickBuildFailReason.h" +#include "eTerminateType.h" +#include "eGameActivity.h" #include "dServer.h" #include "PacketUtils.h" @@ -47,7 +50,7 @@ RebuildComponent::~RebuildComponent() { Entity* builder = GetBuilder(); if (builder) { - CancelRebuild(builder, eFailReason::REASON_BUILD_ENDED, true); + CancelRebuild(builder, eQuickBuildFailReason::BUILD_ENDED, true); } DespawnActivator(); @@ -66,7 +69,7 @@ void RebuildComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitia // If build state is completed and we've already serialized once in the completed state, // don't serializing this component anymore as this will cause the build to jump again. // If state changes, serialization will begin again. - if (!m_StateDirty && m_State == REBUILD_COMPLETED) { + if (!m_StateDirty && m_State == eRebuildState::COMPLETED) { outBitStream->Write0(); outBitStream->Write0(); return; @@ -90,7 +93,7 @@ void RebuildComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitia outBitStream->Write1(); - outBitStream->Write<uint32_t>(m_State); + outBitStream->Write(m_State); outBitStream->Write(m_ShowResetEffect); outBitStream->Write(m_Activator != nullptr); @@ -120,7 +123,7 @@ void RebuildComponent::Update(float deltaTime) { }*/ switch (m_State) { - case REBUILD_OPEN: { + case eRebuildState::OPEN: { SpawnActivator(); m_TimeBeforeDrain = 0; @@ -150,7 +153,7 @@ void RebuildComponent::Update(float deltaTime) { break; } - case REBUILD_COMPLETED: { + case eRebuildState::COMPLETED: { m_Timer += deltaTime; // For reset times < 0 this has to be handled manually @@ -172,7 +175,7 @@ void RebuildComponent::Update(float deltaTime) { } break; } - case REBUILD_BUILDING: + case eRebuildState::BUILDING: { Entity* builder = GetBuilder(); @@ -201,7 +204,7 @@ void RebuildComponent::Update(float deltaTime) { ++m_DrainedImagination; if (newImagination == 0 && m_DrainedImagination < m_TakeImagination) { - CancelRebuild(builder, eFailReason::REASON_OUT_OF_IMAGINATION, true); + CancelRebuild(builder, eQuickBuildFailReason::OUT_OF_IMAGINATION, true); break; } @@ -213,7 +216,7 @@ void RebuildComponent::Update(float deltaTime) { break; } - case REBUILD_INCOMPLETE: { + case eRebuildState::INCOMPLETE: { m_TimerIncomplete += deltaTime; // For reset times < 0 this has to be handled manually @@ -234,12 +237,12 @@ void RebuildComponent::Update(float deltaTime) { } break; } - case REBUILD_RESETTING: break; + case eRebuildState::RESETTING: break; } } void RebuildComponent::OnUse(Entity* originator) { - if (GetBuilder() != nullptr || m_State == REBUILD_COMPLETED) { + if (GetBuilder() != nullptr || m_State == eRebuildState::COMPLETED) { return; } @@ -393,18 +396,18 @@ void RebuildComponent::SetRepositionPlayer(bool value) { } void RebuildComponent::StartRebuild(Entity* user) { - if (m_State == eRebuildState::REBUILD_OPEN || m_State == eRebuildState::REBUILD_COMPLETED || m_State == eRebuildState::REBUILD_INCOMPLETE) { + if (m_State == eRebuildState::OPEN || m_State == eRebuildState::COMPLETED || m_State == eRebuildState::INCOMPLETE) { m_Builder = user->GetObjectID(); auto* character = user->GetComponent<CharacterComponent>(); - character->SetCurrentActivity(eGameActivities::ACTIVITY_QUICKBUILDING); + character->SetCurrentActivity(eGameActivity::QUICKBUILDING); EntityManager::Instance()->SerializeEntity(user); - GameMessages::SendRebuildNotifyState(m_Parent, m_State, eRebuildState::REBUILD_BUILDING, user->GetObjectID()); - GameMessages::SendEnableRebuild(m_Parent, true, false, false, eFailReason::REASON_NOT_GIVEN, 0.0f, user->GetObjectID()); + GameMessages::SendRebuildNotifyState(m_Parent, m_State, eRebuildState::BUILDING, user->GetObjectID()); + GameMessages::SendEnableRebuild(m_Parent, true, false, false, eQuickBuildFailReason::NOT_GIVEN, 0.0f, user->GetObjectID()); - m_State = eRebuildState::REBUILD_BUILDING; + m_State = eRebuildState::BUILDING; m_StateDirty = true; EntityManager::Instance()->SerializeEntity(m_Parent); @@ -432,7 +435,7 @@ void RebuildComponent::CompleteRebuild(Entity* user) { auto* characterComponent = user->GetComponent<CharacterComponent>(); if (characterComponent != nullptr) { - characterComponent->SetCurrentActivity(eGameActivities::ACTIVITY_NONE); + characterComponent->SetCurrentActivity(eGameActivity::NONE); characterComponent->TrackRebuildComplete(); } else { Game::logger->Log("RebuildComponent", "Some user tried to finish the rebuild but they didn't have a character somehow."); @@ -441,13 +444,13 @@ void RebuildComponent::CompleteRebuild(Entity* user) { EntityManager::Instance()->SerializeEntity(user); - GameMessages::SendRebuildNotifyState(m_Parent, m_State, eRebuildState::REBUILD_COMPLETED, user->GetObjectID()); + GameMessages::SendRebuildNotifyState(m_Parent, m_State, eRebuildState::COMPLETED, user->GetObjectID()); GameMessages::SendPlayFXEffect(m_Parent, 507, u"create", "BrickFadeUpVisCompleteEffect", LWOOBJID_EMPTY, 0.4f, 1.0f, true); - GameMessages::SendEnableRebuild(m_Parent, false, false, true, eFailReason::REASON_NOT_GIVEN, m_ResetTime, user->GetObjectID()); + GameMessages::SendEnableRebuild(m_Parent, false, false, true, eQuickBuildFailReason::NOT_GIVEN, m_ResetTime, user->GetObjectID()); GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); - m_State = eRebuildState::REBUILD_COMPLETED; + m_State = eRebuildState::COMPLETED; m_StateDirty = true; m_Timer = 0.0f; m_DrainedImagination = 0; @@ -520,17 +523,17 @@ void RebuildComponent::CompleteRebuild(Entity* user) { void RebuildComponent::ResetRebuild(bool failed) { Entity* builder = GetBuilder(); - if (m_State == eRebuildState::REBUILD_BUILDING && builder) { - GameMessages::SendEnableRebuild(m_Parent, false, false, failed, eFailReason::REASON_NOT_GIVEN, m_ResetTime, builder->GetObjectID()); + if (m_State == eRebuildState::BUILDING && builder) { + GameMessages::SendEnableRebuild(m_Parent, false, false, failed, eQuickBuildFailReason::NOT_GIVEN, m_ResetTime, builder->GetObjectID()); if (failed) { GameMessages::SendPlayAnimation(builder, u"rebuild-fail"); } } - GameMessages::SendRebuildNotifyState(m_Parent, m_State, eRebuildState::REBUILD_RESETTING, LWOOBJID_EMPTY); + GameMessages::SendRebuildNotifyState(m_Parent, m_State, eRebuildState::RESETTING, LWOOBJID_EMPTY); - m_State = eRebuildState::REBUILD_RESETTING; + m_State = eRebuildState::RESETTING; m_StateDirty = true; m_Timer = 0.0f; m_TimerIncomplete = 0.0f; @@ -552,15 +555,15 @@ void RebuildComponent::ResetRebuild(bool failed) { } } -void RebuildComponent::CancelRebuild(Entity* entity, eFailReason failReason, bool skipChecks) { - if (m_State != eRebuildState::REBUILD_COMPLETED || skipChecks) { +void RebuildComponent::CancelRebuild(Entity* entity, eQuickBuildFailReason failReason, bool skipChecks) { + if (m_State != eRebuildState::COMPLETED || skipChecks) { m_Builder = LWOOBJID_EMPTY; const auto entityID = entity != nullptr ? entity->GetObjectID() : LWOOBJID_EMPTY; // Notify the client that a state has changed - GameMessages::SendRebuildNotifyState(m_Parent, m_State, eRebuildState::REBUILD_INCOMPLETE, entityID); + GameMessages::SendRebuildNotifyState(m_Parent, m_State, eRebuildState::INCOMPLETE, entityID); GameMessages::SendEnableRebuild(m_Parent, false, true, false, failReason, m_Timer, entityID); // Now terminate any interaction with the rebuild @@ -568,7 +571,7 @@ void RebuildComponent::CancelRebuild(Entity* entity, eFailReason failReason, boo GameMessages::SendTerminateInteraction(m_Parent->GetObjectID(), eTerminateType::FROM_INTERACTION, m_Parent->GetObjectID()); // Now update the component itself - m_State = eRebuildState::REBUILD_INCOMPLETE; + m_State = eRebuildState::INCOMPLETE; m_StateDirty = true; // Notify scripts and possible subscribers @@ -586,7 +589,7 @@ void RebuildComponent::CancelRebuild(Entity* entity, eFailReason failReason, boo CharacterComponent* characterComponent = entity->GetComponent<CharacterComponent>(); if (characterComponent) { - characterComponent->SetCurrentActivity(eGameActivities::ACTIVITY_NONE); + characterComponent->SetCurrentActivity(eGameActivity::NONE); EntityManager::Instance()->SerializeEntity(entity); } } diff --git a/dGame/dComponents/RebuildComponent.h b/dGame/dComponents/RebuildComponent.h index a8e11e4c..09dd0465 100644 --- a/dGame/dComponents/RebuildComponent.h +++ b/dGame/dComponents/RebuildComponent.h @@ -10,8 +10,10 @@ #include "Preconditions.h" #include "Component.h" #include "eReplicaComponentType.h" +#include "eRebuildState.h" class Entity; +enum class eQuickBuildFailReason : uint32_t; /** * Component that handles entities that can be built into other entities using the quick build mechanic. Generally @@ -215,7 +217,7 @@ public: * @param failReason the reason the rebuild was cancelled * @param skipChecks whether or not to skip the check for the rebuild not being completed */ - void CancelRebuild(Entity* builder, eFailReason failReason, bool skipChecks = false); + void CancelRebuild(Entity* builder, eQuickBuildFailReason failReason, bool skipChecks = false); private: /** * Whether or not the quickbuild state has been changed since we last serialized it. @@ -225,7 +227,7 @@ private: /** * The state the rebuild is currently in */ - eRebuildState m_State = eRebuildState::REBUILD_OPEN; + eRebuildState m_State = eRebuildState::OPEN; /** * The time that has passed since initiating the rebuild diff --git a/dGame/dComponents/RocketLaunchpadControlComponent.cpp b/dGame/dComponents/RocketLaunchpadControlComponent.cpp index 4f248a40..6cc5e2bc 100644 --- a/dGame/dComponents/RocketLaunchpadControlComponent.cpp +++ b/dGame/dComponents/RocketLaunchpadControlComponent.cpp @@ -17,6 +17,7 @@ #include "dServer.h" #include "dMessageIdentifiers.h" #include "PacketUtils.h" +#include "eObjectWorldState.h" RocketLaunchpadControlComponent::RocketLaunchpadControlComponent(Entity* parent, int rocketId) : Component(parent) { auto query = CDClientDatabase::CreatePreppedStmt( @@ -77,7 +78,7 @@ void RocketLaunchpadControlComponent::Launch(Entity* originator, LWOMAPID mapId, GameMessages::SendFireEventClientSide(m_Parent->GetObjectID(), originator->GetSystemAddress(), u"RocketEquipped", rocket->GetId(), cloneId, -1, originator->GetObjectID()); - GameMessages::SendChangeObjectWorldState(rocket->GetId(), WORLDSTATE_ATTACHED, UNASSIGNED_SYSTEM_ADDRESS); + GameMessages::SendChangeObjectWorldState(rocket->GetId(), eObjectWorldState::ATTACHED, UNASSIGNED_SYSTEM_ADDRESS); EntityManager::Instance()->SerializeEntity(originator); } diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index 1bc8c01f..f998d686 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -21,6 +21,7 @@ #include "dMessageIdentifiers.h" #include "Loot.h" #include "eMissionTaskType.h" +#include "eMatchUpdate.h" #include "CDCurrencyTableTable.h" #include "CDActivityRewardsTable.h" @@ -167,9 +168,9 @@ void ScriptedActivityComponent::PlayerJoinLobby(Entity* player) { } std::string matchUpdate = "player=9:" + std::to_string(entity->GetObjectID()) + "\nplayerName=0:" + entity->GetCharacter()->GetName(); - GameMessages::SendMatchUpdate(player, player->GetSystemAddress(), matchUpdate, eMatchUpdate::MATCH_UPDATE_PLAYER_JOINED); + GameMessages::SendMatchUpdate(player, player->GetSystemAddress(), matchUpdate, eMatchUpdate::PLAYER_ADDED); PlayerReady(entity, joinedPlayer->ready); - GameMessages::SendMatchUpdate(entity, entity->GetSystemAddress(), matchUpdateJoined, eMatchUpdate::MATCH_UPDATE_PLAYER_JOINED); + GameMessages::SendMatchUpdate(entity, entity->GetSystemAddress(), matchUpdateJoined, eMatchUpdate::PLAYER_ADDED); } } } @@ -185,7 +186,7 @@ void ScriptedActivityComponent::PlayerJoinLobby(Entity* player) { if (m_ActivityInfo.maxTeamSize != 1 && playerLobby->players.size() >= m_ActivityInfo.minTeamSize || m_ActivityInfo.maxTeamSize == 1 && playerLobby->players.size() >= m_ActivityInfo.minTeams) { // Update the joining player on the match timer std::string matchTimerUpdate = "time=3:" + std::to_string(playerLobby->timer); - GameMessages::SendMatchUpdate(player, player->GetSystemAddress(), matchTimerUpdate, eMatchUpdate::MATCH_UPDATE_TIME); + GameMessages::SendMatchUpdate(player, player->GetSystemAddress(), matchTimerUpdate, eMatchUpdate::PHASE_WAIT_READY); } } @@ -201,7 +202,7 @@ void ScriptedActivityComponent::PlayerLeave(LWOOBJID playerID) { if (entity == nullptr) continue; - GameMessages::SendMatchUpdate(entity, entity->GetSystemAddress(), matchUpdateLeft, eMatchUpdate::MATCH_UPDATE_PLAYER_LEFT); + GameMessages::SendMatchUpdate(entity, entity->GetSystemAddress(), matchUpdateLeft, eMatchUpdate::PLAYER_REMOVED); } delete lobby->players[i]; @@ -242,7 +243,7 @@ void ScriptedActivityComponent::Update(float deltaTime) { continue; std::string matchTimerUpdate = "time=3:" + std::to_string(lobby->timer); - GameMessages::SendMatchUpdate(entity, entity->GetSystemAddress(), matchTimerUpdate, eMatchUpdate::MATCH_UPDATE_TIME); + GameMessages::SendMatchUpdate(entity, entity->GetSystemAddress(), matchTimerUpdate, eMatchUpdate::PHASE_WAIT_READY); } } @@ -267,7 +268,7 @@ void ScriptedActivityComponent::Update(float deltaTime) { if (entity == nullptr) continue; - GameMessages::SendMatchUpdate(entity, entity->GetSystemAddress(), matchTimerUpdate, eMatchUpdate::MATCH_UPDATE_TIME_START_DELAY); + GameMessages::SendMatchUpdate(entity, entity->GetSystemAddress(), matchTimerUpdate, eMatchUpdate::PHASE_WAIT_START); } } @@ -375,8 +376,8 @@ void ScriptedActivityComponent::PlayerReady(Entity* player, bool bReady) { // Update players in lobby on player being ready std::string matchReadyUpdate = "player=9:" + std::to_string(player->GetObjectID()); - eMatchUpdate readyStatus = eMatchUpdate::MATCH_UPDATE_PLAYER_READY; - if (!bReady) readyStatus = eMatchUpdate::MATCH_UPDATE_PLAYER_UNREADY; + eMatchUpdate readyStatus = eMatchUpdate::PLAYER_READY; + if (!bReady) readyStatus = eMatchUpdate::PLAYER_NOT_READY; for (LobbyPlayer* otherPlayer : lobby->players) { auto* entity = otherPlayer->GetEntity(); if (entity == nullptr) diff --git a/dGame/dComponents/SwitchComponent.cpp b/dGame/dComponents/SwitchComponent.cpp index 392d885a..c59559c2 100644 --- a/dGame/dComponents/SwitchComponent.cpp +++ b/dGame/dComponents/SwitchComponent.cpp @@ -39,7 +39,7 @@ bool SwitchComponent::GetActive() const { void SwitchComponent::EntityEnter(Entity* entity) { if (!m_Active) { if (m_Rebuild) { - if (m_Rebuild->GetState() != eRebuildState::REBUILD_COMPLETED) return; + if (m_Rebuild->GetState() != eRebuildState::COMPLETED) return; } m_Active = true; if (!m_Parent) return; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index f5cbc811..4d5a378c 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -36,6 +36,12 @@ #include "eMissionState.h" #include "eObjectBits.h" #include "eTriggerEventType.h" +#include "eMatchUpdate.h" +#include "eCyclingMode.h" +#include "eCinematicEvent.h" +#include "eQuickBuildFailReason.h" +#include "eControlScheme.h" +#include "eStateChangeType.h" #include <sstream> #include <future> @@ -294,9 +300,9 @@ void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, cons bitStream.Write(bAllowCyclingWhileDeadOnly); - bitStream.Write(cyclingMode != ALLOW_CYCLE_TEAMMATES); - if (cyclingMode != ALLOW_CYCLE_TEAMMATES) { - bitStream.Write<uint32_t>(cyclingMode); + bitStream.Write(cyclingMode != eCyclingMode::ALLOW_CYCLE_TEAMMATES); + if (cyclingMode != eCyclingMode::ALLOW_CYCLE_TEAMMATES) { + bitStream.Write(cyclingMode); } SEND_PACKET; @@ -440,8 +446,8 @@ void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const System bitStream.Write(item->GetInfo().isBOE); bitStream.Write(item->GetInfo().isBOP); - bitStream.Write(lootSourceType != eLootSourceType::LOOT_SOURCE_NONE); // Loot source - if (lootSourceType != eLootSourceType::LOOT_SOURCE_NONE) bitStream.Write(lootSourceType); + bitStream.Write(lootSourceType != eLootSourceType::NONE); // Loot source + if (lootSourceType != eLootSourceType::NONE) bitStream.Write(lootSourceType); LWONameValue extraInfo; auto config = item->GetConfig(); @@ -489,7 +495,7 @@ void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const System SEND_PACKET; } -void GameMessages::SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFlagID, bool bFlag, const SystemAddress& sysAddr) { +void GameMessages::SendNotifyClientFlagChange(const LWOOBJID& objectID, uint32_t iFlagID, bool bFlag, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -501,7 +507,7 @@ void GameMessages::SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFla SEND_PACKET; } -void GameMessages::SendChangeObjectWorldState(const LWOOBJID& objectID, int state, const SystemAddress& sysAddr) { +void GameMessages::SendChangeObjectWorldState(const LWOOBJID& objectID, eObjectWorldState state, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -582,8 +588,8 @@ void GameMessages::SendModifyLEGOScore(Entity* entity, const SystemAddress& sysA bitStream.Write((uint16_t)GAME_MSG_MODIFY_LEGO_SCORE); bitStream.Write(score); - bitStream.Write(sourceType != eLootSourceType::LOOT_SOURCE_NONE); - if (sourceType != eLootSourceType::LOOT_SOURCE_NONE) bitStream.Write(sourceType); + bitStream.Write(sourceType != eLootSourceType::NONE); + if (sourceType != eLootSourceType::NONE) bitStream.Write(sourceType); SEND_PACKET; } @@ -743,14 +749,14 @@ void GameMessages::SendSetCurrency(Entity* entity, int64_t currency, int lootTyp bitStream.Write(sourceTradeID != LWOOBJID_EMPTY); if (sourceTradeID != LWOOBJID_EMPTY) bitStream.Write(sourceTradeID); - bitStream.Write(sourceType != LOOTTYPE_NONE); - if (sourceType != LOOTTYPE_NONE) bitStream.Write(sourceType); + bitStream.Write(sourceType != eLootSourceType::NONE); + if (sourceType != eLootSourceType::NONE) bitStream.Write(sourceType); SystemAddress sysAddr = entity->GetSystemAddress(); SEND_PACKET; } -void GameMessages::SendRebuildNotifyState(Entity* entity, int prevState, int state, const LWOOBJID& playerID) { +void GameMessages::SendRebuildNotifyState(Entity* entity, eRebuildState prevState, eRebuildState state, const LWOOBJID& playerID) { CBITSTREAM; CMSGHEADER; @@ -764,7 +770,7 @@ void GameMessages::SendRebuildNotifyState(Entity* entity, int prevState, int sta SEND_PACKET_BROADCAST; } -void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, bool success, int failReason, float duration, const LWOOBJID& playerID) { +void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, bool success, eQuickBuildFailReason failReason, float duration, const LWOOBJID& playerID) { CBITSTREAM; CMSGHEADER; @@ -775,8 +781,8 @@ void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, boo bitStream.Write(fail); bitStream.Write(success); - bitStream.Write(failReason != eFailReason::REASON_NOT_GIVEN); - if (failReason != eFailReason::REASON_NOT_GIVEN) bitStream.Write(failReason); + bitStream.Write(failReason != eQuickBuildFailReason::NOT_GIVEN); + if (failReason != eQuickBuildFailReason::NOT_GIVEN) bitStream.Write(failReason); bitStream.Write(duration); bitStream.Write(playerID); @@ -843,8 +849,8 @@ void GameMessages::SendDie(Entity* entity, const LWOOBJID& killerID, const LWOOB bitStream.Write(directionRelative_AngleY); bitStream.Write(directionRelative_Force); - bitStream.Write(killType != VIOLENT); - if (killType != VIOLENT) bitStream.Write(killType); + bitStream.Write(killType != eKillType::VIOLENT); + if (killType != eKillType::VIOLENT) bitStream.Write(killType); bitStream.Write(killerID); @@ -1104,7 +1110,7 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, SEND_PACKET; } -void GameMessages::SendSetPlayerControlScheme(Entity* entity, eControlSceme controlScheme) { +void GameMessages::SendSetPlayerControlScheme(Entity* entity, eControlScheme controlScheme) { CBITSTREAM; CMSGHEADER; @@ -1117,8 +1123,8 @@ void GameMessages::SendSetPlayerControlScheme(Entity* entity, eControlSceme cont bitStream.Write(bDelayCamSwitchIfInCinematic); bitStream.Write(bSwitchCam); - bitStream.Write(controlScheme != SCHEME_A); - if (controlScheme != SCHEME_A) bitStream.Write(controlScheme); + bitStream.Write(controlScheme != eControlScheme::SCHEME_A); + if (controlScheme != eControlScheme::SCHEME_A) bitStream.Write(controlScheme); SystemAddress sysAddr = entity->GetSystemAddress(); SEND_PACKET; @@ -1376,7 +1382,7 @@ void GameMessages::SendUseItemResult(Entity* entity, LOT templateID, bool useIte SEND_PACKET; } -void GameMessages::SendUseItemRequirementsResponse(LWOOBJID objectID, const SystemAddress& sysAddr, UseItemResponse itemResponse) { +void GameMessages::SendUseItemRequirementsResponse(LWOOBJID objectID, const SystemAddress& sysAddr, eUseItemResponse itemResponse) { CBITSTREAM; CMSGHEADER; @@ -1449,7 +1455,7 @@ void GameMessages::SendMatchResponse(Entity* entity, const SystemAddress& sysAdd SEND_PACKET; } -void GameMessages::SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, std::string data, int type) { +void GameMessages::SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, std::string data, eMatchUpdate type) { CBITSTREAM; CMSGHEADER; @@ -2879,7 +2885,7 @@ void GameMessages::SendEndCinematic(LWOOBJID objectId, std::u16string pathName, void GameMessages::HandleCinematicUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { eCinematicEvent event; if (!inStream->ReadBit()) { - event = STARTED; + event = eCinematicEvent::STARTED; } else { inStream->Read<eCinematicEvent>(event); } @@ -3425,7 +3431,7 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* //Pets: -void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId, LWOOBJID playerTamingId, bool bForceTeleport, uint32_t notifyType, NiPoint3 petsDestPos, NiPoint3 telePos, NiQuaternion teleRot, const SystemAddress& sysAddr) { +void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId, LWOOBJID playerTamingId, bool bForceTeleport, ePetTamingNotifyType notifyType, NiPoint3 petsDestPos, NiPoint3 telePos, NiQuaternion teleRot, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; @@ -4141,7 +4147,7 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, float directionRelativeAngleXZ; float directionRelativeAngleY; float directionRelativeForce; - int32_t killType = VIOLENT; + eKillType killType = eKillType::VIOLENT; LWOOBJID killerID; LWOOBJID lootOwnerID = LWOOBJID_EMPTY; @@ -4415,7 +4421,7 @@ void GameMessages::SendVehicleStopBoost(Entity* targetEntity, const SystemAddres bitStream.Write(targetEntity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_VEHICLE_STOP_BOOST); - + bitStream.Write(affectPassive); SEND_PACKET_BROADCAST; @@ -4427,7 +4433,7 @@ void GameMessages::SendSetResurrectRestoreValues(Entity* targetEntity, int32_t a bitStream.Write(targetEntity->GetObjectID()); bitStream.Write(GAME_MSG::GAME_MSG_SET_RESURRECT_RESTORE_VALUES); - + bitStream.Write(armorRestore != -1); if (armorRestore != -1) bitStream.Write(armorRestore); @@ -4766,7 +4772,7 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti inv->RemoveItem(tokenId, altCurrencyCost); - inv->AddItem(item, count, eLootSourceType::LOOT_SOURCE_VENDOR); + inv->AddItem(item, count, eLootSourceType::VENDOR); } else { float buyScalar = vend->GetBuyScalar(); @@ -4786,8 +4792,8 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti inv->RemoveItem(itemComp.currencyLOT, altCurrencyCost); } - character->SetCoins(character->GetCoins() - (coinCost), eLootSourceType::LOOT_SOURCE_VENDOR); - inv->AddItem(item, count, eLootSourceType::LOOT_SOURCE_VENDOR); + character->SetCoins(character->GetCoins() - (coinCost), eLootSourceType::VENDOR); + inv->AddItem(item, count, eLootSourceType::VENDOR); } GameMessages::SendVendorTransactionResult(entity, sysAddr); @@ -4829,12 +4835,12 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit float sellScalar = vend->GetSellScalar(); if (Inventory::IsValidItem(itemComp.currencyLOT)) { const auto altCurrency = static_cast<uint32_t>(itemComp.altCurrencyCost * sellScalar) * count; - inv->AddItem(itemComp.currencyLOT, std::floor(altCurrency), eLootSourceType::LOOT_SOURCE_VENDOR); // Return alt currencies like faction tokens. + 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<uint32_t>(itemComp.baseValue * sellScalar) * count)), eLootSourceType::LOOT_SOURCE_VENDOR); + character->SetCoins(std::floor(character->GetCoins() + (static_cast<uint32_t>(itemComp.baseValue * sellScalar) * count)), eLootSourceType::VENDOR); //EntityManager::Instance()->SerializeEntity(player); // so inventory updates GameMessages::SendVendorTransactionResult(entity, sysAddr); } @@ -4893,7 +4899,7 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* //inv->RemoveItem(count, -1, iObjID); inv->MoveItemToInventory(item, Inventory::FindInventoryTypeForLot(item->GetLot()), count, true, false); - character->SetCoins(character->GetCoins() - cost, eLootSourceType::LOOT_SOURCE_VENDOR); + character->SetCoins(character->GetCoins() - cost, eLootSourceType::VENDOR); //EntityManager::Instance()->SerializeEntity(player); // so inventory updates GameMessages::SendVendorTransactionResult(entity, sysAddr); } @@ -5015,7 +5021,7 @@ void GameMessages::HandleRebuildCancel(RakNet::BitStream* inStream, Entity* enti RebuildComponent* rebComp = static_cast<RebuildComponent*>(entity->GetComponent(eReplicaComponentType::QUICK_BUILD)); if (!rebComp) return; - rebComp->CancelRebuild(EntityManager::Instance()->GetEntity(userID), eFailReason::REASON_CANCELED_EARLY); + rebComp->CancelRebuild(EntityManager::Instance()->GetEntity(userID), eQuickBuildFailReason::CANCELED_EARLY); } void GameMessages::HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { @@ -5135,12 +5141,12 @@ void GameMessages::HandleModularBuildConvertModel(RakNet::BitStream* inStream, E item->Disassemble(TEMP_MODELS); - item->SetCount(item->GetCount() - 1, false, false, true, eLootSourceType::LOOT_SOURCE_QUICKBUILD); + item->SetCount(item->GetCount() - 1, false, false, true, eLootSourceType::QUICKBUILD); } void GameMessages::HandleSetFlag(RakNet::BitStream* inStream, Entity* entity) { bool bFlag{}; - int iFlagID{}; + int32_t iFlagID{}; inStream->Read(bFlag); inStream->Read(iFlagID); @@ -5301,7 +5307,7 @@ void GameMessages::HandlePickupCurrency(RakNet::BitStream* inStream, Entity* ent auto* ch = entity->GetCharacter(); if (entity->CanPickupCoins(currency)) { - ch->SetCoins(ch->GetCoins() + currency, eLootSourceType::LOOT_SOURCE_PICKUP); + ch->SetCoins(ch->GetCoins() + currency, eLootSourceType::PICKUP); } } @@ -5615,9 +5621,9 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* config.push_back(moduleAssembly); if (count == 3) { - inv->AddItem(6416, 1, eLootSourceType::LOOT_SOURCE_QUICKBUILD, eInventoryType::MODELS, config); + inv->AddItem(6416, 1, eLootSourceType::QUICKBUILD, eInventoryType::MODELS, config); } else if (count == 7) { - inv->AddItem(8092, 1, eLootSourceType::LOOT_SOURCE_QUICKBUILD, eInventoryType::MODELS, config); + inv->AddItem(8092, 1, eLootSourceType::QUICKBUILD, eInventoryType::MODELS, config); } auto* missionComponent = character->GetComponent<MissionComponent>(); diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 68f4542f..ce24a105 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -8,6 +8,9 @@ #include "eMovementPlatformState.h" #include "NiPoint3.h" #include "eEndBehavior.h" +#include "eCyclingMode.h" +#include "eLootSourceType.h" +#include "Brick.h" class AMFValue; class Entity; @@ -23,6 +26,16 @@ enum class eAnimationFlags : uint32_t; enum class eUnequippableActiveType; enum eInventoryType : uint32_t; enum class eGameMasterLevel : uint8_t; +enum class eMatchUpdate : int32_t; +enum class eKillType : uint32_t; +enum class eObjectWorldState : uint32_t; +enum class eTerminateType : uint32_t; +enum class eControlScheme : uint32_t; +enum class eStateChangeType : uint32_t; +enum class ePetTamingNotifyType : uint32_t; +enum class eUseItemResponse : uint32_t; +enum class eQuickBuildFailReason : uint32_t; +enum class eRebuildState : uint32_t; namespace GameMessages { class PropertyDataMessage; @@ -51,8 +64,7 @@ namespace GameMessages { int targetTYPE = 0 ); - void SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, const SystemAddress& sysAddr, - bool bAllowCyclingWhileDeadOnly = true, eCyclingMode cyclingMode = ALLOW_CYCLE_TEAMMATES); + void SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, const SystemAddress& sysAddr, bool bAllowCyclingWhileDeadOnly = true, eCyclingMode cyclingMode = eCyclingMode::ALLOW_CYCLE_TEAMMATES); void SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& sysAddr, std::string audioGUID); @@ -66,9 +78,9 @@ namespace GameMessages { void SendGMLevelBroadcast(const LWOOBJID& objectID, eGameMasterLevel level); void SendChatModeUpdate(const LWOOBJID& objectID, eGameMasterLevel level); - void SendAddItemToInventoryClientSync(Entity* entity, const SystemAddress& sysAddr, Item* item, const LWOOBJID& objectID, bool showFlyingLoot, int itemCount, LWOOBJID subKey = LWOOBJID_EMPTY, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); - void SendNotifyClientFlagChange(const LWOOBJID& objectID, int iFlagID, bool bFlag, const SystemAddress& sysAddr); - void SendChangeObjectWorldState(const LWOOBJID& objectID, int state, const SystemAddress& sysAddr); + void SendAddItemToInventoryClientSync(Entity* entity, const SystemAddress& sysAddr, Item* item, const LWOOBJID& objectID, bool showFlyingLoot, int itemCount, LWOOBJID subKey = LWOOBJID_EMPTY, eLootSourceType lootSourceType = eLootSourceType::NONE); + void SendNotifyClientFlagChange(const LWOOBJID& objectID, uint32_t iFlagID, bool bFlag, const SystemAddress& sysAddr); + void SendChangeObjectWorldState(const LWOOBJID& objectID, eObjectWorldState state, const SystemAddress& sysAddr); void SendOfferMission(const LWOOBJID& entity, const SystemAddress& sysAddr, int32_t missionID, const LWOOBJID& offererID); void SendNotifyMission(Entity* entity, const SystemAddress& sysAddr, int missionID, int missionState, bool sendingRewards); @@ -86,8 +98,8 @@ namespace GameMessages { void SendBroadcastTextToChatbox(Entity* entity, const SystemAddress& sysAddr, const std::u16string& attrs, const std::u16string& wsText); void SendSetCurrency(Entity* entity, int64_t currency, int lootType, const LWOOBJID& sourceID, const LOT& sourceLOT, int sourceTradeID, bool overrideCurrent, eLootSourceType sourceType); - void SendRebuildNotifyState(Entity* entity, int prevState, int state, const LWOOBJID& playerID); - void SendEnableRebuild(Entity* entity, bool enable, bool fail, bool success, int failReason, float duration, const LWOOBJID& playerID); + void SendRebuildNotifyState(Entity* entity, eRebuildState prevState, eRebuildState state, const LWOOBJID& playerID); + void SendEnableRebuild(Entity* entity, bool enable, bool fail, bool success, eQuickBuildFailReason failReason, float duration, const LWOOBJID& playerID); void AddActivityOwner(Entity* entity, LWOOBJID& ownerID); void SendTerminateInteraction(const LWOOBJID& objectID, eTerminateType type, const LWOOBJID& terminator); @@ -104,7 +116,7 @@ namespace GameMessages { 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 SendSetPlayerControlScheme(Entity* entity, eControlSceme controlScheme); + void SendSetPlayerControlScheme(Entity* entity, eControlScheme controlScheme); void SendPlayerReachedRespawnCheckpoint(Entity* entity, const NiPoint3& position, const NiQuaternion& rotation); void SendAddSkill(Entity* entity, TSkillID skillID, int slotID); @@ -123,7 +135,7 @@ namespace GameMessages { void SendMoveInventoryBatch(Entity* entity, uint32_t stackCount, int srcInv, int dstInv, const LWOOBJID& iObjID); void SendMatchResponse(Entity* entity, const SystemAddress& sysAddr, int response); - void SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, std::string data, int type); + void SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, std::string data, eMatchUpdate type); void HandleUnUseModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); void SendStartCelebrationEffect(Entity* entity, const SystemAddress& sysAddr, int celebrationID); @@ -350,7 +362,7 @@ namespace GameMessages { void HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); //Pets: - void SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId, LWOOBJID playerTamingId, bool bForceTeleport, uint32_t notifyType, NiPoint3 petsDestPos, NiPoint3 telePos, NiQuaternion teleRot, const SystemAddress& sysAddr); + void SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId, LWOOBJID playerTamingId, bool bForceTeleport, ePetTamingNotifyType notifyType, NiPoint3 petsDestPos, NiPoint3 telePos, NiQuaternion teleRot, const SystemAddress& sysAddr); void SendNotifyPetTamingPuzzleSelected(LWOOBJID objectId, std::vector<Brick>& bricks, const SystemAddress& sysAddr); @@ -520,7 +532,7 @@ namespace GameMessages { void SendActivityPause(LWOOBJID objectId, bool pause = false, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void SendStartActivityTime(LWOOBJID objectId, float_t startTime, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void SendRequestActivityEnter(LWOOBJID objectId, const SystemAddress& sysAddr, bool bStart, LWOOBJID userID); - void SendUseItemRequirementsResponse(LWOOBJID objectID, const SystemAddress& sysAddr, UseItemResponse itemResponse); + void SendUseItemRequirementsResponse(LWOOBJID objectID, const SystemAddress& sysAddr, eUseItemResponse itemResponse); // SG: diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 62dffa12..83ac8869 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -18,6 +18,7 @@ #include "Loot.h" #include "eObjectBits.h" #include "eReplicaComponentType.h" +#include "eUseItemResponse.h" #include "CDBrickIDTableTable.h" #include "CDObjectSkillsTable.h" @@ -330,7 +331,7 @@ void Item::UseNonEquip(Item* item) { } } if (playerInventoryComponent->HasSpaceForLoot(rolledLoot)) { - LootGenerator::Instance().GiveLoot(playerInventoryComponent->GetParent(), rolledLoot, eLootSourceType::LOOT_SOURCE_CONSUMPTION); + LootGenerator::Instance().GiveLoot(playerInventoryComponent->GetParent(), rolledLoot, eLootSourceType::CONSUMPTION); item->SetCount(item->GetCount() - 1); } else { success = false; @@ -339,7 +340,7 @@ void Item::UseNonEquip(Item* item) { GameMessages::SendUseItemRequirementsResponse( playerInventoryComponent->GetParent()->GetObjectID(), playerInventoryComponent->GetParent()->GetSystemAddress(), - UseItemResponse::FailedPrecondition + eUseItemResponse::FailedPrecondition ); success = false; } @@ -379,7 +380,7 @@ void Item::Disassemble(const eInventoryType inventoryType) { } for (const auto mod : modArray) { - inventory->GetComponent()->AddItem(mod, 1, eLootSourceType::LOOT_SOURCE_DELETION, inventoryType); + inventory->GetComponent()->AddItem(mod, 1, eLootSourceType::DELETION, inventoryType); } } } @@ -477,7 +478,7 @@ void Item::DisassembleModel() { continue; } - GetInventory()->GetComponent()->AddItem(brickID[0].NDObjectID, 1, eLootSourceType::LOOT_SOURCE_DELETION); + GetInventory()->GetComponent()->AddItem(brickID[0].NDObjectID, 1, eLootSourceType::DELETION); } } diff --git a/dGame/dInventory/Item.h b/dGame/dInventory/Item.h index 6993a0ba..be2359ef 100644 --- a/dGame/dInventory/Item.h +++ b/dGame/dInventory/Item.h @@ -7,6 +7,7 @@ #include "dLogger.h" #include "Preconditions.h" #include "eInventoryType.h" +#include "eLootSourceType.h" /** * An item that can be stored in an inventory and optionally consumed or equipped @@ -38,7 +39,7 @@ public: const std::vector<LDFBaseData*>& config, LWOOBJID parent, LWOOBJID subKey, - eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE + eLootSourceType lootSourceType = eLootSourceType::NONE ); /** @@ -65,7 +66,7 @@ public: bool isModMoveAndEquip = false, LWOOBJID subKey = LWOOBJID_EMPTY, bool bound = false, - eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE + eLootSourceType lootSourceType = eLootSourceType::NONE ); ~Item(); @@ -89,7 +90,7 @@ public: * @param disassemble if items were removed, this returns all the sub parts of the item individually if it had assembly part lots * @param showFlyingLoot shows flying loot to the client, if not silent */ - void SetCount(uint32_t value, bool silent = false, bool disassemble = true, bool showFlyingLoot = true, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); + void SetCount(uint32_t value, bool silent = false, bool disassemble = true, bool showFlyingLoot = true, eLootSourceType lootSourceType = eLootSourceType::NONE); /** * Returns the number of items this item represents (e.g. for stacks) diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index 9cfdaaa7..32a930e4 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -388,7 +388,7 @@ void Mission::Catchup() { } if (type == eMissionTaskType::PLAYER_FLAG) { - for (auto target : task->GetAllTargets()) { + for (int32_t target : task->GetAllTargets()) { const auto flag = GetUser()->GetLastUsedChar()->GetPlayerFlag(target); if (!flag) { @@ -442,7 +442,7 @@ void Mission::YieldRewards() { int32_t coinsToSend = 0; if (info->LegoScore > 0) { - eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; + eLootSourceType lootSource = info->isMission ? eLootSourceType::MISSION : eLootSourceType::ACHIEVEMENT; if (levelComponent->GetLevel() >= dZoneManager::Instance()->GetWorldConfig()->levelCap) { // Since the character is at the level cap we reward them with coins instead of UScore. coinsToSend += info->LegoScore * dZoneManager::Instance()->GetWorldConfig()->levelCapCurrencyConversion; @@ -475,11 +475,11 @@ void Mission::YieldRewards() { count = 0; } - inventoryComponent->AddItem(pair.first, count, IsMission() ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT); + inventoryComponent->AddItem(pair.first, count, IsMission() ? eLootSourceType::MISSION : eLootSourceType::ACHIEVEMENT); } if (info->reward_currency_repeatable > 0 || coinsToSend > 0) { - eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; + eLootSourceType lootSource = info->isMission ? eLootSourceType::MISSION : eLootSourceType::ACHIEVEMENT; character->SetCoins(character->GetCoins() + info->reward_currency_repeatable + coinsToSend, lootSource); } @@ -508,11 +508,11 @@ void Mission::YieldRewards() { count = 0; } - inventoryComponent->AddItem(pair.first, count, IsMission() ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT); + inventoryComponent->AddItem(pair.first, count, IsMission() ? eLootSourceType::MISSION : eLootSourceType::ACHIEVEMENT); } if (info->reward_currency > 0 || coinsToSend > 0) { - eLootSourceType lootSource = info->isMission ? eLootSourceType::LOOT_SOURCE_MISSION : eLootSourceType::LOOT_SOURCE_ACHIEVEMENT; + eLootSourceType lootSource = info->isMission ? eLootSourceType::MISSION : eLootSourceType::ACHIEVEMENT; character->SetCoins(character->GetCoins() + info->reward_currency + coinsToSend, lootSource); } diff --git a/dGame/dUtilities/Loot.cpp b/dGame/dUtilities/Loot.cpp index da0f2487..c788c016 100644 --- a/dGame/dUtilities/Loot.cpp +++ b/dGame/dUtilities/Loot.cpp @@ -318,13 +318,13 @@ void LootGenerator::GiveActivityLoot(Entity* player, Entity* source, uint32_t ac maxCoins = currencyTable[0].maxvalue; } - GiveLoot(player, selectedReward->LootMatrixIndex, eLootSourceType::LOOT_SOURCE_ACTIVITY); + GiveLoot(player, selectedReward->LootMatrixIndex, eLootSourceType::ACTIVITY); uint32_t coins = (int)(minCoins + GeneralUtils::GenerateRandomNumber<float>(0, 1) * (maxCoins - minCoins)); auto* character = player->GetCharacter(); - character->SetCoins(character->GetCoins() + coins, eLootSourceType::LOOT_SOURCE_ACTIVITY); + character->SetCoins(character->GetCoins() + coins, eLootSourceType::ACTIVITY); } void LootGenerator::DropLoot(Entity* player, Entity* killedObject, uint32_t matrixIndex, uint32_t minCoins, uint32_t maxCoins) { diff --git a/dGame/dUtilities/Loot.h b/dGame/dUtilities/Loot.h index 7ecc22b8..a1c52b63 100644 --- a/dGame/dUtilities/Loot.h +++ b/dGame/dUtilities/Loot.h @@ -47,8 +47,8 @@ public: std::unordered_map<LOT, int32_t> RollLootMatrix(Entity* player, uint32_t matrixIndex); std::unordered_map<LOT, int32_t> RollLootMatrix(uint32_t matrixIndex); - void GiveLoot(Entity* player, uint32_t matrixIndex, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); - void GiveLoot(Entity* player, std::unordered_map<LOT, int32_t>& result, eLootSourceType lootSourceType = eLootSourceType::LOOT_SOURCE_NONE); + void GiveLoot(Entity* player, uint32_t matrixIndex, eLootSourceType lootSourceType = eLootSourceType::NONE); + void GiveLoot(Entity* player, std::unordered_map<LOT, int32_t>& result, eLootSourceType lootSourceType = eLootSourceType::NONE); void GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating = 0); void DropLoot(Entity* player, Entity* killedObject, uint32_t matrixIndex, uint32_t minCoins, uint32_t maxCoins); void DropLoot(Entity* player, Entity* killedObject, std::unordered_map<LOT, int32_t>& result, uint32_t minCoins, uint32_t maxCoins); diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index 5cd11ea4..1d3e0f60 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -259,7 +259,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd } Mail::SendSendResponse(sysAddr, Mail::MailSendResponse::Success); - entity->GetCharacter()->SetCoins(entity->GetCharacter()->GetCoins() - mailCost, eLootSourceType::LOOT_SOURCE_MAIL); + entity->GetCharacter()->SetCoins(entity->GetCharacter()->GetCoins() - mailCost, eLootSourceType::MAIL); Game::logger->Log("Mail", "Seeing if we need to remove item with ID/count/LOT: %i %i %i", itemID, attachmentCount, itemLOT); @@ -359,7 +359,7 @@ void Mail::HandleAttachmentCollect(RakNet::BitStream* packet, const SystemAddres auto inv = static_cast<InventoryComponent*>(player->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; - inv->AddItem(attachmentLOT, attachmentCount, eLootSourceType::LOOT_SOURCE_MAIL); + inv->AddItem(attachmentLOT, attachmentCount, eLootSourceType::MAIL); Mail::SendAttachmentRemoveConfirm(sysAddr, mailID); diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 9c1bc611..66e9bc9b 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -78,6 +78,7 @@ #include "eObjectBits.h" #include "eGameMasterLevel.h" #include "eReplicaComponentType.h" +#include "eControlScheme.h" #include "CDObjectsTable.h" #include "CDZoneTableTable.h" @@ -497,7 +498,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit const auto state = !entity->GetVar<bool>(u"freecam"); entity->SetVar<bool>(u"freecam", state); - GameMessages::SendSetPlayerControlScheme(entity, static_cast<eControlSceme>(state ? 9 : 1)); + GameMessages::SendSetPlayerControlScheme(entity, static_cast<eControlScheme>(state ? 9 : 1)); ChatPackets::SendSystemMessage(sysAddr, u"Toggled freecam."); return; @@ -511,7 +512,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } - GameMessages::SendSetPlayerControlScheme(entity, static_cast<eControlSceme>(scheme)); + GameMessages::SendSetPlayerControlScheme(entity, static_cast<eControlScheme>(scheme)); ChatPackets::SendSystemMessage(sysAddr, u"Switched control scheme."); return; @@ -653,7 +654,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "setflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - uint32_t flagId; + int32_t flagId; if (!GeneralUtils::TryParse(args[0], flagId)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); @@ -664,7 +665,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "setflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 2) { - uint32_t flagId; + int32_t flagId; std::string onOffFlag = args[0]; if (!GeneralUtils::TryParse(args[1], flagId)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); @@ -677,7 +678,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit entity->GetCharacter()->SetPlayerFlag(flagId, onOffFlag == "on"); } if (chatCommand == "clearflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - uint32_t flagId; + int32_t flagId; if (!GeneralUtils::TryParse(args[0], flagId)) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); @@ -793,7 +794,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit InventoryComponent* inventory = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); - inventory->AddItem(itemLOT, 1, eLootSourceType::LOOT_SOURCE_MODERATION); + inventory->AddItem(itemLOT, 1, eLootSourceType::MODERATION); } else if (args.size() == 2) { uint32_t itemLOT; @@ -811,7 +812,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit InventoryComponent* inventory = static_cast<InventoryComponent*>(entity->GetComponent(eReplicaComponentType::INVENTORY)); - inventory->AddItem(itemLOT, count, eLootSourceType::LOOT_SOURCE_MODERATION); + inventory->AddItem(itemLOT, count, eLootSourceType::MODERATION); } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /gmadditem <lot>"); } @@ -1346,9 +1347,9 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit CharacterComponent* character = entity->GetComponent<CharacterComponent>(); if (character) character->SetUScore(character->GetUScore() + uscore); - // LOOT_SOURCE_MODERATION should work but it doesn't. Relog to see uscore changes + // MODERATION should work but it doesn't. Relog to see uscore changes - eLootSourceType lootType = eLootSourceType::LOOT_SOURCE_MODERATION; + eLootSourceType lootType = eLootSourceType::MODERATION; int32_t type; if (args.size() >= 2 && GeneralUtils::TryParse(args[1], type)) { @@ -1466,7 +1467,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } auto* ch = entity->GetCharacter(); - ch->SetCoins(ch->GetCoins() + money, eLootSourceType::LOOT_SOURCE_MODERATION); + ch->SetCoins(ch->GetCoins() + money, eLootSourceType::MODERATION); } if ((chatCommand == "setcurrency") && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { @@ -1478,7 +1479,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } auto* ch = entity->GetCharacter(); - ch->SetCoins(money, eLootSourceType::LOOT_SOURCE_MODERATION); + ch->SetCoins(money, eLootSourceType::MODERATION); } // Allow for this on even while not a GM, as it sometimes toggles incorrrectly. @@ -1727,7 +1728,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit std::vector<LDFBaseData*> data{}; data.push_back(new LDFData<int32_t>(u"reforgedLOT", reforgedItem)); - inventoryComponent->AddItem(baseItem, 1, eLootSourceType::LOOT_SOURCE_MODERATION, eInventoryType::INVALID, data); + inventoryComponent->AddItem(baseItem, 1, eLootSourceType::MODERATION, eInventoryType::INVALID, data); } if (chatCommand == "crash" && entity->GetGMLevel() >= eGameMasterLevel::OPERATOR) { diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index 4e7cb0a6..eae23394 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -22,6 +22,7 @@ #include "Game.h" #include "dConfig.h" #include "eServerDisconnectIdentifiers.h" +#include "eLoginResponse.h" void AuthPackets::HandleHandshake(dServer* server, Packet* packet) { RakNet::BitStream inStream(packet->data, packet->length, false); @@ -61,7 +62,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { if (res->rowsCount() == 0) { server->GetLogger()->Log("AuthPackets", "No user found!"); - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_WRONG_PASS_OR_USER, "", "", 2001, username); + AuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::INVALID_USER, "", "", 2001, username); return; } @@ -85,14 +86,14 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { //If we aren't running in live mode, then only GMs are allowed to enter: const auto& closedToNonDevs = Game::config->GetValue("closed_to_non_devs"); if (closedToNonDevs.size() > 0 && bool(std::stoi(closedToNonDevs)) && sqlGmLevel == 0) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::LOGIN_RESPONSE_PERMISSIONS_NOT_HIGH_ENOUGH, "The server is currently only open to developers.", "", 2001, username); + AuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::PERMISSIONS_NOT_HIGH_ENOUGH, "The server is currently only open to developers.", "", 2001, username); return; } if (Game::config->GetValue("dont_use_keys") != "1") { //Check to see if we have a play key: if (sqlPlayKey == 0 && sqlGmLevel == 0) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_PERMISSIONS_NOT_HIGH_ENOUGH, "Your account doesn't have a play key associated with it!", "", 2001, username); + AuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::PERMISSIONS_NOT_HIGH_ENOUGH, "Your account doesn't have a play key associated with it!", "", 2001, username); server->GetLogger()->Log("AuthPackets", "User %s tried to log in, but they don't have a play key.", username.c_str()); return; } @@ -104,7 +105,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { bool isKeyActive = false; if (keyRes->rowsCount() == 0 && sqlGmLevel == 0) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_PERMISSIONS_NOT_HIGH_ENOUGH, "Your account doesn't have a play key associated with it!", "", 2001, username); + AuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::PERMISSIONS_NOT_HIGH_ENOUGH, "Your account doesn't have a play key associated with it!", "", 2001, username); return; } @@ -113,18 +114,18 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { } if (!isKeyActive && sqlGmLevel == 0) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_PERMISSIONS_NOT_HIGH_ENOUGH, "Your play key has been disabled.", "", 2001, username); + AuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::PERMISSIONS_NOT_HIGH_ENOUGH, "Your play key has been disabled.", "", 2001, username); server->GetLogger()->Log("AuthPackets", "User %s tried to log in, but their play key was disabled", username.c_str()); return; } } if (sqlBanned) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_BANNED, "", "", 2001, username); return; + AuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::BANNED, "", "", 2001, username); return; } if (sqlLocked) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_ACCOUNT_LOCKED, "", "", 2001, username); return; + AuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::ACCOUNT_LOCKED, "", "", 2001, username); return; } /* @@ -170,18 +171,18 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { } if (!loginSuccess) { - AuthPackets::SendLoginResponse(server, packet->systemAddress, LOGIN_RESPONSE_WRONG_PASS_OR_USER, "", "", 2001, username); + AuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::WRONG_PASS, "", "", 2001, username); server->GetLogger()->Log("AuthPackets", "Wrong password used"); } else { SystemAddress system = packet->systemAddress; //Copy the sysAddr before the Packet gets destroyed from main if (!server->GetIsConnectedToMaster()) { - AuthPackets::SendLoginResponse(server, system, LOGIN_RESPONSE_GENERAL_FAILED, "", "", 0, username); + AuthPackets::SendLoginResponse(server, system, eLoginResponse::GENERAL_FAILED, "", "", 0, username); return; } ZoneInstanceManager::Instance()->RequestZoneTransfer(server, 0, 0, false, [system, server, username](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string zoneIP, uint16_t zonePort) { - AuthPackets::SendLoginResponse(server, system, LOGIN_RESPONSE_SUCCESS, "", zoneIP, zonePort, username); + AuthPackets::SendLoginResponse(server, system, eLoginResponse::SUCCESS, "", zoneIP, zonePort, username); }); } } diff --git a/dNet/AuthPackets.h b/dNet/AuthPackets.h index 378a5862..0f004ca4 100644 --- a/dNet/AuthPackets.h +++ b/dNet/AuthPackets.h @@ -6,6 +6,7 @@ #include "dNetCommon.h" enum class ServerType : uint32_t; +enum class eLoginResponse : uint8_t; class dServer; namespace AuthPackets { diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index febb6bc1..3be4fb4d 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -15,7 +15,6 @@ #include "CharacterComponent.h" #include "ZCompression.h" - void WorldPackets::SendLoadStaticZone(const SystemAddress& sysAddr, float x, float y, float z, uint32_t checksum) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_LOAD_STATIC_ZONE); @@ -89,7 +88,7 @@ void WorldPackets::SendCharacterList(const SystemAddress& sysAddr, User* user) { SEND_PACKET; } -void WorldPackets::SendCharacterCreationResponse(const SystemAddress& sysAddr, eCreationResponse response) { +void WorldPackets::SendCharacterCreationResponse(const SystemAddress& sysAddr, eCharacterCreationResponse response) { RakNet::BitStream bitStream; PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_CREATE_RESPONSE); bitStream.Write(response); diff --git a/dNet/WorldPackets.h b/dNet/WorldPackets.h index ec20ac22..ea8186c7 100644 --- a/dNet/WorldPackets.h +++ b/dNet/WorldPackets.h @@ -9,11 +9,13 @@ class User; struct SystemAddress; enum class eGameMasterLevel : uint8_t; +enum class eCharacterCreationResponse : uint8_t; +enum class eRenameResponse : uint8_t; namespace WorldPackets { void SendLoadStaticZone(const SystemAddress& sysAddr, float x, float y, float z, uint32_t checksum); void SendCharacterList(const SystemAddress& sysAddr, User* user); - void SendCharacterCreationResponse(const SystemAddress& sysAddr, eCreationResponse response); + void SendCharacterCreationResponse(const SystemAddress& sysAddr, eCharacterCreationResponse response); void SendCharacterRenameResponse(const SystemAddress& sysAddr, eRenameResponse response); void SendCharacterDeleteResponse(const SystemAddress& sysAddr, bool response); void SendTransferToWorld(const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift); diff --git a/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp b/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp index ea3ce9b8..e9863b17 100644 --- a/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp +++ b/dScripts/02_server/Enemy/General/BaseEnemyApe.cpp @@ -6,6 +6,7 @@ #include "EntityInfo.h" #include "SkillComponent.h" #include "eAninmationFlags.h" +#include "eStateChangeType.h" void BaseEnemyApe::OnStartup(Entity* self) { self->SetVar<uint32_t>(u"timesStunned", 2); @@ -15,7 +16,7 @@ void BaseEnemyApe::OnStartup(Entity* self) { void BaseEnemyApe::OnDie(Entity* self, Entity* killer) { auto* anchor = EntityManager::Instance()->GetEntity(self->GetVar<LWOOBJID>(u"QB")); if (anchor != nullptr && !anchor->GetIsDead()) { - anchor->Smash(self->GetObjectID(), SILENT); + anchor->Smash(self->GetObjectID(), eKillType::SILENT); } } diff --git a/dScripts/02_server/Equipment/BootyDigServer.cpp b/dScripts/02_server/Equipment/BootyDigServer.cpp index 375bc4e5..190c232b 100644 --- a/dScripts/02_server/Equipment/BootyDigServer.cpp +++ b/dScripts/02_server/Equipment/BootyDigServer.cpp @@ -30,7 +30,7 @@ BootyDigServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string return; if (args == "ChestReady" && (propertyOwner == std::to_string(LWOOBJID_EMPTY) || player->GetVar<bool>(u"bootyDug"))) { - self->Smash(self->GetObjectID(), SILENT); + self->Smash(self->GetObjectID(), eKillType::SILENT); } else if (args == "ChestOpened") { // Make sure players only dig up one booty per instance player->SetVar<bool>(u"bootyDug", true); @@ -49,6 +49,6 @@ BootyDigServer::OnFireEventServerSide(Entity* self, Entity* sender, std::string } } } else if (args == "ChestDead") { - self->Smash(player->GetObjectID(), SILENT); + self->Smash(player->GetObjectID(), eKillType::SILENT); } } diff --git a/dScripts/02_server/Map/AG/AgCagedBricksServer.cpp b/dScripts/02_server/Map/AG/AgCagedBricksServer.cpp index 3c400e5d..13c9c04b 100644 --- a/dScripts/02_server/Map/AG/AgCagedBricksServer.cpp +++ b/dScripts/02_server/Map/AG/AgCagedBricksServer.cpp @@ -4,6 +4,7 @@ #include "Character.h" #include "EntityManager.h" #include "eReplicaComponentType.h" +#include "ePlayerFlag.h" void AgCagedBricksServer::OnUse(Entity* self, Entity* user) { //Tell the client to spawn the baby spiderling: @@ -17,7 +18,7 @@ void AgCagedBricksServer::OnUse(Entity* self, Entity* user) { if (!character) return; - character->SetPlayerFlag(74, true); + character->SetPlayerFlag(ePlayerFlag::CAGED_SPIDER, true); //Remove the maelstrom cube: auto inv = static_cast<InventoryComponent*>(user->GetComponent(eReplicaComponentType::INVENTORY)); diff --git a/dScripts/02_server/Map/AG/NpcCowboyServer.cpp b/dScripts/02_server/Map/AG/NpcCowboyServer.cpp index c5a0e8f9..6dd212a4 100644 --- a/dScripts/02_server/Map/AG/NpcCowboyServer.cpp +++ b/dScripts/02_server/Map/AG/NpcCowboyServer.cpp @@ -18,7 +18,7 @@ void NpcCowboyServer::OnMissionDialogueOK(Entity* self, Entity* target, int miss missionState == eMissionState::AVAILABLE || missionState == eMissionState::COMPLETE_AVAILABLE) { if (inventoryComponent->GetLotCount(14378) == 0) { - inventoryComponent->AddItem(14378, 1, eLootSourceType::LOOT_SOURCE_NONE); + inventoryComponent->AddItem(14378, 1, eLootSourceType::NONE); } } else if (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { inventoryComponent->RemoveItem(14378, 1); diff --git a/dScripts/02_server/Map/AG/NpcPirateServer.cpp b/dScripts/02_server/Map/AG/NpcPirateServer.cpp index 6e7e696c..cad0d64c 100644 --- a/dScripts/02_server/Map/AG/NpcPirateServer.cpp +++ b/dScripts/02_server/Map/AG/NpcPirateServer.cpp @@ -10,7 +10,7 @@ void NpcPirateServer::OnMissionDialogueOK(Entity* self, Entity* target, int miss // Add or remove the lucky shovel based on whether the mission was completed or started if ((missionState == eMissionState::AVAILABLE || missionState == eMissionState::COMPLETE_AVAILABLE) && luckyShovel == nullptr) { - inventory->AddItem(14591, 1, eLootSourceType::LOOT_SOURCE_NONE); + inventory->AddItem(14591, 1, eLootSourceType::NONE); } else if (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { inventory->RemoveItem(14591, 1); } diff --git a/dScripts/02_server/Map/AG/NpcWispServer.cpp b/dScripts/02_server/Map/AG/NpcWispServer.cpp index 99345973..84196c8c 100644 --- a/dScripts/02_server/Map/AG/NpcWispServer.cpp +++ b/dScripts/02_server/Map/AG/NpcWispServer.cpp @@ -19,7 +19,7 @@ void NpcWispServer::OnMissionDialogueOK(Entity* self, Entity* target, int missio // For the daily we add the maelstrom vacuum if the player doesn't have it yet if (missionID == 1883 && (missionState == eMissionState::AVAILABLE || missionState == eMissionState::COMPLETE_AVAILABLE) && maelstromVacuum == nullptr) { - inventory->AddItem(maelstromVacuumLot, 1, eLootSourceType::LOOT_SOURCE_NONE); + inventory->AddItem(maelstromVacuumLot, 1, eLootSourceType::NONE); } else if (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { inventory->RemoveItem(maelstromVacuumLot, 1); } diff --git a/dScripts/02_server/Map/AG/RemoveRentalGear.cpp b/dScripts/02_server/Map/AG/RemoveRentalGear.cpp index 18177e57..f9bdf1ce 100644 --- a/dScripts/02_server/Map/AG/RemoveRentalGear.cpp +++ b/dScripts/02_server/Map/AG/RemoveRentalGear.cpp @@ -4,6 +4,7 @@ #include "eMissionState.h" #include "Character.h" #include "eReplicaComponentType.h" +#include "ePlayerFlag.h" /* -------------------------------------------------------------- @@ -36,6 +37,6 @@ void RemoveRentalGear::OnMissionDialogueOK(Entity* self, Entity* target, int mis //reset the equipment flag auto character = target->GetCharacter(); - if (character) character->SetPlayerFlag(equipFlag, false); + if (character) character->SetPlayerFlag(ePlayerFlag::EQUPPED_TRIAL_FACTION_GEAR, false); } } diff --git a/dScripts/02_server/Map/AG/RemoveRentalGear.h b/dScripts/02_server/Map/AG/RemoveRentalGear.h index cc33b5f6..cf9002d7 100644 --- a/dScripts/02_server/Map/AG/RemoveRentalGear.h +++ b/dScripts/02_server/Map/AG/RemoveRentalGear.h @@ -7,6 +7,5 @@ class RemoveRentalGear : public CppScripts::Script { private: int defaultMission = 768; //mission to remove gearSets on completion std::vector<int> gearSets = { 14359,14321,14353,14315 }; //inventory items to remove - int equipFlag = 126; //Set upon wearing trial faction armor for the first time in a session }; diff --git a/dScripts/02_server/Map/AM/AmBlueX.cpp b/dScripts/02_server/Map/AM/AmBlueX.cpp index 8e32694c..312cdc47 100644 --- a/dScripts/02_server/Map/AM/AmBlueX.cpp +++ b/dScripts/02_server/Map/AM/AmBlueX.cpp @@ -18,7 +18,7 @@ void AmBlueX::OnSkillEventFired(Entity* self, Entity* caster, const std::string& auto* character = caster->GetCharacter(); if (character != nullptr) { - character->SetPlayerFlag(self->GetVar<int32_t>(m_FlagVariable), true); + character->SetPlayerFlag(self->GetVar<uint32_t>(m_FlagVariable), true); } EntityInfo info{}; diff --git a/dScripts/02_server/Map/AM/AmBridge.cpp b/dScripts/02_server/Map/AM/AmBridge.cpp index 88f30642..719ca058 100644 --- a/dScripts/02_server/Map/AM/AmBridge.cpp +++ b/dScripts/02_server/Map/AM/AmBridge.cpp @@ -24,5 +24,5 @@ void AmBridge::OnTimerDone(Entity* self, std::string timerName) { return; } - self->Smash(self->GetObjectID(), VIOLENT); + self->Smash(self->GetObjectID(), eKillType::VIOLENT); } diff --git a/dScripts/02_server/Map/AM/AmDrawBridge.cpp b/dScripts/02_server/Map/AM/AmDrawBridge.cpp index 20636b13..3c4dcce6 100644 --- a/dScripts/02_server/Map/AM/AmDrawBridge.cpp +++ b/dScripts/02_server/Map/AM/AmDrawBridge.cpp @@ -2,6 +2,7 @@ #include "EntityManager.h" #include "GameMessages.h" #include "SimplePhysicsComponent.h" +#include "eTerminateType.h" void AmDrawBridge::OnStartup(Entity* self) { self->SetNetworkVar(u"InUse", false); @@ -25,7 +26,7 @@ void AmDrawBridge::OnUse(Entity* self, Entity* user) { auto* player = user; - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(player->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } void AmDrawBridge::OnTimerDone(Entity* self, std::string timerName) { diff --git a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp index 15ca7267..f23fa93f 100644 --- a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp +++ b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp @@ -12,7 +12,7 @@ void AmDropshipComputer::OnStartup(Entity* self) { void AmDropshipComputer::OnUse(Entity* self, Entity* user) { auto* rebuildComponent = self->GetComponent<RebuildComponent>(); - if (rebuildComponent == nullptr || rebuildComponent->GetState() != REBUILD_COMPLETED) { + if (rebuildComponent == nullptr || rebuildComponent->GetState() != eRebuildState::COMPLETED) { return; } @@ -27,7 +27,7 @@ void AmDropshipComputer::OnUse(Entity* self, Entity* user) { return; } - inventoryComponent->AddItem(m_NexusTalonDataCard, 1, eLootSourceType::LOOT_SOURCE_NONE); + inventoryComponent->AddItem(m_NexusTalonDataCard, 1, eLootSourceType::NONE); } void AmDropshipComputer::OnDie(Entity* self, Entity* killer) { @@ -76,7 +76,7 @@ void AmDropshipComputer::OnTimerDone(Entity* self, std::string timerName) { return; } - if (timerName == "reset" && rebuildComponent->GetState() == REBUILD_OPEN) { - self->Smash(self->GetObjectID(), SILENT); + if (timerName == "reset" && rebuildComponent->GetState() == eRebuildState::OPEN) { + self->Smash(self->GetObjectID(), eKillType::SILENT); } } diff --git a/dScripts/02_server/Map/AM/AmShieldGeneratorQuickbuild.cpp b/dScripts/02_server/Map/AM/AmShieldGeneratorQuickbuild.cpp index 3188db33..381c13bc 100644 --- a/dScripts/02_server/Map/AM/AmShieldGeneratorQuickbuild.cpp +++ b/dScripts/02_server/Map/AM/AmShieldGeneratorQuickbuild.cpp @@ -176,7 +176,7 @@ void AmShieldGeneratorQuickbuild::BuffPlayers(Entity* self) { void AmShieldGeneratorQuickbuild::EnemyEnteredShield(Entity* self, Entity* intruder) { auto* rebuildComponent = self->GetComponent<RebuildComponent>(); - if (rebuildComponent == nullptr || rebuildComponent->GetState() != REBUILD_COMPLETED) { + if (rebuildComponent == nullptr || rebuildComponent->GetState() != eRebuildState::COMPLETED) { return; } diff --git a/dScripts/02_server/Map/AM/AmSkullkinDrill.cpp b/dScripts/02_server/Map/AM/AmSkullkinDrill.cpp index da1954d6..d26218a2 100644 --- a/dScripts/02_server/Map/AM/AmSkullkinDrill.cpp +++ b/dScripts/02_server/Map/AM/AmSkullkinDrill.cpp @@ -5,6 +5,7 @@ #include "ProximityMonitorComponent.h" #include "MissionComponent.h" #include "EntityInfo.h" +#include "eStateChangeType.h" void AmSkullkinDrill::OnStartup(Entity* self) { self->SetNetworkVar(u"bIsInUse", false); @@ -246,7 +247,7 @@ void AmSkullkinDrill::OnHitOrHealResult(Entity* self, Entity* attacker, int32_t } } - self->Smash(attacker->GetObjectID(), SILENT); + self->Smash(attacker->GetObjectID(), eKillType::SILENT); self->CancelAllTimers(); @@ -264,7 +265,7 @@ void AmSkullkinDrill::OnTimerDone(Entity* self, std::string timerName) { auto* child = EntityManager::Instance()->GetEntity(childID); if (child != nullptr) { - child->Smash(self->GetObjectID(), SILENT); + child->Smash(self->GetObjectID(), eKillType::SILENT); } self->SetNetworkVar(u"bIsInUse", false); diff --git a/dScripts/02_server/Map/AM/AmTeapotServer.cpp b/dScripts/02_server/Map/AM/AmTeapotServer.cpp index 1f47cb1a..93f05326 100644 --- a/dScripts/02_server/Map/AM/AmTeapotServer.cpp +++ b/dScripts/02_server/Map/AM/AmTeapotServer.cpp @@ -2,6 +2,7 @@ #include "InventoryComponent.h" #include "GameMessages.h" #include "Item.h" +#include "eTerminateType.h" void AmTeapotServer::OnUse(Entity* self, Entity* user) { auto* inventoryComponent = user->GetComponent<InventoryComponent>(); @@ -18,5 +19,5 @@ void AmTeapotServer::OnUse(Entity* self, Entity* user) { blueFlowerItem->SetCount(blueFlowerItem->GetCount() - 10); inventoryComponent->AddItem(WU_S_IMAGINATION_TEA, 1); } - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/02_server/Map/FV/ImgBrickConsoleQB.cpp b/dScripts/02_server/Map/FV/ImgBrickConsoleQB.cpp index 9c7b858f..7d86cc73 100644 --- a/dScripts/02_server/Map/FV/ImgBrickConsoleQB.cpp +++ b/dScripts/02_server/Map/FV/ImgBrickConsoleQB.cpp @@ -6,6 +6,7 @@ #include "MissionComponent.h" #include "eMissionState.h" #include "InventoryComponent.h" +#include "eTerminateType.h" int32_t ImgBrickConsoleQB::ResetBricks = 30; int32_t ImgBrickConsoleQB::ResetConsole = 60; @@ -20,7 +21,7 @@ void ImgBrickConsoleQB::OnStartup(Entity* self) { void ImgBrickConsoleQB::OnUse(Entity* self, Entity* user) { auto* rebuildComponent = self->GetComponent<RebuildComponent>(); - if (rebuildComponent->GetState() == REBUILD_COMPLETED) { + if (rebuildComponent->GetState() == eRebuildState::COMPLETED) { if (!self->GetNetworkVar<bool>(u"used")) { const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); @@ -29,7 +30,7 @@ void ImgBrickConsoleQB::OnUse(Entity* self, Entity* user) { for (auto* console : consoles) { auto* consoleRebuildComponent = console->GetComponent<RebuildComponent>(); - if (consoleRebuildComponent->GetState() != REBUILD_COMPLETED) { + if (consoleRebuildComponent->GetState() != eRebuildState::COMPLETED) { continue; } @@ -87,7 +88,7 @@ void ImgBrickConsoleQB::OnUse(Entity* self, Entity* user) { self->SetNetworkVar(u"used", true); - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(player->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } } @@ -113,7 +114,7 @@ void ImgBrickConsoleQB::SmashCanister(Entity* self) { const auto canisters = EntityManager::Instance()->GetEntitiesInGroup("Canister"); for (auto* canister : canisters) { - canister->Smash(canister->GetObjectID(), VIOLENT); + canister->Smash(canister->GetObjectID(), eKillType::VIOLENT); } const auto canister = dZoneManager::Instance()->GetSpawnersByName("BrickCanister"); @@ -146,7 +147,7 @@ void ImgBrickConsoleQB::OnRebuildComplete(Entity* self, Entity* target) { for (auto* console : consoles) { auto* consoleRebuildComponent = console->GetComponent<RebuildComponent>(); - if (consoleRebuildComponent->GetState() != REBUILD_COMPLETED) { + if (consoleRebuildComponent->GetState() != eRebuildState::COMPLETED) { continue; } @@ -167,7 +168,7 @@ void ImgBrickConsoleQB::OnDie(Entity* self, Entity* killer) { auto* rebuildComponent = self->GetComponent<RebuildComponent>(); - if (rebuildComponent->GetState() == REBUILD_COMPLETED) { + if (rebuildComponent->GetState() == eRebuildState::COMPLETED) { auto offFX = 0; const auto location = GeneralUtils::UTF16ToWTF8(self->GetVar<std::u16string>(u"console")); @@ -228,14 +229,14 @@ void ImgBrickConsoleQB::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "reset") { auto* rebuildComponent = self->GetComponent<RebuildComponent>(); - if (rebuildComponent->GetState() == REBUILD_OPEN) { - self->Smash(self->GetObjectID(), SILENT); + if (rebuildComponent->GetState() == eRebuildState::OPEN) { + self->Smash(self->GetObjectID(), eKillType::SILENT); } } else if (timerName == "Die") { const auto consoles = EntityManager::Instance()->GetEntitiesInGroup("Console"); for (auto* console : consoles) { - console->Smash(console->GetObjectID(), VIOLENT); + console->Smash(console->GetObjectID(), eKillType::VIOLENT); } } } diff --git a/dScripts/02_server/Map/FV/Racing/RaceMaelstromGeiser.cpp b/dScripts/02_server/Map/FV/Racing/RaceMaelstromGeiser.cpp index b737d449..155be92b 100644 --- a/dScripts/02_server/Map/FV/Racing/RaceMaelstromGeiser.cpp +++ b/dScripts/02_server/Map/FV/Racing/RaceMaelstromGeiser.cpp @@ -55,7 +55,7 @@ void RaceMaelstromGeiser::OnProximityUpdate(Entity* self, Entity* entering, std: } - GameMessages::SendDie(vehicle, self->GetObjectID(), LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, true, false, 0); + GameMessages::SendDie(vehicle, self->GetObjectID(), LWOOBJID_EMPTY, true, eKillType::VIOLENT, u"", 0, 0, 0, true, false, 0); auto* zoneController = dZoneManager::Instance()->GetZoneControlObject(); diff --git a/dScripts/02_server/Map/GF/GfCaptainsCannon.cpp b/dScripts/02_server/Map/GF/GfCaptainsCannon.cpp index eeabeef6..13e2e4e5 100644 --- a/dScripts/02_server/Map/GF/GfCaptainsCannon.cpp +++ b/dScripts/02_server/Map/GF/GfCaptainsCannon.cpp @@ -2,6 +2,8 @@ #include "GameMessages.h" #include "EntityManager.h" #include "MissionComponent.h" +#include "eTerminateType.h" +#include "eStateChangeType.h" void GfCaptainsCannon::OnUse(Entity* self, Entity* user) { if (self->GetVar<bool>(u"bIsInUse")) { @@ -78,6 +80,6 @@ void GfCaptainsCannon::OnTimerDone(Entity* self, std::string timerName) { missionComponent->ForceProgress(601, 910, 1); } - GameMessages::SendTerminateInteraction(playerId, FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(playerId, eTerminateType::FROM_INTERACTION, self->GetObjectID()); } } diff --git a/dScripts/02_server/Map/GF/GfTikiTorch.cpp b/dScripts/02_server/Map/GF/GfTikiTorch.cpp index 22420679..8528192f 100644 --- a/dScripts/02_server/Map/GF/GfTikiTorch.cpp +++ b/dScripts/02_server/Map/GF/GfTikiTorch.cpp @@ -5,6 +5,7 @@ #include "RenderComponent.h" #include "eMissionTaskType.h" #include "eReplicaComponentType.h" +#include "eTerminateType.h" void GfTikiTorch::OnStartup(Entity* self) { LightTorch(self); @@ -33,7 +34,7 @@ void GfTikiTorch::OnTimerDone(Entity* self, std::string timerName) { Entity* player = EntityManager::Instance()->GetEntity(self->GetI64(u"userID")); if (player != nullptr && player->GetCharacter()) { - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(player->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } self->SetBoolean(u"isInUse", false); diff --git a/dScripts/02_server/Map/GF/MastTeleport.cpp b/dScripts/02_server/Map/GF/MastTeleport.cpp index 8b8453b9..97b126b4 100644 --- a/dScripts/02_server/Map/GF/MastTeleport.cpp +++ b/dScripts/02_server/Map/GF/MastTeleport.cpp @@ -4,6 +4,7 @@ #include "Preconditions.h" #include "eEndBehavior.h" #include "DestroyableComponent.h" +#include "eStateChangeType.h" #ifdef _WIN32 #define _USE_MATH_DEFINES diff --git a/dScripts/02_server/Map/General/Ninjago/NjRailActivatorsServer.cpp b/dScripts/02_server/Map/General/Ninjago/NjRailActivatorsServer.cpp index a07de24a..5ca726af 100644 --- a/dScripts/02_server/Map/General/Ninjago/NjRailActivatorsServer.cpp +++ b/dScripts/02_server/Map/General/Ninjago/NjRailActivatorsServer.cpp @@ -7,7 +7,7 @@ void NjRailActivatorsServer::OnUse(Entity* self, Entity* user) { auto* rebuildComponent = self->GetComponent<RebuildComponent>(); // Only allow use if this is not a quick build or the quick build is built - if (rebuildComponent == nullptr || rebuildComponent->GetState() == REBUILD_COMPLETED) { + if (rebuildComponent == nullptr || rebuildComponent->GetState() == eRebuildState::COMPLETED) { auto* character = user->GetCharacter(); if (character != nullptr) { character->SetPlayerFlag(flag, true); diff --git a/dScripts/02_server/Map/General/Ninjago/NjRailPostServer.cpp b/dScripts/02_server/Map/General/Ninjago/NjRailPostServer.cpp index 23389a98..2c435705 100644 --- a/dScripts/02_server/Map/General/Ninjago/NjRailPostServer.cpp +++ b/dScripts/02_server/Map/General/Ninjago/NjRailPostServer.cpp @@ -19,7 +19,7 @@ void NjRailPostServer::OnNotifyObject(Entity* self, Entity* sender, const std::s } void NjRailPostServer::OnRebuildNotifyState(Entity* self, eRebuildState state) { - if (state == REBUILD_COMPLETED) { + if (state == eRebuildState::COMPLETED) { auto* relatedRail = GetRelatedRail(self); if (relatedRail == nullptr) return; @@ -30,7 +30,7 @@ void NjRailPostServer::OnRebuildNotifyState(Entity* self, eRebuildState state) { return; self->SetNetworkVar(NetworkNotActiveVariable, false); - } else if (state == REBUILD_RESETTING) { + } else if (state == eRebuildState::RESETTING) { auto* relatedRail = GetRelatedRail(self); if (relatedRail == nullptr) return; diff --git a/dScripts/02_server/Map/General/Ninjago/NjhubLavaPlayerDeathTrigger.cpp b/dScripts/02_server/Map/General/Ninjago/NjhubLavaPlayerDeathTrigger.cpp index c065f84a..e2b889ef 100644 --- a/dScripts/02_server/Map/General/Ninjago/NjhubLavaPlayerDeathTrigger.cpp +++ b/dScripts/02_server/Map/General/Ninjago/NjhubLavaPlayerDeathTrigger.cpp @@ -5,5 +5,5 @@ void NjhubLavaPlayerDeathTrigger::OnCollisionPhantom(Entity* self, Entity* targe if (!target->IsPlayer()) return; - target->Smash(self->GetObjectID(), VIOLENT, u"drown"); + target->Smash(self->GetObjectID(), eKillType::VIOLENT, u"drown"); } diff --git a/dScripts/02_server/Map/General/PetDigServer.cpp b/dScripts/02_server/Map/General/PetDigServer.cpp index 81d70faf..8c819a8d 100644 --- a/dScripts/02_server/Map/General/PetDigServer.cpp +++ b/dScripts/02_server/Map/General/PetDigServer.cpp @@ -97,7 +97,7 @@ void PetDigServer::OnDie(Entity* self, Entity* killer) { // Handles smashing leftovers (edge case for the AG X) auto* xObject = EntityManager::Instance()->GetEntity(self->GetVar<LWOOBJID>(u"X")); if (xObject != nullptr) { - xObject->Smash(xObject->GetObjectID(), VIOLENT); + xObject->Smash(xObject->GetObjectID(), eKillType::VIOLENT); } } @@ -112,7 +112,7 @@ void PetDigServer::HandleXBuildDig(const Entity* self, Entity* owner, Entity* pe auto* player = playerEntity->GetCharacter(); const auto groupID = self->GetVar<std::u16string>(u"groupID"); - auto playerFlag = 0; + int32_t playerFlag = 0; // The flag that the player dug up if (groupID == u"Flag1") { @@ -136,7 +136,7 @@ void PetDigServer::HandleXBuildDig(const Entity* self, Entity* owner, Entity* pe auto* xObject = EntityManager::Instance()->GetEntity(self->GetVar<LWOOBJID>(u"X")); if (xObject != nullptr) { - xObject->Smash(xObject->GetObjectID(), VIOLENT); + xObject->Smash(xObject->GetObjectID(), eKillType::VIOLENT); } } diff --git a/dScripts/02_server/Map/General/PropertyPlatform.cpp b/dScripts/02_server/Map/General/PropertyPlatform.cpp index 902b9646..7016db94 100644 --- a/dScripts/02_server/Map/General/PropertyPlatform.cpp +++ b/dScripts/02_server/Map/General/PropertyPlatform.cpp @@ -15,7 +15,7 @@ void PropertyPlatform::OnRebuildComplete(Entity* self, Entity* target) { void PropertyPlatform::OnUse(Entity* self, Entity* user) { auto* rebuildComponent = self->GetComponent<RebuildComponent>(); - if (rebuildComponent != nullptr && rebuildComponent->GetState() == REBUILD_COMPLETED) { + if (rebuildComponent != nullptr && rebuildComponent->GetState() == eRebuildState::COMPLETED) { // auto* movingPlatform = self->GetComponent<MovingPlatformComponent>(); // if (movingPlatform != nullptr) { // movingPlatform->GotoWaypoint(1); diff --git a/dScripts/02_server/Map/General/TokenConsoleServer.cpp b/dScripts/02_server/Map/General/TokenConsoleServer.cpp index 5212a9b5..e13011cb 100644 --- a/dScripts/02_server/Map/General/TokenConsoleServer.cpp +++ b/dScripts/02_server/Map/General/TokenConsoleServer.cpp @@ -3,6 +3,8 @@ #include "GameMessages.h" #include "Character.h" #include "eReplicaComponentType.h" +#include "eTerminateType.h" +#include "ePlayerFlag.h" //2021-05-03 - max - added script, omitted some parts related to inheritance in lua which we don't need @@ -22,15 +24,15 @@ void TokenConsoleServer::OnUse(Entity* self, Entity* user) { if (!character) return; // At this point the player has to be in a faction. LOT tokenLOT = 0; - if (character->GetPlayerFlag(ePlayerFlags::VENTURE_FACTION)) //venture + if (character->GetPlayerFlag(ePlayerFlag::VENTURE_FACTION)) //venture tokenLOT = 8321; - else if (character->GetPlayerFlag(ePlayerFlags::ASSEMBLY_FACTION)) //assembly + else if (character->GetPlayerFlag(ePlayerFlag::ASSEMBLY_FACTION)) //assembly tokenLOT = 8318; - else if (character->GetPlayerFlag(ePlayerFlags::PARADOX_FACTION)) //paradox + else if (character->GetPlayerFlag(ePlayerFlag::PARADOX_FACTION)) //paradox tokenLOT = 8320; - else if (character->GetPlayerFlag(ePlayerFlags::SENTINEL_FACTION)) //sentinel + else if (character->GetPlayerFlag(ePlayerFlag::SENTINEL_FACTION)) //sentinel tokenLOT = 8319; - inv->AddItem(tokenLOT, tokensToGive, eLootSourceType::LOOT_SOURCE_NONE); + inv->AddItem(tokenLOT, tokensToGive, eLootSourceType::NONE); } GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); diff --git a/dScripts/02_server/Map/General/WishingWellServer.cpp b/dScripts/02_server/Map/General/WishingWellServer.cpp index fa3e13e0..58ce1c72 100644 --- a/dScripts/02_server/Map/General/WishingWellServer.cpp +++ b/dScripts/02_server/Map/General/WishingWellServer.cpp @@ -3,6 +3,7 @@ #include "GameMessages.h" #include "Loot.h" #include "EntityManager.h" +#include "eTerminateType.h" void WishingWellServer::OnStartup(Entity* self) { } diff --git a/dScripts/02_server/Map/NS/NsTokenConsoleServer.cpp b/dScripts/02_server/Map/NS/NsTokenConsoleServer.cpp index a62c165c..326842d2 100644 --- a/dScripts/02_server/Map/NS/NsTokenConsoleServer.cpp +++ b/dScripts/02_server/Map/NS/NsTokenConsoleServer.cpp @@ -4,6 +4,8 @@ #include "Character.h" #include "MissionComponent.h" #include "RebuildComponent.h" +#include "eTerminateType.h" +#include "ePlayerFlag.h" void NsTokenConsoleServer::OnStartup(Entity* self) { @@ -16,7 +18,7 @@ void NsTokenConsoleServer::OnUse(Entity* self, Entity* user) { return; } - if (rebuildComponent->GetState() != REBUILD_COMPLETED) { + if (rebuildComponent->GetState() != eRebuildState::COMPLETED) { return; } @@ -42,20 +44,18 @@ void NsTokenConsoleServer::OnUse(Entity* self, Entity* user) { // Player must be in faction to interact with this entity. LOT tokenLOT = 0; - - if (character->GetPlayerFlag(46)) { + if (character->GetPlayerFlag(ePlayerFlag::VENTURE_FACTION)) //venture tokenLOT = 8321; - } else if (character->GetPlayerFlag(47)) { + else if (character->GetPlayerFlag(ePlayerFlag::ASSEMBLY_FACTION)) //assembly tokenLOT = 8318; - } else if (character->GetPlayerFlag(48)) { + else if (character->GetPlayerFlag(ePlayerFlag::PARADOX_FACTION)) //paradox tokenLOT = 8320; - } else if (character->GetPlayerFlag(49)) { + else if (character->GetPlayerFlag(ePlayerFlag::SENTINEL_FACTION)) //sentinel tokenLOT = 8319; - } - inventoryComponent->AddItem(tokenLOT, 5, eLootSourceType::LOOT_SOURCE_NONE); + inventoryComponent->AddItem(tokenLOT, 5, eLootSourceType::NONE); missionComponent->ForceProgressTaskType(863, 1, 1, false); - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp b/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp index 74f9bd16..5f1619ab 100644 --- a/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp +++ b/dScripts/02_server/Map/NT/NtAssemblyTubeServer.cpp @@ -5,6 +5,7 @@ #include "eMissionTaskType.h" #include "eMissionState.h" #include "eEndBehavior.h" +#include "eStateChangeType.h" void NtAssemblyTubeServer::OnStartup(Entity* self) { self->SetProximityRadius(5, "teleport"); diff --git a/dScripts/02_server/Map/NT/NtDirtCloudServer.cpp b/dScripts/02_server/Map/NT/NtDirtCloudServer.cpp index a9a70c5c..92175dea 100644 --- a/dScripts/02_server/Map/NT/NtDirtCloudServer.cpp +++ b/dScripts/02_server/Map/NT/NtDirtCloudServer.cpp @@ -42,5 +42,5 @@ void NtDirtCloudServer::OnSkillEventFired(Entity* self, Entity* caster, const st self->SetVar(u"CloudOn", false); - self->Smash(self->GetObjectID(), VIOLENT); + self->Smash(self->GetObjectID(), eKillType::VIOLENT); } diff --git a/dScripts/02_server/Map/NT/NtDukeServer.cpp b/dScripts/02_server/Map/NT/NtDukeServer.cpp index d48d50c7..07d17e96 100644 --- a/dScripts/02_server/Map/NT/NtDukeServer.cpp +++ b/dScripts/02_server/Map/NT/NtDukeServer.cpp @@ -2,12 +2,13 @@ #include "InventoryComponent.h" #include "MissionComponent.h" #include "eMissionState.h" +#include "ePlayerFlag.h" void NtDukeServer::SetVariables(Entity* self) { self->SetVar<float_t>(m_SpyProximityVariable, 35.0f); self->SetVar<SpyData>(m_SpyDataVariable, { - NT_FACTION_SPY_DUKE, 13548, 1319 + ePlayerFlag::NT_FACTION_SPY_DUKE, 13548, 1319 }); self->SetVar<std::vector<SpyDialogue>>(m_SpyDialogueTableVariable, { @@ -31,7 +32,7 @@ void NtDukeServer::OnMissionDialogueOK(Entity* self, Entity* target, int mission auto lotCount = inventoryComponent->GetLotCount(m_SwordLot); if ((state == eMissionState::AVAILABLE || state == eMissionState::ACTIVE) && lotCount < 1) { - inventoryComponent->AddItem(m_SwordLot, 1, eLootSourceType::LOOT_SOURCE_NONE); + inventoryComponent->AddItem(m_SwordLot, 1, eLootSourceType::NONE); } else if (state == eMissionState::READY_TO_COMPLETE) { inventoryComponent->RemoveItem(m_SwordLot, lotCount); } diff --git a/dScripts/02_server/Map/NT/NtHaelServer.cpp b/dScripts/02_server/Map/NT/NtHaelServer.cpp index fbad421f..c726ae58 100644 --- a/dScripts/02_server/Map/NT/NtHaelServer.cpp +++ b/dScripts/02_server/Map/NT/NtHaelServer.cpp @@ -1,11 +1,12 @@ #include "NtHaelServer.h" #include "Entity.h" +#include "ePlayerFlag.h" void NtHaelServer::SetVariables(Entity* self) { self->SetVar<float_t>(m_SpyProximityVariable, 25.0f); self->SetVar<SpyData>(m_SpyDataVariable, { - NT_FACTION_SPY_HAEL, 13892, 1321 + ePlayerFlag::NT_FACTION_SPY_HAEL, 13892, 1321 }); self->SetVar<std::vector<SpyDialogue>>(m_SpyDialogueTableVariable, { diff --git a/dScripts/02_server/Map/NT/NtImagimeterVisibility.cpp b/dScripts/02_server/Map/NT/NtImagimeterVisibility.cpp index c0f9bf51..64493d78 100644 --- a/dScripts/02_server/Map/NT/NtImagimeterVisibility.cpp +++ b/dScripts/02_server/Map/NT/NtImagimeterVisibility.cpp @@ -2,10 +2,11 @@ #include "GameMessages.h" #include "Entity.h" #include "Character.h" +#include "ePlayerFlag.h" void NTImagimeterVisibility::OnRebuildComplete(Entity* self, Entity* target) { auto* character = target->GetCharacter(); - if (character) character->SetPlayerFlag(ePlayerFlags::NT_PLINTH_REBUILD, true); + if (character) character->SetPlayerFlag(ePlayerFlag::NT_PLINTH_REBUILD, true); GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlinthBuilt", 0, 0, LWOOBJID_EMPTY, "", target->GetSystemAddress()); } diff --git a/dScripts/02_server/Map/NT/NtOverbuildServer.cpp b/dScripts/02_server/Map/NT/NtOverbuildServer.cpp index 8411e55b..f8520d87 100644 --- a/dScripts/02_server/Map/NT/NtOverbuildServer.cpp +++ b/dScripts/02_server/Map/NT/NtOverbuildServer.cpp @@ -1,11 +1,12 @@ #include "NtOverbuildServer.h" #include "EntityManager.h" +#include "ePlayerFlag.h" void NtOverbuildServer::SetVariables(Entity* self) { self->SetVar<float_t>(m_SpyProximityVariable, 30.0f); self->SetVar<SpyData>(m_SpyDataVariable, { - NT_FACTION_SPY_OVERBUILD, 13891, 1320 + ePlayerFlag::NT_FACTION_SPY_OVERBUILD, 13891, 1320 }); self->SetVar<std::vector<SpyDialogue>>(m_SpyDialogueTableVariable, { diff --git a/dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp b/dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp index 0cb0bec4..23d336a7 100644 --- a/dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp +++ b/dScripts/02_server/Map/NT/NtParadoxPanelServer.cpp @@ -4,6 +4,8 @@ #include "EntityManager.h" #include "Character.h" #include "eMissionState.h" +#include "eTerminateType.h" +#include "eStateChangeType.h" void NtParadoxPanelServer::OnUse(Entity* self, Entity* user) { GameMessages::SendNotifyClientObject(self->GetObjectID(), u"bActive", 1, 0, user->GetObjectID(), "", user->GetSystemAddress()); diff --git a/dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp b/dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp index 8b4f19fe..b19c8c0b 100644 --- a/dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp +++ b/dScripts/02_server/Map/NT/NtParadoxTeleServer.cpp @@ -3,6 +3,7 @@ #include "EntityManager.h" #include "MissionComponent.h" #include "eMissionTaskType.h" +#include "eStateChangeType.h" void NtParadoxTeleServer::OnStartup(Entity* self) { self->SetProximityRadius(5, "teleport"); diff --git a/dScripts/02_server/Map/NT/NtVentureCannonServer.cpp b/dScripts/02_server/Map/NT/NtVentureCannonServer.cpp index 874d8aa1..38f929a1 100644 --- a/dScripts/02_server/Map/NT/NtVentureCannonServer.cpp +++ b/dScripts/02_server/Map/NT/NtVentureCannonServer.cpp @@ -2,6 +2,8 @@ #include "GameMessages.h" #include "EntityManager.h" #include "eEndBehavior.h" +#include "eTerminateType.h" +#include "eStateChangeType.h" void NtVentureCannonServer::OnUse(Entity* self, Entity* user) { auto* player = user; @@ -99,7 +101,7 @@ void NtVentureCannonServer::UnlockCannonPlayer(Entity* self, Entity* player) { self->SetNetworkVar(u"bIsInUse", false); - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(player->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } void NtVentureCannonServer::FirePlayer(Entity* self, Entity* player) { diff --git a/dScripts/02_server/Map/PR/SpawnGryphonServer.cpp b/dScripts/02_server/Map/PR/SpawnGryphonServer.cpp index 2b7e3904..cf635fe4 100644 --- a/dScripts/02_server/Map/PR/SpawnGryphonServer.cpp +++ b/dScripts/02_server/Map/PR/SpawnGryphonServer.cpp @@ -3,6 +3,7 @@ #include "GameMessages.h" #include "MissionComponent.h" #include "eMissionState.h" +#include "eTerminateType.h" void SpawnGryphonServer::SetVariables(Entity* self) { self->SetVar<LOT>(u"petLOT", 12433); @@ -20,7 +21,7 @@ void SpawnGryphonServer::OnUse(Entity* self, Entity* user) { if (missionComponent != nullptr && inventoryComponent != nullptr && missionComponent->GetMissionState(1391) == eMissionState::ACTIVE) { inventoryComponent->RemoveItem(12483, inventoryComponent->GetLotCount(12483)); - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); return; } diff --git a/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp b/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp index 215e22c2..635eb8b3 100644 --- a/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp +++ b/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp @@ -413,7 +413,7 @@ void ZoneAgProperty::BaseOnFireEventServerSide(Entity* self, Entity* sender, std if (player == nullptr) return; - player->GetCharacter()->SetPlayerFlag(self->GetVar<uint32_t>(defeatedProperyFlag), true); + player->GetCharacter()->SetPlayerFlag(self->GetVar<int32_t>(defeatedProperyFlag), true); GameMessages::SendNotifyClientObject(self->GetObjectID(), u"PlayCinematic", 0, 0, LWOOBJID_EMPTY, destroyedCinematic, UNASSIGNED_SYSTEM_ADDRESS); diff --git a/dScripts/02_server/Map/Property/NS_Med/ZoneNsMedProperty.cpp b/dScripts/02_server/Map/Property/NS_Med/ZoneNsMedProperty.cpp index 30e597ee..55bde71c 100644 --- a/dScripts/02_server/Map/Property/NS_Med/ZoneNsMedProperty.cpp +++ b/dScripts/02_server/Map/Property/NS_Med/ZoneNsMedProperty.cpp @@ -29,8 +29,8 @@ void ZoneNsMedProperty::SetGameVariables(Entity* self) { self->SetVar<std::vector<std::string>>(AmbientFXSpawner, { "Rockets" }); self->SetVar<std::vector<std::string>>(BehaviorObjsSpawner, { }); - self->SetVar<uint32_t>(defeatedProperyFlag, 122); - self->SetVar<uint32_t>(placedModelFlag, 123); + self->SetVar<int32_t>(defeatedProperyFlag, 122); + self->SetVar<int32_t>(placedModelFlag, 123); self->SetVar<uint32_t>(guardMissionFlag, 1322); self->SetVar<uint32_t>(brickLinkMissionIDFlag, 1294); self->SetVar<std::string>(passwordFlag, "s3kratK1ttN"); diff --git a/dScripts/02_server/Map/VE/VeBricksampleServer.cpp b/dScripts/02_server/Map/VE/VeBricksampleServer.cpp index 36306d07..0ead6a87 100644 --- a/dScripts/02_server/Map/VE/VeBricksampleServer.cpp +++ b/dScripts/02_server/Map/VE/VeBricksampleServer.cpp @@ -12,7 +12,7 @@ void VeBricksampleServer::OnUse(Entity* self, Entity* user) { auto* inventoryComponent = user->GetComponent<InventoryComponent>(); if (loot && inventoryComponent != nullptr && inventoryComponent->GetLotCount(loot) == 0) { - inventoryComponent->AddItem(loot, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY); + inventoryComponent->AddItem(loot, 1, eLootSourceType::ACTIVITY); for (auto* brickEntity : EntityManager::Instance()->GetEntitiesInGroup("Bricks")) { GameMessages::SendNotifyClientObject(brickEntity->GetObjectID(), u"Pickedup"); diff --git a/dScripts/02_server/Map/VE/VeEpsilonServer.h b/dScripts/02_server/Map/VE/VeEpsilonServer.h index 971cd93e..d5a53f9e 100644 --- a/dScripts/02_server/Map/VE/VeEpsilonServer.h +++ b/dScripts/02_server/Map/VE/VeEpsilonServer.h @@ -5,6 +5,6 @@ class VeEpsilonServer : public CppScripts::Script { void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; const uint32_t m_ConsoleMissionID = 1220; const uint32_t m_ConsoleRepeatMissionID = 1225; - const uint32_t m_ConsoleBaseFlag = 1010; + const int32_t m_ConsoleBaseFlag = 1010; const std::string m_ConsoleGroup = "Consoles"; }; diff --git a/dScripts/02_server/Map/VE/VeMissionConsole.cpp b/dScripts/02_server/Map/VE/VeMissionConsole.cpp index 534f8c06..35061bdf 100644 --- a/dScripts/02_server/Map/VE/VeMissionConsole.cpp +++ b/dScripts/02_server/Map/VE/VeMissionConsole.cpp @@ -3,18 +3,19 @@ #include "Character.h" #include "GameMessages.h" #include "Loot.h" +#include "eTerminateType.h" void VeMissionConsole::OnUse(Entity* self, Entity* user) { LootGenerator::Instance().DropActivityLoot(user, self, 12551); auto* inventoryComponent = user->GetComponent<InventoryComponent>(); if (inventoryComponent != nullptr) { - inventoryComponent->AddItem(12547, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY); // Add the panel required for pickup + inventoryComponent->AddItem(12547, 1, eLootSourceType::ACTIVITY); // Add the panel required for pickup } // The flag to set is 101<number> const auto flagNumber = self->GetVar<std::u16string>(m_NumberVariable); - const auto flag = std::stoi("101" + GeneralUtils::UTF16ToWTF8(flagNumber)); + const int32_t flag = std::stoi("101" + GeneralUtils::UTF16ToWTF8(flagNumber)); auto* character = user->GetCharacter(); if (character != nullptr) { @@ -22,5 +23,5 @@ void VeMissionConsole::OnUse(Entity* self, Entity* user) { } GameMessages::SendNotifyClientObject(self->GetObjectID(), u""); - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/02_server/Map/njhub/CatapultBaseServer.cpp b/dScripts/02_server/Map/njhub/CatapultBaseServer.cpp index fda103b0..2df32658 100644 --- a/dScripts/02_server/Map/njhub/CatapultBaseServer.cpp +++ b/dScripts/02_server/Map/njhub/CatapultBaseServer.cpp @@ -59,6 +59,6 @@ void CatapultBaseServer::OnTimerDone(Entity* self, std::string timerName) { // kill the bouncer GameMessages::SendNotifyClientObject(bouncer->GetObjectID(), u"TimeToDie"); - bouncer->Smash(self->GetObjectID(), VIOLENT); + bouncer->Smash(self->GetObjectID(), eKillType::VIOLENT); } } diff --git a/dScripts/02_server/Map/njhub/CavePrisonCage.cpp b/dScripts/02_server/Map/njhub/CavePrisonCage.cpp index 0df91884..60bd1b88 100644 --- a/dScripts/02_server/Map/njhub/CavePrisonCage.cpp +++ b/dScripts/02_server/Map/njhub/CavePrisonCage.cpp @@ -45,7 +45,7 @@ void CavePrisonCage::Setup(Entity* self, Spawner* spawner) { } void CavePrisonCage::OnRebuildNotifyState(Entity* self, eRebuildState state) { - if (state != eRebuildState::REBUILD_RESETTING) { + if (state != eRebuildState::RESETTING) { return; } diff --git a/dScripts/02_server/Map/njhub/ImaginationShrineServer.cpp b/dScripts/02_server/Map/njhub/ImaginationShrineServer.cpp index 267d0480..1fbfad98 100644 --- a/dScripts/02_server/Map/njhub/ImaginationShrineServer.cpp +++ b/dScripts/02_server/Map/njhub/ImaginationShrineServer.cpp @@ -9,7 +9,7 @@ void ImaginationShrineServer::OnUse(Entity* self, Entity* user) { return; } - if (rebuildComponent->GetState() == REBUILD_COMPLETED) { + if (rebuildComponent->GetState() == eRebuildState::COMPLETED) { // Use the shrine BaseUse(self, user); } diff --git a/dScripts/02_server/Map/njhub/NjColeNPC.cpp b/dScripts/02_server/Map/njhub/NjColeNPC.cpp index 672fdd95..b989f3ee 100644 --- a/dScripts/02_server/Map/njhub/NjColeNPC.cpp +++ b/dScripts/02_server/Map/njhub/NjColeNPC.cpp @@ -44,6 +44,6 @@ void NjColeNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, return; } - inventoryComponent->AddItem(16644, 1, eLootSourceType::LOOT_SOURCE_NONE); + inventoryComponent->AddItem(16644, 1, eLootSourceType::NONE); } } diff --git a/dScripts/02_server/Map/njhub/NjDragonEmblemChestServer.cpp b/dScripts/02_server/Map/njhub/NjDragonEmblemChestServer.cpp index be9fcbd9..931cfe56 100644 --- a/dScripts/02_server/Map/njhub/NjDragonEmblemChestServer.cpp +++ b/dScripts/02_server/Map/njhub/NjDragonEmblemChestServer.cpp @@ -4,11 +4,12 @@ #include "Loot.h" #include "Entity.h" #include "DestroyableComponent.h" +#include "ePlayerFlag.h" void NjDragonEmblemChestServer::OnUse(Entity* self, Entity* user) { auto* character = user->GetCharacter(); if (character != nullptr) { - character->SetPlayerFlag(NJ_WU_SHOW_DAILY_CHEST, false); + character->SetPlayerFlag(ePlayerFlag::NJ_WU_SHOW_DAILY_CHEST, false); } auto* destroyable = self->GetComponent<DestroyableComponent>(); diff --git a/dScripts/02_server/Map/njhub/NjGarmadonCelebration.cpp b/dScripts/02_server/Map/njhub/NjGarmadonCelebration.cpp index c223c55c..d3e54be1 100644 --- a/dScripts/02_server/Map/njhub/NjGarmadonCelebration.cpp +++ b/dScripts/02_server/Map/njhub/NjGarmadonCelebration.cpp @@ -1,6 +1,7 @@ #include "NjGarmadonCelebration.h" #include "Character.h" #include "GameMessages.h" +#include "ePlayerFlag.h" void NjGarmadonCelebration::OnCollisionPhantom(Entity* self, Entity* target) { auto* character = target->GetCharacter(); @@ -9,8 +10,8 @@ void NjGarmadonCelebration::OnCollisionPhantom(Entity* self, Entity* target) { return; } - if (!character->GetPlayerFlag(ePlayerFlags::NJ_GARMADON_CINEMATIC_SEEN)) { - character->SetPlayerFlag(ePlayerFlags::NJ_GARMADON_CINEMATIC_SEEN, true); + if (!character->GetPlayerFlag(ePlayerFlag::NJ_GARMADON_CINEMATIC_SEEN)) { + character->SetPlayerFlag(ePlayerFlag::NJ_GARMADON_CINEMATIC_SEEN, true); GameMessages::SendStartCelebrationEffect(target, target->GetSystemAddress(), GarmadonCelebrationID); } diff --git a/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.h b/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.h index 3c705925..116ecc93 100644 --- a/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.h +++ b/dScripts/02_server/Map/njhub/NjNPCMissionSpinjitzuServer.h @@ -1,12 +1,13 @@ #pragma once #include "CppScripts.h" #include <map> +#include "ePlayerFlag.h" -static std::map<std::u16string, uint32_t> ElementFlags = { - {u"earth", ePlayerFlags::NJ_EARTH_SPINJITZU}, - {u"lightning", ePlayerFlags::NJ_LIGHTNING_SPINJITZU}, - {u"ice", ePlayerFlags::NJ_ICE_SPINJITZU}, - {u"fire", ePlayerFlags::NJ_FIRE_SPINJITZU} +static std::map<std::u16string, ePlayerFlag> ElementFlags = { + {u"earth", ePlayerFlag::NJ_EARTH_SPINJITZU}, + {u"lightning", ePlayerFlag::NJ_LIGHTNING_SPINJITZU}, + {u"ice", ePlayerFlag::NJ_ICE_SPINJITZU}, + {u"fire", ePlayerFlag::NJ_FIRE_SPINJITZU} }; static std::map<std::u16string, uint32_t> ElementMissions = { diff --git a/dScripts/02_server/Map/njhub/NjScrollChestServer.cpp b/dScripts/02_server/Map/njhub/NjScrollChestServer.cpp index 4e1350b4..7156b368 100644 --- a/dScripts/02_server/Map/njhub/NjScrollChestServer.cpp +++ b/dScripts/02_server/Map/njhub/NjScrollChestServer.cpp @@ -12,6 +12,6 @@ void NjScrollChestServer::OnUse(Entity* self, Entity* user) { playerInventory->RemoveItem(keyLOT, 1); // Reward the player with the item set - playerInventory->AddItem(rewardItemLOT, 1, eLootSourceType::LOOT_SOURCE_NONE); + playerInventory->AddItem(rewardItemLOT, 1, eLootSourceType::NONE); } } diff --git a/dScripts/02_server/Map/njhub/NjWuNPC.cpp b/dScripts/02_server/Map/njhub/NjWuNPC.cpp index 9efc623b..f4969074 100644 --- a/dScripts/02_server/Map/njhub/NjWuNPC.cpp +++ b/dScripts/02_server/Map/njhub/NjWuNPC.cpp @@ -4,6 +4,7 @@ #include "EntityManager.h" #include "GameMessages.h" #include "eMissionState.h" +#include "ePlayerFlag.h" void NjWuNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { @@ -24,7 +25,7 @@ void NjWuNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, e missionComponent->AcceptMission(subMissionID); } - character->SetPlayerFlag(ePlayerFlags::NJ_WU_SHOW_DAILY_CHEST, false); + character->SetPlayerFlag(ePlayerFlag::NJ_WU_SHOW_DAILY_CHEST, false); // Hide the chest for (auto* chest : EntityManager::Instance()->GetEntitiesInGroup(m_DragonChestGroup)) { @@ -37,7 +38,7 @@ void NjWuNPC::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, e case eMissionState::READY_TO_COMPLETE: case eMissionState::COMPLETE_READY_TO_COMPLETE: { - character->SetPlayerFlag(NJ_WU_SHOW_DAILY_CHEST, true); + character->SetPlayerFlag(ePlayerFlag::NJ_WU_SHOW_DAILY_CHEST, true); // Show the chest for (auto* chest : EntityManager::Instance()->GetEntitiesInGroup(m_DragonChestGroup)) { diff --git a/dScripts/02_server/Map/njhub/boss_instance/NjMonastryBossInstance.cpp b/dScripts/02_server/Map/njhub/boss_instance/NjMonastryBossInstance.cpp index dbab7365..4de7638f 100644 --- a/dScripts/02_server/Map/njhub/boss_instance/NjMonastryBossInstance.cpp +++ b/dScripts/02_server/Map/njhub/boss_instance/NjMonastryBossInstance.cpp @@ -225,21 +225,21 @@ void NjMonastryBossInstance::HandleCounterWeightSpawned(Entity* self, Entity* co rebuildComponent->AddRebuildStateCallback([this, self, counterWeight](eRebuildState state) { switch (state) { - case REBUILD_BUILDING: + case eRebuildState::BUILDING: GameMessages::SendNotifyClientObject(self->GetObjectID(), PlayCinematicNotification, 0, 0, counterWeight->GetObjectID(), BaseCounterweightQB + std::to_string(self->GetVar<uint32_t>(WaveNumberVariable)), UNASSIGNED_SYSTEM_ADDRESS); return; - case REBUILD_INCOMPLETE: + case eRebuildState::INCOMPLETE: GameMessages::SendNotifyClientObject(self->GetObjectID(), EndCinematicNotification, 0, 0, LWOOBJID_EMPTY, "", UNASSIGNED_SYSTEM_ADDRESS); return; - case REBUILD_RESETTING: + case eRebuildState::RESETTING: ActivityTimerStart(self, SpawnCounterWeightTimer, 0.0f, 0.0f); return; - case REBUILD_COMPLETED: { + case eRebuildState::COMPLETED: { // TODO: Move the platform? // The counterweight is actually a moving platform and we should listen to the last waypoint event here diff --git a/dScripts/02_server/Pets/DamagingPets.cpp b/dScripts/02_server/Pets/DamagingPets.cpp index f7eada00..6fd8c560 100644 --- a/dScripts/02_server/Pets/DamagingPets.cpp +++ b/dScripts/02_server/Pets/DamagingPets.cpp @@ -3,6 +3,7 @@ #include "DestroyableComponent.h" #include "BaseCombatAIComponent.h" #include "RenderComponent.h" +#include "ePetTamingNotifyType.h" void DamagingPets::OnStartup(Entity* self) { @@ -33,15 +34,15 @@ void DamagingPets::OnPlayerLoaded(Entity* self, Entity* player) { }); } -void DamagingPets::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { +void DamagingPets::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, ePetTamingNotifyType type) { switch (type) { - case NOTIFY_TYPE_SUCCESS: - case NOTIFY_TYPE_BEGIN: + case ePetTamingNotifyType::SUCCESS: + case ePetTamingNotifyType::BEGIN: self->CancelAllTimers(); ClearEffects(self); break; - case NOTIFY_TYPE_FAILED: - case NOTIFY_TYPE_QUIT: + case ePetTamingNotifyType::FAILED: + case ePetTamingNotifyType::QUIT: { self->SetNetworkVar<bool>(u"bIAmTamable", false); self->AddTimer("GoEvil", 1.0f); diff --git a/dScripts/02_server/Pets/DamagingPets.h b/dScripts/02_server/Pets/DamagingPets.h index 2ce0ddc1..303bff52 100644 --- a/dScripts/02_server/Pets/DamagingPets.h +++ b/dScripts/02_server/Pets/DamagingPets.h @@ -13,7 +13,7 @@ class DamagingPets : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnTimerDone(Entity* self, std::string message) override; - void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, ePetTamingNotifyType type) override; void OnSkillEventFired(Entity* self, Entity* target, const std::string& message) override; void OnPlayerLoaded(Entity* self, Entity* player) override; private: diff --git a/dScripts/02_server/Pets/PetFromDigServer.cpp b/dScripts/02_server/Pets/PetFromDigServer.cpp index 5aca7486..525f3e94 100644 --- a/dScripts/02_server/Pets/PetFromDigServer.cpp +++ b/dScripts/02_server/Pets/PetFromDigServer.cpp @@ -1,5 +1,6 @@ #include "PetFromDigServer.h" #include "PetComponent.h" +#include "ePetTamingNotifyType.h" void PetFromDigServer::OnStartup(Entity* self) { auto* petComponent = self->GetComponent<PetComponent>(); @@ -24,16 +25,16 @@ void PetFromDigServer::OnTimerDone(Entity* self, std::string timerName) { if (petComponent == nullptr || petComponent->GetOwner() != nullptr) return; - self->Smash(self->GetObjectID(), SILENT); + self->Smash(self->GetObjectID(), eKillType::SILENT); } } -void PetFromDigServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { - if (type == NOTIFY_TYPE_BEGIN) { +void PetFromDigServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, ePetTamingNotifyType type) { + if (type == ePetTamingNotifyType::BEGIN) { self->CancelTimer("killself"); - } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { - self->Smash(self->GetObjectID(), SILENT); - } else if (type == NOTIFY_TYPE_SUCCESS) { + } else if (type == ePetTamingNotifyType::QUIT || type == ePetTamingNotifyType::FAILED) { + self->Smash(self->GetObjectID(), eKillType::SILENT); + } else if (type == ePetTamingNotifyType::SUCCESS) { auto* petComponent = self->GetComponent<PetComponent>(); if (petComponent == nullptr) return; diff --git a/dScripts/02_server/Pets/PetFromDigServer.h b/dScripts/02_server/Pets/PetFromDigServer.h index 3faf248d..aaf31728 100644 --- a/dScripts/02_server/Pets/PetFromDigServer.h +++ b/dScripts/02_server/Pets/PetFromDigServer.h @@ -6,5 +6,5 @@ class PetFromDigServer : public CppScripts::Script public: void OnStartup(Entity* self) override; void OnTimerDone(Entity* self, std::string timerName) override; - void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, ePetTamingNotifyType type) override; }; diff --git a/dScripts/02_server/Pets/PetFromObjectServer.cpp b/dScripts/02_server/Pets/PetFromObjectServer.cpp index 899b394a..0a78d7ec 100644 --- a/dScripts/02_server/Pets/PetFromObjectServer.cpp +++ b/dScripts/02_server/Pets/PetFromObjectServer.cpp @@ -1,5 +1,6 @@ #include "PetFromObjectServer.h" #include "PetComponent.h" +#include "ePetTamingNotifyType.h" void PetFromObjectServer::OnStartup(Entity* self) { self->SetNetworkVar(u"pettamer", std::to_string(self->GetVar<LWOOBJID>(u"tamer"))); @@ -11,20 +12,20 @@ void PetFromObjectServer::OnTimerDone(Entity* self, std::string timerName) { const auto* petComponent = self->GetComponent<PetComponent>(); if (petComponent == nullptr || petComponent->GetOwner() != nullptr) return; - self->Smash(self->GetObjectID(), SILENT); + self->Smash(self->GetObjectID(), eKillType::SILENT); } } -void PetFromObjectServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { +void PetFromObjectServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, ePetTamingNotifyType type) { switch (type) { - case NOTIFY_TYPE_BEGIN: + case ePetTamingNotifyType::BEGIN: self->CancelAllTimers(); break; - case NOTIFY_TYPE_QUIT: - case NOTIFY_TYPE_FAILED: - self->Smash(self->GetObjectID(), SILENT); + case ePetTamingNotifyType::QUIT: + case ePetTamingNotifyType::FAILED: + self->Smash(self->GetObjectID(), eKillType::SILENT); break; - case NOTIFY_TYPE_SUCCESS: + case ePetTamingNotifyType::SUCCESS: // TODO: Remove from groups? GameMessages::SendNotifyClientObject(self->GetObjectID(), u"UpdateSuccessPicking", 0, 0, tamer->GetObjectID(), "", UNASSIGNED_SYSTEM_ADDRESS); diff --git a/dScripts/02_server/Pets/PetFromObjectServer.h b/dScripts/02_server/Pets/PetFromObjectServer.h index 1a7c244b..67cd5eb0 100644 --- a/dScripts/02_server/Pets/PetFromObjectServer.h +++ b/dScripts/02_server/Pets/PetFromObjectServer.h @@ -5,5 +5,5 @@ class PetFromObjectServer : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnTimerDone(Entity* self, std::string timerName) override; - void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, ePetTamingNotifyType type) override; }; diff --git a/dScripts/BaseConsoleTeleportServer.cpp b/dScripts/BaseConsoleTeleportServer.cpp index d0162e9c..4a059535 100644 --- a/dScripts/BaseConsoleTeleportServer.cpp +++ b/dScripts/BaseConsoleTeleportServer.cpp @@ -1,6 +1,8 @@ #include "BaseConsoleTeleportServer.h" #include "GameMessages.h" #include "Player.h" +#include "eTerminateType.h" +#include "eStateChangeType.h" void BaseConsoleTeleportServer::BaseOnUse(Entity* self, Entity* user) { auto* player = user; @@ -52,7 +54,7 @@ void BaseConsoleTeleportServer::BaseOnMessageBoxResponse(Entity* self, Entity* s GameMessages::SendDisplayZoneSummary(playerID, player->GetSystemAddress(), false, false, self->GetObjectID()); }); } else if (button == -1 || button == 0) { - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, player->GetObjectID()); + GameMessages::SendTerminateInteraction(player->GetObjectID(), eTerminateType::FROM_INTERACTION, player->GetObjectID()); } } @@ -88,7 +90,7 @@ void BaseConsoleTeleportServer::TransferPlayer(Entity* self, Entity* player, int true, true, true, true, true, true, true ); - GameMessages::SendTerminateInteraction(player->GetObjectID(), FROM_INTERACTION, player->GetObjectID()); + GameMessages::SendTerminateInteraction(player->GetObjectID(), eTerminateType::FROM_INTERACTION, player->GetObjectID()); const auto& teleportZone = self->GetVar<std::u16string>(u"transferZoneID"); diff --git a/dScripts/BasePropertyServer.cpp b/dScripts/BasePropertyServer.cpp index a9f35e25..1522ef26 100644 --- a/dScripts/BasePropertyServer.cpp +++ b/dScripts/BasePropertyServer.cpp @@ -127,7 +127,7 @@ void BasePropertyServer::BasePlayerLoaded(Entity* self, Entity* player) { if (player->GetObjectID() != propertyOwner) return; } else { - const auto defeatedFlag = player->GetCharacter()->GetPlayerFlag(self->GetVar<uint32_t>(defeatedProperyFlag)); + const auto defeatedFlag = player->GetCharacter()->GetPlayerFlag(self->GetVar<int32_t>(defeatedProperyFlag)); self->SetNetworkVar(UnclaimedVariable, true); self->SetVar<LWOOBJID>(PlayerIDVariable, player->GetObjectID()); @@ -274,7 +274,7 @@ void BasePropertyServer::RequestDie(Entity* self, Entity* other) { if (destroyable == nullptr) return; - destroyable->Smash(other->GetObjectID(), SILENT); + destroyable->Smash(other->GetObjectID(), eKillType::SILENT); } void BasePropertyServer::ActivateSpawner(const std::string& spawnerName) { @@ -464,7 +464,7 @@ void BasePropertyServer::HandleOrbsTimer(Entity* self) { if (player != nullptr) { auto* character = player->GetCharacter(); if (character != nullptr) { - character->SetPlayerFlag(self->GetVar<uint32_t>(defeatedProperyFlag), true); + character->SetPlayerFlag(self->GetVar<int32_t>(defeatedProperyFlag), true); } } diff --git a/dScripts/ChooseYourDestinationNsToNt.cpp b/dScripts/ChooseYourDestinationNsToNt.cpp index e50d70c5..f9ca0a79 100644 --- a/dScripts/ChooseYourDestinationNsToNt.cpp +++ b/dScripts/ChooseYourDestinationNsToNt.cpp @@ -1,6 +1,7 @@ #include "ChooseYourDestinationNsToNt.h" #include "Character.h" #include "GameMessages.h" +#include "eTerminateType.h" bool ChooseYourDestinationNsToNt::CheckChoice(Entity* self, Entity* player) { const auto choiceZoneID = self->GetVar<int32_t>(u"choiceZone"); @@ -59,6 +60,6 @@ void ChooseYourDestinationNsToNt::BaseChoiceBoxRespond(Entity* self, Entity* sen GameMessages::SendDisplayMessageBox(sender->GetObjectID(), true, self->GetObjectID(), u"TransferBox", 0, strText, u"", sender->GetSystemAddress()); } else { - GameMessages::SendTerminateInteraction(sender->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(sender->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } } diff --git a/dScripts/CppScripts.h b/dScripts/CppScripts.h index 5c702a70..4bf3720f 100644 --- a/dScripts/CppScripts.h +++ b/dScripts/CppScripts.h @@ -8,6 +8,8 @@ class User; class Entity; class NiPoint3; enum class eMissionState : int32_t; +enum class ePetTamingNotifyType : uint32_t; +enum class eRebuildState : uint32_t; namespace CppScripts { /** @@ -269,7 +271,7 @@ namespace CppScripts { * * Equivalent to 'function onNotifyPetTamingMinigame(self, msg)' */ - virtual void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) {}; + virtual void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, ePetTamingNotifyType type) {}; /** * Invoked when a player responded to a message box. diff --git a/dScripts/EquipmentScripts/PersonalFortress.cpp b/dScripts/EquipmentScripts/PersonalFortress.cpp index f5062f9b..f1fe73ee 100644 --- a/dScripts/EquipmentScripts/PersonalFortress.cpp +++ b/dScripts/EquipmentScripts/PersonalFortress.cpp @@ -4,6 +4,7 @@ #include "DestroyableComponent.h" #include "ControllablePhysicsComponent.h" #include "EntityManager.h" +#include "eStateChangeType.h" void PersonalFortress::OnStartup(Entity* self) { auto* owner = self->GetOwner(); diff --git a/dScripts/EquipmentScripts/StunImmunity.cpp b/dScripts/EquipmentScripts/StunImmunity.cpp index f35fe261..0ec956f0 100644 --- a/dScripts/EquipmentScripts/StunImmunity.cpp +++ b/dScripts/EquipmentScripts/StunImmunity.cpp @@ -1,6 +1,7 @@ #include "StunImmunity.h" #include "DestroyableComponent.h" #include "ControllablePhysicsComponent.h" +#include "eStateChangeType.h" void StunImmunity::OnStartup(Entity* self) { auto* destroyableComponent = self->GetComponent<DestroyableComponent>(); diff --git a/dScripts/NPCAddRemoveItem.cpp b/dScripts/NPCAddRemoveItem.cpp index f1ef8c0d..13677072 100644 --- a/dScripts/NPCAddRemoveItem.cpp +++ b/dScripts/NPCAddRemoveItem.cpp @@ -12,7 +12,7 @@ void NPCAddRemoveItem::OnMissionDialogueOK(Entity* self, Entity* target, int mis for (const auto& itemSetting : missionSetting.second) { for (const auto& lot : itemSetting.items) { if (itemSetting.add && (missionState == eMissionState::AVAILABLE || missionState == eMissionState::COMPLETE_AVAILABLE)) { - inventory->AddItem(lot, 1, eLootSourceType::LOOT_SOURCE_NONE); + inventory->AddItem(lot, 1, eLootSourceType::NONE); } else if (itemSetting.remove && (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE)) { inventory->RemoveItem(lot, 1); } diff --git a/dScripts/NtFactionSpyServer.cpp b/dScripts/NtFactionSpyServer.cpp index dc62855a..a1161880 100644 --- a/dScripts/NtFactionSpyServer.cpp +++ b/dScripts/NtFactionSpyServer.cpp @@ -6,6 +6,8 @@ #include "MissionComponent.h" #include "eMissionState.h" #include "eReplicaComponentType.h" +#include "eCinematicEvent.h" +#include "ePlayerFlag.h" void NtFactionSpyServer::OnStartup(Entity* self) { SetVariables(self); @@ -77,14 +79,14 @@ void NtFactionSpyServer::OnCinematicUpdate(Entity* self, Entity* sender, eCinema // Make sure we're listening to the root we're interested in if (pathRoot == cinematicRoot) { - if (event == STARTED && pathIndex >= 0 && pathIndex < dialogueTable.size()) { + if (event == eCinematicEvent::STARTED && pathIndex >= 0 && pathIndex < dialogueTable.size()) { // If the cinematic started, show part of the conversation GameMessages::SendNotifyClientObject(self->GetObjectID(), m_SpyDialogueNotification, 0, 0, ParamObjectForConversationID(self, dialogueTable.at(pathIndex).conversationID), dialogueTable.at(pathIndex).token, sender->GetSystemAddress()); - } else if (event == ENDED && pathIndex >= dialogueTable.size() - 1) { + } else if (event == eCinematicEvent::ENDED && pathIndex >= dialogueTable.size() - 1) { auto spyData = self->GetVar<SpyData>(m_SpyDataVariable); auto* character = sender->GetCharacter(); if (character != nullptr) { diff --git a/dScripts/NtFactionSpyServer.h b/dScripts/NtFactionSpyServer.h index 67955dd4..4406859c 100644 --- a/dScripts/NtFactionSpyServer.h +++ b/dScripts/NtFactionSpyServer.h @@ -7,7 +7,7 @@ struct SpyDialogue { }; struct SpyData { - uint32_t flagID; + int32_t flagID; LOT itemID; uint32_t missionID; }; diff --git a/dScripts/SpawnPetBaseServer.cpp b/dScripts/SpawnPetBaseServer.cpp index d3c87288..75b46382 100644 --- a/dScripts/SpawnPetBaseServer.cpp +++ b/dScripts/SpawnPetBaseServer.cpp @@ -3,6 +3,7 @@ #include "EntityManager.h" #include "PetComponent.h" #include "EntityInfo.h" +#include "eTerminateType.h" void SpawnPetBaseServer::OnStartup(Entity* self) { SetVariables(self); @@ -43,7 +44,7 @@ void SpawnPetBaseServer::OnUse(Entity* self, Entity* user) { GameMessages::SendPlayCinematic(user->GetObjectID(), spawnCinematic, UNASSIGNED_SYSTEM_ADDRESS); } - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } bool SpawnPetBaseServer::CheckNumberOfPets(Entity* self, Entity* user) { diff --git a/dScripts/ai/ACT/ActMine.cpp b/dScripts/ai/ACT/ActMine.cpp index 637bd805..9651e13d 100644 --- a/dScripts/ai/ACT/ActMine.cpp +++ b/dScripts/ai/ACT/ActMine.cpp @@ -9,7 +9,7 @@ void ActMine::OnStartup(Entity* self) { } void ActMine::OnRebuildNotifyState(Entity* self, eRebuildState state) { - if (state == eRebuildState::REBUILD_COMPLETED) { + if (state == eRebuildState::COMPLETED) { auto* rebuild = self->GetComponent<RebuildComponent>(); if (rebuild) { auto* builder = rebuild->GetBuilder(); diff --git a/dScripts/ai/ACT/ActVehicleDeathTrigger.cpp b/dScripts/ai/ACT/ActVehicleDeathTrigger.cpp index 77a3b65a..76c0289e 100644 --- a/dScripts/ai/ACT/ActVehicleDeathTrigger.cpp +++ b/dScripts/ai/ACT/ActVehicleDeathTrigger.cpp @@ -40,7 +40,7 @@ void ActVehicleDeathTrigger::OnCollisionPhantom(Entity* self, Entity* target) { } - GameMessages::SendDie(vehicle, self->GetObjectID(), LWOOBJID_EMPTY, true, VIOLENT, u"", 0, 0, 0, true, false, 0); + GameMessages::SendDie(vehicle, self->GetObjectID(), LWOOBJID_EMPTY, true, eKillType::VIOLENT, u"", 0, 0, 0, true, false, 0); auto* zoneController = dZoneManager::Instance()->GetZoneControlObject(); diff --git a/dScripts/ai/ACT/FootRace/BaseFootRaceManager.cpp b/dScripts/ai/ACT/FootRace/BaseFootRaceManager.cpp index 699ee096..4d1ae5f5 100644 --- a/dScripts/ai/ACT/FootRace/BaseFootRaceManager.cpp +++ b/dScripts/ai/ACT/FootRace/BaseFootRaceManager.cpp @@ -37,7 +37,7 @@ void BaseFootRaceManager::OnFireEventServerSide(Entity* self, Entity* sender, st if (character != nullptr) { character->SetPlayerFlag(115, false); if (param2 != -1) // Certain footraces set a flag - character->SetPlayerFlag(param2, true); + character->SetPlayerFlag(static_cast<uint32_t>(param2), true); } StopActivity(self, player->GetObjectID(), 0, param1); diff --git a/dScripts/ai/AG/AgPicnicBlanket.cpp b/dScripts/ai/AG/AgPicnicBlanket.cpp index d2a54d57..bec5577c 100644 --- a/dScripts/ai/AG/AgPicnicBlanket.cpp +++ b/dScripts/ai/AG/AgPicnicBlanket.cpp @@ -2,9 +2,10 @@ #include "Loot.h" #include "GameMessages.h" #include "Entity.h" +#include "eTerminateType.h" void AgPicnicBlanket::OnUse(Entity* self, Entity* user) { - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); if (self->GetVar<bool>(u"active")) return; self->SetVar<bool>(u"active", true); diff --git a/dScripts/ai/AG/AgQbElevator.cpp b/dScripts/ai/AG/AgQbElevator.cpp index f1ac7bb5..e1d78a21 100644 --- a/dScripts/ai/AG/AgQbElevator.cpp +++ b/dScripts/ai/AG/AgQbElevator.cpp @@ -49,7 +49,7 @@ void AgQbElevator::OnTimerDone(Entity* self, std::string timerName) { } else if (timerName == "startKillTimer") { killTimerStartup(self); } else if (timerName == "KillTimer") { - self->Smash(self->GetObjectID(), VIOLENT); + self->Smash(self->GetObjectID(), eKillType::VIOLENT); } } diff --git a/dScripts/ai/AG/AgShipPlayerShockServer.cpp b/dScripts/ai/AG/AgShipPlayerShockServer.cpp index 2bed8152..9e6c90d4 100644 --- a/dScripts/ai/AG/AgShipPlayerShockServer.cpp +++ b/dScripts/ai/AG/AgShipPlayerShockServer.cpp @@ -1,5 +1,6 @@ #include "AgShipPlayerShockServer.h" #include "GameMessages.h" +#include "eTerminateType.h" void AgShipPlayerShockServer::OnUse(Entity* self, Entity* user) { GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); diff --git a/dScripts/ai/FV/ActNinjaTurret.cpp b/dScripts/ai/FV/ActNinjaTurret.cpp index 79e502b4..ea6e2278 100644 --- a/dScripts/ai/FV/ActNinjaTurret.cpp +++ b/dScripts/ai/FV/ActNinjaTurret.cpp @@ -1,9 +1,10 @@ #include "ActNinjaTurret.h" +#include "eRebuildState.h" void ActNinjaTurret::OnRebuildNotifyState(Entity* self, eRebuildState state) { - if (state == eRebuildState::REBUILD_COMPLETED) { + if (state == eRebuildState::COMPLETED) { self->SetVar(u"AmBuilt", true); - } else if (state == eRebuildState::REBUILD_RESETTING) { + } else if (state == eRebuildState::RESETTING) { self->SetVar(u"AmBuilt", false); } } diff --git a/dScripts/ai/FV/ActParadoxPipeFix.cpp b/dScripts/ai/FV/ActParadoxPipeFix.cpp index 517474a9..10a1e652 100644 --- a/dScripts/ai/FV/ActParadoxPipeFix.cpp +++ b/dScripts/ai/FV/ActParadoxPipeFix.cpp @@ -21,7 +21,7 @@ void ActParadoxPipeFix::OnRebuildComplete(Entity* self, Entity* target) { auto* rebuildComponent = object->GetComponent<RebuildComponent>(); - if (rebuildComponent->GetState() == REBUILD_COMPLETED) { + if (rebuildComponent->GetState() == eRebuildState::COMPLETED) { indexCount++; } } @@ -52,7 +52,7 @@ void ActParadoxPipeFix::OnRebuildComplete(Entity* self, Entity* target) { } void ActParadoxPipeFix::OnRebuildNotifyState(Entity* self, eRebuildState state) { - if (state == REBUILD_RESETTING) { + if (state == eRebuildState::RESETTING) { const auto refinery = EntityManager::Instance()->GetEntitiesInGroup("Paradox"); if (!refinery.empty()) { diff --git a/dScripts/ai/FV/FvBrickPuzzleServer.cpp b/dScripts/ai/FV/FvBrickPuzzleServer.cpp index cea6146b..887b9a4d 100644 --- a/dScripts/ai/FV/FvBrickPuzzleServer.cpp +++ b/dScripts/ai/FV/FvBrickPuzzleServer.cpp @@ -61,8 +61,8 @@ void FvBrickPuzzleServer::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "reset") { auto* rebuildComponent = self->GetComponent<RebuildComponent>(); - if (rebuildComponent != nullptr && rebuildComponent->GetState() == REBUILD_OPEN) { - self->Smash(self->GetObjectID(), SILENT); + if (rebuildComponent != nullptr && rebuildComponent->GetState() == eRebuildState::OPEN) { + self->Smash(self->GetObjectID(), eKillType::SILENT); } } } diff --git a/dScripts/ai/FV/FvConsoleLeftQuickbuild.cpp b/dScripts/ai/FV/FvConsoleLeftQuickbuild.cpp index b998b9ec..3f495ed7 100644 --- a/dScripts/ai/FV/FvConsoleLeftQuickbuild.cpp +++ b/dScripts/ai/FV/FvConsoleLeftQuickbuild.cpp @@ -1,6 +1,8 @@ #include "FvConsoleLeftQuickbuild.h" #include "EntityManager.h" #include "GameMessages.h" +#include "eTerminateType.h" +#include "eRebuildState.h" void FvConsoleLeftQuickbuild::OnStartup(Entity* self) { self->SetVar(u"IAmBuilt", false); @@ -8,7 +10,7 @@ void FvConsoleLeftQuickbuild::OnStartup(Entity* self) { } void FvConsoleLeftQuickbuild::OnRebuildNotifyState(Entity* self, eRebuildState state) { - if (state == REBUILD_COMPLETED) { + if (state == eRebuildState::COMPLETED) { self->SetVar(u"IAmBuilt", true); const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); @@ -16,7 +18,7 @@ void FvConsoleLeftQuickbuild::OnRebuildNotifyState(Entity* self, eRebuildState s if (!objects.empty()) { objects[0]->NotifyObject(self, "ConsoleLeftUp"); } - } else if (state == REBUILD_RESETTING) { + } else if (state == eRebuildState::RESETTING) { self->SetVar(u"IAmBuilt", false); self->SetVar(u"AmActive", false); @@ -43,5 +45,5 @@ void FvConsoleLeftQuickbuild::OnUse(Entity* self, Entity* user) { } } - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/ai/FV/FvConsoleRightQuickbuild.cpp b/dScripts/ai/FV/FvConsoleRightQuickbuild.cpp index ea047cd8..e03e4135 100644 --- a/dScripts/ai/FV/FvConsoleRightQuickbuild.cpp +++ b/dScripts/ai/FV/FvConsoleRightQuickbuild.cpp @@ -1,6 +1,8 @@ #include "FvConsoleRightQuickbuild.h" #include "EntityManager.h" #include "GameMessages.h" +#include "eTerminateType.h" +#include "eRebuildState.h" void FvConsoleRightQuickbuild::OnStartup(Entity* self) { self->SetVar(u"IAmBuilt", false); @@ -8,7 +10,7 @@ void FvConsoleRightQuickbuild::OnStartup(Entity* self) { } void FvConsoleRightQuickbuild::OnRebuildNotifyState(Entity* self, eRebuildState state) { - if (state == REBUILD_COMPLETED) { + if (state == eRebuildState::COMPLETED) { self->SetVar(u"IAmBuilt", true); const auto objects = EntityManager::Instance()->GetEntitiesInGroup("Facility"); @@ -16,7 +18,7 @@ void FvConsoleRightQuickbuild::OnRebuildNotifyState(Entity* self, eRebuildState if (!objects.empty()) { objects[0]->NotifyObject(self, "ConsoleRightUp"); } - } else if (state == REBUILD_RESETTING) { + } else if (state == eRebuildState::RESETTING) { self->SetVar(u"IAmBuilt", false); self->SetVar(u"AmActive", false); @@ -43,5 +45,5 @@ void FvConsoleRightQuickbuild::OnUse(Entity* self, Entity* user) { } } - GameMessages::SendTerminateInteraction(user->GetObjectID(), FROM_INTERACTION, self->GetObjectID()); + GameMessages::SendTerminateInteraction(user->GetObjectID(), eTerminateType::FROM_INTERACTION, self->GetObjectID()); } diff --git a/dScripts/ai/FV/FvDragonSmashingGolemQb.cpp b/dScripts/ai/FV/FvDragonSmashingGolemQb.cpp index a9d38aa5..9cf7fa18 100644 --- a/dScripts/ai/FV/FvDragonSmashingGolemQb.cpp +++ b/dScripts/ai/FV/FvDragonSmashingGolemQb.cpp @@ -1,6 +1,7 @@ #include "FvDragonSmashingGolemQb.h" #include "GameMessages.h" #include "EntityManager.h" +#include "eRebuildState.h" void FvDragonSmashingGolemQb::OnStartup(Entity* self) { self->AddTimer("GolemBreakTimer", 10.5f); @@ -13,7 +14,7 @@ void FvDragonSmashingGolemQb::OnTimerDone(Entity* self, std::string timerName) { } void FvDragonSmashingGolemQb::OnRebuildNotifyState(Entity* self, eRebuildState state) { - if (state == eRebuildState::REBUILD_COMPLETED) { + if (state == eRebuildState::COMPLETED) { GameMessages::SendPlayAnimation(self, u"dragonsmash"); const auto dragonId = self->GetVar<LWOOBJID>(u"Dragon"); diff --git a/dScripts/ai/FV/FvFacilityBrick.cpp b/dScripts/ai/FV/FvFacilityBrick.cpp index 1ae910e4..6ff12750 100644 --- a/dScripts/ai/FV/FvFacilityBrick.cpp +++ b/dScripts/ai/FV/FvFacilityBrick.cpp @@ -56,7 +56,7 @@ void FvFacilityBrick::OnNotifyObject(Entity* self, Entity* sender, const std::st object = EntityManager::Instance()->GetEntitiesInGroup("Canister")[0]; if (object != nullptr) { - object->Smash(self->GetObjectID(), SILENT); + object->Smash(self->GetObjectID(), eKillType::SILENT); } canisterSpawner->Reset(); diff --git a/dScripts/ai/FV/FvPandaServer.cpp b/dScripts/ai/FV/FvPandaServer.cpp index bea93a6c..f29f7f2e 100644 --- a/dScripts/ai/FV/FvPandaServer.cpp +++ b/dScripts/ai/FV/FvPandaServer.cpp @@ -1,6 +1,7 @@ #include "FvPandaServer.h" #include "PetComponent.h" #include "Character.h" +#include "ePetTamingNotifyType.h" void FvPandaServer::OnStartup(Entity* self) { const auto* petComponent = self->GetComponent<PetComponent>(); @@ -10,12 +11,12 @@ void FvPandaServer::OnStartup(Entity* self) { } } -void FvPandaServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { - if (type == NOTIFY_TYPE_BEGIN) { +void FvPandaServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, ePetTamingNotifyType type) { + if (type == ePetTamingNotifyType::BEGIN) { self->CancelAllTimers(); - } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { + } else if (type == ePetTamingNotifyType::QUIT || type == ePetTamingNotifyType::FAILED) { self->Smash(); - } else if (type == NOTIFY_TYPE_SUCCESS) { + } else if (type == ePetTamingNotifyType::SUCCESS) { // TODO: Remove from groups auto* character = tamer->GetCharacter(); @@ -29,7 +30,7 @@ void FvPandaServer::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "killSelf") { const auto* petComponent = self->GetComponent<PetComponent>(); if (petComponent != nullptr && petComponent->GetOwner() == nullptr) { - self->Smash(self->GetObjectID(), SILENT); + self->Smash(self->GetObjectID(), eKillType::SILENT); } } } diff --git a/dScripts/ai/FV/FvPandaServer.h b/dScripts/ai/FV/FvPandaServer.h index 4948fdf4..5db060a0 100644 --- a/dScripts/ai/FV/FvPandaServer.h +++ b/dScripts/ai/FV/FvPandaServer.h @@ -3,6 +3,6 @@ class FvPandaServer : public CppScripts::Script { void OnStartup(Entity* self) override; - void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, ePetTamingNotifyType type) override; void OnTimerDone(Entity* self, std::string timerName) override; }; diff --git a/dScripts/ai/GENERAL/InstanceExitTransferPlayerToLastNonInstance.cpp b/dScripts/ai/GENERAL/InstanceExitTransferPlayerToLastNonInstance.cpp index 4e42e7fb..de1c62e0 100644 --- a/dScripts/ai/GENERAL/InstanceExitTransferPlayerToLastNonInstance.cpp +++ b/dScripts/ai/GENERAL/InstanceExitTransferPlayerToLastNonInstance.cpp @@ -3,6 +3,7 @@ #include "Player.h" #include "Character.h" #include "dServer.h" +#include "eTerminateType.h" void InstanceExitTransferPlayerToLastNonInstance::OnUse(Entity* self, Entity* user) { auto transferText = self->GetVar<std::u16string>(u"transferText"); diff --git a/dScripts/ai/GENERAL/LegoDieRoll.cpp b/dScripts/ai/GENERAL/LegoDieRoll.cpp index 89819271..18082065 100644 --- a/dScripts/ai/GENERAL/LegoDieRoll.cpp +++ b/dScripts/ai/GENERAL/LegoDieRoll.cpp @@ -11,7 +11,7 @@ void LegoDieRoll::OnStartup(Entity* self) { void LegoDieRoll::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "DoneRolling") { - self->Smash(self->GetObjectID(), SILENT); + self->Smash(self->GetObjectID(), eKillType::SILENT); } else if (timerName == "ThrowDice") { int dieRoll = GeneralUtils::GenerateRandomNumber<int>(1, 6); diff --git a/dScripts/ai/GF/GfJailWalls.cpp b/dScripts/ai/GF/GfJailWalls.cpp index 56710832..1835faa2 100644 --- a/dScripts/ai/GF/GfJailWalls.cpp +++ b/dScripts/ai/GF/GfJailWalls.cpp @@ -1,6 +1,7 @@ #include "GfJailWalls.h" #include "dZoneManager.h" #include "GeneralUtils.h" +#include "eRebuildState.h" void GfJailWalls::OnRebuildComplete(Entity* self, Entity* target) { const auto wall = GeneralUtils::UTF16ToWTF8(self->GetVar<std::u16string>(u"Wall")); @@ -15,7 +16,7 @@ void GfJailWalls::OnRebuildComplete(Entity* self, Entity* target) { } void GfJailWalls::OnRebuildNotifyState(Entity* self, eRebuildState state) { - if (state != eRebuildState::REBUILD_RESETTING) return; + if (state != eRebuildState::RESETTING) return; const auto wall = GeneralUtils::UTF16ToWTF8(self->GetVar<std::u16string>(u"Wall")); diff --git a/dScripts/ai/GF/PetDigBuild.cpp b/dScripts/ai/GF/PetDigBuild.cpp index 2c3da9fc..504a1199 100644 --- a/dScripts/ai/GF/PetDigBuild.cpp +++ b/dScripts/ai/GF/PetDigBuild.cpp @@ -46,6 +46,6 @@ void PetDigBuild::OnDie(Entity* self, Entity* killer) { // If the quick build expired and the treasure was not collected, hide the treasure if (!treasure->GetIsDead()) { - treasure->Smash(self->GetObjectID(), SILENT); + treasure->Smash(self->GetObjectID(), eKillType::SILENT); } } diff --git a/dScripts/ai/GF/PirateRep.cpp b/dScripts/ai/GF/PirateRep.cpp index ccfa7af6..33d6ab63 100644 --- a/dScripts/ai/GF/PirateRep.cpp +++ b/dScripts/ai/GF/PirateRep.cpp @@ -2,12 +2,13 @@ #include "Character.h" #include "eMissionState.h" #include "Entity.h" +#include "ePlayerFlag.h" void PirateRep::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { if (missionID == m_PirateRepMissionID && missionState >= eMissionState::READY_TO_COMPLETE) { auto* character = target->GetCharacter(); if (character) { - character->SetPlayerFlag(ePlayerFlags::GF_PIRATE_REP, true); + character->SetPlayerFlag(ePlayerFlag::GF_PIRATE_REP, true); } } } diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp index 703c6bbd..bdd7a506 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp @@ -15,6 +15,7 @@ #include "InventoryComponent.h" #include "eMissionTaskType.h" #include "eReplicaComponentType.h" +#include "eGameActivity.h" void SGCannon::OnStartup(Entity* self) { Game::logger->Log("SGCannon", "OnStartup"); @@ -102,7 +103,7 @@ void SGCannon::OnActivityStateChangeRequest(Entity* self, LWOOBJID senderID, int if (characterComponent != nullptr) { characterComponent->SetIsRacing(true); - characterComponent->SetCurrentActivity(2); + characterComponent->SetCurrentActivity(eGameActivity::SHOOTING_GALLERY); auto possessor = player->GetComponent<PossessorComponent>(); if (possessor) { possessor->SetPossessable(self->GetObjectID()); @@ -570,7 +571,7 @@ void SGCannon::StopGame(Entity* self, bool cancel) { auto* inventory = player->GetComponent<InventoryComponent>(); if (inventory != nullptr) { for (const auto rewardLot : self->GetVar<std::vector<LOT>>(RewardsVariable)) { - inventory->AddItem(rewardLot, 1, eLootSourceType::LOOT_SOURCE_ACTIVITY, eInventoryType::MODELS); + inventory->AddItem(rewardLot, 1, eLootSourceType::ACTIVITY, eInventoryType::MODELS); } } diff --git a/dScripts/ai/NS/NsConcertInstrument.cpp b/dScripts/ai/NS/NsConcertInstrument.cpp index c7478a05..7db1ca16 100644 --- a/dScripts/ai/NS/NsConcertInstrument.cpp +++ b/dScripts/ai/NS/NsConcertInstrument.cpp @@ -20,7 +20,7 @@ void NsConcertInstrument::OnStartup(Entity* self) { } void NsConcertInstrument::OnRebuildNotifyState(Entity* self, eRebuildState state) { - if (state == REBUILD_RESETTING || state == REBUILD_OPEN) { + if (state == eRebuildState::RESETTING || state == eRebuildState::OPEN) { self->SetVar<LWOOBJID>(u"activePlayer", LWOOBJID_EMPTY); } } @@ -96,7 +96,7 @@ void NsConcertInstrument::OnTimerDone(Entity* self, std::string name) { if (rebuildComponent != nullptr) rebuildComponent->ResetRebuild(false); - self->Smash(self->GetObjectID(), VIOLENT); + self->Smash(self->GetObjectID(), eKillType::VIOLENT); self->SetVar<LWOOBJID>(u"activePlayer", LWOOBJID_EMPTY); } else if (activePlayer != nullptr && name == "achievement") { auto* missionComponent = activePlayer->GetComponent<MissionComponent>(); @@ -199,7 +199,7 @@ void NsConcertInstrument::EquipInstruments(Entity* self, Entity* player) { // Equip the left hand instrument const auto leftInstrumentLot = instrumentLotLeft.find(GetInstrumentLot(self))->second; if (leftInstrumentLot != LOT_NULL) { - inventory->AddItem(leftInstrumentLot, 1, eLootSourceType::LOOT_SOURCE_NONE, TEMP_ITEMS, {}, LWOOBJID_EMPTY, false); + inventory->AddItem(leftInstrumentLot, 1, eLootSourceType::NONE, TEMP_ITEMS, {}, LWOOBJID_EMPTY, false); auto* leftInstrument = inventory->FindItemByLot(leftInstrumentLot, TEMP_ITEMS); leftInstrument->Equip(); } @@ -207,7 +207,7 @@ void NsConcertInstrument::EquipInstruments(Entity* self, Entity* player) { // Equip the right hand instrument const auto rightInstrumentLot = instrumentLotRight.find(GetInstrumentLot(self))->second; if (rightInstrumentLot != LOT_NULL) { - inventory->AddItem(rightInstrumentLot, 1, eLootSourceType::LOOT_SOURCE_NONE, TEMP_ITEMS, {}, LWOOBJID_EMPTY, false); + inventory->AddItem(rightInstrumentLot, 1, eLootSourceType::NONE, TEMP_ITEMS, {}, LWOOBJID_EMPTY, false); auto* rightInstrument = inventory->FindItemByLot(rightInstrumentLot, TEMP_ITEMS); rightInstrument->Equip(); } diff --git a/dScripts/ai/NS/NsConcertQuickBuild.cpp b/dScripts/ai/NS/NsConcertQuickBuild.cpp index fcec4dc7..4589ee6a 100644 --- a/dScripts/ai/NS/NsConcertQuickBuild.cpp +++ b/dScripts/ai/NS/NsConcertQuickBuild.cpp @@ -58,7 +58,7 @@ void NsConcertQuickBuild::OnStartup(Entity* self) { // Destroys the quick build after a while if it wasn't built self->AddCallbackTimer(resetActivatorTime, [self]() { self->SetNetworkVar<float>(u"startEffect", -1.0f); - self->Smash(self->GetObjectID(), SILENT); + self->Smash(self->GetObjectID(), eKillType::SILENT); }); } diff --git a/dScripts/ai/NS/NsGetFactionMissionServer.cpp b/dScripts/ai/NS/NsGetFactionMissionServer.cpp index cfecb249..185bd344 100644 --- a/dScripts/ai/NS/NsGetFactionMissionServer.cpp +++ b/dScripts/ai/NS/NsGetFactionMissionServer.cpp @@ -3,6 +3,7 @@ #include "MissionComponent.h" #include "Character.h" #include "eReplicaComponentType.h" +#include "ePlayerFlag.h" void NsGetFactionMissionServer::OnRespondToMission(Entity* self, int missionID, Entity* player, int reward) { if (missionID != 474) return; @@ -10,7 +11,7 @@ void NsGetFactionMissionServer::OnRespondToMission(Entity* self, int missionID, if (reward != LOT_NULL) { std::vector<int> factionMissions; int celebrationID = -1; - int flagID = -1; + int32_t flagID = -1; if (reward == 6980) { // Venture League @@ -41,7 +42,7 @@ void NsGetFactionMissionServer::OnRespondToMission(Entity* self, int missionID, } if (flagID != -1) { - player->GetCharacter()->SetPlayerFlag(ePlayerFlags::JOINED_A_FACTION, true); + player->GetCharacter()->SetPlayerFlag(ePlayerFlag::JOINED_A_FACTION, true); player->GetCharacter()->SetPlayerFlag(flagID, true); } diff --git a/dScripts/ai/SPEC/SpecialCoinSpawner.cpp b/dScripts/ai/SPEC/SpecialCoinSpawner.cpp index aed9e817..ff494845 100644 --- a/dScripts/ai/SPEC/SpecialCoinSpawner.cpp +++ b/dScripts/ai/SPEC/SpecialCoinSpawner.cpp @@ -11,6 +11,6 @@ void SpecialCoinSpawner::OnProximityUpdate(Entity* self, Entity* entering, const auto character = entering->GetCharacter(); if (!character) return; GameMessages::SendPlayFXEffect(self, -1, u"pickup", "", LWOOBJID_EMPTY, 1, 1, true); - character->SetCoins(character->GetCoins() + this->m_CurrencyDenomination, eLootSourceType::LOOT_SOURCE_CURRENCY); + character->SetCoins(character->GetCoins() + this->m_CurrencyDenomination, eLootSourceType::CURRENCY); self->Smash(entering->GetObjectID(), eKillType::SILENT); } diff --git a/dScripts/client/ai/PR/CrabServer.cpp b/dScripts/client/ai/PR/CrabServer.cpp index 890b8ed9..f30142ba 100644 --- a/dScripts/client/ai/PR/CrabServer.cpp +++ b/dScripts/client/ai/PR/CrabServer.cpp @@ -1,5 +1,6 @@ #include "CrabServer.h" #include "PetComponent.h" +#include "ePetTamingNotifyType.h" void CrabServer::OnStartup(Entity* self) { auto* petComponent = self->GetComponent<PetComponent>(); @@ -23,16 +24,16 @@ void CrabServer::OnTimerDone(Entity* self, std::string timerName) { if (petComponent == nullptr || petComponent->GetOwner() != nullptr) return; - self->Smash(self->GetObjectID(), SILENT); + self->Smash(self->GetObjectID(), eKillType::SILENT); } } -void CrabServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) { - if (type == NOTIFY_TYPE_BEGIN) { +void CrabServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, ePetTamingNotifyType type) { + if (type == ePetTamingNotifyType::BEGIN) { self->CancelTimer("killself"); - } else if (type == NOTIFY_TYPE_QUIT || type == NOTIFY_TYPE_FAILED) { - self->Smash(self->GetObjectID(), SILENT); - } else if (type == NOTIFY_TYPE_SUCCESS) { + } else if (type == ePetTamingNotifyType::QUIT || type == ePetTamingNotifyType::FAILED) { + self->Smash(self->GetObjectID(), eKillType::SILENT); + } else if (type == ePetTamingNotifyType::SUCCESS) { auto* petComponent = self->GetComponent<PetComponent>(); if (petComponent == nullptr) return; diff --git a/dScripts/client/ai/PR/CrabServer.h b/dScripts/client/ai/PR/CrabServer.h index 28533cb5..8c689dbd 100644 --- a/dScripts/client/ai/PR/CrabServer.h +++ b/dScripts/client/ai/PR/CrabServer.h @@ -6,5 +6,5 @@ class CrabServer : public CppScripts::Script public: void OnStartup(Entity* self) override; void OnTimerDone(Entity* self, std::string timerName) override; - void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eNotifyType type) override; + void OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, ePetTamingNotifyType type) override; }; diff --git a/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp index 7399456d..db9c033a 100644 --- a/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp +++ b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp @@ -5,6 +5,7 @@ #include "DestroyableComponent.h" #include "Entity.h" #include "eReplicaComponentType.h" +#include "eStateChangeType.h" class DestroyableTest : public GameDependenciesTest { protected: From c17b5fa5862dd0ae29749e690bf7edaba23b19ab Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Wed, 3 May 2023 01:31:50 -0500 Subject: [PATCH 309/322] prevent ressurecting with more than max stats (#1064) for health and imagination --- dGame/dGameMessages/GameMessages.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 4d5a378c..3475c471 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -937,8 +937,13 @@ void GameMessages::SendResurrect(Entity* entity) { if (destroyableComponent != nullptr && entity->GetLOT() == 1) { auto* levelComponent = entity->GetComponent<LevelProgressionComponent>(); if (levelComponent) { - destroyableComponent->SetHealth(levelComponent->GetLevel() >= 45 ? 8 : 4); - destroyableComponent->SetImagination(levelComponent->GetLevel() >= 45 ? 20 : 6); + int32_t healthToRestore = levelComponent->GetLevel() >= 45 ? 8 : 4; + if (healthToRestore > destroyableComponent->GetMaxHealth()) healthToRestore = destroyableComponent->GetMaxHealth(); + destroyableComponent->SetHealth(healthToRestore); + + int32_t imaginationToRestore = levelComponent->GetLevel() >= 45 ? 20 : 6; + if (imaginationToRestore > destroyableComponent->GetMaxImagination()) imaginationToRestore = destroyableComponent->GetMaxImagination(); + destroyableComponent->SetImagination(imaginationToRestore); } } }); From e297aacc68d8b1a03bf69911debad052fa658d5b Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Wed, 3 May 2023 16:38:32 -0500 Subject: [PATCH 310/322] Breakout message identifiers (#1065) and make them scope enums --- dAuthServer/AuthServer.cpp | 13 +- dChatServer/ChatPacketHandler.cpp | 66 +- dChatServer/ChatServer.cpp | 62 +- dChatServer/PlayerContainer.cpp | 7 +- dCommon/dEnums/dCommonVars.h | 4 +- dCommon/dEnums/dMessageIdentifiers.h | 564 ------------------ dCommon/dEnums/eAuthMessageType.h | 15 + dCommon/dEnums/eChatInternalMessageType.h | 31 + dCommon/dEnums/eChatMessageType.h | 78 +++ dCommon/dEnums/eClientMessageType.h | 76 +++ dCommon/dEnums/eConnectionType.h | 14 + dCommon/dEnums/eGameMessageType.h | 303 ++++++++++ dCommon/dEnums/eMasterMessageType.h | 36 ++ dCommon/dEnums/eServerMessageType.h | 12 + dCommon/dEnums/eWorldMessageType.h | 42 ++ dGame/UserManager.cpp | 5 +- dGame/dBehaviors/BehaviorContext.cpp | 4 +- dGame/dComponents/ModuleAssemblyComponent.h | 2 +- .../RocketLaunchpadControlComponent.cpp | 5 +- .../dComponents/ScriptedActivityComponent.cpp | 5 +- dGame/dComponents/SkillComponent.cpp | 8 +- .../dGameMessages/DoClientProjectileImpact.h | 5 +- dGame/dGameMessages/EchoStartSkill.h | 6 +- dGame/dGameMessages/EchoSyncSkill.h | 6 +- dGame/dGameMessages/GameMessageHandler.cpp | 219 +++---- dGame/dGameMessages/GameMessageHandler.h | 5 +- dGame/dGameMessages/GameMessages.cpp | 325 +++++----- .../RequestServerProjectileImpact.h | 6 +- dGame/dGameMessages/StartSkill.h | 6 +- dGame/dGameMessages/SyncSkill.h | 5 +- dGame/dUtilities/Mail.cpp | 14 +- dGame/dUtilities/SlashCommandHandler.cpp | 10 +- dMasterServer/InstanceManager.cpp | 7 +- dMasterServer/MasterServer.cpp | 41 +- dNet/AuthPackets.cpp | 10 +- dNet/ChatPackets.cpp | 9 +- dNet/ClientPackets.cpp | 1 - dNet/MasterPackets.cpp | 19 +- dNet/PacketUtils.cpp | 8 - dNet/PacketUtils.h | 11 +- dNet/WorldPackets.cpp | 22 +- dNet/dServer.cpp | 14 +- dWorldServer/WorldServer.cpp | 96 +-- 43 files changed, 1131 insertions(+), 1066 deletions(-) delete mode 100644 dCommon/dEnums/dMessageIdentifiers.h create mode 100644 dCommon/dEnums/eAuthMessageType.h create mode 100644 dCommon/dEnums/eChatInternalMessageType.h create mode 100644 dCommon/dEnums/eChatMessageType.h create mode 100644 dCommon/dEnums/eClientMessageType.h create mode 100644 dCommon/dEnums/eConnectionType.h create mode 100644 dCommon/dEnums/eGameMessageType.h create mode 100644 dCommon/dEnums/eMasterMessageType.h create mode 100644 dCommon/dEnums/eServerMessageType.h create mode 100644 dCommon/dEnums/eWorldMessageType.h diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index f5090495..ddec32db 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -15,10 +15,13 @@ //RakNet includes: #include "RakNetDefines.h" +#include <MessageIdentifiers.h> //Auth includes: #include "AuthPackets.h" -#include "dMessageIdentifiers.h" +#include "eConnectionType.h" +#include "eServerMessageType.h" +#include "eAuthMessageType.h" #include "Game.h" namespace Game { @@ -169,12 +172,12 @@ dLogger* SetupLogger() { void HandlePacket(Packet* packet) { if (packet->data[0] == ID_USER_PACKET_ENUM) { - if (packet->data[1] == SERVER) { - if (packet->data[3] == MSG_SERVER_VERSION_CONFIRM) { + if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::SERVER) { + if (static_cast<eServerMessageType>(packet->data[3]) == eServerMessageType::VERSION_CONFIRM) { AuthPackets::HandleHandshake(Game::server, packet); } - } else if (packet->data[1] == AUTH) { - if (packet->data[3] == MSG_AUTH_LOGIN_REQUEST) { + } else if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::AUTH) { + if (static_cast<eAuthMessageType>(packet->data[3]) == eAuthMessageType::LOGIN_REQUEST) { AuthPackets::HandleLoginRequest(Game::server, packet); } } diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index a0d508cb..9b5ca761 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -3,7 +3,6 @@ #include "Database.h" #include <vector> #include "PacketUtils.h" -#include "dMessageIdentifiers.h" #include "Game.h" #include "dServer.h" #include "GeneralUtils.h" @@ -13,6 +12,11 @@ #include "RakString.h" #include "dConfig.h" #include "eObjectBits.h" +#include "eConnectionType.h" +#include "eChatMessageType.h" +#include "eChatInternalMessageType.h" +#include "eClientMessageType.h" +#include "eGameMessageType.h" extern PlayerContainer playerContainer; @@ -72,11 +76,11 @@ void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { //Now, we need to send the friendlist to the server they came from: CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(playerID); //portion that will get routed: - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_GET_FRIENDS_LIST_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::GET_FRIENDS_LIST_RESPONSE); bitStream.Write<uint8_t>(0); bitStream.Write<uint16_t>(1); //Length of packet -- just writing one as it doesn't matter, client skips it. bitStream.Write((uint16_t)friends.size()); @@ -413,10 +417,10 @@ void ChatPacketHandler::HandleChatMessage(Packet* packet) { const auto otherName = std::string(otherMember->playerName.c_str()); CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(otherMember->playerID); - PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_PRIVATE_CHAT_MESSAGE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT, eChatMessageType::PRIVATE_CHAT_MESSAGE); bitStream.Write(otherMember->playerID); bitStream.Write<uint8_t>(8); bitStream.Write<unsigned int>(69); @@ -452,10 +456,10 @@ void ChatPacketHandler::HandlePrivateChatMessage(Packet* packet) { //To the sender: { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(goonA->playerID); - PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_PRIVATE_CHAT_MESSAGE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT, eChatMessageType::PRIVATE_CHAT_MESSAGE); bitStream.Write(goonA->playerID); bitStream.Write<uint8_t>(7); bitStream.Write<unsigned int>(69); @@ -475,10 +479,10 @@ void ChatPacketHandler::HandlePrivateChatMessage(Packet* packet) { //To the receiver: { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(goonB->playerID); - PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_PRIVATE_CHAT_MESSAGE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT, eChatMessageType::PRIVATE_CHAT_MESSAGE); bitStream.Write(goonA->playerID); bitStream.Write<uint8_t>(7); bitStream.Write<unsigned int>(69); @@ -717,11 +721,11 @@ void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) { void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); //portion that will get routed: - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_TEAM_INVITE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::TEAM_INVITE); PacketUtils::WritePacketWString(sender->playerName.c_str(), 33, &bitStream); bitStream.Write(sender->playerID); @@ -732,14 +736,14 @@ void ChatPacketHandler::SendTeamInvite(PlayerData* receiver, PlayerData* sender) void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeaderIsFreeTrial, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, uint8_t ucResponseCode, std::u16string wsLeaderName) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); //portion that will get routed: CMSGHEADER; bitStream.Write(receiver->playerID); - bitStream.Write(GAME_MSG::GAME_MSG_TEAM_INVITE_CONFIRM); + bitStream.Write(eGameMessageType::TEAM_INVITE_CONFIRM); bitStream.Write(bLeaderIsFreeTrial); bitStream.Write(i64LeaderID); @@ -759,14 +763,14 @@ void ChatPacketHandler::SendTeamInviteConfirm(PlayerData* receiver, bool bLeader void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderID, LWOZONEID i64LeaderZoneID, uint8_t ucLootFlag, uint8_t ucNumOfOtherPlayers, std::u16string wsLeaderName) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); //portion that will get routed: CMSGHEADER; bitStream.Write(receiver->playerID); - bitStream.Write(GAME_MSG::GAME_MSG_TEAM_GET_STATUS_RESPONSE); + bitStream.Write(eGameMessageType::TEAM_GET_STATUS_RESPONSE); bitStream.Write(i64LeaderID); bitStream.Write(i64LeaderZoneID); @@ -784,14 +788,14 @@ void ChatPacketHandler::SendTeamStatus(PlayerData* receiver, LWOOBJID i64LeaderI void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64PlayerID) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); //portion that will get routed: CMSGHEADER; bitStream.Write(receiver->playerID); - bitStream.Write(GAME_MSG::GAME_MSG_TEAM_SET_LEADER); + bitStream.Write(eGameMessageType::TEAM_SET_LEADER); bitStream.Write(i64PlayerID); @@ -801,14 +805,14 @@ void ChatPacketHandler::SendTeamSetLeader(PlayerData* receiver, LWOOBJID i64Play void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTrial, bool bLocal, bool bNoLootOnDeath, LWOOBJID i64PlayerID, std::u16string wsPlayerName, LWOZONEID zoneID) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); //portion that will get routed: CMSGHEADER; bitStream.Write(receiver->playerID); - bitStream.Write(GAME_MSG::GAME_MSG_TEAM_ADD_PLAYER); + bitStream.Write(eGameMessageType::TEAM_ADD_PLAYER); bitStream.Write(bIsFreeTrial); bitStream.Write(bLocal); @@ -830,14 +834,14 @@ void ChatPacketHandler::SendTeamAddPlayer(PlayerData* receiver, bool bIsFreeTria void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband, bool bIsKicked, bool bIsLeaving, bool bLocal, LWOOBJID i64LeaderID, LWOOBJID i64PlayerID, std::u16string wsPlayerName) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); //portion that will get routed: CMSGHEADER; bitStream.Write(receiver->playerID); - bitStream.Write(GAME_MSG::GAME_MSG_TEAM_REMOVE_PLAYER); + bitStream.Write(eGameMessageType::TEAM_REMOVE_PLAYER); bitStream.Write(bDisband); bitStream.Write(bIsKicked); @@ -856,14 +860,14 @@ void ChatPacketHandler::SendTeamRemovePlayer(PlayerData* receiver, bool bDisband void ChatPacketHandler::SendTeamSetOffWorldFlag(PlayerData* receiver, LWOOBJID i64PlayerID, LWOZONEID zoneID) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); //portion that will get routed: CMSGHEADER; bitStream.Write(receiver->playerID); - bitStream.Write(GAME_MSG::GAME_MSG_TEAM_SET_OFF_WORLD_FLAG); + bitStream.Write(eGameMessageType::TEAM_SET_OFF_WORLD_FLAG); bitStream.Write(i64PlayerID); if (receiver->zoneID.GetCloneID() == zoneID.GetCloneID()) { @@ -890,11 +894,11 @@ void ChatPacketHandler::SendFriendUpdate(PlayerData* friendData, PlayerData* pla [bool] - is FTP*/ CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(friendData->playerID); //portion that will get routed: - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_UPDATE_FRIEND_NOTIFY); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::UPDATE_FRIEND_NOTIFY); bitStream.Write<uint8_t>(notifyType); std::string playerName = playerData->playerName.c_str(); @@ -929,11 +933,11 @@ void ChatPacketHandler::SendFriendRequest(PlayerData* receiver, PlayerData* send } CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); //portion that will get routed: - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_ADD_FRIEND_REQUEST); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::ADD_FRIEND_REQUEST); PacketUtils::WritePacketWString(sender->playerName.c_str(), 33, &bitStream); bitStream.Write<uint8_t>(0); // This is a BFF flag however this is unused in live and does not have an implementation client side. @@ -945,11 +949,11 @@ void ChatPacketHandler::SendFriendResponse(PlayerData* receiver, PlayerData* sen if (!receiver || !sender) return; CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); // Portion that will get routed: - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_ADD_FRIEND_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::ADD_FRIEND_RESPONSE); bitStream.Write(responseCode); // For all requests besides accepted, write a flag that says whether or not we are already best friends with the receiver. bitStream.Write<uint8_t>(responseCode != eAddFriendResponseType::ACCEPTED ? isBestFriendsAlready : sender->sysAddr != UNASSIGNED_SYSTEM_ADDRESS); @@ -970,11 +974,11 @@ void ChatPacketHandler::SendRemoveFriend(PlayerData* receiver, std::string& pers if (!receiver) return; CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ROUTE_TO_PLAYER); bitStream.Write(receiver->playerID); //portion that will get routed: - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_REMOVE_FRIEND_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::REMOVE_FRIEND_RESPONSE); bitStream.Write<uint8_t>(isSuccessful); //isOnline PacketUtils::WritePacketWString(personToRemove, 33, &bitStream); diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index a75c4d51..3e3ddfd3 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -9,19 +9,23 @@ #include "dLogger.h" #include "Database.h" #include "dConfig.h" -#include "dMessageIdentifiers.h" #include "dChatFilter.h" #include "Diagnostics.h" #include "AssetManager.h" #include "BinaryPathFinder.h" - +#include "eConnectionType.h" #include "PlayerContainer.h" #include "ChatPacketHandler.h" +#include "eChatMessageType.h" +#include "eChatInternalMessageType.h" +#include "eWorldMessageType.h" #include "Game.h" //RakNet includes: #include "RakNetDefines.h" +#include <MessageIdentifiers.h> + namespace Game { dLogger* logger = nullptr; dServer* server = nullptr; @@ -68,7 +72,7 @@ int main(int argc, char** argv) { Game::assetManager = new AssetManager(clientPath); } catch (std::runtime_error& ex) { Game::logger->Log("ChatServer", "Got an error while setting up assets: %s", ex.what()); - + return EXIT_FAILURE; } @@ -199,25 +203,25 @@ void HandlePacket(Packet* packet) { Game::logger->Log("ChatServer", "A server is connecting, awaiting user list."); } - if (packet->data[1] == CHAT_INTERNAL) { - switch (packet->data[3]) { - case MSG_CHAT_INTERNAL_PLAYER_ADDED_NOTIFICATION: + if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::CHAT_INTERNAL) { + switch (static_cast<eChatInternalMessageType>(packet->data[3])) { + case eChatInternalMessageType::PLAYER_ADDED_NOTIFICATION: playerContainer.InsertPlayer(packet); break; - case MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION: + case eChatInternalMessageType::PLAYER_REMOVED_NOTIFICATION: playerContainer.RemovePlayer(packet); break; - case MSG_CHAT_INTERNAL_MUTE_UPDATE: + case eChatInternalMessageType::MUTE_UPDATE: playerContainer.MuteUpdate(packet); break; - case MSG_CHAT_INTERNAL_CREATE_TEAM: + case eChatInternalMessageType::CREATE_TEAM: playerContainer.CreateTeamServer(packet); break; - case MSG_CHAT_INTERNAL_ANNOUNCEMENT: { + case eChatInternalMessageType::ANNOUNCEMENT: { //we just forward this packet to every connected server CINSTREAM; Game::server->Send(&inStream, packet->systemAddress, true); //send to everyone except origin @@ -229,67 +233,67 @@ void HandlePacket(Packet* packet) { } } - if (packet->data[1] == CHAT) { - switch (packet->data[3]) { - case MSG_CHAT_GET_FRIENDS_LIST: + if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::CHAT) { + switch (static_cast<eChatMessageType>(packet->data[3])) { + case eChatMessageType::GET_FRIENDS_LIST: ChatPacketHandler::HandleFriendlistRequest(packet); break; - case MSG_CHAT_GET_IGNORE_LIST: + case eChatMessageType::GET_IGNORE_LIST: Game::logger->Log("ChatServer", "Asked for ignore list, but is unimplemented right now."); break; - case MSG_CHAT_TEAM_GET_STATUS: + case eChatMessageType::TEAM_GET_STATUS: ChatPacketHandler::HandleTeamStatusRequest(packet); break; - case MSG_CHAT_ADD_FRIEND_REQUEST: + case eChatMessageType::ADD_FRIEND_REQUEST: //this involves someone sending the initial request, the response is below, response as in from the other player. //We basically just check to see if this player is online or not and route the packet. ChatPacketHandler::HandleFriendRequest(packet); break; - case MSG_CHAT_ADD_FRIEND_RESPONSE: + case eChatMessageType::ADD_FRIEND_RESPONSE: //This isn't the response a server sent, rather it is a player's response to a received request. //Here, we'll actually have to add them to eachother's friend lists depending on the response code. ChatPacketHandler::HandleFriendResponse(packet); break; - case MSG_CHAT_REMOVE_FRIEND: + case eChatMessageType::REMOVE_FRIEND: ChatPacketHandler::HandleRemoveFriend(packet); break; - case MSG_CHAT_GENERAL_CHAT_MESSAGE: + case eChatMessageType::GENERAL_CHAT_MESSAGE: ChatPacketHandler::HandleChatMessage(packet); break; - case MSG_CHAT_PRIVATE_CHAT_MESSAGE: + case eChatMessageType::PRIVATE_CHAT_MESSAGE: //This message is supposed to be echo'd to both the sender and the receiver //BUT: they have to have different responseCodes, so we'll do some of the ol hacky wacky to fix that right up. ChatPacketHandler::HandlePrivateChatMessage(packet); break; - case MSG_CHAT_TEAM_INVITE: + case eChatMessageType::TEAM_INVITE: ChatPacketHandler::HandleTeamInvite(packet); break; - case MSG_CHAT_TEAM_INVITE_RESPONSE: + case eChatMessageType::TEAM_INVITE_RESPONSE: ChatPacketHandler::HandleTeamInviteResponse(packet); break; - case MSG_CHAT_TEAM_LEAVE: + case eChatMessageType::TEAM_LEAVE: ChatPacketHandler::HandleTeamLeave(packet); break; - case MSG_CHAT_TEAM_SET_LEADER: + case eChatMessageType::TEAM_SET_LEADER: ChatPacketHandler::HandleTeamPromote(packet); break; - case MSG_CHAT_TEAM_KICK: + case eChatMessageType::TEAM_KICK: ChatPacketHandler::HandleTeamKick(packet); break; - case MSG_CHAT_TEAM_SET_LOOT: + case eChatMessageType::TEAM_SET_LOOT: ChatPacketHandler::HandleTeamLootOption(packet); break; @@ -298,9 +302,9 @@ void HandlePacket(Packet* packet) { } } - if (packet->data[1] == WORLD) { - switch (packet->data[3]) { - case MSG_WORLD_CLIENT_ROUTE_PACKET: { + if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::WORLD) { + switch (static_cast<eWorldMessageType>(packet->data[3])) { + case eWorldMessageType::ROUTE_PACKET: { Game::logger->Log("ChatServer", "Routing packet from world"); break; } diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index 6bf3ccd1..dcc9ebb9 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -6,9 +6,10 @@ #include "dLogger.h" #include "ChatPacketHandler.h" #include "GeneralUtils.h" -#include "dMessageIdentifiers.h" #include "PacketUtils.h" #include "Database.h" +#include "eConnectionType.h" +#include "eChatInternalMessageType.h" PlayerContainer::PlayerContainer() { } @@ -149,7 +150,7 @@ void PlayerContainer::CreateTeamServer(Packet* packet) { void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_MUTE_UPDATE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::MUTE_UPDATE); bitStream.Write(player); bitStream.Write(time); @@ -348,7 +349,7 @@ void PlayerContainer::TeamStatusUpdate(TeamData* team) { void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_TEAM_UPDATE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::TEAM_UPDATE); bitStream.Write(team->teamID); bitStream.Write(deleteTeam); diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index 26201c3d..e11866f1 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -7,6 +7,8 @@ #include <string> #include <set> #include "BitStream.h" +#include "eConnectionType.h" +#include "eClientMessageType.h" #pragma warning (disable:4251) //Disables SQL warnings @@ -28,7 +30,7 @@ constexpr uint32_t lowFrameDelta = FRAMES_TO_MS(lowFramerate); #define CBITSTREAM RakNet::BitStream bitStream; #define CINSTREAM RakNet::BitStream inStream(packet->data, packet->length, false); -#define CMSGHEADER PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_GAME_MSG); +#define CMSGHEADER PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::GAME_MSG); #define SEND_PACKET Game::server->Send(&bitStream, sysAddr, false); #define SEND_PACKET_BROADCAST Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); diff --git a/dCommon/dEnums/dMessageIdentifiers.h b/dCommon/dEnums/dMessageIdentifiers.h deleted file mode 100644 index 7c810a2d..00000000 --- a/dCommon/dEnums/dMessageIdentifiers.h +++ /dev/null @@ -1,564 +0,0 @@ -#pragma once -#include "MessageIdentifiers.h" - -enum CONNECTION_TYPE { - SERVER = 0, //!< Means it is used throughout all servers - AUTH, //!< Means it is sent from the client authentication - CHAT, //!< Means it is sent from and to the chat server - CHAT_INTERNAL, //!< Unused - We can potentially use this in the future for various things - WORLD, //!< Means it is sent from the client world - CLIENT, //!< Means it is sent to the client from the world server - MASTER //!< Means it is sent to and from the master server -}; - -//! The Internal Server Packet Identifiers -enum SERVER { - MSG_SERVER_VERSION_CONFIRM = 0, /*!< Sent during a handshake to confirm the server/client version */ - MSG_SERVER_DISCONNECT_NOTIFY, /*!< Sent when a user disconnected */ - MSG_SERVER_GENERAL_NOTIFY /*!< A general notification */ -}; - -//! The Internal Authentication Packet Identifiers -enum AUTH { - MSG_AUTH_LOGIN_REQUEST = 0, /*!< Sent from the client when a user logs in */ - MSG_AUTH_LOGOUT_REQUEST, /*!< Sent from the client when a user logs out */ - MSG_AUTH_CREATE_NEW_ACCOUNT_REQUEST, /*!< Sent from the client when a user creates a new account */ - MSG_AUTH_LEGOINTERFACE_AUTH_RESPONSE, /*!< Unknown */ - MSG_AUTH_SESSIONKEY_RECEIVED_CONFIRM, /*!< Sent when the server recieved the session key (?) */ - MSG_AUTH_RUNTIME_CONFIG /*!< Unknown */ -}; - -//! The Internal Chat Packet Identifiers -enum CHAT { - MSG_CHAT_LOGIN_SESSION_NOTIFY = 0, /*!< When a user logs in */ - MSG_CHAT_GENERAL_CHAT_MESSAGE, /*!< Used for global chat messages */ - MSG_CHAT_PRIVATE_CHAT_MESSAGE, /*!< Used for private chat messages */ - MSG_CHAT_USER_CHANNEL_CHAT_MESSAGE, /*!< Unknown */ - MSG_CHAT_WORLD_DISCONNECT_REQUEST, /*!< Unknown */ - MSG_CHAT_WORLD_PROXIMITY_RESPONSE, /*!< Unknown */ - MSG_CHAT_WORLD_PARCEL_RESPONSE, /*!< Unknown */ - MSG_CHAT_ADD_FRIEND_REQUEST, /*!< When the client requests to add a friend */ - MSG_CHAT_ADD_FRIEND_RESPONSE, /*!< Sent from the server when the client adds a friend */ - MSG_CHAT_REMOVE_FRIEND, /*!< When the client removes a friend */ - MSG_CHAT_GET_FRIENDS_LIST, /*!< Sent when the client requests a user's friends list */ - MSG_CHAT_ADD_IGNORE, /*!< Sent when the client adds a friend to the "ignore" list */ - MSG_CHAT_REMOVE_IGNORE, /*!< Sent when the client removes a friend from the "ignore" list */ - MSG_CHAT_GET_IGNORE_LIST, /*!< Sent when the client requests a user's ignored list */ - MSG_CHAT_TEAM_MISSED_INVITE_CHECK, /*!< Unknown (Something with an unresponded-to friend request probably) */ - MSG_CHAT_TEAM_INVITE, /*!< When the client invites a user to a team */ - MSG_CHAT_TEAM_INVITE_RESPONSE, /*!< Sent from the server when the client invites someone to the team */ - MSG_CHAT_TEAM_KICK, /*!< Sent when the client kicks a member from a team */ - MSG_CHAT_TEAM_LEAVE, /*!< Sent when the client leaves a team */ - MSG_CHAT_TEAM_SET_LOOT, /*!< Unknown (Something to do with team loot) */ - MSG_CHAT_TEAM_SET_LEADER, /*!< Unknown (Probably sets the team leader or something) */ - MSG_CHAT_TEAM_GET_STATUS, /*!< Check to see if we are in a team or not, sent on world join */ - MSG_CHAT_GUILD_CREATE, /*!< Guild Creation */ - MSG_CHAT_GUILD_INVITE, /*!< Guild Invitation */ - MSG_CHAT_GUILD_INVITE_RESPONSE, /*!< Guild Invite Response */ - MSG_CHAT_GUILD_LEAVE, /*!< Guild Leave */ - MSG_CHAT_GUILD_KICK, /*!< Guild Kick */ - MSG_CHAT_GUILD_GET_STATUS, /*!< Guild Get Status */ - MSG_CHAT_GUILD_GET_ALL, /*!< Guild Get All */ - MSG_CHAT_SHOW_ALL, - MSG_CHAT_BLUEPRINT_MODERATED, - MSG_CHAT_BLUEPRINT_MODEL_READY, - MSG_CHAT_PROPERTY_READY_FOR_APPROVAL, - MSG_CHAT_PROPERTY_MODERATION_CHANGED, - MSG_CHAT_PROPERTY_BUILDMODE_CHANGED, - MSG_CHAT_PROPERTY_BUILDMODE_CHANGED_REPORT, - MSG_CHAT_MAIL, - MSG_CHAT_WORLD_INSTANCE_LOCATION_REQUEST, - MSG_CHAT_REPUTATION_UPDATE, - MSG_CHAT_SEND_CANNED_TEXT, - MSG_CHAT_GMLEVEL_UPDATE, - MSG_CHAT_CHARACTER_NAME_CHANGE_REQUEST, - MSG_CHAT_CSR_REQUEST, - MSG_CHAT_CSR_REPLY, - MSG_CHAT_GM_KICK, - MSG_CHAT_GM_ANNOUNCE, - MSG_CHAT_GM_MUTE, - MSG_CHAT_ACTIVITY_UPDATE, - MSG_CHAT_WORLD_ROUTE_PACKET, - MSG_CHAT_GET_ZONE_POPULATIONS, - MSG_CHAT_REQUEST_MINIMUM_CHAT_MODE, - MSG_CHAT_REQUEST_MINIMUM_CHAT_MODE_PRIVATE, - MSG_CHAT_MATCH_REQUEST, - MSG_CHAT_UGCMANIFEST_REPORT_MISSING_FILE, - MSG_CHAT_UGCMANIFEST_REPORT_DONE_FILE, - MSG_CHAT_UGCMANIFEST_REPORT_DONE_BLUEPRINT, - MSG_CHAT_UGCC_REQUEST, - MSG_CHAT_WHO, - MSG_CHAT_WORLD_PLAYERS_PET_MODERATED_ACKNOWLEDGE, - MSG_CHAT_ACHIEVEMENT_NOTIFY, - MSG_CHAT_GM_CLOSE_PRIVATE_CHAT_WINDOW, - MSG_CHAT_UNEXPECTED_DISCONNECT, - MSG_CHAT_PLAYER_READY, - MSG_CHAT_GET_DONATION_TOTAL, - MSG_CHAT_UPDATE_DONATION, - MSG_CHAT_PRG_CSR_COMMAND, - MSG_CHAT_HEARTBEAT_REQUEST_FROM_WORLD, - MSG_CHAT_UPDATE_FREE_TRIAL_STATUS -}; - -//! Used for packets related to chatting -enum CHAT_INTERNAL { - MSG_CHAT_INTERNAL_PLAYER_ADDED_NOTIFICATION = 0, - MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION, - MSG_CHAT_INTERNAL_ADD_FRIEND, - MSG_CHAT_INTERNAL_ADD_BEST_FRIEND, - MSG_CHAT_INTERNAL_ADD_TO_TEAM, - MSG_CHAT_INTERNAL_ADD_BLOCK, - MSG_CHAT_INTERNAL_REMOVE_FRIEND, - MSG_CHAT_INTERNAL_REMOVE_BLOCK, - MSG_CHAT_INTERNAL_REMOVE_FROM_TEAM, - MSG_CHAT_INTERNAL_DELETE_TEAM, - MSG_CHAT_INTERNAL_REPORT, - MSG_CHAT_INTERNAL_PRIVATE_CHAT, - MSG_CHAT_INTERNAL_PRIVATE_CHAT_RESPONSE, - MSG_CHAT_INTERNAL_ANNOUNCEMENT, - MSG_CHAT_INTERNAL_MAIL_COUNT_UPDATE, - MSG_CHAT_INTERNAL_MAIL_SEND_NOTIFY, - MSG_CHAT_INTERNAL_REQUEST_USER_LIST, - MSG_CHAT_INTERNAL_FRIEND_LIST, - MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER, - MSG_CHAT_INTERNAL_TEAM_UPDATE, - MSG_CHAT_INTERNAL_MUTE_UPDATE, - MSG_CHAT_INTERNAL_CREATE_TEAM, -}; - -//! Used for packets send to the world -enum WORLD { - MSG_WORLD_CLIENT_VALIDATION = 1, // Session info - MSG_WORLD_CLIENT_CHARACTER_LIST_REQUEST, - MSG_WORLD_CLIENT_CHARACTER_CREATE_REQUEST, - MSG_WORLD_CLIENT_LOGIN_REQUEST, // Character selected - MSG_WORLD_CLIENT_GAME_MSG, - MSG_WORLD_CLIENT_CHARACTER_DELETE_REQUEST, - MSG_WORLD_CLIENT_CHARACTER_RENAME_REQUEST, - MSG_WORLD_CLIENT_HAPPY_FLOWER_MODE_NOTIFY, - MSG_WORLD_CLIENT_SLASH_RELOAD_MAP, // Reload map cmp - MSG_WORLD_CLIENT_SLASH_PUSH_MAP_REQUEST, // Push map req cmd - MSG_WORLD_CLIENT_SLASH_PUSH_MAP, // Push map cmd - MSG_WORLD_CLIENT_SLASH_PULL_MAP, // Pull map cmd - MSG_WORLD_CLIENT_LOCK_MAP_REQUEST, - MSG_WORLD_CLIENT_GENERAL_CHAT_MESSAGE, // General chat message - MSG_WORLD_CLIENT_HTTP_MONITOR_INFO_REQUEST, - MSG_WORLD_CLIENT_SLASH_DEBUG_SCRIPTS, // Debug scripts cmd - MSG_WORLD_CLIENT_MODELS_CLEAR, - MSG_WORLD_CLIENT_EXHIBIT_INSERT_MODEL, - MSG_WORLD_CLIENT_LEVEL_LOAD_COMPLETE, // Character data request - MSG_WORLD_CLIENT_TMP_GUILD_CREATE, - MSG_WORLD_CLIENT_ROUTE_PACKET, // Social? - MSG_WORLD_CLIENT_POSITION_UPDATE, - MSG_WORLD_CLIENT_MAIL, - MSG_WORLD_CLIENT_WORD_CHECK, // Whitelist word check - MSG_WORLD_CLIENT_STRING_CHECK, // Whitelist string check - MSG_WORLD_CLIENT_GET_PLAYERS_IN_ZONE, - MSG_WORLD_CLIENT_REQUEST_UGC_MANIFEST_INFO, - MSG_WORLD_CLIENT_BLUEPRINT_GET_ALL_DATA_REQUEST, - MSG_WORLD_CLIENT_CANCEL_MAP_QUEUE, - MSG_WORLD_CLIENT_HANDLE_FUNNESS, - MSG_WORLD_CLIENT_FAKE_PRG_CSR_MESSAGE, - MSG_WORLD_CLIENT_REQUEST_FREE_TRIAL_REFRESH, - MSG_WORLD_CLIENT_GM_SET_FREE_TRIAL_STATUS -}; - -//! An enum for packets sent to the client -enum CLIENT { - MSG_CLIENT_LOGIN_RESPONSE = 0, - MSG_CLIENT_LOGOUT_RESPONSE, - MSG_CLIENT_LOAD_STATIC_ZONE, - MSG_CLIENT_CREATE_OBJECT, - MSG_CLIENT_CREATE_CHARACTER, - MSG_CLIENT_CREATE_CHARACTER_EXTENDED, - MSG_CLIENT_CHARACTER_LIST_RESPONSE, - MSG_CLIENT_CHARACTER_CREATE_RESPONSE, - MSG_CLIENT_CHARACTER_RENAME_RESPONSE, - MSG_CLIENT_CHAT_CONNECT_RESPONSE, - MSG_CLIENT_AUTH_ACCOUNT_CREATE_RESPONSE, - MSG_CLIENT_DELETE_CHARACTER_RESPONSE, - MSG_CLIENT_GAME_MSG, - MSG_CLIENT_CONNECT_CHAT, - MSG_CLIENT_TRANSFER_TO_WORLD, - MSG_CLIENT_IMPENDING_RELOAD_NOTIFY, - MSG_CLIENT_MAKE_GM_RESPONSE, - MSG_CLIENT_HTTP_MONITOR_INFO_RESPONSE, - MSG_CLIENT_SLASH_PUSH_MAP_RESPONSE, - MSG_CLIENT_SLASH_PULL_MAP_RESPONSE, - MSG_CLIENT_SLASH_LOCK_MAP_RESPONSE, - MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE, - MSG_CLIENT_BLUEPRINT_LUP_SAVE_RESPONSE, - MSG_CLIENT_BLUEPRINT_LOAD_RESPONSE_ITEMID, - MSG_CLIENT_BLUEPRINT_GET_ALL_DATA_RESPONSE, - MSG_CLIENT_MODEL_INSTANTIATE_RESPONSE, - MSG_CLIENT_DEBUG_OUTPUT, - MSG_CLIENT_ADD_FRIEND_REQUEST, - MSG_CLIENT_ADD_FRIEND_RESPONSE, - MSG_CLIENT_REMOVE_FRIEND_RESPONSE, - MSG_CLIENT_GET_FRIENDS_LIST_RESPONSE, - MSG_CLIENT_UPDATE_FRIEND_NOTIFY, - MSG_CLIENT_ADD_IGNORE_RESPONSE, - MSG_CLIENT_REMOVE_IGNORE_RESPONSE, - MSG_CLIENT_GET_IGNORE_LIST_RESPONSE, - MSG_CLIENT_TEAM_INVITE, - MSG_CLIENT_TEAM_INVITE_INITIAL_RESPONSE, - MSG_CLIENT_GUILD_CREATE_RESPONSE, - MSG_CLIENT_GUILD_GET_STATUS_RESPONSE, - MSG_CLIENT_GUILD_INVITE, - MSG_CLIENT_GUILD_INVITE_INITIAL_RESPONSE, - MSG_CLIENT_GUILD_INVITE_FINAL_RESPONSE, - MSG_CLIENT_GUILD_INVITE_CONFIRM, - MSG_CLIENT_GUILD_ADD_PLAYER, - MSG_CLIENT_GUILD_REMOVE_PLAYER, - MSG_CLIENT_GUILD_LOGIN_LOGOUT, - MSG_CLIENT_GUILD_RANK_CHANGE, - MSG_CLIENT_GUILD_DATA, - MSG_CLIENT_GUILD_STATUS, - MSG_CLIENT_MAIL, - MSG_CLIENT_DB_PROXY_RESULT, - MSG_CLIENT_SHOW_ALL_RESPONSE, - MSG_CLIENT_WHO_RESPONSE, - MSG_CLIENT_SEND_CANNED_TEXT, - MSG_CLIENT_UPDATE_CHARACTER_NAME, - MSG_CLIENT_SET_NETWORK_SIMULATOR, - MSG_CLIENT_INVALID_CHAT_MESSAGE, - MSG_CLIENT_MINIMUM_CHAT_MODE_RESPONSE, - MSG_CLIENT_MINIMUM_CHAT_MODE_RESPONSE_PRIVATE, - MSG_CLIENT_CHAT_MODERATION_STRING, - MSG_CLIENT_UGC_MANIFEST_RESPONSE, - MSG_CLIENT_IN_LOGIN_QUEUE, - MSG_CLIENT_SERVER_STATES, - MSG_CLIENT_GM_CLOSE_TARGET_CHAT_WINDOW, - MSG_CLIENT_GENERAL_TEXT_FOR_LOCALIZATION, - MSG_CLIENT_UPDATE_FREE_TRIAL_STATUS, - MSG_CLIENT_UGC_DOWNLOAD_FAILED = 120 -}; - -//! Used for packets sent to the master server -enum MASTER { - MSG_MASTER_REQUEST_PERSISTENT_ID = 1, - MSG_MASTER_REQUEST_PERSISTENT_ID_RESPONSE, - MSG_MASTER_REQUEST_ZONE_TRANSFER, - MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE, - MSG_MASTER_SERVER_INFO, - MSG_MASTER_REQUEST_SESSION_KEY, - MSG_MASTER_SET_SESSION_KEY, - MSG_MASTER_SESSION_KEY_RESPONSE, - MSG_MASTER_PLAYER_ADDED, - MSG_MASTER_PLAYER_REMOVED, - - MSG_MASTER_CREATE_PRIVATE_ZONE, - MSG_MASTER_REQUEST_PRIVATE_ZONE, - - MSG_MASTER_WORLD_READY, - MSG_MASTER_PREP_ZONE, - - MSG_MASTER_SHUTDOWN, - MSG_MASTER_SHUTDOWN_RESPONSE, - MSG_MASTER_SHUTDOWN_IMMEDIATE, - - MSG_MASTER_SHUTDOWN_UNIVERSE, - - MSG_MASTER_AFFIRM_TRANSFER_REQUEST, - MSG_MASTER_AFFIRM_TRANSFER_RESPONSE, - - MSG_MASTER_NEW_SESSION_ALERT -}; - -//! The Game messages -enum GAME_MSG : unsigned short { - GAME_MSG_TELEPORT = 19, - GAME_MSG_SET_PLAYER_CONTROL_SCHEME = 26, - GAME_MSG_DROP_CLIENT_LOOT = 30, - GAME_MSG_DIE = 37, - GAME_MSG_REQUEST_DIE = 38, - GAME_MSG_PLAY_EMOTE = 41, - GAME_MSG_PLAY_ANIMATION = 43, - GAME_MSG_CONTROL_BEHAVIOR = 48, - GAME_MSG_SET_NAME = 72, - GAME_MSG_ECHO_START_SKILL = 118, - GAME_MSG_START_SKILL = 119, - GAME_MSG_VERIFY_ACK = 121, - GAME_MSG_ADD_SKILL = 127, - GAME_MSG_REMOVE_SKILL = 128, - GAME_MSG_SET_CURRENCY = 133, - GAME_MSG_PICKUP_CURRENCY = 137, - GAME_MSG_PICKUP_ITEM = 139, - GAME_MSG_TEAM_PICKUP_ITEM = 140, - GAME_MSG_PLAY_FX_EFFECT = 154, - GAME_MSG_STOP_FX_EFFECT = 155, - GAME_MSG_REQUEST_RESURRECT = 159, - GAME_MSG_RESURRECT = 160, - GAME_MSG_PUSH_EQUIPPED_ITEMS_STATE = 191, - GAME_MSG_POP_EQUIPPED_ITEMS_STATE = 192, - GAME_MSG_SET_GM_LEVEL = 193, - GAME_MSG_SET_STUNNED = 198, - GAME_MSG_SET_STUN_IMMUNITY = 200, - GAME_MSG_KNOCKBACK = 202, - GAME_MSG_REBUILD_CANCEL = 209, - GAME_MSG_ENABLE_REBUILD = 213, - GAME_MSG_MOVE_ITEM_IN_INVENTORY = 224, - GAME_MSG_ADD_ITEM_TO_INVENTORY_CLIENT_SYNC = 227, - GAME_MSG_REMOVE_ITEM_FROM_INVENTORY = 230, - GAME_MSG_EQUIP_ITEM = 231, - GAME_MSG_UN_EQUIP_ITEM = 233, - GAME_MSG_OFFER_MISSION = 248, - GAME_MSG_RESPOND_TO_MISSION = 249, - GAME_MSG_NOTIFY_MISSION = 254, - GAME_MSG_NOTIFY_MISSION_TASK = 255, - GAME_MSG_REBUILD_NOTIFY_STATE = 336, - GAME_MSG_TERMINATE_INTERACTION = 357, - GAME_MSG_SERVER_TERMINATE_INTERACTION = 358, - GAME_MSG_REQUEST_USE = 364, - GAME_MSG_VENDOR_OPEN_WINDOW = 369, - GAME_MSG_BUY_FROM_VENDOR = 373, - GAME_MSG_SELL_TO_VENDOR = 374, - GAME_MSG_TEAM_SET_OFF_WORLD_FLAG = 383, - GAME_MSG_SET_INVENTORY_SIZE = 389, - GAME_MSG_ACKNOWLEDGE_POSSESSION = 391, - GAME_MSG_SET_SHOOTING_GALLERY_PARAMS = 400, - GAME_MSG_REQUEST_ACTIVITY_START_STOP = 402, - GAME_MSG_REQUEST_ACTIVITY_ENTER = 403, - GAME_MSG_REQUEST_ACTIVITY_EXIT = 404, - GAME_MSG_ACTIVITY_ENTER = 405, - GAME_MSG_ACTIVITY_EXIT = 406, - GAME_MSG_ACTIVITY_START = 407, - GAME_MSG_ACTIVITY_STOP = 408, - GAME_MSG_SHOOTING_GALLERY_CLIENT_AIM_UPDATE = 409, - GAME_MSG_SHOOTING_GALLERY_FIRE = 411, - GAME_MSG_REQUEST_VENDOR_STATUS_UPDATE = 416, - GAME_MSG_VENDOR_STATUS_UPDATE = 417, - GAME_MSG_NOTIFY_CLIENT_SHOOTING_GALLERY_SCORE = 425, - GAME_MSG_CONSUME_CLIENT_ITEM = 427, - GAME_MSG_CLIENT_ITEM_CONSUMED = 428, - GAME_MSG_UPDATE_SHOOTING_GALLERY_ROTATION = 448, - GAME_MSG_SET_FLAG = 471, - GAME_MSG_NOTIFY_CLIENT_FLAG_CHANGE = 472, - GAME_MSG_VENDOR_TRANSACTION_RESULT = 476, - GAME_MSG_HAS_BEEN_COLLECTED = 486, - GAME_MSG_DISPLAY_CHAT_BUBBLE = 495, - GAME_MSG_SPAWN_PET = 498, - GAME_MSG_DESPAWN_PET = 499, - GAME_MSG_PLAYER_LOADED = 505, - GAME_MSG_PLAYER_READY = 509, - GAME_MSG_REQUEST_LINKED_MISSION = 515, - GAME_MSG_INVALID_ZONE_TRANSFER_LIST = 519, - GAME_MSG_MISSION_DIALOGUE_OK = 520, - GAME_MSG_DISPLAY_MESSAGE_BOX = 529, - GAME_MSG_MESSAGE_BOX_RESPOND = 530, - GAME_MSG_CHOICE_BOX_RESPOND = 531, - GAME_MSG_SMASH = 537, - GAME_MSG_UNSMASH = 538, - GAME_MSG_SET_SHOOTING_GALLERY_RETICULE_EFFECT = 548, - GAME_MSG_PLACE_MODEL_RESPONSE = 0x223, - GAME_MSG_SET_JET_PACK_MODE = 561, - GAME_MSG_REGISTER_PET_ID = 565, - GAME_MSG_REGISTER_PET_DBID = 566, - GAME_MSG_SHOW_ACTIVITY_COUNTDOWN = 568, - GAME_MSG_START_ACTIVITY_TIME = 576, - GAME_MSG_ACTIVITY_PAUSE = 602, - GAME_MSG_USE_NON_EQUIPMENT_ITEM = 603, - GAME_MSG_USE_ITEM_RESULT = 607, - GAME_MSG_COMMAND_PET = 640, - GAME_MSG_PET_RESPONSE = 641, - GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA = 648, - GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA = 649, - GAME_MSG_NOTIFY_OBJECT = 656, - GAME_MSG_CLIENT_NOTIFY_PET = 659, - GAME_MSG_NOTIFY_PET = 660, - GAME_MSG_NOTIFY_PET_TAMING_MINIGAME = 661, - GAME_MSG_START_SERVER_PET_MINIGAME_TIMER = 662, - GAME_MSG_CLIENT_EXIT_TAMING_MINIGAME = 663, - GAME_MSG_PET_NAME_CHANGED = 686, - GAME_MSG_PET_TAMING_MINIGAME_RESULT = 667, - GAME_MSG_PET_TAMING_TRY_BUILD_RESULT = 668, - GAME_MSG_NOTIFY_TAMING_BUILD_SUCCESS = 673, - GAME_MSG_NOTIFY_TAMING_MODEL_LOADED_ON_SERVER = 674, - GAME_MSG_ACTIVATE_BUBBLE_BUFF = 678, - GAME_MSG_DEACTIVATE_BUBBLE_BUFF = 679, - GAME_MSG_ADD_PET_TO_PLAYER = 681, - GAME_MSG_REQUEST_SET_PET_NAME = 683, - GAME_MSG_SET_PET_NAME = 684, - GAME_MSG_NOTIFY_PET_TAMING_PUZZLE_SELECTED = 675, - GAME_MSG_SHOW_PET_ACTION_BUTTON = 692, - GAME_MSG_SET_EMOTE_LOCK_STATE = 693, - GAME_MSG_USE_ITEM_REQUIREMENTS_RESPONSE = 703, - GAME_MSG_PLAY_EMBEDDED_EFFECT_ON_ALL_CLIENTS_NEAR_OBJECT = 713, - GAME_MSG_DOWNLOAD_PROPERTY_DATA = 716, - GAME_MSG_QUERY_PROPERTY_DATA = 717, - GAME_MSG_PROPERTY_EDITOR_BEGIN = 724, - GAME_MSG_PROPERTY_EDITOR_END = 725, - GAME_MSG_IS_MINIFIG_IN_A_BUBBLE = 729, - GAME_MSG_START_PATHING = 733, - GAME_MSG_ACTIVATE_BUBBLE_BUFF_FROM_SERVER = 734, - GAME_MSG_DEACTIVATE_BUBBLE_BUFF_FROM_SERVER = 735, - GAME_MSG_NOTIFY_CLIENT_ZONE_OBJECT = 737, - GAME_MSG_UPDATE_REPUTATION = 746, - GAME_MSG_PROPERTY_RENTAL_RESPONSE = 750, - GAME_MSG_REQUEST_PLATFORM_RESYNC = 760, - GAME_MSG_PLATFORM_RESYNC = 761, - GAME_MSG_PLAY_CINEMATIC = 762, - GAME_MSG_END_CINEMATIC = 763, - GAME_MSG_CINEMATIC_UPDATE = 764, - GAME_MSG_TOGGLE_GHOST_REFERENCE_OVERRIDE = 767, - GAME_MSG_SET_GHOST_REFERENCE_POSITION = 768, - GAME_MSG_FIRE_EVENT_SERVER_SIDE = 770, - GAME_MSG_SET_NETWORK_SCRIPT_VAR = 781, - GAME_MSG_UPDATE_MODEL_FROM_CLIENT = 793, - GAME_MSG_DELETE_MODEL_FROM_CLIENT = 794, - GAME_MSG_PLAY_ND_AUDIO_EMITTER = 821, - GAME_MSG_PLAY2_DAMBIENT_SOUND = 831, - GAME_MSG_ENTER_PROPERTY1 = 840, - GAME_MSG_ENTER_PROPERTY2 = 841, - GAME_MSG_PROPERTY_ENTRANCE_SYNC = 842, - GAME_MSG_PROPERTY_SELECT_QUERY = 845, - GAME_MSG_PARSE_CHAT_MESSAGE = 850, - GAME_MSG_BROADCAST_TEXT_TO_CHATBOX = 858, - GAME_MSG_OPEN_PROPERTY_MANAGEMENT = 860, - GAME_MSG_OPEN_PROPERTY_VENDOR = 861, - GAME_MSG_UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK = 863, - GAME_MSG_CLIENT_TRADE_REQUEST = 868, - GAME_MSG_SERVER_TRADE_REQUEST = 869, - GAME_MSG_SERVER_TRADE_INVITE = 870, - GAME_MSG_CLIENT_TRADE_REPLY = 871, - GAME_MSG_SERVER_TRADE_REPLY = 872, - GAME_MSG_SERVER_TRADE_INITIAL_REPLY = 873, - GAME_MSG_SERVER_TRADE_FINAL_REPLY = 874, - GAME_MSG_CLIENT_TRADE_UPDATE = 875, - GAME_MSG_SERVER_SIDE_TRADE_UPDATE = 876, - GAME_MSG_SERVER_TRADE_UPDATE = 877, - GAME_MSG_CLIENT_TRADE_CANCEL = 878, - GAME_MSG_CLIENT_SIDE_TRADE_CANCEL = 879, - GAME_MSG_CLIENT_TRADE_ACCEPT = 880, - GAME_MSG_SERVER_SIDE_TRADE_ACCEPT = 881, - GAME_MSG_SERVER_SIDE_TRADE_CANCEL = 882, - GAME_MSG_SERVER_TRADE_CANCEL = 883, - GAME_MSG_SERVER_TRADE_ACCEPT = 884, - GAME_MSG_READY_FOR_UPDATES = 888, - GAME_MSG_ORIENT_TO_OBJECT = 905, - GAME_MSG_ORIENT_TO_POSITION = 906, - GAME_MSG_ORIENT_TO_ANGLE = 907, - GAME_MSG_BOUNCER_ACTIVE_STATUS = 942, - GAME_MSG_UN_USE_BBB_MODEL = 999, - GAME_MSG_BBB_LOAD_ITEM_REQUEST = 1000, - GAME_MSG_BBB_SAVE_REQUEST = 1001, - GAME_MSG_BBB_SAVE_RESPONSE = 1006, - GAME_MSG_NOTIFY_CLIENT_OBJECT = 1042, - GAME_MSG_DISPLAY_ZONE_SUMMARY = 1043, - GAME_MSG_ZONE_SUMMARY_DISMISSED = 1044, - GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST = 1053, - GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC = 1046, - GAME_MSG_START_BUILDING_WITH_ITEM = 1057, - GAME_MSG_START_ARRANGING_WITH_ITEM = 1061, - GAME_MSG_FINISH_ARRANGING_WITH_ITEM = 1062, - GAME_MSG_DONE_ARRANGING_WITH_ITEM = 1063, - GAME_MSG_SET_BUILD_MODE = 1068, - GAME_MSG_BUILD_MODE_SET = 1069, - GAME_MSG_SET_BUILD_MODE_CONFIRMED = 1073, - GAME_MSG_NOTIFY_CLIENT_FAILED_PRECONDITION = 1081, - GAME_MSG_MOVE_ITEM_BETWEEN_INVENTORY_TYPES = 1093, - GAME_MSG_MODULAR_BUILD_BEGIN = 1094, - GAME_MSG_MODULAR_BUILD_END = 1095, - GAME_MSG_MODULAR_BUILD_MOVE_AND_EQUIP = 1096, - GAME_MSG_MODULAR_BUILD_FINISH = 1097, - GAME_MSG_REPORT_BUG = 1198, - GAME_MSG_MISSION_DIALOGUE_CANCELLED = 1129, - GAME_MSG_ECHO_SYNC_SKILL = 1144, - GAME_MSG_SYNC_SKILL = 1145, - GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT = 1148, - GAME_MSG_DO_CLIENT_PROJECTILE_IMPACT = 1151, - GAME_MSG_MODULAR_BUILD_CONVERT_MODEL = 1155, - GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN = 1165, - GAME_MSG_UI_MESSAGE_SERVER_TO_SINGLE_CLIENT = 1184, - GAME_MSG_UI_MESSAGE_SERVER_TO_ALL_CLIENTS = 1185, - GAME_MSG_PET_TAMING_TRY_BUILD = 1197, - GAME_MSG_REQUEST_SMASH_PLAYER = 1202, - GAME_MSG_FIRE_EVENT_CLIENT_SIDE = 1213, - GAME_MSG_TOGGLE_GM_INVIS = 1218, - GAME_MSG_CHANGE_OBJECT_WORLD_STATE = 1223, - GAME_MSG_VEHICLE_LOCK_INPUT = 1230, - GAME_MSG_VEHICLE_UNLOCK_INPUT = 1231, - GAME_MSG_RACING_RESET_PLAYER_TO_LAST_RESET = 1252, - GAME_MSG_RACING_SERVER_SET_PLAYER_LAP_AND_PLANE = 1253, - GAME_MSG_RACING_SET_PLAYER_RESET_INFO = 1254, - GAME_MSG_RACING_PLAYER_INFO_RESET_FINISHED = 1255, - GAME_MSG_LOCK_NODE_ROTATION = 1260, - GAME_MSG_VEHICLE_SET_WHEEL_LOCK_STATE = 1273, - GAME_MSG_NOTIFY_VEHICLE_OF_RACING_OBJECT = 1276, - GAME_MSG_SET_NAME_BILLBOARD_STATE = 1284, - GAME_MSG_PLAYER_REACHED_RESPAWN_CHECKPOINT = 1296, - GAME_MSG_HANDLE_UGC_EQUIP_POST_DELETE_BASED_ON_EDIT_MODE = 1300, - GAME_MSG_HANDLE_UGC_EQUIP_PRE_CREATE_BASED_ON_EDIT_MODE = 1301, - GAME_MSG_PROPERTY_CONTENTS_FROM_CLIENT = 1305, - GAME_MSG_GET_MODELS_ON_PROPERTY = 1306, - GAME_MSG_MATCH_REQUEST = 1308, - GAME_MSG_MATCH_RESPONSE = 1309, - GAME_MSG_MATCH_UPDATE = 1310, - GAME_MSG_MODULE_ASSEMBLY_DB_DATA_FOR_CLIENT = 1131, - GAME_MSG_MODULE_ASSEMBLY_QUERY_DATA = 1132, - GAME_MSG_SHOW_BILLBOARD_INTERACT_ICON = 1337, - GAME_MSG_CHANGE_IDLE_FLAGS = 1338, - GAME_MSG_VEHICLE_ADD_PASSIVE_BOOST_ACTION = 1340, - GAME_MSG_VEHICLE_REMOVE_PASSIVE_BOOST_ACTION = 1341, - GAME_MSG_VEHICLE_NOTIFY_SERVER_ADD_PASSIVE_BOOST_ACTION = 1342, - GAME_MSG_VEHICLE_NOTIFY_SERVER_REMOVE_PASSIVE_BOOST_ACTION = 1343, - GAME_MSG_VEHICLE_ADD_SLOWDOWN_ACTION = 1344, - GAME_MSG_VEHICLE_REMOVE_SLOWDOWN_ACTION = 1345, - GAME_MSG_VEHICLE_NOTIFY_SERVER_ADD_SLOWDOWN_ACTION = 1346, - GAME_MSG_VEHICLE_NOTIFY_SERVER_REMOVE_SLOWDOWN_ACTION = 1347, - GAME_MSG_BUYBACK_FROM_VENDOR = 1350, - GAME_MSG_SET_PROPERTY_ACCESS = 1366, - GAME_MSG_ZONE_PROPERTY_MODEL_PLACED = 1369, - GAME_MSG_ZONE_PROPERTY_MODEL_ROTATED = 1370, - GAME_MSG_ZONE_PROPERTY_MODEL_REMOVED_WHILE_EQUIPPED = 1371, - GAME_MSG_ZONE_PROPERTY_MODEL_EQUIPPED = 1372, - GAME_MSG_ZONE_PROPERTY_MODEL_PICKED_UP = 1373, - GAME_MSG_ZONE_PROPERTY_MODEL_REMOVED = 1374, - GAME_MSG_NOTIFY_RACING_CLIENT = 1390, - GAME_MSG_RACING_PLAYER_HACK_CAR = 1391, - GAME_MSG_RACING_PLAYER_LOADED = 1392, - GAME_MSG_RACING_CLIENT_READY = 1393, - GAME_MSG_UPDATE_CHAT_MODE = 1395, - GAME_MSG_VEHICLE_NOTIFY_FINISHED_RACE = 1396, - GAME_MSG_SET_CONSUMABLE_ITEM = 1409, - GAME_MSG_SET_STATUS_IMMUNITY = 1435, - GAME_MSG_SET_PET_NAME_MODERATED = 1448, - GAME_MSG_MODIFY_LEGO_SCORE = 1459, - GAME_MSG_RESTORE_TO_POST_LOAD_STATS = 1468, - GAME_MSG_SET_RAIL_MOVEMENT = 1471, - GAME_MSG_START_RAIL_MOVEMENT = 1472, - GAME_MSG_CANCEL_RAIL_MOVEMENT = 1474, - GAME_MSG_CLIENT_RAIL_MOVEMENT_READY = 1476, - GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION = 1477, - GAME_MSG_UPDATE_PLAYER_STATISTIC = 1481, - GAME_MSG_MODULAR_ASSEMBLY_NIF_COMPLETED = 1498, - GAME_MSG_NOTIFY_NOT_ENOUGH_INV_SPACE = 1516, - GAME_MSG_TEAM_SET_LEADER = 0x0615, - GAME_MSG_TEAM_INVITE_CONFIRM = 0x0616, - GAME_MSG_TEAM_GET_STATUS_RESPONSE = 0x0617, - GAME_MSG_TEAM_ADD_PLAYER = 0x061a, - GAME_MSG_TEAM_REMOVE_PLAYER = 0x061b, - GAME_MSG_START_CELEBRATION_EFFECT = 1618, - GAME_MSG_ADD_BUFF = 1647, - GAME_MSG_SERVER_DONE_LOADING_ALL_OBJECTS = 1642, - GAME_MSG_PLACE_PROPERTY_MODEL = 1170, - GAME_MSG_VEHICLE_NOTIFY_HIT_IMAGINATION_SERVER = 1606, - GAME_MSG_ADD_RUN_SPEED_MODIFIER = 1505, - GAME_MSG_HANDLE_HOT_PROPERTY_DATA = 1511, - GAME_MSG_SEND_HOT_PROPERTY_DATA = 1510, - GAME_MSG_REMOVE_RUN_SPEED_MODIFIER = 1506, - GAME_MSG_UPDATE_PROPERTY_PERFORMANCE_COST = 1547, - GAME_MSG_PROPERTY_ENTRANCE_BEGIN = 1553, - GAME_MSG_SET_RESURRECT_RESTORE_VALUES = 1591, - GAME_MSG_VEHICLE_STOP_BOOST = 1617, - GAME_MSG_REMOVE_BUFF = 1648, - GAME_MSG_REQUEST_MOVE_ITEM_BETWEEN_INVENTORY_TYPES = 1666, - GAME_MSG_RESPONSE_MOVE_ITEM_BETWEEN_INVENTORY_TYPES = 1667, - GAME_MSG_PLAYER_SET_CAMERA_CYCLING_MODE = 1676, - GAME_MSG_SET_MOUNT_INVENTORY_ID = 1726, - GAME_MSG_NOTIFY_SERVER_LEVEL_PROCESSING_COMPLETE = 1734, - GAME_MSG_NOTIFY_LEVEL_REWARDS = 1735, - GAME_MSG_DISMOUNT_COMPLETE = 1756, - GAME_MSG_MARK_INVENTORY_ITEM_AS_ACTIVE = 1767, - END -}; diff --git a/dCommon/dEnums/eAuthMessageType.h b/dCommon/dEnums/eAuthMessageType.h new file mode 100644 index 00000000..ecc17a37 --- /dev/null +++ b/dCommon/dEnums/eAuthMessageType.h @@ -0,0 +1,15 @@ +#ifndef __EAUTHMESSAGETYPE__H__ +#define __EAUTHMESSAGETYPE__H__ + +#include <cstdint> + +enum class eAuthMessageType : uint32_t { + LOGIN_REQUEST = 0, + LOGOUT_REQUEST, + CREATE_NEW_ACCOUNT_REQUEST, + LEGOINTERFACE_AUTH_RESPONSE, + SESSIONKEY_RECEIVED_CONFIRM, + RUNTIME_CONFIG +}; + +#endif //!__EAUTHMESSAGETYPE__H__ diff --git a/dCommon/dEnums/eChatInternalMessageType.h b/dCommon/dEnums/eChatInternalMessageType.h new file mode 100644 index 00000000..d3b7020b --- /dev/null +++ b/dCommon/dEnums/eChatInternalMessageType.h @@ -0,0 +1,31 @@ +#ifndef __ECHATINTERNALMESSAGETYPE__H__ +#define __ECHATINTERNALMESSAGETYPE__H__ + +#include <cstdint> + +enum eChatInternalMessageType : uint32_t { + PLAYER_ADDED_NOTIFICATION = 0, + PLAYER_REMOVED_NOTIFICATION, + ADD_FRIEND, + ADD_BEST_FRIEND, + ADD_TO_TEAM, + ADD_BLOCK, + REMOVE_FRIEND, + REMOVE_BLOCK, + REMOVE_FROM_TEAM, + DELETE_TEAM, + REPORT, + PRIVATE_CHAT, + PRIVATE_CHAT_RESPONSE, + ANNOUNCEMENT, + MAIL_COUNT_UPDATE, + MAIL_SEND_NOTIFY, + REQUEST_USER_LIST, + FRIEND_LIST, + ROUTE_TO_PLAYER, + TEAM_UPDATE, + MUTE_UPDATE, + CREATE_TEAM, +}; + +#endif //!__ECHATINTERNALMESSAGETYPE__H__ diff --git a/dCommon/dEnums/eChatMessageType.h b/dCommon/dEnums/eChatMessageType.h new file mode 100644 index 00000000..52895ba3 --- /dev/null +++ b/dCommon/dEnums/eChatMessageType.h @@ -0,0 +1,78 @@ +#ifndef __ECHATMESSAGETYPE__H__ +#define __ECHATMESSAGETYPE__H__ + +#include <cstdint> + +//! The Internal Chat Packet Identifiers +enum class eChatMessageType :uint32_t { + LOGIN_SESSION_NOTIFY = 0, + GENERAL_CHAT_MESSAGE, + PRIVATE_CHAT_MESSAGE, + USER_CHANNEL_CHAT_MESSAGE, + WORLD_DISCONNECT_REQUEST, + WORLD_PROXIMITY_RESPONSE, + WORLD_PARCEL_RESPONSE, + ADD_FRIEND_REQUEST, + ADD_FRIEND_RESPONSE, + REMOVE_FRIEND, + GET_FRIENDS_LIST, + ADD_IGNORE, + REMOVE_IGNORE, + GET_IGNORE_LIST, + TEAM_MISSED_INVITE_CHECK, + TEAM_INVITE, + TEAM_INVITE_RESPONSE, + TEAM_KICK, + TEAM_LEAVE, + TEAM_SET_LOOT, + TEAM_SET_LEADER, + TEAM_GET_STATUS, + GUILD_CREATE, + GUILD_INVITE, + GUILD_INVITE_RESPONSE, + GUILD_LEAVE, + GUILD_KICK, + GUILD_GET_STATUS, + GUILD_GET_ALL, + SHOW_ALL, + BLUEPRINT_MODERATED, + BLUEPRINT_MODEL_READY, + PROPERTY_READY_FOR_APPROVAL, + PROPERTY_MODERATION_CHANGED, + PROPERTY_BUILDMODE_CHANGED, + PROPERTY_BUILDMODE_CHANGED_REPORT, + MAIL, + WORLD_INSTANCE_LOCATION_REQUEST, + REPUTATION_UPDATE, + SEND_CANNED_TEXT, + GMLEVEL_UPDATE, + CHARACTER_NAME_CHANGE_REQUEST, + CSR_REQUEST, + CSR_REPLY, + GM_KICK, + GM_ANNOUNCE, + GM_MUTE, + ACTIVITY_UPDATE, + WORLD_ROUTE_PACKET, + GET_ZONE_POPULATIONS, + REQUEST_MINIMUM_CHAT_MODE, + REQUEST_MINIMUM_CHAT_MODE_PRIVATE, + MATCH_REQUEST, + UGCMANIFEST_REPORT_MISSING_FILE, + UGCMANIFEST_REPORT_DONE_FILE, + UGCMANIFEST_REPORT_DONE_BLUEPRINT, + UGCC_REQUEST, + WHO, + WORLD_PLAYERS_PET_MODERATED_ACKNOWLEDGE, + ACHIEVEMENT_NOTIFY, + GM_CLOSE_PRIVATE_CHAT_WINDOW, + UNEXPECTED_DISCONNECT, + PLAYER_READY, + GET_DONATION_TOTAL, + UPDATE_DONATION, + PRG_CSR_COMMAND, + HEARTBEAT_REQUEST_FROM_WORLD, + UPDATE_FREE_TRIAL_STATUS +}; + +#endif //!__ECHATMESSAGETYPE__H__ diff --git a/dCommon/dEnums/eClientMessageType.h b/dCommon/dEnums/eClientMessageType.h new file mode 100644 index 00000000..aafccc36 --- /dev/null +++ b/dCommon/dEnums/eClientMessageType.h @@ -0,0 +1,76 @@ +#ifndef __ECLIENTMESSAGETYPE__H__ +#define __ECLIENTMESSAGETYPE__H__ + +#include <cstdint> + +enum class eClientMessageType : uint32_t { + LOGIN_RESPONSE = 0, + LOGOUT_RESPONSE, + LOAD_STATIC_ZONE, + CREATE_OBJECT, + CREATE_CHARACTER, + CREATE_CHARACTER_EXTENDED, + CHARACTER_LIST_RESPONSE, + CHARACTER_CREATE_RESPONSE, + CHARACTER_RENAME_RESPONSE, + CHAT_CONNECT_RESPONSE, + AUTH_ACCOUNT_CREATE_RESPONSE, + DELETE_CHARACTER_RESPONSE, + GAME_MSG, + CONNECT_CHAT, + TRANSFER_TO_WORLD, + IMPENDING_RELOAD_NOTIFY, + MAKE_GM_RESPONSE, + HTTP_MONITOR_INFO_RESPONSE, + SLASH_PUSH_MAP_RESPONSE, + SLASH_PULL_MAP_RESPONSE, + SLASH_LOCK_MAP_RESPONSE, + BLUEPRINT_SAVE_RESPONSE, + BLUEPRINT_LUP_SAVE_RESPONSE, + BLUEPRINT_LOAD_RESPONSE_ITEMID, + BLUEPRINT_GET_ALL_DATA_RESPONSE, + MODEL_INSTANTIATE_RESPONSE, + DEBUG_OUTPUT, + ADD_FRIEND_REQUEST, + ADD_FRIEND_RESPONSE, + REMOVE_FRIEND_RESPONSE, + GET_FRIENDS_LIST_RESPONSE, + UPDATE_FRIEND_NOTIFY, + ADD_IGNORE_RESPONSE, + REMOVE_IGNORE_RESPONSE, + GET_IGNORE_LIST_RESPONSE, + TEAM_INVITE, + TEAM_INVITE_INITIAL_RESPONSE, + GUILD_CREATE_RESPONSE, + GUILD_GET_STATUS_RESPONSE, + GUILD_INVITE, + GUILD_INVITE_INITIAL_RESPONSE, + GUILD_INVITE_FINAL_RESPONSE, + GUILD_INVITE_CONFIRM, + GUILD_ADD_PLAYER, + GUILD_REMOVE_PLAYER, + GUILD_LOGIN_LOGOUT, + GUILD_RANK_CHANGE, + GUILD_DATA, + GUILD_STATUS, + MAIL, + DB_PROXY_RESULT, + SHOW_ALL_RESPONSE, + WHO_RESPONSE, + SEND_CANNED_TEXT, + UPDATE_CHARACTER_NAME, + SET_NETWORK_SIMULATOR, + INVALID_CHAT_MESSAGE, + MINIMUM_CHAT_MODE_RESPONSE, + MINIMUM_CHAT_MODE_RESPONSE_PRIVATE, + CHAT_MODERATION_STRING, + UGC_MANIFEST_RESPONSE, + IN_LOGIN_QUEUE, + SERVER_STATES, + GM_CLOSE_TARGET_CHAT_WINDOW, + GENERAL_TEXT_FOR_LOCALIZATION, + UPDATE_FREE_TRIAL_STATUS, + UGC_DOWNLOAD_FAILED = 120 +}; + +#endif //!__ECLIENTMESSAGETYPE__H__ diff --git a/dCommon/dEnums/eConnectionType.h b/dCommon/dEnums/eConnectionType.h new file mode 100644 index 00000000..ce1ff90c --- /dev/null +++ b/dCommon/dEnums/eConnectionType.h @@ -0,0 +1,14 @@ +#ifndef __ECONNECTIONTYPE__H__ +#define __ECONNECTIONTYPE__H__ + +enum class eConnectionType : uint16_t { + SERVER = 0, + AUTH, + CHAT, + CHAT_INTERNAL, + WORLD, + CLIENT, + MASTER +}; + +#endif //!__ECONNECTIONTYPE__H__ diff --git a/dCommon/dEnums/eGameMessageType.h b/dCommon/dEnums/eGameMessageType.h new file mode 100644 index 00000000..247ee5e2 --- /dev/null +++ b/dCommon/dEnums/eGameMessageType.h @@ -0,0 +1,303 @@ +#ifndef __EGAMEMESSAGETYPE__H__ +#define __EGAMEMESSAGETYPE__H__ + +#include <cstdint> + +enum class eGameMessageType : uint16_t { + TELEPORT = 19, + SET_PLAYER_CONTROL_SCHEME = 26, + DROP_CLIENT_LOOT = 30, + DIE = 37, + REQUEST_DIE = 38, + PLAY_EMOTE = 41, + PLAY_ANIMATION = 43, + CONTROL_BEHAVIOR = 48, + SET_NAME = 72, + ECHO_START_SKILL = 118, + START_SKILL = 119, + VERIFY_ACK = 121, + ADD_SKILL = 127, + REMOVE_SKILL = 128, + SET_CURRENCY = 133, + PICKUP_CURRENCY = 137, + PICKUP_ITEM = 139, + TEAM_PICKUP_ITEM = 140, + PLAY_FX_EFFECT = 154, + STOP_FX_EFFECT = 155, + REQUEST_RESURRECT = 159, + RESURRECT = 160, + PUSH_EQUIPPED_ITEMS_STATE = 191, + POP_EQUIPPED_ITEMS_STATE = 192, + SET_GM_LEVEL = 193, + SET_STUNNED = 198, + SET_STUN_IMMUNITY = 200, + KNOCKBACK = 202, + REBUILD_CANCEL = 209, + ENABLE_REBUILD = 213, + MOVE_ITEM_IN_INVENTORY = 224, + ADD_ITEM_TO_INVENTORY_CLIENT_SYNC = 227, + REMOVE_ITEM_FROM_INVENTORY = 230, + EQUIP_ITEM = 231, + UN_EQUIP_ITEM = 233, + OFFER_MISSION = 248, + RESPOND_TO_MISSION = 249, + NOTIFY_MISSION = 254, + NOTIFY_MISSION_TASK = 255, + REBUILD_NOTIFY_STATE = 336, + TERMINATE_INTERACTION = 357, + SERVER_TERMINATE_INTERACTION = 358, + REQUEST_USE = 364, + VENDOR_OPEN_WINDOW = 369, + BUY_FROM_VENDOR = 373, + SELL_TO_VENDOR = 374, + TEAM_SET_OFF_WORLD_FLAG = 383, + SET_INVENTORY_SIZE = 389, + ACKNOWLEDGE_POSSESSION = 391, + SET_SHOOTING_GALLERY_PARAMS = 400, + REQUEST_ACTIVITY_START_STOP = 402, + REQUEST_ACTIVITY_ENTER = 403, + REQUEST_ACTIVITY_EXIT = 404, + ACTIVITY_ENTER = 405, + ACTIVITY_EXIT = 406, + ACTIVITY_START = 407, + ACTIVITY_STOP = 408, + SHOOTING_GALLERY_CLIENT_AIM_UPDATE = 409, + SHOOTING_GALLERY_FIRE = 411, + REQUEST_VENDOR_STATUS_UPDATE = 416, + VENDOR_STATUS_UPDATE = 417, + NOTIFY_CLIENT_SHOOTING_GALLERY_SCORE = 425, + CONSUME_CLIENT_ITEM = 427, + CLIENT_ITEM_CONSUMED = 428, + UPDATE_SHOOTING_GALLERY_ROTATION = 448, + SET_FLAG = 471, + NOTIFY_CLIENT_FLAG_CHANGE = 472, + VENDOR_TRANSACTION_RESULT = 476, + HAS_BEEN_COLLECTED = 486, + DISPLAY_CHAT_BUBBLE = 495, + SPAWN_PET = 498, + DESPAWN_PET = 499, + PLAYER_LOADED = 505, + PLAYER_READY = 509, + REQUEST_LINKED_MISSION = 515, + INVALID_ZONE_TRANSFER_LIST = 519, + MISSION_DIALOGUE_OK = 520, + DISPLAY_MESSAGE_BOX = 529, + MESSAGE_BOX_RESPOND = 530, + CHOICE_BOX_RESPOND = 531, + SMASH = 537, + UNSMASH = 538, + PLACE_MODEL_RESPONSE = 547, + SET_SHOOTING_GALLERY_RETICULE_EFFECT = 548, + SET_JET_PACK_MODE = 561, + REGISTER_PET_ID = 565, + REGISTER_PET_DBID = 566, + SHOW_ACTIVITY_COUNTDOWN = 568, + START_ACTIVITY_TIME = 576, + ACTIVITY_PAUSE = 602, + USE_NON_EQUIPMENT_ITEM = 603, + USE_ITEM_RESULT = 607, + COMMAND_PET = 640, + PET_RESPONSE = 641, + REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA = 648, + SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA = 649, + NOTIFY_OBJECT = 656, + CLIENT_NOTIFY_PET = 659, + NOTIFY_PET = 660, + NOTIFY_PET_TAMING_MINIGAME = 661, + START_SERVER_PET_MINIGAME_TIMER = 662, + CLIENT_EXIT_TAMING_MINIGAME = 663, + PET_NAME_CHANGED = 686, + PET_TAMING_MINIGAME_RESULT = 667, + PET_TAMING_TRY_BUILD_RESULT = 668, + NOTIFY_TAMING_BUILD_SUCCESS = 673, + NOTIFY_TAMING_MODEL_LOADED_ON_SERVER = 674, + ACTIVATE_BUBBLE_BUFF = 678, + DEACTIVATE_BUBBLE_BUFF = 679, + ADD_PET_TO_PLAYER = 681, + REQUEST_SET_PET_NAME = 683, + SET_PET_NAME = 684, + NOTIFY_PET_TAMING_PUZZLE_SELECTED = 675, + SHOW_PET_ACTION_BUTTON = 692, + SET_EMOTE_LOCK_STATE = 693, + USE_ITEM_REQUIREMENTS_RESPONSE = 703, + PLAY_EMBEDDED_EFFECT_ON_ALL_CLIENTS_NEAR_OBJECT = 713, + DOWNLOAD_PROPERTY_DATA = 716, + QUERY_PROPERTY_DATA = 717, + PROPERTY_EDITOR_BEGIN = 724, + PROPERTY_EDITOR_END = 725, + IS_MINIFIG_IN_A_BUBBLE = 729, + START_PATHING = 733, + ACTIVATE_BUBBLE_BUFF_FROM_SERVER = 734, + DEACTIVATE_BUBBLE_BUFF_FROM_SERVER = 735, + NOTIFY_CLIENT_ZONE_OBJECT = 737, + UPDATE_REPUTATION = 746, + PROPERTY_RENTAL_RESPONSE = 750, + REQUEST_PLATFORM_RESYNC = 760, + PLATFORM_RESYNC = 761, + PLAY_CINEMATIC = 762, + END_CINEMATIC = 763, + CINEMATIC_UPDATE = 764, + TOGGLE_GHOST_REFERENCE_OVERRIDE = 767, + SET_GHOST_REFERENCE_POSITION = 768, + FIRE_EVENT_SERVER_SIDE = 770, + SET_NETWORK_SCRIPT_VAR = 781, + UPDATE_MODEL_FROM_CLIENT = 793, + DELETE_MODEL_FROM_CLIENT = 794, + PLAY_ND_AUDIO_EMITTER = 821, + PLAY2_DAMBIENT_SOUND = 831, + ENTER_PROPERTY1 = 840, + ENTER_PROPERTY2 = 841, + PROPERTY_ENTRANCE_SYNC = 842, + PROPERTY_SELECT_QUERY = 845, + PARSE_CHAT_MESSAGE = 850, + BROADCAST_TEXT_TO_CHATBOX = 858, + OPEN_PROPERTY_MANAGEMENT = 860, + OPEN_PROPERTY_VENDOR = 861, + UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK = 863, + CLIENT_TRADE_REQUEST = 868, + SERVER_TRADE_REQUEST = 869, + SERVER_TRADE_INVITE = 870, + CLIENT_TRADE_REPLY = 871, + SERVER_TRADE_REPLY = 872, + SERVER_TRADE_INITIAL_REPLY = 873, + SERVER_TRADE_FINAL_REPLY = 874, + CLIENT_TRADE_UPDATE = 875, + SERVER_SIDE_TRADE_UPDATE = 876, + SERVER_TRADE_UPDATE = 877, + CLIENT_TRADE_CANCEL = 878, + CLIENT_SIDE_TRADE_CANCEL = 879, + CLIENT_TRADE_ACCEPT = 880, + SERVER_SIDE_TRADE_ACCEPT = 881, + SERVER_SIDE_TRADE_CANCEL = 882, + SERVER_TRADE_CANCEL = 883, + SERVER_TRADE_ACCEPT = 884, + READY_FOR_UPDATES = 888, + ORIENT_TO_OBJECT = 905, + ORIENT_TO_POSITION = 906, + ORIENT_TO_ANGLE = 907, + BOUNCER_ACTIVE_STATUS = 942, + UN_USE_BBB_MODEL = 999, + BBB_LOAD_ITEM_REQUEST = 1000, + BBB_SAVE_REQUEST = 1001, + BBB_SAVE_RESPONSE = 1006, + NOTIFY_CLIENT_OBJECT = 1042, + DISPLAY_ZONE_SUMMARY = 1043, + ZONE_SUMMARY_DISMISSED = 1044, + ACTIVITY_STATE_CHANGE_REQUEST = 1053, + MODIFY_PLAYER_ZONE_STATISTIC = 1046, + START_BUILDING_WITH_ITEM = 1057, + START_ARRANGING_WITH_ITEM = 1061, + FINISH_ARRANGING_WITH_ITEM = 1062, + DONE_ARRANGING_WITH_ITEM = 1063, + SET_BUILD_MODE = 1068, + BUILD_MODE_SET = 1069, + SET_BUILD_MODE_CONFIRMED = 1073, + NOTIFY_CLIENT_FAILED_PRECONDITION = 1081, + MOVE_ITEM_BETWEEN_INVENTORY_TYPES = 1093, + MODULAR_BUILD_BEGIN = 1094, + MODULAR_BUILD_END = 1095, + MODULAR_BUILD_MOVE_AND_EQUIP = 1096, + MODULAR_BUILD_FINISH = 1097, + REPORT_BUG = 1198, + MISSION_DIALOGUE_CANCELLED = 1129, + ECHO_SYNC_SKILL = 1144, + SYNC_SKILL = 1145, + REQUEST_SERVER_PROJECTILE_IMPACT = 1148, + DO_CLIENT_PROJECTILE_IMPACT = 1151, + MODULAR_BUILD_CONVERT_MODEL = 1155, + SET_PLAYER_ALLOWED_RESPAWN = 1165, + UI_MESSAGE_SERVER_TO_SINGLE_CLIENT = 1184, + UI_MESSAGE_SERVER_TO_ALL_CLIENTS = 1185, + PET_TAMING_TRY_BUILD = 1197, + REQUEST_SMASH_PLAYER = 1202, + FIRE_EVENT_CLIENT_SIDE = 1213, + TOGGLE_GM_INVIS = 1218, + CHANGE_OBJECT_WORLD_STATE = 1223, + VEHICLE_LOCK_INPUT = 1230, + VEHICLE_UNLOCK_INPUT = 1231, + RACING_RESET_PLAYER_TO_LAST_RESET = 1252, + RACING_SERVER_SET_PLAYER_LAP_AND_PLANE = 1253, + RACING_SET_PLAYER_RESET_INFO = 1254, + RACING_PLAYER_INFO_RESET_FINISHED = 1255, + LOCK_NODE_ROTATION = 1260, + VEHICLE_SET_WHEEL_LOCK_STATE = 1273, + NOTIFY_VEHICLE_OF_RACING_OBJECT = 1276, + SET_NAME_BILLBOARD_STATE = 1284, + PLAYER_REACHED_RESPAWN_CHECKPOINT = 1296, + HANDLE_UGC_EQUIP_POST_DELETE_BASED_ON_EDIT_MODE = 1300, + HANDLE_UGC_EQUIP_PRE_CREATE_BASED_ON_EDIT_MODE = 1301, + PROPERTY_CONTENTS_FROM_CLIENT = 1305, + GET_MODELS_ON_PROPERTY = 1306, + MATCH_REQUEST = 1308, + MATCH_RESPONSE = 1309, + MATCH_UPDATE = 1310, + MODULE_ASSEMBLY_DB_DATA_FOR_CLIENT = 1131, + MODULE_ASSEMBLY_QUERY_DATA = 1132, + SHOW_BILLBOARD_INTERACT_ICON = 1337, + CHANGE_IDLE_FLAGS = 1338, + VEHICLE_ADD_PASSIVE_BOOST_ACTION = 1340, + VEHICLE_REMOVE_PASSIVE_BOOST_ACTION = 1341, + VEHICLE_NOTIFY_SERVER_ADD_PASSIVE_BOOST_ACTION = 1342, + VEHICLE_NOTIFY_SERVER_REMOVE_PASSIVE_BOOST_ACTION = 1343, + VEHICLE_ADD_SLOWDOWN_ACTION = 1344, + VEHICLE_REMOVE_SLOWDOWN_ACTION = 1345, + VEHICLE_NOTIFY_SERVER_ADD_SLOWDOWN_ACTION = 1346, + VEHICLE_NOTIFY_SERVER_REMOVE_SLOWDOWN_ACTION = 1347, + BUYBACK_FROM_VENDOR = 1350, + SET_PROPERTY_ACCESS = 1366, + ZONE_PROPERTY_MODEL_PLACED = 1369, + ZONE_PROPERTY_MODEL_ROTATED = 1370, + ZONE_PROPERTY_MODEL_REMOVED_WHILE_EQUIPPED = 1371, + ZONE_PROPERTY_MODEL_EQUIPPED = 1372, + ZONE_PROPERTY_MODEL_PICKED_UP = 1373, + ZONE_PROPERTY_MODEL_REMOVED = 1374, + NOTIFY_RACING_CLIENT = 1390, + RACING_PLAYER_HACK_CAR = 1391, + RACING_PLAYER_LOADED = 1392, + RACING_CLIENT_READY = 1393, + UPDATE_CHAT_MODE = 1395, + VEHICLE_NOTIFY_FINISHED_RACE = 1396, + SET_CONSUMABLE_ITEM = 1409, + SET_STATUS_IMMUNITY = 1435, + SET_PET_NAME_MODERATED = 1448, + MODIFY_LEGO_SCORE = 1459, + RESTORE_TO_POST_LOAD_STATS = 1468, + SET_RAIL_MOVEMENT = 1471, + START_RAIL_MOVEMENT = 1472, + CANCEL_RAIL_MOVEMENT = 1474, + CLIENT_RAIL_MOVEMENT_READY = 1476, + PLAYER_RAIL_ARRIVED_NOTIFICATION = 1477, + UPDATE_PLAYER_STATISTIC = 1481, + MODULAR_ASSEMBLY_NIF_COMPLETED = 1498, + NOTIFY_NOT_ENOUGH_INV_SPACE = 1516, + TEAM_SET_LEADER = 1557, + TEAM_INVITE_CONFIRM = 1558, + TEAM_GET_STATUS_RESPONSE = 1559, + TEAM_ADD_PLAYER = 1526, + TEAM_REMOVE_PLAYER = 1563, + START_CELEBRATION_EFFECT = 1618, + ADD_BUFF = 1647, + SERVER_DONE_LOADING_ALL_OBJECTS = 1642, + PLACE_PROPERTY_MODEL = 1170, + VEHICLE_NOTIFY_HIT_IMAGINATION_SERVER = 1606, + ADD_RUN_SPEED_MODIFIER = 1505, + HANDLE_HOT_PROPERTY_DATA = 1511, + SEND_HOT_PROPERTY_DATA = 1510, + REMOVE_RUN_SPEED_MODIFIER = 1506, + UPDATE_PROPERTY_PERFORMANCE_COST = 1547, + PROPERTY_ENTRANCE_BEGIN = 1553, + SET_RESURRECT_RESTORE_VALUES = 1591, + VEHICLE_STOP_BOOST = 1617, + REMOVE_BUFF = 1648, + REQUEST_MOVE_ITEM_BETWEEN_INVENTORY_TYPES = 1666, + RESPONSE_MOVE_ITEM_BETWEEN_INVENTORY_TYPES = 1667, + PLAYER_SET_CAMERA_CYCLING_MODE = 1676, + SET_MOUNT_INVENTORY_ID = 1726, + NOTIFY_SERVER_LEVEL_PROCESSING_COMPLETE = 1734, + NOTIFY_LEVEL_REWARDS = 1735, + DISMOUNT_COMPLETE = 1756, + MARK_INVENTORY_ITEM_AS_ACTIVE = 1767, + END +}; + +#endif //!__EGAMEMESSAGETYPE__H__ diff --git a/dCommon/dEnums/eMasterMessageType.h b/dCommon/dEnums/eMasterMessageType.h new file mode 100644 index 00000000..5c867d70 --- /dev/null +++ b/dCommon/dEnums/eMasterMessageType.h @@ -0,0 +1,36 @@ +#ifndef __EMASTERMESSAGETYPE__H__ +#define __EMASTERMESSAGETYPE__H__ + +#include <cstdint> + +enum class eMasterMessageType : uint32_t { + REQUEST_PERSISTENT_ID = 1, + REQUEST_PERSISTENT_ID_RESPONSE, + REQUEST_ZONE_TRANSFER, + REQUEST_ZONE_TRANSFER_RESPONSE, + SERVER_INFO, + REQUEST_SESSION_KEY, + SET_SESSION_KEY, + SESSION_KEY_RESPONSE, + PLAYER_ADDED, + PLAYER_REMOVED, + + CREATE_PRIVATE_ZONE, + REQUEST_PRIVATE_ZONE, + + WORLD_READY, + PREP_ZONE, + + SHUTDOWN, + SHUTDOWN_RESPONSE, + SHUTDOWN_IMMEDIATE, + + SHUTDOWN_UNIVERSE, + + AFFIRM_TRANSFER_REQUEST, + AFFIRM_TRANSFER_RESPONSE, + + NEW_SESSION_ALERT +}; + +#endif //!__EMASTERMESSAGETYPE__H__ diff --git a/dCommon/dEnums/eServerMessageType.h b/dCommon/dEnums/eServerMessageType.h new file mode 100644 index 00000000..7f211ffb --- /dev/null +++ b/dCommon/dEnums/eServerMessageType.h @@ -0,0 +1,12 @@ +#ifndef __ESERVERMESSAGETYPE__H__ +#define __ESERVERMESSAGETYPE__H__ + +#include <cstdint> +//! The Internal Server Packet Identifiers +enum class eServerMessageType : uint32_t { + VERSION_CONFIRM = 0, + DISCONNECT_NOTIFY, + GENERAL_NOTIFY +}; + +#endif //!__ESERVERMESSAGETYPE__H__ diff --git a/dCommon/dEnums/eWorldMessageType.h b/dCommon/dEnums/eWorldMessageType.h new file mode 100644 index 00000000..2a65fd98 --- /dev/null +++ b/dCommon/dEnums/eWorldMessageType.h @@ -0,0 +1,42 @@ +#ifndef __EWORLDMESSAGETYPE__H__ +#define __EWORLDMESSAGETYPE__H__ + +#include <cstdint> + +enum class eWorldMessageType : uint32_t { + VALIDATION = 1, // Session info + CHARACTER_LIST_REQUEST, + CHARACTER_CREATE_REQUEST, + LOGIN_REQUEST, // Character selected + GAME_MSG, + CHARACTER_DELETE_REQUEST, + CHARACTER_RENAME_REQUEST, + HAPPY_FLOWER_MODE_NOTIFY, + SLASH_RELOAD_MAP, // Reload map cmp + SLASH_PUSH_MAP_REQUEST, // Push map req cmd + SLASH_PUSH_MAP, // Push map cmd + SLASH_PULL_MAP, // Pull map cmd + LOCK_MAP_REQUEST, + GENERAL_CHAT_MESSAGE, // General chat message + HTTP_MONITOR_INFO_REQUEST, + SLASH_DEBUG_SCRIPTS, // Debug scripts cmd + MODELS_CLEAR, + EXHIBIT_INSERT_MODEL, + LEVEL_LOAD_COMPLETE, // Character data request + TMP_GUILD_CREATE, + ROUTE_PACKET, // Social? + POSITION_UPDATE, + MAIL, + WORD_CHECK, // Whitelist word check + STRING_CHECK, // Whitelist string check + GET_PLAYERS_IN_ZONE, + REQUEST_UGC_MANIFEST_INFO, + BLUEPRINT_GET_ALL_DATA_REQUEST, + CANCEL_MAP_QUEUE, + HANDLE_FUNNESS, + FAKE_PRG_CSR_MESSAGE, + REQUEST_FREE_TRIAL_REFRESH, + GM_SET_FREE_TRIAL_STATUS +}; + +#endif //!__EWORLDMESSAGETYPE__H__ diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index d57caa67..0161395c 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -22,11 +22,12 @@ #include "SkillComponent.h" #include "AssetManager.h" #include "CDClientDatabase.h" -#include "dMessageIdentifiers.h" #include "eObjectBits.h" #include "eGameMasterLevel.h" #include "eCharacterCreationResponse.h" #include "eRenameResponse.h" +#include "eConnectionType.h" +#include "eChatInternalMessageType.h" UserManager* UserManager::m_Address = nullptr; @@ -422,7 +423,7 @@ void UserManager::DeleteCharacter(const SystemAddress& sysAddr, Packet* packet) stmt->execute(); delete stmt; CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::PLAYER_REMOVED_NOTIFICATION); bitStream.Write(objectID); Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); } diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index d0cb68e4..c7db4208 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -10,12 +10,12 @@ #include <sstream> -#include "dMessageIdentifiers.h" #include "DestroyableComponent.h" #include "EchoSyncSkill.h" #include "PhantomPhysicsComponent.h" #include "RebuildComponent.h" #include "eReplicaComponentType.h" +#include "eConnectionType.h" BehaviorSyncEntry::BehaviorSyncEntry() { } @@ -253,7 +253,7 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) { // Write message RakNet::BitStream message; - PacketUtils::WriteHeader(message, CLIENT, MSG_CLIENT_GAME_MSG); + PacketUtils::WriteHeader(message, eConnectionType::CLIENT, eClientMessageType::GAME_MSG); message.Write(this->originator); echo.Serialize(&message); diff --git a/dGame/dComponents/ModuleAssemblyComponent.h b/dGame/dComponents/ModuleAssemblyComponent.h index c6e217ed..39670c9a 100644 --- a/dGame/dComponents/ModuleAssemblyComponent.h +++ b/dGame/dComponents/ModuleAssemblyComponent.h @@ -14,7 +14,7 @@ class ModuleAssemblyComponent : public Component { public: static const eReplicaComponentType ComponentType = eReplicaComponentType::MODULE_ASSEMBLY; - ModuleAssemblyComponent(Entity* MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); + ModuleAssemblyComponent(Entity* parent); ~ModuleAssemblyComponent() override; void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); diff --git a/dGame/dComponents/RocketLaunchpadControlComponent.cpp b/dGame/dComponents/RocketLaunchpadControlComponent.cpp index 6cc5e2bc..3cac9e42 100644 --- a/dGame/dComponents/RocketLaunchpadControlComponent.cpp +++ b/dGame/dComponents/RocketLaunchpadControlComponent.cpp @@ -15,9 +15,10 @@ #include "PropertyEntranceComponent.h" #include "RocketLaunchLupComponent.h" #include "dServer.h" -#include "dMessageIdentifiers.h" #include "PacketUtils.h" #include "eObjectWorldState.h" +#include "eConnectionType.h" +#include "eMasterMessageType.h" RocketLaunchpadControlComponent::RocketLaunchpadControlComponent(Entity* parent, int rocketId) : Component(parent) { auto query = CDClientDatabase::CreatePreppedStmt( @@ -136,7 +137,7 @@ LWOCLONEID RocketLaunchpadControlComponent::GetSelectedCloneId(LWOOBJID player) void RocketLaunchpadControlComponent::TellMasterToPrepZone(int zoneID) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_PREP_ZONE); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::PREP_ZONE); bitStream.Write(zoneID); Game::server->SendToMaster(&bitStream); } diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index f998d686..eb4ab761 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -18,10 +18,11 @@ #include "dConfig.h" #include "InventoryComponent.h" #include "DestroyableComponent.h" -#include "dMessageIdentifiers.h" #include "Loot.h" #include "eMissionTaskType.h" #include "eMatchUpdate.h" +#include "eConnectionType.h" +#include "eChatInternalMessageType.h" #include "CDCurrencyTableTable.h" #include "CDActivityRewardsTable.h" @@ -517,7 +518,7 @@ void ActivityInstance::StartZone() { // only make a team if we have more than one participant if (participants.size() > 1) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_CREATE_TEAM); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::CREATE_TEAM); bitStream.Write(leader->GetObjectID()); bitStream.Write(m_Participants.size()); diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index dc7c16bd..c2f07425 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -20,11 +20,11 @@ #include "ScriptComponent.h" #include "BuffComponent.h" #include "EchoStartSkill.h" -#include "dMessageIdentifiers.h" #include "DoClientProjectileImpact.h" #include "CDClientManager.h" - #include "CDSkillBehaviorTable.h" +#include "eConnectionType.h" +#include "eClientMessageType.h" ProjectileSyncEntry::ProjectileSyncEntry() { } @@ -304,7 +304,7 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c // Write message RakNet::BitStream message; - PacketUtils::WriteHeader(message, CLIENT, MSG_CLIENT_GAME_MSG); + PacketUtils::WriteHeader(message, eConnectionType::CLIENT, eClientMessageType::GAME_MSG); message.Write(this->m_Parent->GetObjectID()); start.Serialize(&message); @@ -437,7 +437,7 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) RakNet::BitStream message; - PacketUtils::WriteHeader(message, CLIENT, MSG_CLIENT_GAME_MSG); + PacketUtils::WriteHeader(message, eConnectionType::CLIENT, eClientMessageType::GAME_MSG); message.Write(this->m_Parent->GetObjectID()); projectileImpact.Serialize(&message); diff --git a/dGame/dGameMessages/DoClientProjectileImpact.h b/dGame/dGameMessages/DoClientProjectileImpact.h index 436e3dd2..6b381aa5 100644 --- a/dGame/dGameMessages/DoClientProjectileImpact.h +++ b/dGame/dGameMessages/DoClientProjectileImpact.h @@ -1,13 +1,10 @@ #ifndef __DOCLIENTPROJECTILEIMPACT__H__ #define __DOCLIENTPROJECTILEIMPACT__H__ -#include "dMessageIdentifiers.h" #include "dCommonVars.h" /* Tell a client local projectile to impact */ class DoClientProjectileImpact { - static const GAME_MSG MsgID = GAME_MSG_DO_CLIENT_PROJECTILE_IMPACT; - public: DoClientProjectileImpact() { i64OrgID = LWOOBJID_EMPTY; @@ -30,7 +27,7 @@ public: } void Serialize(RakNet::BitStream* stream) { - stream->Write(MsgID); + stream->Write(eGameMessageType::DO_CLIENT_PROJECTILE_IMPACT); stream->Write(i64OrgID != LWOOBJID_EMPTY); if (i64OrgID != LWOOBJID_EMPTY) stream->Write(i64OrgID); diff --git a/dGame/dGameMessages/EchoStartSkill.h b/dGame/dGameMessages/EchoStartSkill.h index 6d912798..f5dee816 100644 --- a/dGame/dGameMessages/EchoStartSkill.h +++ b/dGame/dGameMessages/EchoStartSkill.h @@ -2,14 +2,12 @@ #define __ECHOSTARTSKILL__H__ #include "dCommonVars.h" -#include "dMessageIdentifiers.h" #include "NiPoint3.h" #include "NiQuaternion.h" +#include "eGameMessageType.h" /* Same as start skill but with different network options. An echo down to other clients that need to play the skill. */ class EchoStartSkill { - static const GAME_MSG MsgID = GAME_MSG_ECHO_START_SKILL; - public: EchoStartSkill() { bUsedMouse = false; @@ -42,7 +40,7 @@ public: } void Serialize(RakNet::BitStream* stream) { - stream->Write(MsgID); + stream->Write(eGameMessageType::ECHO_START_SKILL); stream->Write(bUsedMouse); diff --git a/dGame/dGameMessages/EchoSyncSkill.h b/dGame/dGameMessages/EchoSyncSkill.h index b56beae8..ab5a3f2b 100644 --- a/dGame/dGameMessages/EchoSyncSkill.h +++ b/dGame/dGameMessages/EchoSyncSkill.h @@ -4,13 +4,11 @@ #include <string> #include "BitStream.h" +#include "eGameMessageType.h" -#include "dMessageIdentifiers.h" /* Message to synchronize a skill cast */ class EchoSyncSkill { - static const GAME_MSG MsgID = GAME_MSG_ECHO_SYNC_SKILL; - public: EchoSyncSkill() { bDone = false; @@ -31,7 +29,7 @@ public: } void Serialize(RakNet::BitStream* stream) { - stream->Write(MsgID); + stream->Write(eGameMessageType::ECHO_SYNC_SKILL); stream->Write(bDone); uint32_t sBitStreamLength = sBitStream.length(); diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index c0893a09..50c7876b 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -33,10 +33,11 @@ #include "EchoSyncSkill.h" #include "eMissionTaskType.h" #include "eReplicaComponentType.h" +#include "eConnectionType.h" using namespace std; -void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, GAME_MSG messageID) { +void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, eGameMessageType messageID) { CBITSTREAM; @@ -53,54 +54,54 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System switch (messageID) { - case GAME_MSG_UN_USE_BBB_MODEL: { + case eGameMessageType::UN_USE_BBB_MODEL: { GameMessages::HandleUnUseModel(inStream, entity, sysAddr); break; } - case GAME_MSG_PLAY_EMOTE: { + case eGameMessageType::PLAY_EMOTE: { GameMessages::HandlePlayEmote(inStream, entity); break; } - case GAME_MSG_MOVE_ITEM_IN_INVENTORY: { + case eGameMessageType::MOVE_ITEM_IN_INVENTORY: { GameMessages::HandleMoveItemInInventory(inStream, entity); break; } - case GAME_MSG_REMOVE_ITEM_FROM_INVENTORY: { + case eGameMessageType::REMOVE_ITEM_FROM_INVENTORY: { GameMessages::HandleRemoveItemFromInventory(inStream, entity, sysAddr); break; } - case GAME_MSG_EQUIP_ITEM: + case eGameMessageType::EQUIP_ITEM: GameMessages::HandleEquipItem(inStream, entity); break; - case GAME_MSG_UN_EQUIP_ITEM: + case eGameMessageType::UN_EQUIP_ITEM: GameMessages::HandleUnequipItem(inStream, entity); break; - case GAME_MSG_RESPOND_TO_MISSION: { + case eGameMessageType::RESPOND_TO_MISSION: { GameMessages::HandleRespondToMission(inStream, entity); break; } - case GAME_MSG_REQUEST_USE: { + case eGameMessageType::REQUEST_USE: { GameMessages::HandleRequestUse(inStream, entity, sysAddr); break; } - case GAME_MSG_SET_FLAG: { + case eGameMessageType::SET_FLAG: { GameMessages::HandleSetFlag(inStream, entity); break; } - case GAME_MSG_HAS_BEEN_COLLECTED: { + case eGameMessageType::HAS_BEEN_COLLECTED: { GameMessages::HandleHasBeenCollected(inStream, entity); break; } - case GAME_MSG_PLAYER_LOADED: { + case eGameMessageType::PLAYER_LOADED: { GameMessages::SendRestoreToPostLoadStats(entity, sysAddr); entity->SetPlayerReadyForUpdates(); @@ -174,73 +175,73 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System break; } - case GAME_MSG_REQUEST_LINKED_MISSION: { + case eGameMessageType::REQUEST_LINKED_MISSION: { GameMessages::HandleRequestLinkedMission(inStream, entity); break; } - case GAME_MSG_MISSION_DIALOGUE_OK: { + case eGameMessageType::MISSION_DIALOGUE_OK: { GameMessages::HandleMissionDialogOK(inStream, entity); break; } - case GAME_MSG_MISSION_DIALOGUE_CANCELLED: { + case eGameMessageType::MISSION_DIALOGUE_CANCELLED: { //This message is pointless for our implementation, as the client just carries on after //rejecting a mission offer. We dont need to do anything. This is just here to remove a warning in our logs :) break; } - case GAME_MSG_REQUEST_PLATFORM_RESYNC: { + case eGameMessageType::REQUEST_PLATFORM_RESYNC: { GameMessages::HandleRequestPlatformResync(inStream, entity, sysAddr); break; } - case GAME_MSG_FIRE_EVENT_SERVER_SIDE: { + case eGameMessageType::FIRE_EVENT_SERVER_SIDE: { GameMessages::HandleFireEventServerSide(inStream, entity, sysAddr); break; } - case GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { + case eGameMessageType::SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { GameMessages::HandleActivitySummaryLeaderboardData(inStream, entity, sysAddr); break; } - case GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { + case eGameMessageType::REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA: { GameMessages::HandleRequestActivitySummaryLeaderboardData(inStream, entity, sysAddr); break; } - case GAME_MSG_ACTIVITY_STATE_CHANGE_REQUEST: { + case eGameMessageType::ACTIVITY_STATE_CHANGE_REQUEST: { GameMessages::HandleActivityStateChangeRequest(inStream, entity); break; } - case GAME_MSG_PARSE_CHAT_MESSAGE: { + case eGameMessageType::PARSE_CHAT_MESSAGE: { GameMessages::HandleParseChatMessage(inStream, entity, sysAddr); break; } - case GAME_MSG_NOTIFY_SERVER_LEVEL_PROCESSING_COMPLETE: { + case eGameMessageType::NOTIFY_SERVER_LEVEL_PROCESSING_COMPLETE: { GameMessages::HandleNotifyServerLevelProcessingComplete(inStream, entity); break; } - case GAME_MSG_PICKUP_CURRENCY: { + case eGameMessageType::PICKUP_CURRENCY: { GameMessages::HandlePickupCurrency(inStream, entity); break; } - case GAME_MSG_PICKUP_ITEM: { + case eGameMessageType::PICKUP_ITEM: { GameMessages::HandlePickupItem(inStream, entity); break; } - case GAME_MSG_RESURRECT: { + case eGameMessageType::RESURRECT: { GameMessages::HandleResurrect(inStream, entity); break; } - case GAME_MSG_REQUEST_RESURRECT: { + case eGameMessageType::REQUEST_RESURRECT: { GameMessages::SendResurrect(entity); /*auto* dest = static_cast<DestroyableComponent*>(entity->GetComponent(eReplicaComponentType::DESTROYABLE)); if (dest) { @@ -251,12 +252,12 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System }*/ break; } - case GAME_MSG_HANDLE_HOT_PROPERTY_DATA: { + case eGameMessageType::HANDLE_HOT_PROPERTY_DATA: { GameMessages::HandleGetHotPropertyData(inStream, entity, sysAddr); break; } - case GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT: + case eGameMessageType::REQUEST_SERVER_PROJECTILE_IMPACT: { auto message = RequestServerProjectileImpact(); @@ -275,7 +276,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System break; } - case GAME_MSG_START_SKILL: { + case eGameMessageType::START_SKILL: { StartSkill startSkill = StartSkill(); startSkill.Deserialize(inStream); // inStream replaces &bitStream @@ -313,7 +314,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System if (success) { //Broadcast our startSkill: RakNet::BitStream bitStreamLocal; - PacketUtils::WriteHeader(bitStreamLocal, CLIENT, MSG_CLIENT_GAME_MSG); + PacketUtils::WriteHeader(bitStreamLocal, eConnectionType::CLIENT, eClientMessageType::GAME_MSG); bitStreamLocal.Write(entity->GetObjectID()); EchoStartSkill echoStartSkill; @@ -333,11 +334,11 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System } } break; - case GAME_MSG_SYNC_SKILL: { + case eGameMessageType::SYNC_SKILL: { RakNet::BitStream bitStreamLocal; - PacketUtils::WriteHeader(bitStreamLocal, CLIENT, MSG_CLIENT_GAME_MSG); + PacketUtils::WriteHeader(bitStreamLocal, eConnectionType::CLIENT, eClientMessageType::GAME_MSG); bitStreamLocal.Write(entity->GetObjectID()); - //bitStreamLocal.Write((unsigned short)GAME_MSG_ECHO_SYNC_SKILL); + //bitStreamLocal.Write((unsigned short)eGameMessageType::ECHO_SYNC_SKILL); //bitStreamLocal.Write(inStream); SyncSkill sync = SyncSkill(inStream); // inStream replaced &bitStream @@ -374,306 +375,306 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System Game::server->Send(&bitStreamLocal, sysAddr, true); } break; - case GAME_MSG_REQUEST_SMASH_PLAYER: + case eGameMessageType::REQUEST_SMASH_PLAYER: entity->Smash(entity->GetObjectID()); break; - case GAME_MSG_MOVE_ITEM_BETWEEN_INVENTORY_TYPES: + case eGameMessageType::MOVE_ITEM_BETWEEN_INVENTORY_TYPES: GameMessages::HandleMoveItemBetweenInventoryTypes(inStream, entity, sysAddr); break; - case GAME_MSG_MODULAR_BUILD_FINISH: + case eGameMessageType::MODULAR_BUILD_FINISH: GameMessages::HandleModularBuildFinish(inStream, entity, sysAddr); break; - case GAME_MSG_PUSH_EQUIPPED_ITEMS_STATE: + case eGameMessageType::PUSH_EQUIPPED_ITEMS_STATE: GameMessages::HandlePushEquippedItemsState(inStream, entity); break; - case GAME_MSG_POP_EQUIPPED_ITEMS_STATE: + case eGameMessageType::POP_EQUIPPED_ITEMS_STATE: GameMessages::HandlePopEquippedItemsState(inStream, entity); break; - case GAME_MSG_BUY_FROM_VENDOR: + case eGameMessageType::BUY_FROM_VENDOR: GameMessages::HandleBuyFromVendor(inStream, entity, sysAddr); break; - case GAME_MSG_SELL_TO_VENDOR: + case eGameMessageType::SELL_TO_VENDOR: GameMessages::HandleSellToVendor(inStream, entity, sysAddr); break; - case GAME_MSG_BUYBACK_FROM_VENDOR: + case eGameMessageType::BUYBACK_FROM_VENDOR: GameMessages::HandleBuybackFromVendor(inStream, entity, sysAddr); break; - case GAME_MSG_MODULAR_BUILD_MOVE_AND_EQUIP: + case eGameMessageType::MODULAR_BUILD_MOVE_AND_EQUIP: GameMessages::HandleModularBuildMoveAndEquip(inStream, entity, sysAddr); break; - case GAME_MSG_DONE_ARRANGING_WITH_ITEM: + case eGameMessageType::DONE_ARRANGING_WITH_ITEM: GameMessages::HandleDoneArrangingWithItem(inStream, entity, sysAddr); break; - case GAME_MSG_MODULAR_BUILD_CONVERT_MODEL: + case eGameMessageType::MODULAR_BUILD_CONVERT_MODEL: GameMessages::HandleModularBuildConvertModel(inStream, entity, sysAddr); break; - case GAME_MSG_BUILD_MODE_SET: + case eGameMessageType::BUILD_MODE_SET: GameMessages::HandleBuildModeSet(inStream, entity); break; - case GAME_MSG_REBUILD_CANCEL: + case eGameMessageType::REBUILD_CANCEL: GameMessages::HandleRebuildCancel(inStream, entity); break; - case GAME_MSG_MATCH_REQUEST: + case eGameMessageType::MATCH_REQUEST: GameMessages::HandleMatchRequest(inStream, entity); break; - case GAME_MSG_USE_NON_EQUIPMENT_ITEM: + case eGameMessageType::USE_NON_EQUIPMENT_ITEM: GameMessages::HandleUseNonEquipmentItem(inStream, entity); break; - case GAME_MSG_CLIENT_ITEM_CONSUMED: + case eGameMessageType::CLIENT_ITEM_CONSUMED: GameMessages::HandleClientItemConsumed(inStream, entity); break; - case GAME_MSG_SET_CONSUMABLE_ITEM: + case eGameMessageType::SET_CONSUMABLE_ITEM: GameMessages::HandleSetConsumableItem(inStream, entity, sysAddr); break; - case GAME_MSG_VERIFY_ACK: + case eGameMessageType::VERIFY_ACK: GameMessages::HandleVerifyAck(inStream, entity, sysAddr); break; // Trading - case GAME_MSG_CLIENT_TRADE_REQUEST: + case eGameMessageType::CLIENT_TRADE_REQUEST: GameMessages::HandleClientTradeRequest(inStream, entity, sysAddr); break; - case GAME_MSG_CLIENT_TRADE_CANCEL: + case eGameMessageType::CLIENT_TRADE_CANCEL: GameMessages::HandleClientTradeCancel(inStream, entity, sysAddr); break; - case GAME_MSG_CLIENT_TRADE_ACCEPT: + case eGameMessageType::CLIENT_TRADE_ACCEPT: GameMessages::HandleClientTradeAccept(inStream, entity, sysAddr); break; - case GAME_MSG_CLIENT_TRADE_UPDATE: + case eGameMessageType::CLIENT_TRADE_UPDATE: GameMessages::HandleClientTradeUpdate(inStream, entity, sysAddr); break; // Pets - case GAME_MSG_PET_TAMING_TRY_BUILD: + case eGameMessageType::PET_TAMING_TRY_BUILD: GameMessages::HandlePetTamingTryBuild(inStream, entity, sysAddr); break; - case GAME_MSG_NOTIFY_TAMING_BUILD_SUCCESS: + case eGameMessageType::NOTIFY_TAMING_BUILD_SUCCESS: GameMessages::HandleNotifyTamingBuildSuccess(inStream, entity, sysAddr); break; - case GAME_MSG_REQUEST_SET_PET_NAME: + case eGameMessageType::REQUEST_SET_PET_NAME: GameMessages::HandleRequestSetPetName(inStream, entity, sysAddr); break; - case GAME_MSG_START_SERVER_PET_MINIGAME_TIMER: + case eGameMessageType::START_SERVER_PET_MINIGAME_TIMER: GameMessages::HandleStartServerPetMinigameTimer(inStream, entity, sysAddr); break; - case GAME_MSG_CLIENT_EXIT_TAMING_MINIGAME: + case eGameMessageType::CLIENT_EXIT_TAMING_MINIGAME: GameMessages::HandleClientExitTamingMinigame(inStream, entity, sysAddr); break; - case GAME_MSG_COMMAND_PET: + case eGameMessageType::COMMAND_PET: GameMessages::HandleCommandPet(inStream, entity, sysAddr); break; - case GAME_MSG_DESPAWN_PET: + case eGameMessageType::DESPAWN_PET: GameMessages::HandleDespawnPet(inStream, entity, sysAddr); break; - case GAME_MSG_MESSAGE_BOX_RESPOND: + case eGameMessageType::MESSAGE_BOX_RESPOND: GameMessages::HandleMessageBoxResponse(inStream, entity, sysAddr); break; - case GAME_MSG_CHOICE_BOX_RESPOND: + case eGameMessageType::CHOICE_BOX_RESPOND: GameMessages::HandleChoiceBoxRespond(inStream, entity, sysAddr); break; // Property - case GAME_MSG_QUERY_PROPERTY_DATA: + case eGameMessageType::QUERY_PROPERTY_DATA: GameMessages::HandleQueryPropertyData(inStream, entity, sysAddr); break; - case GAME_MSG_START_BUILDING_WITH_ITEM: + case eGameMessageType::START_BUILDING_WITH_ITEM: GameMessages::HandleStartBuildingWithItem(inStream, entity, sysAddr); break; - case GAME_MSG_SET_BUILD_MODE: + case eGameMessageType::SET_BUILD_MODE: GameMessages::HandleSetBuildMode(inStream, entity, sysAddr); break; - case GAME_MSG_PROPERTY_EDITOR_BEGIN: + case eGameMessageType::PROPERTY_EDITOR_BEGIN: GameMessages::HandlePropertyEditorBegin(inStream, entity, sysAddr); break; - case GAME_MSG_PROPERTY_EDITOR_END: + case eGameMessageType::PROPERTY_EDITOR_END: GameMessages::HandlePropertyEditorEnd(inStream, entity, sysAddr); break; - case GAME_MSG_PROPERTY_CONTENTS_FROM_CLIENT: + case eGameMessageType::PROPERTY_CONTENTS_FROM_CLIENT: GameMessages::HandlePropertyContentsFromClient(inStream, entity, sysAddr); break; - case GAME_MSG_ZONE_PROPERTY_MODEL_EQUIPPED: + case eGameMessageType::ZONE_PROPERTY_MODEL_EQUIPPED: GameMessages::HandlePropertyModelEquipped(inStream, entity, sysAddr); break; - case GAME_MSG_PLACE_PROPERTY_MODEL: + case eGameMessageType::PLACE_PROPERTY_MODEL: GameMessages::HandlePlacePropertyModel(inStream, entity, sysAddr); break; - case GAME_MSG_UPDATE_MODEL_FROM_CLIENT: + case eGameMessageType::UPDATE_MODEL_FROM_CLIENT: GameMessages::HandleUpdatePropertyModel(inStream, entity, sysAddr); break; - case GAME_MSG_DELETE_MODEL_FROM_CLIENT: + case eGameMessageType::DELETE_MODEL_FROM_CLIENT: GameMessages::HandleDeletePropertyModel(inStream, entity, sysAddr); break; - case GAME_MSG_BBB_LOAD_ITEM_REQUEST: + case eGameMessageType::BBB_LOAD_ITEM_REQUEST: GameMessages::HandleBBBLoadItemRequest(inStream, entity, sysAddr); break; - case GAME_MSG_BBB_SAVE_REQUEST: + case eGameMessageType::BBB_SAVE_REQUEST: GameMessages::HandleBBBSaveRequest(inStream, entity, sysAddr); break; - case GAME_MSG_CONTROL_BEHAVIOR: + case eGameMessageType::CONTROL_BEHAVIOR: GameMessages::HandleControlBehaviors(inStream, entity, sysAddr); break; - case GAME_MSG_PROPERTY_ENTRANCE_SYNC: + case eGameMessageType::PROPERTY_ENTRANCE_SYNC: GameMessages::HandlePropertyEntranceSync(inStream, entity, sysAddr); break; - case GAME_MSG_ENTER_PROPERTY1: + case eGameMessageType::ENTER_PROPERTY1: GameMessages::HandleEnterProperty(inStream, entity, sysAddr); break; - case GAME_MSG_ZONE_PROPERTY_MODEL_ROTATED: + case eGameMessageType::ZONE_PROPERTY_MODEL_ROTATED: EntityManager::Instance()->GetZoneControlEntity()->OnZonePropertyModelRotated(usr->GetLastUsedChar()->GetEntity()); break; - case GAME_MSG_UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK: + case eGameMessageType::UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK: GameMessages::HandleUpdatePropertyOrModelForFilterCheck(inStream, entity, sysAddr); break; - case GAME_MSG_SET_PROPERTY_ACCESS: + case eGameMessageType::SET_PROPERTY_ACCESS: GameMessages::HandleSetPropertyAccess(inStream, entity, sysAddr); break; // Racing - case GAME_MSG_MODULE_ASSEMBLY_QUERY_DATA: + case eGameMessageType::MODULE_ASSEMBLY_QUERY_DATA: GameMessages::HandleModuleAssemblyQueryData(inStream, entity, sysAddr); break; - case GAME_MSG_ACKNOWLEDGE_POSSESSION: + case eGameMessageType::ACKNOWLEDGE_POSSESSION: GameMessages::HandleAcknowledgePossession(inStream, entity, sysAddr); break; - case GAME_MSG_VEHICLE_SET_WHEEL_LOCK_STATE: + case eGameMessageType::VEHICLE_SET_WHEEL_LOCK_STATE: GameMessages::HandleVehicleSetWheelLockState(inStream, entity, sysAddr); break; - case GAME_MSG_MODULAR_ASSEMBLY_NIF_COMPLETED: + case eGameMessageType::MODULAR_ASSEMBLY_NIF_COMPLETED: GameMessages::HandleModularAssemblyNIFCompleted(inStream, entity, sysAddr); break; - case GAME_MSG_RACING_CLIENT_READY: + case eGameMessageType::RACING_CLIENT_READY: GameMessages::HandleRacingClientReady(inStream, entity, sysAddr); break; - case GAME_MSG_REQUEST_DIE: + case eGameMessageType::REQUEST_DIE: GameMessages::HandleRequestDie(inStream, entity, sysAddr); break; - case GAME_MSG_VEHICLE_NOTIFY_SERVER_ADD_PASSIVE_BOOST_ACTION: + case eGameMessageType::VEHICLE_NOTIFY_SERVER_ADD_PASSIVE_BOOST_ACTION: GameMessages::HandleVehicleNotifyServerAddPassiveBoostAction(inStream, entity, sysAddr); break; - case GAME_MSG_VEHICLE_NOTIFY_SERVER_REMOVE_PASSIVE_BOOST_ACTION: + case eGameMessageType::VEHICLE_NOTIFY_SERVER_REMOVE_PASSIVE_BOOST_ACTION: GameMessages::HandleVehicleNotifyServerRemovePassiveBoostAction(inStream, entity, sysAddr); break; - case GAME_MSG_RACING_PLAYER_INFO_RESET_FINISHED: + case eGameMessageType::RACING_PLAYER_INFO_RESET_FINISHED: GameMessages::HandleRacingPlayerInfoResetFinished(inStream, entity, sysAddr); break; - case GAME_MSG_VEHICLE_NOTIFY_HIT_IMAGINATION_SERVER: + case eGameMessageType::VEHICLE_NOTIFY_HIT_IMAGINATION_SERVER: GameMessages::HandleVehicleNotifyHitImaginationServer(inStream, entity, sysAddr); break; - case GAME_MSG_UPDATE_PROPERTY_PERFORMANCE_COST: + case eGameMessageType::UPDATE_PROPERTY_PERFORMANCE_COST: GameMessages::HandleUpdatePropertyPerformanceCost(inStream, entity, sysAddr); break; // SG - case GAME_MSG_UPDATE_SHOOTING_GALLERY_ROTATION: + case eGameMessageType::UPDATE_SHOOTING_GALLERY_ROTATION: GameMessages::HandleUpdateShootingGalleryRotation(inStream, entity, sysAddr); break; // NT - case GAME_MSG_REQUEST_MOVE_ITEM_BETWEEN_INVENTORY_TYPES: + case eGameMessageType::REQUEST_MOVE_ITEM_BETWEEN_INVENTORY_TYPES: GameMessages::HandleRequestMoveItemBetweenInventoryTypes(inStream, entity, sysAddr); break; - case GAME_MSG_TOGGLE_GHOST_REFERENCE_OVERRIDE: + case eGameMessageType::TOGGLE_GHOST_REFERENCE_OVERRIDE: GameMessages::HandleToggleGhostReferenceOverride(inStream, entity, sysAddr); break; - case GAME_MSG_SET_GHOST_REFERENCE_POSITION: + case eGameMessageType::SET_GHOST_REFERENCE_POSITION: GameMessages::HandleSetGhostReferencePosition(inStream, entity, sysAddr); break; - case GAME_MSG_READY_FOR_UPDATES: + case eGameMessageType::READY_FOR_UPDATES: //We don't really care about this message, as it's simply here to inform us that the client is done loading an object. //In the event we _do_ send an update to an object that hasn't finished loading, the client will handle it anyway. break; - case GAME_MSG_REPORT_BUG: + case eGameMessageType::REPORT_BUG: GameMessages::HandleReportBug(inStream, entity); break; - case GAME_MSG_CLIENT_RAIL_MOVEMENT_READY: + case eGameMessageType::CLIENT_RAIL_MOVEMENT_READY: GameMessages::HandleClientRailMovementReady(inStream, entity, sysAddr); break; - case GAME_MSG_CANCEL_RAIL_MOVEMENT: + case eGameMessageType::CANCEL_RAIL_MOVEMENT: GameMessages::HandleCancelRailMovement(inStream, entity, sysAddr); break; - case GAME_MSG_PLAYER_RAIL_ARRIVED_NOTIFICATION: + case eGameMessageType::PLAYER_RAIL_ARRIVED_NOTIFICATION: GameMessages::HandlePlayerRailArrivedNotification(inStream, entity, sysAddr); break; - case GAME_MSG_CINEMATIC_UPDATE: + case eGameMessageType::CINEMATIC_UPDATE: GameMessages::HandleCinematicUpdate(inStream, entity, sysAddr); break; - case GAME_MSG_MODIFY_PLAYER_ZONE_STATISTIC: + case eGameMessageType::MODIFY_PLAYER_ZONE_STATISTIC: GameMessages::HandleModifyPlayerZoneStatistic(inStream, entity); break; - case GAME_MSG_UPDATE_PLAYER_STATISTIC: + case eGameMessageType::UPDATE_PLAYER_STATISTIC: GameMessages::HandleUpdatePlayerStatistic(inStream, entity); break; - case GAME_MSG_DISMOUNT_COMPLETE: + case eGameMessageType::DISMOUNT_COMPLETE: GameMessages::HandleDismountComplete(inStream, entity, sysAddr); break; - case GAME_MSG_DEACTIVATE_BUBBLE_BUFF: + case eGameMessageType::DEACTIVATE_BUBBLE_BUFF: GameMessages::HandleDeactivateBubbleBuff(inStream, entity); break; - case GAME_MSG_ACTIVATE_BUBBLE_BUFF: + case eGameMessageType::ACTIVATE_BUBBLE_BUFF: GameMessages::HandleActivateBubbleBuff(inStream, entity); break; - case GAME_MSG_ZONE_SUMMARY_DISMISSED: + case eGameMessageType::ZONE_SUMMARY_DISMISSED: GameMessages::HandleZoneSummaryDismissed(inStream, entity); break; default: diff --git a/dGame/dGameMessages/GameMessageHandler.h b/dGame/dGameMessages/GameMessageHandler.h index 063e97f6..8b6685cb 100644 --- a/dGame/dGameMessages/GameMessageHandler.h +++ b/dGame/dGameMessages/GameMessageHandler.h @@ -7,7 +7,6 @@ #define GAMEMESSAGEHANDLER_H #include "RakNetTypes.h" -#include "dMessageIdentifiers.h" #include "dCommonVars.h" #include <iostream> #include <sstream> @@ -21,8 +20,10 @@ #include "GameMessages.h" #include "../dDatabase/CDClientDatabase.h" +enum class eGameMessageType : uint16_t; + namespace GameMessageHandler { - void HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, GAME_MSG messageID); + void HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, eGameMessageType messageID); }; #endif // GAMEMESSAGEHANDLER_H diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 3475c471..caab6459 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -4,7 +4,6 @@ #include "PacketUtils.h" #include "BitStream.h" #include "Game.h" -#include "dMessageIdentifiers.h" #include "SlashCommandHandler.h" #include "NiPoint3.h" #include "NiQuaternion.h" @@ -42,6 +41,7 @@ #include "eQuickBuildFailReason.h" #include "eControlScheme.h" #include "eStateChangeType.h" +#include "eConnectionType.h" #include <sstream> #include <future> @@ -89,6 +89,8 @@ #include "eAninmationFlags.h" #include "AMFFormat_BitStream.h" #include "eReplicaComponentType.h" +#include "eClientMessageType.h" +#include "eGameMessageType.h" #include "CDComponentsRegistryTable.h" #include "CDObjectsTable.h" @@ -98,7 +100,7 @@ void GameMessages::SendFireEventClientSide(const LWOOBJID& objectID, const Syste CMSGHEADER; bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_FIRE_EVENT_CLIENT_SIDE); + bitStream.Write(eGameMessageType::FIRE_EVENT_CLIENT_SIDE); //bitStream.Write(args); uint32_t argSize = args.size(); @@ -120,7 +122,7 @@ void GameMessages::SendTeleport(const LWOOBJID& objectID, const NiPoint3& pos, c CBITSTREAM; CMSGHEADER; bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_TELEPORT); + bitStream.Write(eGameMessageType::TELEPORT); bool bIgnoreY = (pos.y == 0.0f); bool bUseNavmesh = false; @@ -158,7 +160,6 @@ void GameMessages::SendPlayAnimation(Entity* entity, const std::u16string& anima //Stolen from the old DLU codebase as the new one's autogenerated code doesn't work properly for animationIDs longer than 6 characters. CBITSTREAM; CMSGHEADER; - uint16_t gameMsgID = GAME_MSG_PLAY_ANIMATION; std::string sAnimationID = GeneralUtils::UTF16ToWTF8(animationName); uint32_t animationIDLength = sAnimationID.size(); @@ -167,7 +168,7 @@ void GameMessages::SendPlayAnimation(Entity* entity, const std::u16string& anima bool bTriggerOnCompleteMsg = false; bitStream.Write(entity->GetObjectID()); - bitStream.Write(gameMsgID); + bitStream.Write(eGameMessageType::PLAY_ANIMATION); bitStream.Write(animationIDLength); PacketUtils::WriteWString(bitStream, animationName, animationIDLength); @@ -191,7 +192,7 @@ void GameMessages::SendPlayerReady(Entity* entity, const SystemAddress& sysAddr) CBITSTREAM; CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_PLAYER_READY); + bitStream.Write(eGameMessageType::PLAYER_READY); SEND_PACKET; } @@ -200,7 +201,7 @@ void GameMessages::SendPlayerAllowedRespawn(LWOOBJID entityID, bool doNotPromptR CMSGHEADER; bitStream.Write(entityID); - bitStream.Write(GAME_MSG::GAME_MSG_SET_PLAYER_ALLOWED_RESPAWN); + bitStream.Write(eGameMessageType::SET_PLAYER_ALLOWED_RESPAWN); bitStream.Write(doNotPromptRespawn); SEND_PACKET; @@ -211,7 +212,7 @@ void GameMessages::SendInvalidZoneTransferList(Entity* entity, const SystemAddre CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_INVALID_ZONE_TRANSFER_LIST); + bitStream.Write(eGameMessageType::INVALID_ZONE_TRANSFER_LIST); uint32_t CustomerFeedbackURLLength = feedbackURL.size(); bitStream.Write(CustomerFeedbackURLLength); @@ -236,7 +237,7 @@ void GameMessages::SendKnockback(const LWOOBJID& objectID, const LWOOBJID& caste CMSGHEADER; bitStream.Write(objectID); - bitStream.Write(GAME_MSG_KNOCKBACK); + bitStream.Write(eGameMessageType::KNOCKBACK); bool casterFlag = caster != LWOOBJID_EMPTY; bool originatorFlag = originator != LWOOBJID_EMPTY; @@ -272,7 +273,7 @@ void GameMessages::SendStartArrangingWithItem( CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_START_ARRANGING_WITH_ITEM); + bitStream.Write(eGameMessageType::START_ARRANGING_WITH_ITEM); bitStream.Write(bFirstTime); bitStream.Write(buildAreaID != LWOOBJID_EMPTY); @@ -296,7 +297,7 @@ void GameMessages::SendPlayerSetCameraCyclingMode(const LWOOBJID& objectID, cons CMSGHEADER; bitStream.Write(objectID); - bitStream.Write(GAME_MSG_PLAYER_SET_CAMERA_CYCLING_MODE); + bitStream.Write(eGameMessageType::PLAYER_SET_CAMERA_CYCLING_MODE); bitStream.Write(bAllowCyclingWhileDeadOnly); @@ -313,7 +314,7 @@ void GameMessages::SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& s CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_PLAY_ND_AUDIO_EMITTER); + bitStream.Write((uint16_t)eGameMessageType::PLAY_ND_AUDIO_EMITTER); bitStream.Write0(); bitStream.Write0(); @@ -342,7 +343,7 @@ void GameMessages::SendStartPathing(Entity* entity) { CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write<uint16_t>(GAME_MSG_START_PATHING); + bitStream.Write(eGameMessageType::START_PATHING); SEND_PACKET_BROADCAST; } @@ -364,7 +365,7 @@ void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAd } bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_PLATFORM_RESYNC); + bitStream.Write((uint16_t)eGameMessageType::PLATFORM_RESYNC); bool bReverse = false; int eCommand = 0; @@ -405,7 +406,7 @@ void GameMessages::SendRestoreToPostLoadStats(Entity* entity, const SystemAddres CBITSTREAM; CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_RESTORE_TO_POST_LOAD_STATS); + bitStream.Write(eGameMessageType::RESTORE_TO_POST_LOAD_STATS); SEND_PACKET; } @@ -413,7 +414,7 @@ void GameMessages::SendServerDoneLoadingAllObjects(Entity* entity, const SystemA CBITSTREAM; CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_SERVER_DONE_LOADING_ALL_OBJECTS); + bitStream.Write(eGameMessageType::SERVER_DONE_LOADING_ALL_OBJECTS); SEND_PACKET; } @@ -421,7 +422,7 @@ void GameMessages::SendChatModeUpdate(const LWOOBJID& objectID, eGameMasterLevel CBITSTREAM; CMSGHEADER; bitStream.Write(objectID); - bitStream.Write((uint16_t)GAME_MSG_UPDATE_CHAT_MODE); + bitStream.Write((uint16_t)eGameMessageType::UPDATE_CHAT_MODE); bitStream.Write(level); SEND_PACKET_BROADCAST; } @@ -430,7 +431,7 @@ void GameMessages::SendGMLevelBroadcast(const LWOOBJID& objectID, eGameMasterLev CBITSTREAM; CMSGHEADER; bitStream.Write(objectID); - bitStream.Write((uint16_t)GAME_MSG_SET_GM_LEVEL); + bitStream.Write((uint16_t)eGameMessageType::SET_GM_LEVEL); bitStream.Write1(); bitStream.Write(level); SEND_PACKET_BROADCAST; @@ -441,7 +442,7 @@ void GameMessages::SendAddItemToInventoryClientSync(Entity* entity, const System CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(static_cast<uint16_t>(GAME_MSG_ADD_ITEM_TO_INVENTORY_CLIENT_SYNC)); + bitStream.Write(eGameMessageType::ADD_ITEM_TO_INVENTORY_CLIENT_SYNC); bitStream.Write(item->GetBound()); bitStream.Write(item->GetInfo().isBOE); bitStream.Write(item->GetInfo().isBOP); @@ -500,7 +501,7 @@ void GameMessages::SendNotifyClientFlagChange(const LWOOBJID& objectID, uint32_t CMSGHEADER; bitStream.Write(objectID); - bitStream.Write((uint16_t)GAME_MSG_NOTIFY_CLIENT_FLAG_CHANGE); + bitStream.Write((uint16_t)eGameMessageType::NOTIFY_CLIENT_FLAG_CHANGE); bitStream.Write(bFlag); bitStream.Write(iFlagID); @@ -512,7 +513,7 @@ void GameMessages::SendChangeObjectWorldState(const LWOOBJID& objectID, eObjectW CMSGHEADER; bitStream.Write(objectID); - bitStream.Write((uint16_t)GAME_MSG_CHANGE_OBJECT_WORLD_STATE); + bitStream.Write((uint16_t)eGameMessageType::CHANGE_OBJECT_WORLD_STATE); bitStream.Write(state); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST @@ -530,7 +531,7 @@ void GameMessages::SendOfferMission(const LWOOBJID& entity, const SystemAddress& CMSGHEADER; bitStream.Write(offererID); - bitStream.Write(uint16_t(GAME_MSG_OFFER_MISSION)); + bitStream.Write(eGameMessageType::OFFER_MISSION); bitStream.Write(missionID); bitStream.Write(offererID); @@ -541,7 +542,7 @@ void GameMessages::SendOfferMission(const LWOOBJID& entity, const SystemAddress& CMSGHEADER; bitStream.Write(entity); - bitStream.Write(uint16_t(GAME_MSG_OFFER_MISSION)); + bitStream.Write(eGameMessageType::OFFER_MISSION); bitStream.Write(missionID); bitStream.Write(offererID); @@ -554,7 +555,7 @@ void GameMessages::SendNotifyMission(Entity* entity, const SystemAddress& sysAdd CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(uint16_t(GAME_MSG_NOTIFY_MISSION)); + bitStream.Write(eGameMessageType::NOTIFY_MISSION); bitStream.Write(missionID); bitStream.Write(missionState); bitStream.Write(sendingRewards); @@ -567,7 +568,7 @@ void GameMessages::SendNotifyMissionTask(Entity* entity, const SystemAddress& sy CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_NOTIFY_MISSION_TASK); + bitStream.Write((uint16_t)eGameMessageType::NOTIFY_MISSION_TASK); bitStream.Write(missionID); bitStream.Write(taskMask); @@ -585,7 +586,7 @@ void GameMessages::SendModifyLEGOScore(Entity* entity, const SystemAddress& sysA CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_MODIFY_LEGO_SCORE); + bitStream.Write((uint16_t)eGameMessageType::MODIFY_LEGO_SCORE); bitStream.Write(score); bitStream.Write(sourceType != eLootSourceType::NONE); @@ -599,7 +600,7 @@ void GameMessages::SendUIMessageServerToSingleClient(Entity* entity, const Syste CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_UI_MESSAGE_SERVER_TO_SINGLE_CLIENT); + bitStream.Write((uint16_t)eGameMessageType::UI_MESSAGE_SERVER_TO_SINGLE_CLIENT); bitStream.Write(args); uint32_t strMessageNameLength = message.size(); @@ -618,7 +619,7 @@ void GameMessages::SendUIMessageServerToAllClients(const std::string& message, A LWOOBJID empty = 0; bitStream.Write(empty); - bitStream.Write((uint16_t)GAME_MSG_UI_MESSAGE_SERVER_TO_ALL_CLIENTS); + bitStream.Write((uint16_t)eGameMessageType::UI_MESSAGE_SERVER_TO_ALL_CLIENTS); bitStream.Write(args); uint32_t strMessageNameLength = message.size(); @@ -636,7 +637,7 @@ void GameMessages::SendPlayEmbeddedEffectOnAllClientsNearObject(Entity* entity, CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_PLAY_EMBEDDED_EFFECT_ON_ALL_CLIENTS_NEAR_OBJECT); + bitStream.Write((uint16_t)eGameMessageType::PLAY_EMBEDDED_EFFECT_ON_ALL_CLIENTS_NEAR_OBJECT); bitStream.Write(static_cast<uint32_t>(effectName.length())); for (uint32_t k = 0; k < effectName.length(); k++) { @@ -657,7 +658,7 @@ void GameMessages::SendPlayFXEffect(const LWOOBJID& entity, int32_t effectID, co CMSGHEADER; bitStream.Write(entity); - bitStream.Write((uint16_t)GAME_MSG::GAME_MSG_PLAY_FX_EFFECT); + bitStream.Write((uint16_t)eGameMessageType::PLAY_FX_EFFECT); bitStream.Write(effectID != -1); if (effectID != -1) bitStream.Write(effectID); @@ -691,7 +692,7 @@ void GameMessages::SendStopFXEffect(Entity* entity, bool killImmediate, std::str CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_STOP_FX_EFFECT); + bitStream.Write(eGameMessageType::STOP_FX_EFFECT); bitStream.Write(killImmediate); bitStream.Write<uint32_t>(name.size()); @@ -705,7 +706,7 @@ void GameMessages::SendBroadcastTextToChatbox(Entity* entity, const SystemAddres CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG::GAME_MSG_BROADCAST_TEXT_TO_CHATBOX); + bitStream.Write((uint16_t)eGameMessageType::BROADCAST_TEXT_TO_CHATBOX); LWONameValue attribs; attribs.name = attrs; @@ -731,7 +732,7 @@ void GameMessages::SendSetCurrency(Entity* entity, int64_t currency, int lootTyp CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(uint16_t(GAME_MSG_SET_CURRENCY)); + bitStream.Write(eGameMessageType::SET_CURRENCY); bitStream.Write(currency); @@ -761,7 +762,7 @@ void GameMessages::SendRebuildNotifyState(Entity* entity, eRebuildState prevStat CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_REBUILD_NOTIFY_STATE); + bitStream.Write((uint16_t)eGameMessageType::REBUILD_NOTIFY_STATE); bitStream.Write(prevState); bitStream.Write(state); @@ -775,7 +776,7 @@ void GameMessages::SendEnableRebuild(Entity* entity, bool enable, bool fail, boo CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_ENABLE_REBUILD); + bitStream.Write((uint16_t)eGameMessageType::ENABLE_REBUILD); bitStream.Write(enable); bitStream.Write(fail); @@ -795,7 +796,7 @@ void GameMessages::SendTerminateInteraction(const LWOOBJID& objectID, eTerminate CMSGHEADER; bitStream.Write(objectID); - bitStream.Write((uint16_t)GAME_MSG_TERMINATE_INTERACTION); + bitStream.Write((uint16_t)eGameMessageType::TERMINATE_INTERACTION); bitStream.Write(terminator); bitStream.Write(type); @@ -808,7 +809,7 @@ void GameMessages::SendDieNoImplCode(Entity* entity, const LWOOBJID& killerID, c CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(uint16_t(GAME_MSG_DIE)); + bitStream.Write(eGameMessageType::DIE); bitStream.Write(bClientDeath); bitStream.Write(bSpawnLoot); bitStream.Write(deathType); @@ -831,7 +832,7 @@ void GameMessages::SendDie(Entity* entity, const LWOOBJID& killerID, const LWOOB bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_DIE); + bitStream.Write((uint16_t)eGameMessageType::DIE); bitStream.Write(bClientDeath); bitStream.Write(bSpawnLoot); @@ -867,7 +868,7 @@ void GameMessages::SendSetInventorySize(Entity* entity, int invType, int size) { CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(uint16_t(GAME_MSG_SET_INVENTORY_SIZE)); + bitStream.Write(eGameMessageType::SET_INVENTORY_SIZE); bitStream.Write(invType); bitStream.Write(size); @@ -880,7 +881,7 @@ void GameMessages::SendSetEmoteLockState(Entity* entity, bool bLock, int emoteID CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(uint16_t(GAME_MSG_SET_EMOTE_LOCK_STATE)); + bitStream.Write(eGameMessageType::SET_EMOTE_LOCK_STATE); bitStream.Write(bLock); bitStream.Write(emoteID); @@ -901,7 +902,7 @@ void GameMessages::SendSetJetPackMode(Entity* entity, bool use, bool bypassCheck CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(uint16_t(GAME_MSG_SET_JET_PACK_MODE)); + bitStream.Write(eGameMessageType::SET_JET_PACK_MODE); bitStream.Write(bypassChecks); bitStream.Write(doHover); @@ -961,7 +962,7 @@ void GameMessages::SendResurrect(Entity* entity) { bool bRezImmediately = false; bitStream.Write(entity->GetObjectID()); - bitStream.Write(uint16_t(GAME_MSG_RESURRECT)); + bitStream.Write(eGameMessageType::RESURRECT); bitStream.Write(bRezImmediately); SEND_PACKET_BROADCAST; @@ -972,7 +973,7 @@ void GameMessages::SendStop2DAmbientSound(Entity* entity, bool force, std::strin CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_PLAY2_DAMBIENT_SOUND); + bitStream.Write((uint16_t)eGameMessageType::PLAY2_DAMBIENT_SOUND); uint32_t audioGUIDSize = audioGUID.size(); @@ -995,7 +996,7 @@ void GameMessages::SendPlay2DAmbientSound(Entity* entity, std::string audioGUID, CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_PLAY2_DAMBIENT_SOUND); + bitStream.Write((uint16_t)eGameMessageType::PLAY2_DAMBIENT_SOUND); uint32_t audioGUIDSize = audioGUID.size(); @@ -1014,7 +1015,7 @@ void GameMessages::SendSetNetworkScriptVar(Entity* entity, const SystemAddress& CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_SET_NETWORK_SCRIPT_VAR); + bitStream.Write((uint16_t)eGameMessageType::SET_NETWORK_SCRIPT_VAR); // FIXME: this is a bad place to need to do a conversion because we have no clue whether data is utf8 or plain ascii // an this has performance implications @@ -1073,7 +1074,7 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(uint16_t(GAME_MSG_DROP_CLIENT_LOOT)); + bitStream.Write(eGameMessageType::DROP_CLIENT_LOOT); bitStream.Write(bUsePosition); @@ -1123,7 +1124,7 @@ void GameMessages::SendSetPlayerControlScheme(Entity* entity, eControlScheme con bool bSwitchCam = true; bitStream.Write(entity->GetObjectID()); - bitStream.Write(uint16_t(GAME_MSG_SET_PLAYER_CONTROL_SCHEME)); + bitStream.Write(eGameMessageType::SET_PLAYER_CONTROL_SCHEME); bitStream.Write(bDelayCamSwitchIfInCinematic); bitStream.Write(bSwitchCam); @@ -1140,7 +1141,7 @@ void GameMessages::SendPlayerReachedRespawnCheckpoint(Entity* entity, const NiPo CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_PLAYER_REACHED_RESPAWN_CHECKPOINT); + bitStream.Write((uint16_t)eGameMessageType::PLAYER_REACHED_RESPAWN_CHECKPOINT); bitStream.Write(position.x); bitStream.Write(position.y); @@ -1174,7 +1175,7 @@ void GameMessages::SendAddSkill(Entity* entity, TSkillID skillID, int slotID) { CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write((uint16_t)GAME_MSG_ADD_SKILL); + bitStream.Write((uint16_t)eGameMessageType::ADD_SKILL); bitStream.Write(AICombatWeight != 0); if (AICombatWeight != 0) bitStream.Write(AICombatWeight); @@ -1206,7 +1207,7 @@ void GameMessages::SendRemoveSkill(Entity* entity, TSkillID skillID) { CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write<uint16_t>(GAME_MSG_REMOVE_SKILL); + bitStream.Write(eGameMessageType::REMOVE_SKILL); bitStream.Write(false); bitStream.Write(skillID); @@ -1235,7 +1236,7 @@ void GameMessages::SendFinishArrangingWithItem(Entity* entity, const LWOOBJID& b bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_FINISH_ARRANGING_WITH_ITEM); + bitStream.Write(eGameMessageType::FINISH_ARRANGING_WITH_ITEM); bitStream.Write(buildAreaID != LWOOBJID_EMPTY); if (buildAreaID != LWOOBJID_EMPTY) bitStream.Write(buildAreaID); @@ -1261,7 +1262,7 @@ void GameMessages::SendModularBuildEnd(Entity* entity) { CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_MODULAR_BUILD_END); + bitStream.Write(eGameMessageType::MODULAR_BUILD_END); SystemAddress sysAddr = entity->GetSystemAddress(); SEND_PACKET; @@ -1272,7 +1273,7 @@ void GameMessages::SendVendorOpenWindow(Entity* entity, const SystemAddress& sys CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_VENDOR_OPEN_WINDOW); + bitStream.Write(eGameMessageType::VENDOR_OPEN_WINDOW); SEND_PACKET; } @@ -1287,7 +1288,7 @@ void GameMessages::SendVendorStatusUpdate(Entity* entity, const SystemAddress& s std::map<LOT, int> vendorItems = vendor->GetInventory(); bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_VENDOR_STATUS_UPDATE); + bitStream.Write(eGameMessageType::VENDOR_STATUS_UPDATE); bitStream.Write(bUpdateOnly); bitStream.Write(static_cast<uint32_t>(vendorItems.size())); @@ -1308,7 +1309,7 @@ void GameMessages::SendVendorTransactionResult(Entity* entity, const SystemAddre int iResult = 0x02; // success, seems to be the only relevant one bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_VENDOR_TRANSACTION_RESULT); + bitStream.Write(eGameMessageType::VENDOR_TRANSACTION_RESULT); bitStream.Write(iResult); SEND_PACKET; @@ -1334,7 +1335,7 @@ void GameMessages::SendRemoveItemFromInventory(Entity* entity, const SystemAddre LWOOBJID iTradeID = LWOOBJID_EMPTY; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_REMOVE_ITEM_FROM_INVENTORY); + bitStream.Write(eGameMessageType::REMOVE_ITEM_FROM_INVENTORY); bitStream.Write(bConfirmed); bitStream.Write(bDeleteItem); bitStream.Write(bOutSuccess); @@ -1366,7 +1367,7 @@ void GameMessages::SendConsumeClientItem(Entity* entity, bool bSuccess, LWOOBJID CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG_CONSUME_CLIENT_ITEM); + bitStream.Write(eGameMessageType::CONSUME_CLIENT_ITEM); bitStream.Write(bSuccess); bitStream.Write(item); @@ -1379,7 +1380,7 @@ void GameMessages::SendUseItemResult(Entity* entity, LOT templateID, bool useIte CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG_USE_ITEM_RESULT); + bitStream.Write(eGameMessageType::USE_ITEM_RESULT); bitStream.Write(templateID); bitStream.Write(useItemResult); @@ -1392,7 +1393,7 @@ void GameMessages::SendUseItemRequirementsResponse(LWOOBJID objectID, const Syst CMSGHEADER; bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_USE_ITEM_REQUIREMENTS_RESPONSE); + bitStream.Write(eGameMessageType::USE_ITEM_REQUIREMENTS_RESPONSE); bitStream.Write(itemResponse); @@ -1454,7 +1455,7 @@ void GameMessages::SendMatchResponse(Entity* entity, const SystemAddress& sysAdd CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_MATCH_RESPONSE); + bitStream.Write(eGameMessageType::MATCH_RESPONSE); bitStream.Write(response); SEND_PACKET; @@ -1465,7 +1466,7 @@ void GameMessages::SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_MATCH_UPDATE); + bitStream.Write(eGameMessageType::MATCH_UPDATE); bitStream.Write(uint32_t(data.size())); for (char character : data) { bitStream.Write(uint16_t(character)); @@ -1484,7 +1485,7 @@ void GameMessages::SendRequestActivitySummaryLeaderboardData(const LWOOBJID& obj CMSGHEADER; bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA); + bitStream.Write(eGameMessageType::REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA); bitStream.Write(gameID != 0); if (gameID != 0) { @@ -1517,7 +1518,7 @@ void GameMessages::SendActivityPause(LWOOBJID objectId, bool pause, const System CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_ACTIVITY_PAUSE); + bitStream.Write(eGameMessageType::ACTIVITY_PAUSE); bitStream.Write(pause); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; @@ -1529,7 +1530,7 @@ void GameMessages::SendStartActivityTime(LWOOBJID objectId, float_t startTime, c CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_START_ACTIVITY_TIME); + bitStream.Write(eGameMessageType::START_ACTIVITY_TIME); bitStream.Write<float_t>(startTime); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; @@ -1541,7 +1542,7 @@ void GameMessages::SendRequestActivityEnter(LWOOBJID objectId, const SystemAddre CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_REQUEST_ACTIVITY_ENTER); + bitStream.Write(eGameMessageType::REQUEST_ACTIVITY_ENTER); bitStream.Write<bool>(bStart); bitStream.Write<LWOOBJID>(userID); @@ -1554,7 +1555,7 @@ void GameMessages::NotifyLevelRewards(LWOOBJID objectID, const SystemAddress& sy CMSGHEADER; bitStream.Write(objectID); - bitStream.Write((uint16_t)GAME_MSG::GAME_MSG_NOTIFY_LEVEL_REWARDS); + bitStream.Write((uint16_t)eGameMessageType::NOTIFY_LEVEL_REWARDS); bitStream.Write(level); bitStream.Write(sending_rewards); @@ -1575,7 +1576,7 @@ void GameMessages::SendSetShootingGalleryParams(LWOOBJID objectId, const SystemA CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SET_SHOOTING_GALLERY_PARAMS); + bitStream.Write(eGameMessageType::SET_SHOOTING_GALLERY_PARAMS); /* bitStream.Write<float>(cameraFOV); bitStream.Write<float>(cooldown); @@ -1610,7 +1611,7 @@ void GameMessages::SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_CLIENT_SHOOTING_GALLERY_SCORE); + bitStream.Write(eGameMessageType::NOTIFY_CLIENT_SHOOTING_GALLERY_SCORE); bitStream.Write<float>(addTime); bitStream.Write<int32_t>(score); bitStream.Write<LWOOBJID>(target); @@ -1641,7 +1642,7 @@ void GameMessages::SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, CMSGHEADER; bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA); + bitStream.Write(eGameMessageType::SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA); bitStream.Write(leaderboard->GetGameID()); bitStream.Write(leaderboard->GetInfoType()); @@ -1720,7 +1721,7 @@ void GameMessages::SendStartCelebrationEffect(Entity* entity, const SystemAddres CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_START_CELEBRATION_EFFECT); + bitStream.Write(eGameMessageType::START_CELEBRATION_EFFECT); bitStream.Write<uint32_t>(0); //animation bitStream.Write0(); //No custom bg obj @@ -1751,7 +1752,7 @@ void GameMessages::SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForw CMSGHEADER; bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_SET_RAIL_MOVEMENT); + bitStream.Write(eGameMessageType::SET_RAIL_MOVEMENT); bitStream.Write(pathGoForward); @@ -1785,7 +1786,7 @@ void GameMessages::SendStartRailMovement(const LWOOBJID& objectID, std::u16strin CMSGHEADER; bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_START_RAIL_MOVEMENT); + bitStream.Write(eGameMessageType::START_RAIL_MOVEMENT); bitStream.Write(damageImmune); bitStream.Write(noAggro); @@ -1845,7 +1846,7 @@ void GameMessages::SendNotifyClientObject(const LWOOBJID& objectID, std::u16stri CMSGHEADER; bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_CLIENT_OBJECT); + bitStream.Write(eGameMessageType::NOTIFY_CLIENT_OBJECT); bitStream.Write(uint32_t(name.size())); for (auto character : name) { @@ -1874,7 +1875,7 @@ void GameMessages::SendNotifyClientZoneObject(const LWOOBJID& objectID, const st CMSGHEADER; bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_CLIENT_ZONE_OBJECT); + bitStream.Write(eGameMessageType::NOTIFY_CLIENT_ZONE_OBJECT); bitStream.Write(uint32_t(name.size())); for (const auto& character : name) { @@ -1900,7 +1901,7 @@ void GameMessages::SendNotifyClientFailedPrecondition(LWOOBJID objectId, const S CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_CLIENT_FAILED_PRECONDITION); + bitStream.Write(eGameMessageType::NOTIFY_CLIENT_FAILED_PRECONDITION); bitStream.Write(uint32_t(failedReason.size())); for (uint16_t character : failedReason) { @@ -1918,7 +1919,7 @@ void GameMessages::SendToggleGMInvis(LWOOBJID objectId, bool enabled, const Syst CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_TOGGLE_GM_INVIS); + bitStream.Write(eGameMessageType::TOGGLE_GM_INVIS); bitStream.Write(enabled); // does not matter? if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; @@ -1930,7 +1931,7 @@ void GameMessages::SendSetName(LWOOBJID objectID, std::u16string name, const Sys CMSGHEADER; bitStream.Write(objectID); - bitStream.Write<uint16_t>(GAME_MSG::GAME_MSG_SET_NAME); + bitStream.Write(eGameMessageType::SET_NAME); bitStream.Write<uint32_t>(name.size()); @@ -1946,7 +1947,7 @@ void GameMessages::SendBBBSaveResponse(const LWOOBJID& objectId, const LWOOBJID& CMSGHEADER; bitStream.Write(objectId); - bitStream.Write<uint16_t>(GAME_MSG::GAME_MSG_BBB_SAVE_RESPONSE); + bitStream.Write(eGameMessageType::BBB_SAVE_RESPONSE); bitStream.Write(localID); @@ -1963,7 +1964,7 @@ void GameMessages::SendBBBSaveResponse(const LWOOBJID& objectId, const LWOOBJID& bitStream.Write(buffer[i]); SEND_PACKET; - PacketUtils::SavePacket("GAME_MSG_BBB_SAVE_RESPONSE.bin", (char*)bitStream.GetData(), bitStream.GetNumberOfBytesUsed()); + PacketUtils::SavePacket("eGameMessageType::BBB_SAVE_RESPONSE.bin", (char*)bitStream.GetData(), bitStream.GetNumberOfBytesUsed()); } // Property @@ -1973,7 +1974,7 @@ void GameMessages::SendOpenPropertyVendor(const LWOOBJID objectId, const SystemA CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_OPEN_PROPERTY_VENDOR); + bitStream.Write(eGameMessageType::OPEN_PROPERTY_VENDOR); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -1984,7 +1985,7 @@ void GameMessages::SendOpenPropertyManagment(const LWOOBJID objectId, const Syst CMSGHEADER; bitStream.Write(PropertyManagementComponent::Instance()->GetParent()->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_OPEN_PROPERTY_MANAGEMENT); + bitStream.Write(eGameMessageType::OPEN_PROPERTY_MANAGEMENT); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -1995,7 +1996,7 @@ void GameMessages::SendDownloadPropertyData(const LWOOBJID objectId, const Prope CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_DOWNLOAD_PROPERTY_DATA); + bitStream.Write(eGameMessageType::DOWNLOAD_PROPERTY_DATA); data.Serialize(bitStream); @@ -2010,7 +2011,7 @@ void GameMessages::SendPropertyRentalResponse(const LWOOBJID objectId, const LWO CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_PROPERTY_RENTAL_RESPONSE); + bitStream.Write(eGameMessageType::PROPERTY_RENTAL_RESPONSE); bitStream.Write(cloneId); bitStream.Write(code); @@ -2026,7 +2027,7 @@ void GameMessages::SendLockNodeRotation(Entity* entity, std::string nodeName) { CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_LOCK_NODE_ROTATION); + bitStream.Write(eGameMessageType::LOCK_NODE_ROTATION); bitStream.Write(uint32_t(nodeName.size())); for (char character : nodeName) { @@ -2041,7 +2042,7 @@ void GameMessages::SendSetBuildModeConfirmed(LWOOBJID objectId, const SystemAddr CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SET_BUILD_MODE_CONFIRMED); + bitStream.Write(eGameMessageType::SET_BUILD_MODE_CONFIRMED); bitStream.Write(start); bitStream.Write(warnVisitors); @@ -2061,7 +2062,7 @@ void GameMessages::SendGetModelsOnProperty(LWOOBJID objectId, std::map<LWOOBJID, CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_GET_MODELS_ON_PROPERTY); + bitStream.Write(eGameMessageType::GET_MODELS_ON_PROPERTY); bitStream.Write(static_cast<uint32_t>(models.size())); @@ -2081,7 +2082,7 @@ void GameMessages::SendZonePropertyModelEquipped(LWOOBJID objectId, LWOOBJID pla CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_ZONE_PROPERTY_MODEL_EQUIPPED); + bitStream.Write(eGameMessageType::ZONE_PROPERTY_MODEL_EQUIPPED); bitStream.Write(playerId); bitStream.Write(propertyId); @@ -2096,7 +2097,7 @@ void GameMessages::SendPlaceModelResponse(LWOOBJID objectId, const SystemAddress CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_PLACE_MODEL_RESPONSE); + bitStream.Write(eGameMessageType::PLACE_MODEL_RESPONSE); bitStream.Write(position != NiPoint3::ZERO); if (position != NiPoint3::ZERO) { @@ -2128,7 +2129,7 @@ void GameMessages::SendUGCEquipPreCreateBasedOnEditMode(LWOOBJID objectId, const CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_HANDLE_UGC_EQUIP_PRE_CREATE_BASED_ON_EDIT_MODE); + bitStream.Write(eGameMessageType::HANDLE_UGC_EQUIP_PRE_CREATE_BASED_ON_EDIT_MODE); bitStream.Write(modelCount); bitStream.Write(model); @@ -2142,7 +2143,7 @@ void GameMessages::SendUGCEquipPostDeleteBasedOnEditMode(LWOOBJID objectId, cons CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_HANDLE_UGC_EQUIP_POST_DELETE_BASED_ON_EDIT_MODE); + bitStream.Write(eGameMessageType::HANDLE_UGC_EQUIP_POST_DELETE_BASED_ON_EDIT_MODE); bitStream.Write(inventoryItem); @@ -2192,7 +2193,7 @@ void GameMessages::HandleUnUseModel(RakNet::BitStream* inStream, Entity* entity, if (unknown) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::BLUEPRINT_SAVE_RESPONSE); bitStream.Write<LWOOBJID>(LWOOBJID_EMPTY); //always zero so that a check on the client passes bitStream.Write(eBlueprintSaveResponseType::PlacementFailed); // Sending a non-zero error code here prevents the client from deleting its in progress build for some reason? bitStream.Write<uint32_t>(0); @@ -2444,7 +2445,7 @@ void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* void GameMessages::SendBlueprintLoadItemResponse(const SystemAddress& sysAddr, bool success, LWOOBJID oldItemId, LWOOBJID newItemId) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_LOAD_RESPONSE_ITEMID); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::BLUEPRINT_LOAD_RESPONSE_ITEMID); bitStream.Write(static_cast<uint8_t>(success)); bitStream.Write<LWOOBJID>(oldItemId); bitStream.Write<LWOOBJID>(newItemId); @@ -2456,7 +2457,7 @@ void GameMessages::SendSmash(Entity* entity, float force, float ghostOpacity, LW CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_SMASH); + bitStream.Write(eGameMessageType::SMASH); bitStream.Write(ignoreObjectVisibility); bitStream.Write(force); @@ -2471,7 +2472,7 @@ void GameMessages::SendUnSmash(Entity* entity, LWOOBJID builderID, float duratio CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_UNSMASH); + bitStream.Write(eGameMessageType::UNSMASH); bitStream.Write(builderID != LWOOBJID_EMPTY); if (builderID != LWOOBJID_EMPTY) bitStream.Write(builderID); @@ -2692,7 +2693,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //Tell the client their model is saved: (this causes us to actually pop out of our current state): CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CLIENT, CLIENT::MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::BLUEPRINT_SAVE_RESPONSE); bitStream.Write(localId); bitStream.Write(eBlueprintSaveResponseType::EverythingWorked); bitStream.Write<uint32_t>(1); @@ -2832,7 +2833,7 @@ void GameMessages::SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_PLAY_CINEMATIC); + bitStream.Write(eGameMessageType::PLAY_CINEMATIC); bitStream.Write(allowGhostUpdates); bitStream.Write(bCloseMultiInteract); @@ -2871,7 +2872,7 @@ void GameMessages::SendEndCinematic(LWOOBJID objectId, std::u16string pathName, CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_END_CINEMATIC); + bitStream.Write(eGameMessageType::END_CINEMATIC); bitStream.Write(leadOut != -1); if (leadOut != -1) bitStream.Write(leadOut); @@ -2944,7 +2945,7 @@ void GameMessages::SendSetStunned(LWOOBJID objectId, eStateChangeType stateChang CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SET_STUNNED); + bitStream.Write(eGameMessageType::SET_STUNNED); bitStream.Write(originator != LWOOBJID_EMPTY); if (originator != LWOOBJID_EMPTY) bitStream.Write(originator); @@ -2993,7 +2994,7 @@ void GameMessages::SendSetStunImmunity(LWOOBJID target, eStateChangeType state, CMSGHEADER; bitStream.Write(target); - bitStream.Write(GAME_MSG::GAME_MSG_SET_STUN_IMMUNITY); + bitStream.Write(eGameMessageType::SET_STUN_IMMUNITY); bitStream.Write(originator != LWOOBJID_EMPTY); if (originator != LWOOBJID_EMPTY) bitStream.Write(originator); @@ -3026,7 +3027,7 @@ void GameMessages::SendSetStatusImmunity(LWOOBJID objectId, eStateChangeType sta CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SET_STATUS_IMMUNITY); + bitStream.Write(eGameMessageType::SET_STATUS_IMMUNITY); bitStream.Write(state); @@ -3049,7 +3050,7 @@ void GameMessages::SendOrientToAngle(LWOOBJID objectId, bool bRelativeToCurrent, CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_ORIENT_TO_ANGLE); + bitStream.Write(eGameMessageType::ORIENT_TO_ANGLE); bitStream.Write(bRelativeToCurrent); bitStream.Write(fAngle); @@ -3064,7 +3065,7 @@ void GameMessages::SendAddRunSpeedModifier(LWOOBJID objectId, LWOOBJID caster, u CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_ADD_RUN_SPEED_MODIFIER); + bitStream.Write(eGameMessageType::ADD_RUN_SPEED_MODIFIER); bitStream.Write(caster != LWOOBJID_EMPTY); if (caster != LWOOBJID_EMPTY) bitStream.Write(caster); @@ -3081,7 +3082,7 @@ void GameMessages::SendRemoveRunSpeedModifier(LWOOBJID objectId, uint32_t modifi CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_REMOVE_RUN_SPEED_MODIFIER); + bitStream.Write(eGameMessageType::REMOVE_RUN_SPEED_MODIFIER); bitStream.Write(modifier != 500); if (modifier != 500) bitStream.Write(modifier); @@ -3095,7 +3096,7 @@ void GameMessages::SendPropertyEntranceBegin(LWOOBJID objectId, const SystemAddr CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_PROPERTY_ENTRANCE_BEGIN); + bitStream.Write(eGameMessageType::PROPERTY_ENTRANCE_BEGIN); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -3106,7 +3107,7 @@ void GameMessages::SendPropertySelectQuery(LWOOBJID objectId, int32_t navOffset, CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_PROPERTY_SELECT_QUERY); + bitStream.Write(eGameMessageType::PROPERTY_SELECT_QUERY); bitStream.Write(navOffset); bitStream.Write(thereAreMore); @@ -3129,7 +3130,7 @@ void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_OBJECT); + bitStream.Write(eGameMessageType::NOTIFY_OBJECT); bitStream.Write(objIDSender); bitStream.Write(static_cast<uint32_t>(name.size())); @@ -3169,7 +3170,7 @@ void GameMessages::SendTeamPickupItem(LWOOBJID objectId, LWOOBJID lootID, LWOOBJ CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_TEAM_PICKUP_ITEM); + bitStream.Write(eGameMessageType::TEAM_PICKUP_ITEM); bitStream.Write(lootID); bitStream.Write(lootOwnerID); @@ -3185,7 +3186,7 @@ void GameMessages::SendServerTradeInvite(LWOOBJID objectId, bool bNeedInvitePopU CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SERVER_TRADE_INVITE); + bitStream.Write(eGameMessageType::SERVER_TRADE_INVITE); bitStream.Write(bNeedInvitePopUp); bitStream.Write(i64Requestor); @@ -3203,7 +3204,7 @@ void GameMessages::SendServerTradeInitialReply(LWOOBJID objectId, LWOOBJID i64In CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SERVER_TRADE_INITIAL_REPLY); + bitStream.Write(eGameMessageType::SERVER_TRADE_INITIAL_REPLY); bitStream.Write(i64Invitee); bitStream.Write(resultType); @@ -3221,7 +3222,7 @@ void GameMessages::SendServerTradeFinalReply(LWOOBJID objectId, bool bResult, LW CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SERVER_TRADE_FINAL_REPLY); + bitStream.Write(eGameMessageType::SERVER_TRADE_FINAL_REPLY); bitStream.Write(bResult); bitStream.Write(i64Invitee); @@ -3239,7 +3240,7 @@ void GameMessages::SendServerTradeAccept(LWOOBJID objectId, bool bFirst, const S CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SERVER_TRADE_ACCEPT); + bitStream.Write(eGameMessageType::SERVER_TRADE_ACCEPT); bitStream.Write(bFirst); @@ -3252,7 +3253,7 @@ void GameMessages::SendServerTradeCancel(LWOOBJID objectId, const SystemAddress& CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SERVER_TRADE_CANCEL); + bitStream.Write(eGameMessageType::SERVER_TRADE_CANCEL); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -3263,7 +3264,7 @@ void GameMessages::SendServerTradeUpdate(LWOOBJID objectId, uint64_t coins, cons CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SERVER_TRADE_UPDATE); + bitStream.Write(eGameMessageType::SERVER_TRADE_UPDATE); bitStream.Write(false); bitStream.Write(coins); @@ -3441,7 +3442,7 @@ void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_PET_TAMING_MINIGAME); + bitStream.Write(eGameMessageType::NOTIFY_PET_TAMING_MINIGAME); bitStream.Write(petId); bitStream.Write(playerTamingId); @@ -3463,7 +3464,7 @@ void GameMessages::SendNotifyTamingModelLoadedOnServer(LWOOBJID objectId, const CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_TAMING_MODEL_LOADED_ON_SERVER); + bitStream.Write(eGameMessageType::NOTIFY_TAMING_MODEL_LOADED_ON_SERVER); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -3474,7 +3475,7 @@ void GameMessages::SendNotifyPetTamingPuzzleSelected(LWOOBJID objectId, std::vec CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_PET_TAMING_PUZZLE_SELECTED); + bitStream.Write(eGameMessageType::NOTIFY_PET_TAMING_PUZZLE_SELECTED); bitStream.Write(static_cast<uint32_t>(bricks.size())); for (const auto& brick : bricks) { @@ -3491,7 +3492,7 @@ void GameMessages::SendPetTamingTryBuildResult(LWOOBJID objectId, bool bSuccess, CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_PET_TAMING_TRY_BUILD_RESULT); + bitStream.Write(eGameMessageType::PET_TAMING_TRY_BUILD_RESULT); bitStream.Write(bSuccess); bitStream.Write(iNumCorrect != 0); @@ -3506,7 +3507,7 @@ void GameMessages::SendPetResponse(LWOOBJID objectId, LWOOBJID objIDPet, int32_t CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_PET_RESPONSE); + bitStream.Write(eGameMessageType::PET_RESPONSE); bitStream.Write(objIDPet); bitStream.Write(iPetCommandType); @@ -3522,7 +3523,7 @@ void GameMessages::SendAddPetToPlayer(LWOOBJID objectId, int32_t iElementalType, CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_ADD_PET_TO_PLAYER); + bitStream.Write(eGameMessageType::ADD_PET_TO_PLAYER); bitStream.Write(iElementalType); bitStream.Write(static_cast<uint32_t>(name.size())); @@ -3542,7 +3543,7 @@ void GameMessages::SendRegisterPetID(LWOOBJID objectId, LWOOBJID objID, const Sy CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_REGISTER_PET_ID); + bitStream.Write(eGameMessageType::REGISTER_PET_ID); bitStream.Write(objID); @@ -3555,7 +3556,7 @@ void GameMessages::SendRegisterPetDBID(LWOOBJID objectId, LWOOBJID petDBID, cons CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_REGISTER_PET_DBID); + bitStream.Write(eGameMessageType::REGISTER_PET_DBID); bitStream.Write(petDBID); @@ -3568,7 +3569,7 @@ void GameMessages::SendMarkInventoryItemAsActive(LWOOBJID objectId, bool bActive CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_MARK_INVENTORY_ITEM_AS_ACTIVE); + bitStream.Write(eGameMessageType::MARK_INVENTORY_ITEM_AS_ACTIVE); bitStream.Write(bActive); @@ -3587,7 +3588,7 @@ void GameMessages::SendClientExitTamingMinigame(LWOOBJID objectId, bool bVolunta CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_CLIENT_EXIT_TAMING_MINIGAME); + bitStream.Write(eGameMessageType::CLIENT_EXIT_TAMING_MINIGAME); bitStream.Write(bVoluntaryExit); @@ -3600,7 +3601,7 @@ void GameMessages::SendShowPetActionButton(LWOOBJID objectId, int32_t buttonLabe CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SHOW_PET_ACTION_BUTTON); + bitStream.Write(eGameMessageType::SHOW_PET_ACTION_BUTTON); bitStream.Write(buttonLabel); bitStream.Write(bShow); @@ -3614,7 +3615,7 @@ void GameMessages::SendPlayEmote(LWOOBJID objectId, int32_t emoteID, LWOOBJID ta CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_PLAY_EMOTE); + bitStream.Write(eGameMessageType::PLAY_EMOTE); bitStream.Write(emoteID); bitStream.Write(target); @@ -3628,7 +3629,7 @@ void GameMessages::SendRemoveBuff(Entity* entity, bool fromUnEquip, bool removeI CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_REMOVE_BUFF); + bitStream.Write(eGameMessageType::REMOVE_BUFF); bitStream.Write(false); // bFromRemoveBehavior but setting this to true makes the GM not do anything on the client? bitStream.Write(fromUnEquip); @@ -3643,7 +3644,7 @@ void GameMessages::SendBouncerActiveStatus(LWOOBJID objectId, bool bActive, cons CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_BOUNCER_ACTIVE_STATUS); + bitStream.Write(eGameMessageType::BOUNCER_ACTIVE_STATUS); bitStream.Write(bActive); @@ -3657,7 +3658,7 @@ void GameMessages::SendSetPetName(LWOOBJID objectId, std::u16string name, LWOOBJ CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SET_PET_NAME); + bitStream.Write(eGameMessageType::SET_PET_NAME); bitStream.Write(static_cast<uint32_t>(name.size())); for (const auto character : name) { @@ -3677,7 +3678,7 @@ void GameMessages::SendSetPetNameModerated(LWOOBJID objectId, LWOOBJID petDBID, CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SET_PET_NAME_MODERATED); + bitStream.Write(eGameMessageType::SET_PET_NAME_MODERATED); bitStream.Write(petDBID != LWOOBJID_EMPTY); if (petDBID != LWOOBJID_EMPTY) bitStream.Write(petDBID); @@ -3694,7 +3695,7 @@ void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatu CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_PET_NAME_CHANGED); + bitStream.Write(eGameMessageType::PET_NAME_CHANGED); bitStream.Write(moderationStatus); @@ -3943,7 +3944,7 @@ void GameMessages::SendDisplayZoneSummary(LWOOBJID objectId, const SystemAddress CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_DISPLAY_ZONE_SUMMARY); + bitStream.Write(eGameMessageType::DISPLAY_ZONE_SUMMARY); bitStream.Write(isPropertyMap); bitStream.Write(isZoneStart); @@ -3961,7 +3962,7 @@ void GameMessages::SendNotifyNotEnoughInvSpace(LWOOBJID objectId, uint32_t freeS CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_VEHICLE_NOTIFY_FINISHED_RACE); + bitStream.Write(eGameMessageType::VEHICLE_NOTIFY_FINISHED_RACE); bitStream.Write(freeSlotsNeeded); bitStream.Write(inventoryType != 0); @@ -3976,7 +3977,7 @@ void GameMessages::SendDisplayMessageBox(LWOOBJID objectId, bool bShow, LWOOBJID CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_DISPLAY_MESSAGE_BOX); + bitStream.Write(eGameMessageType::DISPLAY_MESSAGE_BOX); bitStream.Write(bShow); bitStream.Write(callbackClient); @@ -4003,12 +4004,12 @@ void GameMessages::SendDisplayMessageBox(LWOOBJID objectId, bool bShow, LWOOBJID } void GameMessages::SendDisplayChatBubble(LWOOBJID objectId, const std::u16string& text, const SystemAddress& sysAddr) { - // GAME_MSG_DISPLAY_CHAT_BUBBLE + // eGameMessageType::DISPLAY_CHAT_BUBBLE CBITSTREAM; CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_DISPLAY_CHAT_BUBBLE); + bitStream.Write(eGameMessageType::DISPLAY_CHAT_BUBBLE); bitStream.Write(static_cast<uint32_t>(text.size())); for (const auto character : text) { @@ -4025,7 +4026,7 @@ void GameMessages::SendChangeIdleFlags(LWOOBJID objectId, eAnimationFlags flagsO CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_CHANGE_IDLE_FLAGS); + bitStream.Write(eGameMessageType::CHANGE_IDLE_FLAGS); bitStream.Write<bool>(flagsOff != eAnimationFlags::IDLE_NONE); if (flagsOff != eAnimationFlags::IDLE_NONE) bitStream.Write(flagsOff); bitStream.Write<bool>(flagsOn != eAnimationFlags::IDLE_NONE); @@ -4039,7 +4040,7 @@ void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objec CBITSTREAM; CMSGHEADER; bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_SET_MOUNT_INVENTORY_ID); + bitStream.Write(eGameMessageType::SET_MOUNT_INVENTORY_ID); bitStream.Write(objectID); SEND_PACKET_BROADCAST; @@ -4242,7 +4243,7 @@ void GameMessages::SendUpdateReputation(const LWOOBJID objectId, const int64_t r CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_UPDATE_REPUTATION); + bitStream.Write(eGameMessageType::UPDATE_REPUTATION); bitStream.Write(reputation); @@ -4316,7 +4317,7 @@ void GameMessages::SendModuleAssemblyDBDataForClient(LWOOBJID objectId, LWOOBJID CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_MODULE_ASSEMBLY_DB_DATA_FOR_CLIENT); + bitStream.Write(eGameMessageType::MODULE_ASSEMBLY_DB_DATA_FOR_CLIENT); bitStream.Write(assemblyID); @@ -4335,7 +4336,7 @@ void GameMessages::SendNotifyVehicleOfRacingObject(LWOOBJID objectId, LWOOBJID r CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_VEHICLE_OF_RACING_OBJECT); + bitStream.Write(eGameMessageType::NOTIFY_VEHICLE_OF_RACING_OBJECT); bitStream.Write(racingObjectID != LWOOBJID_EMPTY); if (racingObjectID != LWOOBJID_EMPTY) bitStream.Write(racingObjectID); @@ -4350,7 +4351,7 @@ void GameMessages::SendRacingPlayerLoaded(LWOOBJID objectId, LWOOBJID playerID, CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_RACING_PLAYER_LOADED); + bitStream.Write(eGameMessageType::RACING_PLAYER_LOADED); bitStream.Write(playerID); bitStream.Write(vehicleID); @@ -4365,7 +4366,7 @@ void GameMessages::SendVehicleUnlockInput(LWOOBJID objectId, bool bLockWheels, c CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_VEHICLE_UNLOCK_INPUT); + bitStream.Write(eGameMessageType::VEHICLE_UNLOCK_INPUT); bitStream.Write(bLockWheels); @@ -4379,7 +4380,7 @@ void GameMessages::SendVehicleSetWheelLockState(LWOOBJID objectId, bool bExtraFr CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_VEHICLE_SET_WHEEL_LOCK_STATE); + bitStream.Write(eGameMessageType::VEHICLE_SET_WHEEL_LOCK_STATE); bitStream.Write(bExtraFriction); bitStream.Write(bLocked); @@ -4394,7 +4395,7 @@ void GameMessages::SendRacingSetPlayerResetInfo(LWOOBJID objectId, int32_t curre CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_RACING_SET_PLAYER_RESET_INFO); + bitStream.Write(eGameMessageType::RACING_SET_PLAYER_RESET_INFO); bitStream.Write(currentLap); bitStream.Write(furthestResetPlane); @@ -4412,7 +4413,7 @@ void GameMessages::SendRacingResetPlayerToLastReset(LWOOBJID objectId, LWOOBJID CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_RACING_RESET_PLAYER_TO_LAST_RESET); + bitStream.Write(eGameMessageType::RACING_RESET_PLAYER_TO_LAST_RESET); bitStream.Write(playerID); @@ -4425,7 +4426,7 @@ void GameMessages::SendVehicleStopBoost(Entity* targetEntity, const SystemAddres CMSGHEADER; bitStream.Write(targetEntity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_VEHICLE_STOP_BOOST); + bitStream.Write(eGameMessageType::VEHICLE_STOP_BOOST); bitStream.Write(affectPassive); @@ -4437,7 +4438,7 @@ void GameMessages::SendSetResurrectRestoreValues(Entity* targetEntity, int32_t a CMSGHEADER; bitStream.Write(targetEntity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_SET_RESURRECT_RESTORE_VALUES); + bitStream.Write(eGameMessageType::SET_RESURRECT_RESTORE_VALUES); bitStream.Write(armorRestore != -1); if (armorRestore != -1) bitStream.Write(armorRestore); @@ -4456,7 +4457,7 @@ void GameMessages::SendNotifyRacingClient(LWOOBJID objectId, int32_t eventType, CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_NOTIFY_RACING_CLIENT); + bitStream.Write(eGameMessageType::NOTIFY_RACING_CLIENT); bitStream.Write(eventType != 0); if (eventType != 0) bitStream.Write(eventType); @@ -4482,7 +4483,7 @@ void GameMessages::SendActivityEnter(LWOOBJID objectId, const SystemAddress& sys CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_ACTIVITY_ENTER); + bitStream.Write(eGameMessageType::ACTIVITY_ENTER); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -4494,7 +4495,7 @@ void GameMessages::SendActivityStart(LWOOBJID objectId, const SystemAddress& sys CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_ACTIVITY_START); + bitStream.Write(eGameMessageType::ACTIVITY_START); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -4506,7 +4507,7 @@ void GameMessages::SendActivityExit(LWOOBJID objectId, const SystemAddress& sysA CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_ACTIVITY_EXIT); + bitStream.Write(eGameMessageType::ACTIVITY_EXIT); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -4518,7 +4519,7 @@ void GameMessages::SendActivityStop(LWOOBJID objectId, bool bExit, bool bUserCan CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_ACTIVITY_STOP); + bitStream.Write(eGameMessageType::ACTIVITY_STOP); bitStream.Write(bExit); bitStream.Write(bUserCancel); @@ -4533,7 +4534,7 @@ void GameMessages::SendVehicleAddPassiveBoostAction(LWOOBJID objectId, const Sys CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_VEHICLE_ADD_PASSIVE_BOOST_ACTION); + bitStream.Write(eGameMessageType::VEHICLE_ADD_PASSIVE_BOOST_ACTION); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -4545,7 +4546,7 @@ void GameMessages::SendVehicleRemovePassiveBoostAction(LWOOBJID objectId, const CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_VEHICLE_REMOVE_PASSIVE_BOOST_ACTION); + bitStream.Write(eGameMessageType::VEHICLE_REMOVE_PASSIVE_BOOST_ACTION); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -4557,7 +4558,7 @@ void GameMessages::SendVehicleNotifyFinishedRace(LWOOBJID objectId, const System CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_VEHICLE_NOTIFY_FINISHED_RACE); + bitStream.Write(eGameMessageType::VEHICLE_NOTIFY_FINISHED_RACE); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -4571,7 +4572,7 @@ void GameMessages::SendAddBuff(LWOOBJID& objectID, const LWOOBJID& casterID, uin CMSGHEADER; bitStream.Write(objectID); - bitStream.Write(GAME_MSG::GAME_MSG_ADD_BUFF); + bitStream.Write(eGameMessageType::ADD_BUFF); bitStream.Write(false); // Added by teammate bitStream.Write(false); // Apply on teammates @@ -4652,7 +4653,7 @@ void GameMessages::SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditi CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SHOW_ACTIVITY_COUNTDOWN); + bitStream.Write(eGameMessageType::SHOW_ACTIVITY_COUNTDOWN); bitStream.Write(bPlayAdditionalSound); @@ -5957,7 +5958,7 @@ void GameMessages::SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* e // TODO This needs to be implemented when reputation is implemented for getting hot properties. /** bitStream.Write(entity->GetObjectID()); - bitStream.Write(GAME_MSG::GAME_MSG_SEND_HOT_PROPERTY_DATA); + bitStream.Write(eGameMessageType::SEND_HOT_PROPERTY_DATA); std::vector<int32_t> t = {25166, 25188, 25191, 25194}; bitStream.Write<uint32_t>(4); for (uint8_t i = 0; i < 4; i++) { @@ -6151,7 +6152,7 @@ void GameMessages::SendActivateBubbleBuffFromServer(LWOOBJID objectId, const Sys CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_ACTIVATE_BUBBLE_BUFF_FROM_SERVER); + bitStream.Write(eGameMessageType::ACTIVATE_BUBBLE_BUFF_FROM_SERVER); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -6162,7 +6163,7 @@ void GameMessages::SendDeactivateBubbleBuffFromServer(LWOOBJID objectId, const S CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_DEACTIVATE_BUBBLE_BUFF_FROM_SERVER); + bitStream.Write(eGameMessageType::DEACTIVATE_BUBBLE_BUFF_FROM_SERVER); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST; SEND_PACKET; @@ -6180,7 +6181,7 @@ void GameMessages::SendSetNamebillboardState(const SystemAddress& sysAddr, LWOOB CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SET_NAME_BILLBOARD_STATE); + bitStream.Write(eGameMessageType::SET_NAME_BILLBOARD_STATE); // Technically these bits would be written, however the client does not // contain a deserialize method to actually deserialize, so we are leaving it out. @@ -6198,7 +6199,7 @@ void GameMessages::SendShowBillboardInteractIcon(const SystemAddress& sysAddr, L CMSGHEADER; bitStream.Write(objectId); - bitStream.Write(GAME_MSG::GAME_MSG_SHOW_BILLBOARD_INTERACT_ICON); + bitStream.Write(eGameMessageType::SHOW_BILLBOARD_INTERACT_ICON); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) SEND_PACKET_BROADCAST else SEND_PACKET diff --git a/dGame/dGameMessages/RequestServerProjectileImpact.h b/dGame/dGameMessages/RequestServerProjectileImpact.h index 01426361..090d8274 100644 --- a/dGame/dGameMessages/RequestServerProjectileImpact.h +++ b/dGame/dGameMessages/RequestServerProjectileImpact.h @@ -2,13 +2,11 @@ #define __REQUESTSERVERPROJECTILEIMPACT__H__ #include "dCommonVars.h" -#include "dMessageIdentifiers.h" +#include "eGameMessageType.h" /* Notifying the server that a locally owned projectile impacted. Sent to the caster of the projectile should always be the local char. */ class RequestServerProjectileImpact { - static const GAME_MSG MsgID = GAME_MSG_REQUEST_SERVER_PROJECTILE_IMPACT; - public: RequestServerProjectileImpact() { i64LocalID = LWOOBJID_EMPTY; @@ -29,7 +27,7 @@ public: } void Serialize(RakNet::BitStream* stream) { - stream->Write(MsgID); + stream->Write(eGameMessageType::REQUEST_SERVER_PROJECTILE_IMPACT); stream->Write(i64LocalID != LWOOBJID_EMPTY); if (i64LocalID != LWOOBJID_EMPTY) stream->Write(i64LocalID); diff --git a/dGame/dGameMessages/StartSkill.h b/dGame/dGameMessages/StartSkill.h index af82a9b4..40bc210f 100644 --- a/dGame/dGameMessages/StartSkill.h +++ b/dGame/dGameMessages/StartSkill.h @@ -2,16 +2,14 @@ #define __STARTSKILL__H__ #include "dCommonVars.h" -#include "dMessageIdentifiers.h" #include "NiPoint3.h" #include "NiQuaternion.h" +#include "eGameMessageType.h" /** * Same as sync skill but with different network options. An echo down to other clients that need to play the skill. */ class StartSkill { - static const GAME_MSG MsgID = GAME_MSG_START_SKILL; - public: StartSkill() { bUsedMouse = false; @@ -46,7 +44,7 @@ public: } void Serialize(RakNet::BitStream* stream) { - stream->Write(MsgID); + stream->Write(eGameMessageType::START_SKILL); stream->Write(bUsedMouse); diff --git a/dGame/dGameMessages/SyncSkill.h b/dGame/dGameMessages/SyncSkill.h index 72a88839..6485199e 100644 --- a/dGame/dGameMessages/SyncSkill.h +++ b/dGame/dGameMessages/SyncSkill.h @@ -5,11 +5,10 @@ #include <string> #include "BitStream.h" +#include "eGameMessageType.h" /* Message to synchronize a skill cast */ class SyncSkill { - static const GAME_MSG MsgID = GAME_MSG_SYNC_SKILL; - public: SyncSkill() { bDone = false; @@ -30,7 +29,7 @@ public: } void Serialize(RakNet::BitStream* stream) { - stream->Write(MsgID); + stream->Write(eGameMessageType::SYNC_SKILL); stream->Write(bDone); uint32_t sBitStreamLength = sBitStream.length(); diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index 1d3e0f60..5dc55765 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -13,7 +13,6 @@ #include "Entity.h" #include "Character.h" #include "PacketUtils.h" -#include "dMessageIdentifiers.h" #include "dLogger.h" #include "EntityManager.h" #include "InventoryComponent.h" @@ -26,6 +25,7 @@ #include "WorldConfig.h" #include "eMissionTaskType.h" #include "eReplicaComponentType.h" +#include "eConnectionType.h" void Mail::SendMail(const Entity* recipient, const std::string& subject, const std::string& body, const LOT attachment, const uint16_t attachmentCount) { @@ -283,7 +283,7 @@ void Mail::HandleDataRequest(RakNet::BitStream* packet, const SystemAddress& sys sql::ResultSet* res = stmt->executeQuery(); RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAIL); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::MAIL); bitStream.Write(int(MailMessageID::MailData)); bitStream.Write(int(0)); @@ -406,7 +406,7 @@ void Mail::HandleNotificationRequest(const SystemAddress& sysAddr, uint32_t obje void Mail::SendSendResponse(const SystemAddress& sysAddr, MailSendResponse response) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAIL); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::MAIL); bitStream.Write(int(MailMessageID::SendResponse)); bitStream.Write(int(response)); Game::server->Send(&bitStream, sysAddr, false); @@ -414,7 +414,7 @@ void Mail::SendSendResponse(const SystemAddress& sysAddr, MailSendResponse respo void Mail::SendNotification(const SystemAddress& sysAddr, int mailCount) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAIL); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::MAIL); uint64_t messageType = 2; uint64_t s1 = 0; uint64_t s2 = 0; @@ -433,7 +433,7 @@ void Mail::SendNotification(const SystemAddress& sysAddr, int mailCount) { void Mail::SendAttachmentRemoveConfirm(const SystemAddress& sysAddr, uint64_t mailID) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAIL); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::MAIL); bitStream.Write(int(MailMessageID::AttachmentCollectConfirm)); bitStream.Write(int(0)); //unknown bitStream.Write(mailID); @@ -442,7 +442,7 @@ void Mail::SendAttachmentRemoveConfirm(const SystemAddress& sysAddr, uint64_t ma void Mail::SendDeleteConfirm(const SystemAddress& sysAddr, uint64_t mailID, LWOOBJID playerID) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAIL); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::MAIL); bitStream.Write(int(MailMessageID::MailDeleteConfirm)); bitStream.Write(int(0)); //unknown bitStream.Write(mailID); @@ -456,7 +456,7 @@ void Mail::SendDeleteConfirm(const SystemAddress& sysAddr, uint64_t mailID, LWOO void Mail::SendReadConfirm(const SystemAddress& sysAddr, uint64_t mailID) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAIL); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::MAIL); bitStream.Write(int(MailMessageID::MailReadConfirm)); bitStream.Write(int(0)); //unknown bitStream.Write(mailID); diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 66e9bc9b..07950d7a 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -71,7 +71,6 @@ #include "eBubbleType.h" #include "AMFFormat.h" #include "MovingPlatformComponent.h" -#include "dMessageIdentifiers.h" #include "eMissionState.h" #include "TriggerComponent.h" #include "eServerDisconnectIdentifiers.h" @@ -79,6 +78,9 @@ #include "eGameMasterLevel.h" #include "eReplicaComponentType.h" #include "eControlScheme.h" +#include "eConnectionType.h" +#include "eChatInternalMessageType.h" +#include "eMasterMessageType.h" #include "CDObjectsTable.h" #include "CDZoneTableTable.h" @@ -765,7 +767,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "shutdownuniverse" && entity->GetGMLevel() == eGameMasterLevel::OPERATOR) { //Tell the master server that we're going to be shutting down whole "universe": CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SHUTDOWN_UNIVERSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SHUTDOWN_UNIVERSE); Game::server->SendToMaster(&bitStream); ChatPackets::SendSystemMessage(sysAddr, u"Sent universe shutdown notification to master."); @@ -1096,7 +1098,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit //Notify chat about it CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_MUTE_UPDATE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::MUTE_UPDATE); bitStream.Write(characterId); bitStream.Write(expire); @@ -2044,7 +2046,7 @@ void SlashCommandHandler::SendAnnouncement(const std::string& title, const std:: //Notify chat about it CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_ANNOUNCEMENT); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::ANNOUNCEMENT); bitStream.Write<uint32_t>(title.size()); for (auto character : title) { diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index fe62a5e5..50f55b72 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -7,10 +7,11 @@ #include "CDClientDatabase.h" #include "CDClientManager.h" #include "CDZoneTableTable.h" -#include "dMessageIdentifiers.h" #include "MasterPackets.h" #include "PacketUtils.h" #include "BinaryPathFinder.h" +#include "eConnectionType.h" +#include "eMasterMessageType.h" InstanceManager::InstanceManager(dLogger* logger, const std::string& externalIP) { mLogger = logger; @@ -201,7 +202,7 @@ void InstanceManager::RequestAffirmation(Instance* instance, const PendingInstan CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_AFFIRM_TRANSFER_REQUEST); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::AFFIRM_TRANSFER_REQUEST); bitStream.Write(request.id); @@ -405,7 +406,7 @@ bool Instance::GetShutdownComplete() const { void Instance::Shutdown() { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SHUTDOWN); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SHUTDOWN); Game::server->Send(&bitStream, this->m_SysAddr, false); diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index cc2bdd90..4b524d8d 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -27,6 +27,8 @@ #include "dServer.h" #include "AssetManager.h" #include "BinaryPathFinder.h" +#include "eConnectionType.h" +#include "eMasterMessageType.h" //RakNet includes: #include "RakNetDefines.h" @@ -39,7 +41,6 @@ #include "MasterPackets.h" #include "ObjectIDManager.h" #include "PacketUtils.h" -#include "dMessageIdentifiers.h" #include "FdbToSqlite.h" namespace Game { @@ -494,9 +495,9 @@ void HandlePacket(Packet* packet) { } } - if (packet->data[1] == MASTER) { - switch (packet->data[3]) { - case MSG_MASTER_REQUEST_PERSISTENT_ID: { + if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::MASTER) { + switch (static_cast<eMasterMessageType>(packet->data[3])) { + case eMasterMessageType::REQUEST_PERSISTENT_ID: { Game::logger->Log("MasterServer", "A persistent ID req"); RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); @@ -508,7 +509,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_REQUEST_ZONE_TRANSFER: { + case eMasterMessageType::REQUEST_ZONE_TRANSFER: { Game::logger->Log("MasterServer", "Received zone transfer req"); RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); @@ -544,7 +545,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_SERVER_INFO: { + case eMasterMessageType::SERVER_INFO: { //MasterPackets::HandleServerInfo(packet); //This is here because otherwise we'd have to include IM in @@ -603,7 +604,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_SET_SESSION_KEY: { + case eMasterMessageType::SET_SESSION_KEY: { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); uint32_t sessionKey = 0; @@ -617,7 +618,7 @@ void HandlePacket(Packet* packet) { activeSessions.erase(it.first); CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_NEW_SESSION_ALERT); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::NEW_SESSION_ALERT); bitStream.Write(sessionKey); bitStream.Write<uint32_t>(username.size()); for (auto character : username) { @@ -634,7 +635,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_REQUEST_SESSION_KEY: { + case eMasterMessageType::REQUEST_SESSION_KEY: { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); std::string username = PacketUtils::ReadString(8, packet, false); @@ -642,7 +643,7 @@ void HandlePacket(Packet* packet) { for (auto key : activeSessions) { if (key.second == username) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SESSION_KEY_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SESSION_KEY_RESPONSE); bitStream.Write(key.first); PacketUtils::WriteString(bitStream, key.second, 64); Game::server->Send(&bitStream, packet->systemAddress, false); @@ -652,7 +653,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_PLAYER_ADDED: { + case eMasterMessageType::PLAYER_ADDED: { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); @@ -672,7 +673,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_PLAYER_REMOVED: { + case eMasterMessageType::PLAYER_REMOVED: { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); @@ -690,7 +691,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_CREATE_PRIVATE_ZONE: { + case eMasterMessageType::CREATE_PRIVATE_ZONE: { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); @@ -714,7 +715,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_REQUEST_PRIVATE_ZONE: { + case eMasterMessageType::REQUEST_PRIVATE_ZONE: { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); @@ -749,7 +750,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_WORLD_READY: { + case eMasterMessageType::WORLD_READY: { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); @@ -773,7 +774,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_PREP_ZONE: { + case eMasterMessageType::PREP_ZONE: { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); @@ -789,7 +790,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_AFFIRM_TRANSFER_RESPONSE: { + case eMasterMessageType::AFFIRM_TRANSFER_RESPONSE: { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); @@ -809,7 +810,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_SHUTDOWN_RESPONSE: { + case eMasterMessageType::SHUTDOWN_RESPONSE: { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); @@ -824,7 +825,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_SHUTDOWN_UNIVERSE: { + case eMasterMessageType::SHUTDOWN_UNIVERSE: { Game::logger->Log("MasterServer", "Received shutdown universe command, shutting down in 10 minutes."); Game::shouldShutdown = true; break; @@ -888,7 +889,7 @@ void ShutdownSequence(int32_t signal) { { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SHUTDOWN); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SHUTDOWN); Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); Game::logger->Log("MasterServer", "Triggered master shutdown"); } diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index eae23394..4bbb0576 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -1,6 +1,5 @@ #include "AuthPackets.h" #include "PacketUtils.h" -#include "dMessageIdentifiers.h" #include "dNetCommon.h" #include "dServer.h" @@ -23,6 +22,9 @@ #include "dConfig.h" #include "eServerDisconnectIdentifiers.h" #include "eLoginResponse.h" +#include "eConnectionType.h" +#include "eServerMessageType.h" +#include "eMasterMessageType.h" void AuthPackets::HandleHandshake(dServer* server, Packet* packet) { RakNet::BitStream inStream(packet->data, packet->length, false); @@ -36,7 +38,7 @@ void AuthPackets::HandleHandshake(dServer* server, Packet* packet) { void AuthPackets::SendHandshake(dServer* server, const SystemAddress& sysAddr, const std::string& nextServerIP, uint16_t nextServerPort, const ServerType serverType) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, SERVER, MSG_SERVER_VERSION_CONFIRM); + PacketUtils::WriteHeader(bitStream, eConnectionType::SERVER, eServerMessageType::VERSION_CONFIRM); bitStream.Write<unsigned int>(NET_VERSION); bitStream.Write(uint32_t(0x93)); @@ -189,7 +191,7 @@ void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAddr, eLoginResponse responseCode, const std::string& errorMsg, const std::string& wServerIP, uint16_t wServerPort, std::string username) { RakNet::BitStream packet; - PacketUtils::WriteHeader(packet, CLIENT, MSG_CLIENT_LOGIN_RESPONSE); + PacketUtils::WriteHeader(packet, eConnectionType::CLIENT, eClientMessageType::LOGIN_RESPONSE); packet.Write(static_cast<uint8_t>(responseCode)); @@ -255,7 +257,7 @@ void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAdd //Inform the master server that we've created a session for this user: { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SET_SESSION_KEY); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SET_SESSION_KEY); bitStream.Write(sessionKey); PacketUtils::WriteString(bitStream, username, 66); server->SendToMaster(&bitStream); diff --git a/dNet/ChatPackets.cpp b/dNet/ChatPackets.cpp index 2d592c9b..41661523 100644 --- a/dNet/ChatPackets.cpp +++ b/dNet/ChatPackets.cpp @@ -8,12 +8,13 @@ #include "BitStream.h" #include "Game.h" #include "PacketUtils.h" -#include "dMessageIdentifiers.h" #include "dServer.h" +#include "eConnectionType.h" +#include "eChatMessageType.h" void ChatPackets::SendChatMessage(const SystemAddress& sysAddr, char chatChannel, const std::string& senderName, LWOOBJID playerObjectID, bool senderMythran, const std::u16string& message) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT, eChatMessageType::GENERAL_CHAT_MESSAGE); bitStream.Write(static_cast<uint64_t>(0)); bitStream.Write(chatChannel); @@ -35,7 +36,7 @@ void ChatPackets::SendChatMessage(const SystemAddress& sysAddr, char chatChannel void ChatPackets::SendSystemMessage(const SystemAddress& sysAddr, const std::u16string& message, const bool broadcast) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT, MSG_CHAT_GENERAL_CHAT_MESSAGE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT, eChatMessageType::GENERAL_CHAT_MESSAGE); bitStream.Write(static_cast<uint64_t>(0)); bitStream.Write(static_cast<char>(4)); @@ -67,7 +68,7 @@ void ChatPackets::SendMessageFail(const SystemAddress& sysAddr) { //0x01 - "Upgrade to a full LEGO Universe Membership to chat with other players." CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_SEND_CANNED_TEXT); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::SEND_CANNED_TEXT); bitStream.Write<uint8_t>(0); //response type, options above ^ //docs say there's a wstring here-- no idea what it's for, or if it's even needed so leaving it as is for now. SEND_PACKET; diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index a1c08938..4ccbb609 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -31,7 +31,6 @@ #include "dConfig.h" #include "CharacterComponent.h" #include "Database.h" -#include "dMessageIdentifiers.h" #include "eGameMasterLevel.h" #include "eReplicaComponentType.h" diff --git a/dNet/MasterPackets.cpp b/dNet/MasterPackets.cpp index e5b80e05..4233a37d 100644 --- a/dNet/MasterPackets.cpp +++ b/dNet/MasterPackets.cpp @@ -1,22 +1,23 @@ #include "MasterPackets.h" #include "BitStream.h" #include "PacketUtils.h" -#include "dMessageIdentifiers.h" #include "dCommonVars.h" #include "dServer.h" +#include "eConnectionType.h" +#include "eMasterMessageType.h" #include <string> void MasterPackets::SendPersistentIDRequest(dServer* server, uint64_t requestID) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_PERSISTENT_ID); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::REQUEST_PERSISTENT_ID); bitStream.Write(requestID); server->SendToMaster(&bitStream); } void MasterPackets::SendPersistentIDResponse(dServer* server, const SystemAddress& sysAddr, uint64_t requestID, uint32_t objID) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_PERSISTENT_ID_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::REQUEST_PERSISTENT_ID_RESPONSE); bitStream.Write(requestID); bitStream.Write(objID); @@ -26,7 +27,7 @@ void MasterPackets::SendPersistentIDResponse(dServer* server, const SystemAddres void MasterPackets::SendZoneTransferRequest(dServer* server, uint64_t requestID, bool mythranShift, uint32_t zoneID, uint32_t cloneID) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_ZONE_TRANSFER); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::REQUEST_ZONE_TRANSFER); bitStream.Write(requestID); bitStream.Write(static_cast<uint8_t>(mythranShift)); @@ -38,7 +39,7 @@ void MasterPackets::SendZoneTransferRequest(dServer* server, uint64_t requestID, void MasterPackets::SendZoneCreatePrivate(dServer* server, uint32_t zoneID, uint32_t cloneID, const std::string& password) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_CREATE_PRIVATE_ZONE); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::CREATE_PRIVATE_ZONE); bitStream.Write(zoneID); bitStream.Write(cloneID); @@ -53,7 +54,7 @@ void MasterPackets::SendZoneCreatePrivate(dServer* server, uint32_t zoneID, uint void MasterPackets::SendZoneRequestPrivate(dServer* server, uint64_t requestID, bool mythranShift, const std::string& password) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_PRIVATE_ZONE); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::REQUEST_PRIVATE_ZONE); bitStream.Write(requestID); bitStream.Write(static_cast<uint8_t>(mythranShift)); @@ -68,7 +69,7 @@ void MasterPackets::SendZoneRequestPrivate(dServer* server, uint64_t requestID, void MasterPackets::SendWorldReady(dServer* server, LWOMAPID zoneId, LWOINSTANCEID instanceId) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_WORLD_READY); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::WORLD_READY); bitStream.Write(zoneId); bitStream.Write(instanceId); @@ -78,7 +79,7 @@ void MasterPackets::SendWorldReady(dServer* server, LWOMAPID zoneId, LWOINSTANCE void MasterPackets::SendZoneTransferResponse(dServer* server, const SystemAddress& sysAddr, uint64_t requestID, bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, const std::string& serverIP, uint32_t serverPort) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::REQUEST_ZONE_TRANSFER_RESPONSE); bitStream.Write(requestID); bitStream.Write(static_cast<uint8_t>(mythranShift)); @@ -110,7 +111,7 @@ void MasterPackets::HandleServerInfo(Packet* packet) { void MasterPackets::SendServerInfo(dServer* server, Packet* packet) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SERVER_INFO); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SERVER_INFO); bitStream.Write(server->GetPort()); bitStream.Write(server->GetZoneID()); diff --git a/dNet/PacketUtils.cpp b/dNet/PacketUtils.cpp index 307ff633..77b314d6 100644 --- a/dNet/PacketUtils.cpp +++ b/dNet/PacketUtils.cpp @@ -1,17 +1,9 @@ #include "PacketUtils.h" -#include <MessageIdentifiers.h> #include <vector> #include <fstream> #include "dLogger.h" #include "Game.h" -void PacketUtils::WriteHeader(RakNet::BitStream& bitStream, uint16_t connectionType, uint32_t internalPacketID) { - bitStream.Write(MessageID(ID_USER_PACKET_ENUM)); - bitStream.Write(connectionType); - bitStream.Write(internalPacketID); - bitStream.Write(uint8_t(0)); -} - uint16_t PacketUtils::ReadPacketU16(uint32_t startLoc, Packet* packet) { if (startLoc + 2 > packet->length) return 0; diff --git a/dNet/PacketUtils.h b/dNet/PacketUtils.h index fbbd1839..7c917f2e 100644 --- a/dNet/PacketUtils.h +++ b/dNet/PacketUtils.h @@ -1,11 +1,20 @@ #ifndef PACKETUTILS_H #define PACKETUTILS_H +#include <MessageIdentifiers.h> #include <BitStream.h> #include <string> +enum class eConnectionType : uint16_t; + namespace PacketUtils { - void WriteHeader(RakNet::BitStream& bitStream, uint16_t connectionType, uint32_t internalPacketID); + template<typename T> + void WriteHeader(RakNet::BitStream& bitStream, eConnectionType connectionType, T internalPacketID) { + bitStream.Write(MessageID(ID_USER_PACKET_ENUM)); + bitStream.Write(connectionType); + bitStream.Write(internalPacketID); + bitStream.Write(uint8_t(0)); + } uint16_t ReadPacketU16(uint32_t startLoc, Packet* packet); uint32_t ReadPacketU32(uint32_t startLoc, Packet* packet); diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index 3be4fb4d..5fce14d3 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -1,7 +1,6 @@ #include "dCommonVars.h" #include "WorldPackets.h" #include "BitStream.h" -#include "dMessageIdentifiers.h" #include "PacketUtils.h" #include "GeneralUtils.h" #include "User.h" @@ -14,10 +13,11 @@ #include "dZoneManager.h" #include "CharacterComponent.h" #include "ZCompression.h" +#include "eConnectionType.h" void WorldPackets::SendLoadStaticZone(const SystemAddress& sysAddr, float x, float y, float z, uint32_t checksum) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_LOAD_STATIC_ZONE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::LOAD_STATIC_ZONE); auto zone = dZoneManager::Instance()->GetZone()->GetZoneID(); bitStream.Write(static_cast<uint16_t>(zone.GetMapID())); @@ -41,7 +41,7 @@ void WorldPackets::SendCharacterList(const SystemAddress& sysAddr, User* user) { if (!user) return; RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_LIST_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::CHARACTER_LIST_RESPONSE); std::vector<Character*> characters = user->GetCharacters(); bitStream.Write(static_cast<uint8_t>(characters.size())); @@ -90,28 +90,28 @@ void WorldPackets::SendCharacterList(const SystemAddress& sysAddr, User* user) { void WorldPackets::SendCharacterCreationResponse(const SystemAddress& sysAddr, eCharacterCreationResponse response) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_CREATE_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::CHARACTER_CREATE_RESPONSE); bitStream.Write(response); SEND_PACKET; } void WorldPackets::SendCharacterRenameResponse(const SystemAddress& sysAddr, eRenameResponse response) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHARACTER_RENAME_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::CHARACTER_RENAME_RESPONSE); bitStream.Write(response); SEND_PACKET; } void WorldPackets::SendCharacterDeleteResponse(const SystemAddress& sysAddr, bool response) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_DELETE_CHARACTER_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::DELETE_CHARACTER_RESPONSE); bitStream.Write(static_cast<uint8_t>(response)); SEND_PACKET; } void WorldPackets::SendTransferToWorld(const SystemAddress& sysAddr, const std::string& serverIP, uint32_t serverPort, bool mythranShift) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_TRANSFER_TO_WORLD); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::TRANSFER_TO_WORLD); PacketUtils::WriteString(bitStream, serverIP, 33); bitStream.Write(static_cast<uint16_t>(serverPort)); @@ -122,14 +122,14 @@ void WorldPackets::SendTransferToWorld(const SystemAddress& sysAddr, const std:: void WorldPackets::SendServerState(const SystemAddress& sysAddr) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_SERVER_STATES); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::SERVER_STATES); bitStream.Write(static_cast<uint8_t>(1)); //If the server is receiving this request, it probably is ready anyway. SEND_PACKET; } void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* entity, const std::string& xmlData, const std::u16string& username, eGameMasterLevel gm) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CREATE_CHARACTER); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::CREATE_CHARACTER); RakNet::BitStream data; data.Write<uint32_t>(7); //LDF key count @@ -198,7 +198,7 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, Entity* ent void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool requestAccepted, uint32_t requestID, const std::string& receiver, std::vector<std::pair<uint8_t, uint8_t>> unacceptedItems) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_CHAT_MODERATION_STRING); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::CHAT_MODERATION_STRING); bitStream.Write<uint8_t>(unacceptedItems.empty()); // Is sentence ok? bitStream.Write<uint16_t>(0x16); // Source ID, unknown @@ -222,7 +222,7 @@ void WorldPackets::SendChatModerationResponse(const SystemAddress& sysAddr, bool void WorldPackets::SendGMLevelChange(const SystemAddress& sysAddr, bool success, eGameMasterLevel highestLevel, eGameMasterLevel prevLevel, eGameMasterLevel newLevel) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_MAKE_GM_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::MAKE_GM_RESPONSE); bitStream.Write<uint8_t>(success); bitStream.Write(static_cast<uint16_t>(highestLevel)); diff --git a/dNet/dServer.cpp b/dNet/dServer.cpp index c91c7508..610f06a5 100644 --- a/dNet/dServer.cpp +++ b/dNet/dServer.cpp @@ -6,9 +6,11 @@ #include "RakNetworkFactory.h" #include "MessageIdentifiers.h" +#include "eConnectionType.h" +#include "eServerMessageType.h" +#include "eMasterMessageType.h" #include "PacketUtils.h" -#include "dMessageIdentifiers.h" #include "MasterPackets.h" #include "ZoneInstanceManager.h" @@ -118,14 +120,14 @@ Packet* dServer::ReceiveFromMaster() { } if (packet->data[0] == ID_USER_PACKET_ENUM) { - if (packet->data[1] == MASTER) { - switch (packet->data[3]) { - case MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE: { + if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::MASTER) { + switch (static_cast<eMasterMessageType>(packet->data[3])) { + case eMasterMessageType::REQUEST_ZONE_TRANSFER_RESPONSE: { uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); ZoneInstanceManager::Instance()->HandleRequestZoneTransferResponse(requestID, packet); break; } - case MSG_MASTER_SHUTDOWN: + case eMasterMessageType::SHUTDOWN: *mShouldShutdown = true; break; @@ -166,7 +168,7 @@ void dServer::SendToMaster(RakNet::BitStream* bitStream) { void dServer::Disconnect(const SystemAddress& sysAddr, eServerDisconnectIdentifiers disconNotifyID) { RakNet::BitStream bitStream; - PacketUtils::WriteHeader(bitStream, SERVER, MSG_SERVER_DISCONNECT_NOTIFY); + PacketUtils::WriteHeader(bitStream, eConnectionType::SERVER, eServerMessageType::DISCONNECT_NOTIFY); bitStream.Write(disconNotifyID); mPeer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE_ORDERED, 0, sysAddr, false); diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 71384207..4eca86f2 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -31,7 +31,6 @@ #include "PacketUtils.h" #include "WorldPackets.h" #include "UserManager.h" -#include "dMessageIdentifiers.h" #include "CDClientManager.h" #include "CDClientDatabase.h" #include "GeneralUtils.h" @@ -65,7 +64,12 @@ #include "NiPoint3.h" #include "eServerDisconnectIdentifiers.h" #include "eObjectBits.h" - +#include "eConnectionType.h" +#include "eServerMessageType.h" +#include "eChatInternalMessageType.h" +#include "eWorldMessageType.h" +#include "eMasterMessageType.h" +#include "eGameMessageType.h" #include "ZCompression.h" namespace Game { @@ -547,9 +551,9 @@ void HandlePacketChat(Packet* packet) { } if (packet->data[0] == ID_USER_PACKET_ENUM) { - if (packet->data[1] == CHAT_INTERNAL) { - switch (packet->data[3]) { - case MSG_CHAT_INTERNAL_ROUTE_TO_PLAYER: { + if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::CHAT_INTERNAL) { + switch (static_cast<eChatInternalMessageType>(packet->data[3])) { + case eChatInternalMessageType::ROUTE_TO_PLAYER: { CINSTREAM; LWOOBJID playerID; inStream.Read(playerID); @@ -571,7 +575,7 @@ void HandlePacketChat(Packet* packet) { break; } - case MSG_CHAT_INTERNAL_ANNOUNCEMENT: { + case eChatInternalMessageType::ANNOUNCEMENT: { CINSTREAM; LWOOBJID header; inStream.Read(header); @@ -610,7 +614,7 @@ void HandlePacketChat(Packet* packet) { break; } - case MSG_CHAT_INTERNAL_MUTE_UPDATE: { + case eChatInternalMessageType::MUTE_UPDATE: { CINSTREAM; LWOOBJID playerId; time_t expire = 0; @@ -629,7 +633,7 @@ void HandlePacketChat(Packet* packet) { break; } - case MSG_CHAT_INTERNAL_TEAM_UPDATE: { + case eChatInternalMessageType::TEAM_UPDATE: { CINSTREAM; LWOOBJID header; inStream.Read(header); @@ -706,7 +710,7 @@ void HandlePacket(Packet* packet) { { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::PLAYER_REMOVED_NOTIFICATION); bitStream.Write(user->GetLoggedInChar()); Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); } @@ -718,35 +722,35 @@ void HandlePacket(Packet* packet) { } CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_PLAYER_REMOVED); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::PLAYER_REMOVED); bitStream.Write((LWOMAPID)Game::server->GetZoneID()); bitStream.Write((LWOINSTANCEID)instanceID); Game::server->SendToMaster(&bitStream); } if (packet->data[0] != ID_USER_PACKET_ENUM) return; - if (packet->data[1] == SERVER) { - if (packet->data[3] == MSG_SERVER_VERSION_CONFIRM) { + if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::SERVER) { + if (static_cast<eServerMessageType>(packet->data[3]) == eServerMessageType::VERSION_CONFIRM) { AuthPackets::HandleHandshake(Game::server, packet); } } - if (packet->data[1] == MASTER) { - switch (packet->data[3]) { - case MSG_MASTER_REQUEST_PERSISTENT_ID_RESPONSE: { + if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::MASTER) { + switch (static_cast<eMasterMessageType>(packet->data[3])) { + case eMasterMessageType::REQUEST_PERSISTENT_ID_RESPONSE: { uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); uint32_t objectID = PacketUtils::ReadPacketU32(16, packet); ObjectIDManager::Instance()->HandleRequestPersistentIDResponse(requestID, objectID); break; } - case MSG_MASTER_REQUEST_ZONE_TRANSFER_RESPONSE: { + case eMasterMessageType::REQUEST_ZONE_TRANSFER_RESPONSE: { uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); ZoneInstanceManager::Instance()->HandleRequestZoneTransferResponse(requestID, packet); break; } - case MSG_MASTER_SESSION_KEY_RESPONSE: { + case eMasterMessageType::SESSION_KEY_RESPONSE: { //Read our session key and to which user it belongs: RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); @@ -803,7 +807,7 @@ void HandlePacket(Packet* packet) { //Notify master: { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_PLAYER_ADDED); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::PLAYER_ADDED); bitStream.Write((LWOMAPID)Game::server->GetZoneID()); bitStream.Write((LWOINSTANCEID)instanceID); Game::server->SendToMaster(&bitStream); @@ -812,27 +816,27 @@ void HandlePacket(Packet* packet) { break; } - case MSG_MASTER_AFFIRM_TRANSFER_REQUEST: { + case eMasterMessageType::AFFIRM_TRANSFER_REQUEST: { const uint64_t requestID = PacketUtils::ReadPacketU64(8, packet); Game::logger->Log("MasterServer", "Got affirmation request of transfer %llu", requestID); CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_AFFIRM_TRANSFER_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::AFFIRM_TRANSFER_RESPONSE); bitStream.Write(requestID); Game::server->SendToMaster(&bitStream); break; } - case MSG_MASTER_SHUTDOWN: { + case eMasterMessageType::SHUTDOWN: { Game::shouldShutdown = true; Game::logger->Log("WorldServer", "Got shutdown request from master, zone (%i), instance (%i)", Game::server->GetZoneID(), Game::server->GetInstanceID()); break; } - case MSG_MASTER_NEW_SESSION_ALERT: { + case eMasterMessageType::NEW_SESSION_ALERT: { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); uint32_t sessionKey = inStream.Read(sessionKey); @@ -870,10 +874,10 @@ void HandlePacket(Packet* packet) { return; } - if (packet->data[1] != WORLD) return; + if (static_cast<eConnectionType>(packet->data[1]) != eConnectionType::WORLD) return; - switch (packet->data[3]) { - case MSG_WORLD_CLIENT_VALIDATION: { + switch (static_cast<eWorldMessageType>(packet->data[3])) { + case eWorldMessageType::VALIDATION: { std::string username = PacketUtils::ReadString(0x08, packet, true); std::string sessionKey = PacketUtils::ReadString(74, packet, true); std::string clientDatabaseChecksum = PacketUtils::ReadString(packet->length - 33, packet, false); @@ -905,7 +909,7 @@ void HandlePacket(Packet* packet) { //Request the session info from Master: CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_REQUEST_SESSION_KEY); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::REQUEST_SESSION_KEY); PacketUtils::WriteString(bitStream, username, 64); Game::server->SendToMaster(&bitStream); @@ -918,7 +922,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_WORLD_CLIENT_CHARACTER_LIST_REQUEST: { + case eWorldMessageType::CHARACTER_LIST_REQUEST: { //We need to delete the entity first, otherwise the char list could delete it while it exists in the world! if (Game::server->GetZoneID() != 0) { auto user = UserManager::Instance()->GetUser(packet->systemAddress); @@ -940,12 +944,12 @@ void HandlePacket(Packet* packet) { break; } - case MSG_WORLD_CLIENT_GAME_MSG: { + case eWorldMessageType::GAME_MSG: { RakNet::BitStream bitStream(packet->data, packet->length, false); uint64_t header; LWOOBJID objectID; - uint16_t messageID; + eGameMessageType messageID; bitStream.Read(header); bitStream.Read(objectID); @@ -954,16 +958,16 @@ void HandlePacket(Packet* packet) { RakNet::BitStream dataStream; bitStream.Read(dataStream, bitStream.GetNumberOfUnreadBits()); - GameMessageHandler::HandleMessage(&dataStream, packet->systemAddress, objectID, GAME_MSG(messageID)); + GameMessageHandler::HandleMessage(&dataStream, packet->systemAddress, objectID, messageID); break; } - case MSG_WORLD_CLIENT_CHARACTER_CREATE_REQUEST: { + case eWorldMessageType::CHARACTER_CREATE_REQUEST: { UserManager::Instance()->CreateCharacter(packet->systemAddress, packet); break; } - case MSG_WORLD_CLIENT_LOGIN_REQUEST: { + case eWorldMessageType::LOGIN_REQUEST: { RakNet::BitStream inStream(packet->data, packet->length, false); uint64_t header = inStream.Read(header); @@ -979,7 +983,7 @@ void HandlePacket(Packet* packet) { // This means we swapped characters and we need to remove the previous player from the container. if (static_cast<uint32_t>(lastCharacter) != playerID) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_REMOVED_NOTIFICATION); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::PLAYER_REMOVED_NOTIFICATION); bitStream.Write(lastCharacter); Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); } @@ -989,18 +993,18 @@ void HandlePacket(Packet* packet) { break; } - case MSG_WORLD_CLIENT_CHARACTER_DELETE_REQUEST: { + case eWorldMessageType::CHARACTER_DELETE_REQUEST: { UserManager::Instance()->DeleteCharacter(packet->systemAddress, packet); UserManager::Instance()->RequestCharacterList(packet->systemAddress); break; } - case MSG_WORLD_CLIENT_CHARACTER_RENAME_REQUEST: { + case eWorldMessageType::CHARACTER_RENAME_REQUEST: { UserManager::Instance()->RenameCharacter(packet->systemAddress, packet); break; } - case MSG_WORLD_CLIENT_LEVEL_LOAD_COMPLETE: { + case eWorldMessageType::LEVEL_LOAD_COMPLETE: { Game::logger->Log("WorldServer", "Received level load complete from user."); User* user = UserManager::Instance()->GetUser(packet->systemAddress); if (user) { @@ -1128,7 +1132,7 @@ void HandlePacket(Packet* packet) { GeneralUtils::SetBit(blueprintID, eObjectBits::PERSISTENT); CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CLIENT, MSG_CLIENT_BLUEPRINT_SAVE_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::BLUEPRINT_SAVE_RESPONSE); bitStream.Write<LWOOBJID>(LWOOBJID_EMPTY); //always zero so that a check on the client passes bitStream.Write(eBlueprintSaveResponseType::EverythingWorked); bitStream.Write<uint32_t>(1); @@ -1169,7 +1173,7 @@ void HandlePacket(Packet* packet) { //RakNet::RakString playerName(player->GetCharacter()->GetName().c_str()); CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT_INTERNAL, MSG_CHAT_INTERNAL_PLAYER_ADDED_NOTIFICATION); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::PLAYER_ADDED_NOTIFICATION); bitStream.Write(player->GetObjectID()); bitStream.Write<uint32_t>(playerName.size()); for (size_t i = 0; i < playerName.size(); i++) { @@ -1194,12 +1198,12 @@ void HandlePacket(Packet* packet) { break; } - case MSG_WORLD_CLIENT_POSITION_UPDATE: { + case eWorldMessageType::POSITION_UPDATE: { ClientPackets::HandleClientPositionUpdate(packet->systemAddress, packet); break; } - case MSG_WORLD_CLIENT_MAIL: { + case eWorldMessageType::MAIL: { RakNet::BitStream bitStream(packet->data, packet->length, false); LWOOBJID space; bitStream.Read(space); @@ -1207,7 +1211,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_WORLD_CLIENT_ROUTE_PACKET: { + case eWorldMessageType::ROUTE_PACKET: { //Yeet to chat CINSTREAM; uint64_t header = 0; @@ -1222,7 +1226,7 @@ void HandlePacket(Packet* packet) { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, CHAT, packet->data[14]); + PacketUtils::WriteHeader(bitStream, eConnectionType::CHAT, packet->data[14]); //We need to insert the player's objectID so the chat server can find who originated this request: LWOOBJID objectID = 0; @@ -1243,12 +1247,12 @@ void HandlePacket(Packet* packet) { break; } - case MSG_WORLD_CLIENT_STRING_CHECK: { + case eWorldMessageType::STRING_CHECK: { ClientPackets::HandleChatModerationRequest(packet->systemAddress, packet); break; } - case MSG_WORLD_CLIENT_GENERAL_CHAT_MESSAGE: { + case eWorldMessageType::GENERAL_CHAT_MESSAGE: { if (chatDisabled) { ChatPackets::SendMessageFail(packet->systemAddress); } else { @@ -1258,7 +1262,7 @@ void HandlePacket(Packet* packet) { break; } - case MSG_WORLD_CLIENT_HANDLE_FUNNESS: { + case eWorldMessageType::HANDLE_FUNNESS: { //This means the client is running slower or faster than it should. //Could be insane lag, but I'mma just YEET them as it's usually speedhacking. //This is updated to now count the amount of times we've been caught "speedhacking" to kick with a delay @@ -1346,6 +1350,6 @@ void FinalizeShutdown() { void SendShutdownMessageToMaster() { CBITSTREAM; - PacketUtils::WriteHeader(bitStream, MASTER, MSG_MASTER_SHUTDOWN_RESPONSE); + PacketUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SHUTDOWN_RESPONSE); Game::server->SendToMaster(&bitStream); } From df3265c82e7ea712a892e5e7974e79044c6981ef Mon Sep 17 00:00:00 2001 From: David Markowitz <EmosewaMC@gmail.com> Date: Fri, 5 May 2023 23:31:30 -0700 Subject: [PATCH 311/322] Add more null checks and split out code Makes crash logs more apparent for what stage they crashed in for the engine updating. --- dGame/EntityManager.cpp | 69 +++++++++++-------- dGame/EntityManager.h | 4 ++ .../ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp | 45 ++++++------ 3 files changed, 67 insertions(+), 51 deletions(-) diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index 1a77d365..0fc859bd 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -161,9 +161,7 @@ void EntityManager::DestroyEntity(const LWOOBJID& objectID) { } void EntityManager::DestroyEntity(Entity* entity) { - if (entity == nullptr) { - return; - } + if (!entity) return; entity->TriggerEvent(eTriggerEventType::DESTROY, entity); @@ -182,15 +180,11 @@ void EntityManager::DestroyEntity(Entity* entity) { ScheduleForDeletion(id); } -void EntityManager::UpdateEntities(const float deltaTime) { - for (const auto& e : m_Entities) { - e.second->Update(deltaTime); - } - +void EntityManager::SerializeEntities() { for (auto entry = m_EntitiesToSerialize.begin(); entry != m_EntitiesToSerialize.end(); entry++) { auto* entity = GetEntity(*entry); - if (entity == nullptr) continue; + if (!entity) continue; m_SerializationCounter++; @@ -212,11 +206,16 @@ void EntityManager::UpdateEntities(const float deltaTime) { } } m_EntitiesToSerialize.clear(); +} +void EntityManager::KillEntities() { for (auto entry = m_EntitiesToKill.begin(); entry != m_EntitiesToKill.end(); entry++) { auto* entity = GetEntity(*entry); - if (!entity) continue; + if (!entity) { + Game::logger->Log("EntityManager", "Attempting to kill null entity %llu", *entry); + continue; + } if (entity->GetScheduledKiller()) { entity->Smash(entity->GetScheduledKiller()->GetObjectID(), eKillType::SILENT); @@ -225,32 +224,41 @@ void EntityManager::UpdateEntities(const float deltaTime) { } } m_EntitiesToKill.clear(); +} +void EntityManager::DeleteEntities() { for (auto entry = m_EntitiesToDelete.begin(); entry != m_EntitiesToDelete.end(); entry++) { - - // Get all this info first before we delete the player. auto entityToDelete = GetEntity(*entry); - auto networkIdToErase = entityToDelete->GetNetworkId(); - const auto& ghostingToDelete = std::find(m_EntitiesToGhost.begin(), m_EntitiesToGhost.end(), entityToDelete); - if (entityToDelete) { - // If we are a player run through the player destructor. - if (entityToDelete->IsPlayer()) { - delete dynamic_cast<Player*>(entityToDelete); - } else { - delete entityToDelete; - } + // Get all this info first before we delete the player. + auto networkIdToErase = entityToDelete->GetNetworkId(); + const auto& ghostingToDelete = std::find(m_EntitiesToGhost.begin(), m_EntitiesToGhost.end(), entityToDelete); + + delete entityToDelete; + entityToDelete = nullptr; + if (networkIdToErase != 0) m_LostNetworkIds.push(networkIdToErase); + + if (ghostingToDelete != m_EntitiesToGhost.end()) m_EntitiesToGhost.erase(ghostingToDelete); + } else { + Game::logger->Log("EntityManager", "Attempted to delete non-existent entity %llu", *entry); } - - if (ghostingToDelete != m_EntitiesToGhost.end()) m_EntitiesToGhost.erase(ghostingToDelete); - m_Entities.erase(*entry); } m_EntitiesToDelete.clear(); } +void EntityManager::UpdateEntities(const float deltaTime) { + for (const auto& e : m_Entities) { + e.second->Update(deltaTime); + } + + SerializeEntities(); + KillEntities(); + DeleteEntities(); +} + Entity* EntityManager::GetEntity(const LWOOBJID& objectId) const { const auto& index = m_Entities.find(objectId); @@ -316,6 +324,11 @@ const std::unordered_map<std::string, LWOOBJID>& EntityManager::GetSpawnPointEnt } void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr, const bool skipChecks) { + if (!entity) { + Game::logger->Log("EntityManager", "Attempted to construct null entity"); + return; + } + if (entity->GetNetworkId() == 0) { uint16_t networkId; @@ -395,9 +408,7 @@ void EntityManager::ConstructAllEntities(const SystemAddress& sysAddr) { } void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr) { - if (entity->GetNetworkId() == 0) { - return; - } + if (!entity || entity->GetNetworkId() == 0) return; RakNet::BitStream stream; @@ -414,9 +425,7 @@ void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr) } void EntityManager::SerializeEntity(Entity* entity) { - if (entity->GetNetworkId() == 0) { - return; - } + if (!entity || entity->GetNetworkId() == 0) return; if (std::find(m_EntitiesToSerialize.begin(), m_EntitiesToSerialize.end(), entity->GetObjectID()) == m_EntitiesToSerialize.end()) { m_EntitiesToSerialize.push_back(entity->GetObjectID()); diff --git a/dGame/EntityManager.h b/dGame/EntityManager.h index 0314cc09..b524344c 100644 --- a/dGame/EntityManager.h +++ b/dGame/EntityManager.h @@ -85,6 +85,10 @@ public: const uint32_t GetHardcoreUscoreEnemiesMultiplier() { return m_HardcoreUscoreEnemiesMultiplier; }; private: + void SerializeEntities(); + void KillEntities(); + void DeleteEntities(); + static EntityManager* m_Address; //For singleton method static std::vector<LWOMAPID> m_GhostingExcludedZones; static std::vector<LOT> m_GhostingExcludedLOTs; diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp index bdd7a506..50cd229a 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp @@ -275,6 +275,11 @@ void SGCannon::OnActivityTimerDone(Entity* self, const std::string& name) { toSpawn.spawnPaths.at(pathIndex) ); + if (!path) { + Game::logger->Log("SGCannon", "Path %s at index %i is null", toSpawn.spawnPaths.at(pathIndex).c_str(), pathIndex); + return; + } + auto info = EntityInfo{}; info.lot = toSpawn.lot; info.spawnerID = self->GetObjectID(); @@ -294,32 +299,30 @@ void SGCannon::OnActivityTimerDone(Entity* self, const std::string& name) { auto* enemy = EntityManager::Instance()->CreateEntity(info, nullptr, self); EntityManager::Instance()->ConstructEntity(enemy); - if (true) { - auto* movementAI = new MovementAIComponent(enemy, {}); + auto* movementAI = new MovementAIComponent(enemy, {}); - enemy->AddComponent(eReplicaComponentType::MOVEMENT_AI, movementAI); + enemy->AddComponent(eReplicaComponentType::MOVEMENT_AI, movementAI); - movementAI->SetSpeed(toSpawn.initialSpeed); - movementAI->SetCurrentSpeed(toSpawn.initialSpeed); - movementAI->SetHaltDistance(0.0f); + movementAI->SetSpeed(toSpawn.initialSpeed); + movementAI->SetCurrentSpeed(toSpawn.initialSpeed); + movementAI->SetHaltDistance(0.0f); - std::vector<NiPoint3> pathWaypoints; + std::vector<NiPoint3> pathWaypoints; - for (const auto& waypoint : path->pathWaypoints) { - pathWaypoints.push_back(waypoint.position); - } - - if (GeneralUtils::GenerateRandomNumber<float_t>(0, 1) < 0.5f) { - std::reverse(pathWaypoints.begin(), pathWaypoints.end()); - } - - movementAI->SetPath(pathWaypoints); - - enemy->AddDieCallback([this, self, enemy, name]() { - RegisterHit(self, enemy, name); - }); + for (const auto& waypoint : path->pathWaypoints) { + pathWaypoints.push_back(waypoint.position); } + if (GeneralUtils::GenerateRandomNumber<float_t>(0, 1) < 0.5f) { + std::reverse(pathWaypoints.begin(), pathWaypoints.end()); + } + + movementAI->SetPath(pathWaypoints); + + enemy->AddDieCallback([this, self, enemy, name]() { + RegisterHit(self, enemy, name); + }); + // Save the enemy and tell it to start pathing if (enemy != nullptr) { const_cast<std::vector<LWOOBJID>&>(self->GetVar<std::vector<LWOOBJID>>(SpawnedObjects)).push_back(enemy->GetObjectID()); @@ -577,7 +580,7 @@ void SGCannon::StopGame(Entity* self, bool cancel) { self->SetNetworkVar<std::u16string>(u"UI_Rewards", GeneralUtils::to_u16string(self->GetVar<uint32_t>(TotalScoreVariable)) + u"_0_0_0_0_0_0" - ); + ); GameMessages::SendRequestActivitySummaryLeaderboardData( player->GetObjectID(), From 5479cf44287a0f8c542252a5ee7f7a54045473ea Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Sat, 6 May 2023 13:32:26 -0500 Subject: [PATCH 312/322] Fix typing of some player flag variables (#1067) Mainly on properties Tested that the spider queen mission can now be progressed --- dScripts/02_server/Map/AG_Spider_Queen/ZoneAgSpiderQueen.cpp | 4 ++-- dScripts/02_server/Map/Property/AG_Med/ZoneAgMedProperty.cpp | 4 ++-- dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp | 4 ++-- dScripts/BasePropertyServer.cpp | 4 ++-- dScripts/ai/PROPERTY/AgPropguards.cpp | 2 +- dScripts/ai/PROPERTY/AgPropguards.h | 2 +- dScripts/zone/PROPERTY/FV/ZoneFvProperty.cpp | 4 ++-- dScripts/zone/PROPERTY/GF/ZoneGfProperty.cpp | 4 ++-- dScripts/zone/PROPERTY/NS/ZoneNsProperty.cpp | 4 ++-- 9 files changed, 16 insertions(+), 16 deletions(-) diff --git a/dScripts/02_server/Map/AG_Spider_Queen/ZoneAgSpiderQueen.cpp b/dScripts/02_server/Map/AG_Spider_Queen/ZoneAgSpiderQueen.cpp index 5996548f..2711b179 100644 --- a/dScripts/02_server/Map/AG_Spider_Queen/ZoneAgSpiderQueen.cpp +++ b/dScripts/02_server/Map/AG_Spider_Queen/ZoneAgSpiderQueen.cpp @@ -9,8 +9,8 @@ void ZoneAgSpiderQueen::SetGameVariables(Entity* self) { ZoneAgProperty::SetGameVariables(self); // Disable property flags - self->SetVar<uint32_t>(defeatedProperyFlag, 0); - self->SetVar<uint32_t>(placedModelFlag, 0); + self->SetVar<int32_t>(defeatedProperyFlag, 0); + self->SetVar<int32_t>(placedModelFlag, 0); self->SetVar<uint32_t>(guardFirstMissionFlag, 0); self->SetVar<uint32_t>(guardMissionFlag, 0); self->SetVar<uint32_t>(brickLinkMissionIDFlag, 0); diff --git a/dScripts/02_server/Map/Property/AG_Med/ZoneAgMedProperty.cpp b/dScripts/02_server/Map/Property/AG_Med/ZoneAgMedProperty.cpp index db1c4c4b..46ec7bbd 100644 --- a/dScripts/02_server/Map/Property/AG_Med/ZoneAgMedProperty.cpp +++ b/dScripts/02_server/Map/Property/AG_Med/ZoneAgMedProperty.cpp @@ -31,8 +31,8 @@ void ZoneAgMedProperty::SetGameVariables(Entity* self) { self->SetVar<std::vector<std::string>>(AmbientFXSpawner, { "BirdFX", "SunBeam" }); self->SetVar<std::vector<std::string>>(BehaviorObjsSpawner, {}); - self->SetVar<uint32_t>(defeatedProperyFlag, 118); - self->SetVar<uint32_t>(placedModelFlag, 119); + self->SetVar<int32_t>(defeatedProperyFlag, 118); + self->SetVar<int32_t>(placedModelFlag, 119); self->SetVar<uint32_t>(guardMissionFlag, 1293); self->SetVar<uint32_t>(brickLinkMissionIDFlag, 1294); self->SetVar<std::string>(passwordFlag, "s3kratK1ttN"); diff --git a/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp b/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp index 635eb8b3..6bf91768 100644 --- a/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp +++ b/dScripts/02_server/Map/Property/AG_Small/ZoneAgProperty.cpp @@ -39,8 +39,8 @@ void ZoneAgProperty::SetGameVariables(Entity* self) { self->SetVar<std::string>(LauncherSpawner, "Launcher"); self->SetVar<std::string>(InstancerSpawner, "Instancer"); - self->SetVar<uint32_t>(defeatedProperyFlag, 71); - self->SetVar<uint32_t>(placedModelFlag, 73); + self->SetVar<int32_t>(defeatedProperyFlag, 71); + self->SetVar<int32_t>(placedModelFlag, 73); self->SetVar<uint32_t>(guardFirstMissionFlag, 891); self->SetVar<uint32_t>(guardMissionFlag, 320); self->SetVar<uint32_t>(brickLinkMissionIDFlag, 951); diff --git a/dScripts/BasePropertyServer.cpp b/dScripts/BasePropertyServer.cpp index 1522ef26..72cce09f 100644 --- a/dScripts/BasePropertyServer.cpp +++ b/dScripts/BasePropertyServer.cpp @@ -38,8 +38,8 @@ void BasePropertyServer::SetGameVariables(Entity* self) { self->SetVar<std::vector<std::string>>(AmbientFXSpawner, {}); self->SetVar<std::vector<std::string>>(BehaviorObjsSpawner, {}); - self->SetVar<uint32_t>(defeatedProperyFlag, 0); - self->SetVar<uint32_t>(placedModelFlag, 0); + self->SetVar<int32_t>(defeatedProperyFlag, 0); + self->SetVar<int32_t>(placedModelFlag, 0); self->SetVar<uint32_t>(guardMissionFlag, 0); self->SetVar<uint32_t>(brickLinkMissionIDFlag, 0); self->SetVar<std::string>(passwordFlag, "s3kratK1ttN"); diff --git a/dScripts/ai/PROPERTY/AgPropguards.cpp b/dScripts/ai/PROPERTY/AgPropguards.cpp index 9fc6010a..7e8e2fd1 100644 --- a/dScripts/ai/PROPERTY/AgPropguards.cpp +++ b/dScripts/ai/PROPERTY/AgPropguards.cpp @@ -39,7 +39,7 @@ void AgPropguards::OnMissionDialogueOK(Entity* self, Entity* target, int mission } } -uint32_t AgPropguards::GetFlagForMission(uint32_t missionID) { +int32_t AgPropguards::GetFlagForMission(uint32_t missionID) { switch (missionID) { case 872: return 97; diff --git a/dScripts/ai/PROPERTY/AgPropguards.h b/dScripts/ai/PROPERTY/AgPropguards.h index 25701f86..ed2e3cb0 100644 --- a/dScripts/ai/PROPERTY/AgPropguards.h +++ b/dScripts/ai/PROPERTY/AgPropguards.h @@ -4,5 +4,5 @@ class AgPropguards : public CppScripts::Script { void OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) override; private: - static uint32_t GetFlagForMission(uint32_t missionID); + static int32_t GetFlagForMission(uint32_t missionID); }; diff --git a/dScripts/zone/PROPERTY/FV/ZoneFvProperty.cpp b/dScripts/zone/PROPERTY/FV/ZoneFvProperty.cpp index 67ada039..8b8072ad 100644 --- a/dScripts/zone/PROPERTY/FV/ZoneFvProperty.cpp +++ b/dScripts/zone/PROPERTY/FV/ZoneFvProperty.cpp @@ -29,8 +29,8 @@ void ZoneFvProperty::SetGameVariables(Entity* self) { self->SetVar<std::vector<std::string>>(AmbientFXSpawner, { "Ash", "FX", "Fog" }); self->SetVar<std::vector<std::string>>(BehaviorObjsSpawner, {}); - self->SetVar<uint32_t>(defeatedProperyFlag, 99); - self->SetVar<uint32_t>(placedModelFlag, 107); + self->SetVar<int32_t>(defeatedProperyFlag, 99); + self->SetVar<int32_t>(placedModelFlag, 107); self->SetVar<uint32_t>(guardMissionFlag, 874); self->SetVar<uint32_t>(brickLinkMissionIDFlag, 950); self->SetVar<std::string>(passwordFlag, "s3kratK1ttN"); diff --git a/dScripts/zone/PROPERTY/GF/ZoneGfProperty.cpp b/dScripts/zone/PROPERTY/GF/ZoneGfProperty.cpp index 565d8cd6..87b2345d 100644 --- a/dScripts/zone/PROPERTY/GF/ZoneGfProperty.cpp +++ b/dScripts/zone/PROPERTY/GF/ZoneGfProperty.cpp @@ -29,8 +29,8 @@ void ZoneGfProperty::SetGameVariables(Entity* self) { self->SetVar<std::vector<std::string>>(AmbientFXSpawner, { "Birds", "Falls", "Sunbeam" }); self->SetVar<std::vector<std::string>>(BehaviorObjsSpawner, { "TrappedPlatform", "IceBarrier", "FireBeast" }); - self->SetVar<uint32_t>(defeatedProperyFlag, 98); - self->SetVar<uint32_t>(placedModelFlag, 106); + self->SetVar<int32_t>(defeatedProperyFlag, 98); + self->SetVar<int32_t>(placedModelFlag, 106); self->SetVar<uint32_t>(guardMissionFlag, 873); self->SetVar<uint32_t>(brickLinkMissionIDFlag, 949); self->SetVar<std::string>(passwordFlag, "s3kratK1ttN"); diff --git a/dScripts/zone/PROPERTY/NS/ZoneNsProperty.cpp b/dScripts/zone/PROPERTY/NS/ZoneNsProperty.cpp index 49364ee8..52bb02e2 100644 --- a/dScripts/zone/PROPERTY/NS/ZoneNsProperty.cpp +++ b/dScripts/zone/PROPERTY/NS/ZoneNsProperty.cpp @@ -30,8 +30,8 @@ void ZoneNsProperty::SetGameVariables(Entity* self) { self->SetVar<std::vector<std::string>>(AmbientFXSpawner, { "Rockets" }); self->SetVar<std::vector<std::string>>(BehaviorObjsSpawner, { "Cage", "Platform", "Door" }); - self->SetVar<uint32_t>(defeatedProperyFlag, 97); - self->SetVar<uint32_t>(placedModelFlag, 105); + self->SetVar<int32_t>(defeatedProperyFlag, 97); + self->SetVar<int32_t>(placedModelFlag, 105); self->SetVar<uint32_t>(guardMissionFlag, 872); self->SetVar<uint32_t>(brickLinkMissionIDFlag, 948); self->SetVar<std::string>(passwordFlag, "s3kratK1ttN"); From cffb1449d86193e408ca0565eccab780907db915 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 6 May 2023 11:32:38 -0700 Subject: [PATCH 313/322] Add better logs to saving (#1068) * Fix overread in projectile behavior * Fix stuns * Correctly read in bitStream * Fix projectile behavior * Address movement type issues * Update shutdown time to be accurate * Fix small issues * Fix missing template * Add note for compile jobs * Add bounds check for speed division * Add better logs --- dGame/Character.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dGame/Character.cpp b/dGame/Character.cpp index e565ed4f..319b9376 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -373,7 +373,7 @@ void Character::SaveXMLToDatabase() { //Call upon the entity to update our xmlDoc: if (!m_OurEntity) { - Game::logger->Log("Character", "We didn't have an entity set while saving! CHARACTER WILL NOT BE SAVED!"); + Game::logger->Log("Character", "%i:%s didn't have an entity set while saving! CHARACTER WILL NOT BE SAVED!", this->GetID(), this->GetName().c_str()); return; } @@ -384,7 +384,7 @@ void Character::SaveXMLToDatabase() { //For metrics, log the time it took to save: auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed = end - start; - Game::logger->Log("Character", "Saved character to Database in: %fs", elapsed.count()); + Game::logger->Log("Character", "%i:%s Saved character to Database in: %fs", this->GetID(), this->GetName().c_str(), elapsed.count()); } void Character::SetIsNewLogin() { @@ -396,7 +396,7 @@ void Character::SetIsNewLogin() { while (currentChild) { if (currentChild->Attribute("si")) { flags->DeleteChild(currentChild); - Game::logger->Log("Character", "Removed isLoggedIn flag from character %i, saving character to database", GetID()); + Game::logger->Log("Character", "Removed isLoggedIn flag from character %i:%s, saving character to database", GetID(), GetName().c_str()); WriteToDatabase(); } currentChild = currentChild->NextSiblingElement(); From 7949907517411da0aeeb508676c15745280c5a03 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 6 May 2023 11:32:46 -0700 Subject: [PATCH 314/322] Fix bounds check (#1070) --- dPhysics/dpGrid.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/dPhysics/dpGrid.cpp b/dPhysics/dpGrid.cpp index b4fe385e..1631c91a 100644 --- a/dPhysics/dpGrid.cpp +++ b/dPhysics/dpGrid.cpp @@ -63,13 +63,13 @@ void dpGrid::Move(dpEntity* entity, float x, float z) { if (cellX < 0) cellX = 0; if (cellZ < 0) cellZ = 0; - if (cellX > NUM_CELLS) cellX = NUM_CELLS; - if (cellZ > NUM_CELLS) cellZ = NUM_CELLS; + if (cellX >= NUM_CELLS) cellX = NUM_CELLS - 1; + if (cellZ >= NUM_CELLS) cellZ = NUM_CELLS - 1; if (oldCellX < 0) oldCellX = 0; if (oldCellZ < 0) oldCellZ = 0; - if (oldCellX > NUM_CELLS) oldCellX = NUM_CELLS; - if (oldCellZ > NUM_CELLS) oldCellZ = NUM_CELLS; + if (oldCellX >= NUM_CELLS) oldCellX = NUM_CELLS - 1; + if (oldCellZ >= NUM_CELLS) oldCellZ = NUM_CELLS - 1; if (oldCellX == cellX && oldCellZ == cellZ) return; From 33c12f3bc5998d7af601571aed01a13df99c34f4 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 6 May 2023 11:32:53 -0700 Subject: [PATCH 315/322] Fix bounds check (#1071) Fix Chat Crash Update CMakeVariables.txt Add checks for all servers --- dAuthServer/AuthServer.cpp | 2 ++ dChatServer/ChatServer.cpp | 2 ++ dMasterServer/MasterServer.cpp | 2 ++ dWorldServer/WorldServer.cpp | 2 +- 4 files changed, 7 insertions(+), 1 deletion(-) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index ddec32db..262886d7 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -171,6 +171,8 @@ dLogger* SetupLogger() { } void HandlePacket(Packet* packet) { + if (packet->length < 4) return; + if (packet->data[0] == ID_USER_PACKET_ENUM) { if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::SERVER) { if (static_cast<eServerMessageType>(packet->data[3]) == eServerMessageType::VERSION_CONFIRM) { diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index 3e3ddfd3..b9fb8556 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -203,6 +203,8 @@ void HandlePacket(Packet* packet) { Game::logger->Log("ChatServer", "A server is connecting, awaiting user list."); } + if (packet->length < 4) return; // Nothing left to process. Need 4 bytes to continue. + if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::CHAT_INTERNAL) { switch (static_cast<eChatInternalMessageType>(packet->data[3])) { case eChatInternalMessageType::PLAYER_ADDED_NOTIFICATION: diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index 4b524d8d..bc0937c2 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -495,6 +495,8 @@ void HandlePacket(Packet* packet) { } } + if (packet->length < 4) return; + if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::MASTER) { switch (static_cast<eMasterMessageType>(packet->data[3])) { case eMasterMessageType::REQUEST_PERSISTENT_ID: { diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 4eca86f2..26cbe7ba 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -728,7 +728,7 @@ void HandlePacket(Packet* packet) { Game::server->SendToMaster(&bitStream); } - if (packet->data[0] != ID_USER_PACKET_ENUM) return; + if (packet->data[0] != ID_USER_PACKET_ENUM || packet->length < 4) return; if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::SERVER) { if (static_cast<eServerMessageType>(packet->data[3]) == eServerMessageType::VERSION_CONFIRM) { AuthPackets::HandleHandshake(Game::server, packet); From 7e616385957ec683b48067e9c5960f17a270c7aa Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Sat, 6 May 2023 23:45:07 -0700 Subject: [PATCH 316/322] Reinforce PacketUtils writing (#1073) Ensure the correct size is written to the bitstream. It is always supposed to write 64 bits. --- dNet/PacketUtils.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/dNet/PacketUtils.h b/dNet/PacketUtils.h index 7c917f2e..d07759a0 100644 --- a/dNet/PacketUtils.h +++ b/dNet/PacketUtils.h @@ -10,10 +10,10 @@ enum class eConnectionType : uint16_t; namespace PacketUtils { template<typename T> void WriteHeader(RakNet::BitStream& bitStream, eConnectionType connectionType, T internalPacketID) { - bitStream.Write(MessageID(ID_USER_PACKET_ENUM)); - bitStream.Write(connectionType); - bitStream.Write(internalPacketID); - bitStream.Write(uint8_t(0)); + bitStream.Write<uint8_t>(MessageID(ID_USER_PACKET_ENUM)); + bitStream.Write<eConnectionType>(connectionType); + bitStream.Write<uint32_t>(static_cast<uint32_t>(internalPacketID)); + bitStream.Write<uint8_t>(0); } uint16_t ReadPacketU16(uint32_t startLoc, Packet* packet); From 8ceabadcded407f424c65c7cacc825c761840daf Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Mon, 8 May 2023 04:38:08 -0500 Subject: [PATCH 317/322] Removed some hardcoded logic for racing (#1075) Including return world and what activity ID to use for rewards --- dGame/dComponents/RacingControlComponent.cpp | 36 +++++-------------- .../dComponents/ScriptedActivityComponent.cpp | 6 ++-- dGame/dUtilities/SlashCommandHandler.cpp | 17 ++------- dGame/dUtilities/SlashCommandHandler.h | 2 -- dZoneManager/dZoneManager.cpp | 13 +++++++ dZoneManager/dZoneManager.h | 1 + 6 files changed, 27 insertions(+), 48 deletions(-) diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 703ec7f3..3134d5fe 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -23,6 +23,8 @@ #include "dConfig.h" #include "Loot.h" #include "eMissionTaskType.h" +#include "dZoneManager.h" +#include "CDActivitiesTable.h" #ifndef M_PI #define M_PI 3.14159265358979323846264338327950288 @@ -45,36 +47,14 @@ RacingControlComponent::RacingControlComponent(Entity* parent) m_EmptyTimer = 0; m_SoloRacing = Game::config->GetValue("solo_racing") == "1"; - // Select the main world ID as fallback when a player fails to load. - + m_MainWorld = 1200; const auto worldID = Game::server->GetZoneID(); + if (dZoneManager::Instance()->CheckIfAccessibleZone((worldID/10)*10)) m_MainWorld = (worldID/10)*10; - switch (worldID) { - case 1203: - m_ActivityID = 42; - m_MainWorld = 1200; - break; - - case 1261: - m_ActivityID = 60; - m_MainWorld = 1260; - break; - - case 1303: - m_ActivityID = 39; - m_MainWorld = 1300; - break; - - case 1403: - m_ActivityID = 54; - m_MainWorld = 1400; - break; - - default: - m_ActivityID = 42; - m_MainWorld = 1200; - break; - } + m_ActivityID = 42; + CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable<CDActivitiesTable>(); + std::vector<CDActivities> activities = activitiesTable->Query([=](CDActivities entry) {return (entry.instanceMapID == worldID); }); + for (CDActivities activity : activities) m_ActivityID = activity.ActivityID; } RacingControlComponent::~RacingControlComponent() {} diff --git a/dGame/dComponents/ScriptedActivityComponent.cpp b/dGame/dComponents/ScriptedActivityComponent.cpp index eb4ab761..555332f4 100644 --- a/dGame/dComponents/ScriptedActivityComponent.cpp +++ b/dGame/dComponents/ScriptedActivityComponent.cpp @@ -27,6 +27,7 @@ #include "CDCurrencyTableTable.h" #include "CDActivityRewardsTable.h" #include "CDActivitiesTable.h" +#include "LeaderboardManager.h" ScriptedActivityComponent::ScriptedActivityComponent(Entity* parent, int activityID) : Component(parent) { m_ActivityID = activityID; @@ -35,10 +36,7 @@ ScriptedActivityComponent::ScriptedActivityComponent(Entity* parent, int activit for (CDActivities activity : activities) { m_ActivityInfo = activity; - - const auto mapID = m_ActivityInfo.instanceMapID; - - if ((mapID == 1203 || mapID == 1261 || mapID == 1303 || mapID == 1403) && Game::config->GetValue("solo_racing") == "1") { + if (static_cast<LeaderboardType>(activity.leaderboardType) == LeaderboardType::Racing && Game::config->GetValue("solo_racing") == "1") { m_ActivityInfo.minTeamSize = 1; m_ActivityInfo.minTeams = 1; } diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 07950d7a..16db62a6 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -279,7 +279,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "leave-zone") { const auto currentZone = dZoneManager::Instance()->GetZone()->GetZoneID().GetMapID(); - auto newZone = 0; + LWOMAPID newZone = 0; if (currentZone % 100 == 0) { ChatPackets::SendSystemMessage(sysAddr, u"You are not in an instanced zone."); return; @@ -287,7 +287,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit newZone = (currentZone / 100) * 100; } // If new zone would be inaccessible, then default to Avant Gardens. - if (!CheckIfAccessibleZone(newZone)) newZone = 1100; + if (!dZoneManager::Instance()->CheckIfAccessibleZone(newZone)) newZone = 1100; ChatPackets::SendSystemMessage(sysAddr, u"Leaving zone..."); @@ -1559,7 +1559,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit const auto objid = entity->GetObjectID(); - if (force || CheckIfAccessibleZone(reqZone)) { // to prevent tomfoolery + if (force || dZoneManager::Instance()->CheckIfAccessibleZone(reqZone)) { // to prevent tomfoolery ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, reqZone, cloneId, false, [objid](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) { @@ -2021,17 +2021,6 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } -bool SlashCommandHandler::CheckIfAccessibleZone(const unsigned int zoneID) { - //We're gonna go ahead and presume we've got the db loaded already: - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable<CDZoneTableTable>(); - const CDZoneTable* zone = zoneTable->Query(zoneID); - if (zone != nullptr) { - return Game::assetManager->HasFile(("maps/" + zone->zoneName).c_str()); - } else { - return false; - } -} - void SlashCommandHandler::SendAnnouncement(const std::string& title, const std::string& message) { AMFArrayValue args; auto* titleValue = new AMFStringValue(); diff --git a/dGame/dUtilities/SlashCommandHandler.h b/dGame/dUtilities/SlashCommandHandler.h index 9ef09a2f..85b7c697 100644 --- a/dGame/dUtilities/SlashCommandHandler.h +++ b/dGame/dUtilities/SlashCommandHandler.h @@ -13,8 +13,6 @@ class Entity; namespace SlashCommandHandler { void HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr); - bool CheckIfAccessibleZone(const unsigned int zoneID); - void SendAnnouncement(const std::string& title, const std::string& message); }; diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index 1a40748d..a26e912f 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -12,6 +12,8 @@ #include "CDZoneTableTable.h" #include <chrono> #include "eObjectBits.h" +#include "CDZoneTableTable.h" +#include "AssetManager.h" #include "../dWorldServer/ObjectIDManager.h" @@ -227,6 +229,17 @@ uint32_t dZoneManager::GetUniqueMissionIdStartingValue() { return m_UniqueMissionIdStart; } +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>(); + const CDZoneTable* zone = zoneTable->Query(zoneID); + if (zone != nullptr) { + return Game::assetManager->HasFile(("maps/" + zone->zoneName).c_str()); + } else { + return false; + } +} + void dZoneManager::LoadWorldConfig() { Game::logger->Log("dZoneManager", "Loading WorldConfig into memory"); diff --git a/dZoneManager/dZoneManager.h b/dZoneManager/dZoneManager.h index c1776e79..3086e6d7 100644 --- a/dZoneManager/dZoneManager.h +++ b/dZoneManager/dZoneManager.h @@ -50,6 +50,7 @@ public: Entity* GetZoneControlObject() { return m_ZoneControlObject; } bool GetPlayerLoseCoinOnDeath() { return m_PlayerLoseCoinsOnDeath; } uint32_t GetUniqueMissionIdStartingValue(); + bool CheckIfAccessibleZone(LWOMAPID zoneID); // The world config should not be modified by a caller. const WorldConfig* GetWorldConfig() { From 7aad6e4bc2b399b26ca732a25ac9204f4bdbf6d6 Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 8 May 2023 04:31:10 -0700 Subject: [PATCH 318/322] Make header skips more obvious (#1074) * Make header skips more obvious seeing inStream.Read(LWOOBJID) is much less clear than a macro which very clearly skips the header. * Formatting pass --- dChatServer/ChatPacketHandler.cpp | 36 +++++++++----------------- dChatServer/PlayerContainer.cpp | 12 +++------ dCommon/dEnums/dCommonVars.h | 2 ++ dNet/ClientPackets.cpp | 8 ++---- dWorldServer/WorldServer.cpp | 18 ++++--------- tests/dCommonTests/CMakeLists.txt | 1 + tests/dCommonTests/HeaderSkipTest.cpp | 37 +++++++++++++++++++++++++++ 7 files changed, 63 insertions(+), 51 deletions(-) create mode 100644 tests/dCommonTests/HeaderSkipTest.cpp diff --git a/dChatServer/ChatPacketHandler.cpp b/dChatServer/ChatPacketHandler.cpp index 9b5ca761..878cc71c 100644 --- a/dChatServer/ChatPacketHandler.cpp +++ b/dChatServer/ChatPacketHandler.cpp @@ -22,10 +22,9 @@ extern PlayerContainer playerContainer; void ChatPacketHandler::HandleFriendlistRequest(Packet* packet) { //Get from the packet which player we want to do something with: - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID = 0; inStream.Read(playerID); - inStream.Read(playerID); auto player = playerContainer.GetPlayerData(playerID); if (!player) return; @@ -99,10 +98,9 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { auto maxNumberOfBestFriendsAsString = Game::config->GetValue("max_number_of_best_friends"); // If this config option doesn't exist, default to 5 which is what live used. auto maxNumberOfBestFriends = maxNumberOfBestFriendsAsString != "" ? std::stoi(maxNumberOfBestFriendsAsString) : 5U; - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID requestorPlayerID; inStream.Read(requestorPlayerID); - inStream.Read(requestorPlayerID); uint32_t spacing{}; inStream.Read(spacing); std::string playerName = ""; @@ -247,10 +245,9 @@ void ChatPacketHandler::HandleFriendRequest(Packet* packet) { } void ChatPacketHandler::HandleFriendResponse(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID; inStream.Read(playerID); - inStream.Read(playerID); eAddFriendResponseCode clientResponseCode = static_cast<eAddFriendResponseCode>(packet->data[0x14]); std::string friendName = PacketUtils::ReadString(0x15, packet, true); @@ -323,10 +320,9 @@ void ChatPacketHandler::HandleFriendResponse(Packet* packet) { } void ChatPacketHandler::HandleRemoveFriend(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID; inStream.Read(playerID); - inStream.Read(playerID); std::string friendName = PacketUtils::ReadString(0x14, packet, true); //we'll have to query the db here to find the user, since you can delete them while they're offline. @@ -381,10 +377,9 @@ void ChatPacketHandler::HandleRemoveFriend(Packet* packet) { } void ChatPacketHandler::HandleChatMessage(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); - inStream.Read(playerID); auto* sender = playerContainer.GetPlayerData(playerID); @@ -501,10 +496,9 @@ void ChatPacketHandler::HandlePrivateChatMessage(Packet* packet) { } void ChatPacketHandler::HandleTeamInvite(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID; inStream.Read(playerID); - inStream.Read(playerID); std::string invitedPlayer = PacketUtils::ReadString(0x14, packet, true); auto* player = playerContainer.GetPlayerData(playerID); @@ -542,10 +536,9 @@ void ChatPacketHandler::HandleTeamInvite(Packet* packet) { } void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); - inStream.Read(playerID); uint32_t size = 0; inStream.Read(size); char declined = 0; @@ -576,10 +569,9 @@ void ChatPacketHandler::HandleTeamInviteResponse(Packet* packet) { } void ChatPacketHandler::HandleTeamLeave(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); - inStream.Read(playerID); uint32_t size = 0; inStream.Read(size); @@ -593,10 +585,9 @@ void ChatPacketHandler::HandleTeamLeave(Packet* packet) { } void ChatPacketHandler::HandleTeamKick(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); - inStream.Read(playerID); std::string kickedPlayer = PacketUtils::ReadString(0x14, packet, true); @@ -624,10 +615,9 @@ void ChatPacketHandler::HandleTeamKick(Packet* packet) { } void ChatPacketHandler::HandleTeamPromote(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); - inStream.Read(playerID); std::string promotedPlayer = PacketUtils::ReadString(0x14, packet, true); @@ -647,10 +637,9 @@ void ChatPacketHandler::HandleTeamPromote(Packet* packet) { } void ChatPacketHandler::HandleTeamLootOption(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); - inStream.Read(playerID); uint32_t size = 0; inStream.Read(size); @@ -671,10 +660,9 @@ void ChatPacketHandler::HandleTeamLootOption(Packet* packet) { } void ChatPacketHandler::HandleTeamStatusRequest(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID = LWOOBJID_EMPTY; inStream.Read(playerID); - inStream.Read(playerID); auto* team = playerContainer.GetTeam(playerID); auto* data = playerContainer.GetPlayerData(playerID); diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index dcc9ebb9..689ffd77 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -19,9 +19,8 @@ PlayerContainer::~PlayerContainer() { } void PlayerContainer::InsertPlayer(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; PlayerData* data = new PlayerData(); - inStream.SetReadOffset(inStream.GetReadOffset() + 64); inStream.Read(data->playerID); uint32_t len; @@ -52,9 +51,8 @@ void PlayerContainer::InsertPlayer(Packet* packet) { } void PlayerContainer::RemovePlayer(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID; - inStream.Read(playerID); //skip header inStream.Read(playerID); //Before they get kicked, we need to also send a message to their friends saying that they disconnected. @@ -97,9 +95,8 @@ void PlayerContainer::RemovePlayer(Packet* packet) { } void PlayerContainer::MuteUpdate(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID; - inStream.Read(playerID); //skip header inStream.Read(playerID); time_t expire = 0; inStream.Read(expire); @@ -118,9 +115,8 @@ void PlayerContainer::MuteUpdate(Packet* packet) { } void PlayerContainer::CreateTeamServer(Packet* packet) { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID; - inStream.Read(playerID); //skip header inStream.Read(playerID); size_t membersSize = 0; inStream.Read(membersSize); diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index e11866f1..f67145da 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -28,8 +28,10 @@ constexpr uint32_t lowFrameDelta = FRAMES_TO_MS(lowFramerate); //========== MACROS =========== +#define HEADER_SIZE 8 #define CBITSTREAM RakNet::BitStream bitStream; #define CINSTREAM RakNet::BitStream inStream(packet->data, packet->length, false); +#define CINSTREAM_SKIP_HEADER CINSTREAM if (inStream.GetNumberOfUnreadBits() >= BYTES_TO_BITS(HEADER_SIZE)) inStream.IgnoreBytes(HEADER_SIZE); else inStream.IgnoreBits(inStream.GetNumberOfUnreadBits()); #define CMSGHEADER PacketUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::GAME_MSG); #define SEND_PACKET Game::server->Send(&bitStream, sysAddr, false); #define SEND_PACKET_BROADCAST Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); diff --git a/dNet/ClientPackets.cpp b/dNet/ClientPackets.cpp index 4ccbb609..1c22bdcd 100644 --- a/dNet/ClientPackets.cpp +++ b/dNet/ClientPackets.cpp @@ -46,9 +46,7 @@ void ClientPackets::HandleChatMessage(const SystemAddress& sysAddr, Packet* pack return; } - CINSTREAM; - uint64_t header; - inStream.Read(header); + CINSTREAM_SKIP_HEADER; char chatChannel; uint16_t unknown; @@ -82,9 +80,7 @@ void ClientPackets::HandleClientPositionUpdate(const SystemAddress& sysAddr, Pac return; } - CINSTREAM; - uint64_t header; - inStream.Read(header); + CINSTREAM_SKIP_HEADER; Entity* entity = EntityManager::Instance()->GetEntity(user->GetLastUsedChar()->GetObjectID()); if (!entity) return; diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 26cbe7ba..5dabce1c 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -554,10 +554,9 @@ void HandlePacketChat(Packet* packet) { if (static_cast<eConnectionType>(packet->data[1]) == eConnectionType::CHAT_INTERNAL) { switch (static_cast<eChatInternalMessageType>(packet->data[3])) { case eChatInternalMessageType::ROUTE_TO_PLAYER: { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerID; inStream.Read(playerID); - inStream.Read(playerID); auto player = EntityManager::Instance()->GetEntity(playerID); if (!player) return; @@ -576,9 +575,7 @@ void HandlePacketChat(Packet* packet) { } case eChatInternalMessageType::ANNOUNCEMENT: { - CINSTREAM; - LWOOBJID header; - inStream.Read(header); + CINSTREAM_SKIP_HEADER; std::string title; std::string msg; @@ -615,11 +612,10 @@ void HandlePacketChat(Packet* packet) { } case eChatInternalMessageType::MUTE_UPDATE: { - CINSTREAM; + CINSTREAM_SKIP_HEADER; LWOOBJID playerId; time_t expire = 0; inStream.Read(playerId); - inStream.Read(playerId); inStream.Read(expire); auto* entity = EntityManager::Instance()->GetEntity(playerId); @@ -634,9 +630,7 @@ void HandlePacketChat(Packet* packet) { } case eChatInternalMessageType::TEAM_UPDATE: { - CINSTREAM; - LWOOBJID header; - inStream.Read(header); + CINSTREAM_SKIP_HEADER; LWOOBJID teamID = 0; char lootOption = 0; @@ -1213,10 +1207,8 @@ void HandlePacket(Packet* packet) { case eWorldMessageType::ROUTE_PACKET: { //Yeet to chat - CINSTREAM; - uint64_t header = 0; + CINSTREAM_SKIP_HEADER; uint32_t size = 0; - inStream.Read(header); inStream.Read(size); if (size > 20000) { diff --git a/tests/dCommonTests/CMakeLists.txt b/tests/dCommonTests/CMakeLists.txt index dd282cb5..444afbdd 100644 --- a/tests/dCommonTests/CMakeLists.txt +++ b/tests/dCommonTests/CMakeLists.txt @@ -1,5 +1,6 @@ set(DCOMMONTEST_SOURCES "AMFDeserializeTests.cpp" + "HeaderSkipTest.cpp" "TestLDFFormat.cpp" "TestNiPoint3.cpp" "TestEncoding.cpp" diff --git a/tests/dCommonTests/HeaderSkipTest.cpp b/tests/dCommonTests/HeaderSkipTest.cpp new file mode 100644 index 00000000..a8f78078 --- /dev/null +++ b/tests/dCommonTests/HeaderSkipTest.cpp @@ -0,0 +1,37 @@ +#include <gtest/gtest.h> + +#include "dCommonDependencies.h" +#include "dCommonVars.h" +#include "BitStream.h" + +#define PacketUniquePtr std::unique_ptr<Packet> + +TEST(dCommonTests, HeaderSkipExcessTest) { + PacketUniquePtr packet = std::make_unique<Packet>(); + unsigned char headerAndData[] = { 0x53, 0x02, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00 }; // positive + packet->data = headerAndData; + packet->length = sizeof(headerAndData); + CINSTREAM_SKIP_HEADER; + ASSERT_EQ(inStream.GetNumberOfUnreadBits(), 64); + ASSERT_EQ(inStream.GetNumberOfBitsAllocated(), 128); +} + +TEST(dCommonTests, HeaderSkipExactDataTest) { + PacketUniquePtr packet = std::make_unique<Packet>(); + unsigned char header[] = { 0x53, 0x02, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00 }; // positive + packet->data = header; + packet->length = sizeof(header); + CINSTREAM_SKIP_HEADER; + ASSERT_EQ(inStream.GetNumberOfUnreadBits(), 0); + ASSERT_EQ(inStream.GetNumberOfBitsAllocated(), 64); +} + +TEST(dCommonTests, HeaderSkipNotEnoughDataTest) { + PacketUniquePtr packet = std::make_unique<Packet>(); + unsigned char notEnoughData[] = { 0x53, 0x02, 0x00, 0x07, 0x00, 0x00 }; // negative + packet->data = notEnoughData; + packet->length = sizeof(notEnoughData); + CINSTREAM_SKIP_HEADER; + ASSERT_EQ(inStream.GetNumberOfUnreadBits(), 0); + ASSERT_EQ(inStream.GetNumberOfBitsAllocated(), 48); +} From ce931c2cfe2c1e8a6f80953d290b19010bd00a8b Mon Sep 17 00:00:00 2001 From: David Markowitz <39972741+EmosewaMC@users.noreply.github.com> Date: Mon, 8 May 2023 22:39:43 -0700 Subject: [PATCH 319/322] Fix erroneous GM message ID (#1076) --- dCommon/dEnums/eGameMessageType.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dCommon/dEnums/eGameMessageType.h b/dCommon/dEnums/eGameMessageType.h index 247ee5e2..051a5ae8 100644 --- a/dCommon/dEnums/eGameMessageType.h +++ b/dCommon/dEnums/eGameMessageType.h @@ -273,7 +273,7 @@ enum class eGameMessageType : uint16_t { TEAM_SET_LEADER = 1557, TEAM_INVITE_CONFIRM = 1558, TEAM_GET_STATUS_RESPONSE = 1559, - TEAM_ADD_PLAYER = 1526, + TEAM_ADD_PLAYER = 1562, TEAM_REMOVE_PLAYER = 1563, START_CELEBRATION_EFFECT = 1618, ADD_BUFF = 1647, From 4ff5afd9f7ea5d4df732256351ca01b45fdaa3c7 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Tue, 9 May 2023 00:40:00 -0500 Subject: [PATCH 320/322] Fix race exit dialogue always exiting (#1077) Fixes #1048 Tested that closing the dialog via esc, the x in the top right, or the big red x doesn't exit the race Tested that the green check button does exit the race --- dGame/dComponents/RacingControlComponent.cpp | 5 ++--- dGame/dComponents/RacingControlComponent.h | 7 ++++++- dGame/dGameMessages/GameMessages.cpp | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 3134d5fe..44c9de36 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -362,8 +362,7 @@ void RacingControlComponent::OnRacingPlayerInfoResetFinished(Entity* player) { } } -void RacingControlComponent::HandleMessageBoxResponse(Entity* player, - const std::string& id) { +void RacingControlComponent::HandleMessageBoxResponse(Entity* player, int32_t button, const std::string& id) { auto* data = GetPlayerData(player->GetObjectID()); if (data == nullptr) { @@ -405,7 +404,7 @@ void RacingControlComponent::HandleMessageBoxResponse(Entity* player, missionComponent->Progress(eMissionTaskType::RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)eRacingTaskParam::LAST_PLACE_FINISH); // Finished first place in specific world. } } - } else if (id == "ACT_RACE_EXIT_THE_RACE?" || id == "Exit") { + } else if (id == "ACT_RACE_EXIT_THE_RACE?" && button == m_ActivityExitConfirm) { auto* vehicle = EntityManager::Instance()->GetEntity(data->vehicleID); if (vehicle == nullptr) { diff --git a/dGame/dComponents/RacingControlComponent.h b/dGame/dComponents/RacingControlComponent.h index 91ab2fd4..a81121e1 100644 --- a/dGame/dComponents/RacingControlComponent.h +++ b/dGame/dComponents/RacingControlComponent.h @@ -144,7 +144,7 @@ public: /** * Invoked when the player responds to the GUI. */ - void HandleMessageBoxResponse(Entity* player, const std::string& id); + void HandleMessageBoxResponse(Entity* player, int32_t button, const std::string& id); /** * Get the racing data from a player's LWOOBJID. @@ -246,4 +246,9 @@ private: float m_EmptyTimer; bool m_SoloRacing; + + /** + * Value for message box response to know if we are exiting the race via the activity dialogue + */ + const int32_t m_ActivityExitConfirm = 1; }; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index caab6459..99b1c67f 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -3891,7 +3891,7 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* auto* racingControlComponent = entity->GetComponent<RacingControlComponent>(); if (racingControlComponent != nullptr) { - racingControlComponent->HandleMessageBoxResponse(userEntity, GeneralUtils::UTF16ToWTF8(identifier)); + racingControlComponent->HandleMessageBoxResponse(userEntity, iButton, GeneralUtils::UTF16ToWTF8(identifier)); } for (auto* shootingGallery : EntityManager::Instance()->GetEntitiesByComponent(eReplicaComponentType::SHOOTING_GALLERY)) { From b1cd2776fa2528adb4ba8e300ce03798dd6e6fd6 Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Wed, 10 May 2023 04:05:56 -0500 Subject: [PATCH 321/322] fix: make exiting the race work (#1082) --- dGame/dComponents/RacingControlComponent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 44c9de36..4a4ead59 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -404,7 +404,7 @@ void RacingControlComponent::HandleMessageBoxResponse(Entity* player, int32_t bu missionComponent->Progress(eMissionTaskType::RACING, dZoneManager::Instance()->GetZone()->GetWorldID(), (LWOOBJID)eRacingTaskParam::LAST_PLACE_FINISH); // Finished first place in specific world. } } - } else if (id == "ACT_RACE_EXIT_THE_RACE?" && button == m_ActivityExitConfirm) { + } else if ((id == "ACT_RACE_EXIT_THE_RACE?" || id == "Exit") && button == m_ActivityExitConfirm) { auto* vehicle = EntityManager::Instance()->GetEntity(data->vehicleID); if (vehicle == nullptr) { From bf0ae6f181399620cd1e2f266f7092ae29375d9c Mon Sep 17 00:00:00 2001 From: Aaron Kimbrell <aronwk.aaron@gmail.com> Date: Wed, 10 May 2023 07:44:21 -0500 Subject: [PATCH 322/322] fix: add check for arg nums on handlepushobject (#1081) --- dGame/dComponents/TriggerComponent.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp index 3f05d805..7adf47a8 100644 --- a/dGame/dComponents/TriggerComponent.cpp +++ b/dGame/dComponents/TriggerComponent.cpp @@ -235,6 +235,8 @@ void TriggerComponent::HandleRotateObject(Entity* targetEntity, std::vector<std: } void TriggerComponent::HandlePushObject(Entity* targetEntity, std::vector<std::string> argArray){ + if (argArray.size() < 3) return; + auto* phantomPhysicsComponent = m_Parent->GetComponent<PhantomPhysicsComponent>(); if (!phantomPhysicsComponent) { Game::logger->LogDebug("TriggerComponent::HandlePushObject", "Phantom Physics component not found!");